1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 default: 152 break; 153 } 154 155 return false; 156 } 157 158 namespace { 159 enum class UnqualifiedTypeNameLookupResult { 160 NotFound, 161 FoundNonType, 162 FoundType 163 }; 164 } // end anonymous namespace 165 166 /// \brief Tries to perform unqualified lookup of the type decls in bases for 167 /// dependent class. 168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 169 /// type decl, \a FoundType if only type decls are found. 170 static UnqualifiedTypeNameLookupResult 171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 172 SourceLocation NameLoc, 173 const CXXRecordDecl *RD) { 174 if (!RD->hasDefinition()) 175 return UnqualifiedTypeNameLookupResult::NotFound; 176 // Look for type decls in base classes. 177 UnqualifiedTypeNameLookupResult FoundTypeDecl = 178 UnqualifiedTypeNameLookupResult::NotFound; 179 for (const auto &Base : RD->bases()) { 180 const CXXRecordDecl *BaseRD = nullptr; 181 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 182 BaseRD = BaseTT->getAsCXXRecordDecl(); 183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 184 // Look for type decls in dependent base classes that have known primary 185 // templates. 186 if (!TST || !TST->isDependentType()) 187 continue; 188 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 189 if (!TD) 190 continue; 191 if (auto *BasePrimaryTemplate = 192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 194 BaseRD = BasePrimaryTemplate; 195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 196 if (const ClassTemplatePartialSpecializationDecl *PS = 197 CTD->findPartialSpecialization(Base.getType())) 198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 199 BaseRD = PS; 200 } 201 } 202 } 203 if (BaseRD) { 204 for (NamedDecl *ND : BaseRD->lookup(&II)) { 205 if (!isa<TypeDecl>(ND)) 206 return UnqualifiedTypeNameLookupResult::FoundNonType; 207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 208 } 209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 211 case UnqualifiedTypeNameLookupResult::FoundNonType: 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 case UnqualifiedTypeNameLookupResult::FoundType: 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 break; 216 case UnqualifiedTypeNameLookupResult::NotFound: 217 break; 218 } 219 } 220 } 221 } 222 223 return FoundTypeDecl; 224 } 225 226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 227 const IdentifierInfo &II, 228 SourceLocation NameLoc) { 229 // Lookup in the parent class template context, if any. 230 const CXXRecordDecl *RD = nullptr; 231 UnqualifiedTypeNameLookupResult FoundTypeDecl = 232 UnqualifiedTypeNameLookupResult::NotFound; 233 for (DeclContext *DC = S.CurContext; 234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 235 DC = DC->getParent()) { 236 // Look for type decls in dependent base classes that have known primary 237 // templates. 238 RD = dyn_cast<CXXRecordDecl>(DC); 239 if (RD && RD->getDescribedClassTemplate()) 240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 241 } 242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 243 return nullptr; 244 245 // We found some types in dependent base classes. Recover as if the user 246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 247 // lookup during template instantiation. 248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 249 250 ASTContext &Context = S.Context; 251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 252 cast<Type>(Context.getRecordType(RD))); 253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 254 255 CXXScopeSpec SS; 256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 257 258 TypeLocBuilder Builder; 259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 260 DepTL.setNameLoc(NameLoc); 261 DepTL.setElaboratedKeywordLoc(SourceLocation()); 262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 264 } 265 266 /// \brief If the identifier refers to a type name within this scope, 267 /// return the declaration of that type. 268 /// 269 /// This routine performs ordinary name lookup of the identifier II 270 /// within the given scope, with optional C++ scope specifier SS, to 271 /// determine whether the name refers to a type. If so, returns an 272 /// opaque pointer (actually a QualType) corresponding to that 273 /// type. Otherwise, returns NULL. 274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 275 Scope *S, CXXScopeSpec *SS, 276 bool isClassName, bool HasTrailingDot, 277 ParsedType ObjectTypePtr, 278 bool IsCtorOrDtorName, 279 bool WantNontrivialTypeSourceInfo, 280 bool IsClassTemplateDeductionContext, 281 IdentifierInfo **CorrectedII) { 282 // FIXME: Consider allowing this outside C++1z mode as an extension. 283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 284 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 285 !isClassName && !HasTrailingDot; 286 287 // Determine where we will perform name lookup. 288 DeclContext *LookupCtx = nullptr; 289 if (ObjectTypePtr) { 290 QualType ObjectType = ObjectTypePtr.get(); 291 if (ObjectType->isRecordType()) 292 LookupCtx = computeDeclContext(ObjectType); 293 } else if (SS && SS->isNotEmpty()) { 294 LookupCtx = computeDeclContext(*SS, false); 295 296 if (!LookupCtx) { 297 if (isDependentScopeSpecifier(*SS)) { 298 // C++ [temp.res]p3: 299 // A qualified-id that refers to a type and in which the 300 // nested-name-specifier depends on a template-parameter (14.6.2) 301 // shall be prefixed by the keyword typename to indicate that the 302 // qualified-id denotes a type, forming an 303 // elaborated-type-specifier (7.1.5.3). 304 // 305 // We therefore do not perform any name lookup if the result would 306 // refer to a member of an unknown specialization. 307 if (!isClassName && !IsCtorOrDtorName) 308 return nullptr; 309 310 // We know from the grammar that this name refers to a type, 311 // so build a dependent node to describe the type. 312 if (WantNontrivialTypeSourceInfo) 313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 314 315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 317 II, NameLoc); 318 return ParsedType::make(T); 319 } 320 321 return nullptr; 322 } 323 324 if (!LookupCtx->isDependentContext() && 325 RequireCompleteDeclContext(*SS, LookupCtx)) 326 return nullptr; 327 } 328 329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 330 // lookup for class-names. 331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 332 LookupOrdinaryName; 333 LookupResult Result(*this, &II, NameLoc, Kind); 334 if (LookupCtx) { 335 // Perform "qualified" name lookup into the declaration context we 336 // computed, which is either the type of the base of a member access 337 // expression or the declaration context associated with a prior 338 // nested-name-specifier. 339 LookupQualifiedName(Result, LookupCtx); 340 341 if (ObjectTypePtr && Result.empty()) { 342 // C++ [basic.lookup.classref]p3: 343 // If the unqualified-id is ~type-name, the type-name is looked up 344 // in the context of the entire postfix-expression. If the type T of 345 // the object expression is of a class type C, the type-name is also 346 // looked up in the scope of class C. At least one of the lookups shall 347 // find a name that refers to (possibly cv-qualified) T. 348 LookupName(Result, S); 349 } 350 } else { 351 // Perform unqualified name lookup. 352 LookupName(Result, S); 353 354 // For unqualified lookup in a class template in MSVC mode, look into 355 // dependent base classes where the primary class template is known. 356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 357 if (ParsedType TypeInBase = 358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 359 return TypeInBase; 360 } 361 } 362 363 NamedDecl *IIDecl = nullptr; 364 switch (Result.getResultKind()) { 365 case LookupResult::NotFound: 366 case LookupResult::NotFoundInCurrentInstantiation: 367 if (CorrectedII) { 368 TypoCorrection Correction = 369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 370 llvm::make_unique<TypeNameValidatorCCC>( 371 true, isClassName, AllowDeducedTemplate), 372 CTK_ErrorRecovery); 373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 374 TemplateTy Template; 375 bool MemberOfUnknownSpecialization; 376 UnqualifiedId TemplateName; 377 TemplateName.setIdentifier(NewII, NameLoc); 378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 379 CXXScopeSpec NewSS, *NewSSPtr = SS; 380 if (SS && NNS) { 381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 382 NewSSPtr = &NewSS; 383 } 384 if (Correction && (NNS || NewII != &II) && 385 // Ignore a correction to a template type as the to-be-corrected 386 // identifier is not a template (typo correction for template names 387 // is handled elsewhere). 388 !(getLangOpts().CPlusPlus && NewSSPtr && 389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 390 Template, MemberOfUnknownSpecialization))) { 391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 392 isClassName, HasTrailingDot, ObjectTypePtr, 393 IsCtorOrDtorName, 394 WantNontrivialTypeSourceInfo, 395 IsClassTemplateDeductionContext); 396 if (Ty) { 397 diagnoseTypo(Correction, 398 PDiag(diag::err_unknown_type_or_class_name_suggest) 399 << Result.getLookupName() << isClassName); 400 if (SS && NNS) 401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 402 *CorrectedII = NewII; 403 return Ty; 404 } 405 } 406 } 407 // If typo correction failed or was not performed, fall through 408 LLVM_FALLTHROUGH; 409 case LookupResult::FoundOverloaded: 410 case LookupResult::FoundUnresolvedValue: 411 Result.suppressDiagnostics(); 412 return nullptr; 413 414 case LookupResult::Ambiguous: 415 // Recover from type-hiding ambiguities by hiding the type. We'll 416 // do the lookup again when looking for an object, and we can 417 // diagnose the error then. If we don't do this, then the error 418 // about hiding the type will be immediately followed by an error 419 // that only makes sense if the identifier was treated like a type. 420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 421 Result.suppressDiagnostics(); 422 return nullptr; 423 } 424 425 // Look to see if we have a type anywhere in the list of results. 426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 427 Res != ResEnd; ++Res) { 428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 430 if (!IIDecl || 431 (*Res)->getLocation().getRawEncoding() < 432 IIDecl->getLocation().getRawEncoding()) 433 IIDecl = *Res; 434 } 435 } 436 437 if (!IIDecl) { 438 // None of the entities we found is a type, so there is no way 439 // to even assume that the result is a type. In this case, don't 440 // complain about the ambiguity. The parser will either try to 441 // perform this lookup again (e.g., as an object name), which 442 // will produce the ambiguity, or will complain that it expected 443 // a type name. 444 Result.suppressDiagnostics(); 445 return nullptr; 446 } 447 448 // We found a type within the ambiguous lookup; diagnose the 449 // ambiguity and then return that type. This might be the right 450 // answer, or it might not be, but it suppresses any attempt to 451 // perform the name lookup again. 452 break; 453 454 case LookupResult::Found: 455 IIDecl = Result.getFoundDecl(); 456 break; 457 } 458 459 assert(IIDecl && "Didn't find decl"); 460 461 QualType T; 462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 463 // C++ [class.qual]p2: A lookup that would find the injected-class-name 464 // instead names the constructors of the class, except when naming a class. 465 // This is ill-formed when we're not actually forming a ctor or dtor name. 466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 469 FoundRD->isInjectedClassName() && 470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 472 << &II << /*Type*/1; 473 474 DiagnoseUseOfDecl(IIDecl, NameLoc); 475 476 T = Context.getTypeDeclType(TD); 477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 479 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 480 if (!HasTrailingDot) 481 T = Context.getObjCInterfaceType(IDecl); 482 } else if (AllowDeducedTemplate) { 483 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 485 QualType(), false); 486 } 487 488 if (T.isNull()) { 489 // If it's not plausibly a type, suppress diagnostics. 490 Result.suppressDiagnostics(); 491 return nullptr; 492 } 493 494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 495 // constructor or destructor name (in such a case, the scope specifier 496 // will be attached to the enclosing Expr or Decl node). 497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 498 !isa<ObjCInterfaceDecl>(IIDecl)) { 499 if (WantNontrivialTypeSourceInfo) { 500 // Construct a type with type-source information. 501 TypeLocBuilder Builder; 502 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 503 504 T = getElaboratedType(ETK_None, *SS, T); 505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 506 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 509 } else { 510 T = getElaboratedType(ETK_None, *SS, T); 511 } 512 } 513 514 return ParsedType::make(T); 515 } 516 517 // Builds a fake NNS for the given decl context. 518 static NestedNameSpecifier * 519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 520 for (;; DC = DC->getLookupParent()) { 521 DC = DC->getPrimaryContext(); 522 auto *ND = dyn_cast<NamespaceDecl>(DC); 523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 524 return NestedNameSpecifier::Create(Context, nullptr, ND); 525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 527 RD->getTypeForDecl()); 528 else if (isa<TranslationUnitDecl>(DC)) 529 return NestedNameSpecifier::GlobalSpecifier(Context); 530 } 531 llvm_unreachable("something isn't in TU scope?"); 532 } 533 534 /// Find the parent class with dependent bases of the innermost enclosing method 535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 536 /// up allowing unqualified dependent type names at class-level, which MSVC 537 /// correctly rejects. 538 static const CXXRecordDecl * 539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 541 DC = DC->getPrimaryContext(); 542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 543 if (MD->getParent()->hasAnyDependentBases()) 544 return MD->getParent(); 545 } 546 return nullptr; 547 } 548 549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 550 SourceLocation NameLoc, 551 bool IsTemplateTypeArg) { 552 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 553 554 NestedNameSpecifier *NNS = nullptr; 555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 556 // If we weren't able to parse a default template argument, delay lookup 557 // until instantiation time by making a non-dependent DependentTypeName. We 558 // pretend we saw a NestedNameSpecifier referring to the current scope, and 559 // lookup is retried. 560 // FIXME: This hurts our diagnostic quality, since we get errors like "no 561 // type named 'Foo' in 'current_namespace'" when the user didn't write any 562 // name specifiers. 563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 565 } else if (const CXXRecordDecl *RD = 566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 567 // Build a DependentNameType that will perform lookup into RD at 568 // instantiation time. 569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 570 RD->getTypeForDecl()); 571 572 // Diagnose that this identifier was undeclared, and retry the lookup during 573 // template instantiation. 574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 575 << RD; 576 } else { 577 // This is not a situation that we should recover from. 578 return ParsedType(); 579 } 580 581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 582 583 // Build type location information. We synthesized the qualifier, so we have 584 // to build a fake NestedNameSpecifierLoc. 585 NestedNameSpecifierLocBuilder NNSLocBuilder; 586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 588 589 TypeLocBuilder Builder; 590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 591 DepTL.setNameLoc(NameLoc); 592 DepTL.setElaboratedKeywordLoc(SourceLocation()); 593 DepTL.setQualifierLoc(QualifierLoc); 594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 595 } 596 597 /// isTagName() - This method is called *for error recovery purposes only* 598 /// to determine if the specified name is a valid tag name ("struct foo"). If 599 /// so, this returns the TST for the tag corresponding to it (TST_enum, 600 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 601 /// cases in C where the user forgot to specify the tag. 602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 603 // Do a tag name lookup in this scope. 604 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 605 LookupName(R, S, false); 606 R.suppressDiagnostics(); 607 if (R.getResultKind() == LookupResult::Found) 608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 609 switch (TD->getTagKind()) { 610 case TTK_Struct: return DeclSpec::TST_struct; 611 case TTK_Interface: return DeclSpec::TST_interface; 612 case TTK_Union: return DeclSpec::TST_union; 613 case TTK_Class: return DeclSpec::TST_class; 614 case TTK_Enum: return DeclSpec::TST_enum; 615 } 616 } 617 618 return DeclSpec::TST_unspecified; 619 } 620 621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 623 /// then downgrade the missing typename error to a warning. 624 /// This is needed for MSVC compatibility; Example: 625 /// @code 626 /// template<class T> class A { 627 /// public: 628 /// typedef int TYPE; 629 /// }; 630 /// template<class T> class B : public A<T> { 631 /// public: 632 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 633 /// }; 634 /// @endcode 635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 636 if (CurContext->isRecord()) { 637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 638 return true; 639 640 const Type *Ty = SS->getScopeRep()->getAsType(); 641 642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 643 for (const auto &Base : RD->bases()) 644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 645 return true; 646 return S->isFunctionPrototypeScope(); 647 } 648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 649 } 650 651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 652 SourceLocation IILoc, 653 Scope *S, 654 CXXScopeSpec *SS, 655 ParsedType &SuggestedType, 656 bool IsTemplateName) { 657 // Don't report typename errors for editor placeholders. 658 if (II->isEditorPlaceholder()) 659 return; 660 // We don't have anything to suggest (yet). 661 SuggestedType = nullptr; 662 663 // There may have been a typo in the name of the type. Look up typo 664 // results, in case we have something that we can suggest. 665 if (TypoCorrection Corrected = 666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 667 llvm::make_unique<TypeNameValidatorCCC>( 668 false, false, IsTemplateName, !IsTemplateName), 669 CTK_ErrorRecovery)) { 670 // FIXME: Support error recovery for the template-name case. 671 bool CanRecover = !IsTemplateName; 672 if (Corrected.isKeyword()) { 673 // We corrected to a keyword. 674 diagnoseTypo(Corrected, 675 PDiag(IsTemplateName ? diag::err_no_template_suggest 676 : diag::err_unknown_typename_suggest) 677 << II); 678 II = Corrected.getCorrectionAsIdentifierInfo(); 679 } else { 680 // We found a similarly-named type or interface; suggest that. 681 if (!SS || !SS->isSet()) { 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II, CanRecover); 686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 687 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 689 II->getName().equals(CorrectedStr); 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName 692 ? diag::err_no_member_template_suggest 693 : diag::err_unknown_nested_typename_suggest) 694 << II << DC << DroppedSpecifier << SS->getRange(), 695 CanRecover); 696 } else { 697 llvm_unreachable("could not have corrected a typo here"); 698 } 699 700 if (!CanRecover) 701 return; 702 703 CXXScopeSpec tmpSS; 704 if (Corrected.getCorrectionSpecifier()) 705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 706 SourceRange(IILoc)); 707 // FIXME: Support class template argument deduction here. 708 SuggestedType = 709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 711 /*IsCtorOrDtorName=*/false, 712 /*NonTrivialTypeSourceInfo=*/true); 713 } 714 return; 715 } 716 717 if (getLangOpts().CPlusPlus && !IsTemplateName) { 718 // See if II is a class template that the user forgot to pass arguments to. 719 UnqualifiedId Name; 720 Name.setIdentifier(II, IILoc); 721 CXXScopeSpec EmptySS; 722 TemplateTy TemplateResult; 723 bool MemberOfUnknownSpecialization; 724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 725 Name, nullptr, true, TemplateResult, 726 MemberOfUnknownSpecialization) == TNK_Type_template) { 727 TemplateName TplName = TemplateResult.get(); 728 Diag(IILoc, diag::err_template_missing_args) 729 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 730 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 731 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 732 << TplDecl->getTemplateParameters()->getSourceRange(); 733 } 734 return; 735 } 736 } 737 738 // FIXME: Should we move the logic that tries to recover from a missing tag 739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 740 741 if (!SS || (!SS->isSet() && !SS->isInvalid())) 742 Diag(IILoc, IsTemplateName ? diag::err_no_template 743 : diag::err_unknown_typename) 744 << II; 745 else if (DeclContext *DC = computeDeclContext(*SS, false)) 746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 747 : diag::err_typename_nested_not_found) 748 << II << DC << SS->getRange(); 749 else if (isDependentScopeSpecifier(*SS)) { 750 unsigned DiagID = diag::err_typename_missing; 751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 752 DiagID = diag::ext_typename_missing; 753 754 Diag(SS->getRange().getBegin(), DiagID) 755 << SS->getScopeRep() << II->getName() 756 << SourceRange(SS->getRange().getBegin(), IILoc) 757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 758 SuggestedType = ActOnTypenameType(S, SourceLocation(), 759 *SS, *II, IILoc).get(); 760 } else { 761 assert(SS && SS->isInvalid() && 762 "Invalid scope specifier has already been diagnosed"); 763 } 764 } 765 766 /// \brief Determine whether the given result set contains either a type name 767 /// or 768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 770 NextToken.is(tok::less); 771 772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 774 return true; 775 776 if (CheckTemplate && isa<TemplateDecl>(*I)) 777 return true; 778 } 779 780 return false; 781 } 782 783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 784 Scope *S, CXXScopeSpec &SS, 785 IdentifierInfo *&Name, 786 SourceLocation NameLoc) { 787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 788 SemaRef.LookupParsedName(R, S, &SS); 789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 790 StringRef FixItTagName; 791 switch (Tag->getTagKind()) { 792 case TTK_Class: 793 FixItTagName = "class "; 794 break; 795 796 case TTK_Enum: 797 FixItTagName = "enum "; 798 break; 799 800 case TTK_Struct: 801 FixItTagName = "struct "; 802 break; 803 804 case TTK_Interface: 805 FixItTagName = "__interface "; 806 break; 807 808 case TTK_Union: 809 FixItTagName = "union "; 810 break; 811 } 812 813 StringRef TagName = FixItTagName.drop_back(); 814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 816 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 817 818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 819 I != IEnd; ++I) 820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 821 << Name << TagName; 822 823 // Replace lookup results with just the tag decl. 824 Result.clear(Sema::LookupTagName); 825 SemaRef.LookupParsedName(Result, S, &SS); 826 return true; 827 } 828 829 return false; 830 } 831 832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 834 QualType T, SourceLocation NameLoc) { 835 ASTContext &Context = S.Context; 836 837 TypeLocBuilder Builder; 838 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 839 840 T = S.getElaboratedType(ETK_None, SS, T); 841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 842 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 845 } 846 847 Sema::NameClassification 848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 849 SourceLocation NameLoc, const Token &NextToken, 850 bool IsAddressOfOperand, 851 std::unique_ptr<CorrectionCandidateCallback> CCC) { 852 DeclarationNameInfo NameInfo(Name, NameLoc); 853 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 854 855 if (NextToken.is(tok::coloncolon)) { 856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 858 } else if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 // For unqualified lookup in a class template in MSVC mode, look into 871 // dependent base classes where the primary class template is known. 872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 873 if (ParsedType TypeInBase = 874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 875 return TypeInBase; 876 } 877 878 // Perform lookup for Objective-C instance variables (including automatically 879 // synthesized instance variables), if we're in an Objective-C method. 880 // FIXME: This lookup really, really needs to be folded in to the normal 881 // unqualified lookup mechanism. 882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 883 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 884 if (E.get() || E.isInvalid()) 885 return E; 886 } 887 888 bool SecondTry = false; 889 bool IsFilteredTemplateName = false; 890 891 Corrected: 892 switch (Result.getResultKind()) { 893 case LookupResult::NotFound: 894 // If an unqualified-id is followed by a '(', then we have a function 895 // call. 896 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 897 // In C++, this is an ADL-only call. 898 // FIXME: Reference? 899 if (getLangOpts().CPlusPlus) 900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 901 902 // C90 6.3.2.2: 903 // If the expression that precedes the parenthesized argument list in a 904 // function call consists solely of an identifier, and if no 905 // declaration is visible for this identifier, the identifier is 906 // implicitly declared exactly as if, in the innermost block containing 907 // the function call, the declaration 908 // 909 // extern int identifier (); 910 // 911 // appeared. 912 // 913 // We also allow this in C99 as an extension. 914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 915 Result.addDecl(D); 916 Result.resolveKind(); 917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 918 } 919 } 920 921 // In C, we first see whether there is a tag type by the same name, in 922 // which case it's likely that the user just forgot to write "enum", 923 // "struct", or "union". 924 if (!getLangOpts().CPlusPlus && !SecondTry && 925 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 926 break; 927 } 928 929 // Perform typo correction to determine if there is another name that is 930 // close to this name. 931 if (!SecondTry && CCC) { 932 SecondTry = true; 933 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 934 Result.getLookupKind(), S, 935 &SS, std::move(CCC), 936 CTK_ErrorRecovery)) { 937 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 938 unsigned QualifiedDiag = diag::err_no_member_suggest; 939 940 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 941 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 942 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 943 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 944 UnqualifiedDiag = diag::err_no_template_suggest; 945 QualifiedDiag = diag::err_no_member_template_suggest; 946 } else if (UnderlyingFirstDecl && 947 (isa<TypeDecl>(UnderlyingFirstDecl) || 948 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 949 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 950 UnqualifiedDiag = diag::err_unknown_typename_suggest; 951 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 952 } 953 954 if (SS.isEmpty()) { 955 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 956 } else {// FIXME: is this even reachable? Test it. 957 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 958 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 959 Name->getName().equals(CorrectedStr); 960 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 961 << Name << computeDeclContext(SS, false) 962 << DroppedSpecifier << SS.getRange()); 963 } 964 965 // Update the name, so that the caller has the new name. 966 Name = Corrected.getCorrectionAsIdentifierInfo(); 967 968 // Typo correction corrected to a keyword. 969 if (Corrected.isKeyword()) 970 return Name; 971 972 // Also update the LookupResult... 973 // FIXME: This should probably go away at some point 974 Result.clear(); 975 Result.setLookupName(Corrected.getCorrection()); 976 if (FirstDecl) 977 Result.addDecl(FirstDecl); 978 979 // If we found an Objective-C instance variable, let 980 // LookupInObjCMethod build the appropriate expression to 981 // reference the ivar. 982 // FIXME: This is a gross hack. 983 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 984 Result.clear(); 985 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 986 return E; 987 } 988 989 goto Corrected; 990 } 991 } 992 993 // We failed to correct; just fall through and let the parser deal with it. 994 Result.suppressDiagnostics(); 995 return NameClassification::Unknown(); 996 997 case LookupResult::NotFoundInCurrentInstantiation: { 998 // We performed name lookup into the current instantiation, and there were 999 // dependent bases, so we treat this result the same way as any other 1000 // dependent nested-name-specifier. 1001 1002 // C++ [temp.res]p2: 1003 // A name used in a template declaration or definition and that is 1004 // dependent on a template-parameter is assumed not to name a type 1005 // unless the applicable name lookup finds a type name or the name is 1006 // qualified by the keyword typename. 1007 // 1008 // FIXME: If the next token is '<', we might want to ask the parser to 1009 // perform some heroics to see if we actually have a 1010 // template-argument-list, which would indicate a missing 'template' 1011 // keyword here. 1012 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1013 NameInfo, IsAddressOfOperand, 1014 /*TemplateArgs=*/nullptr); 1015 } 1016 1017 case LookupResult::Found: 1018 case LookupResult::FoundOverloaded: 1019 case LookupResult::FoundUnresolvedValue: 1020 break; 1021 1022 case LookupResult::Ambiguous: 1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1024 hasAnyAcceptableTemplateNames(Result)) { 1025 // C++ [temp.local]p3: 1026 // A lookup that finds an injected-class-name (10.2) can result in an 1027 // ambiguity in certain cases (for example, if it is found in more than 1028 // one base class). If all of the injected-class-names that are found 1029 // refer to specializations of the same class template, and if the name 1030 // is followed by a template-argument-list, the reference refers to the 1031 // class template itself and not a specialization thereof, and is not 1032 // ambiguous. 1033 // 1034 // This filtering can make an ambiguous result into an unambiguous one, 1035 // so try again after filtering out template names. 1036 FilterAcceptableTemplateNames(Result); 1037 if (!Result.isAmbiguous()) { 1038 IsFilteredTemplateName = true; 1039 break; 1040 } 1041 } 1042 1043 // Diagnose the ambiguity and return an error. 1044 return NameClassification::Error(); 1045 } 1046 1047 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1048 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1049 // C++ [temp.names]p3: 1050 // After name lookup (3.4) finds that a name is a template-name or that 1051 // an operator-function-id or a literal- operator-id refers to a set of 1052 // overloaded functions any member of which is a function template if 1053 // this is followed by a <, the < is always taken as the delimiter of a 1054 // template-argument-list and never as the less-than operator. 1055 if (!IsFilteredTemplateName) 1056 FilterAcceptableTemplateNames(Result); 1057 1058 if (!Result.empty()) { 1059 bool IsFunctionTemplate; 1060 bool IsVarTemplate; 1061 TemplateName Template; 1062 if (Result.end() - Result.begin() > 1) { 1063 IsFunctionTemplate = true; 1064 Template = Context.getOverloadedTemplateName(Result.begin(), 1065 Result.end()); 1066 } else { 1067 TemplateDecl *TD 1068 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1069 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1070 IsVarTemplate = isa<VarTemplateDecl>(TD); 1071 1072 if (SS.isSet() && !SS.isInvalid()) 1073 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1074 /*TemplateKeyword=*/false, 1075 TD); 1076 else 1077 Template = TemplateName(TD); 1078 } 1079 1080 if (IsFunctionTemplate) { 1081 // Function templates always go through overload resolution, at which 1082 // point we'll perform the various checks (e.g., accessibility) we need 1083 // to based on which function we selected. 1084 Result.suppressDiagnostics(); 1085 1086 return NameClassification::FunctionTemplate(Template); 1087 } 1088 1089 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1090 : NameClassification::TypeTemplate(Template); 1091 } 1092 } 1093 1094 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1095 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1096 DiagnoseUseOfDecl(Type, NameLoc); 1097 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1098 QualType T = Context.getTypeDeclType(Type); 1099 if (SS.isNotEmpty()) 1100 return buildNestedType(*this, SS, T, NameLoc); 1101 return ParsedType::make(T); 1102 } 1103 1104 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1105 if (!Class) { 1106 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1107 if (ObjCCompatibleAliasDecl *Alias = 1108 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1109 Class = Alias->getClassInterface(); 1110 } 1111 1112 if (Class) { 1113 DiagnoseUseOfDecl(Class, NameLoc); 1114 1115 if (NextToken.is(tok::period)) { 1116 // Interface. <something> is parsed as a property reference expression. 1117 // Just return "unknown" as a fall-through for now. 1118 Result.suppressDiagnostics(); 1119 return NameClassification::Unknown(); 1120 } 1121 1122 QualType T = Context.getObjCInterfaceType(Class); 1123 return ParsedType::make(T); 1124 } 1125 1126 // We can have a type template here if we're classifying a template argument. 1127 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1128 !isa<VarTemplateDecl>(FirstDecl)) 1129 return NameClassification::TypeTemplate( 1130 TemplateName(cast<TemplateDecl>(FirstDecl))); 1131 1132 // Check for a tag type hidden by a non-type decl in a few cases where it 1133 // seems likely a type is wanted instead of the non-type that was found. 1134 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1135 if ((NextToken.is(tok::identifier) || 1136 (NextIsOp && 1137 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1138 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1139 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1140 DiagnoseUseOfDecl(Type, NameLoc); 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 if (FirstDecl->isCXXClassMember()) 1148 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1149 nullptr, S); 1150 1151 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1152 return BuildDeclarationNameExpr(SS, Result, ADL); 1153 } 1154 1155 Sema::TemplateNameKindForDiagnostics 1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1157 auto *TD = Name.getAsTemplateDecl(); 1158 if (!TD) 1159 return TemplateNameKindForDiagnostics::DependentTemplate; 1160 if (isa<ClassTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::ClassTemplate; 1162 if (isa<FunctionTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::FunctionTemplate; 1164 if (isa<VarTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::VarTemplate; 1166 if (isa<TypeAliasTemplateDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::AliasTemplate; 1168 if (isa<TemplateTemplateParmDecl>(TD)) 1169 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1170 return TemplateNameKindForDiagnostics::DependentTemplate; 1171 } 1172 1173 // Determines the context to return to after temporarily entering a 1174 // context. This depends in an unnecessarily complicated way on the 1175 // exact ordering of callbacks from the parser. 1176 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1177 1178 // Functions defined inline within classes aren't parsed until we've 1179 // finished parsing the top-level class, so the top-level class is 1180 // the context we'll need to return to. 1181 // A Lambda call operator whose parent is a class must not be treated 1182 // as an inline member function. A Lambda can be used legally 1183 // either as an in-class member initializer or a default argument. These 1184 // are parsed once the class has been marked complete and so the containing 1185 // context would be the nested class (when the lambda is defined in one); 1186 // If the class is not complete, then the lambda is being used in an 1187 // ill-formed fashion (such as to specify the width of a bit-field, or 1188 // in an array-bound) - in which case we still want to return the 1189 // lexically containing DC (which could be a nested class). 1190 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1191 DC = DC->getLexicalParent(); 1192 1193 // A function not defined within a class will always return to its 1194 // lexical context. 1195 if (!isa<CXXRecordDecl>(DC)) 1196 return DC; 1197 1198 // A C++ inline method/friend is parsed *after* the topmost class 1199 // it was declared in is fully parsed ("complete"); the topmost 1200 // class is the context we need to return to. 1201 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1202 DC = RD; 1203 1204 // Return the declaration context of the topmost class the inline method is 1205 // declared in. 1206 return DC; 1207 } 1208 1209 return DC->getLexicalParent(); 1210 } 1211 1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1213 assert(getContainingDC(DC) == CurContext && 1214 "The next DeclContext should be lexically contained in the current one."); 1215 CurContext = DC; 1216 S->setEntity(DC); 1217 } 1218 1219 void Sema::PopDeclContext() { 1220 assert(CurContext && "DeclContext imbalance!"); 1221 1222 CurContext = getContainingDC(CurContext); 1223 assert(CurContext && "Popped translation unit!"); 1224 } 1225 1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1227 Decl *D) { 1228 // Unlike PushDeclContext, the context to which we return is not necessarily 1229 // the containing DC of TD, because the new context will be some pre-existing 1230 // TagDecl definition instead of a fresh one. 1231 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1232 CurContext = cast<TagDecl>(D)->getDefinition(); 1233 assert(CurContext && "skipping definition of undefined tag"); 1234 // Start lookups from the parent of the current context; we don't want to look 1235 // into the pre-existing complete definition. 1236 S->setEntity(CurContext->getLookupParent()); 1237 return Result; 1238 } 1239 1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1241 CurContext = static_cast<decltype(CurContext)>(Context); 1242 } 1243 1244 /// EnterDeclaratorContext - Used when we must lookup names in the context 1245 /// of a declarator's nested name specifier. 1246 /// 1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1248 // C++0x [basic.lookup.unqual]p13: 1249 // A name used in the definition of a static data member of class 1250 // X (after the qualified-id of the static member) is looked up as 1251 // if the name was used in a member function of X. 1252 // C++0x [basic.lookup.unqual]p14: 1253 // If a variable member of a namespace is defined outside of the 1254 // scope of its namespace then any name used in the definition of 1255 // the variable member (after the declarator-id) is looked up as 1256 // if the definition of the variable member occurred in its 1257 // namespace. 1258 // Both of these imply that we should push a scope whose context 1259 // is the semantic context of the declaration. We can't use 1260 // PushDeclContext here because that context is not necessarily 1261 // lexically contained in the current context. Fortunately, 1262 // the containing scope should have the appropriate information. 1263 1264 assert(!S->getEntity() && "scope already has entity"); 1265 1266 #ifndef NDEBUG 1267 Scope *Ancestor = S->getParent(); 1268 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1269 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1270 #endif 1271 1272 CurContext = DC; 1273 S->setEntity(DC); 1274 } 1275 1276 void Sema::ExitDeclaratorContext(Scope *S) { 1277 assert(S->getEntity() == CurContext && "Context imbalance!"); 1278 1279 // Switch back to the lexical context. The safety of this is 1280 // enforced by an assert in EnterDeclaratorContext. 1281 Scope *Ancestor = S->getParent(); 1282 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1283 CurContext = Ancestor->getEntity(); 1284 1285 // We don't need to do anything with the scope, which is going to 1286 // disappear. 1287 } 1288 1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1290 // We assume that the caller has already called 1291 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1292 FunctionDecl *FD = D->getAsFunction(); 1293 if (!FD) 1294 return; 1295 1296 // Same implementation as PushDeclContext, but enters the context 1297 // from the lexical parent, rather than the top-level class. 1298 assert(CurContext == FD->getLexicalParent() && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = FD; 1301 S->setEntity(CurContext); 1302 1303 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1304 ParmVarDecl *Param = FD->getParamDecl(P); 1305 // If the parameter has an identifier, then add it to the scope 1306 if (Param->getIdentifier()) { 1307 S->AddDecl(Param); 1308 IdResolver.AddDecl(Param); 1309 } 1310 } 1311 } 1312 1313 void Sema::ActOnExitFunctionContext() { 1314 // Same implementation as PopDeclContext, but returns to the lexical parent, 1315 // rather than the top-level class. 1316 assert(CurContext && "DeclContext imbalance!"); 1317 CurContext = CurContext->getLexicalParent(); 1318 assert(CurContext && "Popped translation unit!"); 1319 } 1320 1321 /// \brief Determine whether we allow overloading of the function 1322 /// PrevDecl with another declaration. 1323 /// 1324 /// This routine determines whether overloading is possible, not 1325 /// whether some new function is actually an overload. It will return 1326 /// true in C++ (where we can always provide overloads) or, as an 1327 /// extension, in C when the previous function is already an 1328 /// overloaded function declaration or has the "overloadable" 1329 /// attribute. 1330 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1331 ASTContext &Context, 1332 const FunctionDecl *New) { 1333 if (Context.getLangOpts().CPlusPlus) 1334 return true; 1335 1336 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1337 return true; 1338 1339 return Previous.getResultKind() == LookupResult::Found && 1340 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1341 New->hasAttr<OverloadableAttr>()); 1342 } 1343 1344 /// Add this decl to the scope shadowed decl chains. 1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1346 // Move up the scope chain until we find the nearest enclosing 1347 // non-transparent context. The declaration will be introduced into this 1348 // scope. 1349 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1350 S = S->getParent(); 1351 1352 // Add scoped declarations into their context, so that they can be 1353 // found later. Declarations without a context won't be inserted 1354 // into any context. 1355 if (AddToContext) 1356 CurContext->addDecl(D); 1357 1358 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1359 // are function-local declarations. 1360 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1361 !D->getDeclContext()->getRedeclContext()->Equals( 1362 D->getLexicalDeclContext()->getRedeclContext()) && 1363 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1364 return; 1365 1366 // Template instantiations should also not be pushed into scope. 1367 if (isa<FunctionDecl>(D) && 1368 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1369 return; 1370 1371 // If this replaces anything in the current scope, 1372 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1373 IEnd = IdResolver.end(); 1374 for (; I != IEnd; ++I) { 1375 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1376 S->RemoveDecl(*I); 1377 IdResolver.RemoveDecl(*I); 1378 1379 // Should only need to replace one decl. 1380 break; 1381 } 1382 } 1383 1384 S->AddDecl(D); 1385 1386 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1387 // Implicitly-generated labels may end up getting generated in an order that 1388 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1389 // the label at the appropriate place in the identifier chain. 1390 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1391 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1392 if (IDC == CurContext) { 1393 if (!S->isDeclScope(*I)) 1394 continue; 1395 } else if (IDC->Encloses(CurContext)) 1396 break; 1397 } 1398 1399 IdResolver.InsertDeclAfter(I, D); 1400 } else { 1401 IdResolver.AddDecl(D); 1402 } 1403 } 1404 1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1406 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1407 TUScope->AddDecl(D); 1408 } 1409 1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1411 bool AllowInlineNamespace) { 1412 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1413 } 1414 1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1416 DeclContext *TargetDC = DC->getPrimaryContext(); 1417 do { 1418 if (DeclContext *ScopeDC = S->getEntity()) 1419 if (ScopeDC->getPrimaryContext() == TargetDC) 1420 return S; 1421 } while ((S = S->getParent())); 1422 1423 return nullptr; 1424 } 1425 1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1427 DeclContext*, 1428 ASTContext&); 1429 1430 /// Filters out lookup results that don't fall within the given scope 1431 /// as determined by isDeclInScope. 1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1433 bool ConsiderLinkage, 1434 bool AllowInlineNamespace) { 1435 LookupResult::Filter F = R.makeFilter(); 1436 while (F.hasNext()) { 1437 NamedDecl *D = F.next(); 1438 1439 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1440 continue; 1441 1442 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1443 continue; 1444 1445 F.erase(); 1446 } 1447 1448 F.done(); 1449 } 1450 1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1452 /// have compatible owning modules. 1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1454 // FIXME: The Modules TS is not clear about how friend declarations are 1455 // to be treated. It's not meaningful to have different owning modules for 1456 // linkage in redeclarations of the same entity, so for now allow the 1457 // redeclaration and change the owning modules to match. 1458 if (New->getFriendObjectKind() && 1459 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1460 New->setLocalOwningModule(Old->getOwningModule()); 1461 makeMergedDefinitionVisible(New); 1462 return false; 1463 } 1464 1465 Module *NewM = New->getOwningModule(); 1466 Module *OldM = Old->getOwningModule(); 1467 if (NewM == OldM) 1468 return false; 1469 1470 // FIXME: Check proclaimed-ownership-declarations here too. 1471 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1472 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1473 if (NewIsModuleInterface || OldIsModuleInterface) { 1474 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1475 // if a declaration of D [...] appears in the purview of a module, all 1476 // other such declarations shall appear in the purview of the same module 1477 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1478 << New 1479 << NewIsModuleInterface 1480 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1481 << OldIsModuleInterface 1482 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1483 Diag(Old->getLocation(), diag::note_previous_declaration); 1484 New->setInvalidDecl(); 1485 return true; 1486 } 1487 1488 return false; 1489 } 1490 1491 static bool isUsingDecl(NamedDecl *D) { 1492 return isa<UsingShadowDecl>(D) || 1493 isa<UnresolvedUsingTypenameDecl>(D) || 1494 isa<UnresolvedUsingValueDecl>(D); 1495 } 1496 1497 /// Removes using shadow declarations from the lookup results. 1498 static void RemoveUsingDecls(LookupResult &R) { 1499 LookupResult::Filter F = R.makeFilter(); 1500 while (F.hasNext()) 1501 if (isUsingDecl(F.next())) 1502 F.erase(); 1503 1504 F.done(); 1505 } 1506 1507 /// \brief Check for this common pattern: 1508 /// @code 1509 /// class S { 1510 /// S(const S&); // DO NOT IMPLEMENT 1511 /// void operator=(const S&); // DO NOT IMPLEMENT 1512 /// }; 1513 /// @endcode 1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1515 // FIXME: Should check for private access too but access is set after we get 1516 // the decl here. 1517 if (D->doesThisDeclarationHaveABody()) 1518 return false; 1519 1520 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1521 return CD->isCopyConstructor(); 1522 return D->isCopyAssignmentOperator(); 1523 } 1524 1525 // We need this to handle 1526 // 1527 // typedef struct { 1528 // void *foo() { return 0; } 1529 // } A; 1530 // 1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1532 // for example. If 'A', foo will have external linkage. If we have '*A', 1533 // foo will have no linkage. Since we can't know until we get to the end 1534 // of the typedef, this function finds out if D might have non-external linkage. 1535 // Callers should verify at the end of the TU if it D has external linkage or 1536 // not. 1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1538 const DeclContext *DC = D->getDeclContext(); 1539 while (!DC->isTranslationUnit()) { 1540 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1541 if (!RD->hasNameForLinkage()) 1542 return true; 1543 } 1544 DC = DC->getParent(); 1545 } 1546 1547 return !D->isExternallyVisible(); 1548 } 1549 1550 // FIXME: This needs to be refactored; some other isInMainFile users want 1551 // these semantics. 1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1553 if (S.TUKind != TU_Complete) 1554 return false; 1555 return S.SourceMgr.isInMainFile(Loc); 1556 } 1557 1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1559 assert(D); 1560 1561 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1562 return false; 1563 1564 // Ignore all entities declared within templates, and out-of-line definitions 1565 // of members of class templates. 1566 if (D->getDeclContext()->isDependentContext() || 1567 D->getLexicalDeclContext()->isDependentContext()) 1568 return false; 1569 1570 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1571 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1572 return false; 1573 // A non-out-of-line declaration of a member specialization was implicitly 1574 // instantiated; it's the out-of-line declaration that we're interested in. 1575 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1576 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1577 return false; 1578 1579 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1580 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1581 return false; 1582 } else { 1583 // 'static inline' functions are defined in headers; don't warn. 1584 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1585 return false; 1586 } 1587 1588 if (FD->doesThisDeclarationHaveABody() && 1589 Context.DeclMustBeEmitted(FD)) 1590 return false; 1591 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1592 // Constants and utility variables are defined in headers with internal 1593 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1594 // like "inline".) 1595 if (!isMainFileLoc(*this, VD->getLocation())) 1596 return false; 1597 1598 if (Context.DeclMustBeEmitted(VD)) 1599 return false; 1600 1601 if (VD->isStaticDataMember() && 1602 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1603 return false; 1604 if (VD->isStaticDataMember() && 1605 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1606 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1607 return false; 1608 1609 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1610 return false; 1611 } else { 1612 return false; 1613 } 1614 1615 // Only warn for unused decls internal to the translation unit. 1616 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1617 // for inline functions defined in the main source file, for instance. 1618 return mightHaveNonExternalLinkage(D); 1619 } 1620 1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1622 if (!D) 1623 return; 1624 1625 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1626 const FunctionDecl *First = FD->getFirstDecl(); 1627 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1628 return; // First should already be in the vector. 1629 } 1630 1631 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1632 const VarDecl *First = VD->getFirstDecl(); 1633 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1634 return; // First should already be in the vector. 1635 } 1636 1637 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1638 UnusedFileScopedDecls.push_back(D); 1639 } 1640 1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1642 if (D->isInvalidDecl()) 1643 return false; 1644 1645 bool Referenced = false; 1646 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1647 // For a decomposition declaration, warn if none of the bindings are 1648 // referenced, instead of if the variable itself is referenced (which 1649 // it is, by the bindings' expressions). 1650 for (auto *BD : DD->bindings()) { 1651 if (BD->isReferenced()) { 1652 Referenced = true; 1653 break; 1654 } 1655 } 1656 } else if (!D->getDeclName()) { 1657 return false; 1658 } else if (D->isReferenced() || D->isUsed()) { 1659 Referenced = true; 1660 } 1661 1662 if (Referenced || D->hasAttr<UnusedAttr>() || 1663 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1664 return false; 1665 1666 if (isa<LabelDecl>(D)) 1667 return true; 1668 1669 // Except for labels, we only care about unused decls that are local to 1670 // functions. 1671 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1672 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1673 // For dependent types, the diagnostic is deferred. 1674 WithinFunction = 1675 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1676 if (!WithinFunction) 1677 return false; 1678 1679 if (isa<TypedefNameDecl>(D)) 1680 return true; 1681 1682 // White-list anything that isn't a local variable. 1683 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1684 return false; 1685 1686 // Types of valid local variables should be complete, so this should succeed. 1687 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1688 1689 // White-list anything with an __attribute__((unused)) type. 1690 const auto *Ty = VD->getType().getTypePtr(); 1691 1692 // Only look at the outermost level of typedef. 1693 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1694 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1695 return false; 1696 } 1697 1698 // If we failed to complete the type for some reason, or if the type is 1699 // dependent, don't diagnose the variable. 1700 if (Ty->isIncompleteType() || Ty->isDependentType()) 1701 return false; 1702 1703 // Look at the element type to ensure that the warning behaviour is 1704 // consistent for both scalars and arrays. 1705 Ty = Ty->getBaseElementTypeUnsafe(); 1706 1707 if (const TagType *TT = Ty->getAs<TagType>()) { 1708 const TagDecl *Tag = TT->getDecl(); 1709 if (Tag->hasAttr<UnusedAttr>()) 1710 return false; 1711 1712 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1713 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1714 return false; 1715 1716 if (const Expr *Init = VD->getInit()) { 1717 if (const ExprWithCleanups *Cleanups = 1718 dyn_cast<ExprWithCleanups>(Init)) 1719 Init = Cleanups->getSubExpr(); 1720 const CXXConstructExpr *Construct = 1721 dyn_cast<CXXConstructExpr>(Init); 1722 if (Construct && !Construct->isElidable()) { 1723 CXXConstructorDecl *CD = Construct->getConstructor(); 1724 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1725 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1726 return false; 1727 } 1728 } 1729 } 1730 } 1731 1732 // TODO: __attribute__((unused)) templates? 1733 } 1734 1735 return true; 1736 } 1737 1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1739 FixItHint &Hint) { 1740 if (isa<LabelDecl>(D)) { 1741 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1742 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1743 if (AfterColon.isInvalid()) 1744 return; 1745 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1746 getCharRange(D->getLocStart(), AfterColon)); 1747 } 1748 } 1749 1750 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1751 if (D->getTypeForDecl()->isDependentType()) 1752 return; 1753 1754 for (auto *TmpD : D->decls()) { 1755 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1756 DiagnoseUnusedDecl(T); 1757 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1758 DiagnoseUnusedNestedTypedefs(R); 1759 } 1760 } 1761 1762 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1763 /// unless they are marked attr(unused). 1764 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1765 if (!ShouldDiagnoseUnusedDecl(D)) 1766 return; 1767 1768 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1769 // typedefs can be referenced later on, so the diagnostics are emitted 1770 // at end-of-translation-unit. 1771 UnusedLocalTypedefNameCandidates.insert(TD); 1772 return; 1773 } 1774 1775 FixItHint Hint; 1776 GenerateFixForUnusedDecl(D, Context, Hint); 1777 1778 unsigned DiagID; 1779 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1780 DiagID = diag::warn_unused_exception_param; 1781 else if (isa<LabelDecl>(D)) 1782 DiagID = diag::warn_unused_label; 1783 else 1784 DiagID = diag::warn_unused_variable; 1785 1786 Diag(D->getLocation(), DiagID) << D << Hint; 1787 } 1788 1789 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1790 // Verify that we have no forward references left. If so, there was a goto 1791 // or address of a label taken, but no definition of it. Label fwd 1792 // definitions are indicated with a null substmt which is also not a resolved 1793 // MS inline assembly label name. 1794 bool Diagnose = false; 1795 if (L->isMSAsmLabel()) 1796 Diagnose = !L->isResolvedMSAsmLabel(); 1797 else 1798 Diagnose = L->getStmt() == nullptr; 1799 if (Diagnose) 1800 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1801 } 1802 1803 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1804 S->mergeNRVOIntoParent(); 1805 1806 if (S->decl_empty()) return; 1807 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1808 "Scope shouldn't contain decls!"); 1809 1810 for (auto *TmpD : S->decls()) { 1811 assert(TmpD && "This decl didn't get pushed??"); 1812 1813 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1814 NamedDecl *D = cast<NamedDecl>(TmpD); 1815 1816 // Diagnose unused variables in this scope. 1817 if (!S->hasUnrecoverableErrorOccurred()) { 1818 DiagnoseUnusedDecl(D); 1819 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1820 DiagnoseUnusedNestedTypedefs(RD); 1821 } 1822 1823 if (!D->getDeclName()) continue; 1824 1825 // If this was a forward reference to a label, verify it was defined. 1826 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1827 CheckPoppedLabel(LD, *this); 1828 1829 // Remove this name from our lexical scope, and warn on it if we haven't 1830 // already. 1831 IdResolver.RemoveDecl(D); 1832 auto ShadowI = ShadowingDecls.find(D); 1833 if (ShadowI != ShadowingDecls.end()) { 1834 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1835 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1836 << D << FD << FD->getParent(); 1837 Diag(FD->getLocation(), diag::note_previous_declaration); 1838 } 1839 ShadowingDecls.erase(ShadowI); 1840 } 1841 } 1842 } 1843 1844 /// \brief Look for an Objective-C class in the translation unit. 1845 /// 1846 /// \param Id The name of the Objective-C class we're looking for. If 1847 /// typo-correction fixes this name, the Id will be updated 1848 /// to the fixed name. 1849 /// 1850 /// \param IdLoc The location of the name in the translation unit. 1851 /// 1852 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1853 /// if there is no class with the given name. 1854 /// 1855 /// \returns The declaration of the named Objective-C class, or NULL if the 1856 /// class could not be found. 1857 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1858 SourceLocation IdLoc, 1859 bool DoTypoCorrection) { 1860 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1861 // creation from this context. 1862 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1863 1864 if (!IDecl && DoTypoCorrection) { 1865 // Perform typo correction at the given location, but only if we 1866 // find an Objective-C class name. 1867 if (TypoCorrection C = CorrectTypo( 1868 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1869 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1870 CTK_ErrorRecovery)) { 1871 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1872 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1873 Id = IDecl->getIdentifier(); 1874 } 1875 } 1876 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1877 // This routine must always return a class definition, if any. 1878 if (Def && Def->getDefinition()) 1879 Def = Def->getDefinition(); 1880 return Def; 1881 } 1882 1883 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1884 /// from S, where a non-field would be declared. This routine copes 1885 /// with the difference between C and C++ scoping rules in structs and 1886 /// unions. For example, the following code is well-formed in C but 1887 /// ill-formed in C++: 1888 /// @code 1889 /// struct S6 { 1890 /// enum { BAR } e; 1891 /// }; 1892 /// 1893 /// void test_S6() { 1894 /// struct S6 a; 1895 /// a.e = BAR; 1896 /// } 1897 /// @endcode 1898 /// For the declaration of BAR, this routine will return a different 1899 /// scope. The scope S will be the scope of the unnamed enumeration 1900 /// within S6. In C++, this routine will return the scope associated 1901 /// with S6, because the enumeration's scope is a transparent 1902 /// context but structures can contain non-field names. In C, this 1903 /// routine will return the translation unit scope, since the 1904 /// enumeration's scope is a transparent context and structures cannot 1905 /// contain non-field names. 1906 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1907 while (((S->getFlags() & Scope::DeclScope) == 0) || 1908 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1909 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1910 S = S->getParent(); 1911 return S; 1912 } 1913 1914 /// \brief Looks up the declaration of "struct objc_super" and 1915 /// saves it for later use in building builtin declaration of 1916 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1917 /// pre-existing declaration exists no action takes place. 1918 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1919 IdentifierInfo *II) { 1920 if (!II->isStr("objc_msgSendSuper")) 1921 return; 1922 ASTContext &Context = ThisSema.Context; 1923 1924 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1925 SourceLocation(), Sema::LookupTagName); 1926 ThisSema.LookupName(Result, S); 1927 if (Result.getResultKind() == LookupResult::Found) 1928 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1929 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1930 } 1931 1932 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1933 switch (Error) { 1934 case ASTContext::GE_None: 1935 return ""; 1936 case ASTContext::GE_Missing_stdio: 1937 return "stdio.h"; 1938 case ASTContext::GE_Missing_setjmp: 1939 return "setjmp.h"; 1940 case ASTContext::GE_Missing_ucontext: 1941 return "ucontext.h"; 1942 } 1943 llvm_unreachable("unhandled error kind"); 1944 } 1945 1946 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1947 /// file scope. lazily create a decl for it. ForRedeclaration is true 1948 /// if we're creating this built-in in anticipation of redeclaring the 1949 /// built-in. 1950 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1951 Scope *S, bool ForRedeclaration, 1952 SourceLocation Loc) { 1953 LookupPredefedObjCSuperType(*this, S, II); 1954 1955 ASTContext::GetBuiltinTypeError Error; 1956 QualType R = Context.GetBuiltinType(ID, Error); 1957 if (Error) { 1958 if (ForRedeclaration) 1959 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1960 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1961 return nullptr; 1962 } 1963 1964 if (!ForRedeclaration && 1965 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1966 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1967 Diag(Loc, diag::ext_implicit_lib_function_decl) 1968 << Context.BuiltinInfo.getName(ID) << R; 1969 if (Context.BuiltinInfo.getHeaderName(ID) && 1970 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1971 Diag(Loc, diag::note_include_header_or_declare) 1972 << Context.BuiltinInfo.getHeaderName(ID) 1973 << Context.BuiltinInfo.getName(ID); 1974 } 1975 1976 if (R.isNull()) 1977 return nullptr; 1978 1979 DeclContext *Parent = Context.getTranslationUnitDecl(); 1980 if (getLangOpts().CPlusPlus) { 1981 LinkageSpecDecl *CLinkageDecl = 1982 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1983 LinkageSpecDecl::lang_c, false); 1984 CLinkageDecl->setImplicit(); 1985 Parent->addDecl(CLinkageDecl); 1986 Parent = CLinkageDecl; 1987 } 1988 1989 FunctionDecl *New = FunctionDecl::Create(Context, 1990 Parent, 1991 Loc, Loc, II, R, /*TInfo=*/nullptr, 1992 SC_Extern, 1993 false, 1994 R->isFunctionProtoType()); 1995 New->setImplicit(); 1996 1997 // Create Decl objects for each parameter, adding them to the 1998 // FunctionDecl. 1999 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2000 SmallVector<ParmVarDecl*, 16> Params; 2001 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2002 ParmVarDecl *parm = 2003 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2004 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2005 SC_None, nullptr); 2006 parm->setScopeInfo(0, i); 2007 Params.push_back(parm); 2008 } 2009 New->setParams(Params); 2010 } 2011 2012 AddKnownFunctionAttributes(New); 2013 RegisterLocallyScopedExternCDecl(New, S); 2014 2015 // TUScope is the translation-unit scope to insert this function into. 2016 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2017 // relate Scopes to DeclContexts, and probably eliminate CurContext 2018 // entirely, but we're not there yet. 2019 DeclContext *SavedContext = CurContext; 2020 CurContext = Parent; 2021 PushOnScopeChains(New, TUScope); 2022 CurContext = SavedContext; 2023 return New; 2024 } 2025 2026 /// Typedef declarations don't have linkage, but they still denote the same 2027 /// entity if their types are the same. 2028 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2029 /// isSameEntity. 2030 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2031 TypedefNameDecl *Decl, 2032 LookupResult &Previous) { 2033 // This is only interesting when modules are enabled. 2034 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2035 return; 2036 2037 // Empty sets are uninteresting. 2038 if (Previous.empty()) 2039 return; 2040 2041 LookupResult::Filter Filter = Previous.makeFilter(); 2042 while (Filter.hasNext()) { 2043 NamedDecl *Old = Filter.next(); 2044 2045 // Non-hidden declarations are never ignored. 2046 if (S.isVisible(Old)) 2047 continue; 2048 2049 // Declarations of the same entity are not ignored, even if they have 2050 // different linkages. 2051 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2052 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2053 Decl->getUnderlyingType())) 2054 continue; 2055 2056 // If both declarations give a tag declaration a typedef name for linkage 2057 // purposes, then they declare the same entity. 2058 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2059 Decl->getAnonDeclWithTypedefName()) 2060 continue; 2061 } 2062 2063 Filter.erase(); 2064 } 2065 2066 Filter.done(); 2067 } 2068 2069 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2070 QualType OldType; 2071 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2072 OldType = OldTypedef->getUnderlyingType(); 2073 else 2074 OldType = Context.getTypeDeclType(Old); 2075 QualType NewType = New->getUnderlyingType(); 2076 2077 if (NewType->isVariablyModifiedType()) { 2078 // Must not redefine a typedef with a variably-modified type. 2079 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2080 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2081 << Kind << NewType; 2082 if (Old->getLocation().isValid()) 2083 notePreviousDefinition(Old, New->getLocation()); 2084 New->setInvalidDecl(); 2085 return true; 2086 } 2087 2088 if (OldType != NewType && 2089 !OldType->isDependentType() && 2090 !NewType->isDependentType() && 2091 !Context.hasSameType(OldType, NewType)) { 2092 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2093 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2094 << Kind << NewType << OldType; 2095 if (Old->getLocation().isValid()) 2096 notePreviousDefinition(Old, New->getLocation()); 2097 New->setInvalidDecl(); 2098 return true; 2099 } 2100 return false; 2101 } 2102 2103 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2104 /// same name and scope as a previous declaration 'Old'. Figure out 2105 /// how to resolve this situation, merging decls or emitting 2106 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2107 /// 2108 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2109 LookupResult &OldDecls) { 2110 // If the new decl is known invalid already, don't bother doing any 2111 // merging checks. 2112 if (New->isInvalidDecl()) return; 2113 2114 // Allow multiple definitions for ObjC built-in typedefs. 2115 // FIXME: Verify the underlying types are equivalent! 2116 if (getLangOpts().ObjC1) { 2117 const IdentifierInfo *TypeID = New->getIdentifier(); 2118 switch (TypeID->getLength()) { 2119 default: break; 2120 case 2: 2121 { 2122 if (!TypeID->isStr("id")) 2123 break; 2124 QualType T = New->getUnderlyingType(); 2125 if (!T->isPointerType()) 2126 break; 2127 if (!T->isVoidPointerType()) { 2128 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2129 if (!PT->isStructureType()) 2130 break; 2131 } 2132 Context.setObjCIdRedefinitionType(T); 2133 // Install the built-in type for 'id', ignoring the current definition. 2134 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2135 return; 2136 } 2137 case 5: 2138 if (!TypeID->isStr("Class")) 2139 break; 2140 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2141 // Install the built-in type for 'Class', ignoring the current definition. 2142 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2143 return; 2144 case 3: 2145 if (!TypeID->isStr("SEL")) 2146 break; 2147 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2148 // Install the built-in type for 'SEL', ignoring the current definition. 2149 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2150 return; 2151 } 2152 // Fall through - the typedef name was not a builtin type. 2153 } 2154 2155 // Verify the old decl was also a type. 2156 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2157 if (!Old) { 2158 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2159 << New->getDeclName(); 2160 2161 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2162 if (OldD->getLocation().isValid()) 2163 notePreviousDefinition(OldD, New->getLocation()); 2164 2165 return New->setInvalidDecl(); 2166 } 2167 2168 // If the old declaration is invalid, just give up here. 2169 if (Old->isInvalidDecl()) 2170 return New->setInvalidDecl(); 2171 2172 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2173 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2174 auto *NewTag = New->getAnonDeclWithTypedefName(); 2175 NamedDecl *Hidden = nullptr; 2176 if (OldTag && NewTag && 2177 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2178 !hasVisibleDefinition(OldTag, &Hidden)) { 2179 // There is a definition of this tag, but it is not visible. Use it 2180 // instead of our tag. 2181 New->setTypeForDecl(OldTD->getTypeForDecl()); 2182 if (OldTD->isModed()) 2183 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2184 OldTD->getUnderlyingType()); 2185 else 2186 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2187 2188 // Make the old tag definition visible. 2189 makeMergedDefinitionVisible(Hidden); 2190 2191 // If this was an unscoped enumeration, yank all of its enumerators 2192 // out of the scope. 2193 if (isa<EnumDecl>(NewTag)) { 2194 Scope *EnumScope = getNonFieldDeclScope(S); 2195 for (auto *D : NewTag->decls()) { 2196 auto *ED = cast<EnumConstantDecl>(D); 2197 assert(EnumScope->isDeclScope(ED)); 2198 EnumScope->RemoveDecl(ED); 2199 IdResolver.RemoveDecl(ED); 2200 ED->getLexicalDeclContext()->removeDecl(ED); 2201 } 2202 } 2203 } 2204 } 2205 2206 // If the typedef types are not identical, reject them in all languages and 2207 // with any extensions enabled. 2208 if (isIncompatibleTypedef(Old, New)) 2209 return; 2210 2211 // The types match. Link up the redeclaration chain and merge attributes if 2212 // the old declaration was a typedef. 2213 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2214 New->setPreviousDecl(Typedef); 2215 mergeDeclAttributes(New, Old); 2216 } 2217 2218 if (getLangOpts().MicrosoftExt) 2219 return; 2220 2221 if (getLangOpts().CPlusPlus) { 2222 // C++ [dcl.typedef]p2: 2223 // In a given non-class scope, a typedef specifier can be used to 2224 // redefine the name of any type declared in that scope to refer 2225 // to the type to which it already refers. 2226 if (!isa<CXXRecordDecl>(CurContext)) 2227 return; 2228 2229 // C++0x [dcl.typedef]p4: 2230 // In a given class scope, a typedef specifier can be used to redefine 2231 // any class-name declared in that scope that is not also a typedef-name 2232 // to refer to the type to which it already refers. 2233 // 2234 // This wording came in via DR424, which was a correction to the 2235 // wording in DR56, which accidentally banned code like: 2236 // 2237 // struct S { 2238 // typedef struct A { } A; 2239 // }; 2240 // 2241 // in the C++03 standard. We implement the C++0x semantics, which 2242 // allow the above but disallow 2243 // 2244 // struct S { 2245 // typedef int I; 2246 // typedef int I; 2247 // }; 2248 // 2249 // since that was the intent of DR56. 2250 if (!isa<TypedefNameDecl>(Old)) 2251 return; 2252 2253 Diag(New->getLocation(), diag::err_redefinition) 2254 << New->getDeclName(); 2255 notePreviousDefinition(Old, New->getLocation()); 2256 return New->setInvalidDecl(); 2257 } 2258 2259 // Modules always permit redefinition of typedefs, as does C11. 2260 if (getLangOpts().Modules || getLangOpts().C11) 2261 return; 2262 2263 // If we have a redefinition of a typedef in C, emit a warning. This warning 2264 // is normally mapped to an error, but can be controlled with 2265 // -Wtypedef-redefinition. If either the original or the redefinition is 2266 // in a system header, don't emit this for compatibility with GCC. 2267 if (getDiagnostics().getSuppressSystemWarnings() && 2268 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2269 (Old->isImplicit() || 2270 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2271 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2272 return; 2273 2274 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2275 << New->getDeclName(); 2276 notePreviousDefinition(Old, New->getLocation()); 2277 } 2278 2279 /// DeclhasAttr - returns true if decl Declaration already has the target 2280 /// attribute. 2281 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2282 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2283 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2284 for (const auto *i : D->attrs()) 2285 if (i->getKind() == A->getKind()) { 2286 if (Ann) { 2287 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2288 return true; 2289 continue; 2290 } 2291 // FIXME: Don't hardcode this check 2292 if (OA && isa<OwnershipAttr>(i)) 2293 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2294 return true; 2295 } 2296 2297 return false; 2298 } 2299 2300 static bool isAttributeTargetADefinition(Decl *D) { 2301 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2302 return VD->isThisDeclarationADefinition(); 2303 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2304 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2305 return true; 2306 } 2307 2308 /// Merge alignment attributes from \p Old to \p New, taking into account the 2309 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2310 /// 2311 /// \return \c true if any attributes were added to \p New. 2312 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2313 // Look for alignas attributes on Old, and pick out whichever attribute 2314 // specifies the strictest alignment requirement. 2315 AlignedAttr *OldAlignasAttr = nullptr; 2316 AlignedAttr *OldStrictestAlignAttr = nullptr; 2317 unsigned OldAlign = 0; 2318 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2319 // FIXME: We have no way of representing inherited dependent alignments 2320 // in a case like: 2321 // template<int A, int B> struct alignas(A) X; 2322 // template<int A, int B> struct alignas(B) X {}; 2323 // For now, we just ignore any alignas attributes which are not on the 2324 // definition in such a case. 2325 if (I->isAlignmentDependent()) 2326 return false; 2327 2328 if (I->isAlignas()) 2329 OldAlignasAttr = I; 2330 2331 unsigned Align = I->getAlignment(S.Context); 2332 if (Align > OldAlign) { 2333 OldAlign = Align; 2334 OldStrictestAlignAttr = I; 2335 } 2336 } 2337 2338 // Look for alignas attributes on New. 2339 AlignedAttr *NewAlignasAttr = nullptr; 2340 unsigned NewAlign = 0; 2341 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2342 if (I->isAlignmentDependent()) 2343 return false; 2344 2345 if (I->isAlignas()) 2346 NewAlignasAttr = I; 2347 2348 unsigned Align = I->getAlignment(S.Context); 2349 if (Align > NewAlign) 2350 NewAlign = Align; 2351 } 2352 2353 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2354 // Both declarations have 'alignas' attributes. We require them to match. 2355 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2356 // fall short. (If two declarations both have alignas, they must both match 2357 // every definition, and so must match each other if there is a definition.) 2358 2359 // If either declaration only contains 'alignas(0)' specifiers, then it 2360 // specifies the natural alignment for the type. 2361 if (OldAlign == 0 || NewAlign == 0) { 2362 QualType Ty; 2363 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2364 Ty = VD->getType(); 2365 else 2366 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2367 2368 if (OldAlign == 0) 2369 OldAlign = S.Context.getTypeAlign(Ty); 2370 if (NewAlign == 0) 2371 NewAlign = S.Context.getTypeAlign(Ty); 2372 } 2373 2374 if (OldAlign != NewAlign) { 2375 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2376 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2377 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2378 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2379 } 2380 } 2381 2382 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2383 // C++11 [dcl.align]p6: 2384 // if any declaration of an entity has an alignment-specifier, 2385 // every defining declaration of that entity shall specify an 2386 // equivalent alignment. 2387 // C11 6.7.5/7: 2388 // If the definition of an object does not have an alignment 2389 // specifier, any other declaration of that object shall also 2390 // have no alignment specifier. 2391 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2392 << OldAlignasAttr; 2393 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2394 << OldAlignasAttr; 2395 } 2396 2397 bool AnyAdded = false; 2398 2399 // Ensure we have an attribute representing the strictest alignment. 2400 if (OldAlign > NewAlign) { 2401 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2402 Clone->setInherited(true); 2403 New->addAttr(Clone); 2404 AnyAdded = true; 2405 } 2406 2407 // Ensure we have an alignas attribute if the old declaration had one. 2408 if (OldAlignasAttr && !NewAlignasAttr && 2409 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2410 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2411 Clone->setInherited(true); 2412 New->addAttr(Clone); 2413 AnyAdded = true; 2414 } 2415 2416 return AnyAdded; 2417 } 2418 2419 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2420 const InheritableAttr *Attr, 2421 Sema::AvailabilityMergeKind AMK) { 2422 // This function copies an attribute Attr from a previous declaration to the 2423 // new declaration D if the new declaration doesn't itself have that attribute 2424 // yet or if that attribute allows duplicates. 2425 // If you're adding a new attribute that requires logic different from 2426 // "use explicit attribute on decl if present, else use attribute from 2427 // previous decl", for example if the attribute needs to be consistent 2428 // between redeclarations, you need to call a custom merge function here. 2429 InheritableAttr *NewAttr = nullptr; 2430 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2431 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2432 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2433 AA->isImplicit(), AA->getIntroduced(), 2434 AA->getDeprecated(), 2435 AA->getObsoleted(), AA->getUnavailable(), 2436 AA->getMessage(), AA->getStrict(), 2437 AA->getReplacement(), AMK, 2438 AttrSpellingListIndex); 2439 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2440 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2441 AttrSpellingListIndex); 2442 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2443 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2444 AttrSpellingListIndex); 2445 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2446 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2447 AttrSpellingListIndex); 2448 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2449 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2450 AttrSpellingListIndex); 2451 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2452 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2453 FA->getFormatIdx(), FA->getFirstArg(), 2454 AttrSpellingListIndex); 2455 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2456 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2457 AttrSpellingListIndex); 2458 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2459 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2460 AttrSpellingListIndex, 2461 IA->getSemanticSpelling()); 2462 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2463 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2464 &S.Context.Idents.get(AA->getSpelling()), 2465 AttrSpellingListIndex); 2466 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2467 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2468 isa<CUDAGlobalAttr>(Attr))) { 2469 // CUDA target attributes are part of function signature for 2470 // overloading purposes and must not be merged. 2471 return false; 2472 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2473 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2474 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2475 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2476 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2477 NewAttr = S.mergeInternalLinkageAttr( 2478 D, InternalLinkageA->getRange(), 2479 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2480 AttrSpellingListIndex); 2481 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2482 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2483 &S.Context.Idents.get(CommonA->getSpelling()), 2484 AttrSpellingListIndex); 2485 else if (isa<AlignedAttr>(Attr)) 2486 // AlignedAttrs are handled separately, because we need to handle all 2487 // such attributes on a declaration at the same time. 2488 NewAttr = nullptr; 2489 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2490 (AMK == Sema::AMK_Override || 2491 AMK == Sema::AMK_ProtocolImplementation)) 2492 NewAttr = nullptr; 2493 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2494 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2495 UA->getGuid()); 2496 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2497 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2498 2499 if (NewAttr) { 2500 NewAttr->setInherited(true); 2501 D->addAttr(NewAttr); 2502 if (isa<MSInheritanceAttr>(NewAttr)) 2503 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2504 return true; 2505 } 2506 2507 return false; 2508 } 2509 2510 static const NamedDecl *getDefinition(const Decl *D) { 2511 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2512 return TD->getDefinition(); 2513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2514 const VarDecl *Def = VD->getDefinition(); 2515 if (Def) 2516 return Def; 2517 return VD->getActingDefinition(); 2518 } 2519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2520 return FD->getDefinition(); 2521 return nullptr; 2522 } 2523 2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2525 for (const auto *Attribute : D->attrs()) 2526 if (Attribute->getKind() == Kind) 2527 return true; 2528 return false; 2529 } 2530 2531 /// checkNewAttributesAfterDef - If we already have a definition, check that 2532 /// there are no new attributes in this declaration. 2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2534 if (!New->hasAttrs()) 2535 return; 2536 2537 const NamedDecl *Def = getDefinition(Old); 2538 if (!Def || Def == New) 2539 return; 2540 2541 AttrVec &NewAttributes = New->getAttrs(); 2542 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2543 const Attr *NewAttribute = NewAttributes[I]; 2544 2545 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2547 Sema::SkipBodyInfo SkipBody; 2548 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2549 2550 // If we're skipping this definition, drop the "alias" attribute. 2551 if (SkipBody.ShouldSkip) { 2552 NewAttributes.erase(NewAttributes.begin() + I); 2553 --E; 2554 continue; 2555 } 2556 } else { 2557 VarDecl *VD = cast<VarDecl>(New); 2558 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2559 VarDecl::TentativeDefinition 2560 ? diag::err_alias_after_tentative 2561 : diag::err_redefinition; 2562 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2563 if (Diag == diag::err_redefinition) 2564 S.notePreviousDefinition(Def, VD->getLocation()); 2565 else 2566 S.Diag(Def->getLocation(), diag::note_previous_definition); 2567 VD->setInvalidDecl(); 2568 } 2569 ++I; 2570 continue; 2571 } 2572 2573 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2574 // Tentative definitions are only interesting for the alias check above. 2575 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2576 ++I; 2577 continue; 2578 } 2579 } 2580 2581 if (hasAttribute(Def, NewAttribute->getKind())) { 2582 ++I; 2583 continue; // regular attr merging will take care of validating this. 2584 } 2585 2586 if (isa<C11NoReturnAttr>(NewAttribute)) { 2587 // C's _Noreturn is allowed to be added to a function after it is defined. 2588 ++I; 2589 continue; 2590 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2591 if (AA->isAlignas()) { 2592 // C++11 [dcl.align]p6: 2593 // if any declaration of an entity has an alignment-specifier, 2594 // every defining declaration of that entity shall specify an 2595 // equivalent alignment. 2596 // C11 6.7.5/7: 2597 // If the definition of an object does not have an alignment 2598 // specifier, any other declaration of that object shall also 2599 // have no alignment specifier. 2600 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2601 << AA; 2602 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2603 << AA; 2604 NewAttributes.erase(NewAttributes.begin() + I); 2605 --E; 2606 continue; 2607 } 2608 } 2609 2610 S.Diag(NewAttribute->getLocation(), 2611 diag::warn_attribute_precede_definition); 2612 S.Diag(Def->getLocation(), diag::note_previous_definition); 2613 NewAttributes.erase(NewAttributes.begin() + I); 2614 --E; 2615 } 2616 } 2617 2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2620 AvailabilityMergeKind AMK) { 2621 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2622 UsedAttr *NewAttr = OldAttr->clone(Context); 2623 NewAttr->setInherited(true); 2624 New->addAttr(NewAttr); 2625 } 2626 2627 if (!Old->hasAttrs() && !New->hasAttrs()) 2628 return; 2629 2630 // Attributes declared post-definition are currently ignored. 2631 checkNewAttributesAfterDef(*this, New, Old); 2632 2633 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2634 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2635 if (OldA->getLabel() != NewA->getLabel()) { 2636 // This redeclaration changes __asm__ label. 2637 Diag(New->getLocation(), diag::err_different_asm_label); 2638 Diag(OldA->getLocation(), diag::note_previous_declaration); 2639 } 2640 } else if (Old->isUsed()) { 2641 // This redeclaration adds an __asm__ label to a declaration that has 2642 // already been ODR-used. 2643 Diag(New->getLocation(), diag::err_late_asm_label_name) 2644 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2645 } 2646 } 2647 2648 // Re-declaration cannot add abi_tag's. 2649 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2650 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2651 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2652 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2653 NewTag) == OldAbiTagAttr->tags_end()) { 2654 Diag(NewAbiTagAttr->getLocation(), 2655 diag::err_new_abi_tag_on_redeclaration) 2656 << NewTag; 2657 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2658 } 2659 } 2660 } else { 2661 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2662 Diag(Old->getLocation(), diag::note_previous_declaration); 2663 } 2664 } 2665 2666 // This redeclaration adds a section attribute. 2667 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2668 if (auto *VD = dyn_cast<VarDecl>(New)) { 2669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2670 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2671 Diag(Old->getLocation(), diag::note_previous_declaration); 2672 } 2673 } 2674 } 2675 2676 if (!Old->hasAttrs()) 2677 return; 2678 2679 bool foundAny = New->hasAttrs(); 2680 2681 // Ensure that any moving of objects within the allocated map is done before 2682 // we process them. 2683 if (!foundAny) New->setAttrs(AttrVec()); 2684 2685 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2686 // Ignore deprecated/unavailable/availability attributes if requested. 2687 AvailabilityMergeKind LocalAMK = AMK_None; 2688 if (isa<DeprecatedAttr>(I) || 2689 isa<UnavailableAttr>(I) || 2690 isa<AvailabilityAttr>(I)) { 2691 switch (AMK) { 2692 case AMK_None: 2693 continue; 2694 2695 case AMK_Redeclaration: 2696 case AMK_Override: 2697 case AMK_ProtocolImplementation: 2698 LocalAMK = AMK; 2699 break; 2700 } 2701 } 2702 2703 // Already handled. 2704 if (isa<UsedAttr>(I)) 2705 continue; 2706 2707 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2708 foundAny = true; 2709 } 2710 2711 if (mergeAlignedAttrs(*this, New, Old)) 2712 foundAny = true; 2713 2714 if (!foundAny) New->dropAttrs(); 2715 } 2716 2717 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2718 /// to the new one. 2719 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2720 const ParmVarDecl *oldDecl, 2721 Sema &S) { 2722 // C++11 [dcl.attr.depend]p2: 2723 // The first declaration of a function shall specify the 2724 // carries_dependency attribute for its declarator-id if any declaration 2725 // of the function specifies the carries_dependency attribute. 2726 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2727 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2728 S.Diag(CDA->getLocation(), 2729 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2730 // Find the first declaration of the parameter. 2731 // FIXME: Should we build redeclaration chains for function parameters? 2732 const FunctionDecl *FirstFD = 2733 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2734 const ParmVarDecl *FirstVD = 2735 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2736 S.Diag(FirstVD->getLocation(), 2737 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2738 } 2739 2740 if (!oldDecl->hasAttrs()) 2741 return; 2742 2743 bool foundAny = newDecl->hasAttrs(); 2744 2745 // Ensure that any moving of objects within the allocated map is 2746 // done before we process them. 2747 if (!foundAny) newDecl->setAttrs(AttrVec()); 2748 2749 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2750 if (!DeclHasAttr(newDecl, I)) { 2751 InheritableAttr *newAttr = 2752 cast<InheritableParamAttr>(I->clone(S.Context)); 2753 newAttr->setInherited(true); 2754 newDecl->addAttr(newAttr); 2755 foundAny = true; 2756 } 2757 } 2758 2759 if (!foundAny) newDecl->dropAttrs(); 2760 } 2761 2762 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2763 const ParmVarDecl *OldParam, 2764 Sema &S) { 2765 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2766 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2767 if (*Oldnullability != *Newnullability) { 2768 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2769 << DiagNullabilityKind( 2770 *Newnullability, 2771 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2772 != 0)) 2773 << DiagNullabilityKind( 2774 *Oldnullability, 2775 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2776 != 0)); 2777 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2778 } 2779 } else { 2780 QualType NewT = NewParam->getType(); 2781 NewT = S.Context.getAttributedType( 2782 AttributedType::getNullabilityAttrKind(*Oldnullability), 2783 NewT, NewT); 2784 NewParam->setType(NewT); 2785 } 2786 } 2787 } 2788 2789 namespace { 2790 2791 /// Used in MergeFunctionDecl to keep track of function parameters in 2792 /// C. 2793 struct GNUCompatibleParamWarning { 2794 ParmVarDecl *OldParm; 2795 ParmVarDecl *NewParm; 2796 QualType PromotedType; 2797 }; 2798 2799 } // end anonymous namespace 2800 2801 /// getSpecialMember - get the special member enum for a method. 2802 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2803 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2804 if (Ctor->isDefaultConstructor()) 2805 return Sema::CXXDefaultConstructor; 2806 2807 if (Ctor->isCopyConstructor()) 2808 return Sema::CXXCopyConstructor; 2809 2810 if (Ctor->isMoveConstructor()) 2811 return Sema::CXXMoveConstructor; 2812 } else if (isa<CXXDestructorDecl>(MD)) { 2813 return Sema::CXXDestructor; 2814 } else if (MD->isCopyAssignmentOperator()) { 2815 return Sema::CXXCopyAssignment; 2816 } else if (MD->isMoveAssignmentOperator()) { 2817 return Sema::CXXMoveAssignment; 2818 } 2819 2820 return Sema::CXXInvalid; 2821 } 2822 2823 // Determine whether the previous declaration was a definition, implicit 2824 // declaration, or a declaration. 2825 template <typename T> 2826 static std::pair<diag::kind, SourceLocation> 2827 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2828 diag::kind PrevDiag; 2829 SourceLocation OldLocation = Old->getLocation(); 2830 if (Old->isThisDeclarationADefinition()) 2831 PrevDiag = diag::note_previous_definition; 2832 else if (Old->isImplicit()) { 2833 PrevDiag = diag::note_previous_implicit_declaration; 2834 if (OldLocation.isInvalid()) 2835 OldLocation = New->getLocation(); 2836 } else 2837 PrevDiag = diag::note_previous_declaration; 2838 return std::make_pair(PrevDiag, OldLocation); 2839 } 2840 2841 /// canRedefineFunction - checks if a function can be redefined. Currently, 2842 /// only extern inline functions can be redefined, and even then only in 2843 /// GNU89 mode. 2844 static bool canRedefineFunction(const FunctionDecl *FD, 2845 const LangOptions& LangOpts) { 2846 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2847 !LangOpts.CPlusPlus && 2848 FD->isInlineSpecified() && 2849 FD->getStorageClass() == SC_Extern); 2850 } 2851 2852 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2853 const AttributedType *AT = T->getAs<AttributedType>(); 2854 while (AT && !AT->isCallingConv()) 2855 AT = AT->getModifiedType()->getAs<AttributedType>(); 2856 return AT; 2857 } 2858 2859 template <typename T> 2860 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2861 const DeclContext *DC = Old->getDeclContext(); 2862 if (DC->isRecord()) 2863 return false; 2864 2865 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2866 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2867 return true; 2868 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2869 return true; 2870 return false; 2871 } 2872 2873 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2874 static bool isExternC(VarTemplateDecl *) { return false; } 2875 2876 /// \brief Check whether a redeclaration of an entity introduced by a 2877 /// using-declaration is valid, given that we know it's not an overload 2878 /// (nor a hidden tag declaration). 2879 template<typename ExpectedDecl> 2880 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2881 ExpectedDecl *New) { 2882 // C++11 [basic.scope.declarative]p4: 2883 // Given a set of declarations in a single declarative region, each of 2884 // which specifies the same unqualified name, 2885 // -- they shall all refer to the same entity, or all refer to functions 2886 // and function templates; or 2887 // -- exactly one declaration shall declare a class name or enumeration 2888 // name that is not a typedef name and the other declarations shall all 2889 // refer to the same variable or enumerator, or all refer to functions 2890 // and function templates; in this case the class name or enumeration 2891 // name is hidden (3.3.10). 2892 2893 // C++11 [namespace.udecl]p14: 2894 // If a function declaration in namespace scope or block scope has the 2895 // same name and the same parameter-type-list as a function introduced 2896 // by a using-declaration, and the declarations do not declare the same 2897 // function, the program is ill-formed. 2898 2899 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2900 if (Old && 2901 !Old->getDeclContext()->getRedeclContext()->Equals( 2902 New->getDeclContext()->getRedeclContext()) && 2903 !(isExternC(Old) && isExternC(New))) 2904 Old = nullptr; 2905 2906 if (!Old) { 2907 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2908 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2909 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2910 return true; 2911 } 2912 return false; 2913 } 2914 2915 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2916 const FunctionDecl *B) { 2917 assert(A->getNumParams() == B->getNumParams()); 2918 2919 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2920 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2921 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2922 if (AttrA == AttrB) 2923 return true; 2924 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2925 }; 2926 2927 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2928 } 2929 2930 /// If necessary, adjust the semantic declaration context for a qualified 2931 /// declaration to name the correct inline namespace within the qualifier. 2932 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2933 DeclaratorDecl *OldD) { 2934 // The only case where we need to update the DeclContext is when 2935 // redeclaration lookup for a qualified name finds a declaration 2936 // in an inline namespace within the context named by the qualifier: 2937 // 2938 // inline namespace N { int f(); } 2939 // int ::f(); // Sema DC needs adjusting from :: to N::. 2940 // 2941 // For unqualified declarations, the semantic context *can* change 2942 // along the redeclaration chain (for local extern declarations, 2943 // extern "C" declarations, and friend declarations in particular). 2944 if (!NewD->getQualifier()) 2945 return; 2946 2947 // NewD is probably already in the right context. 2948 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2949 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2950 if (NamedDC->Equals(SemaDC)) 2951 return; 2952 2953 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2954 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2955 "unexpected context for redeclaration"); 2956 2957 auto *LexDC = NewD->getLexicalDeclContext(); 2958 auto FixSemaDC = [=](NamedDecl *D) { 2959 if (!D) 2960 return; 2961 D->setDeclContext(SemaDC); 2962 D->setLexicalDeclContext(LexDC); 2963 }; 2964 2965 FixSemaDC(NewD); 2966 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2967 FixSemaDC(FD->getDescribedFunctionTemplate()); 2968 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2969 FixSemaDC(VD->getDescribedVarTemplate()); 2970 } 2971 2972 /// MergeFunctionDecl - We just parsed a function 'New' from 2973 /// declarator D which has the same name and scope as a previous 2974 /// declaration 'Old'. Figure out how to resolve this situation, 2975 /// merging decls or emitting diagnostics as appropriate. 2976 /// 2977 /// In C++, New and Old must be declarations that are not 2978 /// overloaded. Use IsOverload to determine whether New and Old are 2979 /// overloaded, and to select the Old declaration that New should be 2980 /// merged with. 2981 /// 2982 /// Returns true if there was an error, false otherwise. 2983 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2984 Scope *S, bool MergeTypeWithOld) { 2985 // Verify the old decl was also a function. 2986 FunctionDecl *Old = OldD->getAsFunction(); 2987 if (!Old) { 2988 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2989 if (New->getFriendObjectKind()) { 2990 Diag(New->getLocation(), diag::err_using_decl_friend); 2991 Diag(Shadow->getTargetDecl()->getLocation(), 2992 diag::note_using_decl_target); 2993 Diag(Shadow->getUsingDecl()->getLocation(), 2994 diag::note_using_decl) << 0; 2995 return true; 2996 } 2997 2998 // Check whether the two declarations might declare the same function. 2999 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3000 return true; 3001 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3002 } else { 3003 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3004 << New->getDeclName(); 3005 notePreviousDefinition(OldD, New->getLocation()); 3006 return true; 3007 } 3008 } 3009 3010 // If the old declaration is invalid, just give up here. 3011 if (Old->isInvalidDecl()) 3012 return true; 3013 3014 diag::kind PrevDiag; 3015 SourceLocation OldLocation; 3016 std::tie(PrevDiag, OldLocation) = 3017 getNoteDiagForInvalidRedeclaration(Old, New); 3018 3019 // Don't complain about this if we're in GNU89 mode and the old function 3020 // is an extern inline function. 3021 // Don't complain about specializations. They are not supposed to have 3022 // storage classes. 3023 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3024 New->getStorageClass() == SC_Static && 3025 Old->hasExternalFormalLinkage() && 3026 !New->getTemplateSpecializationInfo() && 3027 !canRedefineFunction(Old, getLangOpts())) { 3028 if (getLangOpts().MicrosoftExt) { 3029 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3030 Diag(OldLocation, PrevDiag); 3031 } else { 3032 Diag(New->getLocation(), diag::err_static_non_static) << New; 3033 Diag(OldLocation, PrevDiag); 3034 return true; 3035 } 3036 } 3037 3038 if (New->hasAttr<InternalLinkageAttr>() && 3039 !Old->hasAttr<InternalLinkageAttr>()) { 3040 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3041 << New->getDeclName(); 3042 notePreviousDefinition(Old, New->getLocation()); 3043 New->dropAttr<InternalLinkageAttr>(); 3044 } 3045 3046 if (CheckRedeclarationModuleOwnership(New, Old)) 3047 return true; 3048 3049 if (!getLangOpts().CPlusPlus) { 3050 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3051 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3052 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3053 << New << OldOvl; 3054 3055 // Try our best to find a decl that actually has the overloadable 3056 // attribute for the note. In most cases (e.g. programs with only one 3057 // broken declaration/definition), this won't matter. 3058 // 3059 // FIXME: We could do this if we juggled some extra state in 3060 // OverloadableAttr, rather than just removing it. 3061 const Decl *DiagOld = Old; 3062 if (OldOvl) { 3063 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3064 const auto *A = D->getAttr<OverloadableAttr>(); 3065 return A && !A->isImplicit(); 3066 }); 3067 // If we've implicitly added *all* of the overloadable attrs to this 3068 // chain, emitting a "previous redecl" note is pointless. 3069 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3070 } 3071 3072 if (DiagOld) 3073 Diag(DiagOld->getLocation(), 3074 diag::note_attribute_overloadable_prev_overload) 3075 << OldOvl; 3076 3077 if (OldOvl) 3078 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3079 else 3080 New->dropAttr<OverloadableAttr>(); 3081 } 3082 } 3083 3084 // If a function is first declared with a calling convention, but is later 3085 // declared or defined without one, all following decls assume the calling 3086 // convention of the first. 3087 // 3088 // It's OK if a function is first declared without a calling convention, 3089 // but is later declared or defined with the default calling convention. 3090 // 3091 // To test if either decl has an explicit calling convention, we look for 3092 // AttributedType sugar nodes on the type as written. If they are missing or 3093 // were canonicalized away, we assume the calling convention was implicit. 3094 // 3095 // Note also that we DO NOT return at this point, because we still have 3096 // other tests to run. 3097 QualType OldQType = Context.getCanonicalType(Old->getType()); 3098 QualType NewQType = Context.getCanonicalType(New->getType()); 3099 const FunctionType *OldType = cast<FunctionType>(OldQType); 3100 const FunctionType *NewType = cast<FunctionType>(NewQType); 3101 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3102 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3103 bool RequiresAdjustment = false; 3104 3105 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3106 FunctionDecl *First = Old->getFirstDecl(); 3107 const FunctionType *FT = 3108 First->getType().getCanonicalType()->castAs<FunctionType>(); 3109 FunctionType::ExtInfo FI = FT->getExtInfo(); 3110 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3111 if (!NewCCExplicit) { 3112 // Inherit the CC from the previous declaration if it was specified 3113 // there but not here. 3114 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3115 RequiresAdjustment = true; 3116 } else { 3117 // Calling conventions aren't compatible, so complain. 3118 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3119 Diag(New->getLocation(), diag::err_cconv_change) 3120 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3121 << !FirstCCExplicit 3122 << (!FirstCCExplicit ? "" : 3123 FunctionType::getNameForCallConv(FI.getCC())); 3124 3125 // Put the note on the first decl, since it is the one that matters. 3126 Diag(First->getLocation(), diag::note_previous_declaration); 3127 return true; 3128 } 3129 } 3130 3131 // FIXME: diagnose the other way around? 3132 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3133 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3134 RequiresAdjustment = true; 3135 } 3136 3137 // Merge regparm attribute. 3138 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3139 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3140 if (NewTypeInfo.getHasRegParm()) { 3141 Diag(New->getLocation(), diag::err_regparm_mismatch) 3142 << NewType->getRegParmType() 3143 << OldType->getRegParmType(); 3144 Diag(OldLocation, diag::note_previous_declaration); 3145 return true; 3146 } 3147 3148 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3149 RequiresAdjustment = true; 3150 } 3151 3152 // Merge ns_returns_retained attribute. 3153 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3154 if (NewTypeInfo.getProducesResult()) { 3155 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3156 << "'ns_returns_retained'"; 3157 Diag(OldLocation, diag::note_previous_declaration); 3158 return true; 3159 } 3160 3161 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3162 RequiresAdjustment = true; 3163 } 3164 3165 if (OldTypeInfo.getNoCallerSavedRegs() != 3166 NewTypeInfo.getNoCallerSavedRegs()) { 3167 if (NewTypeInfo.getNoCallerSavedRegs()) { 3168 AnyX86NoCallerSavedRegistersAttr *Attr = 3169 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3170 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3171 Diag(OldLocation, diag::note_previous_declaration); 3172 return true; 3173 } 3174 3175 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3176 RequiresAdjustment = true; 3177 } 3178 3179 if (RequiresAdjustment) { 3180 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3181 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3182 New->setType(QualType(AdjustedType, 0)); 3183 NewQType = Context.getCanonicalType(New->getType()); 3184 NewType = cast<FunctionType>(NewQType); 3185 } 3186 3187 // If this redeclaration makes the function inline, we may need to add it to 3188 // UndefinedButUsed. 3189 if (!Old->isInlined() && New->isInlined() && 3190 !New->hasAttr<GNUInlineAttr>() && 3191 !getLangOpts().GNUInline && 3192 Old->isUsed(false) && 3193 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3194 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3195 SourceLocation())); 3196 3197 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3198 // about it. 3199 if (New->hasAttr<GNUInlineAttr>() && 3200 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3201 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3202 } 3203 3204 // If pass_object_size params don't match up perfectly, this isn't a valid 3205 // redeclaration. 3206 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3207 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3208 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3209 << New->getDeclName(); 3210 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3211 return true; 3212 } 3213 3214 if (getLangOpts().CPlusPlus) { 3215 // C++1z [over.load]p2 3216 // Certain function declarations cannot be overloaded: 3217 // -- Function declarations that differ only in the return type, 3218 // the exception specification, or both cannot be overloaded. 3219 3220 // Check the exception specifications match. This may recompute the type of 3221 // both Old and New if it resolved exception specifications, so grab the 3222 // types again after this. Because this updates the type, we do this before 3223 // any of the other checks below, which may update the "de facto" NewQType 3224 // but do not necessarily update the type of New. 3225 if (CheckEquivalentExceptionSpec(Old, New)) 3226 return true; 3227 OldQType = Context.getCanonicalType(Old->getType()); 3228 NewQType = Context.getCanonicalType(New->getType()); 3229 3230 // Go back to the type source info to compare the declared return types, 3231 // per C++1y [dcl.type.auto]p13: 3232 // Redeclarations or specializations of a function or function template 3233 // with a declared return type that uses a placeholder type shall also 3234 // use that placeholder, not a deduced type. 3235 QualType OldDeclaredReturnType = 3236 (Old->getTypeSourceInfo() 3237 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3238 : OldType)->getReturnType(); 3239 QualType NewDeclaredReturnType = 3240 (New->getTypeSourceInfo() 3241 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3242 : NewType)->getReturnType(); 3243 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3244 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3245 New->isLocalExternDecl())) { 3246 QualType ResQT; 3247 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3248 OldDeclaredReturnType->isObjCObjectPointerType()) 3249 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3250 if (ResQT.isNull()) { 3251 if (New->isCXXClassMember() && New->isOutOfLine()) 3252 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3253 << New << New->getReturnTypeSourceRange(); 3254 else 3255 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3256 << New->getReturnTypeSourceRange(); 3257 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3258 << Old->getReturnTypeSourceRange(); 3259 return true; 3260 } 3261 else 3262 NewQType = ResQT; 3263 } 3264 3265 QualType OldReturnType = OldType->getReturnType(); 3266 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3267 if (OldReturnType != NewReturnType) { 3268 // If this function has a deduced return type and has already been 3269 // defined, copy the deduced value from the old declaration. 3270 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3271 if (OldAT && OldAT->isDeduced()) { 3272 New->setType( 3273 SubstAutoType(New->getType(), 3274 OldAT->isDependentType() ? Context.DependentTy 3275 : OldAT->getDeducedType())); 3276 NewQType = Context.getCanonicalType( 3277 SubstAutoType(NewQType, 3278 OldAT->isDependentType() ? Context.DependentTy 3279 : OldAT->getDeducedType())); 3280 } 3281 } 3282 3283 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3284 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3285 if (OldMethod && NewMethod) { 3286 // Preserve triviality. 3287 NewMethod->setTrivial(OldMethod->isTrivial()); 3288 3289 // MSVC allows explicit template specialization at class scope: 3290 // 2 CXXMethodDecls referring to the same function will be injected. 3291 // We don't want a redeclaration error. 3292 bool IsClassScopeExplicitSpecialization = 3293 OldMethod->isFunctionTemplateSpecialization() && 3294 NewMethod->isFunctionTemplateSpecialization(); 3295 bool isFriend = NewMethod->getFriendObjectKind(); 3296 3297 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3298 !IsClassScopeExplicitSpecialization) { 3299 // -- Member function declarations with the same name and the 3300 // same parameter types cannot be overloaded if any of them 3301 // is a static member function declaration. 3302 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3303 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3304 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3305 return true; 3306 } 3307 3308 // C++ [class.mem]p1: 3309 // [...] A member shall not be declared twice in the 3310 // member-specification, except that a nested class or member 3311 // class template can be declared and then later defined. 3312 if (!inTemplateInstantiation()) { 3313 unsigned NewDiag; 3314 if (isa<CXXConstructorDecl>(OldMethod)) 3315 NewDiag = diag::err_constructor_redeclared; 3316 else if (isa<CXXDestructorDecl>(NewMethod)) 3317 NewDiag = diag::err_destructor_redeclared; 3318 else if (isa<CXXConversionDecl>(NewMethod)) 3319 NewDiag = diag::err_conv_function_redeclared; 3320 else 3321 NewDiag = diag::err_member_redeclared; 3322 3323 Diag(New->getLocation(), NewDiag); 3324 } else { 3325 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3326 << New << New->getType(); 3327 } 3328 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3329 return true; 3330 3331 // Complain if this is an explicit declaration of a special 3332 // member that was initially declared implicitly. 3333 // 3334 // As an exception, it's okay to befriend such methods in order 3335 // to permit the implicit constructor/destructor/operator calls. 3336 } else if (OldMethod->isImplicit()) { 3337 if (isFriend) { 3338 NewMethod->setImplicit(); 3339 } else { 3340 Diag(NewMethod->getLocation(), 3341 diag::err_definition_of_implicitly_declared_member) 3342 << New << getSpecialMember(OldMethod); 3343 return true; 3344 } 3345 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3346 Diag(NewMethod->getLocation(), 3347 diag::err_definition_of_explicitly_defaulted_member) 3348 << getSpecialMember(OldMethod); 3349 return true; 3350 } 3351 } 3352 3353 // C++11 [dcl.attr.noreturn]p1: 3354 // The first declaration of a function shall specify the noreturn 3355 // attribute if any declaration of that function specifies the noreturn 3356 // attribute. 3357 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3358 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3359 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3360 Diag(Old->getFirstDecl()->getLocation(), 3361 diag::note_noreturn_missing_first_decl); 3362 } 3363 3364 // C++11 [dcl.attr.depend]p2: 3365 // The first declaration of a function shall specify the 3366 // carries_dependency attribute for its declarator-id if any declaration 3367 // of the function specifies the carries_dependency attribute. 3368 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3369 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3370 Diag(CDA->getLocation(), 3371 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3372 Diag(Old->getFirstDecl()->getLocation(), 3373 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3374 } 3375 3376 // (C++98 8.3.5p3): 3377 // All declarations for a function shall agree exactly in both the 3378 // return type and the parameter-type-list. 3379 // We also want to respect all the extended bits except noreturn. 3380 3381 // noreturn should now match unless the old type info didn't have it. 3382 QualType OldQTypeForComparison = OldQType; 3383 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3384 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3385 const FunctionType *OldTypeForComparison 3386 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3387 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3388 assert(OldQTypeForComparison.isCanonical()); 3389 } 3390 3391 if (haveIncompatibleLanguageLinkages(Old, New)) { 3392 // As a special case, retain the language linkage from previous 3393 // declarations of a friend function as an extension. 3394 // 3395 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3396 // and is useful because there's otherwise no way to specify language 3397 // linkage within class scope. 3398 // 3399 // Check cautiously as the friend object kind isn't yet complete. 3400 if (New->getFriendObjectKind() != Decl::FOK_None) { 3401 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3402 Diag(OldLocation, PrevDiag); 3403 } else { 3404 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3405 Diag(OldLocation, PrevDiag); 3406 return true; 3407 } 3408 } 3409 3410 if (OldQTypeForComparison == NewQType) 3411 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3412 3413 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3414 New->isLocalExternDecl()) { 3415 // It's OK if we couldn't merge types for a local function declaraton 3416 // if either the old or new type is dependent. We'll merge the types 3417 // when we instantiate the function. 3418 return false; 3419 } 3420 3421 // Fall through for conflicting redeclarations and redefinitions. 3422 } 3423 3424 // C: Function types need to be compatible, not identical. This handles 3425 // duplicate function decls like "void f(int); void f(enum X);" properly. 3426 if (!getLangOpts().CPlusPlus && 3427 Context.typesAreCompatible(OldQType, NewQType)) { 3428 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3429 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3430 const FunctionProtoType *OldProto = nullptr; 3431 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3432 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3433 // The old declaration provided a function prototype, but the 3434 // new declaration does not. Merge in the prototype. 3435 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3436 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3437 NewQType = 3438 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3439 OldProto->getExtProtoInfo()); 3440 New->setType(NewQType); 3441 New->setHasInheritedPrototype(); 3442 3443 // Synthesize parameters with the same types. 3444 SmallVector<ParmVarDecl*, 16> Params; 3445 for (const auto &ParamType : OldProto->param_types()) { 3446 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3447 SourceLocation(), nullptr, 3448 ParamType, /*TInfo=*/nullptr, 3449 SC_None, nullptr); 3450 Param->setScopeInfo(0, Params.size()); 3451 Param->setImplicit(); 3452 Params.push_back(Param); 3453 } 3454 3455 New->setParams(Params); 3456 } 3457 3458 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3459 } 3460 3461 // GNU C permits a K&R definition to follow a prototype declaration 3462 // if the declared types of the parameters in the K&R definition 3463 // match the types in the prototype declaration, even when the 3464 // promoted types of the parameters from the K&R definition differ 3465 // from the types in the prototype. GCC then keeps the types from 3466 // the prototype. 3467 // 3468 // If a variadic prototype is followed by a non-variadic K&R definition, 3469 // the K&R definition becomes variadic. This is sort of an edge case, but 3470 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3471 // C99 6.9.1p8. 3472 if (!getLangOpts().CPlusPlus && 3473 Old->hasPrototype() && !New->hasPrototype() && 3474 New->getType()->getAs<FunctionProtoType>() && 3475 Old->getNumParams() == New->getNumParams()) { 3476 SmallVector<QualType, 16> ArgTypes; 3477 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3478 const FunctionProtoType *OldProto 3479 = Old->getType()->getAs<FunctionProtoType>(); 3480 const FunctionProtoType *NewProto 3481 = New->getType()->getAs<FunctionProtoType>(); 3482 3483 // Determine whether this is the GNU C extension. 3484 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3485 NewProto->getReturnType()); 3486 bool LooseCompatible = !MergedReturn.isNull(); 3487 for (unsigned Idx = 0, End = Old->getNumParams(); 3488 LooseCompatible && Idx != End; ++Idx) { 3489 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3490 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3491 if (Context.typesAreCompatible(OldParm->getType(), 3492 NewProto->getParamType(Idx))) { 3493 ArgTypes.push_back(NewParm->getType()); 3494 } else if (Context.typesAreCompatible(OldParm->getType(), 3495 NewParm->getType(), 3496 /*CompareUnqualified=*/true)) { 3497 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3498 NewProto->getParamType(Idx) }; 3499 Warnings.push_back(Warn); 3500 ArgTypes.push_back(NewParm->getType()); 3501 } else 3502 LooseCompatible = false; 3503 } 3504 3505 if (LooseCompatible) { 3506 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3507 Diag(Warnings[Warn].NewParm->getLocation(), 3508 diag::ext_param_promoted_not_compatible_with_prototype) 3509 << Warnings[Warn].PromotedType 3510 << Warnings[Warn].OldParm->getType(); 3511 if (Warnings[Warn].OldParm->getLocation().isValid()) 3512 Diag(Warnings[Warn].OldParm->getLocation(), 3513 diag::note_previous_declaration); 3514 } 3515 3516 if (MergeTypeWithOld) 3517 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3518 OldProto->getExtProtoInfo())); 3519 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3520 } 3521 3522 // Fall through to diagnose conflicting types. 3523 } 3524 3525 // A function that has already been declared has been redeclared or 3526 // defined with a different type; show an appropriate diagnostic. 3527 3528 // If the previous declaration was an implicitly-generated builtin 3529 // declaration, then at the very least we should use a specialized note. 3530 unsigned BuiltinID; 3531 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3532 // If it's actually a library-defined builtin function like 'malloc' 3533 // or 'printf', just warn about the incompatible redeclaration. 3534 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3535 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3536 Diag(OldLocation, diag::note_previous_builtin_declaration) 3537 << Old << Old->getType(); 3538 3539 // If this is a global redeclaration, just forget hereafter 3540 // about the "builtin-ness" of the function. 3541 // 3542 // Doing this for local extern declarations is problematic. If 3543 // the builtin declaration remains visible, a second invalid 3544 // local declaration will produce a hard error; if it doesn't 3545 // remain visible, a single bogus local redeclaration (which is 3546 // actually only a warning) could break all the downstream code. 3547 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3548 New->getIdentifier()->revertBuiltin(); 3549 3550 return false; 3551 } 3552 3553 PrevDiag = diag::note_previous_builtin_declaration; 3554 } 3555 3556 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3557 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3558 return true; 3559 } 3560 3561 /// \brief Completes the merge of two function declarations that are 3562 /// known to be compatible. 3563 /// 3564 /// This routine handles the merging of attributes and other 3565 /// properties of function declarations from the old declaration to 3566 /// the new declaration, once we know that New is in fact a 3567 /// redeclaration of Old. 3568 /// 3569 /// \returns false 3570 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3571 Scope *S, bool MergeTypeWithOld) { 3572 // Merge the attributes 3573 mergeDeclAttributes(New, Old); 3574 3575 // Merge "pure" flag. 3576 if (Old->isPure()) 3577 New->setPure(); 3578 3579 // Merge "used" flag. 3580 if (Old->getMostRecentDecl()->isUsed(false)) 3581 New->setIsUsed(); 3582 3583 // Merge attributes from the parameters. These can mismatch with K&R 3584 // declarations. 3585 if (New->getNumParams() == Old->getNumParams()) 3586 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3587 ParmVarDecl *NewParam = New->getParamDecl(i); 3588 ParmVarDecl *OldParam = Old->getParamDecl(i); 3589 mergeParamDeclAttributes(NewParam, OldParam, *this); 3590 mergeParamDeclTypes(NewParam, OldParam, *this); 3591 } 3592 3593 if (getLangOpts().CPlusPlus) 3594 return MergeCXXFunctionDecl(New, Old, S); 3595 3596 // Merge the function types so the we get the composite types for the return 3597 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3598 // was visible. 3599 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3600 if (!Merged.isNull() && MergeTypeWithOld) 3601 New->setType(Merged); 3602 3603 return false; 3604 } 3605 3606 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3607 ObjCMethodDecl *oldMethod) { 3608 // Merge the attributes, including deprecated/unavailable 3609 AvailabilityMergeKind MergeKind = 3610 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3611 ? AMK_ProtocolImplementation 3612 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3613 : AMK_Override; 3614 3615 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3616 3617 // Merge attributes from the parameters. 3618 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3619 oe = oldMethod->param_end(); 3620 for (ObjCMethodDecl::param_iterator 3621 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3622 ni != ne && oi != oe; ++ni, ++oi) 3623 mergeParamDeclAttributes(*ni, *oi, *this); 3624 3625 CheckObjCMethodOverride(newMethod, oldMethod); 3626 } 3627 3628 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3629 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3630 3631 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3632 ? diag::err_redefinition_different_type 3633 : diag::err_redeclaration_different_type) 3634 << New->getDeclName() << New->getType() << Old->getType(); 3635 3636 diag::kind PrevDiag; 3637 SourceLocation OldLocation; 3638 std::tie(PrevDiag, OldLocation) 3639 = getNoteDiagForInvalidRedeclaration(Old, New); 3640 S.Diag(OldLocation, PrevDiag); 3641 New->setInvalidDecl(); 3642 } 3643 3644 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3645 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3646 /// emitting diagnostics as appropriate. 3647 /// 3648 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3649 /// to here in AddInitializerToDecl. We can't check them before the initializer 3650 /// is attached. 3651 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3652 bool MergeTypeWithOld) { 3653 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3654 return; 3655 3656 QualType MergedT; 3657 if (getLangOpts().CPlusPlus) { 3658 if (New->getType()->isUndeducedType()) { 3659 // We don't know what the new type is until the initializer is attached. 3660 return; 3661 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3662 // These could still be something that needs exception specs checked. 3663 return MergeVarDeclExceptionSpecs(New, Old); 3664 } 3665 // C++ [basic.link]p10: 3666 // [...] the types specified by all declarations referring to a given 3667 // object or function shall be identical, except that declarations for an 3668 // array object can specify array types that differ by the presence or 3669 // absence of a major array bound (8.3.4). 3670 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3671 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3672 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3673 3674 // We are merging a variable declaration New into Old. If it has an array 3675 // bound, and that bound differs from Old's bound, we should diagnose the 3676 // mismatch. 3677 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3678 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3679 PrevVD = PrevVD->getPreviousDecl()) { 3680 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3681 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3682 continue; 3683 3684 if (!Context.hasSameType(NewArray, PrevVDTy)) 3685 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3686 } 3687 } 3688 3689 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3690 if (Context.hasSameType(OldArray->getElementType(), 3691 NewArray->getElementType())) 3692 MergedT = New->getType(); 3693 } 3694 // FIXME: Check visibility. New is hidden but has a complete type. If New 3695 // has no array bound, it should not inherit one from Old, if Old is not 3696 // visible. 3697 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3698 if (Context.hasSameType(OldArray->getElementType(), 3699 NewArray->getElementType())) 3700 MergedT = Old->getType(); 3701 } 3702 } 3703 else if (New->getType()->isObjCObjectPointerType() && 3704 Old->getType()->isObjCObjectPointerType()) { 3705 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3706 Old->getType()); 3707 } 3708 } else { 3709 // C 6.2.7p2: 3710 // All declarations that refer to the same object or function shall have 3711 // compatible type. 3712 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3713 } 3714 if (MergedT.isNull()) { 3715 // It's OK if we couldn't merge types if either type is dependent, for a 3716 // block-scope variable. In other cases (static data members of class 3717 // templates, variable templates, ...), we require the types to be 3718 // equivalent. 3719 // FIXME: The C++ standard doesn't say anything about this. 3720 if ((New->getType()->isDependentType() || 3721 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3722 // If the old type was dependent, we can't merge with it, so the new type 3723 // becomes dependent for now. We'll reproduce the original type when we 3724 // instantiate the TypeSourceInfo for the variable. 3725 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3726 New->setType(Context.DependentTy); 3727 return; 3728 } 3729 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3730 } 3731 3732 // Don't actually update the type on the new declaration if the old 3733 // declaration was an extern declaration in a different scope. 3734 if (MergeTypeWithOld) 3735 New->setType(MergedT); 3736 } 3737 3738 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3739 LookupResult &Previous) { 3740 // C11 6.2.7p4: 3741 // For an identifier with internal or external linkage declared 3742 // in a scope in which a prior declaration of that identifier is 3743 // visible, if the prior declaration specifies internal or 3744 // external linkage, the type of the identifier at the later 3745 // declaration becomes the composite type. 3746 // 3747 // If the variable isn't visible, we do not merge with its type. 3748 if (Previous.isShadowed()) 3749 return false; 3750 3751 if (S.getLangOpts().CPlusPlus) { 3752 // C++11 [dcl.array]p3: 3753 // If there is a preceding declaration of the entity in the same 3754 // scope in which the bound was specified, an omitted array bound 3755 // is taken to be the same as in that earlier declaration. 3756 return NewVD->isPreviousDeclInSameBlockScope() || 3757 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3758 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3759 } else { 3760 // If the old declaration was function-local, don't merge with its 3761 // type unless we're in the same function. 3762 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3763 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3764 } 3765 } 3766 3767 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3768 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3769 /// situation, merging decls or emitting diagnostics as appropriate. 3770 /// 3771 /// Tentative definition rules (C99 6.9.2p2) are checked by 3772 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3773 /// definitions here, since the initializer hasn't been attached. 3774 /// 3775 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3776 // If the new decl is already invalid, don't do any other checking. 3777 if (New->isInvalidDecl()) 3778 return; 3779 3780 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3781 return; 3782 3783 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3784 3785 // Verify the old decl was also a variable or variable template. 3786 VarDecl *Old = nullptr; 3787 VarTemplateDecl *OldTemplate = nullptr; 3788 if (Previous.isSingleResult()) { 3789 if (NewTemplate) { 3790 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3791 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3792 3793 if (auto *Shadow = 3794 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3795 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3796 return New->setInvalidDecl(); 3797 } else { 3798 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3799 3800 if (auto *Shadow = 3801 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3802 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3803 return New->setInvalidDecl(); 3804 } 3805 } 3806 if (!Old) { 3807 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3808 << New->getDeclName(); 3809 notePreviousDefinition(Previous.getRepresentativeDecl(), 3810 New->getLocation()); 3811 return New->setInvalidDecl(); 3812 } 3813 3814 // Ensure the template parameters are compatible. 3815 if (NewTemplate && 3816 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3817 OldTemplate->getTemplateParameters(), 3818 /*Complain=*/true, TPL_TemplateMatch)) 3819 return New->setInvalidDecl(); 3820 3821 // C++ [class.mem]p1: 3822 // A member shall not be declared twice in the member-specification [...] 3823 // 3824 // Here, we need only consider static data members. 3825 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3826 Diag(New->getLocation(), diag::err_duplicate_member) 3827 << New->getIdentifier(); 3828 Diag(Old->getLocation(), diag::note_previous_declaration); 3829 New->setInvalidDecl(); 3830 } 3831 3832 mergeDeclAttributes(New, Old); 3833 // Warn if an already-declared variable is made a weak_import in a subsequent 3834 // declaration 3835 if (New->hasAttr<WeakImportAttr>() && 3836 Old->getStorageClass() == SC_None && 3837 !Old->hasAttr<WeakImportAttr>()) { 3838 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3839 notePreviousDefinition(Old, New->getLocation()); 3840 // Remove weak_import attribute on new declaration. 3841 New->dropAttr<WeakImportAttr>(); 3842 } 3843 3844 if (New->hasAttr<InternalLinkageAttr>() && 3845 !Old->hasAttr<InternalLinkageAttr>()) { 3846 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3847 << New->getDeclName(); 3848 notePreviousDefinition(Old, New->getLocation()); 3849 New->dropAttr<InternalLinkageAttr>(); 3850 } 3851 3852 // Merge the types. 3853 VarDecl *MostRecent = Old->getMostRecentDecl(); 3854 if (MostRecent != Old) { 3855 MergeVarDeclTypes(New, MostRecent, 3856 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3857 if (New->isInvalidDecl()) 3858 return; 3859 } 3860 3861 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3862 if (New->isInvalidDecl()) 3863 return; 3864 3865 diag::kind PrevDiag; 3866 SourceLocation OldLocation; 3867 std::tie(PrevDiag, OldLocation) = 3868 getNoteDiagForInvalidRedeclaration(Old, New); 3869 3870 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3871 if (New->getStorageClass() == SC_Static && 3872 !New->isStaticDataMember() && 3873 Old->hasExternalFormalLinkage()) { 3874 if (getLangOpts().MicrosoftExt) { 3875 Diag(New->getLocation(), diag::ext_static_non_static) 3876 << New->getDeclName(); 3877 Diag(OldLocation, PrevDiag); 3878 } else { 3879 Diag(New->getLocation(), diag::err_static_non_static) 3880 << New->getDeclName(); 3881 Diag(OldLocation, PrevDiag); 3882 return New->setInvalidDecl(); 3883 } 3884 } 3885 // C99 6.2.2p4: 3886 // For an identifier declared with the storage-class specifier 3887 // extern in a scope in which a prior declaration of that 3888 // identifier is visible,23) if the prior declaration specifies 3889 // internal or external linkage, the linkage of the identifier at 3890 // the later declaration is the same as the linkage specified at 3891 // the prior declaration. If no prior declaration is visible, or 3892 // if the prior declaration specifies no linkage, then the 3893 // identifier has external linkage. 3894 if (New->hasExternalStorage() && Old->hasLinkage()) 3895 /* Okay */; 3896 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3897 !New->isStaticDataMember() && 3898 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3899 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3900 Diag(OldLocation, PrevDiag); 3901 return New->setInvalidDecl(); 3902 } 3903 3904 // Check if extern is followed by non-extern and vice-versa. 3905 if (New->hasExternalStorage() && 3906 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3907 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3908 Diag(OldLocation, PrevDiag); 3909 return New->setInvalidDecl(); 3910 } 3911 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3912 !New->hasExternalStorage()) { 3913 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3914 Diag(OldLocation, PrevDiag); 3915 return New->setInvalidDecl(); 3916 } 3917 3918 if (CheckRedeclarationModuleOwnership(New, Old)) 3919 return; 3920 3921 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3922 3923 // FIXME: The test for external storage here seems wrong? We still 3924 // need to check for mismatches. 3925 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3926 // Don't complain about out-of-line definitions of static members. 3927 !(Old->getLexicalDeclContext()->isRecord() && 3928 !New->getLexicalDeclContext()->isRecord())) { 3929 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3930 Diag(OldLocation, PrevDiag); 3931 return New->setInvalidDecl(); 3932 } 3933 3934 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3935 if (VarDecl *Def = Old->getDefinition()) { 3936 // C++1z [dcl.fcn.spec]p4: 3937 // If the definition of a variable appears in a translation unit before 3938 // its first declaration as inline, the program is ill-formed. 3939 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3940 Diag(Def->getLocation(), diag::note_previous_definition); 3941 } 3942 } 3943 3944 // If this redeclaration makes the variable inline, we may need to add it to 3945 // UndefinedButUsed. 3946 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3947 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3948 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3949 SourceLocation())); 3950 3951 if (New->getTLSKind() != Old->getTLSKind()) { 3952 if (!Old->getTLSKind()) { 3953 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3954 Diag(OldLocation, PrevDiag); 3955 } else if (!New->getTLSKind()) { 3956 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3957 Diag(OldLocation, PrevDiag); 3958 } else { 3959 // Do not allow redeclaration to change the variable between requiring 3960 // static and dynamic initialization. 3961 // FIXME: GCC allows this, but uses the TLS keyword on the first 3962 // declaration to determine the kind. Do we need to be compatible here? 3963 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3964 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3965 Diag(OldLocation, PrevDiag); 3966 } 3967 } 3968 3969 // C++ doesn't have tentative definitions, so go right ahead and check here. 3970 if (getLangOpts().CPlusPlus && 3971 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3972 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3973 Old->getCanonicalDecl()->isConstexpr()) { 3974 // This definition won't be a definition any more once it's been merged. 3975 Diag(New->getLocation(), 3976 diag::warn_deprecated_redundant_constexpr_static_def); 3977 } else if (VarDecl *Def = Old->getDefinition()) { 3978 if (checkVarDeclRedefinition(Def, New)) 3979 return; 3980 } 3981 } 3982 3983 if (haveIncompatibleLanguageLinkages(Old, New)) { 3984 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3985 Diag(OldLocation, PrevDiag); 3986 New->setInvalidDecl(); 3987 return; 3988 } 3989 3990 // Merge "used" flag. 3991 if (Old->getMostRecentDecl()->isUsed(false)) 3992 New->setIsUsed(); 3993 3994 // Keep a chain of previous declarations. 3995 New->setPreviousDecl(Old); 3996 if (NewTemplate) 3997 NewTemplate->setPreviousDecl(OldTemplate); 3998 adjustDeclContextForDeclaratorDecl(New, Old); 3999 4000 // Inherit access appropriately. 4001 New->setAccess(Old->getAccess()); 4002 if (NewTemplate) 4003 NewTemplate->setAccess(New->getAccess()); 4004 4005 if (Old->isInline()) 4006 New->setImplicitlyInline(); 4007 } 4008 4009 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4010 SourceManager &SrcMgr = getSourceManager(); 4011 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4012 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4013 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4014 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4015 auto &HSI = PP.getHeaderSearchInfo(); 4016 StringRef HdrFilename = 4017 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4018 4019 auto noteFromModuleOrInclude = [&](Module *Mod, 4020 SourceLocation IncLoc) -> bool { 4021 // Redefinition errors with modules are common with non modular mapped 4022 // headers, example: a non-modular header H in module A that also gets 4023 // included directly in a TU. Pointing twice to the same header/definition 4024 // is confusing, try to get better diagnostics when modules is on. 4025 if (IncLoc.isValid()) { 4026 if (Mod) { 4027 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4028 << HdrFilename.str() << Mod->getFullModuleName(); 4029 if (!Mod->DefinitionLoc.isInvalid()) 4030 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4031 << Mod->getFullModuleName(); 4032 } else { 4033 Diag(IncLoc, diag::note_redefinition_include_same_file) 4034 << HdrFilename.str(); 4035 } 4036 return true; 4037 } 4038 4039 return false; 4040 }; 4041 4042 // Is it the same file and same offset? Provide more information on why 4043 // this leads to a redefinition error. 4044 bool EmittedDiag = false; 4045 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4046 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4047 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4048 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4049 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4050 4051 // If the header has no guards, emit a note suggesting one. 4052 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4053 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4054 4055 if (EmittedDiag) 4056 return; 4057 } 4058 4059 // Redefinition coming from different files or couldn't do better above. 4060 if (Old->getLocation().isValid()) 4061 Diag(Old->getLocation(), diag::note_previous_definition); 4062 } 4063 4064 /// We've just determined that \p Old and \p New both appear to be definitions 4065 /// of the same variable. Either diagnose or fix the problem. 4066 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4067 if (!hasVisibleDefinition(Old) && 4068 (New->getFormalLinkage() == InternalLinkage || 4069 New->isInline() || 4070 New->getDescribedVarTemplate() || 4071 New->getNumTemplateParameterLists() || 4072 New->getDeclContext()->isDependentContext())) { 4073 // The previous definition is hidden, and multiple definitions are 4074 // permitted (in separate TUs). Demote this to a declaration. 4075 New->demoteThisDefinitionToDeclaration(); 4076 4077 // Make the canonical definition visible. 4078 if (auto *OldTD = Old->getDescribedVarTemplate()) 4079 makeMergedDefinitionVisible(OldTD); 4080 makeMergedDefinitionVisible(Old); 4081 return false; 4082 } else { 4083 Diag(New->getLocation(), diag::err_redefinition) << New; 4084 notePreviousDefinition(Old, New->getLocation()); 4085 New->setInvalidDecl(); 4086 return true; 4087 } 4088 } 4089 4090 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4091 /// no declarator (e.g. "struct foo;") is parsed. 4092 Decl * 4093 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4094 RecordDecl *&AnonRecord) { 4095 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4096 AnonRecord); 4097 } 4098 4099 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4100 // disambiguate entities defined in different scopes. 4101 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4102 // compatibility. 4103 // We will pick our mangling number depending on which version of MSVC is being 4104 // targeted. 4105 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4106 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4107 ? S->getMSCurManglingNumber() 4108 : S->getMSLastManglingNumber(); 4109 } 4110 4111 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4112 if (!Context.getLangOpts().CPlusPlus) 4113 return; 4114 4115 if (isa<CXXRecordDecl>(Tag->getParent())) { 4116 // If this tag is the direct child of a class, number it if 4117 // it is anonymous. 4118 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4119 return; 4120 MangleNumberingContext &MCtx = 4121 Context.getManglingNumberContext(Tag->getParent()); 4122 Context.setManglingNumber( 4123 Tag, MCtx.getManglingNumber( 4124 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4125 return; 4126 } 4127 4128 // If this tag isn't a direct child of a class, number it if it is local. 4129 Decl *ManglingContextDecl; 4130 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4131 Tag->getDeclContext(), ManglingContextDecl)) { 4132 Context.setManglingNumber( 4133 Tag, MCtx->getManglingNumber( 4134 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4135 } 4136 } 4137 4138 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4139 TypedefNameDecl *NewTD) { 4140 if (TagFromDeclSpec->isInvalidDecl()) 4141 return; 4142 4143 // Do nothing if the tag already has a name for linkage purposes. 4144 if (TagFromDeclSpec->hasNameForLinkage()) 4145 return; 4146 4147 // A well-formed anonymous tag must always be a TUK_Definition. 4148 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4149 4150 // The type must match the tag exactly; no qualifiers allowed. 4151 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4152 Context.getTagDeclType(TagFromDeclSpec))) { 4153 if (getLangOpts().CPlusPlus) 4154 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4155 return; 4156 } 4157 4158 // If we've already computed linkage for the anonymous tag, then 4159 // adding a typedef name for the anonymous decl can change that 4160 // linkage, which might be a serious problem. Diagnose this as 4161 // unsupported and ignore the typedef name. TODO: we should 4162 // pursue this as a language defect and establish a formal rule 4163 // for how to handle it. 4164 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4165 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4166 4167 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4168 tagLoc = getLocForEndOfToken(tagLoc); 4169 4170 llvm::SmallString<40> textToInsert; 4171 textToInsert += ' '; 4172 textToInsert += NewTD->getIdentifier()->getName(); 4173 Diag(tagLoc, diag::note_typedef_changes_linkage) 4174 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4175 return; 4176 } 4177 4178 // Otherwise, set this is the anon-decl typedef for the tag. 4179 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4180 } 4181 4182 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4183 switch (T) { 4184 case DeclSpec::TST_class: 4185 return 0; 4186 case DeclSpec::TST_struct: 4187 return 1; 4188 case DeclSpec::TST_interface: 4189 return 2; 4190 case DeclSpec::TST_union: 4191 return 3; 4192 case DeclSpec::TST_enum: 4193 return 4; 4194 default: 4195 llvm_unreachable("unexpected type specifier"); 4196 } 4197 } 4198 4199 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4200 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4201 /// parameters to cope with template friend declarations. 4202 Decl * 4203 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4204 MultiTemplateParamsArg TemplateParams, 4205 bool IsExplicitInstantiation, 4206 RecordDecl *&AnonRecord) { 4207 Decl *TagD = nullptr; 4208 TagDecl *Tag = nullptr; 4209 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4210 DS.getTypeSpecType() == DeclSpec::TST_struct || 4211 DS.getTypeSpecType() == DeclSpec::TST_interface || 4212 DS.getTypeSpecType() == DeclSpec::TST_union || 4213 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4214 TagD = DS.getRepAsDecl(); 4215 4216 if (!TagD) // We probably had an error 4217 return nullptr; 4218 4219 // Note that the above type specs guarantee that the 4220 // type rep is a Decl, whereas in many of the others 4221 // it's a Type. 4222 if (isa<TagDecl>(TagD)) 4223 Tag = cast<TagDecl>(TagD); 4224 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4225 Tag = CTD->getTemplatedDecl(); 4226 } 4227 4228 if (Tag) { 4229 handleTagNumbering(Tag, S); 4230 Tag->setFreeStanding(); 4231 if (Tag->isInvalidDecl()) 4232 return Tag; 4233 } 4234 4235 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4236 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4237 // or incomplete types shall not be restrict-qualified." 4238 if (TypeQuals & DeclSpec::TQ_restrict) 4239 Diag(DS.getRestrictSpecLoc(), 4240 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4241 << DS.getSourceRange(); 4242 } 4243 4244 if (DS.isInlineSpecified()) 4245 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4246 << getLangOpts().CPlusPlus17; 4247 4248 if (DS.isConstexprSpecified()) { 4249 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4250 // and definitions of functions and variables. 4251 if (Tag) 4252 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4253 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4254 else 4255 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4256 // Don't emit warnings after this error. 4257 return TagD; 4258 } 4259 4260 DiagnoseFunctionSpecifiers(DS); 4261 4262 if (DS.isFriendSpecified()) { 4263 // If we're dealing with a decl but not a TagDecl, assume that 4264 // whatever routines created it handled the friendship aspect. 4265 if (TagD && !Tag) 4266 return nullptr; 4267 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4268 } 4269 4270 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4271 bool IsExplicitSpecialization = 4272 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4273 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4274 !IsExplicitInstantiation && !IsExplicitSpecialization && 4275 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4276 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4277 // nested-name-specifier unless it is an explicit instantiation 4278 // or an explicit specialization. 4279 // 4280 // FIXME: We allow class template partial specializations here too, per the 4281 // obvious intent of DR1819. 4282 // 4283 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4284 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4285 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4286 return nullptr; 4287 } 4288 4289 // Track whether this decl-specifier declares anything. 4290 bool DeclaresAnything = true; 4291 4292 // Handle anonymous struct definitions. 4293 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4294 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4295 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4296 if (getLangOpts().CPlusPlus || 4297 Record->getDeclContext()->isRecord()) { 4298 // If CurContext is a DeclContext that can contain statements, 4299 // RecursiveASTVisitor won't visit the decls that 4300 // BuildAnonymousStructOrUnion() will put into CurContext. 4301 // Also store them here so that they can be part of the 4302 // DeclStmt that gets created in this case. 4303 // FIXME: Also return the IndirectFieldDecls created by 4304 // BuildAnonymousStructOr union, for the same reason? 4305 if (CurContext->isFunctionOrMethod()) 4306 AnonRecord = Record; 4307 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4308 Context.getPrintingPolicy()); 4309 } 4310 4311 DeclaresAnything = false; 4312 } 4313 } 4314 4315 // C11 6.7.2.1p2: 4316 // A struct-declaration that does not declare an anonymous structure or 4317 // anonymous union shall contain a struct-declarator-list. 4318 // 4319 // This rule also existed in C89 and C99; the grammar for struct-declaration 4320 // did not permit a struct-declaration without a struct-declarator-list. 4321 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4322 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4323 // Check for Microsoft C extension: anonymous struct/union member. 4324 // Handle 2 kinds of anonymous struct/union: 4325 // struct STRUCT; 4326 // union UNION; 4327 // and 4328 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4329 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4330 if ((Tag && Tag->getDeclName()) || 4331 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4332 RecordDecl *Record = nullptr; 4333 if (Tag) 4334 Record = dyn_cast<RecordDecl>(Tag); 4335 else if (const RecordType *RT = 4336 DS.getRepAsType().get()->getAsStructureType()) 4337 Record = RT->getDecl(); 4338 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4339 Record = UT->getDecl(); 4340 4341 if (Record && getLangOpts().MicrosoftExt) { 4342 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4343 << Record->isUnion() << DS.getSourceRange(); 4344 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4345 } 4346 4347 DeclaresAnything = false; 4348 } 4349 } 4350 4351 // Skip all the checks below if we have a type error. 4352 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4353 (TagD && TagD->isInvalidDecl())) 4354 return TagD; 4355 4356 if (getLangOpts().CPlusPlus && 4357 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4358 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4359 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4360 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4361 DeclaresAnything = false; 4362 4363 if (!DS.isMissingDeclaratorOk()) { 4364 // Customize diagnostic for a typedef missing a name. 4365 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4366 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4367 << DS.getSourceRange(); 4368 else 4369 DeclaresAnything = false; 4370 } 4371 4372 if (DS.isModulePrivateSpecified() && 4373 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4374 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4375 << Tag->getTagKind() 4376 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4377 4378 ActOnDocumentableDecl(TagD); 4379 4380 // C 6.7/2: 4381 // A declaration [...] shall declare at least a declarator [...], a tag, 4382 // or the members of an enumeration. 4383 // C++ [dcl.dcl]p3: 4384 // [If there are no declarators], and except for the declaration of an 4385 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4386 // names into the program, or shall redeclare a name introduced by a 4387 // previous declaration. 4388 if (!DeclaresAnything) { 4389 // In C, we allow this as a (popular) extension / bug. Don't bother 4390 // producing further diagnostics for redundant qualifiers after this. 4391 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4392 return TagD; 4393 } 4394 4395 // C++ [dcl.stc]p1: 4396 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4397 // init-declarator-list of the declaration shall not be empty. 4398 // C++ [dcl.fct.spec]p1: 4399 // If a cv-qualifier appears in a decl-specifier-seq, the 4400 // init-declarator-list of the declaration shall not be empty. 4401 // 4402 // Spurious qualifiers here appear to be valid in C. 4403 unsigned DiagID = diag::warn_standalone_specifier; 4404 if (getLangOpts().CPlusPlus) 4405 DiagID = diag::ext_standalone_specifier; 4406 4407 // Note that a linkage-specification sets a storage class, but 4408 // 'extern "C" struct foo;' is actually valid and not theoretically 4409 // useless. 4410 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4411 if (SCS == DeclSpec::SCS_mutable) 4412 // Since mutable is not a viable storage class specifier in C, there is 4413 // no reason to treat it as an extension. Instead, diagnose as an error. 4414 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4415 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4416 Diag(DS.getStorageClassSpecLoc(), DiagID) 4417 << DeclSpec::getSpecifierName(SCS); 4418 } 4419 4420 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4421 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4422 << DeclSpec::getSpecifierName(TSCS); 4423 if (DS.getTypeQualifiers()) { 4424 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4425 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4426 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4427 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4428 // Restrict is covered above. 4429 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4430 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4431 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4432 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4433 } 4434 4435 // Warn about ignored type attributes, for example: 4436 // __attribute__((aligned)) struct A; 4437 // Attributes should be placed after tag to apply to type declaration. 4438 if (!DS.getAttributes().empty()) { 4439 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4440 if (TypeSpecType == DeclSpec::TST_class || 4441 TypeSpecType == DeclSpec::TST_struct || 4442 TypeSpecType == DeclSpec::TST_interface || 4443 TypeSpecType == DeclSpec::TST_union || 4444 TypeSpecType == DeclSpec::TST_enum) { 4445 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4446 attrs = attrs->getNext()) 4447 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4448 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4449 } 4450 } 4451 4452 return TagD; 4453 } 4454 4455 /// We are trying to inject an anonymous member into the given scope; 4456 /// check if there's an existing declaration that can't be overloaded. 4457 /// 4458 /// \return true if this is a forbidden redeclaration 4459 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4460 Scope *S, 4461 DeclContext *Owner, 4462 DeclarationName Name, 4463 SourceLocation NameLoc, 4464 bool IsUnion) { 4465 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4466 Sema::ForVisibleRedeclaration); 4467 if (!SemaRef.LookupName(R, S)) return false; 4468 4469 // Pick a representative declaration. 4470 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4471 assert(PrevDecl && "Expected a non-null Decl"); 4472 4473 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4474 return false; 4475 4476 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4477 << IsUnion << Name; 4478 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4479 4480 return true; 4481 } 4482 4483 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4484 /// anonymous struct or union AnonRecord into the owning context Owner 4485 /// and scope S. This routine will be invoked just after we realize 4486 /// that an unnamed union or struct is actually an anonymous union or 4487 /// struct, e.g., 4488 /// 4489 /// @code 4490 /// union { 4491 /// int i; 4492 /// float f; 4493 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4494 /// // f into the surrounding scope.x 4495 /// @endcode 4496 /// 4497 /// This routine is recursive, injecting the names of nested anonymous 4498 /// structs/unions into the owning context and scope as well. 4499 static bool 4500 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4501 RecordDecl *AnonRecord, AccessSpecifier AS, 4502 SmallVectorImpl<NamedDecl *> &Chaining) { 4503 bool Invalid = false; 4504 4505 // Look every FieldDecl and IndirectFieldDecl with a name. 4506 for (auto *D : AnonRecord->decls()) { 4507 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4508 cast<NamedDecl>(D)->getDeclName()) { 4509 ValueDecl *VD = cast<ValueDecl>(D); 4510 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4511 VD->getLocation(), 4512 AnonRecord->isUnion())) { 4513 // C++ [class.union]p2: 4514 // The names of the members of an anonymous union shall be 4515 // distinct from the names of any other entity in the 4516 // scope in which the anonymous union is declared. 4517 Invalid = true; 4518 } else { 4519 // C++ [class.union]p2: 4520 // For the purpose of name lookup, after the anonymous union 4521 // definition, the members of the anonymous union are 4522 // considered to have been defined in the scope in which the 4523 // anonymous union is declared. 4524 unsigned OldChainingSize = Chaining.size(); 4525 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4526 Chaining.append(IF->chain_begin(), IF->chain_end()); 4527 else 4528 Chaining.push_back(VD); 4529 4530 assert(Chaining.size() >= 2); 4531 NamedDecl **NamedChain = 4532 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4533 for (unsigned i = 0; i < Chaining.size(); i++) 4534 NamedChain[i] = Chaining[i]; 4535 4536 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4537 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4538 VD->getType(), {NamedChain, Chaining.size()}); 4539 4540 for (const auto *Attr : VD->attrs()) 4541 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4542 4543 IndirectField->setAccess(AS); 4544 IndirectField->setImplicit(); 4545 SemaRef.PushOnScopeChains(IndirectField, S); 4546 4547 // That includes picking up the appropriate access specifier. 4548 if (AS != AS_none) IndirectField->setAccess(AS); 4549 4550 Chaining.resize(OldChainingSize); 4551 } 4552 } 4553 } 4554 4555 return Invalid; 4556 } 4557 4558 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4559 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4560 /// illegal input values are mapped to SC_None. 4561 static StorageClass 4562 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4563 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4564 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4565 "Parser allowed 'typedef' as storage class VarDecl."); 4566 switch (StorageClassSpec) { 4567 case DeclSpec::SCS_unspecified: return SC_None; 4568 case DeclSpec::SCS_extern: 4569 if (DS.isExternInLinkageSpec()) 4570 return SC_None; 4571 return SC_Extern; 4572 case DeclSpec::SCS_static: return SC_Static; 4573 case DeclSpec::SCS_auto: return SC_Auto; 4574 case DeclSpec::SCS_register: return SC_Register; 4575 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4576 // Illegal SCSs map to None: error reporting is up to the caller. 4577 case DeclSpec::SCS_mutable: // Fall through. 4578 case DeclSpec::SCS_typedef: return SC_None; 4579 } 4580 llvm_unreachable("unknown storage class specifier"); 4581 } 4582 4583 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4584 assert(Record->hasInClassInitializer()); 4585 4586 for (const auto *I : Record->decls()) { 4587 const auto *FD = dyn_cast<FieldDecl>(I); 4588 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4589 FD = IFD->getAnonField(); 4590 if (FD && FD->hasInClassInitializer()) 4591 return FD->getLocation(); 4592 } 4593 4594 llvm_unreachable("couldn't find in-class initializer"); 4595 } 4596 4597 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4598 SourceLocation DefaultInitLoc) { 4599 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4600 return; 4601 4602 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4603 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4604 } 4605 4606 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4607 CXXRecordDecl *AnonUnion) { 4608 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4609 return; 4610 4611 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4612 } 4613 4614 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4615 /// anonymous structure or union. Anonymous unions are a C++ feature 4616 /// (C++ [class.union]) and a C11 feature; anonymous structures 4617 /// are a C11 feature and GNU C++ extension. 4618 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4619 AccessSpecifier AS, 4620 RecordDecl *Record, 4621 const PrintingPolicy &Policy) { 4622 DeclContext *Owner = Record->getDeclContext(); 4623 4624 // Diagnose whether this anonymous struct/union is an extension. 4625 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4626 Diag(Record->getLocation(), diag::ext_anonymous_union); 4627 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4628 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4629 else if (!Record->isUnion() && !getLangOpts().C11) 4630 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4631 4632 // C and C++ require different kinds of checks for anonymous 4633 // structs/unions. 4634 bool Invalid = false; 4635 if (getLangOpts().CPlusPlus) { 4636 const char *PrevSpec = nullptr; 4637 unsigned DiagID; 4638 if (Record->isUnion()) { 4639 // C++ [class.union]p6: 4640 // Anonymous unions declared in a named namespace or in the 4641 // global namespace shall be declared static. 4642 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4643 (isa<TranslationUnitDecl>(Owner) || 4644 (isa<NamespaceDecl>(Owner) && 4645 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4646 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4647 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4648 4649 // Recover by adding 'static'. 4650 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4651 PrevSpec, DiagID, Policy); 4652 } 4653 // C++ [class.union]p6: 4654 // A storage class is not allowed in a declaration of an 4655 // anonymous union in a class scope. 4656 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4657 isa<RecordDecl>(Owner)) { 4658 Diag(DS.getStorageClassSpecLoc(), 4659 diag::err_anonymous_union_with_storage_spec) 4660 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4661 4662 // Recover by removing the storage specifier. 4663 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4664 SourceLocation(), 4665 PrevSpec, DiagID, Context.getPrintingPolicy()); 4666 } 4667 } 4668 4669 // Ignore const/volatile/restrict qualifiers. 4670 if (DS.getTypeQualifiers()) { 4671 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4672 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4673 << Record->isUnion() << "const" 4674 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4675 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4676 Diag(DS.getVolatileSpecLoc(), 4677 diag::ext_anonymous_struct_union_qualified) 4678 << Record->isUnion() << "volatile" 4679 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4680 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4681 Diag(DS.getRestrictSpecLoc(), 4682 diag::ext_anonymous_struct_union_qualified) 4683 << Record->isUnion() << "restrict" 4684 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4685 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4686 Diag(DS.getAtomicSpecLoc(), 4687 diag::ext_anonymous_struct_union_qualified) 4688 << Record->isUnion() << "_Atomic" 4689 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4690 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4691 Diag(DS.getUnalignedSpecLoc(), 4692 diag::ext_anonymous_struct_union_qualified) 4693 << Record->isUnion() << "__unaligned" 4694 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4695 4696 DS.ClearTypeQualifiers(); 4697 } 4698 4699 // C++ [class.union]p2: 4700 // The member-specification of an anonymous union shall only 4701 // define non-static data members. [Note: nested types and 4702 // functions cannot be declared within an anonymous union. ] 4703 for (auto *Mem : Record->decls()) { 4704 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4705 // C++ [class.union]p3: 4706 // An anonymous union shall not have private or protected 4707 // members (clause 11). 4708 assert(FD->getAccess() != AS_none); 4709 if (FD->getAccess() != AS_public) { 4710 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4711 << Record->isUnion() << (FD->getAccess() == AS_protected); 4712 Invalid = true; 4713 } 4714 4715 // C++ [class.union]p1 4716 // An object of a class with a non-trivial constructor, a non-trivial 4717 // copy constructor, a non-trivial destructor, or a non-trivial copy 4718 // assignment operator cannot be a member of a union, nor can an 4719 // array of such objects. 4720 if (CheckNontrivialField(FD)) 4721 Invalid = true; 4722 } else if (Mem->isImplicit()) { 4723 // Any implicit members are fine. 4724 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4725 // This is a type that showed up in an 4726 // elaborated-type-specifier inside the anonymous struct or 4727 // union, but which actually declares a type outside of the 4728 // anonymous struct or union. It's okay. 4729 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4730 if (!MemRecord->isAnonymousStructOrUnion() && 4731 MemRecord->getDeclName()) { 4732 // Visual C++ allows type definition in anonymous struct or union. 4733 if (getLangOpts().MicrosoftExt) 4734 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4735 << Record->isUnion(); 4736 else { 4737 // This is a nested type declaration. 4738 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4739 << Record->isUnion(); 4740 Invalid = true; 4741 } 4742 } else { 4743 // This is an anonymous type definition within another anonymous type. 4744 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4745 // not part of standard C++. 4746 Diag(MemRecord->getLocation(), 4747 diag::ext_anonymous_record_with_anonymous_type) 4748 << Record->isUnion(); 4749 } 4750 } else if (isa<AccessSpecDecl>(Mem)) { 4751 // Any access specifier is fine. 4752 } else if (isa<StaticAssertDecl>(Mem)) { 4753 // In C++1z, static_assert declarations are also fine. 4754 } else { 4755 // We have something that isn't a non-static data 4756 // member. Complain about it. 4757 unsigned DK = diag::err_anonymous_record_bad_member; 4758 if (isa<TypeDecl>(Mem)) 4759 DK = diag::err_anonymous_record_with_type; 4760 else if (isa<FunctionDecl>(Mem)) 4761 DK = diag::err_anonymous_record_with_function; 4762 else if (isa<VarDecl>(Mem)) 4763 DK = diag::err_anonymous_record_with_static; 4764 4765 // Visual C++ allows type definition in anonymous struct or union. 4766 if (getLangOpts().MicrosoftExt && 4767 DK == diag::err_anonymous_record_with_type) 4768 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4769 << Record->isUnion(); 4770 else { 4771 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4772 Invalid = true; 4773 } 4774 } 4775 } 4776 4777 // C++11 [class.union]p8 (DR1460): 4778 // At most one variant member of a union may have a 4779 // brace-or-equal-initializer. 4780 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4781 Owner->isRecord()) 4782 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4783 cast<CXXRecordDecl>(Record)); 4784 } 4785 4786 if (!Record->isUnion() && !Owner->isRecord()) { 4787 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4788 << getLangOpts().CPlusPlus; 4789 Invalid = true; 4790 } 4791 4792 // Mock up a declarator. 4793 Declarator Dc(DS, DeclaratorContext::MemberContext); 4794 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4795 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4796 4797 // Create a declaration for this anonymous struct/union. 4798 NamedDecl *Anon = nullptr; 4799 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4800 Anon = FieldDecl::Create(Context, OwningClass, 4801 DS.getLocStart(), 4802 Record->getLocation(), 4803 /*IdentifierInfo=*/nullptr, 4804 Context.getTypeDeclType(Record), 4805 TInfo, 4806 /*BitWidth=*/nullptr, /*Mutable=*/false, 4807 /*InitStyle=*/ICIS_NoInit); 4808 Anon->setAccess(AS); 4809 if (getLangOpts().CPlusPlus) 4810 FieldCollector->Add(cast<FieldDecl>(Anon)); 4811 } else { 4812 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4813 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4814 if (SCSpec == DeclSpec::SCS_mutable) { 4815 // mutable can only appear on non-static class members, so it's always 4816 // an error here 4817 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4818 Invalid = true; 4819 SC = SC_None; 4820 } 4821 4822 Anon = VarDecl::Create(Context, Owner, 4823 DS.getLocStart(), 4824 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4825 Context.getTypeDeclType(Record), 4826 TInfo, SC); 4827 4828 // Default-initialize the implicit variable. This initialization will be 4829 // trivial in almost all cases, except if a union member has an in-class 4830 // initializer: 4831 // union { int n = 0; }; 4832 ActOnUninitializedDecl(Anon); 4833 } 4834 Anon->setImplicit(); 4835 4836 // Mark this as an anonymous struct/union type. 4837 Record->setAnonymousStructOrUnion(true); 4838 4839 // Add the anonymous struct/union object to the current 4840 // context. We'll be referencing this object when we refer to one of 4841 // its members. 4842 Owner->addDecl(Anon); 4843 4844 // Inject the members of the anonymous struct/union into the owning 4845 // context and into the identifier resolver chain for name lookup 4846 // purposes. 4847 SmallVector<NamedDecl*, 2> Chain; 4848 Chain.push_back(Anon); 4849 4850 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4851 Invalid = true; 4852 4853 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4854 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4855 Decl *ManglingContextDecl; 4856 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4857 NewVD->getDeclContext(), ManglingContextDecl)) { 4858 Context.setManglingNumber( 4859 NewVD, MCtx->getManglingNumber( 4860 NewVD, getMSManglingNumber(getLangOpts(), S))); 4861 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4862 } 4863 } 4864 } 4865 4866 if (Invalid) 4867 Anon->setInvalidDecl(); 4868 4869 return Anon; 4870 } 4871 4872 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4873 /// Microsoft C anonymous structure. 4874 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4875 /// Example: 4876 /// 4877 /// struct A { int a; }; 4878 /// struct B { struct A; int b; }; 4879 /// 4880 /// void foo() { 4881 /// B var; 4882 /// var.a = 3; 4883 /// } 4884 /// 4885 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4886 RecordDecl *Record) { 4887 assert(Record && "expected a record!"); 4888 4889 // Mock up a declarator. 4890 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4891 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4892 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4893 4894 auto *ParentDecl = cast<RecordDecl>(CurContext); 4895 QualType RecTy = Context.getTypeDeclType(Record); 4896 4897 // Create a declaration for this anonymous struct. 4898 NamedDecl *Anon = FieldDecl::Create(Context, 4899 ParentDecl, 4900 DS.getLocStart(), 4901 DS.getLocStart(), 4902 /*IdentifierInfo=*/nullptr, 4903 RecTy, 4904 TInfo, 4905 /*BitWidth=*/nullptr, /*Mutable=*/false, 4906 /*InitStyle=*/ICIS_NoInit); 4907 Anon->setImplicit(); 4908 4909 // Add the anonymous struct object to the current context. 4910 CurContext->addDecl(Anon); 4911 4912 // Inject the members of the anonymous struct into the current 4913 // context and into the identifier resolver chain for name lookup 4914 // purposes. 4915 SmallVector<NamedDecl*, 2> Chain; 4916 Chain.push_back(Anon); 4917 4918 RecordDecl *RecordDef = Record->getDefinition(); 4919 if (RequireCompleteType(Anon->getLocation(), RecTy, 4920 diag::err_field_incomplete) || 4921 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4922 AS_none, Chain)) { 4923 Anon->setInvalidDecl(); 4924 ParentDecl->setInvalidDecl(); 4925 } 4926 4927 return Anon; 4928 } 4929 4930 /// GetNameForDeclarator - Determine the full declaration name for the 4931 /// given Declarator. 4932 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4933 return GetNameFromUnqualifiedId(D.getName()); 4934 } 4935 4936 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4937 DeclarationNameInfo 4938 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4939 DeclarationNameInfo NameInfo; 4940 NameInfo.setLoc(Name.StartLocation); 4941 4942 switch (Name.getKind()) { 4943 4944 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4945 case UnqualifiedIdKind::IK_Identifier: 4946 NameInfo.setName(Name.Identifier); 4947 NameInfo.setLoc(Name.StartLocation); 4948 return NameInfo; 4949 4950 case UnqualifiedIdKind::IK_DeductionGuideName: { 4951 // C++ [temp.deduct.guide]p3: 4952 // The simple-template-id shall name a class template specialization. 4953 // The template-name shall be the same identifier as the template-name 4954 // of the simple-template-id. 4955 // These together intend to imply that the template-name shall name a 4956 // class template. 4957 // FIXME: template<typename T> struct X {}; 4958 // template<typename T> using Y = X<T>; 4959 // Y(int) -> Y<int>; 4960 // satisfies these rules but does not name a class template. 4961 TemplateName TN = Name.TemplateName.get().get(); 4962 auto *Template = TN.getAsTemplateDecl(); 4963 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4964 Diag(Name.StartLocation, 4965 diag::err_deduction_guide_name_not_class_template) 4966 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4967 if (Template) 4968 Diag(Template->getLocation(), diag::note_template_decl_here); 4969 return DeclarationNameInfo(); 4970 } 4971 4972 NameInfo.setName( 4973 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4974 NameInfo.setLoc(Name.StartLocation); 4975 return NameInfo; 4976 } 4977 4978 case UnqualifiedIdKind::IK_OperatorFunctionId: 4979 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4980 Name.OperatorFunctionId.Operator)); 4981 NameInfo.setLoc(Name.StartLocation); 4982 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4983 = Name.OperatorFunctionId.SymbolLocations[0]; 4984 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4985 = Name.EndLocation.getRawEncoding(); 4986 return NameInfo; 4987 4988 case UnqualifiedIdKind::IK_LiteralOperatorId: 4989 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4990 Name.Identifier)); 4991 NameInfo.setLoc(Name.StartLocation); 4992 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4993 return NameInfo; 4994 4995 case UnqualifiedIdKind::IK_ConversionFunctionId: { 4996 TypeSourceInfo *TInfo; 4997 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4998 if (Ty.isNull()) 4999 return DeclarationNameInfo(); 5000 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5001 Context.getCanonicalType(Ty))); 5002 NameInfo.setLoc(Name.StartLocation); 5003 NameInfo.setNamedTypeInfo(TInfo); 5004 return NameInfo; 5005 } 5006 5007 case UnqualifiedIdKind::IK_ConstructorName: { 5008 TypeSourceInfo *TInfo; 5009 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5010 if (Ty.isNull()) 5011 return DeclarationNameInfo(); 5012 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5013 Context.getCanonicalType(Ty))); 5014 NameInfo.setLoc(Name.StartLocation); 5015 NameInfo.setNamedTypeInfo(TInfo); 5016 return NameInfo; 5017 } 5018 5019 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5020 // In well-formed code, we can only have a constructor 5021 // template-id that refers to the current context, so go there 5022 // to find the actual type being constructed. 5023 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5024 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5025 return DeclarationNameInfo(); 5026 5027 // Determine the type of the class being constructed. 5028 QualType CurClassType = Context.getTypeDeclType(CurClass); 5029 5030 // FIXME: Check two things: that the template-id names the same type as 5031 // CurClassType, and that the template-id does not occur when the name 5032 // was qualified. 5033 5034 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5035 Context.getCanonicalType(CurClassType))); 5036 NameInfo.setLoc(Name.StartLocation); 5037 // FIXME: should we retrieve TypeSourceInfo? 5038 NameInfo.setNamedTypeInfo(nullptr); 5039 return NameInfo; 5040 } 5041 5042 case UnqualifiedIdKind::IK_DestructorName: { 5043 TypeSourceInfo *TInfo; 5044 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5045 if (Ty.isNull()) 5046 return DeclarationNameInfo(); 5047 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5048 Context.getCanonicalType(Ty))); 5049 NameInfo.setLoc(Name.StartLocation); 5050 NameInfo.setNamedTypeInfo(TInfo); 5051 return NameInfo; 5052 } 5053 5054 case UnqualifiedIdKind::IK_TemplateId: { 5055 TemplateName TName = Name.TemplateId->Template.get(); 5056 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5057 return Context.getNameForTemplate(TName, TNameLoc); 5058 } 5059 5060 } // switch (Name.getKind()) 5061 5062 llvm_unreachable("Unknown name kind"); 5063 } 5064 5065 static QualType getCoreType(QualType Ty) { 5066 do { 5067 if (Ty->isPointerType() || Ty->isReferenceType()) 5068 Ty = Ty->getPointeeType(); 5069 else if (Ty->isArrayType()) 5070 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5071 else 5072 return Ty.withoutLocalFastQualifiers(); 5073 } while (true); 5074 } 5075 5076 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5077 /// and Definition have "nearly" matching parameters. This heuristic is 5078 /// used to improve diagnostics in the case where an out-of-line function 5079 /// definition doesn't match any declaration within the class or namespace. 5080 /// Also sets Params to the list of indices to the parameters that differ 5081 /// between the declaration and the definition. If hasSimilarParameters 5082 /// returns true and Params is empty, then all of the parameters match. 5083 static bool hasSimilarParameters(ASTContext &Context, 5084 FunctionDecl *Declaration, 5085 FunctionDecl *Definition, 5086 SmallVectorImpl<unsigned> &Params) { 5087 Params.clear(); 5088 if (Declaration->param_size() != Definition->param_size()) 5089 return false; 5090 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5091 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5092 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5093 5094 // The parameter types are identical 5095 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5096 continue; 5097 5098 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5099 QualType DefParamBaseTy = getCoreType(DefParamTy); 5100 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5101 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5102 5103 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5104 (DeclTyName && DeclTyName == DefTyName)) 5105 Params.push_back(Idx); 5106 else // The two parameters aren't even close 5107 return false; 5108 } 5109 5110 return true; 5111 } 5112 5113 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5114 /// declarator needs to be rebuilt in the current instantiation. 5115 /// Any bits of declarator which appear before the name are valid for 5116 /// consideration here. That's specifically the type in the decl spec 5117 /// and the base type in any member-pointer chunks. 5118 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5119 DeclarationName Name) { 5120 // The types we specifically need to rebuild are: 5121 // - typenames, typeofs, and decltypes 5122 // - types which will become injected class names 5123 // Of course, we also need to rebuild any type referencing such a 5124 // type. It's safest to just say "dependent", but we call out a 5125 // few cases here. 5126 5127 DeclSpec &DS = D.getMutableDeclSpec(); 5128 switch (DS.getTypeSpecType()) { 5129 case DeclSpec::TST_typename: 5130 case DeclSpec::TST_typeofType: 5131 case DeclSpec::TST_underlyingType: 5132 case DeclSpec::TST_atomic: { 5133 // Grab the type from the parser. 5134 TypeSourceInfo *TSI = nullptr; 5135 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5136 if (T.isNull() || !T->isDependentType()) break; 5137 5138 // Make sure there's a type source info. This isn't really much 5139 // of a waste; most dependent types should have type source info 5140 // attached already. 5141 if (!TSI) 5142 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5143 5144 // Rebuild the type in the current instantiation. 5145 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5146 if (!TSI) return true; 5147 5148 // Store the new type back in the decl spec. 5149 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5150 DS.UpdateTypeRep(LocType); 5151 break; 5152 } 5153 5154 case DeclSpec::TST_decltype: 5155 case DeclSpec::TST_typeofExpr: { 5156 Expr *E = DS.getRepAsExpr(); 5157 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5158 if (Result.isInvalid()) return true; 5159 DS.UpdateExprRep(Result.get()); 5160 break; 5161 } 5162 5163 default: 5164 // Nothing to do for these decl specs. 5165 break; 5166 } 5167 5168 // It doesn't matter what order we do this in. 5169 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5170 DeclaratorChunk &Chunk = D.getTypeObject(I); 5171 5172 // The only type information in the declarator which can come 5173 // before the declaration name is the base type of a member 5174 // pointer. 5175 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5176 continue; 5177 5178 // Rebuild the scope specifier in-place. 5179 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5180 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5181 return true; 5182 } 5183 5184 return false; 5185 } 5186 5187 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5188 D.setFunctionDefinitionKind(FDK_Declaration); 5189 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5190 5191 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5192 Dcl && Dcl->getDeclContext()->isFileContext()) 5193 Dcl->setTopLevelDeclInObjCContainer(); 5194 5195 if (getLangOpts().OpenCL) 5196 setCurrentOpenCLExtensionForDecl(Dcl); 5197 5198 return Dcl; 5199 } 5200 5201 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5202 /// If T is the name of a class, then each of the following shall have a 5203 /// name different from T: 5204 /// - every static data member of class T; 5205 /// - every member function of class T 5206 /// - every member of class T that is itself a type; 5207 /// \returns true if the declaration name violates these rules. 5208 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5209 DeclarationNameInfo NameInfo) { 5210 DeclarationName Name = NameInfo.getName(); 5211 5212 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5213 while (Record && Record->isAnonymousStructOrUnion()) 5214 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5215 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5216 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5217 return true; 5218 } 5219 5220 return false; 5221 } 5222 5223 /// \brief Diagnose a declaration whose declarator-id has the given 5224 /// nested-name-specifier. 5225 /// 5226 /// \param SS The nested-name-specifier of the declarator-id. 5227 /// 5228 /// \param DC The declaration context to which the nested-name-specifier 5229 /// resolves. 5230 /// 5231 /// \param Name The name of the entity being declared. 5232 /// 5233 /// \param Loc The location of the name of the entity being declared. 5234 /// 5235 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5236 /// we're declaring an explicit / partial specialization / instantiation. 5237 /// 5238 /// \returns true if we cannot safely recover from this error, false otherwise. 5239 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5240 DeclarationName Name, 5241 SourceLocation Loc, bool IsTemplateId) { 5242 DeclContext *Cur = CurContext; 5243 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5244 Cur = Cur->getParent(); 5245 5246 // If the user provided a superfluous scope specifier that refers back to the 5247 // class in which the entity is already declared, diagnose and ignore it. 5248 // 5249 // class X { 5250 // void X::f(); 5251 // }; 5252 // 5253 // Note, it was once ill-formed to give redundant qualification in all 5254 // contexts, but that rule was removed by DR482. 5255 if (Cur->Equals(DC)) { 5256 if (Cur->isRecord()) { 5257 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5258 : diag::err_member_extra_qualification) 5259 << Name << FixItHint::CreateRemoval(SS.getRange()); 5260 SS.clear(); 5261 } else { 5262 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5263 } 5264 return false; 5265 } 5266 5267 // Check whether the qualifying scope encloses the scope of the original 5268 // declaration. For a template-id, we perform the checks in 5269 // CheckTemplateSpecializationScope. 5270 if (!Cur->Encloses(DC) && !IsTemplateId) { 5271 if (Cur->isRecord()) 5272 Diag(Loc, diag::err_member_qualification) 5273 << Name << SS.getRange(); 5274 else if (isa<TranslationUnitDecl>(DC)) 5275 Diag(Loc, diag::err_invalid_declarator_global_scope) 5276 << Name << SS.getRange(); 5277 else if (isa<FunctionDecl>(Cur)) 5278 Diag(Loc, diag::err_invalid_declarator_in_function) 5279 << Name << SS.getRange(); 5280 else if (isa<BlockDecl>(Cur)) 5281 Diag(Loc, diag::err_invalid_declarator_in_block) 5282 << Name << SS.getRange(); 5283 else 5284 Diag(Loc, diag::err_invalid_declarator_scope) 5285 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5286 5287 return true; 5288 } 5289 5290 if (Cur->isRecord()) { 5291 // Cannot qualify members within a class. 5292 Diag(Loc, diag::err_member_qualification) 5293 << Name << SS.getRange(); 5294 SS.clear(); 5295 5296 // C++ constructors and destructors with incorrect scopes can break 5297 // our AST invariants by having the wrong underlying types. If 5298 // that's the case, then drop this declaration entirely. 5299 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5300 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5301 !Context.hasSameType(Name.getCXXNameType(), 5302 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5303 return true; 5304 5305 return false; 5306 } 5307 5308 // C++11 [dcl.meaning]p1: 5309 // [...] "The nested-name-specifier of the qualified declarator-id shall 5310 // not begin with a decltype-specifer" 5311 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5312 while (SpecLoc.getPrefix()) 5313 SpecLoc = SpecLoc.getPrefix(); 5314 if (dyn_cast_or_null<DecltypeType>( 5315 SpecLoc.getNestedNameSpecifier()->getAsType())) 5316 Diag(Loc, diag::err_decltype_in_declarator) 5317 << SpecLoc.getTypeLoc().getSourceRange(); 5318 5319 return false; 5320 } 5321 5322 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5323 MultiTemplateParamsArg TemplateParamLists) { 5324 // TODO: consider using NameInfo for diagnostic. 5325 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5326 DeclarationName Name = NameInfo.getName(); 5327 5328 // All of these full declarators require an identifier. If it doesn't have 5329 // one, the ParsedFreeStandingDeclSpec action should be used. 5330 if (D.isDecompositionDeclarator()) { 5331 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5332 } else if (!Name) { 5333 if (!D.isInvalidType()) // Reject this if we think it is valid. 5334 Diag(D.getDeclSpec().getLocStart(), 5335 diag::err_declarator_need_ident) 5336 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5337 return nullptr; 5338 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5339 return nullptr; 5340 5341 // The scope passed in may not be a decl scope. Zip up the scope tree until 5342 // we find one that is. 5343 while ((S->getFlags() & Scope::DeclScope) == 0 || 5344 (S->getFlags() & Scope::TemplateParamScope) != 0) 5345 S = S->getParent(); 5346 5347 DeclContext *DC = CurContext; 5348 if (D.getCXXScopeSpec().isInvalid()) 5349 D.setInvalidType(); 5350 else if (D.getCXXScopeSpec().isSet()) { 5351 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5352 UPPC_DeclarationQualifier)) 5353 return nullptr; 5354 5355 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5356 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5357 if (!DC || isa<EnumDecl>(DC)) { 5358 // If we could not compute the declaration context, it's because the 5359 // declaration context is dependent but does not refer to a class, 5360 // class template, or class template partial specialization. Complain 5361 // and return early, to avoid the coming semantic disaster. 5362 Diag(D.getIdentifierLoc(), 5363 diag::err_template_qualified_declarator_no_match) 5364 << D.getCXXScopeSpec().getScopeRep() 5365 << D.getCXXScopeSpec().getRange(); 5366 return nullptr; 5367 } 5368 bool IsDependentContext = DC->isDependentContext(); 5369 5370 if (!IsDependentContext && 5371 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5372 return nullptr; 5373 5374 // If a class is incomplete, do not parse entities inside it. 5375 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5376 Diag(D.getIdentifierLoc(), 5377 diag::err_member_def_undefined_record) 5378 << Name << DC << D.getCXXScopeSpec().getRange(); 5379 return nullptr; 5380 } 5381 if (!D.getDeclSpec().isFriendSpecified()) { 5382 if (diagnoseQualifiedDeclaration( 5383 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5384 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5385 if (DC->isRecord()) 5386 return nullptr; 5387 5388 D.setInvalidType(); 5389 } 5390 } 5391 5392 // Check whether we need to rebuild the type of the given 5393 // declaration in the current instantiation. 5394 if (EnteringContext && IsDependentContext && 5395 TemplateParamLists.size() != 0) { 5396 ContextRAII SavedContext(*this, DC); 5397 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5398 D.setInvalidType(); 5399 } 5400 } 5401 5402 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5403 QualType R = TInfo->getType(); 5404 5405 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5406 UPPC_DeclarationType)) 5407 D.setInvalidType(); 5408 5409 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5410 forRedeclarationInCurContext()); 5411 5412 // See if this is a redefinition of a variable in the same scope. 5413 if (!D.getCXXScopeSpec().isSet()) { 5414 bool IsLinkageLookup = false; 5415 bool CreateBuiltins = false; 5416 5417 // If the declaration we're planning to build will be a function 5418 // or object with linkage, then look for another declaration with 5419 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5420 // 5421 // If the declaration we're planning to build will be declared with 5422 // external linkage in the translation unit, create any builtin with 5423 // the same name. 5424 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5425 /* Do nothing*/; 5426 else if (CurContext->isFunctionOrMethod() && 5427 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5428 R->isFunctionType())) { 5429 IsLinkageLookup = true; 5430 CreateBuiltins = 5431 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5432 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5434 CreateBuiltins = true; 5435 5436 if (IsLinkageLookup) { 5437 Previous.clear(LookupRedeclarationWithLinkage); 5438 Previous.setRedeclarationKind(ForExternalRedeclaration); 5439 } 5440 5441 LookupName(Previous, S, CreateBuiltins); 5442 } else { // Something like "int foo::x;" 5443 LookupQualifiedName(Previous, DC); 5444 5445 // C++ [dcl.meaning]p1: 5446 // When the declarator-id is qualified, the declaration shall refer to a 5447 // previously declared member of the class or namespace to which the 5448 // qualifier refers (or, in the case of a namespace, of an element of the 5449 // inline namespace set of that namespace (7.3.1)) or to a specialization 5450 // thereof; [...] 5451 // 5452 // Note that we already checked the context above, and that we do not have 5453 // enough information to make sure that Previous contains the declaration 5454 // we want to match. For example, given: 5455 // 5456 // class X { 5457 // void f(); 5458 // void f(float); 5459 // }; 5460 // 5461 // void X::f(int) { } // ill-formed 5462 // 5463 // In this case, Previous will point to the overload set 5464 // containing the two f's declared in X, but neither of them 5465 // matches. 5466 5467 // C++ [dcl.meaning]p1: 5468 // [...] the member shall not merely have been introduced by a 5469 // using-declaration in the scope of the class or namespace nominated by 5470 // the nested-name-specifier of the declarator-id. 5471 RemoveUsingDecls(Previous); 5472 } 5473 5474 if (Previous.isSingleResult() && 5475 Previous.getFoundDecl()->isTemplateParameter()) { 5476 // Maybe we will complain about the shadowed template parameter. 5477 if (!D.isInvalidType()) 5478 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5479 Previous.getFoundDecl()); 5480 5481 // Just pretend that we didn't see the previous declaration. 5482 Previous.clear(); 5483 } 5484 5485 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5486 // Forget that the previous declaration is the injected-class-name. 5487 Previous.clear(); 5488 5489 // In C++, the previous declaration we find might be a tag type 5490 // (class or enum). In this case, the new declaration will hide the 5491 // tag type. Note that this applies to functions, function templates, and 5492 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5493 if (Previous.isSingleTagDecl() && 5494 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5495 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5496 Previous.clear(); 5497 5498 // Check that there are no default arguments other than in the parameters 5499 // of a function declaration (C++ only). 5500 if (getLangOpts().CPlusPlus) 5501 CheckExtraCXXDefaultArguments(D); 5502 5503 NamedDecl *New; 5504 5505 bool AddToScope = true; 5506 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5507 if (TemplateParamLists.size()) { 5508 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5509 return nullptr; 5510 } 5511 5512 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5513 } else if (R->isFunctionType()) { 5514 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5515 TemplateParamLists, 5516 AddToScope); 5517 } else { 5518 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5519 AddToScope); 5520 } 5521 5522 if (!New) 5523 return nullptr; 5524 5525 // If this has an identifier and is not a function template specialization, 5526 // add it to the scope stack. 5527 if (New->getDeclName() && AddToScope) { 5528 // Only make a locally-scoped extern declaration visible if it is the first 5529 // declaration of this entity. Qualified lookup for such an entity should 5530 // only find this declaration if there is no visible declaration of it. 5531 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5532 PushOnScopeChains(New, S, AddToContext); 5533 if (!AddToContext) 5534 CurContext->addHiddenDecl(New); 5535 } 5536 5537 if (isInOpenMPDeclareTargetContext()) 5538 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5539 5540 return New; 5541 } 5542 5543 /// Helper method to turn variable array types into constant array 5544 /// types in certain situations which would otherwise be errors (for 5545 /// GCC compatibility). 5546 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5547 ASTContext &Context, 5548 bool &SizeIsNegative, 5549 llvm::APSInt &Oversized) { 5550 // This method tries to turn a variable array into a constant 5551 // array even when the size isn't an ICE. This is necessary 5552 // for compatibility with code that depends on gcc's buggy 5553 // constant expression folding, like struct {char x[(int)(char*)2];} 5554 SizeIsNegative = false; 5555 Oversized = 0; 5556 5557 if (T->isDependentType()) 5558 return QualType(); 5559 5560 QualifierCollector Qs; 5561 const Type *Ty = Qs.strip(T); 5562 5563 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5564 QualType Pointee = PTy->getPointeeType(); 5565 QualType FixedType = 5566 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5567 Oversized); 5568 if (FixedType.isNull()) return FixedType; 5569 FixedType = Context.getPointerType(FixedType); 5570 return Qs.apply(Context, FixedType); 5571 } 5572 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5573 QualType Inner = PTy->getInnerType(); 5574 QualType FixedType = 5575 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5576 Oversized); 5577 if (FixedType.isNull()) return FixedType; 5578 FixedType = Context.getParenType(FixedType); 5579 return Qs.apply(Context, FixedType); 5580 } 5581 5582 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5583 if (!VLATy) 5584 return QualType(); 5585 // FIXME: We should probably handle this case 5586 if (VLATy->getElementType()->isVariablyModifiedType()) 5587 return QualType(); 5588 5589 llvm::APSInt Res; 5590 if (!VLATy->getSizeExpr() || 5591 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5592 return QualType(); 5593 5594 // Check whether the array size is negative. 5595 if (Res.isSigned() && Res.isNegative()) { 5596 SizeIsNegative = true; 5597 return QualType(); 5598 } 5599 5600 // Check whether the array is too large to be addressed. 5601 unsigned ActiveSizeBits 5602 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5603 Res); 5604 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5605 Oversized = Res; 5606 return QualType(); 5607 } 5608 5609 return Context.getConstantArrayType(VLATy->getElementType(), 5610 Res, ArrayType::Normal, 0); 5611 } 5612 5613 static void 5614 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5615 SrcTL = SrcTL.getUnqualifiedLoc(); 5616 DstTL = DstTL.getUnqualifiedLoc(); 5617 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5618 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5619 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5620 DstPTL.getPointeeLoc()); 5621 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5622 return; 5623 } 5624 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5625 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5626 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5627 DstPTL.getInnerLoc()); 5628 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5629 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5630 return; 5631 } 5632 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5633 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5634 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5635 TypeLoc DstElemTL = DstATL.getElementLoc(); 5636 DstElemTL.initializeFullCopy(SrcElemTL); 5637 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5638 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5639 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5640 } 5641 5642 /// Helper method to turn variable array types into constant array 5643 /// types in certain situations which would otherwise be errors (for 5644 /// GCC compatibility). 5645 static TypeSourceInfo* 5646 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5647 ASTContext &Context, 5648 bool &SizeIsNegative, 5649 llvm::APSInt &Oversized) { 5650 QualType FixedTy 5651 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5652 SizeIsNegative, Oversized); 5653 if (FixedTy.isNull()) 5654 return nullptr; 5655 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5656 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5657 FixedTInfo->getTypeLoc()); 5658 return FixedTInfo; 5659 } 5660 5661 /// \brief Register the given locally-scoped extern "C" declaration so 5662 /// that it can be found later for redeclarations. We include any extern "C" 5663 /// declaration that is not visible in the translation unit here, not just 5664 /// function-scope declarations. 5665 void 5666 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5667 if (!getLangOpts().CPlusPlus && 5668 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5669 // Don't need to track declarations in the TU in C. 5670 return; 5671 5672 // Note that we have a locally-scoped external with this name. 5673 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5674 } 5675 5676 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5677 // FIXME: We can have multiple results via __attribute__((overloadable)). 5678 auto Result = Context.getExternCContextDecl()->lookup(Name); 5679 return Result.empty() ? nullptr : *Result.begin(); 5680 } 5681 5682 /// \brief Diagnose function specifiers on a declaration of an identifier that 5683 /// does not identify a function. 5684 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5685 // FIXME: We should probably indicate the identifier in question to avoid 5686 // confusion for constructs like "virtual int a(), b;" 5687 if (DS.isVirtualSpecified()) 5688 Diag(DS.getVirtualSpecLoc(), 5689 diag::err_virtual_non_function); 5690 5691 if (DS.isExplicitSpecified()) 5692 Diag(DS.getExplicitSpecLoc(), 5693 diag::err_explicit_non_function); 5694 5695 if (DS.isNoreturnSpecified()) 5696 Diag(DS.getNoreturnSpecLoc(), 5697 diag::err_noreturn_non_function); 5698 } 5699 5700 NamedDecl* 5701 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5702 TypeSourceInfo *TInfo, LookupResult &Previous) { 5703 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5704 if (D.getCXXScopeSpec().isSet()) { 5705 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5706 << D.getCXXScopeSpec().getRange(); 5707 D.setInvalidType(); 5708 // Pretend we didn't see the scope specifier. 5709 DC = CurContext; 5710 Previous.clear(); 5711 } 5712 5713 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5714 5715 if (D.getDeclSpec().isInlineSpecified()) 5716 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5717 << getLangOpts().CPlusPlus17; 5718 if (D.getDeclSpec().isConstexprSpecified()) 5719 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5720 << 1; 5721 5722 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5723 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5724 Diag(D.getName().StartLocation, 5725 diag::err_deduction_guide_invalid_specifier) 5726 << "typedef"; 5727 else 5728 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5729 << D.getName().getSourceRange(); 5730 return nullptr; 5731 } 5732 5733 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5734 if (!NewTD) return nullptr; 5735 5736 // Handle attributes prior to checking for duplicates in MergeVarDecl 5737 ProcessDeclAttributes(S, NewTD, D); 5738 5739 CheckTypedefForVariablyModifiedType(S, NewTD); 5740 5741 bool Redeclaration = D.isRedeclaration(); 5742 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5743 D.setRedeclaration(Redeclaration); 5744 return ND; 5745 } 5746 5747 void 5748 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5749 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5750 // then it shall have block scope. 5751 // Note that variably modified types must be fixed before merging the decl so 5752 // that redeclarations will match. 5753 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5754 QualType T = TInfo->getType(); 5755 if (T->isVariablyModifiedType()) { 5756 setFunctionHasBranchProtectedScope(); 5757 5758 if (S->getFnParent() == nullptr) { 5759 bool SizeIsNegative; 5760 llvm::APSInt Oversized; 5761 TypeSourceInfo *FixedTInfo = 5762 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5763 SizeIsNegative, 5764 Oversized); 5765 if (FixedTInfo) { 5766 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5767 NewTD->setTypeSourceInfo(FixedTInfo); 5768 } else { 5769 if (SizeIsNegative) 5770 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5771 else if (T->isVariableArrayType()) 5772 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5773 else if (Oversized.getBoolValue()) 5774 Diag(NewTD->getLocation(), diag::err_array_too_large) 5775 << Oversized.toString(10); 5776 else 5777 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5778 NewTD->setInvalidDecl(); 5779 } 5780 } 5781 } 5782 } 5783 5784 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5785 /// declares a typedef-name, either using the 'typedef' type specifier or via 5786 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5787 NamedDecl* 5788 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5789 LookupResult &Previous, bool &Redeclaration) { 5790 5791 // Find the shadowed declaration before filtering for scope. 5792 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5793 5794 // Merge the decl with the existing one if appropriate. If the decl is 5795 // in an outer scope, it isn't the same thing. 5796 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5797 /*AllowInlineNamespace*/false); 5798 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5799 if (!Previous.empty()) { 5800 Redeclaration = true; 5801 MergeTypedefNameDecl(S, NewTD, Previous); 5802 } 5803 5804 if (ShadowedDecl && !Redeclaration) 5805 CheckShadow(NewTD, ShadowedDecl, Previous); 5806 5807 // If this is the C FILE type, notify the AST context. 5808 if (IdentifierInfo *II = NewTD->getIdentifier()) 5809 if (!NewTD->isInvalidDecl() && 5810 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5811 if (II->isStr("FILE")) 5812 Context.setFILEDecl(NewTD); 5813 else if (II->isStr("jmp_buf")) 5814 Context.setjmp_bufDecl(NewTD); 5815 else if (II->isStr("sigjmp_buf")) 5816 Context.setsigjmp_bufDecl(NewTD); 5817 else if (II->isStr("ucontext_t")) 5818 Context.setucontext_tDecl(NewTD); 5819 } 5820 5821 return NewTD; 5822 } 5823 5824 /// \brief Determines whether the given declaration is an out-of-scope 5825 /// previous declaration. 5826 /// 5827 /// This routine should be invoked when name lookup has found a 5828 /// previous declaration (PrevDecl) that is not in the scope where a 5829 /// new declaration by the same name is being introduced. If the new 5830 /// declaration occurs in a local scope, previous declarations with 5831 /// linkage may still be considered previous declarations (C99 5832 /// 6.2.2p4-5, C++ [basic.link]p6). 5833 /// 5834 /// \param PrevDecl the previous declaration found by name 5835 /// lookup 5836 /// 5837 /// \param DC the context in which the new declaration is being 5838 /// declared. 5839 /// 5840 /// \returns true if PrevDecl is an out-of-scope previous declaration 5841 /// for a new delcaration with the same name. 5842 static bool 5843 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5844 ASTContext &Context) { 5845 if (!PrevDecl) 5846 return false; 5847 5848 if (!PrevDecl->hasLinkage()) 5849 return false; 5850 5851 if (Context.getLangOpts().CPlusPlus) { 5852 // C++ [basic.link]p6: 5853 // If there is a visible declaration of an entity with linkage 5854 // having the same name and type, ignoring entities declared 5855 // outside the innermost enclosing namespace scope, the block 5856 // scope declaration declares that same entity and receives the 5857 // linkage of the previous declaration. 5858 DeclContext *OuterContext = DC->getRedeclContext(); 5859 if (!OuterContext->isFunctionOrMethod()) 5860 // This rule only applies to block-scope declarations. 5861 return false; 5862 5863 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5864 if (PrevOuterContext->isRecord()) 5865 // We found a member function: ignore it. 5866 return false; 5867 5868 // Find the innermost enclosing namespace for the new and 5869 // previous declarations. 5870 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5871 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5872 5873 // The previous declaration is in a different namespace, so it 5874 // isn't the same function. 5875 if (!OuterContext->Equals(PrevOuterContext)) 5876 return false; 5877 } 5878 5879 return true; 5880 } 5881 5882 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5883 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5884 if (!SS.isSet()) return; 5885 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5886 } 5887 5888 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5889 QualType type = decl->getType(); 5890 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5891 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5892 // Various kinds of declaration aren't allowed to be __autoreleasing. 5893 unsigned kind = -1U; 5894 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5895 if (var->hasAttr<BlocksAttr>()) 5896 kind = 0; // __block 5897 else if (!var->hasLocalStorage()) 5898 kind = 1; // global 5899 } else if (isa<ObjCIvarDecl>(decl)) { 5900 kind = 3; // ivar 5901 } else if (isa<FieldDecl>(decl)) { 5902 kind = 2; // field 5903 } 5904 5905 if (kind != -1U) { 5906 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5907 << kind; 5908 } 5909 } else if (lifetime == Qualifiers::OCL_None) { 5910 // Try to infer lifetime. 5911 if (!type->isObjCLifetimeType()) 5912 return false; 5913 5914 lifetime = type->getObjCARCImplicitLifetime(); 5915 type = Context.getLifetimeQualifiedType(type, lifetime); 5916 decl->setType(type); 5917 } 5918 5919 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5920 // Thread-local variables cannot have lifetime. 5921 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5922 var->getTLSKind()) { 5923 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5924 << var->getType(); 5925 return true; 5926 } 5927 } 5928 5929 return false; 5930 } 5931 5932 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5933 // Ensure that an auto decl is deduced otherwise the checks below might cache 5934 // the wrong linkage. 5935 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5936 5937 // 'weak' only applies to declarations with external linkage. 5938 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5939 if (!ND.isExternallyVisible()) { 5940 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5941 ND.dropAttr<WeakAttr>(); 5942 } 5943 } 5944 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5945 if (ND.isExternallyVisible()) { 5946 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5947 ND.dropAttr<WeakRefAttr>(); 5948 ND.dropAttr<AliasAttr>(); 5949 } 5950 } 5951 5952 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5953 if (VD->hasInit()) { 5954 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5955 assert(VD->isThisDeclarationADefinition() && 5956 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5957 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5958 VD->dropAttr<AliasAttr>(); 5959 } 5960 } 5961 } 5962 5963 // 'selectany' only applies to externally visible variable declarations. 5964 // It does not apply to functions. 5965 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5966 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5967 S.Diag(Attr->getLocation(), 5968 diag::err_attribute_selectany_non_extern_data); 5969 ND.dropAttr<SelectAnyAttr>(); 5970 } 5971 } 5972 5973 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5974 // dll attributes require external linkage. Static locals may have external 5975 // linkage but still cannot be explicitly imported or exported. 5976 auto *VD = dyn_cast<VarDecl>(&ND); 5977 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5978 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5979 << &ND << Attr; 5980 ND.setInvalidDecl(); 5981 } 5982 } 5983 5984 // Virtual functions cannot be marked as 'notail'. 5985 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5986 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5987 if (MD->isVirtual()) { 5988 S.Diag(ND.getLocation(), 5989 diag::err_invalid_attribute_on_virtual_function) 5990 << Attr; 5991 ND.dropAttr<NotTailCalledAttr>(); 5992 } 5993 } 5994 5995 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5996 NamedDecl *NewDecl, 5997 bool IsSpecialization, 5998 bool IsDefinition) { 5999 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6000 return; 6001 6002 bool IsTemplate = false; 6003 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6004 OldDecl = OldTD->getTemplatedDecl(); 6005 IsTemplate = true; 6006 if (!IsSpecialization) 6007 IsDefinition = false; 6008 } 6009 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6010 NewDecl = NewTD->getTemplatedDecl(); 6011 IsTemplate = true; 6012 } 6013 6014 if (!OldDecl || !NewDecl) 6015 return; 6016 6017 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6018 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6019 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6020 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6021 6022 // dllimport and dllexport are inheritable attributes so we have to exclude 6023 // inherited attribute instances. 6024 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6025 (NewExportAttr && !NewExportAttr->isInherited()); 6026 6027 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6028 // the only exception being explicit specializations. 6029 // Implicitly generated declarations are also excluded for now because there 6030 // is no other way to switch these to use dllimport or dllexport. 6031 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6032 6033 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6034 // Allow with a warning for free functions and global variables. 6035 bool JustWarn = false; 6036 if (!OldDecl->isCXXClassMember()) { 6037 auto *VD = dyn_cast<VarDecl>(OldDecl); 6038 if (VD && !VD->getDescribedVarTemplate()) 6039 JustWarn = true; 6040 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6041 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6042 JustWarn = true; 6043 } 6044 6045 // We cannot change a declaration that's been used because IR has already 6046 // been emitted. Dllimported functions will still work though (modulo 6047 // address equality) as they can use the thunk. 6048 if (OldDecl->isUsed()) 6049 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6050 JustWarn = false; 6051 6052 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6053 : diag::err_attribute_dll_redeclaration; 6054 S.Diag(NewDecl->getLocation(), DiagID) 6055 << NewDecl 6056 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6057 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6058 if (!JustWarn) { 6059 NewDecl->setInvalidDecl(); 6060 return; 6061 } 6062 } 6063 6064 // A redeclaration is not allowed to drop a dllimport attribute, the only 6065 // exceptions being inline function definitions (except for function 6066 // templates), local extern declarations, qualified friend declarations or 6067 // special MSVC extension: in the last case, the declaration is treated as if 6068 // it were marked dllexport. 6069 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6070 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6071 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6072 // Ignore static data because out-of-line definitions are diagnosed 6073 // separately. 6074 IsStaticDataMember = VD->isStaticDataMember(); 6075 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6076 VarDecl::DeclarationOnly; 6077 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6078 IsInline = FD->isInlined(); 6079 IsQualifiedFriend = FD->getQualifier() && 6080 FD->getFriendObjectKind() == Decl::FOK_Declared; 6081 } 6082 6083 if (OldImportAttr && !HasNewAttr && 6084 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6085 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6086 if (IsMicrosoft && IsDefinition) { 6087 S.Diag(NewDecl->getLocation(), 6088 diag::warn_redeclaration_without_import_attribute) 6089 << NewDecl; 6090 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6091 NewDecl->dropAttr<DLLImportAttr>(); 6092 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6093 NewImportAttr->getRange(), S.Context, 6094 NewImportAttr->getSpellingListIndex())); 6095 } else { 6096 S.Diag(NewDecl->getLocation(), 6097 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6098 << NewDecl << OldImportAttr; 6099 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6100 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6101 OldDecl->dropAttr<DLLImportAttr>(); 6102 NewDecl->dropAttr<DLLImportAttr>(); 6103 } 6104 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6105 // In MinGW, seeing a function declared inline drops the dllimport 6106 // attribute. 6107 OldDecl->dropAttr<DLLImportAttr>(); 6108 NewDecl->dropAttr<DLLImportAttr>(); 6109 S.Diag(NewDecl->getLocation(), 6110 diag::warn_dllimport_dropped_from_inline_function) 6111 << NewDecl << OldImportAttr; 6112 } 6113 6114 // A specialization of a class template member function is processed here 6115 // since it's a redeclaration. If the parent class is dllexport, the 6116 // specialization inherits that attribute. This doesn't happen automatically 6117 // since the parent class isn't instantiated until later. 6118 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6119 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6120 !NewImportAttr && !NewExportAttr) { 6121 if (const DLLExportAttr *ParentExportAttr = 6122 MD->getParent()->getAttr<DLLExportAttr>()) { 6123 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6124 NewAttr->setInherited(true); 6125 NewDecl->addAttr(NewAttr); 6126 } 6127 } 6128 } 6129 } 6130 6131 /// Given that we are within the definition of the given function, 6132 /// will that definition behave like C99's 'inline', where the 6133 /// definition is discarded except for optimization purposes? 6134 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6135 // Try to avoid calling GetGVALinkageForFunction. 6136 6137 // All cases of this require the 'inline' keyword. 6138 if (!FD->isInlined()) return false; 6139 6140 // This is only possible in C++ with the gnu_inline attribute. 6141 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6142 return false; 6143 6144 // Okay, go ahead and call the relatively-more-expensive function. 6145 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6146 } 6147 6148 /// Determine whether a variable is extern "C" prior to attaching 6149 /// an initializer. We can't just call isExternC() here, because that 6150 /// will also compute and cache whether the declaration is externally 6151 /// visible, which might change when we attach the initializer. 6152 /// 6153 /// This can only be used if the declaration is known to not be a 6154 /// redeclaration of an internal linkage declaration. 6155 /// 6156 /// For instance: 6157 /// 6158 /// auto x = []{}; 6159 /// 6160 /// Attaching the initializer here makes this declaration not externally 6161 /// visible, because its type has internal linkage. 6162 /// 6163 /// FIXME: This is a hack. 6164 template<typename T> 6165 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6166 if (S.getLangOpts().CPlusPlus) { 6167 // In C++, the overloadable attribute negates the effects of extern "C". 6168 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6169 return false; 6170 6171 // So do CUDA's host/device attributes. 6172 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6173 D->template hasAttr<CUDAHostAttr>())) 6174 return false; 6175 } 6176 return D->isExternC(); 6177 } 6178 6179 static bool shouldConsiderLinkage(const VarDecl *VD) { 6180 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6181 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6182 return VD->hasExternalStorage(); 6183 if (DC->isFileContext()) 6184 return true; 6185 if (DC->isRecord()) 6186 return false; 6187 llvm_unreachable("Unexpected context"); 6188 } 6189 6190 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6191 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6192 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6193 isa<OMPDeclareReductionDecl>(DC)) 6194 return true; 6195 if (DC->isRecord()) 6196 return false; 6197 llvm_unreachable("Unexpected context"); 6198 } 6199 6200 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6201 AttributeList::Kind Kind) { 6202 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6203 if (L->getKind() == Kind) 6204 return true; 6205 return false; 6206 } 6207 6208 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6209 AttributeList::Kind Kind) { 6210 // Check decl attributes on the DeclSpec. 6211 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6212 return true; 6213 6214 // Walk the declarator structure, checking decl attributes that were in a type 6215 // position to the decl itself. 6216 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6217 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6218 return true; 6219 } 6220 6221 // Finally, check attributes on the decl itself. 6222 return hasParsedAttr(S, PD.getAttributes(), Kind); 6223 } 6224 6225 /// Adjust the \c DeclContext for a function or variable that might be a 6226 /// function-local external declaration. 6227 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6228 if (!DC->isFunctionOrMethod()) 6229 return false; 6230 6231 // If this is a local extern function or variable declared within a function 6232 // template, don't add it into the enclosing namespace scope until it is 6233 // instantiated; it might have a dependent type right now. 6234 if (DC->isDependentContext()) 6235 return true; 6236 6237 // C++11 [basic.link]p7: 6238 // When a block scope declaration of an entity with linkage is not found to 6239 // refer to some other declaration, then that entity is a member of the 6240 // innermost enclosing namespace. 6241 // 6242 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6243 // semantically-enclosing namespace, not a lexically-enclosing one. 6244 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6245 DC = DC->getParent(); 6246 return true; 6247 } 6248 6249 /// \brief Returns true if given declaration has external C language linkage. 6250 static bool isDeclExternC(const Decl *D) { 6251 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6252 return FD->isExternC(); 6253 if (const auto *VD = dyn_cast<VarDecl>(D)) 6254 return VD->isExternC(); 6255 6256 llvm_unreachable("Unknown type of decl!"); 6257 } 6258 6259 NamedDecl *Sema::ActOnVariableDeclarator( 6260 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6261 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6262 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6263 QualType R = TInfo->getType(); 6264 DeclarationName Name = GetNameForDeclarator(D).getName(); 6265 6266 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6267 6268 if (D.isDecompositionDeclarator()) { 6269 // Take the name of the first declarator as our name for diagnostic 6270 // purposes. 6271 auto &Decomp = D.getDecompositionDeclarator(); 6272 if (!Decomp.bindings().empty()) { 6273 II = Decomp.bindings()[0].Name; 6274 Name = II; 6275 } 6276 } else if (!II) { 6277 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6278 return nullptr; 6279 } 6280 6281 if (getLangOpts().OpenCL) { 6282 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6283 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6284 // argument. 6285 if (R->isImageType() || R->isPipeType()) { 6286 Diag(D.getIdentifierLoc(), 6287 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6288 << R; 6289 D.setInvalidType(); 6290 return nullptr; 6291 } 6292 6293 // OpenCL v1.2 s6.9.r: 6294 // The event type cannot be used to declare a program scope variable. 6295 // OpenCL v2.0 s6.9.q: 6296 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6297 if (NULL == S->getParent()) { 6298 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6299 Diag(D.getIdentifierLoc(), 6300 diag::err_invalid_type_for_program_scope_var) << R; 6301 D.setInvalidType(); 6302 return nullptr; 6303 } 6304 } 6305 6306 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6307 QualType NR = R; 6308 while (NR->isPointerType()) { 6309 if (NR->isFunctionPointerType()) { 6310 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6311 D.setInvalidType(); 6312 break; 6313 } 6314 NR = NR->getPointeeType(); 6315 } 6316 6317 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6318 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6319 // half array type (unless the cl_khr_fp16 extension is enabled). 6320 if (Context.getBaseElementType(R)->isHalfType()) { 6321 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6322 D.setInvalidType(); 6323 } 6324 } 6325 6326 if (R->isSamplerT()) { 6327 // OpenCL v1.2 s6.9.b p4: 6328 // The sampler type cannot be used with the __local and __global address 6329 // space qualifiers. 6330 if (R.getAddressSpace() == LangAS::opencl_local || 6331 R.getAddressSpace() == LangAS::opencl_global) { 6332 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6333 } 6334 6335 // OpenCL v1.2 s6.12.14.1: 6336 // A global sampler must be declared with either the constant address 6337 // space qualifier or with the const qualifier. 6338 if (DC->isTranslationUnit() && 6339 !(R.getAddressSpace() == LangAS::opencl_constant || 6340 R.isConstQualified())) { 6341 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6342 D.setInvalidType(); 6343 } 6344 } 6345 6346 // OpenCL v1.2 s6.9.r: 6347 // The event type cannot be used with the __local, __constant and __global 6348 // address space qualifiers. 6349 if (R->isEventT()) { 6350 if (R.getAddressSpace() != LangAS::opencl_private) { 6351 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6352 D.setInvalidType(); 6353 } 6354 } 6355 } 6356 6357 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6358 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6359 6360 // dllimport globals without explicit storage class are treated as extern. We 6361 // have to change the storage class this early to get the right DeclContext. 6362 if (SC == SC_None && !DC->isRecord() && 6363 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6364 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6365 SC = SC_Extern; 6366 6367 DeclContext *OriginalDC = DC; 6368 bool IsLocalExternDecl = SC == SC_Extern && 6369 adjustContextForLocalExternDecl(DC); 6370 6371 if (SCSpec == DeclSpec::SCS_mutable) { 6372 // mutable can only appear on non-static class members, so it's always 6373 // an error here 6374 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6375 D.setInvalidType(); 6376 SC = SC_None; 6377 } 6378 6379 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6380 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6381 D.getDeclSpec().getStorageClassSpecLoc())) { 6382 // In C++11, the 'register' storage class specifier is deprecated. 6383 // Suppress the warning in system macros, it's used in macros in some 6384 // popular C system headers, such as in glibc's htonl() macro. 6385 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6386 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6387 : diag::warn_deprecated_register) 6388 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6389 } 6390 6391 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6392 6393 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6394 // C99 6.9p2: The storage-class specifiers auto and register shall not 6395 // appear in the declaration specifiers in an external declaration. 6396 // Global Register+Asm is a GNU extension we support. 6397 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6398 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6399 D.setInvalidType(); 6400 } 6401 } 6402 6403 bool IsMemberSpecialization = false; 6404 bool IsVariableTemplateSpecialization = false; 6405 bool IsPartialSpecialization = false; 6406 bool IsVariableTemplate = false; 6407 VarDecl *NewVD = nullptr; 6408 VarTemplateDecl *NewTemplate = nullptr; 6409 TemplateParameterList *TemplateParams = nullptr; 6410 if (!getLangOpts().CPlusPlus) { 6411 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6412 D.getIdentifierLoc(), II, 6413 R, TInfo, SC); 6414 6415 if (R->getContainedDeducedType()) 6416 ParsingInitForAutoVars.insert(NewVD); 6417 6418 if (D.isInvalidType()) 6419 NewVD->setInvalidDecl(); 6420 } else { 6421 bool Invalid = false; 6422 6423 if (DC->isRecord() && !CurContext->isRecord()) { 6424 // This is an out-of-line definition of a static data member. 6425 switch (SC) { 6426 case SC_None: 6427 break; 6428 case SC_Static: 6429 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6430 diag::err_static_out_of_line) 6431 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6432 break; 6433 case SC_Auto: 6434 case SC_Register: 6435 case SC_Extern: 6436 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6437 // to names of variables declared in a block or to function parameters. 6438 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6439 // of class members 6440 6441 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6442 diag::err_storage_class_for_static_member) 6443 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6444 break; 6445 case SC_PrivateExtern: 6446 llvm_unreachable("C storage class in c++!"); 6447 } 6448 } 6449 6450 if (SC == SC_Static && CurContext->isRecord()) { 6451 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6452 if (RD->isLocalClass()) 6453 Diag(D.getIdentifierLoc(), 6454 diag::err_static_data_member_not_allowed_in_local_class) 6455 << Name << RD->getDeclName(); 6456 6457 // C++98 [class.union]p1: If a union contains a static data member, 6458 // the program is ill-formed. C++11 drops this restriction. 6459 if (RD->isUnion()) 6460 Diag(D.getIdentifierLoc(), 6461 getLangOpts().CPlusPlus11 6462 ? diag::warn_cxx98_compat_static_data_member_in_union 6463 : diag::ext_static_data_member_in_union) << Name; 6464 // We conservatively disallow static data members in anonymous structs. 6465 else if (!RD->getDeclName()) 6466 Diag(D.getIdentifierLoc(), 6467 diag::err_static_data_member_not_allowed_in_anon_struct) 6468 << Name << RD->isUnion(); 6469 } 6470 } 6471 6472 // Match up the template parameter lists with the scope specifier, then 6473 // determine whether we have a template or a template specialization. 6474 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6475 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6476 D.getCXXScopeSpec(), 6477 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6478 ? D.getName().TemplateId 6479 : nullptr, 6480 TemplateParamLists, 6481 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6482 6483 if (TemplateParams) { 6484 if (!TemplateParams->size() && 6485 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6486 // There is an extraneous 'template<>' for this variable. Complain 6487 // about it, but allow the declaration of the variable. 6488 Diag(TemplateParams->getTemplateLoc(), 6489 diag::err_template_variable_noparams) 6490 << II 6491 << SourceRange(TemplateParams->getTemplateLoc(), 6492 TemplateParams->getRAngleLoc()); 6493 TemplateParams = nullptr; 6494 } else { 6495 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6496 // This is an explicit specialization or a partial specialization. 6497 // FIXME: Check that we can declare a specialization here. 6498 IsVariableTemplateSpecialization = true; 6499 IsPartialSpecialization = TemplateParams->size() > 0; 6500 } else { // if (TemplateParams->size() > 0) 6501 // This is a template declaration. 6502 IsVariableTemplate = true; 6503 6504 // Check that we can declare a template here. 6505 if (CheckTemplateDeclScope(S, TemplateParams)) 6506 return nullptr; 6507 6508 // Only C++1y supports variable templates (N3651). 6509 Diag(D.getIdentifierLoc(), 6510 getLangOpts().CPlusPlus14 6511 ? diag::warn_cxx11_compat_variable_template 6512 : diag::ext_variable_template); 6513 } 6514 } 6515 } else { 6516 assert((Invalid || 6517 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6518 "should have a 'template<>' for this decl"); 6519 } 6520 6521 if (IsVariableTemplateSpecialization) { 6522 SourceLocation TemplateKWLoc = 6523 TemplateParamLists.size() > 0 6524 ? TemplateParamLists[0]->getTemplateLoc() 6525 : SourceLocation(); 6526 DeclResult Res = ActOnVarTemplateSpecialization( 6527 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6528 IsPartialSpecialization); 6529 if (Res.isInvalid()) 6530 return nullptr; 6531 NewVD = cast<VarDecl>(Res.get()); 6532 AddToScope = false; 6533 } else if (D.isDecompositionDeclarator()) { 6534 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6535 D.getIdentifierLoc(), R, TInfo, SC, 6536 Bindings); 6537 } else 6538 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6539 D.getIdentifierLoc(), II, R, TInfo, SC); 6540 6541 // If this is supposed to be a variable template, create it as such. 6542 if (IsVariableTemplate) { 6543 NewTemplate = 6544 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6545 TemplateParams, NewVD); 6546 NewVD->setDescribedVarTemplate(NewTemplate); 6547 } 6548 6549 // If this decl has an auto type in need of deduction, make a note of the 6550 // Decl so we can diagnose uses of it in its own initializer. 6551 if (R->getContainedDeducedType()) 6552 ParsingInitForAutoVars.insert(NewVD); 6553 6554 if (D.isInvalidType() || Invalid) { 6555 NewVD->setInvalidDecl(); 6556 if (NewTemplate) 6557 NewTemplate->setInvalidDecl(); 6558 } 6559 6560 SetNestedNameSpecifier(NewVD, D); 6561 6562 // If we have any template parameter lists that don't directly belong to 6563 // the variable (matching the scope specifier), store them. 6564 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6565 if (TemplateParamLists.size() > VDTemplateParamLists) 6566 NewVD->setTemplateParameterListsInfo( 6567 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6568 6569 if (D.getDeclSpec().isConstexprSpecified()) { 6570 NewVD->setConstexpr(true); 6571 // C++1z [dcl.spec.constexpr]p1: 6572 // A static data member declared with the constexpr specifier is 6573 // implicitly an inline variable. 6574 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6575 NewVD->setImplicitlyInline(); 6576 } 6577 } 6578 6579 if (D.getDeclSpec().isInlineSpecified()) { 6580 if (!getLangOpts().CPlusPlus) { 6581 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6582 << 0; 6583 } else if (CurContext->isFunctionOrMethod()) { 6584 // 'inline' is not allowed on block scope variable declaration. 6585 Diag(D.getDeclSpec().getInlineSpecLoc(), 6586 diag::err_inline_declaration_block_scope) << Name 6587 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6588 } else { 6589 Diag(D.getDeclSpec().getInlineSpecLoc(), 6590 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6591 : diag::ext_inline_variable); 6592 NewVD->setInlineSpecified(); 6593 } 6594 } 6595 6596 // Set the lexical context. If the declarator has a C++ scope specifier, the 6597 // lexical context will be different from the semantic context. 6598 NewVD->setLexicalDeclContext(CurContext); 6599 if (NewTemplate) 6600 NewTemplate->setLexicalDeclContext(CurContext); 6601 6602 if (IsLocalExternDecl) { 6603 if (D.isDecompositionDeclarator()) 6604 for (auto *B : Bindings) 6605 B->setLocalExternDecl(); 6606 else 6607 NewVD->setLocalExternDecl(); 6608 } 6609 6610 bool EmitTLSUnsupportedError = false; 6611 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6612 // C++11 [dcl.stc]p4: 6613 // When thread_local is applied to a variable of block scope the 6614 // storage-class-specifier static is implied if it does not appear 6615 // explicitly. 6616 // Core issue: 'static' is not implied if the variable is declared 6617 // 'extern'. 6618 if (NewVD->hasLocalStorage() && 6619 (SCSpec != DeclSpec::SCS_unspecified || 6620 TSCS != DeclSpec::TSCS_thread_local || 6621 !DC->isFunctionOrMethod())) 6622 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6623 diag::err_thread_non_global) 6624 << DeclSpec::getSpecifierName(TSCS); 6625 else if (!Context.getTargetInfo().isTLSSupported()) { 6626 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6627 // Postpone error emission until we've collected attributes required to 6628 // figure out whether it's a host or device variable and whether the 6629 // error should be ignored. 6630 EmitTLSUnsupportedError = true; 6631 // We still need to mark the variable as TLS so it shows up in AST with 6632 // proper storage class for other tools to use even if we're not going 6633 // to emit any code for it. 6634 NewVD->setTSCSpec(TSCS); 6635 } else 6636 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6637 diag::err_thread_unsupported); 6638 } else 6639 NewVD->setTSCSpec(TSCS); 6640 } 6641 6642 // C99 6.7.4p3 6643 // An inline definition of a function with external linkage shall 6644 // not contain a definition of a modifiable object with static or 6645 // thread storage duration... 6646 // We only apply this when the function is required to be defined 6647 // elsewhere, i.e. when the function is not 'extern inline'. Note 6648 // that a local variable with thread storage duration still has to 6649 // be marked 'static'. Also note that it's possible to get these 6650 // semantics in C++ using __attribute__((gnu_inline)). 6651 if (SC == SC_Static && S->getFnParent() != nullptr && 6652 !NewVD->getType().isConstQualified()) { 6653 FunctionDecl *CurFD = getCurFunctionDecl(); 6654 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6655 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6656 diag::warn_static_local_in_extern_inline); 6657 MaybeSuggestAddingStaticToDecl(CurFD); 6658 } 6659 } 6660 6661 if (D.getDeclSpec().isModulePrivateSpecified()) { 6662 if (IsVariableTemplateSpecialization) 6663 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6664 << (IsPartialSpecialization ? 1 : 0) 6665 << FixItHint::CreateRemoval( 6666 D.getDeclSpec().getModulePrivateSpecLoc()); 6667 else if (IsMemberSpecialization) 6668 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6669 << 2 6670 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6671 else if (NewVD->hasLocalStorage()) 6672 Diag(NewVD->getLocation(), diag::err_module_private_local) 6673 << 0 << NewVD->getDeclName() 6674 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6675 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6676 else { 6677 NewVD->setModulePrivate(); 6678 if (NewTemplate) 6679 NewTemplate->setModulePrivate(); 6680 for (auto *B : Bindings) 6681 B->setModulePrivate(); 6682 } 6683 } 6684 6685 // Handle attributes prior to checking for duplicates in MergeVarDecl 6686 ProcessDeclAttributes(S, NewVD, D); 6687 6688 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6689 if (EmitTLSUnsupportedError && 6690 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6691 (getLangOpts().OpenMPIsDevice && 6692 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6693 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6694 diag::err_thread_unsupported); 6695 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6696 // storage [duration]." 6697 if (SC == SC_None && S->getFnParent() != nullptr && 6698 (NewVD->hasAttr<CUDASharedAttr>() || 6699 NewVD->hasAttr<CUDAConstantAttr>())) { 6700 NewVD->setStorageClass(SC_Static); 6701 } 6702 } 6703 6704 // Ensure that dllimport globals without explicit storage class are treated as 6705 // extern. The storage class is set above using parsed attributes. Now we can 6706 // check the VarDecl itself. 6707 assert(!NewVD->hasAttr<DLLImportAttr>() || 6708 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6709 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6710 6711 // In auto-retain/release, infer strong retension for variables of 6712 // retainable type. 6713 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6714 NewVD->setInvalidDecl(); 6715 6716 // Handle GNU asm-label extension (encoded as an attribute). 6717 if (Expr *E = (Expr*)D.getAsmLabel()) { 6718 // The parser guarantees this is a string. 6719 StringLiteral *SE = cast<StringLiteral>(E); 6720 StringRef Label = SE->getString(); 6721 if (S->getFnParent() != nullptr) { 6722 switch (SC) { 6723 case SC_None: 6724 case SC_Auto: 6725 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6726 break; 6727 case SC_Register: 6728 // Local Named register 6729 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6730 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6731 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6732 break; 6733 case SC_Static: 6734 case SC_Extern: 6735 case SC_PrivateExtern: 6736 break; 6737 } 6738 } else if (SC == SC_Register) { 6739 // Global Named register 6740 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6741 const auto &TI = Context.getTargetInfo(); 6742 bool HasSizeMismatch; 6743 6744 if (!TI.isValidGCCRegisterName(Label)) 6745 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6746 else if (!TI.validateGlobalRegisterVariable(Label, 6747 Context.getTypeSize(R), 6748 HasSizeMismatch)) 6749 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6750 else if (HasSizeMismatch) 6751 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6752 } 6753 6754 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6755 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6756 NewVD->setInvalidDecl(true); 6757 } 6758 } 6759 6760 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6761 Context, Label, 0)); 6762 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6763 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6764 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6765 if (I != ExtnameUndeclaredIdentifiers.end()) { 6766 if (isDeclExternC(NewVD)) { 6767 NewVD->addAttr(I->second); 6768 ExtnameUndeclaredIdentifiers.erase(I); 6769 } else 6770 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6771 << /*Variable*/1 << NewVD; 6772 } 6773 } 6774 6775 // Find the shadowed declaration before filtering for scope. 6776 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6777 ? getShadowedDeclaration(NewVD, Previous) 6778 : nullptr; 6779 6780 // Don't consider existing declarations that are in a different 6781 // scope and are out-of-semantic-context declarations (if the new 6782 // declaration has linkage). 6783 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6784 D.getCXXScopeSpec().isNotEmpty() || 6785 IsMemberSpecialization || 6786 IsVariableTemplateSpecialization); 6787 6788 // Check whether the previous declaration is in the same block scope. This 6789 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6790 if (getLangOpts().CPlusPlus && 6791 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6792 NewVD->setPreviousDeclInSameBlockScope( 6793 Previous.isSingleResult() && !Previous.isShadowed() && 6794 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6795 6796 if (!getLangOpts().CPlusPlus) { 6797 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6798 } else { 6799 // If this is an explicit specialization of a static data member, check it. 6800 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6801 CheckMemberSpecialization(NewVD, Previous)) 6802 NewVD->setInvalidDecl(); 6803 6804 // Merge the decl with the existing one if appropriate. 6805 if (!Previous.empty()) { 6806 if (Previous.isSingleResult() && 6807 isa<FieldDecl>(Previous.getFoundDecl()) && 6808 D.getCXXScopeSpec().isSet()) { 6809 // The user tried to define a non-static data member 6810 // out-of-line (C++ [dcl.meaning]p1). 6811 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6812 << D.getCXXScopeSpec().getRange(); 6813 Previous.clear(); 6814 NewVD->setInvalidDecl(); 6815 } 6816 } else if (D.getCXXScopeSpec().isSet()) { 6817 // No previous declaration in the qualifying scope. 6818 Diag(D.getIdentifierLoc(), diag::err_no_member) 6819 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6820 << D.getCXXScopeSpec().getRange(); 6821 NewVD->setInvalidDecl(); 6822 } 6823 6824 if (!IsVariableTemplateSpecialization) 6825 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6826 6827 if (NewTemplate) { 6828 VarTemplateDecl *PrevVarTemplate = 6829 NewVD->getPreviousDecl() 6830 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6831 : nullptr; 6832 6833 // Check the template parameter list of this declaration, possibly 6834 // merging in the template parameter list from the previous variable 6835 // template declaration. 6836 if (CheckTemplateParameterList( 6837 TemplateParams, 6838 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6839 : nullptr, 6840 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6841 DC->isDependentContext()) 6842 ? TPC_ClassTemplateMember 6843 : TPC_VarTemplate)) 6844 NewVD->setInvalidDecl(); 6845 6846 // If we are providing an explicit specialization of a static variable 6847 // template, make a note of that. 6848 if (PrevVarTemplate && 6849 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6850 PrevVarTemplate->setMemberSpecialization(); 6851 } 6852 } 6853 6854 // Diagnose shadowed variables iff this isn't a redeclaration. 6855 if (ShadowedDecl && !D.isRedeclaration()) 6856 CheckShadow(NewVD, ShadowedDecl, Previous); 6857 6858 ProcessPragmaWeak(S, NewVD); 6859 6860 // If this is the first declaration of an extern C variable, update 6861 // the map of such variables. 6862 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6863 isIncompleteDeclExternC(*this, NewVD)) 6864 RegisterLocallyScopedExternCDecl(NewVD, S); 6865 6866 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6867 Decl *ManglingContextDecl; 6868 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6869 NewVD->getDeclContext(), ManglingContextDecl)) { 6870 Context.setManglingNumber( 6871 NewVD, MCtx->getManglingNumber( 6872 NewVD, getMSManglingNumber(getLangOpts(), S))); 6873 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6874 } 6875 } 6876 6877 // Special handling of variable named 'main'. 6878 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6879 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6880 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6881 6882 // C++ [basic.start.main]p3 6883 // A program that declares a variable main at global scope is ill-formed. 6884 if (getLangOpts().CPlusPlus) 6885 Diag(D.getLocStart(), diag::err_main_global_variable); 6886 6887 // In C, and external-linkage variable named main results in undefined 6888 // behavior. 6889 else if (NewVD->hasExternalFormalLinkage()) 6890 Diag(D.getLocStart(), diag::warn_main_redefined); 6891 } 6892 6893 if (D.isRedeclaration() && !Previous.empty()) { 6894 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6895 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6896 D.isFunctionDefinition()); 6897 } 6898 6899 if (NewTemplate) { 6900 if (NewVD->isInvalidDecl()) 6901 NewTemplate->setInvalidDecl(); 6902 ActOnDocumentableDecl(NewTemplate); 6903 return NewTemplate; 6904 } 6905 6906 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6907 CompleteMemberSpecialization(NewVD, Previous); 6908 6909 return NewVD; 6910 } 6911 6912 /// Enum describing the %select options in diag::warn_decl_shadow. 6913 enum ShadowedDeclKind { 6914 SDK_Local, 6915 SDK_Global, 6916 SDK_StaticMember, 6917 SDK_Field, 6918 SDK_Typedef, 6919 SDK_Using 6920 }; 6921 6922 /// Determine what kind of declaration we're shadowing. 6923 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6924 const DeclContext *OldDC) { 6925 if (isa<TypeAliasDecl>(ShadowedDecl)) 6926 return SDK_Using; 6927 else if (isa<TypedefDecl>(ShadowedDecl)) 6928 return SDK_Typedef; 6929 else if (isa<RecordDecl>(OldDC)) 6930 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6931 6932 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6933 } 6934 6935 /// Return the location of the capture if the given lambda captures the given 6936 /// variable \p VD, or an invalid source location otherwise. 6937 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6938 const VarDecl *VD) { 6939 for (const Capture &Capture : LSI->Captures) { 6940 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6941 return Capture.getLocation(); 6942 } 6943 return SourceLocation(); 6944 } 6945 6946 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6947 const LookupResult &R) { 6948 // Only diagnose if we're shadowing an unambiguous field or variable. 6949 if (R.getResultKind() != LookupResult::Found) 6950 return false; 6951 6952 // Return false if warning is ignored. 6953 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6954 } 6955 6956 /// \brief Return the declaration shadowed by the given variable \p D, or null 6957 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6958 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6959 const LookupResult &R) { 6960 if (!shouldWarnIfShadowedDecl(Diags, R)) 6961 return nullptr; 6962 6963 // Don't diagnose declarations at file scope. 6964 if (D->hasGlobalStorage()) 6965 return nullptr; 6966 6967 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6968 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6969 ? ShadowedDecl 6970 : nullptr; 6971 } 6972 6973 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6974 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6975 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6976 const LookupResult &R) { 6977 // Don't warn if typedef declaration is part of a class 6978 if (D->getDeclContext()->isRecord()) 6979 return nullptr; 6980 6981 if (!shouldWarnIfShadowedDecl(Diags, R)) 6982 return nullptr; 6983 6984 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6985 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6986 } 6987 6988 /// \brief Diagnose variable or built-in function shadowing. Implements 6989 /// -Wshadow. 6990 /// 6991 /// This method is called whenever a VarDecl is added to a "useful" 6992 /// scope. 6993 /// 6994 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6995 /// \param R the lookup of the name 6996 /// 6997 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6998 const LookupResult &R) { 6999 DeclContext *NewDC = D->getDeclContext(); 7000 7001 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7002 // Fields are not shadowed by variables in C++ static methods. 7003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7004 if (MD->isStatic()) 7005 return; 7006 7007 // Fields shadowed by constructor parameters are a special case. Usually 7008 // the constructor initializes the field with the parameter. 7009 if (isa<CXXConstructorDecl>(NewDC)) 7010 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7011 // Remember that this was shadowed so we can either warn about its 7012 // modification or its existence depending on warning settings. 7013 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7014 return; 7015 } 7016 } 7017 7018 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7019 if (shadowedVar->isExternC()) { 7020 // For shadowing external vars, make sure that we point to the global 7021 // declaration, not a locally scoped extern declaration. 7022 for (auto I : shadowedVar->redecls()) 7023 if (I->isFileVarDecl()) { 7024 ShadowedDecl = I; 7025 break; 7026 } 7027 } 7028 7029 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7030 7031 unsigned WarningDiag = diag::warn_decl_shadow; 7032 SourceLocation CaptureLoc; 7033 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7034 isa<CXXMethodDecl>(NewDC)) { 7035 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7036 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7037 if (RD->getLambdaCaptureDefault() == LCD_None) { 7038 // Try to avoid warnings for lambdas with an explicit capture list. 7039 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7040 // Warn only when the lambda captures the shadowed decl explicitly. 7041 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7042 if (CaptureLoc.isInvalid()) 7043 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7044 } else { 7045 // Remember that this was shadowed so we can avoid the warning if the 7046 // shadowed decl isn't captured and the warning settings allow it. 7047 cast<LambdaScopeInfo>(getCurFunction()) 7048 ->ShadowingDecls.push_back( 7049 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7050 return; 7051 } 7052 } 7053 7054 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7055 // A variable can't shadow a local variable in an enclosing scope, if 7056 // they are separated by a non-capturing declaration context. 7057 for (DeclContext *ParentDC = NewDC; 7058 ParentDC && !ParentDC->Equals(OldDC); 7059 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7060 // Only block literals, captured statements, and lambda expressions 7061 // can capture; other scopes don't. 7062 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7063 !isLambdaCallOperator(ParentDC)) { 7064 return; 7065 } 7066 } 7067 } 7068 } 7069 } 7070 7071 // Only warn about certain kinds of shadowing for class members. 7072 if (NewDC && NewDC->isRecord()) { 7073 // In particular, don't warn about shadowing non-class members. 7074 if (!OldDC->isRecord()) 7075 return; 7076 7077 // TODO: should we warn about static data members shadowing 7078 // static data members from base classes? 7079 7080 // TODO: don't diagnose for inaccessible shadowed members. 7081 // This is hard to do perfectly because we might friend the 7082 // shadowing context, but that's just a false negative. 7083 } 7084 7085 7086 DeclarationName Name = R.getLookupName(); 7087 7088 // Emit warning and note. 7089 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7090 return; 7091 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7092 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7093 if (!CaptureLoc.isInvalid()) 7094 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7095 << Name << /*explicitly*/ 1; 7096 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7097 } 7098 7099 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7100 /// when these variables are captured by the lambda. 7101 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7102 for (const auto &Shadow : LSI->ShadowingDecls) { 7103 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7104 // Try to avoid the warning when the shadowed decl isn't captured. 7105 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7106 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7107 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7108 ? diag::warn_decl_shadow_uncaptured_local 7109 : diag::warn_decl_shadow) 7110 << Shadow.VD->getDeclName() 7111 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7112 if (!CaptureLoc.isInvalid()) 7113 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7114 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7115 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7116 } 7117 } 7118 7119 /// \brief Check -Wshadow without the advantage of a previous lookup. 7120 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7121 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7122 return; 7123 7124 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7125 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7126 LookupName(R, S); 7127 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7128 CheckShadow(D, ShadowedDecl, R); 7129 } 7130 7131 /// Check if 'E', which is an expression that is about to be modified, refers 7132 /// to a constructor parameter that shadows a field. 7133 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7134 // Quickly ignore expressions that can't be shadowing ctor parameters. 7135 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7136 return; 7137 E = E->IgnoreParenImpCasts(); 7138 auto *DRE = dyn_cast<DeclRefExpr>(E); 7139 if (!DRE) 7140 return; 7141 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7142 auto I = ShadowingDecls.find(D); 7143 if (I == ShadowingDecls.end()) 7144 return; 7145 const NamedDecl *ShadowedDecl = I->second; 7146 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7147 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7148 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7149 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7150 7151 // Avoid issuing multiple warnings about the same decl. 7152 ShadowingDecls.erase(I); 7153 } 7154 7155 /// Check for conflict between this global or extern "C" declaration and 7156 /// previous global or extern "C" declarations. This is only used in C++. 7157 template<typename T> 7158 static bool checkGlobalOrExternCConflict( 7159 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7160 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7161 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7162 7163 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7164 // The common case: this global doesn't conflict with any extern "C" 7165 // declaration. 7166 return false; 7167 } 7168 7169 if (Prev) { 7170 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7171 // Both the old and new declarations have C language linkage. This is a 7172 // redeclaration. 7173 Previous.clear(); 7174 Previous.addDecl(Prev); 7175 return true; 7176 } 7177 7178 // This is a global, non-extern "C" declaration, and there is a previous 7179 // non-global extern "C" declaration. Diagnose if this is a variable 7180 // declaration. 7181 if (!isa<VarDecl>(ND)) 7182 return false; 7183 } else { 7184 // The declaration is extern "C". Check for any declaration in the 7185 // translation unit which might conflict. 7186 if (IsGlobal) { 7187 // We have already performed the lookup into the translation unit. 7188 IsGlobal = false; 7189 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7190 I != E; ++I) { 7191 if (isa<VarDecl>(*I)) { 7192 Prev = *I; 7193 break; 7194 } 7195 } 7196 } else { 7197 DeclContext::lookup_result R = 7198 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7199 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7200 I != E; ++I) { 7201 if (isa<VarDecl>(*I)) { 7202 Prev = *I; 7203 break; 7204 } 7205 // FIXME: If we have any other entity with this name in global scope, 7206 // the declaration is ill-formed, but that is a defect: it breaks the 7207 // 'stat' hack, for instance. Only variables can have mangled name 7208 // clashes with extern "C" declarations, so only they deserve a 7209 // diagnostic. 7210 } 7211 } 7212 7213 if (!Prev) 7214 return false; 7215 } 7216 7217 // Use the first declaration's location to ensure we point at something which 7218 // is lexically inside an extern "C" linkage-spec. 7219 assert(Prev && "should have found a previous declaration to diagnose"); 7220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7221 Prev = FD->getFirstDecl(); 7222 else 7223 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7224 7225 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7226 << IsGlobal << ND; 7227 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7228 << IsGlobal; 7229 return false; 7230 } 7231 7232 /// Apply special rules for handling extern "C" declarations. Returns \c true 7233 /// if we have found that this is a redeclaration of some prior entity. 7234 /// 7235 /// Per C++ [dcl.link]p6: 7236 /// Two declarations [for a function or variable] with C language linkage 7237 /// with the same name that appear in different scopes refer to the same 7238 /// [entity]. An entity with C language linkage shall not be declared with 7239 /// the same name as an entity in global scope. 7240 template<typename T> 7241 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7242 LookupResult &Previous) { 7243 if (!S.getLangOpts().CPlusPlus) { 7244 // In C, when declaring a global variable, look for a corresponding 'extern' 7245 // variable declared in function scope. We don't need this in C++, because 7246 // we find local extern decls in the surrounding file-scope DeclContext. 7247 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7248 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7249 Previous.clear(); 7250 Previous.addDecl(Prev); 7251 return true; 7252 } 7253 } 7254 return false; 7255 } 7256 7257 // A declaration in the translation unit can conflict with an extern "C" 7258 // declaration. 7259 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7260 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7261 7262 // An extern "C" declaration can conflict with a declaration in the 7263 // translation unit or can be a redeclaration of an extern "C" declaration 7264 // in another scope. 7265 if (isIncompleteDeclExternC(S,ND)) 7266 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7267 7268 // Neither global nor extern "C": nothing to do. 7269 return false; 7270 } 7271 7272 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7273 // If the decl is already known invalid, don't check it. 7274 if (NewVD->isInvalidDecl()) 7275 return; 7276 7277 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7278 QualType T = TInfo->getType(); 7279 7280 // Defer checking an 'auto' type until its initializer is attached. 7281 if (T->isUndeducedType()) 7282 return; 7283 7284 if (NewVD->hasAttrs()) 7285 CheckAlignasUnderalignment(NewVD); 7286 7287 if (T->isObjCObjectType()) { 7288 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7289 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7290 T = Context.getObjCObjectPointerType(T); 7291 NewVD->setType(T); 7292 } 7293 7294 // Emit an error if an address space was applied to decl with local storage. 7295 // This includes arrays of objects with address space qualifiers, but not 7296 // automatic variables that point to other address spaces. 7297 // ISO/IEC TR 18037 S5.1.2 7298 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7299 T.getAddressSpace() != LangAS::Default) { 7300 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7301 NewVD->setInvalidDecl(); 7302 return; 7303 } 7304 7305 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7306 // scope. 7307 if (getLangOpts().OpenCLVersion == 120 && 7308 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7309 NewVD->isStaticLocal()) { 7310 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7311 NewVD->setInvalidDecl(); 7312 return; 7313 } 7314 7315 if (getLangOpts().OpenCL) { 7316 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7317 if (NewVD->hasAttr<BlocksAttr>()) { 7318 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7319 return; 7320 } 7321 7322 if (T->isBlockPointerType()) { 7323 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7324 // can't use 'extern' storage class. 7325 if (!T.isConstQualified()) { 7326 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7327 << 0 /*const*/; 7328 NewVD->setInvalidDecl(); 7329 return; 7330 } 7331 if (NewVD->hasExternalStorage()) { 7332 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7333 NewVD->setInvalidDecl(); 7334 return; 7335 } 7336 } 7337 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7338 // __constant address space. 7339 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7340 // variables inside a function can also be declared in the global 7341 // address space. 7342 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7343 NewVD->hasExternalStorage()) { 7344 if (!T->isSamplerT() && 7345 !(T.getAddressSpace() == LangAS::opencl_constant || 7346 (T.getAddressSpace() == LangAS::opencl_global && 7347 getLangOpts().OpenCLVersion == 200))) { 7348 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7349 if (getLangOpts().OpenCLVersion == 200) 7350 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7351 << Scope << "global or constant"; 7352 else 7353 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7354 << Scope << "constant"; 7355 NewVD->setInvalidDecl(); 7356 return; 7357 } 7358 } else { 7359 if (T.getAddressSpace() == LangAS::opencl_global) { 7360 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7361 << 1 /*is any function*/ << "global"; 7362 NewVD->setInvalidDecl(); 7363 return; 7364 } 7365 if (T.getAddressSpace() == LangAS::opencl_constant || 7366 T.getAddressSpace() == LangAS::opencl_local) { 7367 FunctionDecl *FD = getCurFunctionDecl(); 7368 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7369 // in functions. 7370 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7371 if (T.getAddressSpace() == LangAS::opencl_constant) 7372 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7373 << 0 /*non-kernel only*/ << "constant"; 7374 else 7375 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7376 << 0 /*non-kernel only*/ << "local"; 7377 NewVD->setInvalidDecl(); 7378 return; 7379 } 7380 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7381 // in the outermost scope of a kernel function. 7382 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7383 if (!getCurScope()->isFunctionScope()) { 7384 if (T.getAddressSpace() == LangAS::opencl_constant) 7385 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7386 << "constant"; 7387 else 7388 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7389 << "local"; 7390 NewVD->setInvalidDecl(); 7391 return; 7392 } 7393 } 7394 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7395 // Do not allow other address spaces on automatic variable. 7396 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7397 NewVD->setInvalidDecl(); 7398 return; 7399 } 7400 } 7401 } 7402 7403 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7404 && !NewVD->hasAttr<BlocksAttr>()) { 7405 if (getLangOpts().getGC() != LangOptions::NonGC) 7406 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7407 else { 7408 assert(!getLangOpts().ObjCAutoRefCount); 7409 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7410 } 7411 } 7412 7413 bool isVM = T->isVariablyModifiedType(); 7414 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7415 NewVD->hasAttr<BlocksAttr>()) 7416 setFunctionHasBranchProtectedScope(); 7417 7418 if ((isVM && NewVD->hasLinkage()) || 7419 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7420 bool SizeIsNegative; 7421 llvm::APSInt Oversized; 7422 TypeSourceInfo *FixedTInfo = 7423 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7424 SizeIsNegative, Oversized); 7425 if (!FixedTInfo && T->isVariableArrayType()) { 7426 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7427 // FIXME: This won't give the correct result for 7428 // int a[10][n]; 7429 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7430 7431 if (NewVD->isFileVarDecl()) 7432 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7433 << SizeRange; 7434 else if (NewVD->isStaticLocal()) 7435 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7436 << SizeRange; 7437 else 7438 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7439 << SizeRange; 7440 NewVD->setInvalidDecl(); 7441 return; 7442 } 7443 7444 if (!FixedTInfo) { 7445 if (NewVD->isFileVarDecl()) 7446 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7447 else 7448 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7449 NewVD->setInvalidDecl(); 7450 return; 7451 } 7452 7453 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7454 NewVD->setType(FixedTInfo->getType()); 7455 NewVD->setTypeSourceInfo(FixedTInfo); 7456 } 7457 7458 if (T->isVoidType()) { 7459 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7460 // of objects and functions. 7461 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7462 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7463 << T; 7464 NewVD->setInvalidDecl(); 7465 return; 7466 } 7467 } 7468 7469 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7470 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7471 NewVD->setInvalidDecl(); 7472 return; 7473 } 7474 7475 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7476 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7477 NewVD->setInvalidDecl(); 7478 return; 7479 } 7480 7481 if (NewVD->isConstexpr() && !T->isDependentType() && 7482 RequireLiteralType(NewVD->getLocation(), T, 7483 diag::err_constexpr_var_non_literal)) { 7484 NewVD->setInvalidDecl(); 7485 return; 7486 } 7487 } 7488 7489 /// \brief Perform semantic checking on a newly-created variable 7490 /// declaration. 7491 /// 7492 /// This routine performs all of the type-checking required for a 7493 /// variable declaration once it has been built. It is used both to 7494 /// check variables after they have been parsed and their declarators 7495 /// have been translated into a declaration, and to check variables 7496 /// that have been instantiated from a template. 7497 /// 7498 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7499 /// 7500 /// Returns true if the variable declaration is a redeclaration. 7501 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7502 CheckVariableDeclarationType(NewVD); 7503 7504 // If the decl is already known invalid, don't check it. 7505 if (NewVD->isInvalidDecl()) 7506 return false; 7507 7508 // If we did not find anything by this name, look for a non-visible 7509 // extern "C" declaration with the same name. 7510 if (Previous.empty() && 7511 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7512 Previous.setShadowed(); 7513 7514 if (!Previous.empty()) { 7515 MergeVarDecl(NewVD, Previous); 7516 return true; 7517 } 7518 return false; 7519 } 7520 7521 namespace { 7522 struct FindOverriddenMethod { 7523 Sema *S; 7524 CXXMethodDecl *Method; 7525 7526 /// Member lookup function that determines whether a given C++ 7527 /// method overrides a method in a base class, to be used with 7528 /// CXXRecordDecl::lookupInBases(). 7529 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7530 RecordDecl *BaseRecord = 7531 Specifier->getType()->getAs<RecordType>()->getDecl(); 7532 7533 DeclarationName Name = Method->getDeclName(); 7534 7535 // FIXME: Do we care about other names here too? 7536 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7537 // We really want to find the base class destructor here. 7538 QualType T = S->Context.getTypeDeclType(BaseRecord); 7539 CanQualType CT = S->Context.getCanonicalType(T); 7540 7541 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7542 } 7543 7544 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7545 Path.Decls = Path.Decls.slice(1)) { 7546 NamedDecl *D = Path.Decls.front(); 7547 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7548 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7549 return true; 7550 } 7551 } 7552 7553 return false; 7554 } 7555 }; 7556 7557 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7558 } // end anonymous namespace 7559 7560 /// \brief Report an error regarding overriding, along with any relevant 7561 /// overridden methods. 7562 /// 7563 /// \param DiagID the primary error to report. 7564 /// \param MD the overriding method. 7565 /// \param OEK which overrides to include as notes. 7566 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7567 OverrideErrorKind OEK = OEK_All) { 7568 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7569 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7570 // This check (& the OEK parameter) could be replaced by a predicate, but 7571 // without lambdas that would be overkill. This is still nicer than writing 7572 // out the diag loop 3 times. 7573 if ((OEK == OEK_All) || 7574 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7575 (OEK == OEK_Deleted && O->isDeleted())) 7576 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7577 } 7578 } 7579 7580 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7581 /// and if so, check that it's a valid override and remember it. 7582 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7583 // Look for methods in base classes that this method might override. 7584 CXXBasePaths Paths; 7585 FindOverriddenMethod FOM; 7586 FOM.Method = MD; 7587 FOM.S = this; 7588 bool hasDeletedOverridenMethods = false; 7589 bool hasNonDeletedOverridenMethods = false; 7590 bool AddedAny = false; 7591 if (DC->lookupInBases(FOM, Paths)) { 7592 for (auto *I : Paths.found_decls()) { 7593 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7594 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7595 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7596 !CheckOverridingFunctionAttributes(MD, OldMD) && 7597 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7598 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7599 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7600 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7601 AddedAny = true; 7602 } 7603 } 7604 } 7605 } 7606 7607 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7608 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7609 } 7610 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7611 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7612 } 7613 7614 return AddedAny; 7615 } 7616 7617 namespace { 7618 // Struct for holding all of the extra arguments needed by 7619 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7620 struct ActOnFDArgs { 7621 Scope *S; 7622 Declarator &D; 7623 MultiTemplateParamsArg TemplateParamLists; 7624 bool AddToScope; 7625 }; 7626 } // end anonymous namespace 7627 7628 namespace { 7629 7630 // Callback to only accept typo corrections that have a non-zero edit distance. 7631 // Also only accept corrections that have the same parent decl. 7632 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7633 public: 7634 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7635 CXXRecordDecl *Parent) 7636 : Context(Context), OriginalFD(TypoFD), 7637 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7638 7639 bool ValidateCandidate(const TypoCorrection &candidate) override { 7640 if (candidate.getEditDistance() == 0) 7641 return false; 7642 7643 SmallVector<unsigned, 1> MismatchedParams; 7644 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7645 CDeclEnd = candidate.end(); 7646 CDecl != CDeclEnd; ++CDecl) { 7647 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7648 7649 if (FD && !FD->hasBody() && 7650 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7651 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7652 CXXRecordDecl *Parent = MD->getParent(); 7653 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7654 return true; 7655 } else if (!ExpectedParent) { 7656 return true; 7657 } 7658 } 7659 } 7660 7661 return false; 7662 } 7663 7664 private: 7665 ASTContext &Context; 7666 FunctionDecl *OriginalFD; 7667 CXXRecordDecl *ExpectedParent; 7668 }; 7669 7670 } // end anonymous namespace 7671 7672 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7673 TypoCorrectedFunctionDefinitions.insert(F); 7674 } 7675 7676 /// \brief Generate diagnostics for an invalid function redeclaration. 7677 /// 7678 /// This routine handles generating the diagnostic messages for an invalid 7679 /// function redeclaration, including finding possible similar declarations 7680 /// or performing typo correction if there are no previous declarations with 7681 /// the same name. 7682 /// 7683 /// Returns a NamedDecl iff typo correction was performed and substituting in 7684 /// the new declaration name does not cause new errors. 7685 static NamedDecl *DiagnoseInvalidRedeclaration( 7686 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7687 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7688 DeclarationName Name = NewFD->getDeclName(); 7689 DeclContext *NewDC = NewFD->getDeclContext(); 7690 SmallVector<unsigned, 1> MismatchedParams; 7691 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7692 TypoCorrection Correction; 7693 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7694 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7695 : diag::err_member_decl_does_not_match; 7696 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7697 IsLocalFriend ? Sema::LookupLocalFriendName 7698 : Sema::LookupOrdinaryName, 7699 Sema::ForVisibleRedeclaration); 7700 7701 NewFD->setInvalidDecl(); 7702 if (IsLocalFriend) 7703 SemaRef.LookupName(Prev, S); 7704 else 7705 SemaRef.LookupQualifiedName(Prev, NewDC); 7706 assert(!Prev.isAmbiguous() && 7707 "Cannot have an ambiguity in previous-declaration lookup"); 7708 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7709 if (!Prev.empty()) { 7710 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7711 Func != FuncEnd; ++Func) { 7712 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7713 if (FD && 7714 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7715 // Add 1 to the index so that 0 can mean the mismatch didn't 7716 // involve a parameter 7717 unsigned ParamNum = 7718 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7719 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7720 } 7721 } 7722 // If the qualified name lookup yielded nothing, try typo correction 7723 } else if ((Correction = SemaRef.CorrectTypo( 7724 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7725 &ExtraArgs.D.getCXXScopeSpec(), 7726 llvm::make_unique<DifferentNameValidatorCCC>( 7727 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7728 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7729 // Set up everything for the call to ActOnFunctionDeclarator 7730 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7731 ExtraArgs.D.getIdentifierLoc()); 7732 Previous.clear(); 7733 Previous.setLookupName(Correction.getCorrection()); 7734 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7735 CDeclEnd = Correction.end(); 7736 CDecl != CDeclEnd; ++CDecl) { 7737 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7738 if (FD && !FD->hasBody() && 7739 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7740 Previous.addDecl(FD); 7741 } 7742 } 7743 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7744 7745 NamedDecl *Result; 7746 // Retry building the function declaration with the new previous 7747 // declarations, and with errors suppressed. 7748 { 7749 // Trap errors. 7750 Sema::SFINAETrap Trap(SemaRef); 7751 7752 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7753 // pieces need to verify the typo-corrected C++ declaration and hopefully 7754 // eliminate the need for the parameter pack ExtraArgs. 7755 Result = SemaRef.ActOnFunctionDeclarator( 7756 ExtraArgs.S, ExtraArgs.D, 7757 Correction.getCorrectionDecl()->getDeclContext(), 7758 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7759 ExtraArgs.AddToScope); 7760 7761 if (Trap.hasErrorOccurred()) 7762 Result = nullptr; 7763 } 7764 7765 if (Result) { 7766 // Determine which correction we picked. 7767 Decl *Canonical = Result->getCanonicalDecl(); 7768 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7769 I != E; ++I) 7770 if ((*I)->getCanonicalDecl() == Canonical) 7771 Correction.setCorrectionDecl(*I); 7772 7773 // Let Sema know about the correction. 7774 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7775 SemaRef.diagnoseTypo( 7776 Correction, 7777 SemaRef.PDiag(IsLocalFriend 7778 ? diag::err_no_matching_local_friend_suggest 7779 : diag::err_member_decl_does_not_match_suggest) 7780 << Name << NewDC << IsDefinition); 7781 return Result; 7782 } 7783 7784 // Pretend the typo correction never occurred 7785 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7786 ExtraArgs.D.getIdentifierLoc()); 7787 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7788 Previous.clear(); 7789 Previous.setLookupName(Name); 7790 } 7791 7792 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7793 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7794 7795 bool NewFDisConst = false; 7796 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7797 NewFDisConst = NewMD->isConst(); 7798 7799 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7800 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7801 NearMatch != NearMatchEnd; ++NearMatch) { 7802 FunctionDecl *FD = NearMatch->first; 7803 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7804 bool FDisConst = MD && MD->isConst(); 7805 bool IsMember = MD || !IsLocalFriend; 7806 7807 // FIXME: These notes are poorly worded for the local friend case. 7808 if (unsigned Idx = NearMatch->second) { 7809 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7810 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7811 if (Loc.isInvalid()) Loc = FD->getLocation(); 7812 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7813 : diag::note_local_decl_close_param_match) 7814 << Idx << FDParam->getType() 7815 << NewFD->getParamDecl(Idx - 1)->getType(); 7816 } else if (FDisConst != NewFDisConst) { 7817 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7818 << NewFDisConst << FD->getSourceRange().getEnd(); 7819 } else 7820 SemaRef.Diag(FD->getLocation(), 7821 IsMember ? diag::note_member_def_close_match 7822 : diag::note_local_decl_close_match); 7823 } 7824 return nullptr; 7825 } 7826 7827 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7828 switch (D.getDeclSpec().getStorageClassSpec()) { 7829 default: llvm_unreachable("Unknown storage class!"); 7830 case DeclSpec::SCS_auto: 7831 case DeclSpec::SCS_register: 7832 case DeclSpec::SCS_mutable: 7833 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7834 diag::err_typecheck_sclass_func); 7835 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7836 D.setInvalidType(); 7837 break; 7838 case DeclSpec::SCS_unspecified: break; 7839 case DeclSpec::SCS_extern: 7840 if (D.getDeclSpec().isExternInLinkageSpec()) 7841 return SC_None; 7842 return SC_Extern; 7843 case DeclSpec::SCS_static: { 7844 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7845 // C99 6.7.1p5: 7846 // The declaration of an identifier for a function that has 7847 // block scope shall have no explicit storage-class specifier 7848 // other than extern 7849 // See also (C++ [dcl.stc]p4). 7850 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7851 diag::err_static_block_func); 7852 break; 7853 } else 7854 return SC_Static; 7855 } 7856 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7857 } 7858 7859 // No explicit storage class has already been returned 7860 return SC_None; 7861 } 7862 7863 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7864 DeclContext *DC, QualType &R, 7865 TypeSourceInfo *TInfo, 7866 StorageClass SC, 7867 bool &IsVirtualOkay) { 7868 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7869 DeclarationName Name = NameInfo.getName(); 7870 7871 FunctionDecl *NewFD = nullptr; 7872 bool isInline = D.getDeclSpec().isInlineSpecified(); 7873 7874 if (!SemaRef.getLangOpts().CPlusPlus) { 7875 // Determine whether the function was written with a 7876 // prototype. This true when: 7877 // - there is a prototype in the declarator, or 7878 // - the type R of the function is some kind of typedef or other non- 7879 // attributed reference to a type name (which eventually refers to a 7880 // function type). 7881 bool HasPrototype = 7882 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7883 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7884 7885 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7886 D.getLocStart(), NameInfo, R, 7887 TInfo, SC, isInline, 7888 HasPrototype, false); 7889 if (D.isInvalidType()) 7890 NewFD->setInvalidDecl(); 7891 7892 return NewFD; 7893 } 7894 7895 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7896 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7897 7898 // Check that the return type is not an abstract class type. 7899 // For record types, this is done by the AbstractClassUsageDiagnoser once 7900 // the class has been completely parsed. 7901 if (!DC->isRecord() && 7902 SemaRef.RequireNonAbstractType( 7903 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7904 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7905 D.setInvalidType(); 7906 7907 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7908 // This is a C++ constructor declaration. 7909 assert(DC->isRecord() && 7910 "Constructors can only be declared in a member context"); 7911 7912 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7913 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7914 D.getLocStart(), NameInfo, 7915 R, TInfo, isExplicit, isInline, 7916 /*isImplicitlyDeclared=*/false, 7917 isConstexpr); 7918 7919 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7920 // This is a C++ destructor declaration. 7921 if (DC->isRecord()) { 7922 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7923 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7924 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7925 SemaRef.Context, Record, 7926 D.getLocStart(), 7927 NameInfo, R, TInfo, isInline, 7928 /*isImplicitlyDeclared=*/false); 7929 7930 // If the class is complete, then we now create the implicit exception 7931 // specification. If the class is incomplete or dependent, we can't do 7932 // it yet. 7933 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7934 Record->getDefinition() && !Record->isBeingDefined() && 7935 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7936 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7937 } 7938 7939 IsVirtualOkay = true; 7940 return NewDD; 7941 7942 } else { 7943 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7944 D.setInvalidType(); 7945 7946 // Create a FunctionDecl to satisfy the function definition parsing 7947 // code path. 7948 return FunctionDecl::Create(SemaRef.Context, DC, 7949 D.getLocStart(), 7950 D.getIdentifierLoc(), Name, R, TInfo, 7951 SC, isInline, 7952 /*hasPrototype=*/true, isConstexpr); 7953 } 7954 7955 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7956 if (!DC->isRecord()) { 7957 SemaRef.Diag(D.getIdentifierLoc(), 7958 diag::err_conv_function_not_member); 7959 return nullptr; 7960 } 7961 7962 SemaRef.CheckConversionDeclarator(D, R, SC); 7963 IsVirtualOkay = true; 7964 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7965 D.getLocStart(), NameInfo, 7966 R, TInfo, isInline, isExplicit, 7967 isConstexpr, SourceLocation()); 7968 7969 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7970 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7971 7972 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7973 isExplicit, NameInfo, R, TInfo, 7974 D.getLocEnd()); 7975 } else if (DC->isRecord()) { 7976 // If the name of the function is the same as the name of the record, 7977 // then this must be an invalid constructor that has a return type. 7978 // (The parser checks for a return type and makes the declarator a 7979 // constructor if it has no return type). 7980 if (Name.getAsIdentifierInfo() && 7981 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7982 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7983 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7984 << SourceRange(D.getIdentifierLoc()); 7985 return nullptr; 7986 } 7987 7988 // This is a C++ method declaration. 7989 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7990 cast<CXXRecordDecl>(DC), 7991 D.getLocStart(), NameInfo, R, 7992 TInfo, SC, isInline, 7993 isConstexpr, SourceLocation()); 7994 IsVirtualOkay = !Ret->isStatic(); 7995 return Ret; 7996 } else { 7997 bool isFriend = 7998 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7999 if (!isFriend && SemaRef.CurContext->isRecord()) 8000 return nullptr; 8001 8002 // Determine whether the function was written with a 8003 // prototype. This true when: 8004 // - we're in C++ (where every function has a prototype), 8005 return FunctionDecl::Create(SemaRef.Context, DC, 8006 D.getLocStart(), 8007 NameInfo, R, TInfo, SC, isInline, 8008 true/*HasPrototype*/, isConstexpr); 8009 } 8010 } 8011 8012 enum OpenCLParamType { 8013 ValidKernelParam, 8014 PtrPtrKernelParam, 8015 PtrKernelParam, 8016 InvalidAddrSpacePtrKernelParam, 8017 InvalidKernelParam, 8018 RecordKernelParam 8019 }; 8020 8021 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8022 if (PT->isPointerType()) { 8023 QualType PointeeType = PT->getPointeeType(); 8024 if (PointeeType->isPointerType()) 8025 return PtrPtrKernelParam; 8026 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8027 PointeeType.getAddressSpace() == LangAS::opencl_private || 8028 PointeeType.getAddressSpace() == LangAS::Default) 8029 return InvalidAddrSpacePtrKernelParam; 8030 return PtrKernelParam; 8031 } 8032 8033 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8034 // be used as builtin types. 8035 8036 if (PT->isImageType()) 8037 return PtrKernelParam; 8038 8039 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8040 return InvalidKernelParam; 8041 8042 // OpenCL extension spec v1.2 s9.5: 8043 // This extension adds support for half scalar and vector types as built-in 8044 // types that can be used for arithmetic operations, conversions etc. 8045 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8046 return InvalidKernelParam; 8047 8048 if (PT->isRecordType()) 8049 return RecordKernelParam; 8050 8051 return ValidKernelParam; 8052 } 8053 8054 static void checkIsValidOpenCLKernelParameter( 8055 Sema &S, 8056 Declarator &D, 8057 ParmVarDecl *Param, 8058 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8059 QualType PT = Param->getType(); 8060 8061 // Cache the valid types we encounter to avoid rechecking structs that are 8062 // used again 8063 if (ValidTypes.count(PT.getTypePtr())) 8064 return; 8065 8066 switch (getOpenCLKernelParameterType(S, PT)) { 8067 case PtrPtrKernelParam: 8068 // OpenCL v1.2 s6.9.a: 8069 // A kernel function argument cannot be declared as a 8070 // pointer to a pointer type. 8071 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8072 D.setInvalidType(); 8073 return; 8074 8075 case InvalidAddrSpacePtrKernelParam: 8076 // OpenCL v1.0 s6.5: 8077 // __kernel function arguments declared to be a pointer of a type can point 8078 // to one of the following address spaces only : __global, __local or 8079 // __constant. 8080 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8081 D.setInvalidType(); 8082 return; 8083 8084 // OpenCL v1.2 s6.9.k: 8085 // Arguments to kernel functions in a program cannot be declared with the 8086 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8087 // uintptr_t or a struct and/or union that contain fields declared to be 8088 // one of these built-in scalar types. 8089 8090 case InvalidKernelParam: 8091 // OpenCL v1.2 s6.8 n: 8092 // A kernel function argument cannot be declared 8093 // of event_t type. 8094 // Do not diagnose half type since it is diagnosed as invalid argument 8095 // type for any function elsewhere. 8096 if (!PT->isHalfType()) 8097 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8098 D.setInvalidType(); 8099 return; 8100 8101 case PtrKernelParam: 8102 case ValidKernelParam: 8103 ValidTypes.insert(PT.getTypePtr()); 8104 return; 8105 8106 case RecordKernelParam: 8107 break; 8108 } 8109 8110 // Track nested structs we will inspect 8111 SmallVector<const Decl *, 4> VisitStack; 8112 8113 // Track where we are in the nested structs. Items will migrate from 8114 // VisitStack to HistoryStack as we do the DFS for bad field. 8115 SmallVector<const FieldDecl *, 4> HistoryStack; 8116 HistoryStack.push_back(nullptr); 8117 8118 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8119 VisitStack.push_back(PD); 8120 8121 assert(VisitStack.back() && "First decl null?"); 8122 8123 do { 8124 const Decl *Next = VisitStack.pop_back_val(); 8125 if (!Next) { 8126 assert(!HistoryStack.empty()); 8127 // Found a marker, we have gone up a level 8128 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8129 ValidTypes.insert(Hist->getType().getTypePtr()); 8130 8131 continue; 8132 } 8133 8134 // Adds everything except the original parameter declaration (which is not a 8135 // field itself) to the history stack. 8136 const RecordDecl *RD; 8137 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8138 HistoryStack.push_back(Field); 8139 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8140 } else { 8141 RD = cast<RecordDecl>(Next); 8142 } 8143 8144 // Add a null marker so we know when we've gone back up a level 8145 VisitStack.push_back(nullptr); 8146 8147 for (const auto *FD : RD->fields()) { 8148 QualType QT = FD->getType(); 8149 8150 if (ValidTypes.count(QT.getTypePtr())) 8151 continue; 8152 8153 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8154 if (ParamType == ValidKernelParam) 8155 continue; 8156 8157 if (ParamType == RecordKernelParam) { 8158 VisitStack.push_back(FD); 8159 continue; 8160 } 8161 8162 // OpenCL v1.2 s6.9.p: 8163 // Arguments to kernel functions that are declared to be a struct or union 8164 // do not allow OpenCL objects to be passed as elements of the struct or 8165 // union. 8166 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8167 ParamType == InvalidAddrSpacePtrKernelParam) { 8168 S.Diag(Param->getLocation(), 8169 diag::err_record_with_pointers_kernel_param) 8170 << PT->isUnionType() 8171 << PT; 8172 } else { 8173 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8174 } 8175 8176 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8177 << PD->getDeclName(); 8178 8179 // We have an error, now let's go back up through history and show where 8180 // the offending field came from 8181 for (ArrayRef<const FieldDecl *>::const_iterator 8182 I = HistoryStack.begin() + 1, 8183 E = HistoryStack.end(); 8184 I != E; ++I) { 8185 const FieldDecl *OuterField = *I; 8186 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8187 << OuterField->getType(); 8188 } 8189 8190 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8191 << QT->isPointerType() 8192 << QT; 8193 D.setInvalidType(); 8194 return; 8195 } 8196 } while (!VisitStack.empty()); 8197 } 8198 8199 /// Find the DeclContext in which a tag is implicitly declared if we see an 8200 /// elaborated type specifier in the specified context, and lookup finds 8201 /// nothing. 8202 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8203 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8204 DC = DC->getParent(); 8205 return DC; 8206 } 8207 8208 /// Find the Scope in which a tag is implicitly declared if we see an 8209 /// elaborated type specifier in the specified context, and lookup finds 8210 /// nothing. 8211 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8212 while (S->isClassScope() || 8213 (LangOpts.CPlusPlus && 8214 S->isFunctionPrototypeScope()) || 8215 ((S->getFlags() & Scope::DeclScope) == 0) || 8216 (S->getEntity() && S->getEntity()->isTransparentContext())) 8217 S = S->getParent(); 8218 return S; 8219 } 8220 8221 NamedDecl* 8222 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8223 TypeSourceInfo *TInfo, LookupResult &Previous, 8224 MultiTemplateParamsArg TemplateParamLists, 8225 bool &AddToScope) { 8226 QualType R = TInfo->getType(); 8227 8228 assert(R.getTypePtr()->isFunctionType()); 8229 8230 // TODO: consider using NameInfo for diagnostic. 8231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8232 DeclarationName Name = NameInfo.getName(); 8233 StorageClass SC = getFunctionStorageClass(*this, D); 8234 8235 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8236 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8237 diag::err_invalid_thread) 8238 << DeclSpec::getSpecifierName(TSCS); 8239 8240 if (D.isFirstDeclarationOfMember()) 8241 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8242 D.getIdentifierLoc()); 8243 8244 bool isFriend = false; 8245 FunctionTemplateDecl *FunctionTemplate = nullptr; 8246 bool isMemberSpecialization = false; 8247 bool isFunctionTemplateSpecialization = false; 8248 8249 bool isDependentClassScopeExplicitSpecialization = false; 8250 bool HasExplicitTemplateArgs = false; 8251 TemplateArgumentListInfo TemplateArgs; 8252 8253 bool isVirtualOkay = false; 8254 8255 DeclContext *OriginalDC = DC; 8256 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8257 8258 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8259 isVirtualOkay); 8260 if (!NewFD) return nullptr; 8261 8262 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8263 NewFD->setTopLevelDeclInObjCContainer(); 8264 8265 // Set the lexical context. If this is a function-scope declaration, or has a 8266 // C++ scope specifier, or is the object of a friend declaration, the lexical 8267 // context will be different from the semantic context. 8268 NewFD->setLexicalDeclContext(CurContext); 8269 8270 if (IsLocalExternDecl) 8271 NewFD->setLocalExternDecl(); 8272 8273 if (getLangOpts().CPlusPlus) { 8274 bool isInline = D.getDeclSpec().isInlineSpecified(); 8275 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8276 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8277 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8278 isFriend = D.getDeclSpec().isFriendSpecified(); 8279 if (isFriend && !isInline && D.isFunctionDefinition()) { 8280 // C++ [class.friend]p5 8281 // A function can be defined in a friend declaration of a 8282 // class . . . . Such a function is implicitly inline. 8283 NewFD->setImplicitlyInline(); 8284 } 8285 8286 // If this is a method defined in an __interface, and is not a constructor 8287 // or an overloaded operator, then set the pure flag (isVirtual will already 8288 // return true). 8289 if (const CXXRecordDecl *Parent = 8290 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8291 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8292 NewFD->setPure(true); 8293 8294 // C++ [class.union]p2 8295 // A union can have member functions, but not virtual functions. 8296 if (isVirtual && Parent->isUnion()) 8297 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8298 } 8299 8300 SetNestedNameSpecifier(NewFD, D); 8301 isMemberSpecialization = false; 8302 isFunctionTemplateSpecialization = false; 8303 if (D.isInvalidType()) 8304 NewFD->setInvalidDecl(); 8305 8306 // Match up the template parameter lists with the scope specifier, then 8307 // determine whether we have a template or a template specialization. 8308 bool Invalid = false; 8309 if (TemplateParameterList *TemplateParams = 8310 MatchTemplateParametersToScopeSpecifier( 8311 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8312 D.getCXXScopeSpec(), 8313 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8314 ? D.getName().TemplateId 8315 : nullptr, 8316 TemplateParamLists, isFriend, isMemberSpecialization, 8317 Invalid)) { 8318 if (TemplateParams->size() > 0) { 8319 // This is a function template 8320 8321 // Check that we can declare a template here. 8322 if (CheckTemplateDeclScope(S, TemplateParams)) 8323 NewFD->setInvalidDecl(); 8324 8325 // A destructor cannot be a template. 8326 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8327 Diag(NewFD->getLocation(), diag::err_destructor_template); 8328 NewFD->setInvalidDecl(); 8329 } 8330 8331 // If we're adding a template to a dependent context, we may need to 8332 // rebuilding some of the types used within the template parameter list, 8333 // now that we know what the current instantiation is. 8334 if (DC->isDependentContext()) { 8335 ContextRAII SavedContext(*this, DC); 8336 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8337 Invalid = true; 8338 } 8339 8340 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8341 NewFD->getLocation(), 8342 Name, TemplateParams, 8343 NewFD); 8344 FunctionTemplate->setLexicalDeclContext(CurContext); 8345 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8346 8347 // For source fidelity, store the other template param lists. 8348 if (TemplateParamLists.size() > 1) { 8349 NewFD->setTemplateParameterListsInfo(Context, 8350 TemplateParamLists.drop_back(1)); 8351 } 8352 } else { 8353 // This is a function template specialization. 8354 isFunctionTemplateSpecialization = true; 8355 // For source fidelity, store all the template param lists. 8356 if (TemplateParamLists.size() > 0) 8357 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8358 8359 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8360 if (isFriend) { 8361 // We want to remove the "template<>", found here. 8362 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8363 8364 // If we remove the template<> and the name is not a 8365 // template-id, we're actually silently creating a problem: 8366 // the friend declaration will refer to an untemplated decl, 8367 // and clearly the user wants a template specialization. So 8368 // we need to insert '<>' after the name. 8369 SourceLocation InsertLoc; 8370 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8371 InsertLoc = D.getName().getSourceRange().getEnd(); 8372 InsertLoc = getLocForEndOfToken(InsertLoc); 8373 } 8374 8375 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8376 << Name << RemoveRange 8377 << FixItHint::CreateRemoval(RemoveRange) 8378 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8379 } 8380 } 8381 } 8382 else { 8383 // All template param lists were matched against the scope specifier: 8384 // this is NOT (an explicit specialization of) a template. 8385 if (TemplateParamLists.size() > 0) 8386 // For source fidelity, store all the template param lists. 8387 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8388 } 8389 8390 if (Invalid) { 8391 NewFD->setInvalidDecl(); 8392 if (FunctionTemplate) 8393 FunctionTemplate->setInvalidDecl(); 8394 } 8395 8396 // C++ [dcl.fct.spec]p5: 8397 // The virtual specifier shall only be used in declarations of 8398 // nonstatic class member functions that appear within a 8399 // member-specification of a class declaration; see 10.3. 8400 // 8401 if (isVirtual && !NewFD->isInvalidDecl()) { 8402 if (!isVirtualOkay) { 8403 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8404 diag::err_virtual_non_function); 8405 } else if (!CurContext->isRecord()) { 8406 // 'virtual' was specified outside of the class. 8407 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8408 diag::err_virtual_out_of_class) 8409 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8410 } else if (NewFD->getDescribedFunctionTemplate()) { 8411 // C++ [temp.mem]p3: 8412 // A member function template shall not be virtual. 8413 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8414 diag::err_virtual_member_function_template) 8415 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8416 } else { 8417 // Okay: Add virtual to the method. 8418 NewFD->setVirtualAsWritten(true); 8419 } 8420 8421 if (getLangOpts().CPlusPlus14 && 8422 NewFD->getReturnType()->isUndeducedType()) 8423 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8424 } 8425 8426 if (getLangOpts().CPlusPlus14 && 8427 (NewFD->isDependentContext() || 8428 (isFriend && CurContext->isDependentContext())) && 8429 NewFD->getReturnType()->isUndeducedType()) { 8430 // If the function template is referenced directly (for instance, as a 8431 // member of the current instantiation), pretend it has a dependent type. 8432 // This is not really justified by the standard, but is the only sane 8433 // thing to do. 8434 // FIXME: For a friend function, we have not marked the function as being 8435 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8436 const FunctionProtoType *FPT = 8437 NewFD->getType()->castAs<FunctionProtoType>(); 8438 QualType Result = 8439 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8440 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8441 FPT->getExtProtoInfo())); 8442 } 8443 8444 // C++ [dcl.fct.spec]p3: 8445 // The inline specifier shall not appear on a block scope function 8446 // declaration. 8447 if (isInline && !NewFD->isInvalidDecl()) { 8448 if (CurContext->isFunctionOrMethod()) { 8449 // 'inline' is not allowed on block scope function declaration. 8450 Diag(D.getDeclSpec().getInlineSpecLoc(), 8451 diag::err_inline_declaration_block_scope) << Name 8452 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8453 } 8454 } 8455 8456 // C++ [dcl.fct.spec]p6: 8457 // The explicit specifier shall be used only in the declaration of a 8458 // constructor or conversion function within its class definition; 8459 // see 12.3.1 and 12.3.2. 8460 if (isExplicit && !NewFD->isInvalidDecl() && 8461 !isa<CXXDeductionGuideDecl>(NewFD)) { 8462 if (!CurContext->isRecord()) { 8463 // 'explicit' was specified outside of the class. 8464 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8465 diag::err_explicit_out_of_class) 8466 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8467 } else if (!isa<CXXConstructorDecl>(NewFD) && 8468 !isa<CXXConversionDecl>(NewFD)) { 8469 // 'explicit' was specified on a function that wasn't a constructor 8470 // or conversion function. 8471 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8472 diag::err_explicit_non_ctor_or_conv_function) 8473 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8474 } 8475 } 8476 8477 if (isConstexpr) { 8478 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8479 // are implicitly inline. 8480 NewFD->setImplicitlyInline(); 8481 8482 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8483 // be either constructors or to return a literal type. Therefore, 8484 // destructors cannot be declared constexpr. 8485 if (isa<CXXDestructorDecl>(NewFD)) 8486 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8487 } 8488 8489 // If __module_private__ was specified, mark the function accordingly. 8490 if (D.getDeclSpec().isModulePrivateSpecified()) { 8491 if (isFunctionTemplateSpecialization) { 8492 SourceLocation ModulePrivateLoc 8493 = D.getDeclSpec().getModulePrivateSpecLoc(); 8494 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8495 << 0 8496 << FixItHint::CreateRemoval(ModulePrivateLoc); 8497 } else { 8498 NewFD->setModulePrivate(); 8499 if (FunctionTemplate) 8500 FunctionTemplate->setModulePrivate(); 8501 } 8502 } 8503 8504 if (isFriend) { 8505 if (FunctionTemplate) { 8506 FunctionTemplate->setObjectOfFriendDecl(); 8507 FunctionTemplate->setAccess(AS_public); 8508 } 8509 NewFD->setObjectOfFriendDecl(); 8510 NewFD->setAccess(AS_public); 8511 } 8512 8513 // If a function is defined as defaulted or deleted, mark it as such now. 8514 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8515 // definition kind to FDK_Definition. 8516 switch (D.getFunctionDefinitionKind()) { 8517 case FDK_Declaration: 8518 case FDK_Definition: 8519 break; 8520 8521 case FDK_Defaulted: 8522 NewFD->setDefaulted(); 8523 break; 8524 8525 case FDK_Deleted: 8526 NewFD->setDeletedAsWritten(); 8527 break; 8528 } 8529 8530 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8531 D.isFunctionDefinition()) { 8532 // C++ [class.mfct]p2: 8533 // A member function may be defined (8.4) in its class definition, in 8534 // which case it is an inline member function (7.1.2) 8535 NewFD->setImplicitlyInline(); 8536 } 8537 8538 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8539 !CurContext->isRecord()) { 8540 // C++ [class.static]p1: 8541 // A data or function member of a class may be declared static 8542 // in a class definition, in which case it is a static member of 8543 // the class. 8544 8545 // Complain about the 'static' specifier if it's on an out-of-line 8546 // member function definition. 8547 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8548 diag::err_static_out_of_line) 8549 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8550 } 8551 8552 // C++11 [except.spec]p15: 8553 // A deallocation function with no exception-specification is treated 8554 // as if it were specified with noexcept(true). 8555 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8556 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8557 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8558 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8559 NewFD->setType(Context.getFunctionType( 8560 FPT->getReturnType(), FPT->getParamTypes(), 8561 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8562 } 8563 8564 // Filter out previous declarations that don't match the scope. 8565 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8566 D.getCXXScopeSpec().isNotEmpty() || 8567 isMemberSpecialization || 8568 isFunctionTemplateSpecialization); 8569 8570 // Handle GNU asm-label extension (encoded as an attribute). 8571 if (Expr *E = (Expr*) D.getAsmLabel()) { 8572 // The parser guarantees this is a string. 8573 StringLiteral *SE = cast<StringLiteral>(E); 8574 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8575 SE->getString(), 0)); 8576 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8577 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8578 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8579 if (I != ExtnameUndeclaredIdentifiers.end()) { 8580 if (isDeclExternC(NewFD)) { 8581 NewFD->addAttr(I->second); 8582 ExtnameUndeclaredIdentifiers.erase(I); 8583 } else 8584 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8585 << /*Variable*/0 << NewFD; 8586 } 8587 } 8588 8589 // Copy the parameter declarations from the declarator D to the function 8590 // declaration NewFD, if they are available. First scavenge them into Params. 8591 SmallVector<ParmVarDecl*, 16> Params; 8592 unsigned FTIIdx; 8593 if (D.isFunctionDeclarator(FTIIdx)) { 8594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8595 8596 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8597 // function that takes no arguments, not a function that takes a 8598 // single void argument. 8599 // We let through "const void" here because Sema::GetTypeForDeclarator 8600 // already checks for that case. 8601 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8602 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8603 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8604 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8605 Param->setDeclContext(NewFD); 8606 Params.push_back(Param); 8607 8608 if (Param->isInvalidDecl()) 8609 NewFD->setInvalidDecl(); 8610 } 8611 } 8612 8613 if (!getLangOpts().CPlusPlus) { 8614 // In C, find all the tag declarations from the prototype and move them 8615 // into the function DeclContext. Remove them from the surrounding tag 8616 // injection context of the function, which is typically but not always 8617 // the TU. 8618 DeclContext *PrototypeTagContext = 8619 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8620 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8621 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8622 8623 // We don't want to reparent enumerators. Look at their parent enum 8624 // instead. 8625 if (!TD) { 8626 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8627 TD = cast<EnumDecl>(ECD->getDeclContext()); 8628 } 8629 if (!TD) 8630 continue; 8631 DeclContext *TagDC = TD->getLexicalDeclContext(); 8632 if (!TagDC->containsDecl(TD)) 8633 continue; 8634 TagDC->removeDecl(TD); 8635 TD->setDeclContext(NewFD); 8636 NewFD->addDecl(TD); 8637 8638 // Preserve the lexical DeclContext if it is not the surrounding tag 8639 // injection context of the FD. In this example, the semantic context of 8640 // E will be f and the lexical context will be S, while both the 8641 // semantic and lexical contexts of S will be f: 8642 // void f(struct S { enum E { a } f; } s); 8643 if (TagDC != PrototypeTagContext) 8644 TD->setLexicalDeclContext(TagDC); 8645 } 8646 } 8647 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8648 // When we're declaring a function with a typedef, typeof, etc as in the 8649 // following example, we'll need to synthesize (unnamed) 8650 // parameters for use in the declaration. 8651 // 8652 // @code 8653 // typedef void fn(int); 8654 // fn f; 8655 // @endcode 8656 8657 // Synthesize a parameter for each argument type. 8658 for (const auto &AI : FT->param_types()) { 8659 ParmVarDecl *Param = 8660 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8661 Param->setScopeInfo(0, Params.size()); 8662 Params.push_back(Param); 8663 } 8664 } else { 8665 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8666 "Should not need args for typedef of non-prototype fn"); 8667 } 8668 8669 // Finally, we know we have the right number of parameters, install them. 8670 NewFD->setParams(Params); 8671 8672 if (D.getDeclSpec().isNoreturnSpecified()) 8673 NewFD->addAttr( 8674 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8675 Context, 0)); 8676 8677 // Functions returning a variably modified type violate C99 6.7.5.2p2 8678 // because all functions have linkage. 8679 if (!NewFD->isInvalidDecl() && 8680 NewFD->getReturnType()->isVariablyModifiedType()) { 8681 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8682 NewFD->setInvalidDecl(); 8683 } 8684 8685 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8686 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8687 !NewFD->hasAttr<SectionAttr>()) { 8688 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8689 PragmaClangTextSection.SectionName, 8690 PragmaClangTextSection.PragmaLocation)); 8691 } 8692 8693 // Apply an implicit SectionAttr if #pragma code_seg is active. 8694 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8695 !NewFD->hasAttr<SectionAttr>()) { 8696 NewFD->addAttr( 8697 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8698 CodeSegStack.CurrentValue->getString(), 8699 CodeSegStack.CurrentPragmaLocation)); 8700 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8701 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8702 ASTContext::PSF_Read, 8703 NewFD)) 8704 NewFD->dropAttr<SectionAttr>(); 8705 } 8706 8707 // Handle attributes. 8708 ProcessDeclAttributes(S, NewFD, D); 8709 8710 if (getLangOpts().OpenCL) { 8711 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8712 // type declaration will generate a compilation error. 8713 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8714 if (AddressSpace != LangAS::Default) { 8715 Diag(NewFD->getLocation(), 8716 diag::err_opencl_return_value_with_address_space); 8717 NewFD->setInvalidDecl(); 8718 } 8719 } 8720 8721 if (!getLangOpts().CPlusPlus) { 8722 // Perform semantic checking on the function declaration. 8723 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8724 CheckMain(NewFD, D.getDeclSpec()); 8725 8726 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8727 CheckMSVCRTEntryPoint(NewFD); 8728 8729 if (!NewFD->isInvalidDecl()) 8730 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8731 isMemberSpecialization)); 8732 else if (!Previous.empty()) 8733 // Recover gracefully from an invalid redeclaration. 8734 D.setRedeclaration(true); 8735 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8736 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8737 "previous declaration set still overloaded"); 8738 8739 // Diagnose no-prototype function declarations with calling conventions that 8740 // don't support variadic calls. Only do this in C and do it after merging 8741 // possibly prototyped redeclarations. 8742 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8743 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8744 CallingConv CC = FT->getExtInfo().getCC(); 8745 if (!supportsVariadicCall(CC)) { 8746 // Windows system headers sometimes accidentally use stdcall without 8747 // (void) parameters, so we relax this to a warning. 8748 int DiagID = 8749 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8750 Diag(NewFD->getLocation(), DiagID) 8751 << FunctionType::getNameForCallConv(CC); 8752 } 8753 } 8754 } else { 8755 // C++11 [replacement.functions]p3: 8756 // The program's definitions shall not be specified as inline. 8757 // 8758 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8759 // 8760 // Suppress the diagnostic if the function is __attribute__((used)), since 8761 // that forces an external definition to be emitted. 8762 if (D.getDeclSpec().isInlineSpecified() && 8763 NewFD->isReplaceableGlobalAllocationFunction() && 8764 !NewFD->hasAttr<UsedAttr>()) 8765 Diag(D.getDeclSpec().getInlineSpecLoc(), 8766 diag::ext_operator_new_delete_declared_inline) 8767 << NewFD->getDeclName(); 8768 8769 // If the declarator is a template-id, translate the parser's template 8770 // argument list into our AST format. 8771 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8772 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8773 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8774 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8775 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8776 TemplateId->NumArgs); 8777 translateTemplateArguments(TemplateArgsPtr, 8778 TemplateArgs); 8779 8780 HasExplicitTemplateArgs = true; 8781 8782 if (NewFD->isInvalidDecl()) { 8783 HasExplicitTemplateArgs = false; 8784 } else if (FunctionTemplate) { 8785 // Function template with explicit template arguments. 8786 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8787 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8788 8789 HasExplicitTemplateArgs = false; 8790 } else { 8791 assert((isFunctionTemplateSpecialization || 8792 D.getDeclSpec().isFriendSpecified()) && 8793 "should have a 'template<>' for this decl"); 8794 // "friend void foo<>(int);" is an implicit specialization decl. 8795 isFunctionTemplateSpecialization = true; 8796 } 8797 } else if (isFriend && isFunctionTemplateSpecialization) { 8798 // This combination is only possible in a recovery case; the user 8799 // wrote something like: 8800 // template <> friend void foo(int); 8801 // which we're recovering from as if the user had written: 8802 // friend void foo<>(int); 8803 // Go ahead and fake up a template id. 8804 HasExplicitTemplateArgs = true; 8805 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8806 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8807 } 8808 8809 // We do not add HD attributes to specializations here because 8810 // they may have different constexpr-ness compared to their 8811 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8812 // may end up with different effective targets. Instead, a 8813 // specialization inherits its target attributes from its template 8814 // in the CheckFunctionTemplateSpecialization() call below. 8815 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8816 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8817 8818 // If it's a friend (and only if it's a friend), it's possible 8819 // that either the specialized function type or the specialized 8820 // template is dependent, and therefore matching will fail. In 8821 // this case, don't check the specialization yet. 8822 bool InstantiationDependent = false; 8823 if (isFunctionTemplateSpecialization && isFriend && 8824 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8825 TemplateSpecializationType::anyDependentTemplateArguments( 8826 TemplateArgs, 8827 InstantiationDependent))) { 8828 assert(HasExplicitTemplateArgs && 8829 "friend function specialization without template args"); 8830 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8831 Previous)) 8832 NewFD->setInvalidDecl(); 8833 } else if (isFunctionTemplateSpecialization) { 8834 if (CurContext->isDependentContext() && CurContext->isRecord() 8835 && !isFriend) { 8836 isDependentClassScopeExplicitSpecialization = true; 8837 } else if (!NewFD->isInvalidDecl() && 8838 CheckFunctionTemplateSpecialization( 8839 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8840 Previous)) 8841 NewFD->setInvalidDecl(); 8842 8843 // C++ [dcl.stc]p1: 8844 // A storage-class-specifier shall not be specified in an explicit 8845 // specialization (14.7.3) 8846 FunctionTemplateSpecializationInfo *Info = 8847 NewFD->getTemplateSpecializationInfo(); 8848 if (Info && SC != SC_None) { 8849 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8850 Diag(NewFD->getLocation(), 8851 diag::err_explicit_specialization_inconsistent_storage_class) 8852 << SC 8853 << FixItHint::CreateRemoval( 8854 D.getDeclSpec().getStorageClassSpecLoc()); 8855 8856 else 8857 Diag(NewFD->getLocation(), 8858 diag::ext_explicit_specialization_storage_class) 8859 << FixItHint::CreateRemoval( 8860 D.getDeclSpec().getStorageClassSpecLoc()); 8861 } 8862 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8863 if (CheckMemberSpecialization(NewFD, Previous)) 8864 NewFD->setInvalidDecl(); 8865 } 8866 8867 // Perform semantic checking on the function declaration. 8868 if (!isDependentClassScopeExplicitSpecialization) { 8869 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8870 CheckMain(NewFD, D.getDeclSpec()); 8871 8872 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8873 CheckMSVCRTEntryPoint(NewFD); 8874 8875 if (!NewFD->isInvalidDecl()) 8876 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8877 isMemberSpecialization)); 8878 else if (!Previous.empty()) 8879 // Recover gracefully from an invalid redeclaration. 8880 D.setRedeclaration(true); 8881 } 8882 8883 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8884 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8885 "previous declaration set still overloaded"); 8886 8887 NamedDecl *PrincipalDecl = (FunctionTemplate 8888 ? cast<NamedDecl>(FunctionTemplate) 8889 : NewFD); 8890 8891 if (isFriend && NewFD->getPreviousDecl()) { 8892 AccessSpecifier Access = AS_public; 8893 if (!NewFD->isInvalidDecl()) 8894 Access = NewFD->getPreviousDecl()->getAccess(); 8895 8896 NewFD->setAccess(Access); 8897 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8898 } 8899 8900 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8901 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8902 PrincipalDecl->setNonMemberOperator(); 8903 8904 // If we have a function template, check the template parameter 8905 // list. This will check and merge default template arguments. 8906 if (FunctionTemplate) { 8907 FunctionTemplateDecl *PrevTemplate = 8908 FunctionTemplate->getPreviousDecl(); 8909 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8910 PrevTemplate ? PrevTemplate->getTemplateParameters() 8911 : nullptr, 8912 D.getDeclSpec().isFriendSpecified() 8913 ? (D.isFunctionDefinition() 8914 ? TPC_FriendFunctionTemplateDefinition 8915 : TPC_FriendFunctionTemplate) 8916 : (D.getCXXScopeSpec().isSet() && 8917 DC && DC->isRecord() && 8918 DC->isDependentContext()) 8919 ? TPC_ClassTemplateMember 8920 : TPC_FunctionTemplate); 8921 } 8922 8923 if (NewFD->isInvalidDecl()) { 8924 // Ignore all the rest of this. 8925 } else if (!D.isRedeclaration()) { 8926 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8927 AddToScope }; 8928 // Fake up an access specifier if it's supposed to be a class member. 8929 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8930 NewFD->setAccess(AS_public); 8931 8932 // Qualified decls generally require a previous declaration. 8933 if (D.getCXXScopeSpec().isSet()) { 8934 // ...with the major exception of templated-scope or 8935 // dependent-scope friend declarations. 8936 8937 // TODO: we currently also suppress this check in dependent 8938 // contexts because (1) the parameter depth will be off when 8939 // matching friend templates and (2) we might actually be 8940 // selecting a friend based on a dependent factor. But there 8941 // are situations where these conditions don't apply and we 8942 // can actually do this check immediately. 8943 if (isFriend && 8944 (TemplateParamLists.size() || 8945 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8946 CurContext->isDependentContext())) { 8947 // ignore these 8948 } else { 8949 // The user tried to provide an out-of-line definition for a 8950 // function that is a member of a class or namespace, but there 8951 // was no such member function declared (C++ [class.mfct]p2, 8952 // C++ [namespace.memdef]p2). For example: 8953 // 8954 // class X { 8955 // void f() const; 8956 // }; 8957 // 8958 // void X::f() { } // ill-formed 8959 // 8960 // Complain about this problem, and attempt to suggest close 8961 // matches (e.g., those that differ only in cv-qualifiers and 8962 // whether the parameter types are references). 8963 8964 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8965 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8966 AddToScope = ExtraArgs.AddToScope; 8967 return Result; 8968 } 8969 } 8970 8971 // Unqualified local friend declarations are required to resolve 8972 // to something. 8973 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8974 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8975 *this, Previous, NewFD, ExtraArgs, true, S)) { 8976 AddToScope = ExtraArgs.AddToScope; 8977 return Result; 8978 } 8979 } 8980 } else if (!D.isFunctionDefinition() && 8981 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8982 !isFriend && !isFunctionTemplateSpecialization && 8983 !isMemberSpecialization) { 8984 // An out-of-line member function declaration must also be a 8985 // definition (C++ [class.mfct]p2). 8986 // Note that this is not the case for explicit specializations of 8987 // function templates or member functions of class templates, per 8988 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8989 // extension for compatibility with old SWIG code which likes to 8990 // generate them. 8991 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8992 << D.getCXXScopeSpec().getRange(); 8993 } 8994 } 8995 8996 ProcessPragmaWeak(S, NewFD); 8997 checkAttributesAfterMerging(*this, *NewFD); 8998 8999 AddKnownFunctionAttributes(NewFD); 9000 9001 if (NewFD->hasAttr<OverloadableAttr>() && 9002 !NewFD->getType()->getAs<FunctionProtoType>()) { 9003 Diag(NewFD->getLocation(), 9004 diag::err_attribute_overloadable_no_prototype) 9005 << NewFD; 9006 9007 // Turn this into a variadic function with no parameters. 9008 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9009 FunctionProtoType::ExtProtoInfo EPI( 9010 Context.getDefaultCallingConvention(true, false)); 9011 EPI.Variadic = true; 9012 EPI.ExtInfo = FT->getExtInfo(); 9013 9014 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9015 NewFD->setType(R); 9016 } 9017 9018 // If there's a #pragma GCC visibility in scope, and this isn't a class 9019 // member, set the visibility of this function. 9020 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9021 AddPushedVisibilityAttribute(NewFD); 9022 9023 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9024 // marking the function. 9025 AddCFAuditedAttribute(NewFD); 9026 9027 // If this is a function definition, check if we have to apply optnone due to 9028 // a pragma. 9029 if(D.isFunctionDefinition()) 9030 AddRangeBasedOptnone(NewFD); 9031 9032 // If this is the first declaration of an extern C variable, update 9033 // the map of such variables. 9034 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9035 isIncompleteDeclExternC(*this, NewFD)) 9036 RegisterLocallyScopedExternCDecl(NewFD, S); 9037 9038 // Set this FunctionDecl's range up to the right paren. 9039 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9040 9041 if (D.isRedeclaration() && !Previous.empty()) { 9042 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9043 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9044 isMemberSpecialization || 9045 isFunctionTemplateSpecialization, 9046 D.isFunctionDefinition()); 9047 } 9048 9049 if (getLangOpts().CUDA) { 9050 IdentifierInfo *II = NewFD->getIdentifier(); 9051 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9052 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9053 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9054 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9055 9056 Context.setcudaConfigureCallDecl(NewFD); 9057 } 9058 9059 // Variadic functions, other than a *declaration* of printf, are not allowed 9060 // in device-side CUDA code, unless someone passed 9061 // -fcuda-allow-variadic-functions. 9062 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9063 (NewFD->hasAttr<CUDADeviceAttr>() || 9064 NewFD->hasAttr<CUDAGlobalAttr>()) && 9065 !(II && II->isStr("printf") && NewFD->isExternC() && 9066 !D.isFunctionDefinition())) { 9067 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9068 } 9069 } 9070 9071 MarkUnusedFileScopedDecl(NewFD); 9072 9073 if (getLangOpts().CPlusPlus) { 9074 if (FunctionTemplate) { 9075 if (NewFD->isInvalidDecl()) 9076 FunctionTemplate->setInvalidDecl(); 9077 return FunctionTemplate; 9078 } 9079 9080 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9081 CompleteMemberSpecialization(NewFD, Previous); 9082 } 9083 9084 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9085 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9086 if ((getLangOpts().OpenCLVersion >= 120) 9087 && (SC == SC_Static)) { 9088 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9089 D.setInvalidType(); 9090 } 9091 9092 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9093 if (!NewFD->getReturnType()->isVoidType()) { 9094 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9095 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9096 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9097 : FixItHint()); 9098 D.setInvalidType(); 9099 } 9100 9101 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9102 for (auto Param : NewFD->parameters()) 9103 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9104 } 9105 for (const ParmVarDecl *Param : NewFD->parameters()) { 9106 QualType PT = Param->getType(); 9107 9108 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9109 // types. 9110 if (getLangOpts().OpenCLVersion >= 200) { 9111 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9112 QualType ElemTy = PipeTy->getElementType(); 9113 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9114 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9115 D.setInvalidType(); 9116 } 9117 } 9118 } 9119 } 9120 9121 // Here we have an function template explicit specialization at class scope. 9122 // The actual specialization will be postponed to template instatiation 9123 // time via the ClassScopeFunctionSpecializationDecl node. 9124 if (isDependentClassScopeExplicitSpecialization) { 9125 ClassScopeFunctionSpecializationDecl *NewSpec = 9126 ClassScopeFunctionSpecializationDecl::Create( 9127 Context, CurContext, NewFD->getLocation(), 9128 cast<CXXMethodDecl>(NewFD), 9129 HasExplicitTemplateArgs, TemplateArgs); 9130 CurContext->addDecl(NewSpec); 9131 AddToScope = false; 9132 } 9133 9134 return NewFD; 9135 } 9136 9137 /// \brief Checks if the new declaration declared in dependent context must be 9138 /// put in the same redeclaration chain as the specified declaration. 9139 /// 9140 /// \param D Declaration that is checked. 9141 /// \param PrevDecl Previous declaration found with proper lookup method for the 9142 /// same declaration name. 9143 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9144 /// belongs to. 9145 /// 9146 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9147 // Any declarations should be put into redeclaration chains except for 9148 // friend declaration in a dependent context that names a function in 9149 // namespace scope. 9150 // 9151 // This allows to compile code like: 9152 // 9153 // void func(); 9154 // template<typename T> class C1 { friend void func() { } }; 9155 // template<typename T> class C2 { friend void func() { } }; 9156 // 9157 // This code snippet is a valid code unless both templates are instantiated. 9158 return !(D->getLexicalDeclContext()->isDependentContext() && 9159 D->getDeclContext()->isFileContext() && 9160 D->getFriendObjectKind() != Decl::FOK_None); 9161 } 9162 9163 /// \brief Check the target attribute of the function for MultiVersion 9164 /// validity. 9165 /// 9166 /// Returns true if there was an error, false otherwise. 9167 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9168 const auto *TA = FD->getAttr<TargetAttr>(); 9169 assert(TA && "MultiVersion Candidate requires a target attribute"); 9170 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9171 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9172 enum ErrType { Feature = 0, Architecture = 1 }; 9173 9174 if (!ParseInfo.Architecture.empty() && 9175 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9176 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9177 << Architecture << ParseInfo.Architecture; 9178 return true; 9179 } 9180 9181 for (const auto &Feat : ParseInfo.Features) { 9182 auto BareFeat = StringRef{Feat}.substr(1); 9183 if (Feat[0] == '-') { 9184 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9185 << Feature << ("no-" + BareFeat).str(); 9186 return true; 9187 } 9188 9189 if (!TargetInfo.validateCpuSupports(BareFeat) || 9190 !TargetInfo.isValidFeatureName(BareFeat)) { 9191 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9192 << Feature << BareFeat; 9193 return true; 9194 } 9195 } 9196 return false; 9197 } 9198 9199 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9200 const FunctionDecl *NewFD, 9201 bool CausesMV) { 9202 enum DoesntSupport { 9203 FuncTemplates = 0, 9204 VirtFuncs = 1, 9205 DeducedReturn = 2, 9206 Constructors = 3, 9207 Destructors = 4, 9208 DeletedFuncs = 5, 9209 DefaultedFuncs = 6 9210 }; 9211 enum Different { 9212 CallingConv = 0, 9213 ReturnType = 1, 9214 ConstexprSpec = 2, 9215 InlineSpec = 3, 9216 StorageClass = 4, 9217 Linkage = 5 9218 }; 9219 9220 // For now, disallow all other attributes. These should be opt-in, but 9221 // an analysis of all of them is a future FIXME. 9222 if (CausesMV && OldFD && 9223 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9224 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9225 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9226 return true; 9227 } 9228 9229 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9230 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9231 9232 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9233 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9234 << FuncTemplates; 9235 9236 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9237 if (NewCXXFD->isVirtual()) 9238 return S.Diag(NewCXXFD->getLocation(), 9239 diag::err_multiversion_doesnt_support) 9240 << VirtFuncs; 9241 9242 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9243 return S.Diag(NewCXXCtor->getLocation(), 9244 diag::err_multiversion_doesnt_support) 9245 << Constructors; 9246 9247 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9248 return S.Diag(NewCXXDtor->getLocation(), 9249 diag::err_multiversion_doesnt_support) 9250 << Destructors; 9251 } 9252 9253 if (NewFD->isDeleted()) 9254 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9255 << DeletedFuncs; 9256 9257 if (NewFD->isDefaulted()) 9258 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9259 << DefaultedFuncs; 9260 9261 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9262 const auto *NewType = cast<FunctionType>(NewQType); 9263 QualType NewReturnType = NewType->getReturnType(); 9264 9265 if (NewReturnType->isUndeducedType()) 9266 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9267 << DeducedReturn; 9268 9269 // Only allow transition to MultiVersion if it hasn't been used. 9270 if (OldFD && CausesMV && OldFD->isUsed(false)) 9271 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9272 9273 // Ensure the return type is identical. 9274 if (OldFD) { 9275 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9276 const auto *OldType = cast<FunctionType>(OldQType); 9277 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9278 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9279 9280 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9281 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9282 << CallingConv; 9283 9284 QualType OldReturnType = OldType->getReturnType(); 9285 9286 if (OldReturnType != NewReturnType) 9287 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9288 << ReturnType; 9289 9290 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9291 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9292 << ConstexprSpec; 9293 9294 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9295 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9296 << InlineSpec; 9297 9298 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9299 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9300 << StorageClass; 9301 9302 if (OldFD->isExternC() != NewFD->isExternC()) 9303 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9304 << Linkage; 9305 9306 if (S.CheckEquivalentExceptionSpec( 9307 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9308 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9309 return true; 9310 } 9311 return false; 9312 } 9313 9314 /// \brief Check the validity of a mulitversion function declaration. 9315 /// Also sets the multiversion'ness' of the function itself. 9316 /// 9317 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9318 /// 9319 /// Returns true if there was an error, false otherwise. 9320 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9321 bool &Redeclaration, NamedDecl *&OldDecl, 9322 bool &MergeTypeWithPrevious, 9323 LookupResult &Previous) { 9324 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9325 if (NewFD->isMain()) { 9326 if (NewTA && NewTA->isDefaultVersion()) { 9327 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9328 NewFD->setInvalidDecl(); 9329 return true; 9330 } 9331 return false; 9332 } 9333 9334 // If there is no matching previous decl, only 'default' can 9335 // cause MultiVersioning. 9336 if (!OldDecl) { 9337 if (NewTA && NewTA->isDefaultVersion()) { 9338 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9339 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9340 NewFD->setInvalidDecl(); 9341 return true; 9342 } 9343 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9344 NewFD->setInvalidDecl(); 9345 return true; 9346 } 9347 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9348 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9349 NewFD->setInvalidDecl(); 9350 return true; 9351 } 9352 9353 NewFD->setIsMultiVersion(); 9354 } 9355 return false; 9356 } 9357 9358 if (OldDecl->getDeclContext()->getRedeclContext() != 9359 NewFD->getDeclContext()->getRedeclContext()) 9360 return false; 9361 9362 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9363 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9364 // likely cannot cause a problem here. 9365 if (!OldFD) 9366 return false; 9367 9368 if (!OldFD->isMultiVersion() && !NewTA) 9369 return false; 9370 9371 if (OldFD->isMultiVersion() && !NewTA) { 9372 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9373 NewFD->setInvalidDecl(); 9374 return true; 9375 } 9376 9377 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9378 // Sort order doesn't matter, it just needs to be consistent. 9379 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9380 9381 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9382 if (!OldFD->isMultiVersion()) { 9383 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9384 // to change, this is a simple redeclaration. 9385 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9386 return false; 9387 9388 // Otherwise, this decl causes MultiVersioning. 9389 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9390 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9391 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9392 NewFD->setInvalidDecl(); 9393 return true; 9394 } 9395 9396 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9397 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9398 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9399 NewFD->setInvalidDecl(); 9400 return true; 9401 } 9402 9403 if (CheckMultiVersionValue(S, NewFD)) { 9404 NewFD->setInvalidDecl(); 9405 return true; 9406 } 9407 9408 if (CheckMultiVersionValue(S, OldFD)) { 9409 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9410 NewFD->setInvalidDecl(); 9411 return true; 9412 } 9413 9414 TargetAttr::ParsedTargetAttr OldParsed = 9415 OldTA->parse(std::less<std::string>()); 9416 9417 if (OldParsed == NewParsed) { 9418 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9419 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9420 NewFD->setInvalidDecl(); 9421 return true; 9422 } 9423 9424 for (const auto *FD : OldFD->redecls()) { 9425 const auto *CurTA = FD->getAttr<TargetAttr>(); 9426 if (!CurTA || CurTA->isInherited()) { 9427 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9428 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9429 NewFD->setInvalidDecl(); 9430 return true; 9431 } 9432 } 9433 9434 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9435 NewFD->setInvalidDecl(); 9436 return true; 9437 } 9438 9439 OldFD->setIsMultiVersion(); 9440 NewFD->setIsMultiVersion(); 9441 Redeclaration = false; 9442 MergeTypeWithPrevious = false; 9443 OldDecl = nullptr; 9444 Previous.clear(); 9445 return false; 9446 } 9447 9448 bool UseMemberUsingDeclRules = 9449 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9450 9451 // Next, check ALL non-overloads to see if this is a redeclaration of a 9452 // previous member of the MultiVersion set. 9453 for (NamedDecl *ND : Previous) { 9454 FunctionDecl *CurFD = ND->getAsFunction(); 9455 if (!CurFD) 9456 continue; 9457 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9458 continue; 9459 9460 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9461 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9462 NewFD->setIsMultiVersion(); 9463 Redeclaration = true; 9464 OldDecl = ND; 9465 return false; 9466 } 9467 9468 TargetAttr::ParsedTargetAttr CurParsed = 9469 CurTA->parse(std::less<std::string>()); 9470 9471 if (CurParsed == NewParsed) { 9472 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9473 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9474 NewFD->setInvalidDecl(); 9475 return true; 9476 } 9477 } 9478 9479 // Else, this is simply a non-redecl case. 9480 if (CheckMultiVersionValue(S, NewFD)) { 9481 NewFD->setInvalidDecl(); 9482 return true; 9483 } 9484 9485 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9486 NewFD->setInvalidDecl(); 9487 return true; 9488 } 9489 9490 NewFD->setIsMultiVersion(); 9491 Redeclaration = false; 9492 MergeTypeWithPrevious = false; 9493 OldDecl = nullptr; 9494 Previous.clear(); 9495 return false; 9496 } 9497 9498 /// \brief Perform semantic checking of a new function declaration. 9499 /// 9500 /// Performs semantic analysis of the new function declaration 9501 /// NewFD. This routine performs all semantic checking that does not 9502 /// require the actual declarator involved in the declaration, and is 9503 /// used both for the declaration of functions as they are parsed 9504 /// (called via ActOnDeclarator) and for the declaration of functions 9505 /// that have been instantiated via C++ template instantiation (called 9506 /// via InstantiateDecl). 9507 /// 9508 /// \param IsMemberSpecialization whether this new function declaration is 9509 /// a member specialization (that replaces any definition provided by the 9510 /// previous declaration). 9511 /// 9512 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9513 /// 9514 /// \returns true if the function declaration is a redeclaration. 9515 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9516 LookupResult &Previous, 9517 bool IsMemberSpecialization) { 9518 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9519 "Variably modified return types are not handled here"); 9520 9521 // Determine whether the type of this function should be merged with 9522 // a previous visible declaration. This never happens for functions in C++, 9523 // and always happens in C if the previous declaration was visible. 9524 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9525 !Previous.isShadowed(); 9526 9527 bool Redeclaration = false; 9528 NamedDecl *OldDecl = nullptr; 9529 bool MayNeedOverloadableChecks = false; 9530 9531 // Merge or overload the declaration with an existing declaration of 9532 // the same name, if appropriate. 9533 if (!Previous.empty()) { 9534 // Determine whether NewFD is an overload of PrevDecl or 9535 // a declaration that requires merging. If it's an overload, 9536 // there's no more work to do here; we'll just add the new 9537 // function to the scope. 9538 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9539 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9540 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9541 Redeclaration = true; 9542 OldDecl = Candidate; 9543 } 9544 } else { 9545 MayNeedOverloadableChecks = true; 9546 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9547 /*NewIsUsingDecl*/ false)) { 9548 case Ovl_Match: 9549 Redeclaration = true; 9550 break; 9551 9552 case Ovl_NonFunction: 9553 Redeclaration = true; 9554 break; 9555 9556 case Ovl_Overload: 9557 Redeclaration = false; 9558 break; 9559 } 9560 } 9561 } 9562 9563 // Check for a previous extern "C" declaration with this name. 9564 if (!Redeclaration && 9565 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9566 if (!Previous.empty()) { 9567 // This is an extern "C" declaration with the same name as a previous 9568 // declaration, and thus redeclares that entity... 9569 Redeclaration = true; 9570 OldDecl = Previous.getFoundDecl(); 9571 MergeTypeWithPrevious = false; 9572 9573 // ... except in the presence of __attribute__((overloadable)). 9574 if (OldDecl->hasAttr<OverloadableAttr>() || 9575 NewFD->hasAttr<OverloadableAttr>()) { 9576 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9577 MayNeedOverloadableChecks = true; 9578 Redeclaration = false; 9579 OldDecl = nullptr; 9580 } 9581 } 9582 } 9583 } 9584 9585 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9586 MergeTypeWithPrevious, Previous)) 9587 return Redeclaration; 9588 9589 // C++11 [dcl.constexpr]p8: 9590 // A constexpr specifier for a non-static member function that is not 9591 // a constructor declares that member function to be const. 9592 // 9593 // This needs to be delayed until we know whether this is an out-of-line 9594 // definition of a static member function. 9595 // 9596 // This rule is not present in C++1y, so we produce a backwards 9597 // compatibility warning whenever it happens in C++11. 9598 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9599 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9600 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9601 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9602 CXXMethodDecl *OldMD = nullptr; 9603 if (OldDecl) 9604 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9605 if (!OldMD || !OldMD->isStatic()) { 9606 const FunctionProtoType *FPT = 9607 MD->getType()->castAs<FunctionProtoType>(); 9608 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9609 EPI.TypeQuals |= Qualifiers::Const; 9610 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9611 FPT->getParamTypes(), EPI)); 9612 9613 // Warn that we did this, if we're not performing template instantiation. 9614 // In that case, we'll have warned already when the template was defined. 9615 if (!inTemplateInstantiation()) { 9616 SourceLocation AddConstLoc; 9617 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9618 .IgnoreParens().getAs<FunctionTypeLoc>()) 9619 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9620 9621 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9622 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9623 } 9624 } 9625 } 9626 9627 if (Redeclaration) { 9628 // NewFD and OldDecl represent declarations that need to be 9629 // merged. 9630 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9631 NewFD->setInvalidDecl(); 9632 return Redeclaration; 9633 } 9634 9635 Previous.clear(); 9636 Previous.addDecl(OldDecl); 9637 9638 if (FunctionTemplateDecl *OldTemplateDecl = 9639 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9640 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9641 NewFD->setPreviousDeclaration(OldFD); 9642 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9643 FunctionTemplateDecl *NewTemplateDecl 9644 = NewFD->getDescribedFunctionTemplate(); 9645 assert(NewTemplateDecl && "Template/non-template mismatch"); 9646 if (NewFD->isCXXClassMember()) { 9647 NewFD->setAccess(OldTemplateDecl->getAccess()); 9648 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9649 } 9650 9651 // If this is an explicit specialization of a member that is a function 9652 // template, mark it as a member specialization. 9653 if (IsMemberSpecialization && 9654 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9655 NewTemplateDecl->setMemberSpecialization(); 9656 assert(OldTemplateDecl->isMemberSpecialization()); 9657 // Explicit specializations of a member template do not inherit deleted 9658 // status from the parent member template that they are specializing. 9659 if (OldFD->isDeleted()) { 9660 // FIXME: This assert will not hold in the presence of modules. 9661 assert(OldFD->getCanonicalDecl() == OldFD); 9662 // FIXME: We need an update record for this AST mutation. 9663 OldFD->setDeletedAsWritten(false); 9664 } 9665 } 9666 9667 } else { 9668 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9669 auto *OldFD = cast<FunctionDecl>(OldDecl); 9670 // This needs to happen first so that 'inline' propagates. 9671 NewFD->setPreviousDeclaration(OldFD); 9672 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9673 if (NewFD->isCXXClassMember()) 9674 NewFD->setAccess(OldFD->getAccess()); 9675 } 9676 } 9677 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9678 !NewFD->getAttr<OverloadableAttr>()) { 9679 assert((Previous.empty() || 9680 llvm::any_of(Previous, 9681 [](const NamedDecl *ND) { 9682 return ND->hasAttr<OverloadableAttr>(); 9683 })) && 9684 "Non-redecls shouldn't happen without overloadable present"); 9685 9686 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9687 const auto *FD = dyn_cast<FunctionDecl>(ND); 9688 return FD && !FD->hasAttr<OverloadableAttr>(); 9689 }); 9690 9691 if (OtherUnmarkedIter != Previous.end()) { 9692 Diag(NewFD->getLocation(), 9693 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9694 Diag((*OtherUnmarkedIter)->getLocation(), 9695 diag::note_attribute_overloadable_prev_overload) 9696 << false; 9697 9698 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9699 } 9700 } 9701 9702 // Semantic checking for this function declaration (in isolation). 9703 9704 if (getLangOpts().CPlusPlus) { 9705 // C++-specific checks. 9706 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9707 CheckConstructor(Constructor); 9708 } else if (CXXDestructorDecl *Destructor = 9709 dyn_cast<CXXDestructorDecl>(NewFD)) { 9710 CXXRecordDecl *Record = Destructor->getParent(); 9711 QualType ClassType = Context.getTypeDeclType(Record); 9712 9713 // FIXME: Shouldn't we be able to perform this check even when the class 9714 // type is dependent? Both gcc and edg can handle that. 9715 if (!ClassType->isDependentType()) { 9716 DeclarationName Name 9717 = Context.DeclarationNames.getCXXDestructorName( 9718 Context.getCanonicalType(ClassType)); 9719 if (NewFD->getDeclName() != Name) { 9720 Diag(NewFD->getLocation(), diag::err_destructor_name); 9721 NewFD->setInvalidDecl(); 9722 return Redeclaration; 9723 } 9724 } 9725 } else if (CXXConversionDecl *Conversion 9726 = dyn_cast<CXXConversionDecl>(NewFD)) { 9727 ActOnConversionDeclarator(Conversion); 9728 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9729 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9730 CheckDeductionGuideTemplate(TD); 9731 9732 // A deduction guide is not on the list of entities that can be 9733 // explicitly specialized. 9734 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9735 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9736 << /*explicit specialization*/ 1; 9737 } 9738 9739 // Find any virtual functions that this function overrides. 9740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9741 if (!Method->isFunctionTemplateSpecialization() && 9742 !Method->getDescribedFunctionTemplate() && 9743 Method->isCanonicalDecl()) { 9744 if (AddOverriddenMethods(Method->getParent(), Method)) { 9745 // If the function was marked as "static", we have a problem. 9746 if (NewFD->getStorageClass() == SC_Static) { 9747 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9748 } 9749 } 9750 } 9751 9752 if (Method->isStatic()) 9753 checkThisInStaticMemberFunctionType(Method); 9754 } 9755 9756 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9757 if (NewFD->isOverloadedOperator() && 9758 CheckOverloadedOperatorDeclaration(NewFD)) { 9759 NewFD->setInvalidDecl(); 9760 return Redeclaration; 9761 } 9762 9763 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9764 if (NewFD->getLiteralIdentifier() && 9765 CheckLiteralOperatorDeclaration(NewFD)) { 9766 NewFD->setInvalidDecl(); 9767 return Redeclaration; 9768 } 9769 9770 // In C++, check default arguments now that we have merged decls. Unless 9771 // the lexical context is the class, because in this case this is done 9772 // during delayed parsing anyway. 9773 if (!CurContext->isRecord()) 9774 CheckCXXDefaultArguments(NewFD); 9775 9776 // If this function declares a builtin function, check the type of this 9777 // declaration against the expected type for the builtin. 9778 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9779 ASTContext::GetBuiltinTypeError Error; 9780 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9781 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9782 // If the type of the builtin differs only in its exception 9783 // specification, that's OK. 9784 // FIXME: If the types do differ in this way, it would be better to 9785 // retain the 'noexcept' form of the type. 9786 if (!T.isNull() && 9787 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9788 NewFD->getType())) 9789 // The type of this function differs from the type of the builtin, 9790 // so forget about the builtin entirely. 9791 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9792 } 9793 9794 // If this function is declared as being extern "C", then check to see if 9795 // the function returns a UDT (class, struct, or union type) that is not C 9796 // compatible, and if it does, warn the user. 9797 // But, issue any diagnostic on the first declaration only. 9798 if (Previous.empty() && NewFD->isExternC()) { 9799 QualType R = NewFD->getReturnType(); 9800 if (R->isIncompleteType() && !R->isVoidType()) 9801 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9802 << NewFD << R; 9803 else if (!R.isPODType(Context) && !R->isVoidType() && 9804 !R->isObjCObjectPointerType()) 9805 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9806 } 9807 9808 // C++1z [dcl.fct]p6: 9809 // [...] whether the function has a non-throwing exception-specification 9810 // [is] part of the function type 9811 // 9812 // This results in an ABI break between C++14 and C++17 for functions whose 9813 // declared type includes an exception-specification in a parameter or 9814 // return type. (Exception specifications on the function itself are OK in 9815 // most cases, and exception specifications are not permitted in most other 9816 // contexts where they could make it into a mangling.) 9817 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9818 auto HasNoexcept = [&](QualType T) -> bool { 9819 // Strip off declarator chunks that could be between us and a function 9820 // type. We don't need to look far, exception specifications are very 9821 // restricted prior to C++17. 9822 if (auto *RT = T->getAs<ReferenceType>()) 9823 T = RT->getPointeeType(); 9824 else if (T->isAnyPointerType()) 9825 T = T->getPointeeType(); 9826 else if (auto *MPT = T->getAs<MemberPointerType>()) 9827 T = MPT->getPointeeType(); 9828 if (auto *FPT = T->getAs<FunctionProtoType>()) 9829 if (FPT->isNothrow(Context)) 9830 return true; 9831 return false; 9832 }; 9833 9834 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9835 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9836 for (QualType T : FPT->param_types()) 9837 AnyNoexcept |= HasNoexcept(T); 9838 if (AnyNoexcept) 9839 Diag(NewFD->getLocation(), 9840 diag::warn_cxx17_compat_exception_spec_in_signature) 9841 << NewFD; 9842 } 9843 9844 if (!Redeclaration && LangOpts.CUDA) 9845 checkCUDATargetOverload(NewFD, Previous); 9846 } 9847 return Redeclaration; 9848 } 9849 9850 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9851 // C++11 [basic.start.main]p3: 9852 // A program that [...] declares main to be inline, static or 9853 // constexpr is ill-formed. 9854 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9855 // appear in a declaration of main. 9856 // static main is not an error under C99, but we should warn about it. 9857 // We accept _Noreturn main as an extension. 9858 if (FD->getStorageClass() == SC_Static) 9859 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9860 ? diag::err_static_main : diag::warn_static_main) 9861 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9862 if (FD->isInlineSpecified()) 9863 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9864 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9865 if (DS.isNoreturnSpecified()) { 9866 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9867 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9868 Diag(NoreturnLoc, diag::ext_noreturn_main); 9869 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9870 << FixItHint::CreateRemoval(NoreturnRange); 9871 } 9872 if (FD->isConstexpr()) { 9873 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9874 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9875 FD->setConstexpr(false); 9876 } 9877 9878 if (getLangOpts().OpenCL) { 9879 Diag(FD->getLocation(), diag::err_opencl_no_main) 9880 << FD->hasAttr<OpenCLKernelAttr>(); 9881 FD->setInvalidDecl(); 9882 return; 9883 } 9884 9885 QualType T = FD->getType(); 9886 assert(T->isFunctionType() && "function decl is not of function type"); 9887 const FunctionType* FT = T->castAs<FunctionType>(); 9888 9889 // Set default calling convention for main() 9890 if (FT->getCallConv() != CC_C) { 9891 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9892 FD->setType(QualType(FT, 0)); 9893 T = Context.getCanonicalType(FD->getType()); 9894 } 9895 9896 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9897 // In C with GNU extensions we allow main() to have non-integer return 9898 // type, but we should warn about the extension, and we disable the 9899 // implicit-return-zero rule. 9900 9901 // GCC in C mode accepts qualified 'int'. 9902 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9903 FD->setHasImplicitReturnZero(true); 9904 else { 9905 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9906 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9907 if (RTRange.isValid()) 9908 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9909 << FixItHint::CreateReplacement(RTRange, "int"); 9910 } 9911 } else { 9912 // In C and C++, main magically returns 0 if you fall off the end; 9913 // set the flag which tells us that. 9914 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9915 9916 // All the standards say that main() should return 'int'. 9917 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9918 FD->setHasImplicitReturnZero(true); 9919 else { 9920 // Otherwise, this is just a flat-out error. 9921 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9922 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9923 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9924 : FixItHint()); 9925 FD->setInvalidDecl(true); 9926 } 9927 } 9928 9929 // Treat protoless main() as nullary. 9930 if (isa<FunctionNoProtoType>(FT)) return; 9931 9932 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9933 unsigned nparams = FTP->getNumParams(); 9934 assert(FD->getNumParams() == nparams); 9935 9936 bool HasExtraParameters = (nparams > 3); 9937 9938 if (FTP->isVariadic()) { 9939 Diag(FD->getLocation(), diag::ext_variadic_main); 9940 // FIXME: if we had information about the location of the ellipsis, we 9941 // could add a FixIt hint to remove it as a parameter. 9942 } 9943 9944 // Darwin passes an undocumented fourth argument of type char**. If 9945 // other platforms start sprouting these, the logic below will start 9946 // getting shifty. 9947 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9948 HasExtraParameters = false; 9949 9950 if (HasExtraParameters) { 9951 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9952 FD->setInvalidDecl(true); 9953 nparams = 3; 9954 } 9955 9956 // FIXME: a lot of the following diagnostics would be improved 9957 // if we had some location information about types. 9958 9959 QualType CharPP = 9960 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9961 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9962 9963 for (unsigned i = 0; i < nparams; ++i) { 9964 QualType AT = FTP->getParamType(i); 9965 9966 bool mismatch = true; 9967 9968 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9969 mismatch = false; 9970 else if (Expected[i] == CharPP) { 9971 // As an extension, the following forms are okay: 9972 // char const ** 9973 // char const * const * 9974 // char * const * 9975 9976 QualifierCollector qs; 9977 const PointerType* PT; 9978 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9979 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9980 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9981 Context.CharTy)) { 9982 qs.removeConst(); 9983 mismatch = !qs.empty(); 9984 } 9985 } 9986 9987 if (mismatch) { 9988 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9989 // TODO: suggest replacing given type with expected type 9990 FD->setInvalidDecl(true); 9991 } 9992 } 9993 9994 if (nparams == 1 && !FD->isInvalidDecl()) { 9995 Diag(FD->getLocation(), diag::warn_main_one_arg); 9996 } 9997 9998 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9999 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10000 FD->setInvalidDecl(); 10001 } 10002 } 10003 10004 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10005 QualType T = FD->getType(); 10006 assert(T->isFunctionType() && "function decl is not of function type"); 10007 const FunctionType *FT = T->castAs<FunctionType>(); 10008 10009 // Set an implicit return of 'zero' if the function can return some integral, 10010 // enumeration, pointer or nullptr type. 10011 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10012 FT->getReturnType()->isAnyPointerType() || 10013 FT->getReturnType()->isNullPtrType()) 10014 // DllMain is exempt because a return value of zero means it failed. 10015 if (FD->getName() != "DllMain") 10016 FD->setHasImplicitReturnZero(true); 10017 10018 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10019 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10020 FD->setInvalidDecl(); 10021 } 10022 } 10023 10024 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10025 // FIXME: Need strict checking. In C89, we need to check for 10026 // any assignment, increment, decrement, function-calls, or 10027 // commas outside of a sizeof. In C99, it's the same list, 10028 // except that the aforementioned are allowed in unevaluated 10029 // expressions. Everything else falls under the 10030 // "may accept other forms of constant expressions" exception. 10031 // (We never end up here for C++, so the constant expression 10032 // rules there don't matter.) 10033 const Expr *Culprit; 10034 if (Init->isConstantInitializer(Context, false, &Culprit)) 10035 return false; 10036 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10037 << Culprit->getSourceRange(); 10038 return true; 10039 } 10040 10041 namespace { 10042 // Visits an initialization expression to see if OrigDecl is evaluated in 10043 // its own initialization and throws a warning if it does. 10044 class SelfReferenceChecker 10045 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10046 Sema &S; 10047 Decl *OrigDecl; 10048 bool isRecordType; 10049 bool isPODType; 10050 bool isReferenceType; 10051 10052 bool isInitList; 10053 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10054 10055 public: 10056 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10057 10058 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10059 S(S), OrigDecl(OrigDecl) { 10060 isPODType = false; 10061 isRecordType = false; 10062 isReferenceType = false; 10063 isInitList = false; 10064 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10065 isPODType = VD->getType().isPODType(S.Context); 10066 isRecordType = VD->getType()->isRecordType(); 10067 isReferenceType = VD->getType()->isReferenceType(); 10068 } 10069 } 10070 10071 // For most expressions, just call the visitor. For initializer lists, 10072 // track the index of the field being initialized since fields are 10073 // initialized in order allowing use of previously initialized fields. 10074 void CheckExpr(Expr *E) { 10075 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10076 if (!InitList) { 10077 Visit(E); 10078 return; 10079 } 10080 10081 // Track and increment the index here. 10082 isInitList = true; 10083 InitFieldIndex.push_back(0); 10084 for (auto Child : InitList->children()) { 10085 CheckExpr(cast<Expr>(Child)); 10086 ++InitFieldIndex.back(); 10087 } 10088 InitFieldIndex.pop_back(); 10089 } 10090 10091 // Returns true if MemberExpr is checked and no further checking is needed. 10092 // Returns false if additional checking is required. 10093 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10094 llvm::SmallVector<FieldDecl*, 4> Fields; 10095 Expr *Base = E; 10096 bool ReferenceField = false; 10097 10098 // Get the field memebers used. 10099 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10100 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10101 if (!FD) 10102 return false; 10103 Fields.push_back(FD); 10104 if (FD->getType()->isReferenceType()) 10105 ReferenceField = true; 10106 Base = ME->getBase()->IgnoreParenImpCasts(); 10107 } 10108 10109 // Keep checking only if the base Decl is the same. 10110 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10111 if (!DRE || DRE->getDecl() != OrigDecl) 10112 return false; 10113 10114 // A reference field can be bound to an unininitialized field. 10115 if (CheckReference && !ReferenceField) 10116 return true; 10117 10118 // Convert FieldDecls to their index number. 10119 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10120 for (const FieldDecl *I : llvm::reverse(Fields)) 10121 UsedFieldIndex.push_back(I->getFieldIndex()); 10122 10123 // See if a warning is needed by checking the first difference in index 10124 // numbers. If field being used has index less than the field being 10125 // initialized, then the use is safe. 10126 for (auto UsedIter = UsedFieldIndex.begin(), 10127 UsedEnd = UsedFieldIndex.end(), 10128 OrigIter = InitFieldIndex.begin(), 10129 OrigEnd = InitFieldIndex.end(); 10130 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10131 if (*UsedIter < *OrigIter) 10132 return true; 10133 if (*UsedIter > *OrigIter) 10134 break; 10135 } 10136 10137 // TODO: Add a different warning which will print the field names. 10138 HandleDeclRefExpr(DRE); 10139 return true; 10140 } 10141 10142 // For most expressions, the cast is directly above the DeclRefExpr. 10143 // For conditional operators, the cast can be outside the conditional 10144 // operator if both expressions are DeclRefExpr's. 10145 void HandleValue(Expr *E) { 10146 E = E->IgnoreParens(); 10147 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10148 HandleDeclRefExpr(DRE); 10149 return; 10150 } 10151 10152 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10153 Visit(CO->getCond()); 10154 HandleValue(CO->getTrueExpr()); 10155 HandleValue(CO->getFalseExpr()); 10156 return; 10157 } 10158 10159 if (BinaryConditionalOperator *BCO = 10160 dyn_cast<BinaryConditionalOperator>(E)) { 10161 Visit(BCO->getCond()); 10162 HandleValue(BCO->getFalseExpr()); 10163 return; 10164 } 10165 10166 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10167 HandleValue(OVE->getSourceExpr()); 10168 return; 10169 } 10170 10171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10172 if (BO->getOpcode() == BO_Comma) { 10173 Visit(BO->getLHS()); 10174 HandleValue(BO->getRHS()); 10175 return; 10176 } 10177 } 10178 10179 if (isa<MemberExpr>(E)) { 10180 if (isInitList) { 10181 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10182 false /*CheckReference*/)) 10183 return; 10184 } 10185 10186 Expr *Base = E->IgnoreParenImpCasts(); 10187 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10188 // Check for static member variables and don't warn on them. 10189 if (!isa<FieldDecl>(ME->getMemberDecl())) 10190 return; 10191 Base = ME->getBase()->IgnoreParenImpCasts(); 10192 } 10193 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10194 HandleDeclRefExpr(DRE); 10195 return; 10196 } 10197 10198 Visit(E); 10199 } 10200 10201 // Reference types not handled in HandleValue are handled here since all 10202 // uses of references are bad, not just r-value uses. 10203 void VisitDeclRefExpr(DeclRefExpr *E) { 10204 if (isReferenceType) 10205 HandleDeclRefExpr(E); 10206 } 10207 10208 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10209 if (E->getCastKind() == CK_LValueToRValue) { 10210 HandleValue(E->getSubExpr()); 10211 return; 10212 } 10213 10214 Inherited::VisitImplicitCastExpr(E); 10215 } 10216 10217 void VisitMemberExpr(MemberExpr *E) { 10218 if (isInitList) { 10219 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10220 return; 10221 } 10222 10223 // Don't warn on arrays since they can be treated as pointers. 10224 if (E->getType()->canDecayToPointerType()) return; 10225 10226 // Warn when a non-static method call is followed by non-static member 10227 // field accesses, which is followed by a DeclRefExpr. 10228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10229 bool Warn = (MD && !MD->isStatic()); 10230 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10231 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10232 if (!isa<FieldDecl>(ME->getMemberDecl())) 10233 Warn = false; 10234 Base = ME->getBase()->IgnoreParenImpCasts(); 10235 } 10236 10237 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10238 if (Warn) 10239 HandleDeclRefExpr(DRE); 10240 return; 10241 } 10242 10243 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10244 // Visit that expression. 10245 Visit(Base); 10246 } 10247 10248 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10249 Expr *Callee = E->getCallee(); 10250 10251 if (isa<UnresolvedLookupExpr>(Callee)) 10252 return Inherited::VisitCXXOperatorCallExpr(E); 10253 10254 Visit(Callee); 10255 for (auto Arg: E->arguments()) 10256 HandleValue(Arg->IgnoreParenImpCasts()); 10257 } 10258 10259 void VisitUnaryOperator(UnaryOperator *E) { 10260 // For POD record types, addresses of its own members are well-defined. 10261 if (E->getOpcode() == UO_AddrOf && isRecordType && 10262 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10263 if (!isPODType) 10264 HandleValue(E->getSubExpr()); 10265 return; 10266 } 10267 10268 if (E->isIncrementDecrementOp()) { 10269 HandleValue(E->getSubExpr()); 10270 return; 10271 } 10272 10273 Inherited::VisitUnaryOperator(E); 10274 } 10275 10276 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10277 10278 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10279 if (E->getConstructor()->isCopyConstructor()) { 10280 Expr *ArgExpr = E->getArg(0); 10281 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10282 if (ILE->getNumInits() == 1) 10283 ArgExpr = ILE->getInit(0); 10284 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10285 if (ICE->getCastKind() == CK_NoOp) 10286 ArgExpr = ICE->getSubExpr(); 10287 HandleValue(ArgExpr); 10288 return; 10289 } 10290 Inherited::VisitCXXConstructExpr(E); 10291 } 10292 10293 void VisitCallExpr(CallExpr *E) { 10294 // Treat std::move as a use. 10295 if (E->isCallToStdMove()) { 10296 HandleValue(E->getArg(0)); 10297 return; 10298 } 10299 10300 Inherited::VisitCallExpr(E); 10301 } 10302 10303 void VisitBinaryOperator(BinaryOperator *E) { 10304 if (E->isCompoundAssignmentOp()) { 10305 HandleValue(E->getLHS()); 10306 Visit(E->getRHS()); 10307 return; 10308 } 10309 10310 Inherited::VisitBinaryOperator(E); 10311 } 10312 10313 // A custom visitor for BinaryConditionalOperator is needed because the 10314 // regular visitor would check the condition and true expression separately 10315 // but both point to the same place giving duplicate diagnostics. 10316 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10317 Visit(E->getCond()); 10318 Visit(E->getFalseExpr()); 10319 } 10320 10321 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10322 Decl* ReferenceDecl = DRE->getDecl(); 10323 if (OrigDecl != ReferenceDecl) return; 10324 unsigned diag; 10325 if (isReferenceType) { 10326 diag = diag::warn_uninit_self_reference_in_reference_init; 10327 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10328 diag = diag::warn_static_self_reference_in_init; 10329 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10330 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10331 DRE->getDecl()->getType()->isRecordType()) { 10332 diag = diag::warn_uninit_self_reference_in_init; 10333 } else { 10334 // Local variables will be handled by the CFG analysis. 10335 return; 10336 } 10337 10338 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10339 S.PDiag(diag) 10340 << DRE->getDecl() 10341 << OrigDecl->getLocation() 10342 << DRE->getSourceRange()); 10343 } 10344 }; 10345 10346 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10347 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10348 bool DirectInit) { 10349 // Parameters arguments are occassionially constructed with itself, 10350 // for instance, in recursive functions. Skip them. 10351 if (isa<ParmVarDecl>(OrigDecl)) 10352 return; 10353 10354 E = E->IgnoreParens(); 10355 10356 // Skip checking T a = a where T is not a record or reference type. 10357 // Doing so is a way to silence uninitialized warnings. 10358 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10359 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10360 if (ICE->getCastKind() == CK_LValueToRValue) 10361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10362 if (DRE->getDecl() == OrigDecl) 10363 return; 10364 10365 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10366 } 10367 } // end anonymous namespace 10368 10369 namespace { 10370 // Simple wrapper to add the name of a variable or (if no variable is 10371 // available) a DeclarationName into a diagnostic. 10372 struct VarDeclOrName { 10373 VarDecl *VDecl; 10374 DeclarationName Name; 10375 10376 friend const Sema::SemaDiagnosticBuilder & 10377 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10378 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10379 } 10380 }; 10381 } // end anonymous namespace 10382 10383 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10384 DeclarationName Name, QualType Type, 10385 TypeSourceInfo *TSI, 10386 SourceRange Range, bool DirectInit, 10387 Expr *Init) { 10388 bool IsInitCapture = !VDecl; 10389 assert((!VDecl || !VDecl->isInitCapture()) && 10390 "init captures are expected to be deduced prior to initialization"); 10391 10392 VarDeclOrName VN{VDecl, Name}; 10393 10394 DeducedType *Deduced = Type->getContainedDeducedType(); 10395 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10396 10397 // C++11 [dcl.spec.auto]p3 10398 if (!Init) { 10399 assert(VDecl && "no init for init capture deduction?"); 10400 10401 // Except for class argument deduction, and then for an initializing 10402 // declaration only, i.e. no static at class scope or extern. 10403 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10404 VDecl->hasExternalStorage() || 10405 VDecl->isStaticDataMember()) { 10406 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10407 << VDecl->getDeclName() << Type; 10408 return QualType(); 10409 } 10410 } 10411 10412 ArrayRef<Expr*> DeduceInits; 10413 if (Init) 10414 DeduceInits = Init; 10415 10416 if (DirectInit) { 10417 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10418 DeduceInits = PL->exprs(); 10419 } 10420 10421 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10422 assert(VDecl && "non-auto type for init capture deduction?"); 10423 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10424 InitializationKind Kind = InitializationKind::CreateForInit( 10425 VDecl->getLocation(), DirectInit, Init); 10426 // FIXME: Initialization should not be taking a mutable list of inits. 10427 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10428 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10429 InitsCopy); 10430 } 10431 10432 if (DirectInit) { 10433 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10434 DeduceInits = IL->inits(); 10435 } 10436 10437 // Deduction only works if we have exactly one source expression. 10438 if (DeduceInits.empty()) { 10439 // It isn't possible to write this directly, but it is possible to 10440 // end up in this situation with "auto x(some_pack...);" 10441 Diag(Init->getLocStart(), IsInitCapture 10442 ? diag::err_init_capture_no_expression 10443 : diag::err_auto_var_init_no_expression) 10444 << VN << Type << Range; 10445 return QualType(); 10446 } 10447 10448 if (DeduceInits.size() > 1) { 10449 Diag(DeduceInits[1]->getLocStart(), 10450 IsInitCapture ? diag::err_init_capture_multiple_expressions 10451 : diag::err_auto_var_init_multiple_expressions) 10452 << VN << Type << Range; 10453 return QualType(); 10454 } 10455 10456 Expr *DeduceInit = DeduceInits[0]; 10457 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10458 Diag(Init->getLocStart(), IsInitCapture 10459 ? diag::err_init_capture_paren_braces 10460 : diag::err_auto_var_init_paren_braces) 10461 << isa<InitListExpr>(Init) << VN << Type << Range; 10462 return QualType(); 10463 } 10464 10465 // Expressions default to 'id' when we're in a debugger. 10466 bool DefaultedAnyToId = false; 10467 if (getLangOpts().DebuggerCastResultToId && 10468 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10469 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10470 if (Result.isInvalid()) { 10471 return QualType(); 10472 } 10473 Init = Result.get(); 10474 DefaultedAnyToId = true; 10475 } 10476 10477 // C++ [dcl.decomp]p1: 10478 // If the assignment-expression [...] has array type A and no ref-qualifier 10479 // is present, e has type cv A 10480 if (VDecl && isa<DecompositionDecl>(VDecl) && 10481 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10482 DeduceInit->getType()->isConstantArrayType()) 10483 return Context.getQualifiedType(DeduceInit->getType(), 10484 Type.getQualifiers()); 10485 10486 QualType DeducedType; 10487 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10488 if (!IsInitCapture) 10489 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10490 else if (isa<InitListExpr>(Init)) 10491 Diag(Range.getBegin(), 10492 diag::err_init_capture_deduction_failure_from_init_list) 10493 << VN 10494 << (DeduceInit->getType().isNull() ? TSI->getType() 10495 : DeduceInit->getType()) 10496 << DeduceInit->getSourceRange(); 10497 else 10498 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10499 << VN << TSI->getType() 10500 << (DeduceInit->getType().isNull() ? TSI->getType() 10501 : DeduceInit->getType()) 10502 << DeduceInit->getSourceRange(); 10503 } 10504 10505 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10506 // 'id' instead of a specific object type prevents most of our usual 10507 // checks. 10508 // We only want to warn outside of template instantiations, though: 10509 // inside a template, the 'id' could have come from a parameter. 10510 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10511 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10512 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10513 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10514 } 10515 10516 return DeducedType; 10517 } 10518 10519 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10520 Expr *Init) { 10521 QualType DeducedType = deduceVarTypeFromInitializer( 10522 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10523 VDecl->getSourceRange(), DirectInit, Init); 10524 if (DeducedType.isNull()) { 10525 VDecl->setInvalidDecl(); 10526 return true; 10527 } 10528 10529 VDecl->setType(DeducedType); 10530 assert(VDecl->isLinkageValid()); 10531 10532 // In ARC, infer lifetime. 10533 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10534 VDecl->setInvalidDecl(); 10535 10536 // If this is a redeclaration, check that the type we just deduced matches 10537 // the previously declared type. 10538 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10539 // We never need to merge the type, because we cannot form an incomplete 10540 // array of auto, nor deduce such a type. 10541 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10542 } 10543 10544 // Check the deduced type is valid for a variable declaration. 10545 CheckVariableDeclarationType(VDecl); 10546 return VDecl->isInvalidDecl(); 10547 } 10548 10549 /// AddInitializerToDecl - Adds the initializer Init to the 10550 /// declaration dcl. If DirectInit is true, this is C++ direct 10551 /// initialization rather than copy initialization. 10552 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10553 // If there is no declaration, there was an error parsing it. Just ignore 10554 // the initializer. 10555 if (!RealDecl || RealDecl->isInvalidDecl()) { 10556 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10557 return; 10558 } 10559 10560 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10561 // Pure-specifiers are handled in ActOnPureSpecifier. 10562 Diag(Method->getLocation(), diag::err_member_function_initialization) 10563 << Method->getDeclName() << Init->getSourceRange(); 10564 Method->setInvalidDecl(); 10565 return; 10566 } 10567 10568 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10569 if (!VDecl) { 10570 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10571 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10572 RealDecl->setInvalidDecl(); 10573 return; 10574 } 10575 10576 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10577 if (VDecl->getType()->isUndeducedType()) { 10578 // Attempt typo correction early so that the type of the init expression can 10579 // be deduced based on the chosen correction if the original init contains a 10580 // TypoExpr. 10581 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10582 if (!Res.isUsable()) { 10583 RealDecl->setInvalidDecl(); 10584 return; 10585 } 10586 Init = Res.get(); 10587 10588 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10589 return; 10590 } 10591 10592 // dllimport cannot be used on variable definitions. 10593 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10594 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10595 VDecl->setInvalidDecl(); 10596 return; 10597 } 10598 10599 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10600 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10601 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10602 VDecl->setInvalidDecl(); 10603 return; 10604 } 10605 10606 if (!VDecl->getType()->isDependentType()) { 10607 // A definition must end up with a complete type, which means it must be 10608 // complete with the restriction that an array type might be completed by 10609 // the initializer; note that later code assumes this restriction. 10610 QualType BaseDeclType = VDecl->getType(); 10611 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10612 BaseDeclType = Array->getElementType(); 10613 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10614 diag::err_typecheck_decl_incomplete_type)) { 10615 RealDecl->setInvalidDecl(); 10616 return; 10617 } 10618 10619 // The variable can not have an abstract class type. 10620 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10621 diag::err_abstract_type_in_decl, 10622 AbstractVariableType)) 10623 VDecl->setInvalidDecl(); 10624 } 10625 10626 // If adding the initializer will turn this declaration into a definition, 10627 // and we already have a definition for this variable, diagnose or otherwise 10628 // handle the situation. 10629 VarDecl *Def; 10630 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10631 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10632 !VDecl->isThisDeclarationADemotedDefinition() && 10633 checkVarDeclRedefinition(Def, VDecl)) 10634 return; 10635 10636 if (getLangOpts().CPlusPlus) { 10637 // C++ [class.static.data]p4 10638 // If a static data member is of const integral or const 10639 // enumeration type, its declaration in the class definition can 10640 // specify a constant-initializer which shall be an integral 10641 // constant expression (5.19). In that case, the member can appear 10642 // in integral constant expressions. The member shall still be 10643 // defined in a namespace scope if it is used in the program and the 10644 // namespace scope definition shall not contain an initializer. 10645 // 10646 // We already performed a redefinition check above, but for static 10647 // data members we also need to check whether there was an in-class 10648 // declaration with an initializer. 10649 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10650 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10651 << VDecl->getDeclName(); 10652 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10653 diag::note_previous_initializer) 10654 << 0; 10655 return; 10656 } 10657 10658 if (VDecl->hasLocalStorage()) 10659 setFunctionHasBranchProtectedScope(); 10660 10661 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10662 VDecl->setInvalidDecl(); 10663 return; 10664 } 10665 } 10666 10667 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10668 // a kernel function cannot be initialized." 10669 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10670 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10671 VDecl->setInvalidDecl(); 10672 return; 10673 } 10674 10675 // Get the decls type and save a reference for later, since 10676 // CheckInitializerTypes may change it. 10677 QualType DclT = VDecl->getType(), SavT = DclT; 10678 10679 // Expressions default to 'id' when we're in a debugger 10680 // and we are assigning it to a variable of Objective-C pointer type. 10681 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10682 Init->getType() == Context.UnknownAnyTy) { 10683 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10684 if (Result.isInvalid()) { 10685 VDecl->setInvalidDecl(); 10686 return; 10687 } 10688 Init = Result.get(); 10689 } 10690 10691 // Perform the initialization. 10692 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10693 if (!VDecl->isInvalidDecl()) { 10694 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10695 InitializationKind Kind = InitializationKind::CreateForInit( 10696 VDecl->getLocation(), DirectInit, Init); 10697 10698 MultiExprArg Args = Init; 10699 if (CXXDirectInit) 10700 Args = MultiExprArg(CXXDirectInit->getExprs(), 10701 CXXDirectInit->getNumExprs()); 10702 10703 // Try to correct any TypoExprs in the initialization arguments. 10704 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10705 ExprResult Res = CorrectDelayedTyposInExpr( 10706 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10707 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10708 return Init.Failed() ? ExprError() : E; 10709 }); 10710 if (Res.isInvalid()) { 10711 VDecl->setInvalidDecl(); 10712 } else if (Res.get() != Args[Idx]) { 10713 Args[Idx] = Res.get(); 10714 } 10715 } 10716 if (VDecl->isInvalidDecl()) 10717 return; 10718 10719 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10720 /*TopLevelOfInitList=*/false, 10721 /*TreatUnavailableAsInvalid=*/false); 10722 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10723 if (Result.isInvalid()) { 10724 VDecl->setInvalidDecl(); 10725 return; 10726 } 10727 10728 Init = Result.getAs<Expr>(); 10729 } 10730 10731 // Check for self-references within variable initializers. 10732 // Variables declared within a function/method body (except for references) 10733 // are handled by a dataflow analysis. 10734 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10735 VDecl->getType()->isReferenceType()) { 10736 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10737 } 10738 10739 // If the type changed, it means we had an incomplete type that was 10740 // completed by the initializer. For example: 10741 // int ary[] = { 1, 3, 5 }; 10742 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10743 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10744 VDecl->setType(DclT); 10745 10746 if (!VDecl->isInvalidDecl()) { 10747 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10748 10749 if (VDecl->hasAttr<BlocksAttr>()) 10750 checkRetainCycles(VDecl, Init); 10751 10752 // It is safe to assign a weak reference into a strong variable. 10753 // Although this code can still have problems: 10754 // id x = self.weakProp; 10755 // id y = self.weakProp; 10756 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10757 // paths through the function. This should be revisited if 10758 // -Wrepeated-use-of-weak is made flow-sensitive. 10759 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10760 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10762 Init->getLocStart())) 10763 getCurFunction()->markSafeWeakUse(Init); 10764 } 10765 10766 // The initialization is usually a full-expression. 10767 // 10768 // FIXME: If this is a braced initialization of an aggregate, it is not 10769 // an expression, and each individual field initializer is a separate 10770 // full-expression. For instance, in: 10771 // 10772 // struct Temp { ~Temp(); }; 10773 // struct S { S(Temp); }; 10774 // struct T { S a, b; } t = { Temp(), Temp() } 10775 // 10776 // we should destroy the first Temp before constructing the second. 10777 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10778 false, 10779 VDecl->isConstexpr()); 10780 if (Result.isInvalid()) { 10781 VDecl->setInvalidDecl(); 10782 return; 10783 } 10784 Init = Result.get(); 10785 10786 // Attach the initializer to the decl. 10787 VDecl->setInit(Init); 10788 10789 if (VDecl->isLocalVarDecl()) { 10790 // Don't check the initializer if the declaration is malformed. 10791 if (VDecl->isInvalidDecl()) { 10792 // do nothing 10793 10794 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10795 // This is true even in OpenCL C++. 10796 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10797 CheckForConstantInitializer(Init, DclT); 10798 10799 // Otherwise, C++ does not restrict the initializer. 10800 } else if (getLangOpts().CPlusPlus) { 10801 // do nothing 10802 10803 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10804 // static storage duration shall be constant expressions or string literals. 10805 } else if (VDecl->getStorageClass() == SC_Static) { 10806 CheckForConstantInitializer(Init, DclT); 10807 10808 // C89 is stricter than C99 for aggregate initializers. 10809 // C89 6.5.7p3: All the expressions [...] in an initializer list 10810 // for an object that has aggregate or union type shall be 10811 // constant expressions. 10812 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10813 isa<InitListExpr>(Init)) { 10814 const Expr *Culprit; 10815 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10816 Diag(Culprit->getExprLoc(), 10817 diag::ext_aggregate_init_not_constant) 10818 << Culprit->getSourceRange(); 10819 } 10820 } 10821 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10822 VDecl->getLexicalDeclContext()->isRecord()) { 10823 // This is an in-class initialization for a static data member, e.g., 10824 // 10825 // struct S { 10826 // static const int value = 17; 10827 // }; 10828 10829 // C++ [class.mem]p4: 10830 // A member-declarator can contain a constant-initializer only 10831 // if it declares a static member (9.4) of const integral or 10832 // const enumeration type, see 9.4.2. 10833 // 10834 // C++11 [class.static.data]p3: 10835 // If a non-volatile non-inline const static data member is of integral 10836 // or enumeration type, its declaration in the class definition can 10837 // specify a brace-or-equal-initializer in which every initializer-clause 10838 // that is an assignment-expression is a constant expression. A static 10839 // data member of literal type can be declared in the class definition 10840 // with the constexpr specifier; if so, its declaration shall specify a 10841 // brace-or-equal-initializer in which every initializer-clause that is 10842 // an assignment-expression is a constant expression. 10843 10844 // Do nothing on dependent types. 10845 if (DclT->isDependentType()) { 10846 10847 // Allow any 'static constexpr' members, whether or not they are of literal 10848 // type. We separately check that every constexpr variable is of literal 10849 // type. 10850 } else if (VDecl->isConstexpr()) { 10851 10852 // Require constness. 10853 } else if (!DclT.isConstQualified()) { 10854 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10855 << Init->getSourceRange(); 10856 VDecl->setInvalidDecl(); 10857 10858 // We allow integer constant expressions in all cases. 10859 } else if (DclT->isIntegralOrEnumerationType()) { 10860 // Check whether the expression is a constant expression. 10861 SourceLocation Loc; 10862 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10863 // In C++11, a non-constexpr const static data member with an 10864 // in-class initializer cannot be volatile. 10865 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10866 else if (Init->isValueDependent()) 10867 ; // Nothing to check. 10868 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10869 ; // Ok, it's an ICE! 10870 else if (Init->isEvaluatable(Context)) { 10871 // If we can constant fold the initializer through heroics, accept it, 10872 // but report this as a use of an extension for -pedantic. 10873 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10874 << Init->getSourceRange(); 10875 } else { 10876 // Otherwise, this is some crazy unknown case. Report the issue at the 10877 // location provided by the isIntegerConstantExpr failed check. 10878 Diag(Loc, diag::err_in_class_initializer_non_constant) 10879 << Init->getSourceRange(); 10880 VDecl->setInvalidDecl(); 10881 } 10882 10883 // We allow foldable floating-point constants as an extension. 10884 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10885 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10886 // it anyway and provide a fixit to add the 'constexpr'. 10887 if (getLangOpts().CPlusPlus11) { 10888 Diag(VDecl->getLocation(), 10889 diag::ext_in_class_initializer_float_type_cxx11) 10890 << DclT << Init->getSourceRange(); 10891 Diag(VDecl->getLocStart(), 10892 diag::note_in_class_initializer_float_type_cxx11) 10893 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10894 } else { 10895 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10896 << DclT << Init->getSourceRange(); 10897 10898 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10899 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10900 << Init->getSourceRange(); 10901 VDecl->setInvalidDecl(); 10902 } 10903 } 10904 10905 // Suggest adding 'constexpr' in C++11 for literal types. 10906 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10907 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10908 << DclT << Init->getSourceRange() 10909 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10910 VDecl->setConstexpr(true); 10911 10912 } else { 10913 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10914 << DclT << Init->getSourceRange(); 10915 VDecl->setInvalidDecl(); 10916 } 10917 } else if (VDecl->isFileVarDecl()) { 10918 // In C, extern is typically used to avoid tentative definitions when 10919 // declaring variables in headers, but adding an intializer makes it a 10920 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 10921 // In C++, extern is often used to give implictly static const variables 10922 // external linkage, so don't warn in that case. If selectany is present, 10923 // this might be header code intended for C and C++ inclusion, so apply the 10924 // C++ rules. 10925 if (VDecl->getStorageClass() == SC_Extern && 10926 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10927 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10928 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10929 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10930 Diag(VDecl->getLocation(), diag::warn_extern_init); 10931 10932 // C99 6.7.8p4. All file scoped initializers need to be constant. 10933 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10934 CheckForConstantInitializer(Init, DclT); 10935 } 10936 10937 // We will represent direct-initialization similarly to copy-initialization: 10938 // int x(1); -as-> int x = 1; 10939 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10940 // 10941 // Clients that want to distinguish between the two forms, can check for 10942 // direct initializer using VarDecl::getInitStyle(). 10943 // A major benefit is that clients that don't particularly care about which 10944 // exactly form was it (like the CodeGen) can handle both cases without 10945 // special case code. 10946 10947 // C++ 8.5p11: 10948 // The form of initialization (using parentheses or '=') is generally 10949 // insignificant, but does matter when the entity being initialized has a 10950 // class type. 10951 if (CXXDirectInit) { 10952 assert(DirectInit && "Call-style initializer must be direct init."); 10953 VDecl->setInitStyle(VarDecl::CallInit); 10954 } else if (DirectInit) { 10955 // This must be list-initialization. No other way is direct-initialization. 10956 VDecl->setInitStyle(VarDecl::ListInit); 10957 } 10958 10959 CheckCompleteVariableDeclaration(VDecl); 10960 } 10961 10962 /// ActOnInitializerError - Given that there was an error parsing an 10963 /// initializer for the given declaration, try to return to some form 10964 /// of sanity. 10965 void Sema::ActOnInitializerError(Decl *D) { 10966 // Our main concern here is re-establishing invariants like "a 10967 // variable's type is either dependent or complete". 10968 if (!D || D->isInvalidDecl()) return; 10969 10970 VarDecl *VD = dyn_cast<VarDecl>(D); 10971 if (!VD) return; 10972 10973 // Bindings are not usable if we can't make sense of the initializer. 10974 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10975 for (auto *BD : DD->bindings()) 10976 BD->setInvalidDecl(); 10977 10978 // Auto types are meaningless if we can't make sense of the initializer. 10979 if (ParsingInitForAutoVars.count(D)) { 10980 D->setInvalidDecl(); 10981 return; 10982 } 10983 10984 QualType Ty = VD->getType(); 10985 if (Ty->isDependentType()) return; 10986 10987 // Require a complete type. 10988 if (RequireCompleteType(VD->getLocation(), 10989 Context.getBaseElementType(Ty), 10990 diag::err_typecheck_decl_incomplete_type)) { 10991 VD->setInvalidDecl(); 10992 return; 10993 } 10994 10995 // Require a non-abstract type. 10996 if (RequireNonAbstractType(VD->getLocation(), Ty, 10997 diag::err_abstract_type_in_decl, 10998 AbstractVariableType)) { 10999 VD->setInvalidDecl(); 11000 return; 11001 } 11002 11003 // Don't bother complaining about constructors or destructors, 11004 // though. 11005 } 11006 11007 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11008 // If there is no declaration, there was an error parsing it. Just ignore it. 11009 if (!RealDecl) 11010 return; 11011 11012 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11013 QualType Type = Var->getType(); 11014 11015 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11016 if (isa<DecompositionDecl>(RealDecl)) { 11017 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11018 Var->setInvalidDecl(); 11019 return; 11020 } 11021 11022 if (Type->isUndeducedType() && 11023 DeduceVariableDeclarationType(Var, false, nullptr)) 11024 return; 11025 11026 // C++11 [class.static.data]p3: A static data member can be declared with 11027 // the constexpr specifier; if so, its declaration shall specify 11028 // a brace-or-equal-initializer. 11029 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11030 // the definition of a variable [...] or the declaration of a static data 11031 // member. 11032 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11033 !Var->isThisDeclarationADemotedDefinition()) { 11034 if (Var->isStaticDataMember()) { 11035 // C++1z removes the relevant rule; the in-class declaration is always 11036 // a definition there. 11037 if (!getLangOpts().CPlusPlus17) { 11038 Diag(Var->getLocation(), 11039 diag::err_constexpr_static_mem_var_requires_init) 11040 << Var->getDeclName(); 11041 Var->setInvalidDecl(); 11042 return; 11043 } 11044 } else { 11045 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11046 Var->setInvalidDecl(); 11047 return; 11048 } 11049 } 11050 11051 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11052 // be initialized. 11053 if (!Var->isInvalidDecl() && 11054 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11055 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11056 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11057 Var->setInvalidDecl(); 11058 return; 11059 } 11060 11061 switch (Var->isThisDeclarationADefinition()) { 11062 case VarDecl::Definition: 11063 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11064 break; 11065 11066 // We have an out-of-line definition of a static data member 11067 // that has an in-class initializer, so we type-check this like 11068 // a declaration. 11069 // 11070 LLVM_FALLTHROUGH; 11071 11072 case VarDecl::DeclarationOnly: 11073 // It's only a declaration. 11074 11075 // Block scope. C99 6.7p7: If an identifier for an object is 11076 // declared with no linkage (C99 6.2.2p6), the type for the 11077 // object shall be complete. 11078 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11079 !Var->hasLinkage() && !Var->isInvalidDecl() && 11080 RequireCompleteType(Var->getLocation(), Type, 11081 diag::err_typecheck_decl_incomplete_type)) 11082 Var->setInvalidDecl(); 11083 11084 // Make sure that the type is not abstract. 11085 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11086 RequireNonAbstractType(Var->getLocation(), Type, 11087 diag::err_abstract_type_in_decl, 11088 AbstractVariableType)) 11089 Var->setInvalidDecl(); 11090 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11091 Var->getStorageClass() == SC_PrivateExtern) { 11092 Diag(Var->getLocation(), diag::warn_private_extern); 11093 Diag(Var->getLocation(), diag::note_private_extern); 11094 } 11095 11096 return; 11097 11098 case VarDecl::TentativeDefinition: 11099 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11100 // object that has file scope without an initializer, and without a 11101 // storage-class specifier or with the storage-class specifier "static", 11102 // constitutes a tentative definition. Note: A tentative definition with 11103 // external linkage is valid (C99 6.2.2p5). 11104 if (!Var->isInvalidDecl()) { 11105 if (const IncompleteArrayType *ArrayT 11106 = Context.getAsIncompleteArrayType(Type)) { 11107 if (RequireCompleteType(Var->getLocation(), 11108 ArrayT->getElementType(), 11109 diag::err_illegal_decl_array_incomplete_type)) 11110 Var->setInvalidDecl(); 11111 } else if (Var->getStorageClass() == SC_Static) { 11112 // C99 6.9.2p3: If the declaration of an identifier for an object is 11113 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11114 // declared type shall not be an incomplete type. 11115 // NOTE: code such as the following 11116 // static struct s; 11117 // struct s { int a; }; 11118 // is accepted by gcc. Hence here we issue a warning instead of 11119 // an error and we do not invalidate the static declaration. 11120 // NOTE: to avoid multiple warnings, only check the first declaration. 11121 if (Var->isFirstDecl()) 11122 RequireCompleteType(Var->getLocation(), Type, 11123 diag::ext_typecheck_decl_incomplete_type); 11124 } 11125 } 11126 11127 // Record the tentative definition; we're done. 11128 if (!Var->isInvalidDecl()) 11129 TentativeDefinitions.push_back(Var); 11130 return; 11131 } 11132 11133 // Provide a specific diagnostic for uninitialized variable 11134 // definitions with incomplete array type. 11135 if (Type->isIncompleteArrayType()) { 11136 Diag(Var->getLocation(), 11137 diag::err_typecheck_incomplete_array_needs_initializer); 11138 Var->setInvalidDecl(); 11139 return; 11140 } 11141 11142 // Provide a specific diagnostic for uninitialized variable 11143 // definitions with reference type. 11144 if (Type->isReferenceType()) { 11145 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11146 << Var->getDeclName() 11147 << SourceRange(Var->getLocation(), Var->getLocation()); 11148 Var->setInvalidDecl(); 11149 return; 11150 } 11151 11152 // Do not attempt to type-check the default initializer for a 11153 // variable with dependent type. 11154 if (Type->isDependentType()) 11155 return; 11156 11157 if (Var->isInvalidDecl()) 11158 return; 11159 11160 if (!Var->hasAttr<AliasAttr>()) { 11161 if (RequireCompleteType(Var->getLocation(), 11162 Context.getBaseElementType(Type), 11163 diag::err_typecheck_decl_incomplete_type)) { 11164 Var->setInvalidDecl(); 11165 return; 11166 } 11167 } else { 11168 return; 11169 } 11170 11171 // The variable can not have an abstract class type. 11172 if (RequireNonAbstractType(Var->getLocation(), Type, 11173 diag::err_abstract_type_in_decl, 11174 AbstractVariableType)) { 11175 Var->setInvalidDecl(); 11176 return; 11177 } 11178 11179 // Check for jumps past the implicit initializer. C++0x 11180 // clarifies that this applies to a "variable with automatic 11181 // storage duration", not a "local variable". 11182 // C++11 [stmt.dcl]p3 11183 // A program that jumps from a point where a variable with automatic 11184 // storage duration is not in scope to a point where it is in scope is 11185 // ill-formed unless the variable has scalar type, class type with a 11186 // trivial default constructor and a trivial destructor, a cv-qualified 11187 // version of one of these types, or an array of one of the preceding 11188 // types and is declared without an initializer. 11189 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11190 if (const RecordType *Record 11191 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11192 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11193 // Mark the function (if we're in one) for further checking even if the 11194 // looser rules of C++11 do not require such checks, so that we can 11195 // diagnose incompatibilities with C++98. 11196 if (!CXXRecord->isPOD()) 11197 setFunctionHasBranchProtectedScope(); 11198 } 11199 } 11200 11201 // C++03 [dcl.init]p9: 11202 // If no initializer is specified for an object, and the 11203 // object is of (possibly cv-qualified) non-POD class type (or 11204 // array thereof), the object shall be default-initialized; if 11205 // the object is of const-qualified type, the underlying class 11206 // type shall have a user-declared default 11207 // constructor. Otherwise, if no initializer is specified for 11208 // a non- static object, the object and its subobjects, if 11209 // any, have an indeterminate initial value); if the object 11210 // or any of its subobjects are of const-qualified type, the 11211 // program is ill-formed. 11212 // C++0x [dcl.init]p11: 11213 // If no initializer is specified for an object, the object is 11214 // default-initialized; [...]. 11215 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11216 InitializationKind Kind 11217 = InitializationKind::CreateDefault(Var->getLocation()); 11218 11219 InitializationSequence InitSeq(*this, Entity, Kind, None); 11220 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11221 if (Init.isInvalid()) 11222 Var->setInvalidDecl(); 11223 else if (Init.get()) { 11224 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11225 // This is important for template substitution. 11226 Var->setInitStyle(VarDecl::CallInit); 11227 } 11228 11229 CheckCompleteVariableDeclaration(Var); 11230 } 11231 } 11232 11233 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11234 // If there is no declaration, there was an error parsing it. Ignore it. 11235 if (!D) 11236 return; 11237 11238 VarDecl *VD = dyn_cast<VarDecl>(D); 11239 if (!VD) { 11240 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11241 D->setInvalidDecl(); 11242 return; 11243 } 11244 11245 VD->setCXXForRangeDecl(true); 11246 11247 // for-range-declaration cannot be given a storage class specifier. 11248 int Error = -1; 11249 switch (VD->getStorageClass()) { 11250 case SC_None: 11251 break; 11252 case SC_Extern: 11253 Error = 0; 11254 break; 11255 case SC_Static: 11256 Error = 1; 11257 break; 11258 case SC_PrivateExtern: 11259 Error = 2; 11260 break; 11261 case SC_Auto: 11262 Error = 3; 11263 break; 11264 case SC_Register: 11265 Error = 4; 11266 break; 11267 } 11268 if (Error != -1) { 11269 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11270 << VD->getDeclName() << Error; 11271 D->setInvalidDecl(); 11272 } 11273 } 11274 11275 StmtResult 11276 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11277 IdentifierInfo *Ident, 11278 ParsedAttributes &Attrs, 11279 SourceLocation AttrEnd) { 11280 // C++1y [stmt.iter]p1: 11281 // A range-based for statement of the form 11282 // for ( for-range-identifier : for-range-initializer ) statement 11283 // is equivalent to 11284 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11285 DeclSpec DS(Attrs.getPool().getFactory()); 11286 11287 const char *PrevSpec; 11288 unsigned DiagID; 11289 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11290 getPrintingPolicy()); 11291 11292 Declarator D(DS, DeclaratorContext::ForContext); 11293 D.SetIdentifier(Ident, IdentLoc); 11294 D.takeAttributes(Attrs, AttrEnd); 11295 11296 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11297 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11298 EmptyAttrs, IdentLoc); 11299 Decl *Var = ActOnDeclarator(S, D); 11300 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11301 FinalizeDeclaration(Var); 11302 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11303 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11304 } 11305 11306 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11307 if (var->isInvalidDecl()) return; 11308 11309 if (getLangOpts().OpenCL) { 11310 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11311 // initialiser 11312 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11313 !var->hasInit()) { 11314 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11315 << 1 /*Init*/; 11316 var->setInvalidDecl(); 11317 return; 11318 } 11319 } 11320 11321 // In Objective-C, don't allow jumps past the implicit initialization of a 11322 // local retaining variable. 11323 if (getLangOpts().ObjC1 && 11324 var->hasLocalStorage()) { 11325 switch (var->getType().getObjCLifetime()) { 11326 case Qualifiers::OCL_None: 11327 case Qualifiers::OCL_ExplicitNone: 11328 case Qualifiers::OCL_Autoreleasing: 11329 break; 11330 11331 case Qualifiers::OCL_Weak: 11332 case Qualifiers::OCL_Strong: 11333 setFunctionHasBranchProtectedScope(); 11334 break; 11335 } 11336 } 11337 11338 if (var->hasLocalStorage() && 11339 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11340 setFunctionHasBranchProtectedScope(); 11341 11342 // Warn about externally-visible variables being defined without a 11343 // prior declaration. We only want to do this for global 11344 // declarations, but we also specifically need to avoid doing it for 11345 // class members because the linkage of an anonymous class can 11346 // change if it's later given a typedef name. 11347 if (var->isThisDeclarationADefinition() && 11348 var->getDeclContext()->getRedeclContext()->isFileContext() && 11349 var->isExternallyVisible() && var->hasLinkage() && 11350 !var->isInline() && !var->getDescribedVarTemplate() && 11351 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11352 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11353 var->getLocation())) { 11354 // Find a previous declaration that's not a definition. 11355 VarDecl *prev = var->getPreviousDecl(); 11356 while (prev && prev->isThisDeclarationADefinition()) 11357 prev = prev->getPreviousDecl(); 11358 11359 if (!prev) 11360 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11361 } 11362 11363 // Cache the result of checking for constant initialization. 11364 Optional<bool> CacheHasConstInit; 11365 const Expr *CacheCulprit; 11366 auto checkConstInit = [&]() mutable { 11367 if (!CacheHasConstInit) 11368 CacheHasConstInit = var->getInit()->isConstantInitializer( 11369 Context, var->getType()->isReferenceType(), &CacheCulprit); 11370 return *CacheHasConstInit; 11371 }; 11372 11373 if (var->getTLSKind() == VarDecl::TLS_Static) { 11374 if (var->getType().isDestructedType()) { 11375 // GNU C++98 edits for __thread, [basic.start.term]p3: 11376 // The type of an object with thread storage duration shall not 11377 // have a non-trivial destructor. 11378 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11379 if (getLangOpts().CPlusPlus11) 11380 Diag(var->getLocation(), diag::note_use_thread_local); 11381 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11382 if (!checkConstInit()) { 11383 // GNU C++98 edits for __thread, [basic.start.init]p4: 11384 // An object of thread storage duration shall not require dynamic 11385 // initialization. 11386 // FIXME: Need strict checking here. 11387 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11388 << CacheCulprit->getSourceRange(); 11389 if (getLangOpts().CPlusPlus11) 11390 Diag(var->getLocation(), diag::note_use_thread_local); 11391 } 11392 } 11393 } 11394 11395 // Apply section attributes and pragmas to global variables. 11396 bool GlobalStorage = var->hasGlobalStorage(); 11397 if (GlobalStorage && var->isThisDeclarationADefinition() && 11398 !inTemplateInstantiation()) { 11399 PragmaStack<StringLiteral *> *Stack = nullptr; 11400 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11401 if (var->getType().isConstQualified()) 11402 Stack = &ConstSegStack; 11403 else if (!var->getInit()) { 11404 Stack = &BSSSegStack; 11405 SectionFlags |= ASTContext::PSF_Write; 11406 } else { 11407 Stack = &DataSegStack; 11408 SectionFlags |= ASTContext::PSF_Write; 11409 } 11410 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11411 var->addAttr(SectionAttr::CreateImplicit( 11412 Context, SectionAttr::Declspec_allocate, 11413 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11414 } 11415 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11416 if (UnifySection(SA->getName(), SectionFlags, var)) 11417 var->dropAttr<SectionAttr>(); 11418 11419 // Apply the init_seg attribute if this has an initializer. If the 11420 // initializer turns out to not be dynamic, we'll end up ignoring this 11421 // attribute. 11422 if (CurInitSeg && var->getInit()) 11423 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11424 CurInitSegLoc)); 11425 } 11426 11427 // All the following checks are C++ only. 11428 if (!getLangOpts().CPlusPlus) { 11429 // If this variable must be emitted, add it as an initializer for the 11430 // current module. 11431 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11432 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11433 return; 11434 } 11435 11436 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11437 CheckCompleteDecompositionDeclaration(DD); 11438 11439 QualType type = var->getType(); 11440 if (type->isDependentType()) return; 11441 11442 // __block variables might require us to capture a copy-initializer. 11443 if (var->hasAttr<BlocksAttr>()) { 11444 // It's currently invalid to ever have a __block variable with an 11445 // array type; should we diagnose that here? 11446 11447 // Regardless, we don't want to ignore array nesting when 11448 // constructing this copy. 11449 if (type->isStructureOrClassType()) { 11450 EnterExpressionEvaluationContext scope( 11451 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11452 SourceLocation poi = var->getLocation(); 11453 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11454 ExprResult result 11455 = PerformMoveOrCopyInitialization( 11456 InitializedEntity::InitializeBlock(poi, type, false), 11457 var, var->getType(), varRef, /*AllowNRVO=*/true); 11458 if (!result.isInvalid()) { 11459 result = MaybeCreateExprWithCleanups(result); 11460 Expr *init = result.getAs<Expr>(); 11461 Context.setBlockVarCopyInits(var, init); 11462 } 11463 } 11464 } 11465 11466 Expr *Init = var->getInit(); 11467 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11468 QualType baseType = Context.getBaseElementType(type); 11469 11470 if (Init && !Init->isValueDependent()) { 11471 if (var->isConstexpr()) { 11472 SmallVector<PartialDiagnosticAt, 8> Notes; 11473 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11474 SourceLocation DiagLoc = var->getLocation(); 11475 // If the note doesn't add any useful information other than a source 11476 // location, fold it into the primary diagnostic. 11477 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11478 diag::note_invalid_subexpr_in_const_expr) { 11479 DiagLoc = Notes[0].first; 11480 Notes.clear(); 11481 } 11482 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11483 << var << Init->getSourceRange(); 11484 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11485 Diag(Notes[I].first, Notes[I].second); 11486 } 11487 } else if (var->isUsableInConstantExpressions(Context)) { 11488 // Check whether the initializer of a const variable of integral or 11489 // enumeration type is an ICE now, since we can't tell whether it was 11490 // initialized by a constant expression if we check later. 11491 var->checkInitIsICE(); 11492 } 11493 11494 // Don't emit further diagnostics about constexpr globals since they 11495 // were just diagnosed. 11496 if (!var->isConstexpr() && GlobalStorage && 11497 var->hasAttr<RequireConstantInitAttr>()) { 11498 // FIXME: Need strict checking in C++03 here. 11499 bool DiagErr = getLangOpts().CPlusPlus11 11500 ? !var->checkInitIsICE() : !checkConstInit(); 11501 if (DiagErr) { 11502 auto attr = var->getAttr<RequireConstantInitAttr>(); 11503 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11504 << Init->getSourceRange(); 11505 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11506 << attr->getRange(); 11507 if (getLangOpts().CPlusPlus11) { 11508 APValue Value; 11509 SmallVector<PartialDiagnosticAt, 8> Notes; 11510 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11511 for (auto &it : Notes) 11512 Diag(it.first, it.second); 11513 } else { 11514 Diag(CacheCulprit->getExprLoc(), 11515 diag::note_invalid_subexpr_in_const_expr) 11516 << CacheCulprit->getSourceRange(); 11517 } 11518 } 11519 } 11520 else if (!var->isConstexpr() && IsGlobal && 11521 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11522 var->getLocation())) { 11523 // Warn about globals which don't have a constant initializer. Don't 11524 // warn about globals with a non-trivial destructor because we already 11525 // warned about them. 11526 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11527 if (!(RD && !RD->hasTrivialDestructor())) { 11528 if (!checkConstInit()) 11529 Diag(var->getLocation(), diag::warn_global_constructor) 11530 << Init->getSourceRange(); 11531 } 11532 } 11533 } 11534 11535 // Require the destructor. 11536 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11537 FinalizeVarWithDestructor(var, recordType); 11538 11539 // If this variable must be emitted, add it as an initializer for the current 11540 // module. 11541 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11542 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11543 } 11544 11545 /// \brief Determines if a variable's alignment is dependent. 11546 static bool hasDependentAlignment(VarDecl *VD) { 11547 if (VD->getType()->isDependentType()) 11548 return true; 11549 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11550 if (I->isAlignmentDependent()) 11551 return true; 11552 return false; 11553 } 11554 11555 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11556 /// any semantic actions necessary after any initializer has been attached. 11557 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11558 // Note that we are no longer parsing the initializer for this declaration. 11559 ParsingInitForAutoVars.erase(ThisDecl); 11560 11561 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11562 if (!VD) 11563 return; 11564 11565 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11566 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11567 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11568 if (PragmaClangBSSSection.Valid) 11569 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11570 PragmaClangBSSSection.SectionName, 11571 PragmaClangBSSSection.PragmaLocation)); 11572 if (PragmaClangDataSection.Valid) 11573 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11574 PragmaClangDataSection.SectionName, 11575 PragmaClangDataSection.PragmaLocation)); 11576 if (PragmaClangRodataSection.Valid) 11577 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11578 PragmaClangRodataSection.SectionName, 11579 PragmaClangRodataSection.PragmaLocation)); 11580 } 11581 11582 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11583 for (auto *BD : DD->bindings()) { 11584 FinalizeDeclaration(BD); 11585 } 11586 } 11587 11588 checkAttributesAfterMerging(*this, *VD); 11589 11590 // Perform TLS alignment check here after attributes attached to the variable 11591 // which may affect the alignment have been processed. Only perform the check 11592 // if the target has a maximum TLS alignment (zero means no constraints). 11593 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11594 // Protect the check so that it's not performed on dependent types and 11595 // dependent alignments (we can't determine the alignment in that case). 11596 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11597 !VD->isInvalidDecl()) { 11598 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11599 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11600 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11601 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11602 << (unsigned)MaxAlignChars.getQuantity(); 11603 } 11604 } 11605 } 11606 11607 if (VD->isStaticLocal()) { 11608 if (FunctionDecl *FD = 11609 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11610 // Static locals inherit dll attributes from their function. 11611 if (Attr *A = getDLLAttr(FD)) { 11612 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11613 NewAttr->setInherited(true); 11614 VD->addAttr(NewAttr); 11615 } 11616 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11617 // function, only __shared__ variables may be declared with 11618 // static storage class. 11619 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11620 CUDADiagIfDeviceCode(VD->getLocation(), 11621 diag::err_device_static_local_var) 11622 << CurrentCUDATarget()) 11623 VD->setInvalidDecl(); 11624 } 11625 } 11626 11627 // Perform check for initializers of device-side global variables. 11628 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11629 // 7.5). We must also apply the same checks to all __shared__ 11630 // variables whether they are local or not. CUDA also allows 11631 // constant initializers for __constant__ and __device__ variables. 11632 if (getLangOpts().CUDA) { 11633 const Expr *Init = VD->getInit(); 11634 if (Init && VD->hasGlobalStorage()) { 11635 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11636 VD->hasAttr<CUDASharedAttr>()) { 11637 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11638 bool AllowedInit = false; 11639 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11640 AllowedInit = 11641 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11642 // We'll allow constant initializers even if it's a non-empty 11643 // constructor according to CUDA rules. This deviates from NVCC, 11644 // but allows us to handle things like constexpr constructors. 11645 if (!AllowedInit && 11646 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11647 AllowedInit = VD->getInit()->isConstantInitializer( 11648 Context, VD->getType()->isReferenceType()); 11649 11650 // Also make sure that destructor, if there is one, is empty. 11651 if (AllowedInit) 11652 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11653 AllowedInit = 11654 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11655 11656 if (!AllowedInit) { 11657 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11658 ? diag::err_shared_var_init 11659 : diag::err_dynamic_var_init) 11660 << Init->getSourceRange(); 11661 VD->setInvalidDecl(); 11662 } 11663 } else { 11664 // This is a host-side global variable. Check that the initializer is 11665 // callable from the host side. 11666 const FunctionDecl *InitFn = nullptr; 11667 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11668 InitFn = CE->getConstructor(); 11669 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11670 InitFn = CE->getDirectCallee(); 11671 } 11672 if (InitFn) { 11673 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11674 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11675 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11676 << InitFnTarget << InitFn; 11677 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11678 VD->setInvalidDecl(); 11679 } 11680 } 11681 } 11682 } 11683 } 11684 11685 // Grab the dllimport or dllexport attribute off of the VarDecl. 11686 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11687 11688 // Imported static data members cannot be defined out-of-line. 11689 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11690 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11691 VD->isThisDeclarationADefinition()) { 11692 // We allow definitions of dllimport class template static data members 11693 // with a warning. 11694 CXXRecordDecl *Context = 11695 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11696 bool IsClassTemplateMember = 11697 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11698 Context->getDescribedClassTemplate(); 11699 11700 Diag(VD->getLocation(), 11701 IsClassTemplateMember 11702 ? diag::warn_attribute_dllimport_static_field_definition 11703 : diag::err_attribute_dllimport_static_field_definition); 11704 Diag(IA->getLocation(), diag::note_attribute); 11705 if (!IsClassTemplateMember) 11706 VD->setInvalidDecl(); 11707 } 11708 } 11709 11710 // dllimport/dllexport variables cannot be thread local, their TLS index 11711 // isn't exported with the variable. 11712 if (DLLAttr && VD->getTLSKind()) { 11713 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11714 if (F && getDLLAttr(F)) { 11715 assert(VD->isStaticLocal()); 11716 // But if this is a static local in a dlimport/dllexport function, the 11717 // function will never be inlined, which means the var would never be 11718 // imported, so having it marked import/export is safe. 11719 } else { 11720 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11721 << DLLAttr; 11722 VD->setInvalidDecl(); 11723 } 11724 } 11725 11726 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11727 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11728 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11729 VD->dropAttr<UsedAttr>(); 11730 } 11731 } 11732 11733 const DeclContext *DC = VD->getDeclContext(); 11734 // If there's a #pragma GCC visibility in scope, and this isn't a class 11735 // member, set the visibility of this variable. 11736 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11737 AddPushedVisibilityAttribute(VD); 11738 11739 // FIXME: Warn on unused var template partial specializations. 11740 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11741 MarkUnusedFileScopedDecl(VD); 11742 11743 // Now we have parsed the initializer and can update the table of magic 11744 // tag values. 11745 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11746 !VD->getType()->isIntegralOrEnumerationType()) 11747 return; 11748 11749 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11750 const Expr *MagicValueExpr = VD->getInit(); 11751 if (!MagicValueExpr) { 11752 continue; 11753 } 11754 llvm::APSInt MagicValueInt; 11755 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11756 Diag(I->getRange().getBegin(), 11757 diag::err_type_tag_for_datatype_not_ice) 11758 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11759 continue; 11760 } 11761 if (MagicValueInt.getActiveBits() > 64) { 11762 Diag(I->getRange().getBegin(), 11763 diag::err_type_tag_for_datatype_too_large) 11764 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11765 continue; 11766 } 11767 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11768 RegisterTypeTagForDatatype(I->getArgumentKind(), 11769 MagicValue, 11770 I->getMatchingCType(), 11771 I->getLayoutCompatible(), 11772 I->getMustBeNull()); 11773 } 11774 } 11775 11776 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11777 auto *VD = dyn_cast<VarDecl>(DD); 11778 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11779 } 11780 11781 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11782 ArrayRef<Decl *> Group) { 11783 SmallVector<Decl*, 8> Decls; 11784 11785 if (DS.isTypeSpecOwned()) 11786 Decls.push_back(DS.getRepAsDecl()); 11787 11788 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11789 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11790 bool DiagnosedMultipleDecomps = false; 11791 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11792 bool DiagnosedNonDeducedAuto = false; 11793 11794 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11795 if (Decl *D = Group[i]) { 11796 // For declarators, there are some additional syntactic-ish checks we need 11797 // to perform. 11798 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11799 if (!FirstDeclaratorInGroup) 11800 FirstDeclaratorInGroup = DD; 11801 if (!FirstDecompDeclaratorInGroup) 11802 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11803 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11804 !hasDeducedAuto(DD)) 11805 FirstNonDeducedAutoInGroup = DD; 11806 11807 if (FirstDeclaratorInGroup != DD) { 11808 // A decomposition declaration cannot be combined with any other 11809 // declaration in the same group. 11810 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11811 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11812 diag::err_decomp_decl_not_alone) 11813 << FirstDeclaratorInGroup->getSourceRange() 11814 << DD->getSourceRange(); 11815 DiagnosedMultipleDecomps = true; 11816 } 11817 11818 // A declarator that uses 'auto' in any way other than to declare a 11819 // variable with a deduced type cannot be combined with any other 11820 // declarator in the same group. 11821 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11822 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11823 diag::err_auto_non_deduced_not_alone) 11824 << FirstNonDeducedAutoInGroup->getType() 11825 ->hasAutoForTrailingReturnType() 11826 << FirstDeclaratorInGroup->getSourceRange() 11827 << DD->getSourceRange(); 11828 DiagnosedNonDeducedAuto = true; 11829 } 11830 } 11831 } 11832 11833 Decls.push_back(D); 11834 } 11835 } 11836 11837 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11838 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11839 handleTagNumbering(Tag, S); 11840 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11841 getLangOpts().CPlusPlus) 11842 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11843 } 11844 } 11845 11846 return BuildDeclaratorGroup(Decls); 11847 } 11848 11849 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11850 /// group, performing any necessary semantic checking. 11851 Sema::DeclGroupPtrTy 11852 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11853 // C++14 [dcl.spec.auto]p7: (DR1347) 11854 // If the type that replaces the placeholder type is not the same in each 11855 // deduction, the program is ill-formed. 11856 if (Group.size() > 1) { 11857 QualType Deduced; 11858 VarDecl *DeducedDecl = nullptr; 11859 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11860 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11861 if (!D || D->isInvalidDecl()) 11862 break; 11863 DeducedType *DT = D->getType()->getContainedDeducedType(); 11864 if (!DT || DT->getDeducedType().isNull()) 11865 continue; 11866 if (Deduced.isNull()) { 11867 Deduced = DT->getDeducedType(); 11868 DeducedDecl = D; 11869 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11870 auto *AT = dyn_cast<AutoType>(DT); 11871 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11872 diag::err_auto_different_deductions) 11873 << (AT ? (unsigned)AT->getKeyword() : 3) 11874 << Deduced << DeducedDecl->getDeclName() 11875 << DT->getDeducedType() << D->getDeclName() 11876 << DeducedDecl->getInit()->getSourceRange() 11877 << D->getInit()->getSourceRange(); 11878 D->setInvalidDecl(); 11879 break; 11880 } 11881 } 11882 } 11883 11884 ActOnDocumentableDecls(Group); 11885 11886 return DeclGroupPtrTy::make( 11887 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11888 } 11889 11890 void Sema::ActOnDocumentableDecl(Decl *D) { 11891 ActOnDocumentableDecls(D); 11892 } 11893 11894 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11895 // Don't parse the comment if Doxygen diagnostics are ignored. 11896 if (Group.empty() || !Group[0]) 11897 return; 11898 11899 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11900 Group[0]->getLocation()) && 11901 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11902 Group[0]->getLocation())) 11903 return; 11904 11905 if (Group.size() >= 2) { 11906 // This is a decl group. Normally it will contain only declarations 11907 // produced from declarator list. But in case we have any definitions or 11908 // additional declaration references: 11909 // 'typedef struct S {} S;' 11910 // 'typedef struct S *S;' 11911 // 'struct S *pS;' 11912 // FinalizeDeclaratorGroup adds these as separate declarations. 11913 Decl *MaybeTagDecl = Group[0]; 11914 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11915 Group = Group.slice(1); 11916 } 11917 } 11918 11919 // See if there are any new comments that are not attached to a decl. 11920 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11921 if (!Comments.empty() && 11922 !Comments.back()->isAttached()) { 11923 // There is at least one comment that not attached to a decl. 11924 // Maybe it should be attached to one of these decls? 11925 // 11926 // Note that this way we pick up not only comments that precede the 11927 // declaration, but also comments that *follow* the declaration -- thanks to 11928 // the lookahead in the lexer: we've consumed the semicolon and looked 11929 // ahead through comments. 11930 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11931 Context.getCommentForDecl(Group[i], &PP); 11932 } 11933 } 11934 11935 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11936 /// to introduce parameters into function prototype scope. 11937 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11938 const DeclSpec &DS = D.getDeclSpec(); 11939 11940 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11941 11942 // C++03 [dcl.stc]p2 also permits 'auto'. 11943 StorageClass SC = SC_None; 11944 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11945 SC = SC_Register; 11946 // In C++11, the 'register' storage class specifier is deprecated. 11947 // In C++17, it is not allowed, but we tolerate it as an extension. 11948 if (getLangOpts().CPlusPlus11) { 11949 Diag(DS.getStorageClassSpecLoc(), 11950 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 11951 : diag::warn_deprecated_register) 11952 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11953 } 11954 } else if (getLangOpts().CPlusPlus && 11955 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11956 SC = SC_Auto; 11957 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11958 Diag(DS.getStorageClassSpecLoc(), 11959 diag::err_invalid_storage_class_in_func_decl); 11960 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11961 } 11962 11963 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11964 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11965 << DeclSpec::getSpecifierName(TSCS); 11966 if (DS.isInlineSpecified()) 11967 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11968 << getLangOpts().CPlusPlus17; 11969 if (DS.isConstexprSpecified()) 11970 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11971 << 0; 11972 11973 DiagnoseFunctionSpecifiers(DS); 11974 11975 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11976 QualType parmDeclType = TInfo->getType(); 11977 11978 if (getLangOpts().CPlusPlus) { 11979 // Check that there are no default arguments inside the type of this 11980 // parameter. 11981 CheckExtraCXXDefaultArguments(D); 11982 11983 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11984 if (D.getCXXScopeSpec().isSet()) { 11985 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11986 << D.getCXXScopeSpec().getRange(); 11987 D.getCXXScopeSpec().clear(); 11988 } 11989 } 11990 11991 // Ensure we have a valid name 11992 IdentifierInfo *II = nullptr; 11993 if (D.hasName()) { 11994 II = D.getIdentifier(); 11995 if (!II) { 11996 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11997 << GetNameForDeclarator(D).getName(); 11998 D.setInvalidType(true); 11999 } 12000 } 12001 12002 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12003 if (II) { 12004 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12005 ForVisibleRedeclaration); 12006 LookupName(R, S); 12007 if (R.isSingleResult()) { 12008 NamedDecl *PrevDecl = R.getFoundDecl(); 12009 if (PrevDecl->isTemplateParameter()) { 12010 // Maybe we will complain about the shadowed template parameter. 12011 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12012 // Just pretend that we didn't see the previous declaration. 12013 PrevDecl = nullptr; 12014 } else if (S->isDeclScope(PrevDecl)) { 12015 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12016 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12017 12018 // Recover by removing the name 12019 II = nullptr; 12020 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12021 D.setInvalidType(true); 12022 } 12023 } 12024 } 12025 12026 // Temporarily put parameter variables in the translation unit, not 12027 // the enclosing context. This prevents them from accidentally 12028 // looking like class members in C++. 12029 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12030 D.getLocStart(), 12031 D.getIdentifierLoc(), II, 12032 parmDeclType, TInfo, 12033 SC); 12034 12035 if (D.isInvalidType()) 12036 New->setInvalidDecl(); 12037 12038 assert(S->isFunctionPrototypeScope()); 12039 assert(S->getFunctionPrototypeDepth() >= 1); 12040 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12041 S->getNextFunctionPrototypeIndex()); 12042 12043 // Add the parameter declaration into this scope. 12044 S->AddDecl(New); 12045 if (II) 12046 IdResolver.AddDecl(New); 12047 12048 ProcessDeclAttributes(S, New, D); 12049 12050 if (D.getDeclSpec().isModulePrivateSpecified()) 12051 Diag(New->getLocation(), diag::err_module_private_local) 12052 << 1 << New->getDeclName() 12053 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12054 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12055 12056 if (New->hasAttr<BlocksAttr>()) { 12057 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12058 } 12059 return New; 12060 } 12061 12062 /// \brief Synthesizes a variable for a parameter arising from a 12063 /// typedef. 12064 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12065 SourceLocation Loc, 12066 QualType T) { 12067 /* FIXME: setting StartLoc == Loc. 12068 Would it be worth to modify callers so as to provide proper source 12069 location for the unnamed parameters, embedding the parameter's type? */ 12070 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12071 T, Context.getTrivialTypeSourceInfo(T, Loc), 12072 SC_None, nullptr); 12073 Param->setImplicit(); 12074 return Param; 12075 } 12076 12077 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12078 // Don't diagnose unused-parameter errors in template instantiations; we 12079 // will already have done so in the template itself. 12080 if (inTemplateInstantiation()) 12081 return; 12082 12083 for (const ParmVarDecl *Parameter : Parameters) { 12084 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12085 !Parameter->hasAttr<UnusedAttr>()) { 12086 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12087 << Parameter->getDeclName(); 12088 } 12089 } 12090 } 12091 12092 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12093 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12094 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12095 return; 12096 12097 // Warn if the return value is pass-by-value and larger than the specified 12098 // threshold. 12099 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12100 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12101 if (Size > LangOpts.NumLargeByValueCopy) 12102 Diag(D->getLocation(), diag::warn_return_value_size) 12103 << D->getDeclName() << Size; 12104 } 12105 12106 // Warn if any parameter is pass-by-value and larger than the specified 12107 // threshold. 12108 for (const ParmVarDecl *Parameter : Parameters) { 12109 QualType T = Parameter->getType(); 12110 if (T->isDependentType() || !T.isPODType(Context)) 12111 continue; 12112 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12113 if (Size > LangOpts.NumLargeByValueCopy) 12114 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12115 << Parameter->getDeclName() << Size; 12116 } 12117 } 12118 12119 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12120 SourceLocation NameLoc, IdentifierInfo *Name, 12121 QualType T, TypeSourceInfo *TSInfo, 12122 StorageClass SC) { 12123 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12124 if (getLangOpts().ObjCAutoRefCount && 12125 T.getObjCLifetime() == Qualifiers::OCL_None && 12126 T->isObjCLifetimeType()) { 12127 12128 Qualifiers::ObjCLifetime lifetime; 12129 12130 // Special cases for arrays: 12131 // - if it's const, use __unsafe_unretained 12132 // - otherwise, it's an error 12133 if (T->isArrayType()) { 12134 if (!T.isConstQualified()) { 12135 DelayedDiagnostics.add( 12136 sema::DelayedDiagnostic::makeForbiddenType( 12137 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12138 } 12139 lifetime = Qualifiers::OCL_ExplicitNone; 12140 } else { 12141 lifetime = T->getObjCARCImplicitLifetime(); 12142 } 12143 T = Context.getLifetimeQualifiedType(T, lifetime); 12144 } 12145 12146 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12147 Context.getAdjustedParameterType(T), 12148 TSInfo, SC, nullptr); 12149 12150 // Parameters can not be abstract class types. 12151 // For record types, this is done by the AbstractClassUsageDiagnoser once 12152 // the class has been completely parsed. 12153 if (!CurContext->isRecord() && 12154 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12155 AbstractParamType)) 12156 New->setInvalidDecl(); 12157 12158 // Parameter declarators cannot be interface types. All ObjC objects are 12159 // passed by reference. 12160 if (T->isObjCObjectType()) { 12161 SourceLocation TypeEndLoc = 12162 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12163 Diag(NameLoc, 12164 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12165 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12166 T = Context.getObjCObjectPointerType(T); 12167 New->setType(T); 12168 } 12169 12170 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12171 // duration shall not be qualified by an address-space qualifier." 12172 // Since all parameters have automatic store duration, they can not have 12173 // an address space. 12174 if (T.getAddressSpace() != LangAS::Default && 12175 // OpenCL allows function arguments declared to be an array of a type 12176 // to be qualified with an address space. 12177 !(getLangOpts().OpenCL && 12178 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12179 Diag(NameLoc, diag::err_arg_with_address_space); 12180 New->setInvalidDecl(); 12181 } 12182 12183 return New; 12184 } 12185 12186 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12187 SourceLocation LocAfterDecls) { 12188 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12189 12190 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12191 // for a K&R function. 12192 if (!FTI.hasPrototype) { 12193 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12194 --i; 12195 if (FTI.Params[i].Param == nullptr) { 12196 SmallString<256> Code; 12197 llvm::raw_svector_ostream(Code) 12198 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12199 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12200 << FTI.Params[i].Ident 12201 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12202 12203 // Implicitly declare the argument as type 'int' for lack of a better 12204 // type. 12205 AttributeFactory attrs; 12206 DeclSpec DS(attrs); 12207 const char* PrevSpec; // unused 12208 unsigned DiagID; // unused 12209 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12210 DiagID, Context.getPrintingPolicy()); 12211 // Use the identifier location for the type source range. 12212 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12213 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12214 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12215 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12216 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12217 } 12218 } 12219 } 12220 } 12221 12222 Decl * 12223 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12224 MultiTemplateParamsArg TemplateParameterLists, 12225 SkipBodyInfo *SkipBody) { 12226 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12227 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12228 Scope *ParentScope = FnBodyScope->getParent(); 12229 12230 D.setFunctionDefinitionKind(FDK_Definition); 12231 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12232 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12233 } 12234 12235 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12236 Consumer.HandleInlineFunctionDefinition(D); 12237 } 12238 12239 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12240 const FunctionDecl*& PossibleZeroParamPrototype) { 12241 // Don't warn about invalid declarations. 12242 if (FD->isInvalidDecl()) 12243 return false; 12244 12245 // Or declarations that aren't global. 12246 if (!FD->isGlobal()) 12247 return false; 12248 12249 // Don't warn about C++ member functions. 12250 if (isa<CXXMethodDecl>(FD)) 12251 return false; 12252 12253 // Don't warn about 'main'. 12254 if (FD->isMain()) 12255 return false; 12256 12257 // Don't warn about inline functions. 12258 if (FD->isInlined()) 12259 return false; 12260 12261 // Don't warn about function templates. 12262 if (FD->getDescribedFunctionTemplate()) 12263 return false; 12264 12265 // Don't warn about function template specializations. 12266 if (FD->isFunctionTemplateSpecialization()) 12267 return false; 12268 12269 // Don't warn for OpenCL kernels. 12270 if (FD->hasAttr<OpenCLKernelAttr>()) 12271 return false; 12272 12273 // Don't warn on explicitly deleted functions. 12274 if (FD->isDeleted()) 12275 return false; 12276 12277 bool MissingPrototype = true; 12278 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12279 Prev; Prev = Prev->getPreviousDecl()) { 12280 // Ignore any declarations that occur in function or method 12281 // scope, because they aren't visible from the header. 12282 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12283 continue; 12284 12285 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12286 if (FD->getNumParams() == 0) 12287 PossibleZeroParamPrototype = Prev; 12288 break; 12289 } 12290 12291 return MissingPrototype; 12292 } 12293 12294 void 12295 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12296 const FunctionDecl *EffectiveDefinition, 12297 SkipBodyInfo *SkipBody) { 12298 const FunctionDecl *Definition = EffectiveDefinition; 12299 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12300 // If this is a friend function defined in a class template, it does not 12301 // have a body until it is used, nevertheless it is a definition, see 12302 // [temp.inst]p2: 12303 // 12304 // ... for the purpose of determining whether an instantiated redeclaration 12305 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12306 // corresponds to a definition in the template is considered to be a 12307 // definition. 12308 // 12309 // The following code must produce redefinition error: 12310 // 12311 // template<typename T> struct C20 { friend void func_20() {} }; 12312 // C20<int> c20i; 12313 // void func_20() {} 12314 // 12315 for (auto I : FD->redecls()) { 12316 if (I != FD && !I->isInvalidDecl() && 12317 I->getFriendObjectKind() != Decl::FOK_None) { 12318 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12319 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12320 // A merged copy of the same function, instantiated as a member of 12321 // the same class, is OK. 12322 if (declaresSameEntity(OrigFD, Original) && 12323 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12324 cast<Decl>(FD->getLexicalDeclContext()))) 12325 continue; 12326 } 12327 12328 if (Original->isThisDeclarationADefinition()) { 12329 Definition = I; 12330 break; 12331 } 12332 } 12333 } 12334 } 12335 } 12336 if (!Definition) 12337 return; 12338 12339 if (canRedefineFunction(Definition, getLangOpts())) 12340 return; 12341 12342 // Don't emit an error when this is redefinition of a typo-corrected 12343 // definition. 12344 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12345 return; 12346 12347 // If we don't have a visible definition of the function, and it's inline or 12348 // a template, skip the new definition. 12349 if (SkipBody && !hasVisibleDefinition(Definition) && 12350 (Definition->getFormalLinkage() == InternalLinkage || 12351 Definition->isInlined() || 12352 Definition->getDescribedFunctionTemplate() || 12353 Definition->getNumTemplateParameterLists())) { 12354 SkipBody->ShouldSkip = true; 12355 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12356 makeMergedDefinitionVisible(TD); 12357 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12358 return; 12359 } 12360 12361 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12362 Definition->getStorageClass() == SC_Extern) 12363 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12364 << FD->getDeclName() << getLangOpts().CPlusPlus; 12365 else 12366 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12367 12368 Diag(Definition->getLocation(), diag::note_previous_definition); 12369 FD->setInvalidDecl(); 12370 } 12371 12372 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12373 Sema &S) { 12374 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12375 12376 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12377 LSI->CallOperator = CallOperator; 12378 LSI->Lambda = LambdaClass; 12379 LSI->ReturnType = CallOperator->getReturnType(); 12380 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12381 12382 if (LCD == LCD_None) 12383 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12384 else if (LCD == LCD_ByCopy) 12385 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12386 else if (LCD == LCD_ByRef) 12387 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12388 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12389 12390 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12391 LSI->Mutable = !CallOperator->isConst(); 12392 12393 // Add the captures to the LSI so they can be noted as already 12394 // captured within tryCaptureVar. 12395 auto I = LambdaClass->field_begin(); 12396 for (const auto &C : LambdaClass->captures()) { 12397 if (C.capturesVariable()) { 12398 VarDecl *VD = C.getCapturedVar(); 12399 if (VD->isInitCapture()) 12400 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12401 QualType CaptureType = VD->getType(); 12402 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12403 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12404 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12405 /*EllipsisLoc*/C.isPackExpansion() 12406 ? C.getEllipsisLoc() : SourceLocation(), 12407 CaptureType, /*Expr*/ nullptr); 12408 12409 } else if (C.capturesThis()) { 12410 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12411 /*Expr*/ nullptr, 12412 C.getCaptureKind() == LCK_StarThis); 12413 } else { 12414 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12415 } 12416 ++I; 12417 } 12418 } 12419 12420 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12421 SkipBodyInfo *SkipBody) { 12422 if (!D) { 12423 // Parsing the function declaration failed in some way. Push on a fake scope 12424 // anyway so we can try to parse the function body. 12425 PushFunctionScope(); 12426 return D; 12427 } 12428 12429 FunctionDecl *FD = nullptr; 12430 12431 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12432 FD = FunTmpl->getTemplatedDecl(); 12433 else 12434 FD = cast<FunctionDecl>(D); 12435 12436 // Check for defining attributes before the check for redefinition. 12437 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12438 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12439 FD->dropAttr<AliasAttr>(); 12440 FD->setInvalidDecl(); 12441 } 12442 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12443 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12444 FD->dropAttr<IFuncAttr>(); 12445 FD->setInvalidDecl(); 12446 } 12447 12448 // See if this is a redefinition. If 'will have body' is already set, then 12449 // these checks were already performed when it was set. 12450 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12451 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12452 12453 // If we're skipping the body, we're done. Don't enter the scope. 12454 if (SkipBody && SkipBody->ShouldSkip) 12455 return D; 12456 } 12457 12458 // Mark this function as "will have a body eventually". This lets users to 12459 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12460 // this function. 12461 FD->setWillHaveBody(); 12462 12463 // If we are instantiating a generic lambda call operator, push 12464 // a LambdaScopeInfo onto the function stack. But use the information 12465 // that's already been calculated (ActOnLambdaExpr) to prime the current 12466 // LambdaScopeInfo. 12467 // When the template operator is being specialized, the LambdaScopeInfo, 12468 // has to be properly restored so that tryCaptureVariable doesn't try 12469 // and capture any new variables. In addition when calculating potential 12470 // captures during transformation of nested lambdas, it is necessary to 12471 // have the LSI properly restored. 12472 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12473 assert(inTemplateInstantiation() && 12474 "There should be an active template instantiation on the stack " 12475 "when instantiating a generic lambda!"); 12476 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12477 } else { 12478 // Enter a new function scope 12479 PushFunctionScope(); 12480 } 12481 12482 // Builtin functions cannot be defined. 12483 if (unsigned BuiltinID = FD->getBuiltinID()) { 12484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12485 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12486 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12487 FD->setInvalidDecl(); 12488 } 12489 } 12490 12491 // The return type of a function definition must be complete 12492 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12493 QualType ResultType = FD->getReturnType(); 12494 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12495 !FD->isInvalidDecl() && 12496 RequireCompleteType(FD->getLocation(), ResultType, 12497 diag::err_func_def_incomplete_result)) 12498 FD->setInvalidDecl(); 12499 12500 if (FnBodyScope) 12501 PushDeclContext(FnBodyScope, FD); 12502 12503 // Check the validity of our function parameters 12504 CheckParmsForFunctionDef(FD->parameters(), 12505 /*CheckParameterNames=*/true); 12506 12507 // Add non-parameter declarations already in the function to the current 12508 // scope. 12509 if (FnBodyScope) { 12510 for (Decl *NPD : FD->decls()) { 12511 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12512 if (!NonParmDecl) 12513 continue; 12514 assert(!isa<ParmVarDecl>(NonParmDecl) && 12515 "parameters should not be in newly created FD yet"); 12516 12517 // If the decl has a name, make it accessible in the current scope. 12518 if (NonParmDecl->getDeclName()) 12519 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12520 12521 // Similarly, dive into enums and fish their constants out, making them 12522 // accessible in this scope. 12523 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12524 for (auto *EI : ED->enumerators()) 12525 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12526 } 12527 } 12528 } 12529 12530 // Introduce our parameters into the function scope 12531 for (auto Param : FD->parameters()) { 12532 Param->setOwningFunction(FD); 12533 12534 // If this has an identifier, add it to the scope stack. 12535 if (Param->getIdentifier() && FnBodyScope) { 12536 CheckShadow(FnBodyScope, Param); 12537 12538 PushOnScopeChains(Param, FnBodyScope); 12539 } 12540 } 12541 12542 // Ensure that the function's exception specification is instantiated. 12543 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12544 ResolveExceptionSpec(D->getLocation(), FPT); 12545 12546 // dllimport cannot be applied to non-inline function definitions. 12547 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12548 !FD->isTemplateInstantiation()) { 12549 assert(!FD->hasAttr<DLLExportAttr>()); 12550 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12551 FD->setInvalidDecl(); 12552 return D; 12553 } 12554 // We want to attach documentation to original Decl (which might be 12555 // a function template). 12556 ActOnDocumentableDecl(D); 12557 if (getCurLexicalContext()->isObjCContainer() && 12558 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12559 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12560 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12561 12562 return D; 12563 } 12564 12565 /// \brief Given the set of return statements within a function body, 12566 /// compute the variables that are subject to the named return value 12567 /// optimization. 12568 /// 12569 /// Each of the variables that is subject to the named return value 12570 /// optimization will be marked as NRVO variables in the AST, and any 12571 /// return statement that has a marked NRVO variable as its NRVO candidate can 12572 /// use the named return value optimization. 12573 /// 12574 /// This function applies a very simplistic algorithm for NRVO: if every return 12575 /// statement in the scope of a variable has the same NRVO candidate, that 12576 /// candidate is an NRVO variable. 12577 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12578 ReturnStmt **Returns = Scope->Returns.data(); 12579 12580 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12581 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12582 if (!NRVOCandidate->isNRVOVariable()) 12583 Returns[I]->setNRVOCandidate(nullptr); 12584 } 12585 } 12586 } 12587 12588 bool Sema::canDelayFunctionBody(const Declarator &D) { 12589 // We can't delay parsing the body of a constexpr function template (yet). 12590 if (D.getDeclSpec().isConstexprSpecified()) 12591 return false; 12592 12593 // We can't delay parsing the body of a function template with a deduced 12594 // return type (yet). 12595 if (D.getDeclSpec().hasAutoTypeSpec()) { 12596 // If the placeholder introduces a non-deduced trailing return type, 12597 // we can still delay parsing it. 12598 if (D.getNumTypeObjects()) { 12599 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12600 if (Outer.Kind == DeclaratorChunk::Function && 12601 Outer.Fun.hasTrailingReturnType()) { 12602 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12603 return Ty.isNull() || !Ty->isUndeducedType(); 12604 } 12605 } 12606 return false; 12607 } 12608 12609 return true; 12610 } 12611 12612 bool Sema::canSkipFunctionBody(Decl *D) { 12613 // We cannot skip the body of a function (or function template) which is 12614 // constexpr, since we may need to evaluate its body in order to parse the 12615 // rest of the file. 12616 // We cannot skip the body of a function with an undeduced return type, 12617 // because any callers of that function need to know the type. 12618 if (const FunctionDecl *FD = D->getAsFunction()) 12619 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12620 return false; 12621 return Consumer.shouldSkipFunctionBody(D); 12622 } 12623 12624 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12625 if (!Decl) 12626 return nullptr; 12627 if (FunctionDecl *FD = Decl->getAsFunction()) 12628 FD->setHasSkippedBody(); 12629 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12630 MD->setHasSkippedBody(); 12631 return Decl; 12632 } 12633 12634 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12635 return ActOnFinishFunctionBody(D, BodyArg, false); 12636 } 12637 12638 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12639 bool IsInstantiation) { 12640 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12641 12642 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12643 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12644 12645 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12646 CheckCompletedCoroutineBody(FD, Body); 12647 12648 if (FD) { 12649 FD->setBody(Body); 12650 FD->setWillHaveBody(false); 12651 12652 if (getLangOpts().CPlusPlus14) { 12653 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12654 FD->getReturnType()->isUndeducedType()) { 12655 // If the function has a deduced result type but contains no 'return' 12656 // statements, the result type as written must be exactly 'auto', and 12657 // the deduced result type is 'void'. 12658 if (!FD->getReturnType()->getAs<AutoType>()) { 12659 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12660 << FD->getReturnType(); 12661 FD->setInvalidDecl(); 12662 } else { 12663 // Substitute 'void' for the 'auto' in the type. 12664 TypeLoc ResultType = getReturnTypeLoc(FD); 12665 Context.adjustDeducedFunctionResultType( 12666 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12667 } 12668 } 12669 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12670 // In C++11, we don't use 'auto' deduction rules for lambda call 12671 // operators because we don't support return type deduction. 12672 auto *LSI = getCurLambda(); 12673 if (LSI->HasImplicitReturnType) { 12674 deduceClosureReturnType(*LSI); 12675 12676 // C++11 [expr.prim.lambda]p4: 12677 // [...] if there are no return statements in the compound-statement 12678 // [the deduced type is] the type void 12679 QualType RetType = 12680 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12681 12682 // Update the return type to the deduced type. 12683 const FunctionProtoType *Proto = 12684 FD->getType()->getAs<FunctionProtoType>(); 12685 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12686 Proto->getExtProtoInfo())); 12687 } 12688 } 12689 12690 // If the function implicitly returns zero (like 'main') or is naked, 12691 // don't complain about missing return statements. 12692 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12693 WP.disableCheckFallThrough(); 12694 12695 // MSVC permits the use of pure specifier (=0) on function definition, 12696 // defined at class scope, warn about this non-standard construct. 12697 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12698 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12699 12700 if (!FD->isInvalidDecl()) { 12701 // Don't diagnose unused parameters of defaulted or deleted functions. 12702 if (!FD->isDeleted() && !FD->isDefaulted()) 12703 DiagnoseUnusedParameters(FD->parameters()); 12704 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12705 FD->getReturnType(), FD); 12706 12707 // If this is a structor, we need a vtable. 12708 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12709 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12710 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12711 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12712 12713 // Try to apply the named return value optimization. We have to check 12714 // if we can do this here because lambdas keep return statements around 12715 // to deduce an implicit return type. 12716 if (FD->getReturnType()->isRecordType() && 12717 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12718 computeNRVO(Body, getCurFunction()); 12719 } 12720 12721 // GNU warning -Wmissing-prototypes: 12722 // Warn if a global function is defined without a previous 12723 // prototype declaration. This warning is issued even if the 12724 // definition itself provides a prototype. The aim is to detect 12725 // global functions that fail to be declared in header files. 12726 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12727 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12728 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12729 12730 if (PossibleZeroParamPrototype) { 12731 // We found a declaration that is not a prototype, 12732 // but that could be a zero-parameter prototype 12733 if (TypeSourceInfo *TI = 12734 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12735 TypeLoc TL = TI->getTypeLoc(); 12736 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12737 Diag(PossibleZeroParamPrototype->getLocation(), 12738 diag::note_declaration_not_a_prototype) 12739 << PossibleZeroParamPrototype 12740 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12741 } 12742 } 12743 12744 // GNU warning -Wstrict-prototypes 12745 // Warn if K&R function is defined without a previous declaration. 12746 // This warning is issued only if the definition itself does not provide 12747 // a prototype. Only K&R definitions do not provide a prototype. 12748 // An empty list in a function declarator that is part of a definition 12749 // of that function specifies that the function has no parameters 12750 // (C99 6.7.5.3p14) 12751 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12752 !LangOpts.CPlusPlus) { 12753 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12754 TypeLoc TL = TI->getTypeLoc(); 12755 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12756 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12757 } 12758 } 12759 12760 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12761 const CXXMethodDecl *KeyFunction; 12762 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12763 MD->isVirtual() && 12764 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12765 MD == KeyFunction->getCanonicalDecl()) { 12766 // Update the key-function state if necessary for this ABI. 12767 if (FD->isInlined() && 12768 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12769 Context.setNonKeyFunction(MD); 12770 12771 // If the newly-chosen key function is already defined, then we 12772 // need to mark the vtable as used retroactively. 12773 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12774 const FunctionDecl *Definition; 12775 if (KeyFunction && KeyFunction->isDefined(Definition)) 12776 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12777 } else { 12778 // We just defined they key function; mark the vtable as used. 12779 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12780 } 12781 } 12782 } 12783 12784 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12785 "Function parsing confused"); 12786 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12787 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12788 MD->setBody(Body); 12789 if (!MD->isInvalidDecl()) { 12790 DiagnoseUnusedParameters(MD->parameters()); 12791 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12792 MD->getReturnType(), MD); 12793 12794 if (Body) 12795 computeNRVO(Body, getCurFunction()); 12796 } 12797 if (getCurFunction()->ObjCShouldCallSuper) { 12798 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12799 << MD->getSelector().getAsString(); 12800 getCurFunction()->ObjCShouldCallSuper = false; 12801 } 12802 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12803 const ObjCMethodDecl *InitMethod = nullptr; 12804 bool isDesignated = 12805 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12806 assert(isDesignated && InitMethod); 12807 (void)isDesignated; 12808 12809 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12810 auto IFace = MD->getClassInterface(); 12811 if (!IFace) 12812 return false; 12813 auto SuperD = IFace->getSuperClass(); 12814 if (!SuperD) 12815 return false; 12816 return SuperD->getIdentifier() == 12817 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12818 }; 12819 // Don't issue this warning for unavailable inits or direct subclasses 12820 // of NSObject. 12821 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12822 Diag(MD->getLocation(), 12823 diag::warn_objc_designated_init_missing_super_call); 12824 Diag(InitMethod->getLocation(), 12825 diag::note_objc_designated_init_marked_here); 12826 } 12827 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12828 } 12829 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12830 // Don't issue this warning for unavaialable inits. 12831 if (!MD->isUnavailable()) 12832 Diag(MD->getLocation(), 12833 diag::warn_objc_secondary_init_missing_init_call); 12834 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12835 } 12836 } else { 12837 // Parsing the function declaration failed in some way. Pop the fake scope 12838 // we pushed on. 12839 PopFunctionScopeInfo(ActivePolicy, dcl); 12840 return nullptr; 12841 } 12842 12843 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12844 DiagnoseUnguardedAvailabilityViolations(dcl); 12845 12846 assert(!getCurFunction()->ObjCShouldCallSuper && 12847 "This should only be set for ObjC methods, which should have been " 12848 "handled in the block above."); 12849 12850 // Verify and clean out per-function state. 12851 if (Body && (!FD || !FD->isDefaulted())) { 12852 // C++ constructors that have function-try-blocks can't have return 12853 // statements in the handlers of that block. (C++ [except.handle]p14) 12854 // Verify this. 12855 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12856 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12857 12858 // Verify that gotos and switch cases don't jump into scopes illegally. 12859 if (getCurFunction()->NeedsScopeChecking() && 12860 !PP.isCodeCompletionEnabled()) 12861 DiagnoseInvalidJumps(Body); 12862 12863 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12864 if (!Destructor->getParent()->isDependentType()) 12865 CheckDestructor(Destructor); 12866 12867 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12868 Destructor->getParent()); 12869 } 12870 12871 // If any errors have occurred, clear out any temporaries that may have 12872 // been leftover. This ensures that these temporaries won't be picked up for 12873 // deletion in some later function. 12874 if (getDiagnostics().hasErrorOccurred() || 12875 getDiagnostics().getSuppressAllDiagnostics()) { 12876 DiscardCleanupsInEvaluationContext(); 12877 } 12878 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12879 !isa<FunctionTemplateDecl>(dcl)) { 12880 // Since the body is valid, issue any analysis-based warnings that are 12881 // enabled. 12882 ActivePolicy = &WP; 12883 } 12884 12885 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12886 (!CheckConstexprFunctionDecl(FD) || 12887 !CheckConstexprFunctionBody(FD, Body))) 12888 FD->setInvalidDecl(); 12889 12890 if (FD && FD->hasAttr<NakedAttr>()) { 12891 for (const Stmt *S : Body->children()) { 12892 // Allow local register variables without initializer as they don't 12893 // require prologue. 12894 bool RegisterVariables = false; 12895 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12896 for (const auto *Decl : DS->decls()) { 12897 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12898 RegisterVariables = 12899 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12900 if (!RegisterVariables) 12901 break; 12902 } 12903 } 12904 } 12905 if (RegisterVariables) 12906 continue; 12907 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12908 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12909 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12910 FD->setInvalidDecl(); 12911 break; 12912 } 12913 } 12914 } 12915 12916 assert(ExprCleanupObjects.size() == 12917 ExprEvalContexts.back().NumCleanupObjects && 12918 "Leftover temporaries in function"); 12919 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12920 assert(MaybeODRUseExprs.empty() && 12921 "Leftover expressions for odr-use checking"); 12922 } 12923 12924 if (!IsInstantiation) 12925 PopDeclContext(); 12926 12927 PopFunctionScopeInfo(ActivePolicy, dcl); 12928 // If any errors have occurred, clear out any temporaries that may have 12929 // been leftover. This ensures that these temporaries won't be picked up for 12930 // deletion in some later function. 12931 if (getDiagnostics().hasErrorOccurred()) { 12932 DiscardCleanupsInEvaluationContext(); 12933 } 12934 12935 return dcl; 12936 } 12937 12938 /// When we finish delayed parsing of an attribute, we must attach it to the 12939 /// relevant Decl. 12940 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12941 ParsedAttributes &Attrs) { 12942 // Always attach attributes to the underlying decl. 12943 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12944 D = TD->getTemplatedDecl(); 12945 ProcessDeclAttributeList(S, D, Attrs.getList()); 12946 12947 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12948 if (Method->isStatic()) 12949 checkThisInStaticMemberFunctionAttributes(Method); 12950 } 12951 12952 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12953 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12954 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12955 IdentifierInfo &II, Scope *S) { 12956 // Find the scope in which the identifier is injected and the corresponding 12957 // DeclContext. 12958 // FIXME: C89 does not say what happens if there is no enclosing block scope. 12959 // In that case, we inject the declaration into the translation unit scope 12960 // instead. 12961 Scope *BlockScope = S; 12962 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 12963 BlockScope = BlockScope->getParent(); 12964 12965 Scope *ContextScope = BlockScope; 12966 while (!ContextScope->getEntity()) 12967 ContextScope = ContextScope->getParent(); 12968 ContextRAII SavedContext(*this, ContextScope->getEntity()); 12969 12970 // Before we produce a declaration for an implicitly defined 12971 // function, see whether there was a locally-scoped declaration of 12972 // this name as a function or variable. If so, use that 12973 // (non-visible) declaration, and complain about it. 12974 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 12975 if (ExternCPrev) { 12976 // We still need to inject the function into the enclosing block scope so 12977 // that later (non-call) uses can see it. 12978 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 12979 12980 // C89 footnote 38: 12981 // If in fact it is not defined as having type "function returning int", 12982 // the behavior is undefined. 12983 if (!isa<FunctionDecl>(ExternCPrev) || 12984 !Context.typesAreCompatible( 12985 cast<FunctionDecl>(ExternCPrev)->getType(), 12986 Context.getFunctionNoProtoType(Context.IntTy))) { 12987 Diag(Loc, diag::ext_use_out_of_scope_declaration) 12988 << ExternCPrev << !getLangOpts().C99; 12989 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12990 return ExternCPrev; 12991 } 12992 } 12993 12994 // Extension in C99. Legal in C90, but warn about it. 12995 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 12996 unsigned diag_id; 12997 if (II.getName().startswith("__builtin_")) 12998 diag_id = diag::warn_builtin_unknown; 12999 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13000 diag_id = diag::ext_implicit_function_decl; 13001 else 13002 diag_id = diag::warn_implicit_function_decl; 13003 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13004 13005 // If we found a prior declaration of this function, don't bother building 13006 // another one. We've already pushed that one into scope, so there's nothing 13007 // more to do. 13008 if (ExternCPrev) 13009 return ExternCPrev; 13010 13011 // Because typo correction is expensive, only do it if the implicit 13012 // function declaration is going to be treated as an error. 13013 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13014 TypoCorrection Corrected; 13015 if (S && 13016 (Corrected = CorrectTypo( 13017 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13018 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13019 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13020 /*ErrorRecovery*/false); 13021 } 13022 13023 // Set a Declarator for the implicit definition: int foo(); 13024 const char *Dummy; 13025 AttributeFactory attrFactory; 13026 DeclSpec DS(attrFactory); 13027 unsigned DiagID; 13028 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13029 Context.getPrintingPolicy()); 13030 (void)Error; // Silence warning. 13031 assert(!Error && "Error setting up implicit decl!"); 13032 SourceLocation NoLoc; 13033 Declarator D(DS, DeclaratorContext::BlockContext); 13034 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13035 /*IsAmbiguous=*/false, 13036 /*LParenLoc=*/NoLoc, 13037 /*Params=*/nullptr, 13038 /*NumParams=*/0, 13039 /*EllipsisLoc=*/NoLoc, 13040 /*RParenLoc=*/NoLoc, 13041 /*TypeQuals=*/0, 13042 /*RefQualifierIsLvalueRef=*/true, 13043 /*RefQualifierLoc=*/NoLoc, 13044 /*ConstQualifierLoc=*/NoLoc, 13045 /*VolatileQualifierLoc=*/NoLoc, 13046 /*RestrictQualifierLoc=*/NoLoc, 13047 /*MutableLoc=*/NoLoc, 13048 EST_None, 13049 /*ESpecRange=*/SourceRange(), 13050 /*Exceptions=*/nullptr, 13051 /*ExceptionRanges=*/nullptr, 13052 /*NumExceptions=*/0, 13053 /*NoexceptExpr=*/nullptr, 13054 /*ExceptionSpecTokens=*/nullptr, 13055 /*DeclsInPrototype=*/None, 13056 Loc, Loc, D), 13057 DS.getAttributes(), 13058 SourceLocation()); 13059 D.SetIdentifier(&II, Loc); 13060 13061 // Insert this function into the enclosing block scope. 13062 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13063 FD->setImplicit(); 13064 13065 AddKnownFunctionAttributes(FD); 13066 13067 return FD; 13068 } 13069 13070 /// \brief Adds any function attributes that we know a priori based on 13071 /// the declaration of this function. 13072 /// 13073 /// These attributes can apply both to implicitly-declared builtins 13074 /// (like __builtin___printf_chk) or to library-declared functions 13075 /// like NSLog or printf. 13076 /// 13077 /// We need to check for duplicate attributes both here and where user-written 13078 /// attributes are applied to declarations. 13079 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13080 if (FD->isInvalidDecl()) 13081 return; 13082 13083 // If this is a built-in function, map its builtin attributes to 13084 // actual attributes. 13085 if (unsigned BuiltinID = FD->getBuiltinID()) { 13086 // Handle printf-formatting attributes. 13087 unsigned FormatIdx; 13088 bool HasVAListArg; 13089 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13090 if (!FD->hasAttr<FormatAttr>()) { 13091 const char *fmt = "printf"; 13092 unsigned int NumParams = FD->getNumParams(); 13093 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13094 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13095 fmt = "NSString"; 13096 FD->addAttr(FormatAttr::CreateImplicit(Context, 13097 &Context.Idents.get(fmt), 13098 FormatIdx+1, 13099 HasVAListArg ? 0 : FormatIdx+2, 13100 FD->getLocation())); 13101 } 13102 } 13103 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13104 HasVAListArg)) { 13105 if (!FD->hasAttr<FormatAttr>()) 13106 FD->addAttr(FormatAttr::CreateImplicit(Context, 13107 &Context.Idents.get("scanf"), 13108 FormatIdx+1, 13109 HasVAListArg ? 0 : FormatIdx+2, 13110 FD->getLocation())); 13111 } 13112 13113 // Mark const if we don't care about errno and that is the only thing 13114 // preventing the function from being const. This allows IRgen to use LLVM 13115 // intrinsics for such functions. 13116 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13117 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13118 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13119 13120 // We make "fma" on some platforms const because we know it does not set 13121 // errno in those environments even though it could set errno based on the 13122 // C standard. 13123 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13124 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13125 !FD->hasAttr<ConstAttr>()) { 13126 switch (BuiltinID) { 13127 case Builtin::BI__builtin_fma: 13128 case Builtin::BI__builtin_fmaf: 13129 case Builtin::BI__builtin_fmal: 13130 case Builtin::BIfma: 13131 case Builtin::BIfmaf: 13132 case Builtin::BIfmal: 13133 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13134 break; 13135 default: 13136 break; 13137 } 13138 } 13139 13140 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13141 !FD->hasAttr<ReturnsTwiceAttr>()) 13142 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13143 FD->getLocation())); 13144 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13145 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13146 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13147 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13148 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13149 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13150 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13151 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13152 // Add the appropriate attribute, depending on the CUDA compilation mode 13153 // and which target the builtin belongs to. For example, during host 13154 // compilation, aux builtins are __device__, while the rest are __host__. 13155 if (getLangOpts().CUDAIsDevice != 13156 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13157 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13158 else 13159 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13160 } 13161 } 13162 13163 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13164 // throw, add an implicit nothrow attribute to any extern "C" function we come 13165 // across. 13166 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13167 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13168 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13169 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13170 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13171 } 13172 13173 IdentifierInfo *Name = FD->getIdentifier(); 13174 if (!Name) 13175 return; 13176 if ((!getLangOpts().CPlusPlus && 13177 FD->getDeclContext()->isTranslationUnit()) || 13178 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13179 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13180 LinkageSpecDecl::lang_c)) { 13181 // Okay: this could be a libc/libm/Objective-C function we know 13182 // about. 13183 } else 13184 return; 13185 13186 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13187 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13188 // target-specific builtins, perhaps? 13189 if (!FD->hasAttr<FormatAttr>()) 13190 FD->addAttr(FormatAttr::CreateImplicit(Context, 13191 &Context.Idents.get("printf"), 2, 13192 Name->isStr("vasprintf") ? 0 : 3, 13193 FD->getLocation())); 13194 } 13195 13196 if (Name->isStr("__CFStringMakeConstantString")) { 13197 // We already have a __builtin___CFStringMakeConstantString, 13198 // but builds that use -fno-constant-cfstrings don't go through that. 13199 if (!FD->hasAttr<FormatArgAttr>()) 13200 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13201 FD->getLocation())); 13202 } 13203 } 13204 13205 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13206 TypeSourceInfo *TInfo) { 13207 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13208 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13209 13210 if (!TInfo) { 13211 assert(D.isInvalidType() && "no declarator info for valid type"); 13212 TInfo = Context.getTrivialTypeSourceInfo(T); 13213 } 13214 13215 // Scope manipulation handled by caller. 13216 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13217 D.getLocStart(), 13218 D.getIdentifierLoc(), 13219 D.getIdentifier(), 13220 TInfo); 13221 13222 // Bail out immediately if we have an invalid declaration. 13223 if (D.isInvalidType()) { 13224 NewTD->setInvalidDecl(); 13225 return NewTD; 13226 } 13227 13228 if (D.getDeclSpec().isModulePrivateSpecified()) { 13229 if (CurContext->isFunctionOrMethod()) 13230 Diag(NewTD->getLocation(), diag::err_module_private_local) 13231 << 2 << NewTD->getDeclName() 13232 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13233 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13234 else 13235 NewTD->setModulePrivate(); 13236 } 13237 13238 // C++ [dcl.typedef]p8: 13239 // If the typedef declaration defines an unnamed class (or 13240 // enum), the first typedef-name declared by the declaration 13241 // to be that class type (or enum type) is used to denote the 13242 // class type (or enum type) for linkage purposes only. 13243 // We need to check whether the type was declared in the declaration. 13244 switch (D.getDeclSpec().getTypeSpecType()) { 13245 case TST_enum: 13246 case TST_struct: 13247 case TST_interface: 13248 case TST_union: 13249 case TST_class: { 13250 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13251 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13252 break; 13253 } 13254 13255 default: 13256 break; 13257 } 13258 13259 return NewTD; 13260 } 13261 13262 /// \brief Check that this is a valid underlying type for an enum declaration. 13263 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13264 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13265 QualType T = TI->getType(); 13266 13267 if (T->isDependentType()) 13268 return false; 13269 13270 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13271 if (BT->isInteger()) 13272 return false; 13273 13274 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13275 return true; 13276 } 13277 13278 /// Check whether this is a valid redeclaration of a previous enumeration. 13279 /// \return true if the redeclaration was invalid. 13280 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13281 QualType EnumUnderlyingTy, bool IsFixed, 13282 const EnumDecl *Prev) { 13283 if (IsScoped != Prev->isScoped()) { 13284 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13285 << Prev->isScoped(); 13286 Diag(Prev->getLocation(), diag::note_previous_declaration); 13287 return true; 13288 } 13289 13290 if (IsFixed && Prev->isFixed()) { 13291 if (!EnumUnderlyingTy->isDependentType() && 13292 !Prev->getIntegerType()->isDependentType() && 13293 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13294 Prev->getIntegerType())) { 13295 // TODO: Highlight the underlying type of the redeclaration. 13296 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13297 << EnumUnderlyingTy << Prev->getIntegerType(); 13298 Diag(Prev->getLocation(), diag::note_previous_declaration) 13299 << Prev->getIntegerTypeRange(); 13300 return true; 13301 } 13302 } else if (IsFixed != Prev->isFixed()) { 13303 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13304 << Prev->isFixed(); 13305 Diag(Prev->getLocation(), diag::note_previous_declaration); 13306 return true; 13307 } 13308 13309 return false; 13310 } 13311 13312 /// \brief Get diagnostic %select index for tag kind for 13313 /// redeclaration diagnostic message. 13314 /// WARNING: Indexes apply to particular diagnostics only! 13315 /// 13316 /// \returns diagnostic %select index. 13317 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13318 switch (Tag) { 13319 case TTK_Struct: return 0; 13320 case TTK_Interface: return 1; 13321 case TTK_Class: return 2; 13322 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13323 } 13324 } 13325 13326 /// \brief Determine if tag kind is a class-key compatible with 13327 /// class for redeclaration (class, struct, or __interface). 13328 /// 13329 /// \returns true iff the tag kind is compatible. 13330 static bool isClassCompatTagKind(TagTypeKind Tag) 13331 { 13332 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13333 } 13334 13335 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13336 TagTypeKind TTK) { 13337 if (isa<TypedefDecl>(PrevDecl)) 13338 return NTK_Typedef; 13339 else if (isa<TypeAliasDecl>(PrevDecl)) 13340 return NTK_TypeAlias; 13341 else if (isa<ClassTemplateDecl>(PrevDecl)) 13342 return NTK_Template; 13343 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13344 return NTK_TypeAliasTemplate; 13345 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13346 return NTK_TemplateTemplateArgument; 13347 switch (TTK) { 13348 case TTK_Struct: 13349 case TTK_Interface: 13350 case TTK_Class: 13351 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13352 case TTK_Union: 13353 return NTK_NonUnion; 13354 case TTK_Enum: 13355 return NTK_NonEnum; 13356 } 13357 llvm_unreachable("invalid TTK"); 13358 } 13359 13360 /// \brief Determine whether a tag with a given kind is acceptable 13361 /// as a redeclaration of the given tag declaration. 13362 /// 13363 /// \returns true if the new tag kind is acceptable, false otherwise. 13364 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13365 TagTypeKind NewTag, bool isDefinition, 13366 SourceLocation NewTagLoc, 13367 const IdentifierInfo *Name) { 13368 // C++ [dcl.type.elab]p3: 13369 // The class-key or enum keyword present in the 13370 // elaborated-type-specifier shall agree in kind with the 13371 // declaration to which the name in the elaborated-type-specifier 13372 // refers. This rule also applies to the form of 13373 // elaborated-type-specifier that declares a class-name or 13374 // friend class since it can be construed as referring to the 13375 // definition of the class. Thus, in any 13376 // elaborated-type-specifier, the enum keyword shall be used to 13377 // refer to an enumeration (7.2), the union class-key shall be 13378 // used to refer to a union (clause 9), and either the class or 13379 // struct class-key shall be used to refer to a class (clause 9) 13380 // declared using the class or struct class-key. 13381 TagTypeKind OldTag = Previous->getTagKind(); 13382 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13383 if (OldTag == NewTag) 13384 return true; 13385 13386 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13387 // Warn about the struct/class tag mismatch. 13388 bool isTemplate = false; 13389 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13390 isTemplate = Record->getDescribedClassTemplate(); 13391 13392 if (inTemplateInstantiation()) { 13393 // In a template instantiation, do not offer fix-its for tag mismatches 13394 // since they usually mess up the template instead of fixing the problem. 13395 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13396 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13397 << getRedeclDiagFromTagKind(OldTag); 13398 return true; 13399 } 13400 13401 if (isDefinition) { 13402 // On definitions, check previous tags and issue a fix-it for each 13403 // one that doesn't match the current tag. 13404 if (Previous->getDefinition()) { 13405 // Don't suggest fix-its for redefinitions. 13406 return true; 13407 } 13408 13409 bool previousMismatch = false; 13410 for (auto I : Previous->redecls()) { 13411 if (I->getTagKind() != NewTag) { 13412 if (!previousMismatch) { 13413 previousMismatch = true; 13414 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13415 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13416 << getRedeclDiagFromTagKind(I->getTagKind()); 13417 } 13418 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13419 << getRedeclDiagFromTagKind(NewTag) 13420 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13421 TypeWithKeyword::getTagTypeKindName(NewTag)); 13422 } 13423 } 13424 return true; 13425 } 13426 13427 // Check for a previous definition. If current tag and definition 13428 // are same type, do nothing. If no definition, but disagree with 13429 // with previous tag type, give a warning, but no fix-it. 13430 const TagDecl *Redecl = Previous->getDefinition() ? 13431 Previous->getDefinition() : Previous; 13432 if (Redecl->getTagKind() == NewTag) { 13433 return true; 13434 } 13435 13436 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13437 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13438 << getRedeclDiagFromTagKind(OldTag); 13439 Diag(Redecl->getLocation(), diag::note_previous_use); 13440 13441 // If there is a previous definition, suggest a fix-it. 13442 if (Previous->getDefinition()) { 13443 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13444 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13445 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13446 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13447 } 13448 13449 return true; 13450 } 13451 return false; 13452 } 13453 13454 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13455 /// from an outer enclosing namespace or file scope inside a friend declaration. 13456 /// This should provide the commented out code in the following snippet: 13457 /// namespace N { 13458 /// struct X; 13459 /// namespace M { 13460 /// struct Y { friend struct /*N::*/ X; }; 13461 /// } 13462 /// } 13463 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13464 SourceLocation NameLoc) { 13465 // While the decl is in a namespace, do repeated lookup of that name and see 13466 // if we get the same namespace back. If we do not, continue until 13467 // translation unit scope, at which point we have a fully qualified NNS. 13468 SmallVector<IdentifierInfo *, 4> Namespaces; 13469 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13470 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13471 // This tag should be declared in a namespace, which can only be enclosed by 13472 // other namespaces. Bail if there's an anonymous namespace in the chain. 13473 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13474 if (!Namespace || Namespace->isAnonymousNamespace()) 13475 return FixItHint(); 13476 IdentifierInfo *II = Namespace->getIdentifier(); 13477 Namespaces.push_back(II); 13478 NamedDecl *Lookup = SemaRef.LookupSingleName( 13479 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13480 if (Lookup == Namespace) 13481 break; 13482 } 13483 13484 // Once we have all the namespaces, reverse them to go outermost first, and 13485 // build an NNS. 13486 SmallString<64> Insertion; 13487 llvm::raw_svector_ostream OS(Insertion); 13488 if (DC->isTranslationUnit()) 13489 OS << "::"; 13490 std::reverse(Namespaces.begin(), Namespaces.end()); 13491 for (auto *II : Namespaces) 13492 OS << II->getName() << "::"; 13493 return FixItHint::CreateInsertion(NameLoc, Insertion); 13494 } 13495 13496 /// \brief Determine whether a tag originally declared in context \p OldDC can 13497 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13498 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13499 /// using-declaration). 13500 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13501 DeclContext *NewDC) { 13502 OldDC = OldDC->getRedeclContext(); 13503 NewDC = NewDC->getRedeclContext(); 13504 13505 if (OldDC->Equals(NewDC)) 13506 return true; 13507 13508 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13509 // encloses the other). 13510 if (S.getLangOpts().MSVCCompat && 13511 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13512 return true; 13513 13514 return false; 13515 } 13516 13517 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13518 /// former case, Name will be non-null. In the later case, Name will be null. 13519 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13520 /// reference/declaration/definition of a tag. 13521 /// 13522 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13523 /// trailing-type-specifier) other than one in an alias-declaration. 13524 /// 13525 /// \param SkipBody If non-null, will be set to indicate if the caller should 13526 /// skip the definition of this tag and treat it as if it were a declaration. 13527 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13528 SourceLocation KWLoc, CXXScopeSpec &SS, 13529 IdentifierInfo *Name, SourceLocation NameLoc, 13530 AttributeList *Attr, AccessSpecifier AS, 13531 SourceLocation ModulePrivateLoc, 13532 MultiTemplateParamsArg TemplateParameterLists, 13533 bool &OwnedDecl, bool &IsDependent, 13534 SourceLocation ScopedEnumKWLoc, 13535 bool ScopedEnumUsesClassTag, 13536 TypeResult UnderlyingType, 13537 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13538 SkipBodyInfo *SkipBody) { 13539 // If this is not a definition, it must have a name. 13540 IdentifierInfo *OrigName = Name; 13541 assert((Name != nullptr || TUK == TUK_Definition) && 13542 "Nameless record must be a definition!"); 13543 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13544 13545 OwnedDecl = false; 13546 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13547 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13548 13549 // FIXME: Check member specializations more carefully. 13550 bool isMemberSpecialization = false; 13551 bool Invalid = false; 13552 13553 // We only need to do this matching if we have template parameters 13554 // or a scope specifier, which also conveniently avoids this work 13555 // for non-C++ cases. 13556 if (TemplateParameterLists.size() > 0 || 13557 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13558 if (TemplateParameterList *TemplateParams = 13559 MatchTemplateParametersToScopeSpecifier( 13560 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13561 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13562 if (Kind == TTK_Enum) { 13563 Diag(KWLoc, diag::err_enum_template); 13564 return nullptr; 13565 } 13566 13567 if (TemplateParams->size() > 0) { 13568 // This is a declaration or definition of a class template (which may 13569 // be a member of another template). 13570 13571 if (Invalid) 13572 return nullptr; 13573 13574 OwnedDecl = false; 13575 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13576 SS, Name, NameLoc, Attr, 13577 TemplateParams, AS, 13578 ModulePrivateLoc, 13579 /*FriendLoc*/SourceLocation(), 13580 TemplateParameterLists.size()-1, 13581 TemplateParameterLists.data(), 13582 SkipBody); 13583 return Result.get(); 13584 } else { 13585 // The "template<>" header is extraneous. 13586 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13587 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13588 isMemberSpecialization = true; 13589 } 13590 } 13591 } 13592 13593 // Figure out the underlying type if this a enum declaration. We need to do 13594 // this early, because it's needed to detect if this is an incompatible 13595 // redeclaration. 13596 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13597 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13598 13599 if (Kind == TTK_Enum) { 13600 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13601 // No underlying type explicitly specified, or we failed to parse the 13602 // type, default to int. 13603 EnumUnderlying = Context.IntTy.getTypePtr(); 13604 } else if (UnderlyingType.get()) { 13605 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13606 // integral type; any cv-qualification is ignored. 13607 TypeSourceInfo *TI = nullptr; 13608 GetTypeFromParser(UnderlyingType.get(), &TI); 13609 EnumUnderlying = TI; 13610 13611 if (CheckEnumUnderlyingType(TI)) 13612 // Recover by falling back to int. 13613 EnumUnderlying = Context.IntTy.getTypePtr(); 13614 13615 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13616 UPPC_FixedUnderlyingType)) 13617 EnumUnderlying = Context.IntTy.getTypePtr(); 13618 13619 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13620 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13621 // of 'int'. However, if this is an unfixed forward declaration, don't set 13622 // the underlying type unless the user enables -fms-compatibility. This 13623 // makes unfixed forward declared enums incomplete and is more conforming. 13624 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13625 EnumUnderlying = Context.IntTy.getTypePtr(); 13626 } 13627 } 13628 13629 DeclContext *SearchDC = CurContext; 13630 DeclContext *DC = CurContext; 13631 bool isStdBadAlloc = false; 13632 bool isStdAlignValT = false; 13633 13634 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13635 if (TUK == TUK_Friend || TUK == TUK_Reference) 13636 Redecl = NotForRedeclaration; 13637 13638 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13639 /// implemented asks for structural equivalence checking, the returned decl 13640 /// here is passed back to the parser, allowing the tag body to be parsed. 13641 auto createTagFromNewDecl = [&]() -> TagDecl * { 13642 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13643 // If there is an identifier, use the location of the identifier as the 13644 // location of the decl, otherwise use the location of the struct/union 13645 // keyword. 13646 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13647 TagDecl *New = nullptr; 13648 13649 if (Kind == TTK_Enum) { 13650 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13651 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13652 // If this is an undefined enum, bail. 13653 if (TUK != TUK_Definition && !Invalid) 13654 return nullptr; 13655 if (EnumUnderlying) { 13656 EnumDecl *ED = cast<EnumDecl>(New); 13657 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13658 ED->setIntegerTypeSourceInfo(TI); 13659 else 13660 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13661 ED->setPromotionType(ED->getIntegerType()); 13662 } 13663 } else { // struct/union 13664 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13665 nullptr); 13666 } 13667 13668 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13669 // Add alignment attributes if necessary; these attributes are checked 13670 // when the ASTContext lays out the structure. 13671 // 13672 // It is important for implementing the correct semantics that this 13673 // happen here (in ActOnTag). The #pragma pack stack is 13674 // maintained as a result of parser callbacks which can occur at 13675 // many points during the parsing of a struct declaration (because 13676 // the #pragma tokens are effectively skipped over during the 13677 // parsing of the struct). 13678 if (TUK == TUK_Definition) { 13679 AddAlignmentAttributesForRecord(RD); 13680 AddMsStructLayoutForRecord(RD); 13681 } 13682 } 13683 New->setLexicalDeclContext(CurContext); 13684 return New; 13685 }; 13686 13687 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13688 if (Name && SS.isNotEmpty()) { 13689 // We have a nested-name tag ('struct foo::bar'). 13690 13691 // Check for invalid 'foo::'. 13692 if (SS.isInvalid()) { 13693 Name = nullptr; 13694 goto CreateNewDecl; 13695 } 13696 13697 // If this is a friend or a reference to a class in a dependent 13698 // context, don't try to make a decl for it. 13699 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13700 DC = computeDeclContext(SS, false); 13701 if (!DC) { 13702 IsDependent = true; 13703 return nullptr; 13704 } 13705 } else { 13706 DC = computeDeclContext(SS, true); 13707 if (!DC) { 13708 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13709 << SS.getRange(); 13710 return nullptr; 13711 } 13712 } 13713 13714 if (RequireCompleteDeclContext(SS, DC)) 13715 return nullptr; 13716 13717 SearchDC = DC; 13718 // Look-up name inside 'foo::'. 13719 LookupQualifiedName(Previous, DC); 13720 13721 if (Previous.isAmbiguous()) 13722 return nullptr; 13723 13724 if (Previous.empty()) { 13725 // Name lookup did not find anything. However, if the 13726 // nested-name-specifier refers to the current instantiation, 13727 // and that current instantiation has any dependent base 13728 // classes, we might find something at instantiation time: treat 13729 // this as a dependent elaborated-type-specifier. 13730 // But this only makes any sense for reference-like lookups. 13731 if (Previous.wasNotFoundInCurrentInstantiation() && 13732 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13733 IsDependent = true; 13734 return nullptr; 13735 } 13736 13737 // A tag 'foo::bar' must already exist. 13738 Diag(NameLoc, diag::err_not_tag_in_scope) 13739 << Kind << Name << DC << SS.getRange(); 13740 Name = nullptr; 13741 Invalid = true; 13742 goto CreateNewDecl; 13743 } 13744 } else if (Name) { 13745 // C++14 [class.mem]p14: 13746 // If T is the name of a class, then each of the following shall have a 13747 // name different from T: 13748 // -- every member of class T that is itself a type 13749 if (TUK != TUK_Reference && TUK != TUK_Friend && 13750 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13751 return nullptr; 13752 13753 // If this is a named struct, check to see if there was a previous forward 13754 // declaration or definition. 13755 // FIXME: We're looking into outer scopes here, even when we 13756 // shouldn't be. Doing so can result in ambiguities that we 13757 // shouldn't be diagnosing. 13758 LookupName(Previous, S); 13759 13760 // When declaring or defining a tag, ignore ambiguities introduced 13761 // by types using'ed into this scope. 13762 if (Previous.isAmbiguous() && 13763 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13764 LookupResult::Filter F = Previous.makeFilter(); 13765 while (F.hasNext()) { 13766 NamedDecl *ND = F.next(); 13767 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13768 SearchDC->getRedeclContext())) 13769 F.erase(); 13770 } 13771 F.done(); 13772 } 13773 13774 // C++11 [namespace.memdef]p3: 13775 // If the name in a friend declaration is neither qualified nor 13776 // a template-id and the declaration is a function or an 13777 // elaborated-type-specifier, the lookup to determine whether 13778 // the entity has been previously declared shall not consider 13779 // any scopes outside the innermost enclosing namespace. 13780 // 13781 // MSVC doesn't implement the above rule for types, so a friend tag 13782 // declaration may be a redeclaration of a type declared in an enclosing 13783 // scope. They do implement this rule for friend functions. 13784 // 13785 // Does it matter that this should be by scope instead of by 13786 // semantic context? 13787 if (!Previous.empty() && TUK == TUK_Friend) { 13788 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13789 LookupResult::Filter F = Previous.makeFilter(); 13790 bool FriendSawTagOutsideEnclosingNamespace = false; 13791 while (F.hasNext()) { 13792 NamedDecl *ND = F.next(); 13793 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13794 if (DC->isFileContext() && 13795 !EnclosingNS->Encloses(ND->getDeclContext())) { 13796 if (getLangOpts().MSVCCompat) 13797 FriendSawTagOutsideEnclosingNamespace = true; 13798 else 13799 F.erase(); 13800 } 13801 } 13802 F.done(); 13803 13804 // Diagnose this MSVC extension in the easy case where lookup would have 13805 // unambiguously found something outside the enclosing namespace. 13806 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13807 NamedDecl *ND = Previous.getFoundDecl(); 13808 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13809 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13810 } 13811 } 13812 13813 // Note: there used to be some attempt at recovery here. 13814 if (Previous.isAmbiguous()) 13815 return nullptr; 13816 13817 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13818 // FIXME: This makes sure that we ignore the contexts associated 13819 // with C structs, unions, and enums when looking for a matching 13820 // tag declaration or definition. See the similar lookup tweak 13821 // in Sema::LookupName; is there a better way to deal with this? 13822 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13823 SearchDC = SearchDC->getParent(); 13824 } 13825 } 13826 13827 if (Previous.isSingleResult() && 13828 Previous.getFoundDecl()->isTemplateParameter()) { 13829 // Maybe we will complain about the shadowed template parameter. 13830 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13831 // Just pretend that we didn't see the previous declaration. 13832 Previous.clear(); 13833 } 13834 13835 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13836 DC->Equals(getStdNamespace())) { 13837 if (Name->isStr("bad_alloc")) { 13838 // This is a declaration of or a reference to "std::bad_alloc". 13839 isStdBadAlloc = true; 13840 13841 // If std::bad_alloc has been implicitly declared (but made invisible to 13842 // name lookup), fill in this implicit declaration as the previous 13843 // declaration, so that the declarations get chained appropriately. 13844 if (Previous.empty() && StdBadAlloc) 13845 Previous.addDecl(getStdBadAlloc()); 13846 } else if (Name->isStr("align_val_t")) { 13847 isStdAlignValT = true; 13848 if (Previous.empty() && StdAlignValT) 13849 Previous.addDecl(getStdAlignValT()); 13850 } 13851 } 13852 13853 // If we didn't find a previous declaration, and this is a reference 13854 // (or friend reference), move to the correct scope. In C++, we 13855 // also need to do a redeclaration lookup there, just in case 13856 // there's a shadow friend decl. 13857 if (Name && Previous.empty() && 13858 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13859 if (Invalid) goto CreateNewDecl; 13860 assert(SS.isEmpty()); 13861 13862 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13863 // C++ [basic.scope.pdecl]p5: 13864 // -- for an elaborated-type-specifier of the form 13865 // 13866 // class-key identifier 13867 // 13868 // if the elaborated-type-specifier is used in the 13869 // decl-specifier-seq or parameter-declaration-clause of a 13870 // function defined in namespace scope, the identifier is 13871 // declared as a class-name in the namespace that contains 13872 // the declaration; otherwise, except as a friend 13873 // declaration, the identifier is declared in the smallest 13874 // non-class, non-function-prototype scope that contains the 13875 // declaration. 13876 // 13877 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13878 // C structs and unions. 13879 // 13880 // It is an error in C++ to declare (rather than define) an enum 13881 // type, including via an elaborated type specifier. We'll 13882 // diagnose that later; for now, declare the enum in the same 13883 // scope as we would have picked for any other tag type. 13884 // 13885 // GNU C also supports this behavior as part of its incomplete 13886 // enum types extension, while GNU C++ does not. 13887 // 13888 // Find the context where we'll be declaring the tag. 13889 // FIXME: We would like to maintain the current DeclContext as the 13890 // lexical context, 13891 SearchDC = getTagInjectionContext(SearchDC); 13892 13893 // Find the scope where we'll be declaring the tag. 13894 S = getTagInjectionScope(S, getLangOpts()); 13895 } else { 13896 assert(TUK == TUK_Friend); 13897 // C++ [namespace.memdef]p3: 13898 // If a friend declaration in a non-local class first declares a 13899 // class or function, the friend class or function is a member of 13900 // the innermost enclosing namespace. 13901 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13902 } 13903 13904 // In C++, we need to do a redeclaration lookup to properly 13905 // diagnose some problems. 13906 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13907 // hidden declaration so that we don't get ambiguity errors when using a 13908 // type declared by an elaborated-type-specifier. In C that is not correct 13909 // and we should instead merge compatible types found by lookup. 13910 if (getLangOpts().CPlusPlus) { 13911 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13912 LookupQualifiedName(Previous, SearchDC); 13913 } else { 13914 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13915 LookupName(Previous, S); 13916 } 13917 } 13918 13919 // If we have a known previous declaration to use, then use it. 13920 if (Previous.empty() && SkipBody && SkipBody->Previous) 13921 Previous.addDecl(SkipBody->Previous); 13922 13923 if (!Previous.empty()) { 13924 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13925 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13926 13927 // It's okay to have a tag decl in the same scope as a typedef 13928 // which hides a tag decl in the same scope. Finding this 13929 // insanity with a redeclaration lookup can only actually happen 13930 // in C++. 13931 // 13932 // This is also okay for elaborated-type-specifiers, which is 13933 // technically forbidden by the current standard but which is 13934 // okay according to the likely resolution of an open issue; 13935 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13936 if (getLangOpts().CPlusPlus) { 13937 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13938 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13939 TagDecl *Tag = TT->getDecl(); 13940 if (Tag->getDeclName() == Name && 13941 Tag->getDeclContext()->getRedeclContext() 13942 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13943 PrevDecl = Tag; 13944 Previous.clear(); 13945 Previous.addDecl(Tag); 13946 Previous.resolveKind(); 13947 } 13948 } 13949 } 13950 } 13951 13952 // If this is a redeclaration of a using shadow declaration, it must 13953 // declare a tag in the same context. In MSVC mode, we allow a 13954 // redefinition if either context is within the other. 13955 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13956 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13957 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13958 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13959 !(OldTag && isAcceptableTagRedeclContext( 13960 *this, OldTag->getDeclContext(), SearchDC))) { 13961 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13962 Diag(Shadow->getTargetDecl()->getLocation(), 13963 diag::note_using_decl_target); 13964 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13965 << 0; 13966 // Recover by ignoring the old declaration. 13967 Previous.clear(); 13968 goto CreateNewDecl; 13969 } 13970 } 13971 13972 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13973 // If this is a use of a previous tag, or if the tag is already declared 13974 // in the same scope (so that the definition/declaration completes or 13975 // rementions the tag), reuse the decl. 13976 if (TUK == TUK_Reference || TUK == TUK_Friend || 13977 isDeclInScope(DirectPrevDecl, SearchDC, S, 13978 SS.isNotEmpty() || isMemberSpecialization)) { 13979 // Make sure that this wasn't declared as an enum and now used as a 13980 // struct or something similar. 13981 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13982 TUK == TUK_Definition, KWLoc, 13983 Name)) { 13984 bool SafeToContinue 13985 = (PrevTagDecl->getTagKind() != TTK_Enum && 13986 Kind != TTK_Enum); 13987 if (SafeToContinue) 13988 Diag(KWLoc, diag::err_use_with_wrong_tag) 13989 << Name 13990 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13991 PrevTagDecl->getKindName()); 13992 else 13993 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13994 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13995 13996 if (SafeToContinue) 13997 Kind = PrevTagDecl->getTagKind(); 13998 else { 13999 // Recover by making this an anonymous redefinition. 14000 Name = nullptr; 14001 Previous.clear(); 14002 Invalid = true; 14003 } 14004 } 14005 14006 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14007 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14008 14009 // If this is an elaborated-type-specifier for a scoped enumeration, 14010 // the 'class' keyword is not necessary and not permitted. 14011 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14012 if (ScopedEnum) 14013 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14014 << PrevEnum->isScoped() 14015 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14016 return PrevTagDecl; 14017 } 14018 14019 QualType EnumUnderlyingTy; 14020 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14021 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14022 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14023 EnumUnderlyingTy = QualType(T, 0); 14024 14025 // All conflicts with previous declarations are recovered by 14026 // returning the previous declaration, unless this is a definition, 14027 // in which case we want the caller to bail out. 14028 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14029 ScopedEnum, EnumUnderlyingTy, 14030 IsFixed, PrevEnum)) 14031 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14032 } 14033 14034 // C++11 [class.mem]p1: 14035 // A member shall not be declared twice in the member-specification, 14036 // except that a nested class or member class template can be declared 14037 // and then later defined. 14038 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14039 S->isDeclScope(PrevDecl)) { 14040 Diag(NameLoc, diag::ext_member_redeclared); 14041 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14042 } 14043 14044 if (!Invalid) { 14045 // If this is a use, just return the declaration we found, unless 14046 // we have attributes. 14047 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14048 if (Attr) { 14049 // FIXME: Diagnose these attributes. For now, we create a new 14050 // declaration to hold them. 14051 } else if (TUK == TUK_Reference && 14052 (PrevTagDecl->getFriendObjectKind() == 14053 Decl::FOK_Undeclared || 14054 PrevDecl->getOwningModule() != getCurrentModule()) && 14055 SS.isEmpty()) { 14056 // This declaration is a reference to an existing entity, but 14057 // has different visibility from that entity: it either makes 14058 // a friend visible or it makes a type visible in a new module. 14059 // In either case, create a new declaration. We only do this if 14060 // the declaration would have meant the same thing if no prior 14061 // declaration were found, that is, if it was found in the same 14062 // scope where we would have injected a declaration. 14063 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14064 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14065 return PrevTagDecl; 14066 // This is in the injected scope, create a new declaration in 14067 // that scope. 14068 S = getTagInjectionScope(S, getLangOpts()); 14069 } else { 14070 return PrevTagDecl; 14071 } 14072 } 14073 14074 // Diagnose attempts to redefine a tag. 14075 if (TUK == TUK_Definition) { 14076 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14077 // If we're defining a specialization and the previous definition 14078 // is from an implicit instantiation, don't emit an error 14079 // here; we'll catch this in the general case below. 14080 bool IsExplicitSpecializationAfterInstantiation = false; 14081 if (isMemberSpecialization) { 14082 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14083 IsExplicitSpecializationAfterInstantiation = 14084 RD->getTemplateSpecializationKind() != 14085 TSK_ExplicitSpecialization; 14086 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14087 IsExplicitSpecializationAfterInstantiation = 14088 ED->getTemplateSpecializationKind() != 14089 TSK_ExplicitSpecialization; 14090 } 14091 14092 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14093 // not keep more that one definition around (merge them). However, 14094 // ensure the decl passes the structural compatibility check in 14095 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14096 NamedDecl *Hidden = nullptr; 14097 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14098 // There is a definition of this tag, but it is not visible. We 14099 // explicitly make use of C++'s one definition rule here, and 14100 // assume that this definition is identical to the hidden one 14101 // we already have. Make the existing definition visible and 14102 // use it in place of this one. 14103 if (!getLangOpts().CPlusPlus) { 14104 // Postpone making the old definition visible until after we 14105 // complete parsing the new one and do the structural 14106 // comparison. 14107 SkipBody->CheckSameAsPrevious = true; 14108 SkipBody->New = createTagFromNewDecl(); 14109 SkipBody->Previous = Hidden; 14110 } else { 14111 SkipBody->ShouldSkip = true; 14112 makeMergedDefinitionVisible(Hidden); 14113 } 14114 return Def; 14115 } else if (!IsExplicitSpecializationAfterInstantiation) { 14116 // A redeclaration in function prototype scope in C isn't 14117 // visible elsewhere, so merely issue a warning. 14118 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14119 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14120 else 14121 Diag(NameLoc, diag::err_redefinition) << Name; 14122 notePreviousDefinition(Def, 14123 NameLoc.isValid() ? NameLoc : KWLoc); 14124 // If this is a redefinition, recover by making this 14125 // struct be anonymous, which will make any later 14126 // references get the previous definition. 14127 Name = nullptr; 14128 Previous.clear(); 14129 Invalid = true; 14130 } 14131 } else { 14132 // If the type is currently being defined, complain 14133 // about a nested redefinition. 14134 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14135 if (TD->isBeingDefined()) { 14136 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14137 Diag(PrevTagDecl->getLocation(), 14138 diag::note_previous_definition); 14139 Name = nullptr; 14140 Previous.clear(); 14141 Invalid = true; 14142 } 14143 } 14144 14145 // Okay, this is definition of a previously declared or referenced 14146 // tag. We're going to create a new Decl for it. 14147 } 14148 14149 // Okay, we're going to make a redeclaration. If this is some kind 14150 // of reference, make sure we build the redeclaration in the same DC 14151 // as the original, and ignore the current access specifier. 14152 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14153 SearchDC = PrevTagDecl->getDeclContext(); 14154 AS = AS_none; 14155 } 14156 } 14157 // If we get here we have (another) forward declaration or we 14158 // have a definition. Just create a new decl. 14159 14160 } else { 14161 // If we get here, this is a definition of a new tag type in a nested 14162 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14163 // new decl/type. We set PrevDecl to NULL so that the entities 14164 // have distinct types. 14165 Previous.clear(); 14166 } 14167 // If we get here, we're going to create a new Decl. If PrevDecl 14168 // is non-NULL, it's a definition of the tag declared by 14169 // PrevDecl. If it's NULL, we have a new definition. 14170 14171 // Otherwise, PrevDecl is not a tag, but was found with tag 14172 // lookup. This is only actually possible in C++, where a few 14173 // things like templates still live in the tag namespace. 14174 } else { 14175 // Use a better diagnostic if an elaborated-type-specifier 14176 // found the wrong kind of type on the first 14177 // (non-redeclaration) lookup. 14178 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14179 !Previous.isForRedeclaration()) { 14180 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14181 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14182 << Kind; 14183 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14184 Invalid = true; 14185 14186 // Otherwise, only diagnose if the declaration is in scope. 14187 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14188 SS.isNotEmpty() || isMemberSpecialization)) { 14189 // do nothing 14190 14191 // Diagnose implicit declarations introduced by elaborated types. 14192 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14193 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14194 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14195 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14196 Invalid = true; 14197 14198 // Otherwise it's a declaration. Call out a particularly common 14199 // case here. 14200 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14201 unsigned Kind = 0; 14202 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14203 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14204 << Name << Kind << TND->getUnderlyingType(); 14205 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14206 Invalid = true; 14207 14208 // Otherwise, diagnose. 14209 } else { 14210 // The tag name clashes with something else in the target scope, 14211 // issue an error and recover by making this tag be anonymous. 14212 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14213 notePreviousDefinition(PrevDecl, NameLoc); 14214 Name = nullptr; 14215 Invalid = true; 14216 } 14217 14218 // The existing declaration isn't relevant to us; we're in a 14219 // new scope, so clear out the previous declaration. 14220 Previous.clear(); 14221 } 14222 } 14223 14224 CreateNewDecl: 14225 14226 TagDecl *PrevDecl = nullptr; 14227 if (Previous.isSingleResult()) 14228 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14229 14230 // If there is an identifier, use the location of the identifier as the 14231 // location of the decl, otherwise use the location of the struct/union 14232 // keyword. 14233 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14234 14235 // Otherwise, create a new declaration. If there is a previous 14236 // declaration of the same entity, the two will be linked via 14237 // PrevDecl. 14238 TagDecl *New; 14239 14240 bool IsForwardReference = false; 14241 if (Kind == TTK_Enum) { 14242 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14243 // enum X { A, B, C } D; D should chain to X. 14244 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14245 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14246 ScopedEnumUsesClassTag, IsFixed); 14247 14248 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14249 StdAlignValT = cast<EnumDecl>(New); 14250 14251 // If this is an undefined enum, warn. 14252 if (TUK != TUK_Definition && !Invalid) { 14253 TagDecl *Def; 14254 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14255 cast<EnumDecl>(New)->isFixed()) { 14256 // C++0x: 7.2p2: opaque-enum-declaration. 14257 // Conflicts are diagnosed above. Do nothing. 14258 } 14259 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14260 Diag(Loc, diag::ext_forward_ref_enum_def) 14261 << New; 14262 Diag(Def->getLocation(), diag::note_previous_definition); 14263 } else { 14264 unsigned DiagID = diag::ext_forward_ref_enum; 14265 if (getLangOpts().MSVCCompat) 14266 DiagID = diag::ext_ms_forward_ref_enum; 14267 else if (getLangOpts().CPlusPlus) 14268 DiagID = diag::err_forward_ref_enum; 14269 Diag(Loc, DiagID); 14270 14271 // If this is a forward-declared reference to an enumeration, make a 14272 // note of it; we won't actually be introducing the declaration into 14273 // the declaration context. 14274 if (TUK == TUK_Reference) 14275 IsForwardReference = true; 14276 } 14277 } 14278 14279 if (EnumUnderlying) { 14280 EnumDecl *ED = cast<EnumDecl>(New); 14281 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14282 ED->setIntegerTypeSourceInfo(TI); 14283 else 14284 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14285 ED->setPromotionType(ED->getIntegerType()); 14286 assert(ED->isComplete() && "enum with type should be complete"); 14287 } 14288 } else { 14289 // struct/union/class 14290 14291 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14292 // struct X { int A; } D; D should chain to X. 14293 if (getLangOpts().CPlusPlus) { 14294 // FIXME: Look for a way to use RecordDecl for simple structs. 14295 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14296 cast_or_null<CXXRecordDecl>(PrevDecl)); 14297 14298 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14299 StdBadAlloc = cast<CXXRecordDecl>(New); 14300 } else 14301 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14302 cast_or_null<RecordDecl>(PrevDecl)); 14303 } 14304 14305 // C++11 [dcl.type]p3: 14306 // A type-specifier-seq shall not define a class or enumeration [...]. 14307 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14308 TUK == TUK_Definition) { 14309 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14310 << Context.getTagDeclType(New); 14311 Invalid = true; 14312 } 14313 14314 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14315 DC->getDeclKind() == Decl::Enum) { 14316 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14317 << Context.getTagDeclType(New); 14318 Invalid = true; 14319 } 14320 14321 // Maybe add qualifier info. 14322 if (SS.isNotEmpty()) { 14323 if (SS.isSet()) { 14324 // If this is either a declaration or a definition, check the 14325 // nested-name-specifier against the current context. 14326 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14327 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14328 isMemberSpecialization)) 14329 Invalid = true; 14330 14331 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14332 if (TemplateParameterLists.size() > 0) { 14333 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14334 } 14335 } 14336 else 14337 Invalid = true; 14338 } 14339 14340 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14341 // Add alignment attributes if necessary; these attributes are checked when 14342 // the ASTContext lays out the structure. 14343 // 14344 // It is important for implementing the correct semantics that this 14345 // happen here (in ActOnTag). The #pragma pack stack is 14346 // maintained as a result of parser callbacks which can occur at 14347 // many points during the parsing of a struct declaration (because 14348 // the #pragma tokens are effectively skipped over during the 14349 // parsing of the struct). 14350 if (TUK == TUK_Definition) { 14351 AddAlignmentAttributesForRecord(RD); 14352 AddMsStructLayoutForRecord(RD); 14353 } 14354 } 14355 14356 if (ModulePrivateLoc.isValid()) { 14357 if (isMemberSpecialization) 14358 Diag(New->getLocation(), diag::err_module_private_specialization) 14359 << 2 14360 << FixItHint::CreateRemoval(ModulePrivateLoc); 14361 // __module_private__ does not apply to local classes. However, we only 14362 // diagnose this as an error when the declaration specifiers are 14363 // freestanding. Here, we just ignore the __module_private__. 14364 else if (!SearchDC->isFunctionOrMethod()) 14365 New->setModulePrivate(); 14366 } 14367 14368 // If this is a specialization of a member class (of a class template), 14369 // check the specialization. 14370 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14371 Invalid = true; 14372 14373 // If we're declaring or defining a tag in function prototype scope in C, 14374 // note that this type can only be used within the function and add it to 14375 // the list of decls to inject into the function definition scope. 14376 if ((Name || Kind == TTK_Enum) && 14377 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14378 if (getLangOpts().CPlusPlus) { 14379 // C++ [dcl.fct]p6: 14380 // Types shall not be defined in return or parameter types. 14381 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14382 Diag(Loc, diag::err_type_defined_in_param_type) 14383 << Name; 14384 Invalid = true; 14385 } 14386 } else if (!PrevDecl) { 14387 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14388 } 14389 } 14390 14391 if (Invalid) 14392 New->setInvalidDecl(); 14393 14394 // Set the lexical context. If the tag has a C++ scope specifier, the 14395 // lexical context will be different from the semantic context. 14396 New->setLexicalDeclContext(CurContext); 14397 14398 // Mark this as a friend decl if applicable. 14399 // In Microsoft mode, a friend declaration also acts as a forward 14400 // declaration so we always pass true to setObjectOfFriendDecl to make 14401 // the tag name visible. 14402 if (TUK == TUK_Friend) 14403 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14404 14405 // Set the access specifier. 14406 if (!Invalid && SearchDC->isRecord()) 14407 SetMemberAccessSpecifier(New, PrevDecl, AS); 14408 14409 if (PrevDecl) 14410 CheckRedeclarationModuleOwnership(New, PrevDecl); 14411 14412 if (TUK == TUK_Definition) 14413 New->startDefinition(); 14414 14415 if (Attr) 14416 ProcessDeclAttributeList(S, New, Attr); 14417 AddPragmaAttributes(S, New); 14418 14419 // If this has an identifier, add it to the scope stack. 14420 if (TUK == TUK_Friend) { 14421 // We might be replacing an existing declaration in the lookup tables; 14422 // if so, borrow its access specifier. 14423 if (PrevDecl) 14424 New->setAccess(PrevDecl->getAccess()); 14425 14426 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14427 DC->makeDeclVisibleInContext(New); 14428 if (Name) // can be null along some error paths 14429 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14430 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14431 } else if (Name) { 14432 S = getNonFieldDeclScope(S); 14433 PushOnScopeChains(New, S, !IsForwardReference); 14434 if (IsForwardReference) 14435 SearchDC->makeDeclVisibleInContext(New); 14436 } else { 14437 CurContext->addDecl(New); 14438 } 14439 14440 // If this is the C FILE type, notify the AST context. 14441 if (IdentifierInfo *II = New->getIdentifier()) 14442 if (!New->isInvalidDecl() && 14443 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14444 II->isStr("FILE")) 14445 Context.setFILEDecl(New); 14446 14447 if (PrevDecl) 14448 mergeDeclAttributes(New, PrevDecl); 14449 14450 // If there's a #pragma GCC visibility in scope, set the visibility of this 14451 // record. 14452 AddPushedVisibilityAttribute(New); 14453 14454 if (isMemberSpecialization && !New->isInvalidDecl()) 14455 CompleteMemberSpecialization(New, Previous); 14456 14457 OwnedDecl = true; 14458 // In C++, don't return an invalid declaration. We can't recover well from 14459 // the cases where we make the type anonymous. 14460 if (Invalid && getLangOpts().CPlusPlus) { 14461 if (New->isBeingDefined()) 14462 if (auto RD = dyn_cast<RecordDecl>(New)) 14463 RD->completeDefinition(); 14464 return nullptr; 14465 } else { 14466 return New; 14467 } 14468 } 14469 14470 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14471 AdjustDeclIfTemplate(TagD); 14472 TagDecl *Tag = cast<TagDecl>(TagD); 14473 14474 // Enter the tag context. 14475 PushDeclContext(S, Tag); 14476 14477 ActOnDocumentableDecl(TagD); 14478 14479 // If there's a #pragma GCC visibility in scope, set the visibility of this 14480 // record. 14481 AddPushedVisibilityAttribute(Tag); 14482 } 14483 14484 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14485 SkipBodyInfo &SkipBody) { 14486 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14487 return false; 14488 14489 // Make the previous decl visible. 14490 makeMergedDefinitionVisible(SkipBody.Previous); 14491 return true; 14492 } 14493 14494 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14495 assert(isa<ObjCContainerDecl>(IDecl) && 14496 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14497 DeclContext *OCD = cast<DeclContext>(IDecl); 14498 assert(getContainingDC(OCD) == CurContext && 14499 "The next DeclContext should be lexically contained in the current one."); 14500 CurContext = OCD; 14501 return IDecl; 14502 } 14503 14504 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14505 SourceLocation FinalLoc, 14506 bool IsFinalSpelledSealed, 14507 SourceLocation LBraceLoc) { 14508 AdjustDeclIfTemplate(TagD); 14509 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14510 14511 FieldCollector->StartClass(); 14512 14513 if (!Record->getIdentifier()) 14514 return; 14515 14516 if (FinalLoc.isValid()) 14517 Record->addAttr(new (Context) 14518 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14519 14520 // C++ [class]p2: 14521 // [...] The class-name is also inserted into the scope of the 14522 // class itself; this is known as the injected-class-name. For 14523 // purposes of access checking, the injected-class-name is treated 14524 // as if it were a public member name. 14525 CXXRecordDecl *InjectedClassName 14526 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14527 Record->getLocStart(), Record->getLocation(), 14528 Record->getIdentifier(), 14529 /*PrevDecl=*/nullptr, 14530 /*DelayTypeCreation=*/true); 14531 Context.getTypeDeclType(InjectedClassName, Record); 14532 InjectedClassName->setImplicit(); 14533 InjectedClassName->setAccess(AS_public); 14534 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14535 InjectedClassName->setDescribedClassTemplate(Template); 14536 PushOnScopeChains(InjectedClassName, S); 14537 assert(InjectedClassName->isInjectedClassName() && 14538 "Broken injected-class-name"); 14539 } 14540 14541 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14542 SourceRange BraceRange) { 14543 AdjustDeclIfTemplate(TagD); 14544 TagDecl *Tag = cast<TagDecl>(TagD); 14545 Tag->setBraceRange(BraceRange); 14546 14547 // Make sure we "complete" the definition even it is invalid. 14548 if (Tag->isBeingDefined()) { 14549 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14550 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14551 RD->completeDefinition(); 14552 } 14553 14554 if (isa<CXXRecordDecl>(Tag)) { 14555 FieldCollector->FinishClass(); 14556 } 14557 14558 // Exit this scope of this tag's definition. 14559 PopDeclContext(); 14560 14561 if (getCurLexicalContext()->isObjCContainer() && 14562 Tag->getDeclContext()->isFileContext()) 14563 Tag->setTopLevelDeclInObjCContainer(); 14564 14565 // Notify the consumer that we've defined a tag. 14566 if (!Tag->isInvalidDecl()) 14567 Consumer.HandleTagDeclDefinition(Tag); 14568 } 14569 14570 void Sema::ActOnObjCContainerFinishDefinition() { 14571 // Exit this scope of this interface definition. 14572 PopDeclContext(); 14573 } 14574 14575 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14576 assert(DC == CurContext && "Mismatch of container contexts"); 14577 OriginalLexicalContext = DC; 14578 ActOnObjCContainerFinishDefinition(); 14579 } 14580 14581 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14582 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14583 OriginalLexicalContext = nullptr; 14584 } 14585 14586 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14587 AdjustDeclIfTemplate(TagD); 14588 TagDecl *Tag = cast<TagDecl>(TagD); 14589 Tag->setInvalidDecl(); 14590 14591 // Make sure we "complete" the definition even it is invalid. 14592 if (Tag->isBeingDefined()) { 14593 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14594 RD->completeDefinition(); 14595 } 14596 14597 // We're undoing ActOnTagStartDefinition here, not 14598 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14599 // the FieldCollector. 14600 14601 PopDeclContext(); 14602 } 14603 14604 // Note that FieldName may be null for anonymous bitfields. 14605 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14606 IdentifierInfo *FieldName, 14607 QualType FieldTy, bool IsMsStruct, 14608 Expr *BitWidth, bool *ZeroWidth) { 14609 // Default to true; that shouldn't confuse checks for emptiness 14610 if (ZeroWidth) 14611 *ZeroWidth = true; 14612 14613 // C99 6.7.2.1p4 - verify the field type. 14614 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14615 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14616 // Handle incomplete types with specific error. 14617 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14618 return ExprError(); 14619 if (FieldName) 14620 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14621 << FieldName << FieldTy << BitWidth->getSourceRange(); 14622 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14623 << FieldTy << BitWidth->getSourceRange(); 14624 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14625 UPPC_BitFieldWidth)) 14626 return ExprError(); 14627 14628 // If the bit-width is type- or value-dependent, don't try to check 14629 // it now. 14630 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14631 return BitWidth; 14632 14633 llvm::APSInt Value; 14634 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14635 if (ICE.isInvalid()) 14636 return ICE; 14637 BitWidth = ICE.get(); 14638 14639 if (Value != 0 && ZeroWidth) 14640 *ZeroWidth = false; 14641 14642 // Zero-width bitfield is ok for anonymous field. 14643 if (Value == 0 && FieldName) 14644 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14645 14646 if (Value.isSigned() && Value.isNegative()) { 14647 if (FieldName) 14648 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14649 << FieldName << Value.toString(10); 14650 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14651 << Value.toString(10); 14652 } 14653 14654 if (!FieldTy->isDependentType()) { 14655 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14656 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14657 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14658 14659 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14660 // ABI. 14661 bool CStdConstraintViolation = 14662 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14663 bool MSBitfieldViolation = 14664 Value.ugt(TypeStorageSize) && 14665 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14666 if (CStdConstraintViolation || MSBitfieldViolation) { 14667 unsigned DiagWidth = 14668 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14669 if (FieldName) 14670 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14671 << FieldName << (unsigned)Value.getZExtValue() 14672 << !CStdConstraintViolation << DiagWidth; 14673 14674 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14675 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14676 << DiagWidth; 14677 } 14678 14679 // Warn on types where the user might conceivably expect to get all 14680 // specified bits as value bits: that's all integral types other than 14681 // 'bool'. 14682 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14683 if (FieldName) 14684 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14685 << FieldName << (unsigned)Value.getZExtValue() 14686 << (unsigned)TypeWidth; 14687 else 14688 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14689 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14690 } 14691 } 14692 14693 return BitWidth; 14694 } 14695 14696 /// ActOnField - Each field of a C struct/union is passed into this in order 14697 /// to create a FieldDecl object for it. 14698 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14699 Declarator &D, Expr *BitfieldWidth) { 14700 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14701 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14702 /*InitStyle=*/ICIS_NoInit, AS_public); 14703 return Res; 14704 } 14705 14706 /// HandleField - Analyze a field of a C struct or a C++ data member. 14707 /// 14708 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14709 SourceLocation DeclStart, 14710 Declarator &D, Expr *BitWidth, 14711 InClassInitStyle InitStyle, 14712 AccessSpecifier AS) { 14713 if (D.isDecompositionDeclarator()) { 14714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14715 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14716 << Decomp.getSourceRange(); 14717 return nullptr; 14718 } 14719 14720 IdentifierInfo *II = D.getIdentifier(); 14721 SourceLocation Loc = DeclStart; 14722 if (II) Loc = D.getIdentifierLoc(); 14723 14724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14725 QualType T = TInfo->getType(); 14726 if (getLangOpts().CPlusPlus) { 14727 CheckExtraCXXDefaultArguments(D); 14728 14729 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14730 UPPC_DataMemberType)) { 14731 D.setInvalidType(); 14732 T = Context.IntTy; 14733 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14734 } 14735 } 14736 14737 // TR 18037 does not allow fields to be declared with address spaces. 14738 if (T.getQualifiers().hasAddressSpace() || 14739 T->isDependentAddressSpaceType() || 14740 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14741 Diag(Loc, diag::err_field_with_address_space); 14742 D.setInvalidType(); 14743 } 14744 14745 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14746 // used as structure or union field: image, sampler, event or block types. 14747 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14748 T->isSamplerT() || T->isBlockPointerType())) { 14749 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14750 D.setInvalidType(); 14751 } 14752 14753 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14754 14755 if (D.getDeclSpec().isInlineSpecified()) 14756 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14757 << getLangOpts().CPlusPlus17; 14758 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14759 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14760 diag::err_invalid_thread) 14761 << DeclSpec::getSpecifierName(TSCS); 14762 14763 // Check to see if this name was declared as a member previously 14764 NamedDecl *PrevDecl = nullptr; 14765 LookupResult Previous(*this, II, Loc, LookupMemberName, 14766 ForVisibleRedeclaration); 14767 LookupName(Previous, S); 14768 switch (Previous.getResultKind()) { 14769 case LookupResult::Found: 14770 case LookupResult::FoundUnresolvedValue: 14771 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14772 break; 14773 14774 case LookupResult::FoundOverloaded: 14775 PrevDecl = Previous.getRepresentativeDecl(); 14776 break; 14777 14778 case LookupResult::NotFound: 14779 case LookupResult::NotFoundInCurrentInstantiation: 14780 case LookupResult::Ambiguous: 14781 break; 14782 } 14783 Previous.suppressDiagnostics(); 14784 14785 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14786 // Maybe we will complain about the shadowed template parameter. 14787 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14788 // Just pretend that we didn't see the previous declaration. 14789 PrevDecl = nullptr; 14790 } 14791 14792 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14793 PrevDecl = nullptr; 14794 14795 bool Mutable 14796 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14797 SourceLocation TSSL = D.getLocStart(); 14798 FieldDecl *NewFD 14799 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14800 TSSL, AS, PrevDecl, &D); 14801 14802 if (NewFD->isInvalidDecl()) 14803 Record->setInvalidDecl(); 14804 14805 if (D.getDeclSpec().isModulePrivateSpecified()) 14806 NewFD->setModulePrivate(); 14807 14808 if (NewFD->isInvalidDecl() && PrevDecl) { 14809 // Don't introduce NewFD into scope; there's already something 14810 // with the same name in the same scope. 14811 } else if (II) { 14812 PushOnScopeChains(NewFD, S); 14813 } else 14814 Record->addDecl(NewFD); 14815 14816 return NewFD; 14817 } 14818 14819 /// \brief Build a new FieldDecl and check its well-formedness. 14820 /// 14821 /// This routine builds a new FieldDecl given the fields name, type, 14822 /// record, etc. \p PrevDecl should refer to any previous declaration 14823 /// with the same name and in the same scope as the field to be 14824 /// created. 14825 /// 14826 /// \returns a new FieldDecl. 14827 /// 14828 /// \todo The Declarator argument is a hack. It will be removed once 14829 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14830 TypeSourceInfo *TInfo, 14831 RecordDecl *Record, SourceLocation Loc, 14832 bool Mutable, Expr *BitWidth, 14833 InClassInitStyle InitStyle, 14834 SourceLocation TSSL, 14835 AccessSpecifier AS, NamedDecl *PrevDecl, 14836 Declarator *D) { 14837 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14838 bool InvalidDecl = false; 14839 if (D) InvalidDecl = D->isInvalidType(); 14840 14841 // If we receive a broken type, recover by assuming 'int' and 14842 // marking this declaration as invalid. 14843 if (T.isNull()) { 14844 InvalidDecl = true; 14845 T = Context.IntTy; 14846 } 14847 14848 QualType EltTy = Context.getBaseElementType(T); 14849 if (!EltTy->isDependentType()) { 14850 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14851 // Fields of incomplete type force their record to be invalid. 14852 Record->setInvalidDecl(); 14853 InvalidDecl = true; 14854 } else { 14855 NamedDecl *Def; 14856 EltTy->isIncompleteType(&Def); 14857 if (Def && Def->isInvalidDecl()) { 14858 Record->setInvalidDecl(); 14859 InvalidDecl = true; 14860 } 14861 } 14862 } 14863 14864 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14865 if (BitWidth && getLangOpts().OpenCL) { 14866 Diag(Loc, diag::err_opencl_bitfields); 14867 InvalidDecl = true; 14868 } 14869 14870 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14871 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14872 T.hasQualifiers()) { 14873 InvalidDecl = true; 14874 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14875 } 14876 14877 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14878 // than a variably modified type. 14879 if (!InvalidDecl && T->isVariablyModifiedType()) { 14880 bool SizeIsNegative; 14881 llvm::APSInt Oversized; 14882 14883 TypeSourceInfo *FixedTInfo = 14884 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14885 SizeIsNegative, 14886 Oversized); 14887 if (FixedTInfo) { 14888 Diag(Loc, diag::warn_illegal_constant_array_size); 14889 TInfo = FixedTInfo; 14890 T = FixedTInfo->getType(); 14891 } else { 14892 if (SizeIsNegative) 14893 Diag(Loc, diag::err_typecheck_negative_array_size); 14894 else if (Oversized.getBoolValue()) 14895 Diag(Loc, diag::err_array_too_large) 14896 << Oversized.toString(10); 14897 else 14898 Diag(Loc, diag::err_typecheck_field_variable_size); 14899 InvalidDecl = true; 14900 } 14901 } 14902 14903 // Fields can not have abstract class types 14904 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14905 diag::err_abstract_type_in_decl, 14906 AbstractFieldType)) 14907 InvalidDecl = true; 14908 14909 bool ZeroWidth = false; 14910 if (InvalidDecl) 14911 BitWidth = nullptr; 14912 // If this is declared as a bit-field, check the bit-field. 14913 if (BitWidth) { 14914 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14915 &ZeroWidth).get(); 14916 if (!BitWidth) { 14917 InvalidDecl = true; 14918 BitWidth = nullptr; 14919 ZeroWidth = false; 14920 } 14921 } 14922 14923 // Check that 'mutable' is consistent with the type of the declaration. 14924 if (!InvalidDecl && Mutable) { 14925 unsigned DiagID = 0; 14926 if (T->isReferenceType()) 14927 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14928 : diag::err_mutable_reference; 14929 else if (T.isConstQualified()) 14930 DiagID = diag::err_mutable_const; 14931 14932 if (DiagID) { 14933 SourceLocation ErrLoc = Loc; 14934 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14935 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14936 Diag(ErrLoc, DiagID); 14937 if (DiagID != diag::ext_mutable_reference) { 14938 Mutable = false; 14939 InvalidDecl = true; 14940 } 14941 } 14942 } 14943 14944 // C++11 [class.union]p8 (DR1460): 14945 // At most one variant member of a union may have a 14946 // brace-or-equal-initializer. 14947 if (InitStyle != ICIS_NoInit) 14948 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14949 14950 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14951 BitWidth, Mutable, InitStyle); 14952 if (InvalidDecl) 14953 NewFD->setInvalidDecl(); 14954 14955 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14956 Diag(Loc, diag::err_duplicate_member) << II; 14957 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14958 NewFD->setInvalidDecl(); 14959 } 14960 14961 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14962 if (Record->isUnion()) { 14963 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14964 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14965 if (RDecl->getDefinition()) { 14966 // C++ [class.union]p1: An object of a class with a non-trivial 14967 // constructor, a non-trivial copy constructor, a non-trivial 14968 // destructor, or a non-trivial copy assignment operator 14969 // cannot be a member of a union, nor can an array of such 14970 // objects. 14971 if (CheckNontrivialField(NewFD)) 14972 NewFD->setInvalidDecl(); 14973 } 14974 } 14975 14976 // C++ [class.union]p1: If a union contains a member of reference type, 14977 // the program is ill-formed, except when compiling with MSVC extensions 14978 // enabled. 14979 if (EltTy->isReferenceType()) { 14980 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14981 diag::ext_union_member_of_reference_type : 14982 diag::err_union_member_of_reference_type) 14983 << NewFD->getDeclName() << EltTy; 14984 if (!getLangOpts().MicrosoftExt) 14985 NewFD->setInvalidDecl(); 14986 } 14987 } 14988 } 14989 14990 // FIXME: We need to pass in the attributes given an AST 14991 // representation, not a parser representation. 14992 if (D) { 14993 // FIXME: The current scope is almost... but not entirely... correct here. 14994 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14995 14996 if (NewFD->hasAttrs()) 14997 CheckAlignasUnderalignment(NewFD); 14998 } 14999 15000 // In auto-retain/release, infer strong retension for fields of 15001 // retainable type. 15002 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15003 NewFD->setInvalidDecl(); 15004 15005 if (T.isObjCGCWeak()) 15006 Diag(Loc, diag::warn_attribute_weak_on_field); 15007 15008 NewFD->setAccess(AS); 15009 return NewFD; 15010 } 15011 15012 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15013 assert(FD); 15014 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15015 15016 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15017 return false; 15018 15019 QualType EltTy = Context.getBaseElementType(FD->getType()); 15020 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15021 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15022 if (RDecl->getDefinition()) { 15023 // We check for copy constructors before constructors 15024 // because otherwise we'll never get complaints about 15025 // copy constructors. 15026 15027 CXXSpecialMember member = CXXInvalid; 15028 // We're required to check for any non-trivial constructors. Since the 15029 // implicit default constructor is suppressed if there are any 15030 // user-declared constructors, we just need to check that there is a 15031 // trivial default constructor and a trivial copy constructor. (We don't 15032 // worry about move constructors here, since this is a C++98 check.) 15033 if (RDecl->hasNonTrivialCopyConstructor()) 15034 member = CXXCopyConstructor; 15035 else if (!RDecl->hasTrivialDefaultConstructor()) 15036 member = CXXDefaultConstructor; 15037 else if (RDecl->hasNonTrivialCopyAssignment()) 15038 member = CXXCopyAssignment; 15039 else if (RDecl->hasNonTrivialDestructor()) 15040 member = CXXDestructor; 15041 15042 if (member != CXXInvalid) { 15043 if (!getLangOpts().CPlusPlus11 && 15044 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15045 // Objective-C++ ARC: it is an error to have a non-trivial field of 15046 // a union. However, system headers in Objective-C programs 15047 // occasionally have Objective-C lifetime objects within unions, 15048 // and rather than cause the program to fail, we make those 15049 // members unavailable. 15050 SourceLocation Loc = FD->getLocation(); 15051 if (getSourceManager().isInSystemHeader(Loc)) { 15052 if (!FD->hasAttr<UnavailableAttr>()) 15053 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15054 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15055 return false; 15056 } 15057 } 15058 15059 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15060 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15061 diag::err_illegal_union_or_anon_struct_member) 15062 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15063 DiagnoseNontrivial(RDecl, member); 15064 return !getLangOpts().CPlusPlus11; 15065 } 15066 } 15067 } 15068 15069 return false; 15070 } 15071 15072 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15073 /// AST enum value. 15074 static ObjCIvarDecl::AccessControl 15075 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15076 switch (ivarVisibility) { 15077 default: llvm_unreachable("Unknown visitibility kind"); 15078 case tok::objc_private: return ObjCIvarDecl::Private; 15079 case tok::objc_public: return ObjCIvarDecl::Public; 15080 case tok::objc_protected: return ObjCIvarDecl::Protected; 15081 case tok::objc_package: return ObjCIvarDecl::Package; 15082 } 15083 } 15084 15085 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15086 /// in order to create an IvarDecl object for it. 15087 Decl *Sema::ActOnIvar(Scope *S, 15088 SourceLocation DeclStart, 15089 Declarator &D, Expr *BitfieldWidth, 15090 tok::ObjCKeywordKind Visibility) { 15091 15092 IdentifierInfo *II = D.getIdentifier(); 15093 Expr *BitWidth = (Expr*)BitfieldWidth; 15094 SourceLocation Loc = DeclStart; 15095 if (II) Loc = D.getIdentifierLoc(); 15096 15097 // FIXME: Unnamed fields can be handled in various different ways, for 15098 // example, unnamed unions inject all members into the struct namespace! 15099 15100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15101 QualType T = TInfo->getType(); 15102 15103 if (BitWidth) { 15104 // 6.7.2.1p3, 6.7.2.1p4 15105 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15106 if (!BitWidth) 15107 D.setInvalidType(); 15108 } else { 15109 // Not a bitfield. 15110 15111 // validate II. 15112 15113 } 15114 if (T->isReferenceType()) { 15115 Diag(Loc, diag::err_ivar_reference_type); 15116 D.setInvalidType(); 15117 } 15118 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15119 // than a variably modified type. 15120 else if (T->isVariablyModifiedType()) { 15121 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15122 D.setInvalidType(); 15123 } 15124 15125 // Get the visibility (access control) for this ivar. 15126 ObjCIvarDecl::AccessControl ac = 15127 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15128 : ObjCIvarDecl::None; 15129 // Must set ivar's DeclContext to its enclosing interface. 15130 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15131 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15132 return nullptr; 15133 ObjCContainerDecl *EnclosingContext; 15134 if (ObjCImplementationDecl *IMPDecl = 15135 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15136 if (LangOpts.ObjCRuntime.isFragile()) { 15137 // Case of ivar declared in an implementation. Context is that of its class. 15138 EnclosingContext = IMPDecl->getClassInterface(); 15139 assert(EnclosingContext && "Implementation has no class interface!"); 15140 } 15141 else 15142 EnclosingContext = EnclosingDecl; 15143 } else { 15144 if (ObjCCategoryDecl *CDecl = 15145 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15146 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15147 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15148 return nullptr; 15149 } 15150 } 15151 EnclosingContext = EnclosingDecl; 15152 } 15153 15154 // Construct the decl. 15155 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15156 DeclStart, Loc, II, T, 15157 TInfo, ac, (Expr *)BitfieldWidth); 15158 15159 if (II) { 15160 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15161 ForVisibleRedeclaration); 15162 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15163 && !isa<TagDecl>(PrevDecl)) { 15164 Diag(Loc, diag::err_duplicate_member) << II; 15165 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15166 NewID->setInvalidDecl(); 15167 } 15168 } 15169 15170 // Process attributes attached to the ivar. 15171 ProcessDeclAttributes(S, NewID, D); 15172 15173 if (D.isInvalidType()) 15174 NewID->setInvalidDecl(); 15175 15176 // In ARC, infer 'retaining' for ivars of retainable type. 15177 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15178 NewID->setInvalidDecl(); 15179 15180 if (D.getDeclSpec().isModulePrivateSpecified()) 15181 NewID->setModulePrivate(); 15182 15183 if (II) { 15184 // FIXME: When interfaces are DeclContexts, we'll need to add 15185 // these to the interface. 15186 S->AddDecl(NewID); 15187 IdResolver.AddDecl(NewID); 15188 } 15189 15190 if (LangOpts.ObjCRuntime.isNonFragile() && 15191 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15192 Diag(Loc, diag::warn_ivars_in_interface); 15193 15194 return NewID; 15195 } 15196 15197 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15198 /// class and class extensions. For every class \@interface and class 15199 /// extension \@interface, if the last ivar is a bitfield of any type, 15200 /// then add an implicit `char :0` ivar to the end of that interface. 15201 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15202 SmallVectorImpl<Decl *> &AllIvarDecls) { 15203 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15204 return; 15205 15206 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15207 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15208 15209 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15210 return; 15211 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15212 if (!ID) { 15213 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15214 if (!CD->IsClassExtension()) 15215 return; 15216 } 15217 // No need to add this to end of @implementation. 15218 else 15219 return; 15220 } 15221 // All conditions are met. Add a new bitfield to the tail end of ivars. 15222 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15223 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15224 15225 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15226 DeclLoc, DeclLoc, nullptr, 15227 Context.CharTy, 15228 Context.getTrivialTypeSourceInfo(Context.CharTy, 15229 DeclLoc), 15230 ObjCIvarDecl::Private, BW, 15231 true); 15232 AllIvarDecls.push_back(Ivar); 15233 } 15234 15235 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15236 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15237 SourceLocation RBrac, AttributeList *Attr) { 15238 assert(EnclosingDecl && "missing record or interface decl"); 15239 15240 // If this is an Objective-C @implementation or category and we have 15241 // new fields here we should reset the layout of the interface since 15242 // it will now change. 15243 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15244 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15245 switch (DC->getKind()) { 15246 default: break; 15247 case Decl::ObjCCategory: 15248 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15249 break; 15250 case Decl::ObjCImplementation: 15251 Context. 15252 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15253 break; 15254 } 15255 } 15256 15257 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15258 15259 // Start counting up the number of named members; make sure to include 15260 // members of anonymous structs and unions in the total. 15261 unsigned NumNamedMembers = 0; 15262 if (Record) { 15263 for (const auto *I : Record->decls()) { 15264 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15265 if (IFD->getDeclName()) 15266 ++NumNamedMembers; 15267 } 15268 } 15269 15270 // Verify that all the fields are okay. 15271 SmallVector<FieldDecl*, 32> RecFields; 15272 15273 bool ObjCFieldLifetimeErrReported = false; 15274 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15275 i != end; ++i) { 15276 FieldDecl *FD = cast<FieldDecl>(*i); 15277 15278 // Get the type for the field. 15279 const Type *FDTy = FD->getType().getTypePtr(); 15280 15281 if (!FD->isAnonymousStructOrUnion()) { 15282 // Remember all fields written by the user. 15283 RecFields.push_back(FD); 15284 } 15285 15286 // If the field is already invalid for some reason, don't emit more 15287 // diagnostics about it. 15288 if (FD->isInvalidDecl()) { 15289 EnclosingDecl->setInvalidDecl(); 15290 continue; 15291 } 15292 15293 // C99 6.7.2.1p2: 15294 // A structure or union shall not contain a member with 15295 // incomplete or function type (hence, a structure shall not 15296 // contain an instance of itself, but may contain a pointer to 15297 // an instance of itself), except that the last member of a 15298 // structure with more than one named member may have incomplete 15299 // array type; such a structure (and any union containing, 15300 // possibly recursively, a member that is such a structure) 15301 // shall not be a member of a structure or an element of an 15302 // array. 15303 bool IsLastField = (i + 1 == Fields.end()); 15304 if (FDTy->isFunctionType()) { 15305 // Field declared as a function. 15306 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15307 << FD->getDeclName(); 15308 FD->setInvalidDecl(); 15309 EnclosingDecl->setInvalidDecl(); 15310 continue; 15311 } else if (FDTy->isIncompleteArrayType() && 15312 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15313 if (Record) { 15314 // Flexible array member. 15315 // Microsoft and g++ is more permissive regarding flexible array. 15316 // It will accept flexible array in union and also 15317 // as the sole element of a struct/class. 15318 unsigned DiagID = 0; 15319 if (!Record->isUnion() && !IsLastField) { 15320 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15321 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15322 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15323 FD->setInvalidDecl(); 15324 EnclosingDecl->setInvalidDecl(); 15325 continue; 15326 } else if (Record->isUnion()) 15327 DiagID = getLangOpts().MicrosoftExt 15328 ? diag::ext_flexible_array_union_ms 15329 : getLangOpts().CPlusPlus 15330 ? diag::ext_flexible_array_union_gnu 15331 : diag::err_flexible_array_union; 15332 else if (NumNamedMembers < 1) 15333 DiagID = getLangOpts().MicrosoftExt 15334 ? diag::ext_flexible_array_empty_aggregate_ms 15335 : getLangOpts().CPlusPlus 15336 ? diag::ext_flexible_array_empty_aggregate_gnu 15337 : diag::err_flexible_array_empty_aggregate; 15338 15339 if (DiagID) 15340 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15341 << Record->getTagKind(); 15342 // While the layout of types that contain virtual bases is not specified 15343 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15344 // virtual bases after the derived members. This would make a flexible 15345 // array member declared at the end of an object not adjacent to the end 15346 // of the type. 15347 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15348 if (RD->getNumVBases() != 0) 15349 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15350 << FD->getDeclName() << Record->getTagKind(); 15351 if (!getLangOpts().C99) 15352 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15353 << FD->getDeclName() << Record->getTagKind(); 15354 15355 // If the element type has a non-trivial destructor, we would not 15356 // implicitly destroy the elements, so disallow it for now. 15357 // 15358 // FIXME: GCC allows this. We should probably either implicitly delete 15359 // the destructor of the containing class, or just allow this. 15360 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15361 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15362 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15363 << FD->getDeclName() << FD->getType(); 15364 FD->setInvalidDecl(); 15365 EnclosingDecl->setInvalidDecl(); 15366 continue; 15367 } 15368 // Okay, we have a legal flexible array member at the end of the struct. 15369 Record->setHasFlexibleArrayMember(true); 15370 } else { 15371 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15372 // unless they are followed by another ivar. That check is done 15373 // elsewhere, after synthesized ivars are known. 15374 } 15375 } else if (!FDTy->isDependentType() && 15376 RequireCompleteType(FD->getLocation(), FD->getType(), 15377 diag::err_field_incomplete)) { 15378 // Incomplete type 15379 FD->setInvalidDecl(); 15380 EnclosingDecl->setInvalidDecl(); 15381 continue; 15382 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15383 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15384 // A type which contains a flexible array member is considered to be a 15385 // flexible array member. 15386 Record->setHasFlexibleArrayMember(true); 15387 if (!Record->isUnion()) { 15388 // If this is a struct/class and this is not the last element, reject 15389 // it. Note that GCC supports variable sized arrays in the middle of 15390 // structures. 15391 if (!IsLastField) 15392 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15393 << FD->getDeclName() << FD->getType(); 15394 else { 15395 // We support flexible arrays at the end of structs in 15396 // other structs as an extension. 15397 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15398 << FD->getDeclName(); 15399 } 15400 } 15401 } 15402 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15403 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15404 diag::err_abstract_type_in_decl, 15405 AbstractIvarType)) { 15406 // Ivars can not have abstract class types 15407 FD->setInvalidDecl(); 15408 } 15409 if (Record && FDTTy->getDecl()->hasObjectMember()) 15410 Record->setHasObjectMember(true); 15411 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15412 Record->setHasVolatileMember(true); 15413 } else if (FDTy->isObjCObjectType()) { 15414 /// A field cannot be an Objective-c object 15415 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15416 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15417 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15418 FD->setType(T); 15419 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15420 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15421 // It's an error in ARC or Weak if a field has lifetime. 15422 // We don't want to report this in a system header, though, 15423 // so we just make the field unavailable. 15424 // FIXME: that's really not sufficient; we need to make the type 15425 // itself invalid to, say, initialize or copy. 15426 QualType T = FD->getType(); 15427 if (T.hasNonTrivialObjCLifetime()) { 15428 SourceLocation loc = FD->getLocation(); 15429 if (getSourceManager().isInSystemHeader(loc)) { 15430 if (!FD->hasAttr<UnavailableAttr>()) { 15431 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15432 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15433 } 15434 } else { 15435 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15436 << T->isBlockPointerType() << Record->getTagKind(); 15437 } 15438 ObjCFieldLifetimeErrReported = true; 15439 } 15440 } else if (getLangOpts().ObjC1 && 15441 getLangOpts().getGC() != LangOptions::NonGC && 15442 Record && !Record->hasObjectMember()) { 15443 if (FD->getType()->isObjCObjectPointerType() || 15444 FD->getType().isObjCGCStrong()) 15445 Record->setHasObjectMember(true); 15446 else if (Context.getAsArrayType(FD->getType())) { 15447 QualType BaseType = Context.getBaseElementType(FD->getType()); 15448 if (BaseType->isRecordType() && 15449 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15450 Record->setHasObjectMember(true); 15451 else if (BaseType->isObjCObjectPointerType() || 15452 BaseType.isObjCGCStrong()) 15453 Record->setHasObjectMember(true); 15454 } 15455 } 15456 15457 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15458 QualType FT = FD->getType(); 15459 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15460 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15461 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15462 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15463 Record->setNonTrivialToPrimitiveCopy(true); 15464 if (FT.isDestructedType()) { 15465 Record->setNonTrivialToPrimitiveDestroy(true); 15466 Record->setParamDestroyedInCallee(true); 15467 } 15468 15469 if (const auto *RT = FT->getAs<RecordType>()) { 15470 if (RT->getDecl()->getArgPassingRestrictions() == 15471 RecordDecl::APK_CanNeverPassInRegs) 15472 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15473 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15474 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15475 } 15476 15477 if (Record && FD->getType().isVolatileQualified()) 15478 Record->setHasVolatileMember(true); 15479 // Keep track of the number of named members. 15480 if (FD->getIdentifier()) 15481 ++NumNamedMembers; 15482 } 15483 15484 // Okay, we successfully defined 'Record'. 15485 if (Record) { 15486 bool Completed = false; 15487 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15488 if (!CXXRecord->isInvalidDecl()) { 15489 // Set access bits correctly on the directly-declared conversions. 15490 for (CXXRecordDecl::conversion_iterator 15491 I = CXXRecord->conversion_begin(), 15492 E = CXXRecord->conversion_end(); I != E; ++I) 15493 I.setAccess((*I)->getAccess()); 15494 } 15495 15496 if (!CXXRecord->isDependentType()) { 15497 if (CXXRecord->hasUserDeclaredDestructor()) { 15498 // Adjust user-defined destructor exception spec. 15499 if (getLangOpts().CPlusPlus11) 15500 AdjustDestructorExceptionSpec(CXXRecord, 15501 CXXRecord->getDestructor()); 15502 } 15503 15504 // Add any implicitly-declared members to this class. 15505 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15506 15507 if (!CXXRecord->isInvalidDecl()) { 15508 // If we have virtual base classes, we may end up finding multiple 15509 // final overriders for a given virtual function. Check for this 15510 // problem now. 15511 if (CXXRecord->getNumVBases()) { 15512 CXXFinalOverriderMap FinalOverriders; 15513 CXXRecord->getFinalOverriders(FinalOverriders); 15514 15515 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15516 MEnd = FinalOverriders.end(); 15517 M != MEnd; ++M) { 15518 for (OverridingMethods::iterator SO = M->second.begin(), 15519 SOEnd = M->second.end(); 15520 SO != SOEnd; ++SO) { 15521 assert(SO->second.size() > 0 && 15522 "Virtual function without overriding functions?"); 15523 if (SO->second.size() == 1) 15524 continue; 15525 15526 // C++ [class.virtual]p2: 15527 // In a derived class, if a virtual member function of a base 15528 // class subobject has more than one final overrider the 15529 // program is ill-formed. 15530 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15531 << (const NamedDecl *)M->first << Record; 15532 Diag(M->first->getLocation(), 15533 diag::note_overridden_virtual_function); 15534 for (OverridingMethods::overriding_iterator 15535 OM = SO->second.begin(), 15536 OMEnd = SO->second.end(); 15537 OM != OMEnd; ++OM) 15538 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15539 << (const NamedDecl *)M->first << OM->Method->getParent(); 15540 15541 Record->setInvalidDecl(); 15542 } 15543 } 15544 CXXRecord->completeDefinition(&FinalOverriders); 15545 Completed = true; 15546 } 15547 } 15548 } 15549 } 15550 15551 if (!Completed) 15552 Record->completeDefinition(); 15553 15554 // We may have deferred checking for a deleted destructor. Check now. 15555 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15556 auto *Dtor = CXXRecord->getDestructor(); 15557 if (Dtor && Dtor->isImplicit() && 15558 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15559 CXXRecord->setImplicitDestructorIsDeleted(); 15560 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15561 } 15562 } 15563 15564 if (Record->hasAttrs()) { 15565 CheckAlignasUnderalignment(Record); 15566 15567 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15568 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15569 IA->getRange(), IA->getBestCase(), 15570 IA->getSemanticSpelling()); 15571 } 15572 15573 // Check if the structure/union declaration is a type that can have zero 15574 // size in C. For C this is a language extension, for C++ it may cause 15575 // compatibility problems. 15576 bool CheckForZeroSize; 15577 if (!getLangOpts().CPlusPlus) { 15578 CheckForZeroSize = true; 15579 } else { 15580 // For C++ filter out types that cannot be referenced in C code. 15581 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15582 CheckForZeroSize = 15583 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15584 !CXXRecord->isDependentType() && 15585 CXXRecord->isCLike(); 15586 } 15587 if (CheckForZeroSize) { 15588 bool ZeroSize = true; 15589 bool IsEmpty = true; 15590 unsigned NonBitFields = 0; 15591 for (RecordDecl::field_iterator I = Record->field_begin(), 15592 E = Record->field_end(); 15593 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15594 IsEmpty = false; 15595 if (I->isUnnamedBitfield()) { 15596 if (!I->isZeroLengthBitField(Context)) 15597 ZeroSize = false; 15598 } else { 15599 ++NonBitFields; 15600 QualType FieldType = I->getType(); 15601 if (FieldType->isIncompleteType() || 15602 !Context.getTypeSizeInChars(FieldType).isZero()) 15603 ZeroSize = false; 15604 } 15605 } 15606 15607 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15608 // allowed in C++, but warn if its declaration is inside 15609 // extern "C" block. 15610 if (ZeroSize) { 15611 Diag(RecLoc, getLangOpts().CPlusPlus ? 15612 diag::warn_zero_size_struct_union_in_extern_c : 15613 diag::warn_zero_size_struct_union_compat) 15614 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15615 } 15616 15617 // Structs without named members are extension in C (C99 6.7.2.1p7), 15618 // but are accepted by GCC. 15619 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15620 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15621 diag::ext_no_named_members_in_struct_union) 15622 << Record->isUnion(); 15623 } 15624 } 15625 } else { 15626 ObjCIvarDecl **ClsFields = 15627 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15628 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15629 ID->setEndOfDefinitionLoc(RBrac); 15630 // Add ivar's to class's DeclContext. 15631 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15632 ClsFields[i]->setLexicalDeclContext(ID); 15633 ID->addDecl(ClsFields[i]); 15634 } 15635 // Must enforce the rule that ivars in the base classes may not be 15636 // duplicates. 15637 if (ID->getSuperClass()) 15638 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15639 } else if (ObjCImplementationDecl *IMPDecl = 15640 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15641 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15642 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15643 // Ivar declared in @implementation never belongs to the implementation. 15644 // Only it is in implementation's lexical context. 15645 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15646 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15647 IMPDecl->setIvarLBraceLoc(LBrac); 15648 IMPDecl->setIvarRBraceLoc(RBrac); 15649 } else if (ObjCCategoryDecl *CDecl = 15650 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15651 // case of ivars in class extension; all other cases have been 15652 // reported as errors elsewhere. 15653 // FIXME. Class extension does not have a LocEnd field. 15654 // CDecl->setLocEnd(RBrac); 15655 // Add ivar's to class extension's DeclContext. 15656 // Diagnose redeclaration of private ivars. 15657 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15658 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15659 if (IDecl) { 15660 if (const ObjCIvarDecl *ClsIvar = 15661 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15662 Diag(ClsFields[i]->getLocation(), 15663 diag::err_duplicate_ivar_declaration); 15664 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15665 continue; 15666 } 15667 for (const auto *Ext : IDecl->known_extensions()) { 15668 if (const ObjCIvarDecl *ClsExtIvar 15669 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15670 Diag(ClsFields[i]->getLocation(), 15671 diag::err_duplicate_ivar_declaration); 15672 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15673 continue; 15674 } 15675 } 15676 } 15677 ClsFields[i]->setLexicalDeclContext(CDecl); 15678 CDecl->addDecl(ClsFields[i]); 15679 } 15680 CDecl->setIvarLBraceLoc(LBrac); 15681 CDecl->setIvarRBraceLoc(RBrac); 15682 } 15683 } 15684 15685 if (Attr) 15686 ProcessDeclAttributeList(S, Record, Attr); 15687 } 15688 15689 /// \brief Determine whether the given integral value is representable within 15690 /// the given type T. 15691 static bool isRepresentableIntegerValue(ASTContext &Context, 15692 llvm::APSInt &Value, 15693 QualType T) { 15694 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15695 "Integral type required!"); 15696 unsigned BitWidth = Context.getIntWidth(T); 15697 15698 if (Value.isUnsigned() || Value.isNonNegative()) { 15699 if (T->isSignedIntegerOrEnumerationType()) 15700 --BitWidth; 15701 return Value.getActiveBits() <= BitWidth; 15702 } 15703 return Value.getMinSignedBits() <= BitWidth; 15704 } 15705 15706 // \brief Given an integral type, return the next larger integral type 15707 // (or a NULL type of no such type exists). 15708 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15709 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15710 // enum checking below. 15711 assert((T->isIntegralType(Context) || 15712 T->isEnumeralType()) && "Integral type required!"); 15713 const unsigned NumTypes = 4; 15714 QualType SignedIntegralTypes[NumTypes] = { 15715 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15716 }; 15717 QualType UnsignedIntegralTypes[NumTypes] = { 15718 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15719 Context.UnsignedLongLongTy 15720 }; 15721 15722 unsigned BitWidth = Context.getTypeSize(T); 15723 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15724 : UnsignedIntegralTypes; 15725 for (unsigned I = 0; I != NumTypes; ++I) 15726 if (Context.getTypeSize(Types[I]) > BitWidth) 15727 return Types[I]; 15728 15729 return QualType(); 15730 } 15731 15732 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15733 EnumConstantDecl *LastEnumConst, 15734 SourceLocation IdLoc, 15735 IdentifierInfo *Id, 15736 Expr *Val) { 15737 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15738 llvm::APSInt EnumVal(IntWidth); 15739 QualType EltTy; 15740 15741 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15742 Val = nullptr; 15743 15744 if (Val) 15745 Val = DefaultLvalueConversion(Val).get(); 15746 15747 if (Val) { 15748 if (Enum->isDependentType() || Val->isTypeDependent()) 15749 EltTy = Context.DependentTy; 15750 else { 15751 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15752 !getLangOpts().MSVCCompat) { 15753 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15754 // constant-expression in the enumerator-definition shall be a converted 15755 // constant expression of the underlying type. 15756 EltTy = Enum->getIntegerType(); 15757 ExprResult Converted = 15758 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15759 CCEK_Enumerator); 15760 if (Converted.isInvalid()) 15761 Val = nullptr; 15762 else 15763 Val = Converted.get(); 15764 } else if (!Val->isValueDependent() && 15765 !(Val = VerifyIntegerConstantExpression(Val, 15766 &EnumVal).get())) { 15767 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15768 } else { 15769 if (Enum->isComplete()) { 15770 EltTy = Enum->getIntegerType(); 15771 15772 // In Obj-C and Microsoft mode, require the enumeration value to be 15773 // representable in the underlying type of the enumeration. In C++11, 15774 // we perform a non-narrowing conversion as part of converted constant 15775 // expression checking. 15776 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15777 if (getLangOpts().MSVCCompat) { 15778 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15779 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15780 } else 15781 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15782 } else 15783 Val = ImpCastExprToType(Val, EltTy, 15784 EltTy->isBooleanType() ? 15785 CK_IntegralToBoolean : CK_IntegralCast) 15786 .get(); 15787 } else if (getLangOpts().CPlusPlus) { 15788 // C++11 [dcl.enum]p5: 15789 // If the underlying type is not fixed, the type of each enumerator 15790 // is the type of its initializing value: 15791 // - If an initializer is specified for an enumerator, the 15792 // initializing value has the same type as the expression. 15793 EltTy = Val->getType(); 15794 } else { 15795 // C99 6.7.2.2p2: 15796 // The expression that defines the value of an enumeration constant 15797 // shall be an integer constant expression that has a value 15798 // representable as an int. 15799 15800 // Complain if the value is not representable in an int. 15801 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15802 Diag(IdLoc, diag::ext_enum_value_not_int) 15803 << EnumVal.toString(10) << Val->getSourceRange() 15804 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15805 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15806 // Force the type of the expression to 'int'. 15807 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15808 } 15809 EltTy = Val->getType(); 15810 } 15811 } 15812 } 15813 } 15814 15815 if (!Val) { 15816 if (Enum->isDependentType()) 15817 EltTy = Context.DependentTy; 15818 else if (!LastEnumConst) { 15819 // C++0x [dcl.enum]p5: 15820 // If the underlying type is not fixed, the type of each enumerator 15821 // is the type of its initializing value: 15822 // - If no initializer is specified for the first enumerator, the 15823 // initializing value has an unspecified integral type. 15824 // 15825 // GCC uses 'int' for its unspecified integral type, as does 15826 // C99 6.7.2.2p3. 15827 if (Enum->isFixed()) { 15828 EltTy = Enum->getIntegerType(); 15829 } 15830 else { 15831 EltTy = Context.IntTy; 15832 } 15833 } else { 15834 // Assign the last value + 1. 15835 EnumVal = LastEnumConst->getInitVal(); 15836 ++EnumVal; 15837 EltTy = LastEnumConst->getType(); 15838 15839 // Check for overflow on increment. 15840 if (EnumVal < LastEnumConst->getInitVal()) { 15841 // C++0x [dcl.enum]p5: 15842 // If the underlying type is not fixed, the type of each enumerator 15843 // is the type of its initializing value: 15844 // 15845 // - Otherwise the type of the initializing value is the same as 15846 // the type of the initializing value of the preceding enumerator 15847 // unless the incremented value is not representable in that type, 15848 // in which case the type is an unspecified integral type 15849 // sufficient to contain the incremented value. If no such type 15850 // exists, the program is ill-formed. 15851 QualType T = getNextLargerIntegralType(Context, EltTy); 15852 if (T.isNull() || Enum->isFixed()) { 15853 // There is no integral type larger enough to represent this 15854 // value. Complain, then allow the value to wrap around. 15855 EnumVal = LastEnumConst->getInitVal(); 15856 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15857 ++EnumVal; 15858 if (Enum->isFixed()) 15859 // When the underlying type is fixed, this is ill-formed. 15860 Diag(IdLoc, diag::err_enumerator_wrapped) 15861 << EnumVal.toString(10) 15862 << EltTy; 15863 else 15864 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15865 << EnumVal.toString(10); 15866 } else { 15867 EltTy = T; 15868 } 15869 15870 // Retrieve the last enumerator's value, extent that type to the 15871 // type that is supposed to be large enough to represent the incremented 15872 // value, then increment. 15873 EnumVal = LastEnumConst->getInitVal(); 15874 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15875 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15876 ++EnumVal; 15877 15878 // If we're not in C++, diagnose the overflow of enumerator values, 15879 // which in C99 means that the enumerator value is not representable in 15880 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15881 // permits enumerator values that are representable in some larger 15882 // integral type. 15883 if (!getLangOpts().CPlusPlus && !T.isNull()) 15884 Diag(IdLoc, diag::warn_enum_value_overflow); 15885 } else if (!getLangOpts().CPlusPlus && 15886 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15887 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15888 Diag(IdLoc, diag::ext_enum_value_not_int) 15889 << EnumVal.toString(10) << 1; 15890 } 15891 } 15892 } 15893 15894 if (!EltTy->isDependentType()) { 15895 // Make the enumerator value match the signedness and size of the 15896 // enumerator's type. 15897 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15898 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15899 } 15900 15901 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15902 Val, EnumVal); 15903 } 15904 15905 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15906 SourceLocation IILoc) { 15907 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15908 !getLangOpts().CPlusPlus) 15909 return SkipBodyInfo(); 15910 15911 // We have an anonymous enum definition. Look up the first enumerator to 15912 // determine if we should merge the definition with an existing one and 15913 // skip the body. 15914 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15915 forRedeclarationInCurContext()); 15916 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15917 if (!PrevECD) 15918 return SkipBodyInfo(); 15919 15920 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15921 NamedDecl *Hidden; 15922 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15923 SkipBodyInfo Skip; 15924 Skip.Previous = Hidden; 15925 return Skip; 15926 } 15927 15928 return SkipBodyInfo(); 15929 } 15930 15931 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15932 SourceLocation IdLoc, IdentifierInfo *Id, 15933 AttributeList *Attr, 15934 SourceLocation EqualLoc, Expr *Val) { 15935 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15936 EnumConstantDecl *LastEnumConst = 15937 cast_or_null<EnumConstantDecl>(lastEnumConst); 15938 15939 // The scope passed in may not be a decl scope. Zip up the scope tree until 15940 // we find one that is. 15941 S = getNonFieldDeclScope(S); 15942 15943 // Verify that there isn't already something declared with this name in this 15944 // scope. 15945 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15946 ForVisibleRedeclaration); 15947 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15948 // Maybe we will complain about the shadowed template parameter. 15949 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15950 // Just pretend that we didn't see the previous declaration. 15951 PrevDecl = nullptr; 15952 } 15953 15954 // C++ [class.mem]p15: 15955 // If T is the name of a class, then each of the following shall have a name 15956 // different from T: 15957 // - every enumerator of every member of class T that is an unscoped 15958 // enumerated type 15959 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15960 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15961 DeclarationNameInfo(Id, IdLoc)); 15962 15963 EnumConstantDecl *New = 15964 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15965 if (!New) 15966 return nullptr; 15967 15968 if (PrevDecl) { 15969 // When in C++, we may get a TagDecl with the same name; in this case the 15970 // enum constant will 'hide' the tag. 15971 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15972 "Received TagDecl when not in C++!"); 15973 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 15974 if (isa<EnumConstantDecl>(PrevDecl)) 15975 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15976 else 15977 Diag(IdLoc, diag::err_redefinition) << Id; 15978 notePreviousDefinition(PrevDecl, IdLoc); 15979 return nullptr; 15980 } 15981 } 15982 15983 // Process attributes. 15984 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15985 AddPragmaAttributes(S, New); 15986 15987 // Register this decl in the current scope stack. 15988 New->setAccess(TheEnumDecl->getAccess()); 15989 PushOnScopeChains(New, S); 15990 15991 ActOnDocumentableDecl(New); 15992 15993 return New; 15994 } 15995 15996 // Returns true when the enum initial expression does not trigger the 15997 // duplicate enum warning. A few common cases are exempted as follows: 15998 // Element2 = Element1 15999 // Element2 = Element1 + 1 16000 // Element2 = Element1 - 1 16001 // Where Element2 and Element1 are from the same enum. 16002 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16003 Expr *InitExpr = ECD->getInitExpr(); 16004 if (!InitExpr) 16005 return true; 16006 InitExpr = InitExpr->IgnoreImpCasts(); 16007 16008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16009 if (!BO->isAdditiveOp()) 16010 return true; 16011 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16012 if (!IL) 16013 return true; 16014 if (IL->getValue() != 1) 16015 return true; 16016 16017 InitExpr = BO->getLHS(); 16018 } 16019 16020 // This checks if the elements are from the same enum. 16021 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16022 if (!DRE) 16023 return true; 16024 16025 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16026 if (!EnumConstant) 16027 return true; 16028 16029 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16030 Enum) 16031 return true; 16032 16033 return false; 16034 } 16035 16036 // Emits a warning when an element is implicitly set a value that 16037 // a previous element has already been set to. 16038 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16039 EnumDecl *Enum, QualType EnumType) { 16040 // Avoid anonymous enums 16041 if (!Enum->getIdentifier()) 16042 return; 16043 16044 // Only check for small enums. 16045 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16046 return; 16047 16048 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16049 return; 16050 16051 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16052 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16053 16054 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16055 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16056 16057 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16058 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16059 llvm::APSInt Val = D->getInitVal(); 16060 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16061 }; 16062 16063 DuplicatesVector DupVector; 16064 ValueToVectorMap EnumMap; 16065 16066 // Populate the EnumMap with all values represented by enum constants without 16067 // an initializer. 16068 for (auto *Element : Elements) { 16069 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16070 16071 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16072 // this constant. Skip this enum since it may be ill-formed. 16073 if (!ECD) { 16074 return; 16075 } 16076 16077 // Constants with initalizers are handled in the next loop. 16078 if (ECD->getInitExpr()) 16079 continue; 16080 16081 // Duplicate values are handled in the next loop. 16082 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16083 } 16084 16085 if (EnumMap.size() == 0) 16086 return; 16087 16088 // Create vectors for any values that has duplicates. 16089 for (auto *Element : Elements) { 16090 // The last loop returned if any constant was null. 16091 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16092 if (!ValidDuplicateEnum(ECD, Enum)) 16093 continue; 16094 16095 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16096 if (Iter == EnumMap.end()) 16097 continue; 16098 16099 DeclOrVector& Entry = Iter->second; 16100 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16101 // Ensure constants are different. 16102 if (D == ECD) 16103 continue; 16104 16105 // Create new vector and push values onto it. 16106 auto Vec = llvm::make_unique<ECDVector>(); 16107 Vec->push_back(D); 16108 Vec->push_back(ECD); 16109 16110 // Update entry to point to the duplicates vector. 16111 Entry = Vec.get(); 16112 16113 // Store the vector somewhere we can consult later for quick emission of 16114 // diagnostics. 16115 DupVector.emplace_back(std::move(Vec)); 16116 continue; 16117 } 16118 16119 ECDVector *Vec = Entry.get<ECDVector*>(); 16120 // Make sure constants are not added more than once. 16121 if (*Vec->begin() == ECD) 16122 continue; 16123 16124 Vec->push_back(ECD); 16125 } 16126 16127 // Emit diagnostics. 16128 for (const auto &Vec : DupVector) { 16129 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16130 16131 // Emit warning for one enum constant. 16132 auto *FirstECD = Vec->front(); 16133 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16134 << FirstECD << FirstECD->getInitVal().toString(10) 16135 << FirstECD->getSourceRange(); 16136 16137 // Emit one note for each of the remaining enum constants with 16138 // the same value. 16139 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16140 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16141 << ECD << ECD->getInitVal().toString(10) 16142 << ECD->getSourceRange(); 16143 } 16144 } 16145 16146 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16147 bool AllowMask) const { 16148 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16149 assert(ED->isCompleteDefinition() && "expected enum definition"); 16150 16151 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16152 llvm::APInt &FlagBits = R.first->second; 16153 16154 if (R.second) { 16155 for (auto *E : ED->enumerators()) { 16156 const auto &EVal = E->getInitVal(); 16157 // Only single-bit enumerators introduce new flag values. 16158 if (EVal.isPowerOf2()) 16159 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16160 } 16161 } 16162 16163 // A value is in a flag enum if either its bits are a subset of the enum's 16164 // flag bits (the first condition) or we are allowing masks and the same is 16165 // true of its complement (the second condition). When masks are allowed, we 16166 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16167 // 16168 // While it's true that any value could be used as a mask, the assumption is 16169 // that a mask will have all of the insignificant bits set. Anything else is 16170 // likely a logic error. 16171 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16172 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16173 } 16174 16175 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16176 Decl *EnumDeclX, 16177 ArrayRef<Decl *> Elements, 16178 Scope *S, AttributeList *Attr) { 16179 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16180 QualType EnumType = Context.getTypeDeclType(Enum); 16181 16182 if (Attr) 16183 ProcessDeclAttributeList(S, Enum, Attr); 16184 16185 if (Enum->isDependentType()) { 16186 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16187 EnumConstantDecl *ECD = 16188 cast_or_null<EnumConstantDecl>(Elements[i]); 16189 if (!ECD) continue; 16190 16191 ECD->setType(EnumType); 16192 } 16193 16194 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16195 return; 16196 } 16197 16198 // TODO: If the result value doesn't fit in an int, it must be a long or long 16199 // long value. ISO C does not support this, but GCC does as an extension, 16200 // emit a warning. 16201 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16202 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16203 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16204 16205 // Verify that all the values are okay, compute the size of the values, and 16206 // reverse the list. 16207 unsigned NumNegativeBits = 0; 16208 unsigned NumPositiveBits = 0; 16209 16210 // Keep track of whether all elements have type int. 16211 bool AllElementsInt = true; 16212 16213 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16214 EnumConstantDecl *ECD = 16215 cast_or_null<EnumConstantDecl>(Elements[i]); 16216 if (!ECD) continue; // Already issued a diagnostic. 16217 16218 const llvm::APSInt &InitVal = ECD->getInitVal(); 16219 16220 // Keep track of the size of positive and negative values. 16221 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16222 NumPositiveBits = std::max(NumPositiveBits, 16223 (unsigned)InitVal.getActiveBits()); 16224 else 16225 NumNegativeBits = std::max(NumNegativeBits, 16226 (unsigned)InitVal.getMinSignedBits()); 16227 16228 // Keep track of whether every enum element has type int (very commmon). 16229 if (AllElementsInt) 16230 AllElementsInt = ECD->getType() == Context.IntTy; 16231 } 16232 16233 // Figure out the type that should be used for this enum. 16234 QualType BestType; 16235 unsigned BestWidth; 16236 16237 // C++0x N3000 [conv.prom]p3: 16238 // An rvalue of an unscoped enumeration type whose underlying 16239 // type is not fixed can be converted to an rvalue of the first 16240 // of the following types that can represent all the values of 16241 // the enumeration: int, unsigned int, long int, unsigned long 16242 // int, long long int, or unsigned long long int. 16243 // C99 6.4.4.3p2: 16244 // An identifier declared as an enumeration constant has type int. 16245 // The C99 rule is modified by a gcc extension 16246 QualType BestPromotionType; 16247 16248 bool Packed = Enum->hasAttr<PackedAttr>(); 16249 // -fshort-enums is the equivalent to specifying the packed attribute on all 16250 // enum definitions. 16251 if (LangOpts.ShortEnums) 16252 Packed = true; 16253 16254 // If the enum already has a type because it is fixed or dictated by the 16255 // target, promote that type instead of analyzing the enumerators. 16256 if (Enum->isComplete()) { 16257 BestType = Enum->getIntegerType(); 16258 if (BestType->isPromotableIntegerType()) 16259 BestPromotionType = Context.getPromotedIntegerType(BestType); 16260 else 16261 BestPromotionType = BestType; 16262 16263 BestWidth = Context.getIntWidth(BestType); 16264 } 16265 else if (NumNegativeBits) { 16266 // If there is a negative value, figure out the smallest integer type (of 16267 // int/long/longlong) that fits. 16268 // If it's packed, check also if it fits a char or a short. 16269 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16270 BestType = Context.SignedCharTy; 16271 BestWidth = CharWidth; 16272 } else if (Packed && NumNegativeBits <= ShortWidth && 16273 NumPositiveBits < ShortWidth) { 16274 BestType = Context.ShortTy; 16275 BestWidth = ShortWidth; 16276 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16277 BestType = Context.IntTy; 16278 BestWidth = IntWidth; 16279 } else { 16280 BestWidth = Context.getTargetInfo().getLongWidth(); 16281 16282 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16283 BestType = Context.LongTy; 16284 } else { 16285 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16286 16287 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16288 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16289 BestType = Context.LongLongTy; 16290 } 16291 } 16292 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16293 } else { 16294 // If there is no negative value, figure out the smallest type that fits 16295 // all of the enumerator values. 16296 // If it's packed, check also if it fits a char or a short. 16297 if (Packed && NumPositiveBits <= CharWidth) { 16298 BestType = Context.UnsignedCharTy; 16299 BestPromotionType = Context.IntTy; 16300 BestWidth = CharWidth; 16301 } else if (Packed && NumPositiveBits <= ShortWidth) { 16302 BestType = Context.UnsignedShortTy; 16303 BestPromotionType = Context.IntTy; 16304 BestWidth = ShortWidth; 16305 } else if (NumPositiveBits <= IntWidth) { 16306 BestType = Context.UnsignedIntTy; 16307 BestWidth = IntWidth; 16308 BestPromotionType 16309 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16310 ? Context.UnsignedIntTy : Context.IntTy; 16311 } else if (NumPositiveBits <= 16312 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16313 BestType = Context.UnsignedLongTy; 16314 BestPromotionType 16315 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16316 ? Context.UnsignedLongTy : Context.LongTy; 16317 } else { 16318 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16319 assert(NumPositiveBits <= BestWidth && 16320 "How could an initializer get larger than ULL?"); 16321 BestType = Context.UnsignedLongLongTy; 16322 BestPromotionType 16323 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16324 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16325 } 16326 } 16327 16328 // Loop over all of the enumerator constants, changing their types to match 16329 // the type of the enum if needed. 16330 for (auto *D : Elements) { 16331 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16332 if (!ECD) continue; // Already issued a diagnostic. 16333 16334 // Standard C says the enumerators have int type, but we allow, as an 16335 // extension, the enumerators to be larger than int size. If each 16336 // enumerator value fits in an int, type it as an int, otherwise type it the 16337 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16338 // that X has type 'int', not 'unsigned'. 16339 16340 // Determine whether the value fits into an int. 16341 llvm::APSInt InitVal = ECD->getInitVal(); 16342 16343 // If it fits into an integer type, force it. Otherwise force it to match 16344 // the enum decl type. 16345 QualType NewTy; 16346 unsigned NewWidth; 16347 bool NewSign; 16348 if (!getLangOpts().CPlusPlus && 16349 !Enum->isFixed() && 16350 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16351 NewTy = Context.IntTy; 16352 NewWidth = IntWidth; 16353 NewSign = true; 16354 } else if (ECD->getType() == BestType) { 16355 // Already the right type! 16356 if (getLangOpts().CPlusPlus) 16357 // C++ [dcl.enum]p4: Following the closing brace of an 16358 // enum-specifier, each enumerator has the type of its 16359 // enumeration. 16360 ECD->setType(EnumType); 16361 continue; 16362 } else { 16363 NewTy = BestType; 16364 NewWidth = BestWidth; 16365 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16366 } 16367 16368 // Adjust the APSInt value. 16369 InitVal = InitVal.extOrTrunc(NewWidth); 16370 InitVal.setIsSigned(NewSign); 16371 ECD->setInitVal(InitVal); 16372 16373 // Adjust the Expr initializer and type. 16374 if (ECD->getInitExpr() && 16375 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16376 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16377 CK_IntegralCast, 16378 ECD->getInitExpr(), 16379 /*base paths*/ nullptr, 16380 VK_RValue)); 16381 if (getLangOpts().CPlusPlus) 16382 // C++ [dcl.enum]p4: Following the closing brace of an 16383 // enum-specifier, each enumerator has the type of its 16384 // enumeration. 16385 ECD->setType(EnumType); 16386 else 16387 ECD->setType(NewTy); 16388 } 16389 16390 Enum->completeDefinition(BestType, BestPromotionType, 16391 NumPositiveBits, NumNegativeBits); 16392 16393 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16394 16395 if (Enum->isClosedFlag()) { 16396 for (Decl *D : Elements) { 16397 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16398 if (!ECD) continue; // Already issued a diagnostic. 16399 16400 llvm::APSInt InitVal = ECD->getInitVal(); 16401 if (InitVal != 0 && !InitVal.isPowerOf2() && 16402 !IsValueInFlagEnum(Enum, InitVal, true)) 16403 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16404 << ECD << Enum; 16405 } 16406 } 16407 16408 // Now that the enum type is defined, ensure it's not been underaligned. 16409 if (Enum->hasAttrs()) 16410 CheckAlignasUnderalignment(Enum); 16411 } 16412 16413 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16414 SourceLocation StartLoc, 16415 SourceLocation EndLoc) { 16416 StringLiteral *AsmString = cast<StringLiteral>(expr); 16417 16418 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16419 AsmString, StartLoc, 16420 EndLoc); 16421 CurContext->addDecl(New); 16422 return New; 16423 } 16424 16425 static void checkModuleImportContext(Sema &S, Module *M, 16426 SourceLocation ImportLoc, DeclContext *DC, 16427 bool FromInclude = false) { 16428 SourceLocation ExternCLoc; 16429 16430 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16431 switch (LSD->getLanguage()) { 16432 case LinkageSpecDecl::lang_c: 16433 if (ExternCLoc.isInvalid()) 16434 ExternCLoc = LSD->getLocStart(); 16435 break; 16436 case LinkageSpecDecl::lang_cxx: 16437 break; 16438 } 16439 DC = LSD->getParent(); 16440 } 16441 16442 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16443 DC = DC->getParent(); 16444 16445 if (!isa<TranslationUnitDecl>(DC)) { 16446 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16447 ? diag::ext_module_import_not_at_top_level_noop 16448 : diag::err_module_import_not_at_top_level_fatal) 16449 << M->getFullModuleName() << DC; 16450 S.Diag(cast<Decl>(DC)->getLocStart(), 16451 diag::note_module_import_not_at_top_level) << DC; 16452 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16453 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16454 << M->getFullModuleName(); 16455 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16456 } 16457 } 16458 16459 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16460 SourceLocation ModuleLoc, 16461 ModuleDeclKind MDK, 16462 ModuleIdPath Path) { 16463 assert(getLangOpts().ModulesTS && 16464 "should only have module decl in modules TS"); 16465 16466 // A module implementation unit requires that we are not compiling a module 16467 // of any kind. A module interface unit requires that we are not compiling a 16468 // module map. 16469 switch (getLangOpts().getCompilingModule()) { 16470 case LangOptions::CMK_None: 16471 // It's OK to compile a module interface as a normal translation unit. 16472 break; 16473 16474 case LangOptions::CMK_ModuleInterface: 16475 if (MDK != ModuleDeclKind::Implementation) 16476 break; 16477 16478 // We were asked to compile a module interface unit but this is a module 16479 // implementation unit. That indicates the 'export' is missing. 16480 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16481 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16482 MDK = ModuleDeclKind::Interface; 16483 break; 16484 16485 case LangOptions::CMK_ModuleMap: 16486 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16487 return nullptr; 16488 } 16489 16490 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16491 16492 // FIXME: Most of this work should be done by the preprocessor rather than 16493 // here, in order to support macro import. 16494 16495 // Only one module-declaration is permitted per source file. 16496 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16497 Diag(ModuleLoc, diag::err_module_redeclaration); 16498 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16499 diag::note_prev_module_declaration); 16500 return nullptr; 16501 } 16502 16503 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16504 // modules, the dots here are just another character that can appear in a 16505 // module name. 16506 std::string ModuleName; 16507 for (auto &Piece : Path) { 16508 if (!ModuleName.empty()) 16509 ModuleName += "."; 16510 ModuleName += Piece.first->getName(); 16511 } 16512 16513 // If a module name was explicitly specified on the command line, it must be 16514 // correct. 16515 if (!getLangOpts().CurrentModule.empty() && 16516 getLangOpts().CurrentModule != ModuleName) { 16517 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16518 << SourceRange(Path.front().second, Path.back().second) 16519 << getLangOpts().CurrentModule; 16520 return nullptr; 16521 } 16522 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16523 16524 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16525 Module *Mod; 16526 16527 switch (MDK) { 16528 case ModuleDeclKind::Interface: { 16529 // We can't have parsed or imported a definition of this module or parsed a 16530 // module map defining it already. 16531 if (auto *M = Map.findModule(ModuleName)) { 16532 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16533 if (M->DefinitionLoc.isValid()) 16534 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16535 else if (const auto *FE = M->getASTFile()) 16536 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16537 << FE->getName(); 16538 Mod = M; 16539 break; 16540 } 16541 16542 // Create a Module for the module that we're defining. 16543 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16544 ModuleScopes.front().Module); 16545 assert(Mod && "module creation should not fail"); 16546 break; 16547 } 16548 16549 case ModuleDeclKind::Partition: 16550 // FIXME: Check we are in a submodule of the named module. 16551 return nullptr; 16552 16553 case ModuleDeclKind::Implementation: 16554 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16555 PP.getIdentifierInfo(ModuleName), Path[0].second); 16556 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16557 /*IsIncludeDirective=*/false); 16558 if (!Mod) { 16559 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16560 // Create an empty module interface unit for error recovery. 16561 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16562 ModuleScopes.front().Module); 16563 } 16564 break; 16565 } 16566 16567 // Switch from the global module to the named module. 16568 ModuleScopes.back().Module = Mod; 16569 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16570 VisibleModules.setVisible(Mod, ModuleLoc); 16571 16572 // From now on, we have an owning module for all declarations we see. 16573 // However, those declarations are module-private unless explicitly 16574 // exported. 16575 auto *TU = Context.getTranslationUnitDecl(); 16576 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16577 TU->setLocalOwningModule(Mod); 16578 16579 // FIXME: Create a ModuleDecl. 16580 return nullptr; 16581 } 16582 16583 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16584 SourceLocation ImportLoc, 16585 ModuleIdPath Path) { 16586 Module *Mod = 16587 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16588 /*IsIncludeDirective=*/false); 16589 if (!Mod) 16590 return true; 16591 16592 VisibleModules.setVisible(Mod, ImportLoc); 16593 16594 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16595 16596 // FIXME: we should support importing a submodule within a different submodule 16597 // of the same top-level module. Until we do, make it an error rather than 16598 // silently ignoring the import. 16599 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16600 // warn on a redundant import of the current module? 16601 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16602 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16603 Diag(ImportLoc, getLangOpts().isCompilingModule() 16604 ? diag::err_module_self_import 16605 : diag::err_module_import_in_implementation) 16606 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16607 16608 SmallVector<SourceLocation, 2> IdentifierLocs; 16609 Module *ModCheck = Mod; 16610 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16611 // If we've run out of module parents, just drop the remaining identifiers. 16612 // We need the length to be consistent. 16613 if (!ModCheck) 16614 break; 16615 ModCheck = ModCheck->Parent; 16616 16617 IdentifierLocs.push_back(Path[I].second); 16618 } 16619 16620 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16621 Mod, IdentifierLocs); 16622 if (!ModuleScopes.empty()) 16623 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16624 CurContext->addDecl(Import); 16625 16626 // Re-export the module if needed. 16627 if (Import->isExported() && 16628 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16629 getCurrentModule()->Exports.emplace_back(Mod, false); 16630 16631 return Import; 16632 } 16633 16634 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16635 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16636 BuildModuleInclude(DirectiveLoc, Mod); 16637 } 16638 16639 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16640 // Determine whether we're in the #include buffer for a module. The #includes 16641 // in that buffer do not qualify as module imports; they're just an 16642 // implementation detail of us building the module. 16643 // 16644 // FIXME: Should we even get ActOnModuleInclude calls for those? 16645 bool IsInModuleIncludes = 16646 TUKind == TU_Module && 16647 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16648 16649 bool ShouldAddImport = !IsInModuleIncludes; 16650 16651 // If this module import was due to an inclusion directive, create an 16652 // implicit import declaration to capture it in the AST. 16653 if (ShouldAddImport) { 16654 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16655 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16656 DirectiveLoc, Mod, 16657 DirectiveLoc); 16658 if (!ModuleScopes.empty()) 16659 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16660 TU->addDecl(ImportD); 16661 Consumer.HandleImplicitImportDecl(ImportD); 16662 } 16663 16664 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16665 VisibleModules.setVisible(Mod, DirectiveLoc); 16666 } 16667 16668 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16669 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16670 16671 ModuleScopes.push_back({}); 16672 ModuleScopes.back().Module = Mod; 16673 if (getLangOpts().ModulesLocalVisibility) 16674 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16675 16676 VisibleModules.setVisible(Mod, DirectiveLoc); 16677 16678 // The enclosing context is now part of this module. 16679 // FIXME: Consider creating a child DeclContext to hold the entities 16680 // lexically within the module. 16681 if (getLangOpts().trackLocalOwningModule()) { 16682 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16683 cast<Decl>(DC)->setModuleOwnershipKind( 16684 getLangOpts().ModulesLocalVisibility 16685 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16686 : Decl::ModuleOwnershipKind::Visible); 16687 cast<Decl>(DC)->setLocalOwningModule(Mod); 16688 } 16689 } 16690 } 16691 16692 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16693 if (getLangOpts().ModulesLocalVisibility) { 16694 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16695 // Leaving a module hides namespace names, so our visible namespace cache 16696 // is now out of date. 16697 VisibleNamespaceCache.clear(); 16698 } 16699 16700 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16701 "left the wrong module scope"); 16702 ModuleScopes.pop_back(); 16703 16704 // We got to the end of processing a local module. Create an 16705 // ImportDecl as we would for an imported module. 16706 FileID File = getSourceManager().getFileID(EomLoc); 16707 SourceLocation DirectiveLoc; 16708 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16709 // We reached the end of a #included module header. Use the #include loc. 16710 assert(File != getSourceManager().getMainFileID() && 16711 "end of submodule in main source file"); 16712 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16713 } else { 16714 // We reached an EOM pragma. Use the pragma location. 16715 DirectiveLoc = EomLoc; 16716 } 16717 BuildModuleInclude(DirectiveLoc, Mod); 16718 16719 // Any further declarations are in whatever module we returned to. 16720 if (getLangOpts().trackLocalOwningModule()) { 16721 // The parser guarantees that this is the same context that we entered 16722 // the module within. 16723 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16724 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16725 if (!getCurrentModule()) 16726 cast<Decl>(DC)->setModuleOwnershipKind( 16727 Decl::ModuleOwnershipKind::Unowned); 16728 } 16729 } 16730 } 16731 16732 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16733 Module *Mod) { 16734 // Bail if we're not allowed to implicitly import a module here. 16735 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16736 VisibleModules.isVisible(Mod)) 16737 return; 16738 16739 // Create the implicit import declaration. 16740 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16741 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16742 Loc, Mod, Loc); 16743 TU->addDecl(ImportD); 16744 Consumer.HandleImplicitImportDecl(ImportD); 16745 16746 // Make the module visible. 16747 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16748 VisibleModules.setVisible(Mod, Loc); 16749 } 16750 16751 /// We have parsed the start of an export declaration, including the '{' 16752 /// (if present). 16753 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16754 SourceLocation LBraceLoc) { 16755 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16756 16757 // C++ Modules TS draft: 16758 // An export-declaration shall appear in the purview of a module other than 16759 // the global module. 16760 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16761 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16762 16763 // An export-declaration [...] shall not contain more than one 16764 // export keyword. 16765 // 16766 // The intent here is that an export-declaration cannot appear within another 16767 // export-declaration. 16768 if (D->isExported()) 16769 Diag(ExportLoc, diag::err_export_within_export); 16770 16771 CurContext->addDecl(D); 16772 PushDeclContext(S, D); 16773 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16774 return D; 16775 } 16776 16777 /// Complete the definition of an export declaration. 16778 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16779 auto *ED = cast<ExportDecl>(D); 16780 if (RBraceLoc.isValid()) 16781 ED->setRBraceLoc(RBraceLoc); 16782 16783 // FIXME: Diagnose export of internal-linkage declaration (including 16784 // anonymous namespace). 16785 16786 PopDeclContext(); 16787 return D; 16788 } 16789 16790 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16791 IdentifierInfo* AliasName, 16792 SourceLocation PragmaLoc, 16793 SourceLocation NameLoc, 16794 SourceLocation AliasNameLoc) { 16795 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16796 LookupOrdinaryName); 16797 AsmLabelAttr *Attr = 16798 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16799 16800 // If a declaration that: 16801 // 1) declares a function or a variable 16802 // 2) has external linkage 16803 // already exists, add a label attribute to it. 16804 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16805 if (isDeclExternC(PrevDecl)) 16806 PrevDecl->addAttr(Attr); 16807 else 16808 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16809 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16810 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16811 } else 16812 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16813 } 16814 16815 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16816 SourceLocation PragmaLoc, 16817 SourceLocation NameLoc) { 16818 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16819 16820 if (PrevDecl) { 16821 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16822 } else { 16823 (void)WeakUndeclaredIdentifiers.insert( 16824 std::pair<IdentifierInfo*,WeakInfo> 16825 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16826 } 16827 } 16828 16829 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16830 IdentifierInfo* AliasName, 16831 SourceLocation PragmaLoc, 16832 SourceLocation NameLoc, 16833 SourceLocation AliasNameLoc) { 16834 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16835 LookupOrdinaryName); 16836 WeakInfo W = WeakInfo(Name, NameLoc); 16837 16838 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16839 if (!PrevDecl->hasAttr<AliasAttr>()) 16840 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16841 DeclApplyPragmaWeak(TUScope, ND, W); 16842 } else { 16843 (void)WeakUndeclaredIdentifiers.insert( 16844 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16845 } 16846 } 16847 16848 Decl *Sema::getObjCDeclContext() const { 16849 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16850 } 16851