1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw___float128: 136 case tok::kw_wchar_t: 137 case tok::kw_bool: 138 case tok::kw___underlying_type: 139 case tok::kw___auto_type: 140 return true; 141 142 case tok::annot_typename: 143 case tok::kw_char16_t: 144 case tok::kw_char32_t: 145 case tok::kw_typeof: 146 case tok::annot_decltype: 147 case tok::kw_decltype: 148 return getLangOpts().CPlusPlus; 149 150 default: 151 break; 152 } 153 154 return false; 155 } 156 157 namespace { 158 enum class UnqualifiedTypeNameLookupResult { 159 NotFound, 160 FoundNonType, 161 FoundType 162 }; 163 } // end anonymous namespace 164 165 /// \brief Tries to perform unqualified lookup of the type decls in bases for 166 /// dependent class. 167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 168 /// type decl, \a FoundType if only type decls are found. 169 static UnqualifiedTypeNameLookupResult 170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 171 SourceLocation NameLoc, 172 const CXXRecordDecl *RD) { 173 if (!RD->hasDefinition()) 174 return UnqualifiedTypeNameLookupResult::NotFound; 175 // Look for type decls in base classes. 176 UnqualifiedTypeNameLookupResult FoundTypeDecl = 177 UnqualifiedTypeNameLookupResult::NotFound; 178 for (const auto &Base : RD->bases()) { 179 const CXXRecordDecl *BaseRD = nullptr; 180 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 181 BaseRD = BaseTT->getAsCXXRecordDecl(); 182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 183 // Look for type decls in dependent base classes that have known primary 184 // templates. 185 if (!TST || !TST->isDependentType()) 186 continue; 187 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 188 if (!TD) 189 continue; 190 if (auto *BasePrimaryTemplate = 191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 193 BaseRD = BasePrimaryTemplate; 194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 195 if (const ClassTemplatePartialSpecializationDecl *PS = 196 CTD->findPartialSpecialization(Base.getType())) 197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 198 BaseRD = PS; 199 } 200 } 201 } 202 if (BaseRD) { 203 for (NamedDecl *ND : BaseRD->lookup(&II)) { 204 if (!isa<TypeDecl>(ND)) 205 return UnqualifiedTypeNameLookupResult::FoundNonType; 206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 207 } 208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 210 case UnqualifiedTypeNameLookupResult::FoundNonType: 211 return UnqualifiedTypeNameLookupResult::FoundNonType; 212 case UnqualifiedTypeNameLookupResult::FoundType: 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 break; 215 case UnqualifiedTypeNameLookupResult::NotFound: 216 break; 217 } 218 } 219 } 220 } 221 222 return FoundTypeDecl; 223 } 224 225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 226 const IdentifierInfo &II, 227 SourceLocation NameLoc) { 228 // Lookup in the parent class template context, if any. 229 const CXXRecordDecl *RD = nullptr; 230 UnqualifiedTypeNameLookupResult FoundTypeDecl = 231 UnqualifiedTypeNameLookupResult::NotFound; 232 for (DeclContext *DC = S.CurContext; 233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 234 DC = DC->getParent()) { 235 // Look for type decls in dependent base classes that have known primary 236 // templates. 237 RD = dyn_cast<CXXRecordDecl>(DC); 238 if (RD && RD->getDescribedClassTemplate()) 239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 240 } 241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 242 return nullptr; 243 244 // We found some types in dependent base classes. Recover as if the user 245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 246 // lookup during template instantiation. 247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 248 249 ASTContext &Context = S.Context; 250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 251 cast<Type>(Context.getRecordType(RD))); 252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 253 254 CXXScopeSpec SS; 255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 256 257 TypeLocBuilder Builder; 258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 259 DepTL.setNameLoc(NameLoc); 260 DepTL.setElaboratedKeywordLoc(SourceLocation()); 261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263 } 264 265 /// \brief If the identifier refers to a type name within this scope, 266 /// return the declaration of that type. 267 /// 268 /// This routine performs ordinary name lookup of the identifier II 269 /// within the given scope, with optional C++ scope specifier SS, to 270 /// determine whether the name refers to a type. If so, returns an 271 /// opaque pointer (actually a QualType) corresponding to that 272 /// type. Otherwise, returns NULL. 273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 274 Scope *S, CXXScopeSpec *SS, 275 bool isClassName, bool HasTrailingDot, 276 ParsedType ObjectTypePtr, 277 bool IsCtorOrDtorName, 278 bool WantNontrivialTypeSourceInfo, 279 bool IsClassTemplateDeductionContext, 280 IdentifierInfo **CorrectedII) { 281 // FIXME: Consider allowing this outside C++1z mode as an extension. 282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 284 !isClassName && !HasTrailingDot; 285 286 // Determine where we will perform name lookup. 287 DeclContext *LookupCtx = nullptr; 288 if (ObjectTypePtr) { 289 QualType ObjectType = ObjectTypePtr.get(); 290 if (ObjectType->isRecordType()) 291 LookupCtx = computeDeclContext(ObjectType); 292 } else if (SS && SS->isNotEmpty()) { 293 LookupCtx = computeDeclContext(*SS, false); 294 295 if (!LookupCtx) { 296 if (isDependentScopeSpecifier(*SS)) { 297 // C++ [temp.res]p3: 298 // A qualified-id that refers to a type and in which the 299 // nested-name-specifier depends on a template-parameter (14.6.2) 300 // shall be prefixed by the keyword typename to indicate that the 301 // qualified-id denotes a type, forming an 302 // elaborated-type-specifier (7.1.5.3). 303 // 304 // We therefore do not perform any name lookup if the result would 305 // refer to a member of an unknown specialization. 306 if (!isClassName && !IsCtorOrDtorName) 307 return nullptr; 308 309 // We know from the grammar that this name refers to a type, 310 // so build a dependent node to describe the type. 311 if (WantNontrivialTypeSourceInfo) 312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 313 314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 316 II, NameLoc); 317 return ParsedType::make(T); 318 } 319 320 return nullptr; 321 } 322 323 if (!LookupCtx->isDependentContext() && 324 RequireCompleteDeclContext(*SS, LookupCtx)) 325 return nullptr; 326 } 327 328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 329 // lookup for class-names. 330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 331 LookupOrdinaryName; 332 LookupResult Result(*this, &II, NameLoc, Kind); 333 if (LookupCtx) { 334 // Perform "qualified" name lookup into the declaration context we 335 // computed, which is either the type of the base of a member access 336 // expression or the declaration context associated with a prior 337 // nested-name-specifier. 338 LookupQualifiedName(Result, LookupCtx); 339 340 if (ObjectTypePtr && Result.empty()) { 341 // C++ [basic.lookup.classref]p3: 342 // If the unqualified-id is ~type-name, the type-name is looked up 343 // in the context of the entire postfix-expression. If the type T of 344 // the object expression is of a class type C, the type-name is also 345 // looked up in the scope of class C. At least one of the lookups shall 346 // find a name that refers to (possibly cv-qualified) T. 347 LookupName(Result, S); 348 } 349 } else { 350 // Perform unqualified name lookup. 351 LookupName(Result, S); 352 353 // For unqualified lookup in a class template in MSVC mode, look into 354 // dependent base classes where the primary class template is known. 355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 356 if (ParsedType TypeInBase = 357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 358 return TypeInBase; 359 } 360 } 361 362 NamedDecl *IIDecl = nullptr; 363 switch (Result.getResultKind()) { 364 case LookupResult::NotFound: 365 case LookupResult::NotFoundInCurrentInstantiation: 366 if (CorrectedII) { 367 TypoCorrection Correction = 368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 369 llvm::make_unique<TypeNameValidatorCCC>( 370 true, isClassName, AllowDeducedTemplate), 371 CTK_ErrorRecovery); 372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 373 TemplateTy Template; 374 bool MemberOfUnknownSpecialization; 375 UnqualifiedId TemplateName; 376 TemplateName.setIdentifier(NewII, NameLoc); 377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 378 CXXScopeSpec NewSS, *NewSSPtr = SS; 379 if (SS && NNS) { 380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 381 NewSSPtr = &NewSS; 382 } 383 if (Correction && (NNS || NewII != &II) && 384 // Ignore a correction to a template type as the to-be-corrected 385 // identifier is not a template (typo correction for template names 386 // is handled elsewhere). 387 !(getLangOpts().CPlusPlus && NewSSPtr && 388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 389 Template, MemberOfUnknownSpecialization))) { 390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 391 isClassName, HasTrailingDot, ObjectTypePtr, 392 IsCtorOrDtorName, 393 WantNontrivialTypeSourceInfo, 394 IsClassTemplateDeductionContext); 395 if (Ty) { 396 diagnoseTypo(Correction, 397 PDiag(diag::err_unknown_type_or_class_name_suggest) 398 << Result.getLookupName() << isClassName); 399 if (SS && NNS) 400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 401 *CorrectedII = NewII; 402 return Ty; 403 } 404 } 405 } 406 // If typo correction failed or was not performed, fall through 407 LLVM_FALLTHROUGH; 408 case LookupResult::FoundOverloaded: 409 case LookupResult::FoundUnresolvedValue: 410 Result.suppressDiagnostics(); 411 return nullptr; 412 413 case LookupResult::Ambiguous: 414 // Recover from type-hiding ambiguities by hiding the type. We'll 415 // do the lookup again when looking for an object, and we can 416 // diagnose the error then. If we don't do this, then the error 417 // about hiding the type will be immediately followed by an error 418 // that only makes sense if the identifier was treated like a type. 419 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 420 Result.suppressDiagnostics(); 421 return nullptr; 422 } 423 424 // Look to see if we have a type anywhere in the list of results. 425 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 426 Res != ResEnd; ++Res) { 427 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 428 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 429 if (!IIDecl || 430 (*Res)->getLocation().getRawEncoding() < 431 IIDecl->getLocation().getRawEncoding()) 432 IIDecl = *Res; 433 } 434 } 435 436 if (!IIDecl) { 437 // None of the entities we found is a type, so there is no way 438 // to even assume that the result is a type. In this case, don't 439 // complain about the ambiguity. The parser will either try to 440 // perform this lookup again (e.g., as an object name), which 441 // will produce the ambiguity, or will complain that it expected 442 // a type name. 443 Result.suppressDiagnostics(); 444 return nullptr; 445 } 446 447 // We found a type within the ambiguous lookup; diagnose the 448 // ambiguity and then return that type. This might be the right 449 // answer, or it might not be, but it suppresses any attempt to 450 // perform the name lookup again. 451 break; 452 453 case LookupResult::Found: 454 IIDecl = Result.getFoundDecl(); 455 break; 456 } 457 458 assert(IIDecl && "Didn't find decl"); 459 460 QualType T; 461 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 462 // C++ [class.qual]p2: A lookup that would find the injected-class-name 463 // instead names the constructors of the class, except when naming a class. 464 // This is ill-formed when we're not actually forming a ctor or dtor name. 465 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 466 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 467 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 468 FoundRD->isInjectedClassName() && 469 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 470 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 471 << &II << /*Type*/1; 472 473 DiagnoseUseOfDecl(IIDecl, NameLoc); 474 475 T = Context.getTypeDeclType(TD); 476 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 477 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 478 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 479 if (!HasTrailingDot) 480 T = Context.getObjCInterfaceType(IDecl); 481 } else if (AllowDeducedTemplate) { 482 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 483 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 484 QualType(), false); 485 } 486 487 if (T.isNull()) { 488 // If it's not plausibly a type, suppress diagnostics. 489 Result.suppressDiagnostics(); 490 return nullptr; 491 } 492 493 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 494 // constructor or destructor name (in such a case, the scope specifier 495 // will be attached to the enclosing Expr or Decl node). 496 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 497 !isa<ObjCInterfaceDecl>(IIDecl)) { 498 if (WantNontrivialTypeSourceInfo) { 499 // Construct a type with type-source information. 500 TypeLocBuilder Builder; 501 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 502 503 T = getElaboratedType(ETK_None, *SS, T); 504 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 505 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 506 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 507 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 508 } else { 509 T = getElaboratedType(ETK_None, *SS, T); 510 } 511 } 512 513 return ParsedType::make(T); 514 } 515 516 // Builds a fake NNS for the given decl context. 517 static NestedNameSpecifier * 518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 519 for (;; DC = DC->getLookupParent()) { 520 DC = DC->getPrimaryContext(); 521 auto *ND = dyn_cast<NamespaceDecl>(DC); 522 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 523 return NestedNameSpecifier::Create(Context, nullptr, ND); 524 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 525 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 526 RD->getTypeForDecl()); 527 else if (isa<TranslationUnitDecl>(DC)) 528 return NestedNameSpecifier::GlobalSpecifier(Context); 529 } 530 llvm_unreachable("something isn't in TU scope?"); 531 } 532 533 /// Find the parent class with dependent bases of the innermost enclosing method 534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 535 /// up allowing unqualified dependent type names at class-level, which MSVC 536 /// correctly rejects. 537 static const CXXRecordDecl * 538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 539 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 540 DC = DC->getPrimaryContext(); 541 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 542 if (MD->getParent()->hasAnyDependentBases()) 543 return MD->getParent(); 544 } 545 return nullptr; 546 } 547 548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 549 SourceLocation NameLoc, 550 bool IsTemplateTypeArg) { 551 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 552 553 NestedNameSpecifier *NNS = nullptr; 554 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 555 // If we weren't able to parse a default template argument, delay lookup 556 // until instantiation time by making a non-dependent DependentTypeName. We 557 // pretend we saw a NestedNameSpecifier referring to the current scope, and 558 // lookup is retried. 559 // FIXME: This hurts our diagnostic quality, since we get errors like "no 560 // type named 'Foo' in 'current_namespace'" when the user didn't write any 561 // name specifiers. 562 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 563 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 564 } else if (const CXXRecordDecl *RD = 565 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 566 // Build a DependentNameType that will perform lookup into RD at 567 // instantiation time. 568 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 569 RD->getTypeForDecl()); 570 571 // Diagnose that this identifier was undeclared, and retry the lookup during 572 // template instantiation. 573 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 574 << RD; 575 } else { 576 // This is not a situation that we should recover from. 577 return ParsedType(); 578 } 579 580 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 581 582 // Build type location information. We synthesized the qualifier, so we have 583 // to build a fake NestedNameSpecifierLoc. 584 NestedNameSpecifierLocBuilder NNSLocBuilder; 585 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 586 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 587 588 TypeLocBuilder Builder; 589 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 590 DepTL.setNameLoc(NameLoc); 591 DepTL.setElaboratedKeywordLoc(SourceLocation()); 592 DepTL.setQualifierLoc(QualifierLoc); 593 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 594 } 595 596 /// isTagName() - This method is called *for error recovery purposes only* 597 /// to determine if the specified name is a valid tag name ("struct foo"). If 598 /// so, this returns the TST for the tag corresponding to it (TST_enum, 599 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 600 /// cases in C where the user forgot to specify the tag. 601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 602 // Do a tag name lookup in this scope. 603 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 604 LookupName(R, S, false); 605 R.suppressDiagnostics(); 606 if (R.getResultKind() == LookupResult::Found) 607 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 608 switch (TD->getTagKind()) { 609 case TTK_Struct: return DeclSpec::TST_struct; 610 case TTK_Interface: return DeclSpec::TST_interface; 611 case TTK_Union: return DeclSpec::TST_union; 612 case TTK_Class: return DeclSpec::TST_class; 613 case TTK_Enum: return DeclSpec::TST_enum; 614 } 615 } 616 617 return DeclSpec::TST_unspecified; 618 } 619 620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 622 /// then downgrade the missing typename error to a warning. 623 /// This is needed for MSVC compatibility; Example: 624 /// @code 625 /// template<class T> class A { 626 /// public: 627 /// typedef int TYPE; 628 /// }; 629 /// template<class T> class B : public A<T> { 630 /// public: 631 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 632 /// }; 633 /// @endcode 634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 635 if (CurContext->isRecord()) { 636 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 637 return true; 638 639 const Type *Ty = SS->getScopeRep()->getAsType(); 640 641 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 642 for (const auto &Base : RD->bases()) 643 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 644 return true; 645 return S->isFunctionPrototypeScope(); 646 } 647 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 648 } 649 650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 651 SourceLocation IILoc, 652 Scope *S, 653 CXXScopeSpec *SS, 654 ParsedType &SuggestedType, 655 bool IsTemplateName) { 656 // Don't report typename errors for editor placeholders. 657 if (II->isEditorPlaceholder()) 658 return; 659 // We don't have anything to suggest (yet). 660 SuggestedType = nullptr; 661 662 // There may have been a typo in the name of the type. Look up typo 663 // results, in case we have something that we can suggest. 664 if (TypoCorrection Corrected = 665 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 666 llvm::make_unique<TypeNameValidatorCCC>( 667 false, false, IsTemplateName, !IsTemplateName), 668 CTK_ErrorRecovery)) { 669 // FIXME: Support error recovery for the template-name case. 670 bool CanRecover = !IsTemplateName; 671 if (Corrected.isKeyword()) { 672 // We corrected to a keyword. 673 diagnoseTypo(Corrected, 674 PDiag(IsTemplateName ? diag::err_no_template_suggest 675 : diag::err_unknown_typename_suggest) 676 << II); 677 II = Corrected.getCorrectionAsIdentifierInfo(); 678 } else { 679 // We found a similarly-named type or interface; suggest that. 680 if (!SS || !SS->isSet()) { 681 diagnoseTypo(Corrected, 682 PDiag(IsTemplateName ? diag::err_no_template_suggest 683 : diag::err_unknown_typename_suggest) 684 << II, CanRecover); 685 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 686 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 687 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 688 II->getName().equals(CorrectedStr); 689 diagnoseTypo(Corrected, 690 PDiag(IsTemplateName 691 ? diag::err_no_member_template_suggest 692 : diag::err_unknown_nested_typename_suggest) 693 << II << DC << DroppedSpecifier << SS->getRange(), 694 CanRecover); 695 } else { 696 llvm_unreachable("could not have corrected a typo here"); 697 } 698 699 if (!CanRecover) 700 return; 701 702 CXXScopeSpec tmpSS; 703 if (Corrected.getCorrectionSpecifier()) 704 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 705 SourceRange(IILoc)); 706 // FIXME: Support class template argument deduction here. 707 SuggestedType = 708 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 709 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 710 /*IsCtorOrDtorName=*/false, 711 /*NonTrivialTypeSourceInfo=*/true); 712 } 713 return; 714 } 715 716 if (getLangOpts().CPlusPlus && !IsTemplateName) { 717 // See if II is a class template that the user forgot to pass arguments to. 718 UnqualifiedId Name; 719 Name.setIdentifier(II, IILoc); 720 CXXScopeSpec EmptySS; 721 TemplateTy TemplateResult; 722 bool MemberOfUnknownSpecialization; 723 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 724 Name, nullptr, true, TemplateResult, 725 MemberOfUnknownSpecialization) == TNK_Type_template) { 726 TemplateName TplName = TemplateResult.get(); 727 Diag(IILoc, diag::err_template_missing_args) 728 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 729 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 730 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 731 << TplDecl->getTemplateParameters()->getSourceRange(); 732 } 733 return; 734 } 735 } 736 737 // FIXME: Should we move the logic that tries to recover from a missing tag 738 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 739 740 if (!SS || (!SS->isSet() && !SS->isInvalid())) 741 Diag(IILoc, IsTemplateName ? diag::err_no_template 742 : diag::err_unknown_typename) 743 << II; 744 else if (DeclContext *DC = computeDeclContext(*SS, false)) 745 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 746 : diag::err_typename_nested_not_found) 747 << II << DC << SS->getRange(); 748 else if (isDependentScopeSpecifier(*SS)) { 749 unsigned DiagID = diag::err_typename_missing; 750 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 751 DiagID = diag::ext_typename_missing; 752 753 Diag(SS->getRange().getBegin(), DiagID) 754 << SS->getScopeRep() << II->getName() 755 << SourceRange(SS->getRange().getBegin(), IILoc) 756 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 757 SuggestedType = ActOnTypenameType(S, SourceLocation(), 758 *SS, *II, IILoc).get(); 759 } else { 760 assert(SS && SS->isInvalid() && 761 "Invalid scope specifier has already been diagnosed"); 762 } 763 } 764 765 /// \brief Determine whether the given result set contains either a type name 766 /// or 767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 768 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 769 NextToken.is(tok::less); 770 771 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 772 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 773 return true; 774 775 if (CheckTemplate && isa<TemplateDecl>(*I)) 776 return true; 777 } 778 779 return false; 780 } 781 782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 783 Scope *S, CXXScopeSpec &SS, 784 IdentifierInfo *&Name, 785 SourceLocation NameLoc) { 786 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 787 SemaRef.LookupParsedName(R, S, &SS); 788 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 789 StringRef FixItTagName; 790 switch (Tag->getTagKind()) { 791 case TTK_Class: 792 FixItTagName = "class "; 793 break; 794 795 case TTK_Enum: 796 FixItTagName = "enum "; 797 break; 798 799 case TTK_Struct: 800 FixItTagName = "struct "; 801 break; 802 803 case TTK_Interface: 804 FixItTagName = "__interface "; 805 break; 806 807 case TTK_Union: 808 FixItTagName = "union "; 809 break; 810 } 811 812 StringRef TagName = FixItTagName.drop_back(); 813 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 814 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 815 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 816 817 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 818 I != IEnd; ++I) 819 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 820 << Name << TagName; 821 822 // Replace lookup results with just the tag decl. 823 Result.clear(Sema::LookupTagName); 824 SemaRef.LookupParsedName(Result, S, &SS); 825 return true; 826 } 827 828 return false; 829 } 830 831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 833 QualType T, SourceLocation NameLoc) { 834 ASTContext &Context = S.Context; 835 836 TypeLocBuilder Builder; 837 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 838 839 T = S.getElaboratedType(ETK_None, SS, T); 840 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 841 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 842 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 843 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 844 } 845 846 Sema::NameClassification 847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 848 SourceLocation NameLoc, const Token &NextToken, 849 bool IsAddressOfOperand, 850 std::unique_ptr<CorrectionCandidateCallback> CCC) { 851 DeclarationNameInfo NameInfo(Name, NameLoc); 852 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 853 854 if (NextToken.is(tok::coloncolon)) { 855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 857 } else if (getLangOpts().CPlusPlus && SS.isSet() && 858 isCurrentClassName(*Name, S, &SS)) { 859 // Per [class.qual]p2, this names the constructors of SS, not the 860 // injected-class-name. We don't have a classification for that. 861 // There's not much point caching this result, since the parser 862 // will reject it later. 863 return NameClassification::Unknown(); 864 } 865 866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 867 LookupParsedName(Result, S, &SS, !CurMethod); 868 869 // For unqualified lookup in a class template in MSVC mode, look into 870 // dependent base classes where the primary class template is known. 871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 872 if (ParsedType TypeInBase = 873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 874 return TypeInBase; 875 } 876 877 // Perform lookup for Objective-C instance variables (including automatically 878 // synthesized instance variables), if we're in an Objective-C method. 879 // FIXME: This lookup really, really needs to be folded in to the normal 880 // unqualified lookup mechanism. 881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 882 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 883 if (E.get() || E.isInvalid()) 884 return E; 885 } 886 887 bool SecondTry = false; 888 bool IsFilteredTemplateName = false; 889 890 Corrected: 891 switch (Result.getResultKind()) { 892 case LookupResult::NotFound: 893 // If an unqualified-id is followed by a '(', then we have a function 894 // call. 895 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 896 // In C++, this is an ADL-only call. 897 // FIXME: Reference? 898 if (getLangOpts().CPlusPlus) 899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 900 901 // C90 6.3.2.2: 902 // If the expression that precedes the parenthesized argument list in a 903 // function call consists solely of an identifier, and if no 904 // declaration is visible for this identifier, the identifier is 905 // implicitly declared exactly as if, in the innermost block containing 906 // the function call, the declaration 907 // 908 // extern int identifier (); 909 // 910 // appeared. 911 // 912 // We also allow this in C99 as an extension. 913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 914 Result.addDecl(D); 915 Result.resolveKind(); 916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 917 } 918 } 919 920 // In C, we first see whether there is a tag type by the same name, in 921 // which case it's likely that the user just forgot to write "enum", 922 // "struct", or "union". 923 if (!getLangOpts().CPlusPlus && !SecondTry && 924 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 925 break; 926 } 927 928 // Perform typo correction to determine if there is another name that is 929 // close to this name. 930 if (!SecondTry && CCC) { 931 SecondTry = true; 932 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 933 Result.getLookupKind(), S, 934 &SS, std::move(CCC), 935 CTK_ErrorRecovery)) { 936 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 937 unsigned QualifiedDiag = diag::err_no_member_suggest; 938 939 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 940 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 941 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 942 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 943 UnqualifiedDiag = diag::err_no_template_suggest; 944 QualifiedDiag = diag::err_no_member_template_suggest; 945 } else if (UnderlyingFirstDecl && 946 (isa<TypeDecl>(UnderlyingFirstDecl) || 947 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 948 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 949 UnqualifiedDiag = diag::err_unknown_typename_suggest; 950 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 951 } 952 953 if (SS.isEmpty()) { 954 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 955 } else {// FIXME: is this even reachable? Test it. 956 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 957 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 958 Name->getName().equals(CorrectedStr); 959 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 960 << Name << computeDeclContext(SS, false) 961 << DroppedSpecifier << SS.getRange()); 962 } 963 964 // Update the name, so that the caller has the new name. 965 Name = Corrected.getCorrectionAsIdentifierInfo(); 966 967 // Typo correction corrected to a keyword. 968 if (Corrected.isKeyword()) 969 return Name; 970 971 // Also update the LookupResult... 972 // FIXME: This should probably go away at some point 973 Result.clear(); 974 Result.setLookupName(Corrected.getCorrection()); 975 if (FirstDecl) 976 Result.addDecl(FirstDecl); 977 978 // If we found an Objective-C instance variable, let 979 // LookupInObjCMethod build the appropriate expression to 980 // reference the ivar. 981 // FIXME: This is a gross hack. 982 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 983 Result.clear(); 984 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 985 return E; 986 } 987 988 goto Corrected; 989 } 990 } 991 992 // We failed to correct; just fall through and let the parser deal with it. 993 Result.suppressDiagnostics(); 994 return NameClassification::Unknown(); 995 996 case LookupResult::NotFoundInCurrentInstantiation: { 997 // We performed name lookup into the current instantiation, and there were 998 // dependent bases, so we treat this result the same way as any other 999 // dependent nested-name-specifier. 1000 1001 // C++ [temp.res]p2: 1002 // A name used in a template declaration or definition and that is 1003 // dependent on a template-parameter is assumed not to name a type 1004 // unless the applicable name lookup finds a type name or the name is 1005 // qualified by the keyword typename. 1006 // 1007 // FIXME: If the next token is '<', we might want to ask the parser to 1008 // perform some heroics to see if we actually have a 1009 // template-argument-list, which would indicate a missing 'template' 1010 // keyword here. 1011 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1012 NameInfo, IsAddressOfOperand, 1013 /*TemplateArgs=*/nullptr); 1014 } 1015 1016 case LookupResult::Found: 1017 case LookupResult::FoundOverloaded: 1018 case LookupResult::FoundUnresolvedValue: 1019 break; 1020 1021 case LookupResult::Ambiguous: 1022 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1023 hasAnyAcceptableTemplateNames(Result)) { 1024 // C++ [temp.local]p3: 1025 // A lookup that finds an injected-class-name (10.2) can result in an 1026 // ambiguity in certain cases (for example, if it is found in more than 1027 // one base class). If all of the injected-class-names that are found 1028 // refer to specializations of the same class template, and if the name 1029 // is followed by a template-argument-list, the reference refers to the 1030 // class template itself and not a specialization thereof, and is not 1031 // ambiguous. 1032 // 1033 // This filtering can make an ambiguous result into an unambiguous one, 1034 // so try again after filtering out template names. 1035 FilterAcceptableTemplateNames(Result); 1036 if (!Result.isAmbiguous()) { 1037 IsFilteredTemplateName = true; 1038 break; 1039 } 1040 } 1041 1042 // Diagnose the ambiguity and return an error. 1043 return NameClassification::Error(); 1044 } 1045 1046 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1047 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1048 // C++ [temp.names]p3: 1049 // After name lookup (3.4) finds that a name is a template-name or that 1050 // an operator-function-id or a literal- operator-id refers to a set of 1051 // overloaded functions any member of which is a function template if 1052 // this is followed by a <, the < is always taken as the delimiter of a 1053 // template-argument-list and never as the less-than operator. 1054 if (!IsFilteredTemplateName) 1055 FilterAcceptableTemplateNames(Result); 1056 1057 if (!Result.empty()) { 1058 bool IsFunctionTemplate; 1059 bool IsVarTemplate; 1060 TemplateName Template; 1061 if (Result.end() - Result.begin() > 1) { 1062 IsFunctionTemplate = true; 1063 Template = Context.getOverloadedTemplateName(Result.begin(), 1064 Result.end()); 1065 } else { 1066 TemplateDecl *TD 1067 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1068 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1069 IsVarTemplate = isa<VarTemplateDecl>(TD); 1070 1071 if (SS.isSet() && !SS.isInvalid()) 1072 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1073 /*TemplateKeyword=*/false, 1074 TD); 1075 else 1076 Template = TemplateName(TD); 1077 } 1078 1079 if (IsFunctionTemplate) { 1080 // Function templates always go through overload resolution, at which 1081 // point we'll perform the various checks (e.g., accessibility) we need 1082 // to based on which function we selected. 1083 Result.suppressDiagnostics(); 1084 1085 return NameClassification::FunctionTemplate(Template); 1086 } 1087 1088 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1089 : NameClassification::TypeTemplate(Template); 1090 } 1091 } 1092 1093 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1094 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1095 DiagnoseUseOfDecl(Type, NameLoc); 1096 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1097 QualType T = Context.getTypeDeclType(Type); 1098 if (SS.isNotEmpty()) 1099 return buildNestedType(*this, SS, T, NameLoc); 1100 return ParsedType::make(T); 1101 } 1102 1103 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1104 if (!Class) { 1105 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1106 if (ObjCCompatibleAliasDecl *Alias = 1107 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1108 Class = Alias->getClassInterface(); 1109 } 1110 1111 if (Class) { 1112 DiagnoseUseOfDecl(Class, NameLoc); 1113 1114 if (NextToken.is(tok::period)) { 1115 // Interface. <something> is parsed as a property reference expression. 1116 // Just return "unknown" as a fall-through for now. 1117 Result.suppressDiagnostics(); 1118 return NameClassification::Unknown(); 1119 } 1120 1121 QualType T = Context.getObjCInterfaceType(Class); 1122 return ParsedType::make(T); 1123 } 1124 1125 // We can have a type template here if we're classifying a template argument. 1126 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1127 !isa<VarTemplateDecl>(FirstDecl)) 1128 return NameClassification::TypeTemplate( 1129 TemplateName(cast<TemplateDecl>(FirstDecl))); 1130 1131 // Check for a tag type hidden by a non-type decl in a few cases where it 1132 // seems likely a type is wanted instead of the non-type that was found. 1133 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1134 if ((NextToken.is(tok::identifier) || 1135 (NextIsOp && 1136 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1137 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1138 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1139 DiagnoseUseOfDecl(Type, NameLoc); 1140 QualType T = Context.getTypeDeclType(Type); 1141 if (SS.isNotEmpty()) 1142 return buildNestedType(*this, SS, T, NameLoc); 1143 return ParsedType::make(T); 1144 } 1145 1146 if (FirstDecl->isCXXClassMember()) 1147 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1148 nullptr, S); 1149 1150 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1151 return BuildDeclarationNameExpr(SS, Result, ADL); 1152 } 1153 1154 Sema::TemplateNameKindForDiagnostics 1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1156 auto *TD = Name.getAsTemplateDecl(); 1157 if (!TD) 1158 return TemplateNameKindForDiagnostics::DependentTemplate; 1159 if (isa<ClassTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::ClassTemplate; 1161 if (isa<FunctionTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::FunctionTemplate; 1163 if (isa<VarTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::VarTemplate; 1165 if (isa<TypeAliasTemplateDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::AliasTemplate; 1167 if (isa<TemplateTemplateParmDecl>(TD)) 1168 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1169 return TemplateNameKindForDiagnostics::DependentTemplate; 1170 } 1171 1172 // Determines the context to return to after temporarily entering a 1173 // context. This depends in an unnecessarily complicated way on the 1174 // exact ordering of callbacks from the parser. 1175 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1176 1177 // Functions defined inline within classes aren't parsed until we've 1178 // finished parsing the top-level class, so the top-level class is 1179 // the context we'll need to return to. 1180 // A Lambda call operator whose parent is a class must not be treated 1181 // as an inline member function. A Lambda can be used legally 1182 // either as an in-class member initializer or a default argument. These 1183 // are parsed once the class has been marked complete and so the containing 1184 // context would be the nested class (when the lambda is defined in one); 1185 // If the class is not complete, then the lambda is being used in an 1186 // ill-formed fashion (such as to specify the width of a bit-field, or 1187 // in an array-bound) - in which case we still want to return the 1188 // lexically containing DC (which could be a nested class). 1189 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1190 DC = DC->getLexicalParent(); 1191 1192 // A function not defined within a class will always return to its 1193 // lexical context. 1194 if (!isa<CXXRecordDecl>(DC)) 1195 return DC; 1196 1197 // A C++ inline method/friend is parsed *after* the topmost class 1198 // it was declared in is fully parsed ("complete"); the topmost 1199 // class is the context we need to return to. 1200 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1201 DC = RD; 1202 1203 // Return the declaration context of the topmost class the inline method is 1204 // declared in. 1205 return DC; 1206 } 1207 1208 return DC->getLexicalParent(); 1209 } 1210 1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1212 assert(getContainingDC(DC) == CurContext && 1213 "The next DeclContext should be lexically contained in the current one."); 1214 CurContext = DC; 1215 S->setEntity(DC); 1216 } 1217 1218 void Sema::PopDeclContext() { 1219 assert(CurContext && "DeclContext imbalance!"); 1220 1221 CurContext = getContainingDC(CurContext); 1222 assert(CurContext && "Popped translation unit!"); 1223 } 1224 1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1226 Decl *D) { 1227 // Unlike PushDeclContext, the context to which we return is not necessarily 1228 // the containing DC of TD, because the new context will be some pre-existing 1229 // TagDecl definition instead of a fresh one. 1230 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1231 CurContext = cast<TagDecl>(D)->getDefinition(); 1232 assert(CurContext && "skipping definition of undefined tag"); 1233 // Start lookups from the parent of the current context; we don't want to look 1234 // into the pre-existing complete definition. 1235 S->setEntity(CurContext->getLookupParent()); 1236 return Result; 1237 } 1238 1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1240 CurContext = static_cast<decltype(CurContext)>(Context); 1241 } 1242 1243 /// EnterDeclaratorContext - Used when we must lookup names in the context 1244 /// of a declarator's nested name specifier. 1245 /// 1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1247 // C++0x [basic.lookup.unqual]p13: 1248 // A name used in the definition of a static data member of class 1249 // X (after the qualified-id of the static member) is looked up as 1250 // if the name was used in a member function of X. 1251 // C++0x [basic.lookup.unqual]p14: 1252 // If a variable member of a namespace is defined outside of the 1253 // scope of its namespace then any name used in the definition of 1254 // the variable member (after the declarator-id) is looked up as 1255 // if the definition of the variable member occurred in its 1256 // namespace. 1257 // Both of these imply that we should push a scope whose context 1258 // is the semantic context of the declaration. We can't use 1259 // PushDeclContext here because that context is not necessarily 1260 // lexically contained in the current context. Fortunately, 1261 // the containing scope should have the appropriate information. 1262 1263 assert(!S->getEntity() && "scope already has entity"); 1264 1265 #ifndef NDEBUG 1266 Scope *Ancestor = S->getParent(); 1267 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1268 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1269 #endif 1270 1271 CurContext = DC; 1272 S->setEntity(DC); 1273 } 1274 1275 void Sema::ExitDeclaratorContext(Scope *S) { 1276 assert(S->getEntity() == CurContext && "Context imbalance!"); 1277 1278 // Switch back to the lexical context. The safety of this is 1279 // enforced by an assert in EnterDeclaratorContext. 1280 Scope *Ancestor = S->getParent(); 1281 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1282 CurContext = Ancestor->getEntity(); 1283 1284 // We don't need to do anything with the scope, which is going to 1285 // disappear. 1286 } 1287 1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1289 // We assume that the caller has already called 1290 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1291 FunctionDecl *FD = D->getAsFunction(); 1292 if (!FD) 1293 return; 1294 1295 // Same implementation as PushDeclContext, but enters the context 1296 // from the lexical parent, rather than the top-level class. 1297 assert(CurContext == FD->getLexicalParent() && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = FD; 1300 S->setEntity(CurContext); 1301 1302 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1303 ParmVarDecl *Param = FD->getParamDecl(P); 1304 // If the parameter has an identifier, then add it to the scope 1305 if (Param->getIdentifier()) { 1306 S->AddDecl(Param); 1307 IdResolver.AddDecl(Param); 1308 } 1309 } 1310 } 1311 1312 void Sema::ActOnExitFunctionContext() { 1313 // Same implementation as PopDeclContext, but returns to the lexical parent, 1314 // rather than the top-level class. 1315 assert(CurContext && "DeclContext imbalance!"); 1316 CurContext = CurContext->getLexicalParent(); 1317 assert(CurContext && "Popped translation unit!"); 1318 } 1319 1320 /// \brief Determine whether we allow overloading of the function 1321 /// PrevDecl with another declaration. 1322 /// 1323 /// This routine determines whether overloading is possible, not 1324 /// whether some new function is actually an overload. It will return 1325 /// true in C++ (where we can always provide overloads) or, as an 1326 /// extension, in C when the previous function is already an 1327 /// overloaded function declaration or has the "overloadable" 1328 /// attribute. 1329 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1330 ASTContext &Context, 1331 const FunctionDecl *New) { 1332 if (Context.getLangOpts().CPlusPlus) 1333 return true; 1334 1335 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1336 return true; 1337 1338 return Previous.getResultKind() == LookupResult::Found && 1339 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1340 New->hasAttr<OverloadableAttr>()); 1341 } 1342 1343 /// Add this decl to the scope shadowed decl chains. 1344 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1345 // Move up the scope chain until we find the nearest enclosing 1346 // non-transparent context. The declaration will be introduced into this 1347 // scope. 1348 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1349 S = S->getParent(); 1350 1351 // Add scoped declarations into their context, so that they can be 1352 // found later. Declarations without a context won't be inserted 1353 // into any context. 1354 if (AddToContext) 1355 CurContext->addDecl(D); 1356 1357 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1358 // are function-local declarations. 1359 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1360 !D->getDeclContext()->getRedeclContext()->Equals( 1361 D->getLexicalDeclContext()->getRedeclContext()) && 1362 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1363 return; 1364 1365 // Template instantiations should also not be pushed into scope. 1366 if (isa<FunctionDecl>(D) && 1367 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1368 return; 1369 1370 // If this replaces anything in the current scope, 1371 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1372 IEnd = IdResolver.end(); 1373 for (; I != IEnd; ++I) { 1374 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1375 S->RemoveDecl(*I); 1376 IdResolver.RemoveDecl(*I); 1377 1378 // Should only need to replace one decl. 1379 break; 1380 } 1381 } 1382 1383 S->AddDecl(D); 1384 1385 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1386 // Implicitly-generated labels may end up getting generated in an order that 1387 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1388 // the label at the appropriate place in the identifier chain. 1389 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1390 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1391 if (IDC == CurContext) { 1392 if (!S->isDeclScope(*I)) 1393 continue; 1394 } else if (IDC->Encloses(CurContext)) 1395 break; 1396 } 1397 1398 IdResolver.InsertDeclAfter(I, D); 1399 } else { 1400 IdResolver.AddDecl(D); 1401 } 1402 } 1403 1404 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1405 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1406 TUScope->AddDecl(D); 1407 } 1408 1409 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1410 bool AllowInlineNamespace) { 1411 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1412 } 1413 1414 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1415 DeclContext *TargetDC = DC->getPrimaryContext(); 1416 do { 1417 if (DeclContext *ScopeDC = S->getEntity()) 1418 if (ScopeDC->getPrimaryContext() == TargetDC) 1419 return S; 1420 } while ((S = S->getParent())); 1421 1422 return nullptr; 1423 } 1424 1425 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1426 DeclContext*, 1427 ASTContext&); 1428 1429 /// Filters out lookup results that don't fall within the given scope 1430 /// as determined by isDeclInScope. 1431 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1432 bool ConsiderLinkage, 1433 bool AllowInlineNamespace) { 1434 LookupResult::Filter F = R.makeFilter(); 1435 while (F.hasNext()) { 1436 NamedDecl *D = F.next(); 1437 1438 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1439 continue; 1440 1441 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1442 continue; 1443 1444 F.erase(); 1445 } 1446 1447 F.done(); 1448 } 1449 1450 static bool isUsingDecl(NamedDecl *D) { 1451 return isa<UsingShadowDecl>(D) || 1452 isa<UnresolvedUsingTypenameDecl>(D) || 1453 isa<UnresolvedUsingValueDecl>(D); 1454 } 1455 1456 /// Removes using shadow declarations from the lookup results. 1457 static void RemoveUsingDecls(LookupResult &R) { 1458 LookupResult::Filter F = R.makeFilter(); 1459 while (F.hasNext()) 1460 if (isUsingDecl(F.next())) 1461 F.erase(); 1462 1463 F.done(); 1464 } 1465 1466 /// \brief Check for this common pattern: 1467 /// @code 1468 /// class S { 1469 /// S(const S&); // DO NOT IMPLEMENT 1470 /// void operator=(const S&); // DO NOT IMPLEMENT 1471 /// }; 1472 /// @endcode 1473 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1474 // FIXME: Should check for private access too but access is set after we get 1475 // the decl here. 1476 if (D->doesThisDeclarationHaveABody()) 1477 return false; 1478 1479 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1480 return CD->isCopyConstructor(); 1481 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1482 return Method->isCopyAssignmentOperator(); 1483 return false; 1484 } 1485 1486 // We need this to handle 1487 // 1488 // typedef struct { 1489 // void *foo() { return 0; } 1490 // } A; 1491 // 1492 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1493 // for example. If 'A', foo will have external linkage. If we have '*A', 1494 // foo will have no linkage. Since we can't know until we get to the end 1495 // of the typedef, this function finds out if D might have non-external linkage. 1496 // Callers should verify at the end of the TU if it D has external linkage or 1497 // not. 1498 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1499 const DeclContext *DC = D->getDeclContext(); 1500 while (!DC->isTranslationUnit()) { 1501 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1502 if (!RD->hasNameForLinkage()) 1503 return true; 1504 } 1505 DC = DC->getParent(); 1506 } 1507 1508 return !D->isExternallyVisible(); 1509 } 1510 1511 // FIXME: This needs to be refactored; some other isInMainFile users want 1512 // these semantics. 1513 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1514 if (S.TUKind != TU_Complete) 1515 return false; 1516 return S.SourceMgr.isInMainFile(Loc); 1517 } 1518 1519 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1520 assert(D); 1521 1522 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1523 return false; 1524 1525 // Ignore all entities declared within templates, and out-of-line definitions 1526 // of members of class templates. 1527 if (D->getDeclContext()->isDependentContext() || 1528 D->getLexicalDeclContext()->isDependentContext()) 1529 return false; 1530 1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1532 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1533 return false; 1534 // A non-out-of-line declaration of a member specialization was implicitly 1535 // instantiated; it's the out-of-line declaration that we're interested in. 1536 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1537 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1538 return false; 1539 1540 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1541 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1542 return false; 1543 } else { 1544 // 'static inline' functions are defined in headers; don't warn. 1545 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1546 return false; 1547 } 1548 1549 if (FD->doesThisDeclarationHaveABody() && 1550 Context.DeclMustBeEmitted(FD)) 1551 return false; 1552 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1553 // Constants and utility variables are defined in headers with internal 1554 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1555 // like "inline".) 1556 if (!isMainFileLoc(*this, VD->getLocation())) 1557 return false; 1558 1559 if (Context.DeclMustBeEmitted(VD)) 1560 return false; 1561 1562 if (VD->isStaticDataMember() && 1563 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1564 return false; 1565 if (VD->isStaticDataMember() && 1566 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1567 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1568 return false; 1569 1570 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1571 return false; 1572 } else { 1573 return false; 1574 } 1575 1576 // Only warn for unused decls internal to the translation unit. 1577 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1578 // for inline functions defined in the main source file, for instance. 1579 return mightHaveNonExternalLinkage(D); 1580 } 1581 1582 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1583 if (!D) 1584 return; 1585 1586 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1587 const FunctionDecl *First = FD->getFirstDecl(); 1588 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1589 return; // First should already be in the vector. 1590 } 1591 1592 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1593 const VarDecl *First = VD->getFirstDecl(); 1594 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1595 return; // First should already be in the vector. 1596 } 1597 1598 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1599 UnusedFileScopedDecls.push_back(D); 1600 } 1601 1602 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1603 if (D->isInvalidDecl()) 1604 return false; 1605 1606 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1607 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1608 return false; 1609 1610 if (isa<LabelDecl>(D)) 1611 return true; 1612 1613 // Except for labels, we only care about unused decls that are local to 1614 // functions. 1615 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1616 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1617 // For dependent types, the diagnostic is deferred. 1618 WithinFunction = 1619 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1620 if (!WithinFunction) 1621 return false; 1622 1623 if (isa<TypedefNameDecl>(D)) 1624 return true; 1625 1626 // White-list anything that isn't a local variable. 1627 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1628 return false; 1629 1630 // Types of valid local variables should be complete, so this should succeed. 1631 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1632 1633 // White-list anything with an __attribute__((unused)) type. 1634 const auto *Ty = VD->getType().getTypePtr(); 1635 1636 // Only look at the outermost level of typedef. 1637 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1638 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1639 return false; 1640 } 1641 1642 // If we failed to complete the type for some reason, or if the type is 1643 // dependent, don't diagnose the variable. 1644 if (Ty->isIncompleteType() || Ty->isDependentType()) 1645 return false; 1646 1647 // Look at the element type to ensure that the warning behaviour is 1648 // consistent for both scalars and arrays. 1649 Ty = Ty->getBaseElementTypeUnsafe(); 1650 1651 if (const TagType *TT = Ty->getAs<TagType>()) { 1652 const TagDecl *Tag = TT->getDecl(); 1653 if (Tag->hasAttr<UnusedAttr>()) 1654 return false; 1655 1656 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1657 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1658 return false; 1659 1660 if (const Expr *Init = VD->getInit()) { 1661 if (const ExprWithCleanups *Cleanups = 1662 dyn_cast<ExprWithCleanups>(Init)) 1663 Init = Cleanups->getSubExpr(); 1664 const CXXConstructExpr *Construct = 1665 dyn_cast<CXXConstructExpr>(Init); 1666 if (Construct && !Construct->isElidable()) { 1667 CXXConstructorDecl *CD = Construct->getConstructor(); 1668 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1669 return false; 1670 } 1671 } 1672 } 1673 } 1674 1675 // TODO: __attribute__((unused)) templates? 1676 } 1677 1678 return true; 1679 } 1680 1681 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1682 FixItHint &Hint) { 1683 if (isa<LabelDecl>(D)) { 1684 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1685 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1686 if (AfterColon.isInvalid()) 1687 return; 1688 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1689 getCharRange(D->getLocStart(), AfterColon)); 1690 } 1691 } 1692 1693 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1694 if (D->getTypeForDecl()->isDependentType()) 1695 return; 1696 1697 for (auto *TmpD : D->decls()) { 1698 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1699 DiagnoseUnusedDecl(T); 1700 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1701 DiagnoseUnusedNestedTypedefs(R); 1702 } 1703 } 1704 1705 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1706 /// unless they are marked attr(unused). 1707 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1708 if (!ShouldDiagnoseUnusedDecl(D)) 1709 return; 1710 1711 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1712 // typedefs can be referenced later on, so the diagnostics are emitted 1713 // at end-of-translation-unit. 1714 UnusedLocalTypedefNameCandidates.insert(TD); 1715 return; 1716 } 1717 1718 FixItHint Hint; 1719 GenerateFixForUnusedDecl(D, Context, Hint); 1720 1721 unsigned DiagID; 1722 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1723 DiagID = diag::warn_unused_exception_param; 1724 else if (isa<LabelDecl>(D)) 1725 DiagID = diag::warn_unused_label; 1726 else 1727 DiagID = diag::warn_unused_variable; 1728 1729 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1730 } 1731 1732 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1733 // Verify that we have no forward references left. If so, there was a goto 1734 // or address of a label taken, but no definition of it. Label fwd 1735 // definitions are indicated with a null substmt which is also not a resolved 1736 // MS inline assembly label name. 1737 bool Diagnose = false; 1738 if (L->isMSAsmLabel()) 1739 Diagnose = !L->isResolvedMSAsmLabel(); 1740 else 1741 Diagnose = L->getStmt() == nullptr; 1742 if (Diagnose) 1743 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1744 } 1745 1746 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1747 S->mergeNRVOIntoParent(); 1748 1749 if (S->decl_empty()) return; 1750 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1751 "Scope shouldn't contain decls!"); 1752 1753 for (auto *TmpD : S->decls()) { 1754 assert(TmpD && "This decl didn't get pushed??"); 1755 1756 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1757 NamedDecl *D = cast<NamedDecl>(TmpD); 1758 1759 if (!D->getDeclName()) continue; 1760 1761 // Diagnose unused variables in this scope. 1762 if (!S->hasUnrecoverableErrorOccurred()) { 1763 DiagnoseUnusedDecl(D); 1764 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1765 DiagnoseUnusedNestedTypedefs(RD); 1766 } 1767 1768 // If this was a forward reference to a label, verify it was defined. 1769 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1770 CheckPoppedLabel(LD, *this); 1771 1772 // Remove this name from our lexical scope, and warn on it if we haven't 1773 // already. 1774 IdResolver.RemoveDecl(D); 1775 auto ShadowI = ShadowingDecls.find(D); 1776 if (ShadowI != ShadowingDecls.end()) { 1777 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1778 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1779 << D << FD << FD->getParent(); 1780 Diag(FD->getLocation(), diag::note_previous_declaration); 1781 } 1782 ShadowingDecls.erase(ShadowI); 1783 } 1784 } 1785 } 1786 1787 /// \brief Look for an Objective-C class in the translation unit. 1788 /// 1789 /// \param Id The name of the Objective-C class we're looking for. If 1790 /// typo-correction fixes this name, the Id will be updated 1791 /// to the fixed name. 1792 /// 1793 /// \param IdLoc The location of the name in the translation unit. 1794 /// 1795 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1796 /// if there is no class with the given name. 1797 /// 1798 /// \returns The declaration of the named Objective-C class, or NULL if the 1799 /// class could not be found. 1800 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1801 SourceLocation IdLoc, 1802 bool DoTypoCorrection) { 1803 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1804 // creation from this context. 1805 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1806 1807 if (!IDecl && DoTypoCorrection) { 1808 // Perform typo correction at the given location, but only if we 1809 // find an Objective-C class name. 1810 if (TypoCorrection C = CorrectTypo( 1811 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1812 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1813 CTK_ErrorRecovery)) { 1814 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1815 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1816 Id = IDecl->getIdentifier(); 1817 } 1818 } 1819 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1820 // This routine must always return a class definition, if any. 1821 if (Def && Def->getDefinition()) 1822 Def = Def->getDefinition(); 1823 return Def; 1824 } 1825 1826 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1827 /// from S, where a non-field would be declared. This routine copes 1828 /// with the difference between C and C++ scoping rules in structs and 1829 /// unions. For example, the following code is well-formed in C but 1830 /// ill-formed in C++: 1831 /// @code 1832 /// struct S6 { 1833 /// enum { BAR } e; 1834 /// }; 1835 /// 1836 /// void test_S6() { 1837 /// struct S6 a; 1838 /// a.e = BAR; 1839 /// } 1840 /// @endcode 1841 /// For the declaration of BAR, this routine will return a different 1842 /// scope. The scope S will be the scope of the unnamed enumeration 1843 /// within S6. In C++, this routine will return the scope associated 1844 /// with S6, because the enumeration's scope is a transparent 1845 /// context but structures can contain non-field names. In C, this 1846 /// routine will return the translation unit scope, since the 1847 /// enumeration's scope is a transparent context and structures cannot 1848 /// contain non-field names. 1849 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1850 while (((S->getFlags() & Scope::DeclScope) == 0) || 1851 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1852 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1853 S = S->getParent(); 1854 return S; 1855 } 1856 1857 /// \brief Looks up the declaration of "struct objc_super" and 1858 /// saves it for later use in building builtin declaration of 1859 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1860 /// pre-existing declaration exists no action takes place. 1861 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1862 IdentifierInfo *II) { 1863 if (!II->isStr("objc_msgSendSuper")) 1864 return; 1865 ASTContext &Context = ThisSema.Context; 1866 1867 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1868 SourceLocation(), Sema::LookupTagName); 1869 ThisSema.LookupName(Result, S); 1870 if (Result.getResultKind() == LookupResult::Found) 1871 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1872 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1873 } 1874 1875 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1876 switch (Error) { 1877 case ASTContext::GE_None: 1878 return ""; 1879 case ASTContext::GE_Missing_stdio: 1880 return "stdio.h"; 1881 case ASTContext::GE_Missing_setjmp: 1882 return "setjmp.h"; 1883 case ASTContext::GE_Missing_ucontext: 1884 return "ucontext.h"; 1885 } 1886 llvm_unreachable("unhandled error kind"); 1887 } 1888 1889 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1890 /// file scope. lazily create a decl for it. ForRedeclaration is true 1891 /// if we're creating this built-in in anticipation of redeclaring the 1892 /// built-in. 1893 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1894 Scope *S, bool ForRedeclaration, 1895 SourceLocation Loc) { 1896 LookupPredefedObjCSuperType(*this, S, II); 1897 1898 ASTContext::GetBuiltinTypeError Error; 1899 QualType R = Context.GetBuiltinType(ID, Error); 1900 if (Error) { 1901 if (ForRedeclaration) 1902 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1903 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1904 return nullptr; 1905 } 1906 1907 if (!ForRedeclaration && 1908 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1909 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1910 Diag(Loc, diag::ext_implicit_lib_function_decl) 1911 << Context.BuiltinInfo.getName(ID) << R; 1912 if (Context.BuiltinInfo.getHeaderName(ID) && 1913 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1914 Diag(Loc, diag::note_include_header_or_declare) 1915 << Context.BuiltinInfo.getHeaderName(ID) 1916 << Context.BuiltinInfo.getName(ID); 1917 } 1918 1919 if (R.isNull()) 1920 return nullptr; 1921 1922 DeclContext *Parent = Context.getTranslationUnitDecl(); 1923 if (getLangOpts().CPlusPlus) { 1924 LinkageSpecDecl *CLinkageDecl = 1925 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1926 LinkageSpecDecl::lang_c, false); 1927 CLinkageDecl->setImplicit(); 1928 Parent->addDecl(CLinkageDecl); 1929 Parent = CLinkageDecl; 1930 } 1931 1932 FunctionDecl *New = FunctionDecl::Create(Context, 1933 Parent, 1934 Loc, Loc, II, R, /*TInfo=*/nullptr, 1935 SC_Extern, 1936 false, 1937 R->isFunctionProtoType()); 1938 New->setImplicit(); 1939 1940 // Create Decl objects for each parameter, adding them to the 1941 // FunctionDecl. 1942 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1943 SmallVector<ParmVarDecl*, 16> Params; 1944 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1945 ParmVarDecl *parm = 1946 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1947 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1948 SC_None, nullptr); 1949 parm->setScopeInfo(0, i); 1950 Params.push_back(parm); 1951 } 1952 New->setParams(Params); 1953 } 1954 1955 AddKnownFunctionAttributes(New); 1956 RegisterLocallyScopedExternCDecl(New, S); 1957 1958 // TUScope is the translation-unit scope to insert this function into. 1959 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1960 // relate Scopes to DeclContexts, and probably eliminate CurContext 1961 // entirely, but we're not there yet. 1962 DeclContext *SavedContext = CurContext; 1963 CurContext = Parent; 1964 PushOnScopeChains(New, TUScope); 1965 CurContext = SavedContext; 1966 return New; 1967 } 1968 1969 /// Typedef declarations don't have linkage, but they still denote the same 1970 /// entity if their types are the same. 1971 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1972 /// isSameEntity. 1973 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1974 TypedefNameDecl *Decl, 1975 LookupResult &Previous) { 1976 // This is only interesting when modules are enabled. 1977 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1978 return; 1979 1980 // Empty sets are uninteresting. 1981 if (Previous.empty()) 1982 return; 1983 1984 LookupResult::Filter Filter = Previous.makeFilter(); 1985 while (Filter.hasNext()) { 1986 NamedDecl *Old = Filter.next(); 1987 1988 // Non-hidden declarations are never ignored. 1989 if (S.isVisible(Old)) 1990 continue; 1991 1992 // Declarations of the same entity are not ignored, even if they have 1993 // different linkages. 1994 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1995 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1996 Decl->getUnderlyingType())) 1997 continue; 1998 1999 // If both declarations give a tag declaration a typedef name for linkage 2000 // purposes, then they declare the same entity. 2001 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2002 Decl->getAnonDeclWithTypedefName()) 2003 continue; 2004 } 2005 2006 Filter.erase(); 2007 } 2008 2009 Filter.done(); 2010 } 2011 2012 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2013 QualType OldType; 2014 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2015 OldType = OldTypedef->getUnderlyingType(); 2016 else 2017 OldType = Context.getTypeDeclType(Old); 2018 QualType NewType = New->getUnderlyingType(); 2019 2020 if (NewType->isVariablyModifiedType()) { 2021 // Must not redefine a typedef with a variably-modified type. 2022 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2023 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2024 << Kind << NewType; 2025 if (Old->getLocation().isValid()) 2026 notePreviousDefinition(Old, New->getLocation()); 2027 New->setInvalidDecl(); 2028 return true; 2029 } 2030 2031 if (OldType != NewType && 2032 !OldType->isDependentType() && 2033 !NewType->isDependentType() && 2034 !Context.hasSameType(OldType, NewType)) { 2035 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2036 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2037 << Kind << NewType << OldType; 2038 if (Old->getLocation().isValid()) 2039 notePreviousDefinition(Old, New->getLocation()); 2040 New->setInvalidDecl(); 2041 return true; 2042 } 2043 return false; 2044 } 2045 2046 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2047 /// same name and scope as a previous declaration 'Old'. Figure out 2048 /// how to resolve this situation, merging decls or emitting 2049 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2050 /// 2051 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2052 LookupResult &OldDecls) { 2053 // If the new decl is known invalid already, don't bother doing any 2054 // merging checks. 2055 if (New->isInvalidDecl()) return; 2056 2057 // Allow multiple definitions for ObjC built-in typedefs. 2058 // FIXME: Verify the underlying types are equivalent! 2059 if (getLangOpts().ObjC1) { 2060 const IdentifierInfo *TypeID = New->getIdentifier(); 2061 switch (TypeID->getLength()) { 2062 default: break; 2063 case 2: 2064 { 2065 if (!TypeID->isStr("id")) 2066 break; 2067 QualType T = New->getUnderlyingType(); 2068 if (!T->isPointerType()) 2069 break; 2070 if (!T->isVoidPointerType()) { 2071 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2072 if (!PT->isStructureType()) 2073 break; 2074 } 2075 Context.setObjCIdRedefinitionType(T); 2076 // Install the built-in type for 'id', ignoring the current definition. 2077 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2078 return; 2079 } 2080 case 5: 2081 if (!TypeID->isStr("Class")) 2082 break; 2083 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2084 // Install the built-in type for 'Class', ignoring the current definition. 2085 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2086 return; 2087 case 3: 2088 if (!TypeID->isStr("SEL")) 2089 break; 2090 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2091 // Install the built-in type for 'SEL', ignoring the current definition. 2092 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2093 return; 2094 } 2095 // Fall through - the typedef name was not a builtin type. 2096 } 2097 2098 // Verify the old decl was also a type. 2099 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2100 if (!Old) { 2101 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2102 << New->getDeclName(); 2103 2104 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2105 if (OldD->getLocation().isValid()) 2106 notePreviousDefinition(OldD, New->getLocation()); 2107 2108 return New->setInvalidDecl(); 2109 } 2110 2111 // If the old declaration is invalid, just give up here. 2112 if (Old->isInvalidDecl()) 2113 return New->setInvalidDecl(); 2114 2115 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2116 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2117 auto *NewTag = New->getAnonDeclWithTypedefName(); 2118 NamedDecl *Hidden = nullptr; 2119 if (OldTag && NewTag && 2120 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2121 !hasVisibleDefinition(OldTag, &Hidden)) { 2122 // There is a definition of this tag, but it is not visible. Use it 2123 // instead of our tag. 2124 New->setTypeForDecl(OldTD->getTypeForDecl()); 2125 if (OldTD->isModed()) 2126 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2127 OldTD->getUnderlyingType()); 2128 else 2129 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2130 2131 // Make the old tag definition visible. 2132 makeMergedDefinitionVisible(Hidden); 2133 2134 // If this was an unscoped enumeration, yank all of its enumerators 2135 // out of the scope. 2136 if (isa<EnumDecl>(NewTag)) { 2137 Scope *EnumScope = getNonFieldDeclScope(S); 2138 for (auto *D : NewTag->decls()) { 2139 auto *ED = cast<EnumConstantDecl>(D); 2140 assert(EnumScope->isDeclScope(ED)); 2141 EnumScope->RemoveDecl(ED); 2142 IdResolver.RemoveDecl(ED); 2143 ED->getLexicalDeclContext()->removeDecl(ED); 2144 } 2145 } 2146 } 2147 } 2148 2149 // If the typedef types are not identical, reject them in all languages and 2150 // with any extensions enabled. 2151 if (isIncompatibleTypedef(Old, New)) 2152 return; 2153 2154 // The types match. Link up the redeclaration chain and merge attributes if 2155 // the old declaration was a typedef. 2156 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2157 New->setPreviousDecl(Typedef); 2158 mergeDeclAttributes(New, Old); 2159 } 2160 2161 if (getLangOpts().MicrosoftExt) 2162 return; 2163 2164 if (getLangOpts().CPlusPlus) { 2165 // C++ [dcl.typedef]p2: 2166 // In a given non-class scope, a typedef specifier can be used to 2167 // redefine the name of any type declared in that scope to refer 2168 // to the type to which it already refers. 2169 if (!isa<CXXRecordDecl>(CurContext)) 2170 return; 2171 2172 // C++0x [dcl.typedef]p4: 2173 // In a given class scope, a typedef specifier can be used to redefine 2174 // any class-name declared in that scope that is not also a typedef-name 2175 // to refer to the type to which it already refers. 2176 // 2177 // This wording came in via DR424, which was a correction to the 2178 // wording in DR56, which accidentally banned code like: 2179 // 2180 // struct S { 2181 // typedef struct A { } A; 2182 // }; 2183 // 2184 // in the C++03 standard. We implement the C++0x semantics, which 2185 // allow the above but disallow 2186 // 2187 // struct S { 2188 // typedef int I; 2189 // typedef int I; 2190 // }; 2191 // 2192 // since that was the intent of DR56. 2193 if (!isa<TypedefNameDecl>(Old)) 2194 return; 2195 2196 Diag(New->getLocation(), diag::err_redefinition) 2197 << New->getDeclName(); 2198 notePreviousDefinition(Old, New->getLocation()); 2199 return New->setInvalidDecl(); 2200 } 2201 2202 // Modules always permit redefinition of typedefs, as does C11. 2203 if (getLangOpts().Modules || getLangOpts().C11) 2204 return; 2205 2206 // If we have a redefinition of a typedef in C, emit a warning. This warning 2207 // is normally mapped to an error, but can be controlled with 2208 // -Wtypedef-redefinition. If either the original or the redefinition is 2209 // in a system header, don't emit this for compatibility with GCC. 2210 if (getDiagnostics().getSuppressSystemWarnings() && 2211 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2212 (Old->isImplicit() || 2213 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2214 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2215 return; 2216 2217 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2218 << New->getDeclName(); 2219 notePreviousDefinition(Old, New->getLocation()); 2220 } 2221 2222 /// DeclhasAttr - returns true if decl Declaration already has the target 2223 /// attribute. 2224 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2225 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2226 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2227 for (const auto *i : D->attrs()) 2228 if (i->getKind() == A->getKind()) { 2229 if (Ann) { 2230 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2231 return true; 2232 continue; 2233 } 2234 // FIXME: Don't hardcode this check 2235 if (OA && isa<OwnershipAttr>(i)) 2236 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2237 return true; 2238 } 2239 2240 return false; 2241 } 2242 2243 static bool isAttributeTargetADefinition(Decl *D) { 2244 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2245 return VD->isThisDeclarationADefinition(); 2246 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2247 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2248 return true; 2249 } 2250 2251 /// Merge alignment attributes from \p Old to \p New, taking into account the 2252 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2253 /// 2254 /// \return \c true if any attributes were added to \p New. 2255 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2256 // Look for alignas attributes on Old, and pick out whichever attribute 2257 // specifies the strictest alignment requirement. 2258 AlignedAttr *OldAlignasAttr = nullptr; 2259 AlignedAttr *OldStrictestAlignAttr = nullptr; 2260 unsigned OldAlign = 0; 2261 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2262 // FIXME: We have no way of representing inherited dependent alignments 2263 // in a case like: 2264 // template<int A, int B> struct alignas(A) X; 2265 // template<int A, int B> struct alignas(B) X {}; 2266 // For now, we just ignore any alignas attributes which are not on the 2267 // definition in such a case. 2268 if (I->isAlignmentDependent()) 2269 return false; 2270 2271 if (I->isAlignas()) 2272 OldAlignasAttr = I; 2273 2274 unsigned Align = I->getAlignment(S.Context); 2275 if (Align > OldAlign) { 2276 OldAlign = Align; 2277 OldStrictestAlignAttr = I; 2278 } 2279 } 2280 2281 // Look for alignas attributes on New. 2282 AlignedAttr *NewAlignasAttr = nullptr; 2283 unsigned NewAlign = 0; 2284 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2285 if (I->isAlignmentDependent()) 2286 return false; 2287 2288 if (I->isAlignas()) 2289 NewAlignasAttr = I; 2290 2291 unsigned Align = I->getAlignment(S.Context); 2292 if (Align > NewAlign) 2293 NewAlign = Align; 2294 } 2295 2296 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2297 // Both declarations have 'alignas' attributes. We require them to match. 2298 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2299 // fall short. (If two declarations both have alignas, they must both match 2300 // every definition, and so must match each other if there is a definition.) 2301 2302 // If either declaration only contains 'alignas(0)' specifiers, then it 2303 // specifies the natural alignment for the type. 2304 if (OldAlign == 0 || NewAlign == 0) { 2305 QualType Ty; 2306 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2307 Ty = VD->getType(); 2308 else 2309 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2310 2311 if (OldAlign == 0) 2312 OldAlign = S.Context.getTypeAlign(Ty); 2313 if (NewAlign == 0) 2314 NewAlign = S.Context.getTypeAlign(Ty); 2315 } 2316 2317 if (OldAlign != NewAlign) { 2318 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2319 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2320 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2321 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2322 } 2323 } 2324 2325 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2326 // C++11 [dcl.align]p6: 2327 // if any declaration of an entity has an alignment-specifier, 2328 // every defining declaration of that entity shall specify an 2329 // equivalent alignment. 2330 // C11 6.7.5/7: 2331 // If the definition of an object does not have an alignment 2332 // specifier, any other declaration of that object shall also 2333 // have no alignment specifier. 2334 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2335 << OldAlignasAttr; 2336 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2337 << OldAlignasAttr; 2338 } 2339 2340 bool AnyAdded = false; 2341 2342 // Ensure we have an attribute representing the strictest alignment. 2343 if (OldAlign > NewAlign) { 2344 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2345 Clone->setInherited(true); 2346 New->addAttr(Clone); 2347 AnyAdded = true; 2348 } 2349 2350 // Ensure we have an alignas attribute if the old declaration had one. 2351 if (OldAlignasAttr && !NewAlignasAttr && 2352 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2353 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2354 Clone->setInherited(true); 2355 New->addAttr(Clone); 2356 AnyAdded = true; 2357 } 2358 2359 return AnyAdded; 2360 } 2361 2362 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2363 const InheritableAttr *Attr, 2364 Sema::AvailabilityMergeKind AMK) { 2365 // This function copies an attribute Attr from a previous declaration to the 2366 // new declaration D if the new declaration doesn't itself have that attribute 2367 // yet or if that attribute allows duplicates. 2368 // If you're adding a new attribute that requires logic different from 2369 // "use explicit attribute on decl if present, else use attribute from 2370 // previous decl", for example if the attribute needs to be consistent 2371 // between redeclarations, you need to call a custom merge function here. 2372 InheritableAttr *NewAttr = nullptr; 2373 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2374 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2375 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2376 AA->isImplicit(), AA->getIntroduced(), 2377 AA->getDeprecated(), 2378 AA->getObsoleted(), AA->getUnavailable(), 2379 AA->getMessage(), AA->getStrict(), 2380 AA->getReplacement(), AMK, 2381 AttrSpellingListIndex); 2382 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2383 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2384 AttrSpellingListIndex); 2385 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2386 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2387 AttrSpellingListIndex); 2388 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2389 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2390 AttrSpellingListIndex); 2391 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2392 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2393 AttrSpellingListIndex); 2394 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2395 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2396 FA->getFormatIdx(), FA->getFirstArg(), 2397 AttrSpellingListIndex); 2398 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2399 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2400 AttrSpellingListIndex); 2401 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2402 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2403 AttrSpellingListIndex, 2404 IA->getSemanticSpelling()); 2405 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2406 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2407 &S.Context.Idents.get(AA->getSpelling()), 2408 AttrSpellingListIndex); 2409 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2410 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2411 isa<CUDAGlobalAttr>(Attr))) { 2412 // CUDA target attributes are part of function signature for 2413 // overloading purposes and must not be merged. 2414 return false; 2415 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2416 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2417 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2418 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2419 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2420 NewAttr = S.mergeInternalLinkageAttr( 2421 D, InternalLinkageA->getRange(), 2422 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2423 AttrSpellingListIndex); 2424 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2425 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2426 &S.Context.Idents.get(CommonA->getSpelling()), 2427 AttrSpellingListIndex); 2428 else if (isa<AlignedAttr>(Attr)) 2429 // AlignedAttrs are handled separately, because we need to handle all 2430 // such attributes on a declaration at the same time. 2431 NewAttr = nullptr; 2432 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2433 (AMK == Sema::AMK_Override || 2434 AMK == Sema::AMK_ProtocolImplementation)) 2435 NewAttr = nullptr; 2436 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2437 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2438 UA->getGuid()); 2439 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2440 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2441 2442 if (NewAttr) { 2443 NewAttr->setInherited(true); 2444 D->addAttr(NewAttr); 2445 if (isa<MSInheritanceAttr>(NewAttr)) 2446 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2447 return true; 2448 } 2449 2450 return false; 2451 } 2452 2453 static const NamedDecl *getDefinition(const Decl *D) { 2454 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2455 return TD->getDefinition(); 2456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2457 const VarDecl *Def = VD->getDefinition(); 2458 if (Def) 2459 return Def; 2460 return VD->getActingDefinition(); 2461 } 2462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2463 return FD->getDefinition(); 2464 return nullptr; 2465 } 2466 2467 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2468 for (const auto *Attribute : D->attrs()) 2469 if (Attribute->getKind() == Kind) 2470 return true; 2471 return false; 2472 } 2473 2474 /// checkNewAttributesAfterDef - If we already have a definition, check that 2475 /// there are no new attributes in this declaration. 2476 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2477 if (!New->hasAttrs()) 2478 return; 2479 2480 const NamedDecl *Def = getDefinition(Old); 2481 if (!Def || Def == New) 2482 return; 2483 2484 AttrVec &NewAttributes = New->getAttrs(); 2485 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2486 const Attr *NewAttribute = NewAttributes[I]; 2487 2488 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2489 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2490 Sema::SkipBodyInfo SkipBody; 2491 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2492 2493 // If we're skipping this definition, drop the "alias" attribute. 2494 if (SkipBody.ShouldSkip) { 2495 NewAttributes.erase(NewAttributes.begin() + I); 2496 --E; 2497 continue; 2498 } 2499 } else { 2500 VarDecl *VD = cast<VarDecl>(New); 2501 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2502 VarDecl::TentativeDefinition 2503 ? diag::err_alias_after_tentative 2504 : diag::err_redefinition; 2505 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2506 if (Diag == diag::err_redefinition) 2507 S.notePreviousDefinition(Def, VD->getLocation()); 2508 else 2509 S.Diag(Def->getLocation(), diag::note_previous_definition); 2510 VD->setInvalidDecl(); 2511 } 2512 ++I; 2513 continue; 2514 } 2515 2516 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2517 // Tentative definitions are only interesting for the alias check above. 2518 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2519 ++I; 2520 continue; 2521 } 2522 } 2523 2524 if (hasAttribute(Def, NewAttribute->getKind())) { 2525 ++I; 2526 continue; // regular attr merging will take care of validating this. 2527 } 2528 2529 if (isa<C11NoReturnAttr>(NewAttribute)) { 2530 // C's _Noreturn is allowed to be added to a function after it is defined. 2531 ++I; 2532 continue; 2533 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2534 if (AA->isAlignas()) { 2535 // C++11 [dcl.align]p6: 2536 // if any declaration of an entity has an alignment-specifier, 2537 // every defining declaration of that entity shall specify an 2538 // equivalent alignment. 2539 // C11 6.7.5/7: 2540 // If the definition of an object does not have an alignment 2541 // specifier, any other declaration of that object shall also 2542 // have no alignment specifier. 2543 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2544 << AA; 2545 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2546 << AA; 2547 NewAttributes.erase(NewAttributes.begin() + I); 2548 --E; 2549 continue; 2550 } 2551 } 2552 2553 S.Diag(NewAttribute->getLocation(), 2554 diag::warn_attribute_precede_definition); 2555 S.Diag(Def->getLocation(), diag::note_previous_definition); 2556 NewAttributes.erase(NewAttributes.begin() + I); 2557 --E; 2558 } 2559 } 2560 2561 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2562 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2563 AvailabilityMergeKind AMK) { 2564 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2565 UsedAttr *NewAttr = OldAttr->clone(Context); 2566 NewAttr->setInherited(true); 2567 New->addAttr(NewAttr); 2568 } 2569 2570 if (!Old->hasAttrs() && !New->hasAttrs()) 2571 return; 2572 2573 // Attributes declared post-definition are currently ignored. 2574 checkNewAttributesAfterDef(*this, New, Old); 2575 2576 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2577 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2578 if (OldA->getLabel() != NewA->getLabel()) { 2579 // This redeclaration changes __asm__ label. 2580 Diag(New->getLocation(), diag::err_different_asm_label); 2581 Diag(OldA->getLocation(), diag::note_previous_declaration); 2582 } 2583 } else if (Old->isUsed()) { 2584 // This redeclaration adds an __asm__ label to a declaration that has 2585 // already been ODR-used. 2586 Diag(New->getLocation(), diag::err_late_asm_label_name) 2587 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2588 } 2589 } 2590 2591 // Re-declaration cannot add abi_tag's. 2592 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2593 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2594 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2595 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2596 NewTag) == OldAbiTagAttr->tags_end()) { 2597 Diag(NewAbiTagAttr->getLocation(), 2598 diag::err_new_abi_tag_on_redeclaration) 2599 << NewTag; 2600 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2601 } 2602 } 2603 } else { 2604 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2605 Diag(Old->getLocation(), diag::note_previous_declaration); 2606 } 2607 } 2608 2609 if (!Old->hasAttrs()) 2610 return; 2611 2612 bool foundAny = New->hasAttrs(); 2613 2614 // Ensure that any moving of objects within the allocated map is done before 2615 // we process them. 2616 if (!foundAny) New->setAttrs(AttrVec()); 2617 2618 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2619 // Ignore deprecated/unavailable/availability attributes if requested. 2620 AvailabilityMergeKind LocalAMK = AMK_None; 2621 if (isa<DeprecatedAttr>(I) || 2622 isa<UnavailableAttr>(I) || 2623 isa<AvailabilityAttr>(I)) { 2624 switch (AMK) { 2625 case AMK_None: 2626 continue; 2627 2628 case AMK_Redeclaration: 2629 case AMK_Override: 2630 case AMK_ProtocolImplementation: 2631 LocalAMK = AMK; 2632 break; 2633 } 2634 } 2635 2636 // Already handled. 2637 if (isa<UsedAttr>(I)) 2638 continue; 2639 2640 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2641 foundAny = true; 2642 } 2643 2644 if (mergeAlignedAttrs(*this, New, Old)) 2645 foundAny = true; 2646 2647 if (!foundAny) New->dropAttrs(); 2648 } 2649 2650 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2651 /// to the new one. 2652 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2653 const ParmVarDecl *oldDecl, 2654 Sema &S) { 2655 // C++11 [dcl.attr.depend]p2: 2656 // The first declaration of a function shall specify the 2657 // carries_dependency attribute for its declarator-id if any declaration 2658 // of the function specifies the carries_dependency attribute. 2659 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2660 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2661 S.Diag(CDA->getLocation(), 2662 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2663 // Find the first declaration of the parameter. 2664 // FIXME: Should we build redeclaration chains for function parameters? 2665 const FunctionDecl *FirstFD = 2666 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2667 const ParmVarDecl *FirstVD = 2668 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2669 S.Diag(FirstVD->getLocation(), 2670 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2671 } 2672 2673 if (!oldDecl->hasAttrs()) 2674 return; 2675 2676 bool foundAny = newDecl->hasAttrs(); 2677 2678 // Ensure that any moving of objects within the allocated map is 2679 // done before we process them. 2680 if (!foundAny) newDecl->setAttrs(AttrVec()); 2681 2682 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2683 if (!DeclHasAttr(newDecl, I)) { 2684 InheritableAttr *newAttr = 2685 cast<InheritableParamAttr>(I->clone(S.Context)); 2686 newAttr->setInherited(true); 2687 newDecl->addAttr(newAttr); 2688 foundAny = true; 2689 } 2690 } 2691 2692 if (!foundAny) newDecl->dropAttrs(); 2693 } 2694 2695 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2696 const ParmVarDecl *OldParam, 2697 Sema &S) { 2698 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2699 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2700 if (*Oldnullability != *Newnullability) { 2701 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2702 << DiagNullabilityKind( 2703 *Newnullability, 2704 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2705 != 0)) 2706 << DiagNullabilityKind( 2707 *Oldnullability, 2708 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2709 != 0)); 2710 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2711 } 2712 } else { 2713 QualType NewT = NewParam->getType(); 2714 NewT = S.Context.getAttributedType( 2715 AttributedType::getNullabilityAttrKind(*Oldnullability), 2716 NewT, NewT); 2717 NewParam->setType(NewT); 2718 } 2719 } 2720 } 2721 2722 namespace { 2723 2724 /// Used in MergeFunctionDecl to keep track of function parameters in 2725 /// C. 2726 struct GNUCompatibleParamWarning { 2727 ParmVarDecl *OldParm; 2728 ParmVarDecl *NewParm; 2729 QualType PromotedType; 2730 }; 2731 2732 } // end anonymous namespace 2733 2734 /// getSpecialMember - get the special member enum for a method. 2735 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2736 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2737 if (Ctor->isDefaultConstructor()) 2738 return Sema::CXXDefaultConstructor; 2739 2740 if (Ctor->isCopyConstructor()) 2741 return Sema::CXXCopyConstructor; 2742 2743 if (Ctor->isMoveConstructor()) 2744 return Sema::CXXMoveConstructor; 2745 } else if (isa<CXXDestructorDecl>(MD)) { 2746 return Sema::CXXDestructor; 2747 } else if (MD->isCopyAssignmentOperator()) { 2748 return Sema::CXXCopyAssignment; 2749 } else if (MD->isMoveAssignmentOperator()) { 2750 return Sema::CXXMoveAssignment; 2751 } 2752 2753 return Sema::CXXInvalid; 2754 } 2755 2756 // Determine whether the previous declaration was a definition, implicit 2757 // declaration, or a declaration. 2758 template <typename T> 2759 static std::pair<diag::kind, SourceLocation> 2760 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2761 diag::kind PrevDiag; 2762 SourceLocation OldLocation = Old->getLocation(); 2763 if (Old->isThisDeclarationADefinition()) 2764 PrevDiag = diag::note_previous_definition; 2765 else if (Old->isImplicit()) { 2766 PrevDiag = diag::note_previous_implicit_declaration; 2767 if (OldLocation.isInvalid()) 2768 OldLocation = New->getLocation(); 2769 } else 2770 PrevDiag = diag::note_previous_declaration; 2771 return std::make_pair(PrevDiag, OldLocation); 2772 } 2773 2774 /// canRedefineFunction - checks if a function can be redefined. Currently, 2775 /// only extern inline functions can be redefined, and even then only in 2776 /// GNU89 mode. 2777 static bool canRedefineFunction(const FunctionDecl *FD, 2778 const LangOptions& LangOpts) { 2779 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2780 !LangOpts.CPlusPlus && 2781 FD->isInlineSpecified() && 2782 FD->getStorageClass() == SC_Extern); 2783 } 2784 2785 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2786 const AttributedType *AT = T->getAs<AttributedType>(); 2787 while (AT && !AT->isCallingConv()) 2788 AT = AT->getModifiedType()->getAs<AttributedType>(); 2789 return AT; 2790 } 2791 2792 template <typename T> 2793 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2794 const DeclContext *DC = Old->getDeclContext(); 2795 if (DC->isRecord()) 2796 return false; 2797 2798 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2799 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2800 return true; 2801 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2802 return true; 2803 return false; 2804 } 2805 2806 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2807 static bool isExternC(VarTemplateDecl *) { return false; } 2808 2809 /// \brief Check whether a redeclaration of an entity introduced by a 2810 /// using-declaration is valid, given that we know it's not an overload 2811 /// (nor a hidden tag declaration). 2812 template<typename ExpectedDecl> 2813 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2814 ExpectedDecl *New) { 2815 // C++11 [basic.scope.declarative]p4: 2816 // Given a set of declarations in a single declarative region, each of 2817 // which specifies the same unqualified name, 2818 // -- they shall all refer to the same entity, or all refer to functions 2819 // and function templates; or 2820 // -- exactly one declaration shall declare a class name or enumeration 2821 // name that is not a typedef name and the other declarations shall all 2822 // refer to the same variable or enumerator, or all refer to functions 2823 // and function templates; in this case the class name or enumeration 2824 // name is hidden (3.3.10). 2825 2826 // C++11 [namespace.udecl]p14: 2827 // If a function declaration in namespace scope or block scope has the 2828 // same name and the same parameter-type-list as a function introduced 2829 // by a using-declaration, and the declarations do not declare the same 2830 // function, the program is ill-formed. 2831 2832 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2833 if (Old && 2834 !Old->getDeclContext()->getRedeclContext()->Equals( 2835 New->getDeclContext()->getRedeclContext()) && 2836 !(isExternC(Old) && isExternC(New))) 2837 Old = nullptr; 2838 2839 if (!Old) { 2840 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2841 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2842 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2843 return true; 2844 } 2845 return false; 2846 } 2847 2848 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2849 const FunctionDecl *B) { 2850 assert(A->getNumParams() == B->getNumParams()); 2851 2852 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2853 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2854 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2855 if (AttrA == AttrB) 2856 return true; 2857 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2858 }; 2859 2860 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2861 } 2862 2863 /// MergeFunctionDecl - We just parsed a function 'New' from 2864 /// declarator D which has the same name and scope as a previous 2865 /// declaration 'Old'. Figure out how to resolve this situation, 2866 /// merging decls or emitting diagnostics as appropriate. 2867 /// 2868 /// In C++, New and Old must be declarations that are not 2869 /// overloaded. Use IsOverload to determine whether New and Old are 2870 /// overloaded, and to select the Old declaration that New should be 2871 /// merged with. 2872 /// 2873 /// Returns true if there was an error, false otherwise. 2874 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2875 Scope *S, bool MergeTypeWithOld) { 2876 // Verify the old decl was also a function. 2877 FunctionDecl *Old = OldD->getAsFunction(); 2878 if (!Old) { 2879 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2880 if (New->getFriendObjectKind()) { 2881 Diag(New->getLocation(), diag::err_using_decl_friend); 2882 Diag(Shadow->getTargetDecl()->getLocation(), 2883 diag::note_using_decl_target); 2884 Diag(Shadow->getUsingDecl()->getLocation(), 2885 diag::note_using_decl) << 0; 2886 return true; 2887 } 2888 2889 // Check whether the two declarations might declare the same function. 2890 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2891 return true; 2892 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2893 } else { 2894 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2895 << New->getDeclName(); 2896 notePreviousDefinition(OldD, New->getLocation()); 2897 return true; 2898 } 2899 } 2900 2901 // If the old declaration is invalid, just give up here. 2902 if (Old->isInvalidDecl()) 2903 return true; 2904 2905 diag::kind PrevDiag; 2906 SourceLocation OldLocation; 2907 std::tie(PrevDiag, OldLocation) = 2908 getNoteDiagForInvalidRedeclaration(Old, New); 2909 2910 // Don't complain about this if we're in GNU89 mode and the old function 2911 // is an extern inline function. 2912 // Don't complain about specializations. They are not supposed to have 2913 // storage classes. 2914 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2915 New->getStorageClass() == SC_Static && 2916 Old->hasExternalFormalLinkage() && 2917 !New->getTemplateSpecializationInfo() && 2918 !canRedefineFunction(Old, getLangOpts())) { 2919 if (getLangOpts().MicrosoftExt) { 2920 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2921 Diag(OldLocation, PrevDiag); 2922 } else { 2923 Diag(New->getLocation(), diag::err_static_non_static) << New; 2924 Diag(OldLocation, PrevDiag); 2925 return true; 2926 } 2927 } 2928 2929 if (New->hasAttr<InternalLinkageAttr>() && 2930 !Old->hasAttr<InternalLinkageAttr>()) { 2931 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2932 << New->getDeclName(); 2933 notePreviousDefinition(Old, New->getLocation()); 2934 New->dropAttr<InternalLinkageAttr>(); 2935 } 2936 2937 if (!getLangOpts().CPlusPlus) { 2938 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 2939 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 2940 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 2941 << New << OldOvl; 2942 2943 // Try our best to find a decl that actually has the overloadable 2944 // attribute for the note. In most cases (e.g. programs with only one 2945 // broken declaration/definition), this won't matter. 2946 // 2947 // FIXME: We could do this if we juggled some extra state in 2948 // OverloadableAttr, rather than just removing it. 2949 const Decl *DiagOld = Old; 2950 if (OldOvl) { 2951 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 2952 const auto *A = D->getAttr<OverloadableAttr>(); 2953 return A && !A->isImplicit(); 2954 }); 2955 // If we've implicitly added *all* of the overloadable attrs to this 2956 // chain, emitting a "previous redecl" note is pointless. 2957 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 2958 } 2959 2960 if (DiagOld) 2961 Diag(DiagOld->getLocation(), 2962 diag::note_attribute_overloadable_prev_overload) 2963 << OldOvl; 2964 2965 if (OldOvl) 2966 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 2967 else 2968 New->dropAttr<OverloadableAttr>(); 2969 } 2970 } 2971 2972 // If a function is first declared with a calling convention, but is later 2973 // declared or defined without one, all following decls assume the calling 2974 // convention of the first. 2975 // 2976 // It's OK if a function is first declared without a calling convention, 2977 // but is later declared or defined with the default calling convention. 2978 // 2979 // To test if either decl has an explicit calling convention, we look for 2980 // AttributedType sugar nodes on the type as written. If they are missing or 2981 // were canonicalized away, we assume the calling convention was implicit. 2982 // 2983 // Note also that we DO NOT return at this point, because we still have 2984 // other tests to run. 2985 QualType OldQType = Context.getCanonicalType(Old->getType()); 2986 QualType NewQType = Context.getCanonicalType(New->getType()); 2987 const FunctionType *OldType = cast<FunctionType>(OldQType); 2988 const FunctionType *NewType = cast<FunctionType>(NewQType); 2989 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2990 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2991 bool RequiresAdjustment = false; 2992 2993 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2994 FunctionDecl *First = Old->getFirstDecl(); 2995 const FunctionType *FT = 2996 First->getType().getCanonicalType()->castAs<FunctionType>(); 2997 FunctionType::ExtInfo FI = FT->getExtInfo(); 2998 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2999 if (!NewCCExplicit) { 3000 // Inherit the CC from the previous declaration if it was specified 3001 // there but not here. 3002 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3003 RequiresAdjustment = true; 3004 } else { 3005 // Calling conventions aren't compatible, so complain. 3006 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3007 Diag(New->getLocation(), diag::err_cconv_change) 3008 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3009 << !FirstCCExplicit 3010 << (!FirstCCExplicit ? "" : 3011 FunctionType::getNameForCallConv(FI.getCC())); 3012 3013 // Put the note on the first decl, since it is the one that matters. 3014 Diag(First->getLocation(), diag::note_previous_declaration); 3015 return true; 3016 } 3017 } 3018 3019 // FIXME: diagnose the other way around? 3020 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3021 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3022 RequiresAdjustment = true; 3023 } 3024 3025 // Merge regparm attribute. 3026 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3027 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3028 if (NewTypeInfo.getHasRegParm()) { 3029 Diag(New->getLocation(), diag::err_regparm_mismatch) 3030 << NewType->getRegParmType() 3031 << OldType->getRegParmType(); 3032 Diag(OldLocation, diag::note_previous_declaration); 3033 return true; 3034 } 3035 3036 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3037 RequiresAdjustment = true; 3038 } 3039 3040 // Merge ns_returns_retained attribute. 3041 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3042 if (NewTypeInfo.getProducesResult()) { 3043 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3044 << "'ns_returns_retained'"; 3045 Diag(OldLocation, diag::note_previous_declaration); 3046 return true; 3047 } 3048 3049 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3050 RequiresAdjustment = true; 3051 } 3052 3053 if (OldTypeInfo.getNoCallerSavedRegs() != 3054 NewTypeInfo.getNoCallerSavedRegs()) { 3055 if (NewTypeInfo.getNoCallerSavedRegs()) { 3056 AnyX86NoCallerSavedRegistersAttr *Attr = 3057 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3058 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3059 Diag(OldLocation, diag::note_previous_declaration); 3060 return true; 3061 } 3062 3063 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3064 RequiresAdjustment = true; 3065 } 3066 3067 if (RequiresAdjustment) { 3068 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3069 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3070 New->setType(QualType(AdjustedType, 0)); 3071 NewQType = Context.getCanonicalType(New->getType()); 3072 NewType = cast<FunctionType>(NewQType); 3073 } 3074 3075 // If this redeclaration makes the function inline, we may need to add it to 3076 // UndefinedButUsed. 3077 if (!Old->isInlined() && New->isInlined() && 3078 !New->hasAttr<GNUInlineAttr>() && 3079 !getLangOpts().GNUInline && 3080 Old->isUsed(false) && 3081 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3082 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3083 SourceLocation())); 3084 3085 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3086 // about it. 3087 if (New->hasAttr<GNUInlineAttr>() && 3088 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3089 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3090 } 3091 3092 // If pass_object_size params don't match up perfectly, this isn't a valid 3093 // redeclaration. 3094 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3095 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3096 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3097 << New->getDeclName(); 3098 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3099 return true; 3100 } 3101 3102 if (getLangOpts().CPlusPlus) { 3103 // C++1z [over.load]p2 3104 // Certain function declarations cannot be overloaded: 3105 // -- Function declarations that differ only in the return type, 3106 // the exception specification, or both cannot be overloaded. 3107 3108 // Check the exception specifications match. This may recompute the type of 3109 // both Old and New if it resolved exception specifications, so grab the 3110 // types again after this. Because this updates the type, we do this before 3111 // any of the other checks below, which may update the "de facto" NewQType 3112 // but do not necessarily update the type of New. 3113 if (CheckEquivalentExceptionSpec(Old, New)) 3114 return true; 3115 OldQType = Context.getCanonicalType(Old->getType()); 3116 NewQType = Context.getCanonicalType(New->getType()); 3117 3118 // Go back to the type source info to compare the declared return types, 3119 // per C++1y [dcl.type.auto]p13: 3120 // Redeclarations or specializations of a function or function template 3121 // with a declared return type that uses a placeholder type shall also 3122 // use that placeholder, not a deduced type. 3123 QualType OldDeclaredReturnType = 3124 (Old->getTypeSourceInfo() 3125 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3126 : OldType)->getReturnType(); 3127 QualType NewDeclaredReturnType = 3128 (New->getTypeSourceInfo() 3129 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3130 : NewType)->getReturnType(); 3131 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3132 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3133 New->isLocalExternDecl())) { 3134 QualType ResQT; 3135 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3136 OldDeclaredReturnType->isObjCObjectPointerType()) 3137 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3138 if (ResQT.isNull()) { 3139 if (New->isCXXClassMember() && New->isOutOfLine()) 3140 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3141 << New << New->getReturnTypeSourceRange(); 3142 else 3143 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3144 << New->getReturnTypeSourceRange(); 3145 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3146 << Old->getReturnTypeSourceRange(); 3147 return true; 3148 } 3149 else 3150 NewQType = ResQT; 3151 } 3152 3153 QualType OldReturnType = OldType->getReturnType(); 3154 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3155 if (OldReturnType != NewReturnType) { 3156 // If this function has a deduced return type and has already been 3157 // defined, copy the deduced value from the old declaration. 3158 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3159 if (OldAT && OldAT->isDeduced()) { 3160 New->setType( 3161 SubstAutoType(New->getType(), 3162 OldAT->isDependentType() ? Context.DependentTy 3163 : OldAT->getDeducedType())); 3164 NewQType = Context.getCanonicalType( 3165 SubstAutoType(NewQType, 3166 OldAT->isDependentType() ? Context.DependentTy 3167 : OldAT->getDeducedType())); 3168 } 3169 } 3170 3171 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3172 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3173 if (OldMethod && NewMethod) { 3174 // Preserve triviality. 3175 NewMethod->setTrivial(OldMethod->isTrivial()); 3176 3177 // MSVC allows explicit template specialization at class scope: 3178 // 2 CXXMethodDecls referring to the same function will be injected. 3179 // We don't want a redeclaration error. 3180 bool IsClassScopeExplicitSpecialization = 3181 OldMethod->isFunctionTemplateSpecialization() && 3182 NewMethod->isFunctionTemplateSpecialization(); 3183 bool isFriend = NewMethod->getFriendObjectKind(); 3184 3185 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3186 !IsClassScopeExplicitSpecialization) { 3187 // -- Member function declarations with the same name and the 3188 // same parameter types cannot be overloaded if any of them 3189 // is a static member function declaration. 3190 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3191 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3192 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3193 return true; 3194 } 3195 3196 // C++ [class.mem]p1: 3197 // [...] A member shall not be declared twice in the 3198 // member-specification, except that a nested class or member 3199 // class template can be declared and then later defined. 3200 if (!inTemplateInstantiation()) { 3201 unsigned NewDiag; 3202 if (isa<CXXConstructorDecl>(OldMethod)) 3203 NewDiag = diag::err_constructor_redeclared; 3204 else if (isa<CXXDestructorDecl>(NewMethod)) 3205 NewDiag = diag::err_destructor_redeclared; 3206 else if (isa<CXXConversionDecl>(NewMethod)) 3207 NewDiag = diag::err_conv_function_redeclared; 3208 else 3209 NewDiag = diag::err_member_redeclared; 3210 3211 Diag(New->getLocation(), NewDiag); 3212 } else { 3213 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3214 << New << New->getType(); 3215 } 3216 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3217 return true; 3218 3219 // Complain if this is an explicit declaration of a special 3220 // member that was initially declared implicitly. 3221 // 3222 // As an exception, it's okay to befriend such methods in order 3223 // to permit the implicit constructor/destructor/operator calls. 3224 } else if (OldMethod->isImplicit()) { 3225 if (isFriend) { 3226 NewMethod->setImplicit(); 3227 } else { 3228 Diag(NewMethod->getLocation(), 3229 diag::err_definition_of_implicitly_declared_member) 3230 << New << getSpecialMember(OldMethod); 3231 return true; 3232 } 3233 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3234 Diag(NewMethod->getLocation(), 3235 diag::err_definition_of_explicitly_defaulted_member) 3236 << getSpecialMember(OldMethod); 3237 return true; 3238 } 3239 } 3240 3241 // C++11 [dcl.attr.noreturn]p1: 3242 // The first declaration of a function shall specify the noreturn 3243 // attribute if any declaration of that function specifies the noreturn 3244 // attribute. 3245 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3246 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3247 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3248 Diag(Old->getFirstDecl()->getLocation(), 3249 diag::note_noreturn_missing_first_decl); 3250 } 3251 3252 // C++11 [dcl.attr.depend]p2: 3253 // The first declaration of a function shall specify the 3254 // carries_dependency attribute for its declarator-id if any declaration 3255 // of the function specifies the carries_dependency attribute. 3256 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3257 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3258 Diag(CDA->getLocation(), 3259 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3260 Diag(Old->getFirstDecl()->getLocation(), 3261 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3262 } 3263 3264 // (C++98 8.3.5p3): 3265 // All declarations for a function shall agree exactly in both the 3266 // return type and the parameter-type-list. 3267 // We also want to respect all the extended bits except noreturn. 3268 3269 // noreturn should now match unless the old type info didn't have it. 3270 QualType OldQTypeForComparison = OldQType; 3271 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3272 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3273 const FunctionType *OldTypeForComparison 3274 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3275 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3276 assert(OldQTypeForComparison.isCanonical()); 3277 } 3278 3279 if (haveIncompatibleLanguageLinkages(Old, New)) { 3280 // As a special case, retain the language linkage from previous 3281 // declarations of a friend function as an extension. 3282 // 3283 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3284 // and is useful because there's otherwise no way to specify language 3285 // linkage within class scope. 3286 // 3287 // Check cautiously as the friend object kind isn't yet complete. 3288 if (New->getFriendObjectKind() != Decl::FOK_None) { 3289 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3290 Diag(OldLocation, PrevDiag); 3291 } else { 3292 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3293 Diag(OldLocation, PrevDiag); 3294 return true; 3295 } 3296 } 3297 3298 if (OldQTypeForComparison == NewQType) 3299 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3300 3301 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3302 New->isLocalExternDecl()) { 3303 // It's OK if we couldn't merge types for a local function declaraton 3304 // if either the old or new type is dependent. We'll merge the types 3305 // when we instantiate the function. 3306 return false; 3307 } 3308 3309 // Fall through for conflicting redeclarations and redefinitions. 3310 } 3311 3312 // C: Function types need to be compatible, not identical. This handles 3313 // duplicate function decls like "void f(int); void f(enum X);" properly. 3314 if (!getLangOpts().CPlusPlus && 3315 Context.typesAreCompatible(OldQType, NewQType)) { 3316 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3317 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3318 const FunctionProtoType *OldProto = nullptr; 3319 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3320 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3321 // The old declaration provided a function prototype, but the 3322 // new declaration does not. Merge in the prototype. 3323 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3324 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3325 NewQType = 3326 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3327 OldProto->getExtProtoInfo()); 3328 New->setType(NewQType); 3329 New->setHasInheritedPrototype(); 3330 3331 // Synthesize parameters with the same types. 3332 SmallVector<ParmVarDecl*, 16> Params; 3333 for (const auto &ParamType : OldProto->param_types()) { 3334 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3335 SourceLocation(), nullptr, 3336 ParamType, /*TInfo=*/nullptr, 3337 SC_None, nullptr); 3338 Param->setScopeInfo(0, Params.size()); 3339 Param->setImplicit(); 3340 Params.push_back(Param); 3341 } 3342 3343 New->setParams(Params); 3344 } 3345 3346 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3347 } 3348 3349 // GNU C permits a K&R definition to follow a prototype declaration 3350 // if the declared types of the parameters in the K&R definition 3351 // match the types in the prototype declaration, even when the 3352 // promoted types of the parameters from the K&R definition differ 3353 // from the types in the prototype. GCC then keeps the types from 3354 // the prototype. 3355 // 3356 // If a variadic prototype is followed by a non-variadic K&R definition, 3357 // the K&R definition becomes variadic. This is sort of an edge case, but 3358 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3359 // C99 6.9.1p8. 3360 if (!getLangOpts().CPlusPlus && 3361 Old->hasPrototype() && !New->hasPrototype() && 3362 New->getType()->getAs<FunctionProtoType>() && 3363 Old->getNumParams() == New->getNumParams()) { 3364 SmallVector<QualType, 16> ArgTypes; 3365 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3366 const FunctionProtoType *OldProto 3367 = Old->getType()->getAs<FunctionProtoType>(); 3368 const FunctionProtoType *NewProto 3369 = New->getType()->getAs<FunctionProtoType>(); 3370 3371 // Determine whether this is the GNU C extension. 3372 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3373 NewProto->getReturnType()); 3374 bool LooseCompatible = !MergedReturn.isNull(); 3375 for (unsigned Idx = 0, End = Old->getNumParams(); 3376 LooseCompatible && Idx != End; ++Idx) { 3377 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3378 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3379 if (Context.typesAreCompatible(OldParm->getType(), 3380 NewProto->getParamType(Idx))) { 3381 ArgTypes.push_back(NewParm->getType()); 3382 } else if (Context.typesAreCompatible(OldParm->getType(), 3383 NewParm->getType(), 3384 /*CompareUnqualified=*/true)) { 3385 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3386 NewProto->getParamType(Idx) }; 3387 Warnings.push_back(Warn); 3388 ArgTypes.push_back(NewParm->getType()); 3389 } else 3390 LooseCompatible = false; 3391 } 3392 3393 if (LooseCompatible) { 3394 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3395 Diag(Warnings[Warn].NewParm->getLocation(), 3396 diag::ext_param_promoted_not_compatible_with_prototype) 3397 << Warnings[Warn].PromotedType 3398 << Warnings[Warn].OldParm->getType(); 3399 if (Warnings[Warn].OldParm->getLocation().isValid()) 3400 Diag(Warnings[Warn].OldParm->getLocation(), 3401 diag::note_previous_declaration); 3402 } 3403 3404 if (MergeTypeWithOld) 3405 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3406 OldProto->getExtProtoInfo())); 3407 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3408 } 3409 3410 // Fall through to diagnose conflicting types. 3411 } 3412 3413 // A function that has already been declared has been redeclared or 3414 // defined with a different type; show an appropriate diagnostic. 3415 3416 // If the previous declaration was an implicitly-generated builtin 3417 // declaration, then at the very least we should use a specialized note. 3418 unsigned BuiltinID; 3419 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3420 // If it's actually a library-defined builtin function like 'malloc' 3421 // or 'printf', just warn about the incompatible redeclaration. 3422 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3423 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3424 Diag(OldLocation, diag::note_previous_builtin_declaration) 3425 << Old << Old->getType(); 3426 3427 // If this is a global redeclaration, just forget hereafter 3428 // about the "builtin-ness" of the function. 3429 // 3430 // Doing this for local extern declarations is problematic. If 3431 // the builtin declaration remains visible, a second invalid 3432 // local declaration will produce a hard error; if it doesn't 3433 // remain visible, a single bogus local redeclaration (which is 3434 // actually only a warning) could break all the downstream code. 3435 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3436 New->getIdentifier()->revertBuiltin(); 3437 3438 return false; 3439 } 3440 3441 PrevDiag = diag::note_previous_builtin_declaration; 3442 } 3443 3444 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3445 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3446 return true; 3447 } 3448 3449 /// \brief Completes the merge of two function declarations that are 3450 /// known to be compatible. 3451 /// 3452 /// This routine handles the merging of attributes and other 3453 /// properties of function declarations from the old declaration to 3454 /// the new declaration, once we know that New is in fact a 3455 /// redeclaration of Old. 3456 /// 3457 /// \returns false 3458 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3459 Scope *S, bool MergeTypeWithOld) { 3460 // Merge the attributes 3461 mergeDeclAttributes(New, Old); 3462 3463 // Merge "pure" flag. 3464 if (Old->isPure()) 3465 New->setPure(); 3466 3467 // Merge "used" flag. 3468 if (Old->getMostRecentDecl()->isUsed(false)) 3469 New->setIsUsed(); 3470 3471 // Merge attributes from the parameters. These can mismatch with K&R 3472 // declarations. 3473 if (New->getNumParams() == Old->getNumParams()) 3474 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3475 ParmVarDecl *NewParam = New->getParamDecl(i); 3476 ParmVarDecl *OldParam = Old->getParamDecl(i); 3477 mergeParamDeclAttributes(NewParam, OldParam, *this); 3478 mergeParamDeclTypes(NewParam, OldParam, *this); 3479 } 3480 3481 if (getLangOpts().CPlusPlus) 3482 return MergeCXXFunctionDecl(New, Old, S); 3483 3484 // Merge the function types so the we get the composite types for the return 3485 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3486 // was visible. 3487 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3488 if (!Merged.isNull() && MergeTypeWithOld) 3489 New->setType(Merged); 3490 3491 return false; 3492 } 3493 3494 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3495 ObjCMethodDecl *oldMethod) { 3496 // Merge the attributes, including deprecated/unavailable 3497 AvailabilityMergeKind MergeKind = 3498 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3499 ? AMK_ProtocolImplementation 3500 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3501 : AMK_Override; 3502 3503 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3504 3505 // Merge attributes from the parameters. 3506 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3507 oe = oldMethod->param_end(); 3508 for (ObjCMethodDecl::param_iterator 3509 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3510 ni != ne && oi != oe; ++ni, ++oi) 3511 mergeParamDeclAttributes(*ni, *oi, *this); 3512 3513 CheckObjCMethodOverride(newMethod, oldMethod); 3514 } 3515 3516 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3517 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3518 3519 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3520 ? diag::err_redefinition_different_type 3521 : diag::err_redeclaration_different_type) 3522 << New->getDeclName() << New->getType() << Old->getType(); 3523 3524 diag::kind PrevDiag; 3525 SourceLocation OldLocation; 3526 std::tie(PrevDiag, OldLocation) 3527 = getNoteDiagForInvalidRedeclaration(Old, New); 3528 S.Diag(OldLocation, PrevDiag); 3529 New->setInvalidDecl(); 3530 } 3531 3532 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3533 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3534 /// emitting diagnostics as appropriate. 3535 /// 3536 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3537 /// to here in AddInitializerToDecl. We can't check them before the initializer 3538 /// is attached. 3539 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3540 bool MergeTypeWithOld) { 3541 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3542 return; 3543 3544 QualType MergedT; 3545 if (getLangOpts().CPlusPlus) { 3546 if (New->getType()->isUndeducedType()) { 3547 // We don't know what the new type is until the initializer is attached. 3548 return; 3549 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3550 // These could still be something that needs exception specs checked. 3551 return MergeVarDeclExceptionSpecs(New, Old); 3552 } 3553 // C++ [basic.link]p10: 3554 // [...] the types specified by all declarations referring to a given 3555 // object or function shall be identical, except that declarations for an 3556 // array object can specify array types that differ by the presence or 3557 // absence of a major array bound (8.3.4). 3558 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3559 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3560 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3561 3562 // We are merging a variable declaration New into Old. If it has an array 3563 // bound, and that bound differs from Old's bound, we should diagnose the 3564 // mismatch. 3565 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3566 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3567 PrevVD = PrevVD->getPreviousDecl()) { 3568 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3569 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3570 continue; 3571 3572 if (!Context.hasSameType(NewArray, PrevVDTy)) 3573 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3574 } 3575 } 3576 3577 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3578 if (Context.hasSameType(OldArray->getElementType(), 3579 NewArray->getElementType())) 3580 MergedT = New->getType(); 3581 } 3582 // FIXME: Check visibility. New is hidden but has a complete type. If New 3583 // has no array bound, it should not inherit one from Old, if Old is not 3584 // visible. 3585 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3586 if (Context.hasSameType(OldArray->getElementType(), 3587 NewArray->getElementType())) 3588 MergedT = Old->getType(); 3589 } 3590 } 3591 else if (New->getType()->isObjCObjectPointerType() && 3592 Old->getType()->isObjCObjectPointerType()) { 3593 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3594 Old->getType()); 3595 } 3596 } else { 3597 // C 6.2.7p2: 3598 // All declarations that refer to the same object or function shall have 3599 // compatible type. 3600 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3601 } 3602 if (MergedT.isNull()) { 3603 // It's OK if we couldn't merge types if either type is dependent, for a 3604 // block-scope variable. In other cases (static data members of class 3605 // templates, variable templates, ...), we require the types to be 3606 // equivalent. 3607 // FIXME: The C++ standard doesn't say anything about this. 3608 if ((New->getType()->isDependentType() || 3609 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3610 // If the old type was dependent, we can't merge with it, so the new type 3611 // becomes dependent for now. We'll reproduce the original type when we 3612 // instantiate the TypeSourceInfo for the variable. 3613 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3614 New->setType(Context.DependentTy); 3615 return; 3616 } 3617 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3618 } 3619 3620 // Don't actually update the type on the new declaration if the old 3621 // declaration was an extern declaration in a different scope. 3622 if (MergeTypeWithOld) 3623 New->setType(MergedT); 3624 } 3625 3626 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3627 LookupResult &Previous) { 3628 // C11 6.2.7p4: 3629 // For an identifier with internal or external linkage declared 3630 // in a scope in which a prior declaration of that identifier is 3631 // visible, if the prior declaration specifies internal or 3632 // external linkage, the type of the identifier at the later 3633 // declaration becomes the composite type. 3634 // 3635 // If the variable isn't visible, we do not merge with its type. 3636 if (Previous.isShadowed()) 3637 return false; 3638 3639 if (S.getLangOpts().CPlusPlus) { 3640 // C++11 [dcl.array]p3: 3641 // If there is a preceding declaration of the entity in the same 3642 // scope in which the bound was specified, an omitted array bound 3643 // is taken to be the same as in that earlier declaration. 3644 return NewVD->isPreviousDeclInSameBlockScope() || 3645 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3646 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3647 } else { 3648 // If the old declaration was function-local, don't merge with its 3649 // type unless we're in the same function. 3650 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3651 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3652 } 3653 } 3654 3655 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3656 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3657 /// situation, merging decls or emitting diagnostics as appropriate. 3658 /// 3659 /// Tentative definition rules (C99 6.9.2p2) are checked by 3660 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3661 /// definitions here, since the initializer hasn't been attached. 3662 /// 3663 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3664 // If the new decl is already invalid, don't do any other checking. 3665 if (New->isInvalidDecl()) 3666 return; 3667 3668 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3669 return; 3670 3671 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3672 3673 // Verify the old decl was also a variable or variable template. 3674 VarDecl *Old = nullptr; 3675 VarTemplateDecl *OldTemplate = nullptr; 3676 if (Previous.isSingleResult()) { 3677 if (NewTemplate) { 3678 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3679 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3680 3681 if (auto *Shadow = 3682 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3683 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3684 return New->setInvalidDecl(); 3685 } else { 3686 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3687 3688 if (auto *Shadow = 3689 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3690 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3691 return New->setInvalidDecl(); 3692 } 3693 } 3694 if (!Old) { 3695 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3696 << New->getDeclName(); 3697 notePreviousDefinition(Previous.getRepresentativeDecl(), 3698 New->getLocation()); 3699 return New->setInvalidDecl(); 3700 } 3701 3702 // Ensure the template parameters are compatible. 3703 if (NewTemplate && 3704 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3705 OldTemplate->getTemplateParameters(), 3706 /*Complain=*/true, TPL_TemplateMatch)) 3707 return New->setInvalidDecl(); 3708 3709 // C++ [class.mem]p1: 3710 // A member shall not be declared twice in the member-specification [...] 3711 // 3712 // Here, we need only consider static data members. 3713 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3714 Diag(New->getLocation(), diag::err_duplicate_member) 3715 << New->getIdentifier(); 3716 Diag(Old->getLocation(), diag::note_previous_declaration); 3717 New->setInvalidDecl(); 3718 } 3719 3720 mergeDeclAttributes(New, Old); 3721 // Warn if an already-declared variable is made a weak_import in a subsequent 3722 // declaration 3723 if (New->hasAttr<WeakImportAttr>() && 3724 Old->getStorageClass() == SC_None && 3725 !Old->hasAttr<WeakImportAttr>()) { 3726 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3727 notePreviousDefinition(Old, New->getLocation()); 3728 // Remove weak_import attribute on new declaration. 3729 New->dropAttr<WeakImportAttr>(); 3730 } 3731 3732 if (New->hasAttr<InternalLinkageAttr>() && 3733 !Old->hasAttr<InternalLinkageAttr>()) { 3734 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3735 << New->getDeclName(); 3736 notePreviousDefinition(Old, New->getLocation()); 3737 New->dropAttr<InternalLinkageAttr>(); 3738 } 3739 3740 // Merge the types. 3741 VarDecl *MostRecent = Old->getMostRecentDecl(); 3742 if (MostRecent != Old) { 3743 MergeVarDeclTypes(New, MostRecent, 3744 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3745 if (New->isInvalidDecl()) 3746 return; 3747 } 3748 3749 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3750 if (New->isInvalidDecl()) 3751 return; 3752 3753 diag::kind PrevDiag; 3754 SourceLocation OldLocation; 3755 std::tie(PrevDiag, OldLocation) = 3756 getNoteDiagForInvalidRedeclaration(Old, New); 3757 3758 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3759 if (New->getStorageClass() == SC_Static && 3760 !New->isStaticDataMember() && 3761 Old->hasExternalFormalLinkage()) { 3762 if (getLangOpts().MicrosoftExt) { 3763 Diag(New->getLocation(), diag::ext_static_non_static) 3764 << New->getDeclName(); 3765 Diag(OldLocation, PrevDiag); 3766 } else { 3767 Diag(New->getLocation(), diag::err_static_non_static) 3768 << New->getDeclName(); 3769 Diag(OldLocation, PrevDiag); 3770 return New->setInvalidDecl(); 3771 } 3772 } 3773 // C99 6.2.2p4: 3774 // For an identifier declared with the storage-class specifier 3775 // extern in a scope in which a prior declaration of that 3776 // identifier is visible,23) if the prior declaration specifies 3777 // internal or external linkage, the linkage of the identifier at 3778 // the later declaration is the same as the linkage specified at 3779 // the prior declaration. If no prior declaration is visible, or 3780 // if the prior declaration specifies no linkage, then the 3781 // identifier has external linkage. 3782 if (New->hasExternalStorage() && Old->hasLinkage()) 3783 /* Okay */; 3784 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3785 !New->isStaticDataMember() && 3786 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3787 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3788 Diag(OldLocation, PrevDiag); 3789 return New->setInvalidDecl(); 3790 } 3791 3792 // Check if extern is followed by non-extern and vice-versa. 3793 if (New->hasExternalStorage() && 3794 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3795 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3796 Diag(OldLocation, PrevDiag); 3797 return New->setInvalidDecl(); 3798 } 3799 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3800 !New->hasExternalStorage()) { 3801 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag); 3803 return New->setInvalidDecl(); 3804 } 3805 3806 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3807 3808 // FIXME: The test for external storage here seems wrong? We still 3809 // need to check for mismatches. 3810 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3811 // Don't complain about out-of-line definitions of static members. 3812 !(Old->getLexicalDeclContext()->isRecord() && 3813 !New->getLexicalDeclContext()->isRecord())) { 3814 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3815 Diag(OldLocation, PrevDiag); 3816 return New->setInvalidDecl(); 3817 } 3818 3819 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3820 if (VarDecl *Def = Old->getDefinition()) { 3821 // C++1z [dcl.fcn.spec]p4: 3822 // If the definition of a variable appears in a translation unit before 3823 // its first declaration as inline, the program is ill-formed. 3824 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3825 Diag(Def->getLocation(), diag::note_previous_definition); 3826 } 3827 } 3828 3829 // If this redeclaration makes the function inline, we may need to add it to 3830 // UndefinedButUsed. 3831 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3832 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3833 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3834 SourceLocation())); 3835 3836 if (New->getTLSKind() != Old->getTLSKind()) { 3837 if (!Old->getTLSKind()) { 3838 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3839 Diag(OldLocation, PrevDiag); 3840 } else if (!New->getTLSKind()) { 3841 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3842 Diag(OldLocation, PrevDiag); 3843 } else { 3844 // Do not allow redeclaration to change the variable between requiring 3845 // static and dynamic initialization. 3846 // FIXME: GCC allows this, but uses the TLS keyword on the first 3847 // declaration to determine the kind. Do we need to be compatible here? 3848 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3849 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3850 Diag(OldLocation, PrevDiag); 3851 } 3852 } 3853 3854 // C++ doesn't have tentative definitions, so go right ahead and check here. 3855 if (getLangOpts().CPlusPlus && 3856 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3857 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3858 Old->getCanonicalDecl()->isConstexpr()) { 3859 // This definition won't be a definition any more once it's been merged. 3860 Diag(New->getLocation(), 3861 diag::warn_deprecated_redundant_constexpr_static_def); 3862 } else if (VarDecl *Def = Old->getDefinition()) { 3863 if (checkVarDeclRedefinition(Def, New)) 3864 return; 3865 } 3866 } 3867 3868 if (haveIncompatibleLanguageLinkages(Old, New)) { 3869 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3870 Diag(OldLocation, PrevDiag); 3871 New->setInvalidDecl(); 3872 return; 3873 } 3874 3875 // Merge "used" flag. 3876 if (Old->getMostRecentDecl()->isUsed(false)) 3877 New->setIsUsed(); 3878 3879 // Keep a chain of previous declarations. 3880 New->setPreviousDecl(Old); 3881 if (NewTemplate) 3882 NewTemplate->setPreviousDecl(OldTemplate); 3883 3884 // Inherit access appropriately. 3885 New->setAccess(Old->getAccess()); 3886 if (NewTemplate) 3887 NewTemplate->setAccess(New->getAccess()); 3888 3889 if (Old->isInline()) 3890 New->setImplicitlyInline(); 3891 } 3892 3893 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 3894 SourceManager &SrcMgr = getSourceManager(); 3895 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3896 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3897 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3898 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3899 auto &HSI = PP.getHeaderSearchInfo(); 3900 StringRef HdrFilename = 3901 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3902 3903 auto noteFromModuleOrInclude = [&](Module *Mod, 3904 SourceLocation IncLoc) -> bool { 3905 // Redefinition errors with modules are common with non modular mapped 3906 // headers, example: a non-modular header H in module A that also gets 3907 // included directly in a TU. Pointing twice to the same header/definition 3908 // is confusing, try to get better diagnostics when modules is on. 3909 if (IncLoc.isValid()) { 3910 if (Mod) { 3911 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3912 << HdrFilename.str() << Mod->getFullModuleName(); 3913 if (!Mod->DefinitionLoc.isInvalid()) 3914 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3915 << Mod->getFullModuleName(); 3916 } else { 3917 Diag(IncLoc, diag::note_redefinition_include_same_file) 3918 << HdrFilename.str(); 3919 } 3920 return true; 3921 } 3922 3923 return false; 3924 }; 3925 3926 // Is it the same file and same offset? Provide more information on why 3927 // this leads to a redefinition error. 3928 bool EmittedDiag = false; 3929 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3930 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3931 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3932 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 3933 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 3934 3935 // If the header has no guards, emit a note suggesting one. 3936 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3937 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 3938 3939 if (EmittedDiag) 3940 return; 3941 } 3942 3943 // Redefinition coming from different files or couldn't do better above. 3944 Diag(Old->getLocation(), diag::note_previous_definition); 3945 } 3946 3947 /// We've just determined that \p Old and \p New both appear to be definitions 3948 /// of the same variable. Either diagnose or fix the problem. 3949 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3950 if (!hasVisibleDefinition(Old) && 3951 (New->getFormalLinkage() == InternalLinkage || 3952 New->isInline() || 3953 New->getDescribedVarTemplate() || 3954 New->getNumTemplateParameterLists() || 3955 New->getDeclContext()->isDependentContext())) { 3956 // The previous definition is hidden, and multiple definitions are 3957 // permitted (in separate TUs). Demote this to a declaration. 3958 New->demoteThisDefinitionToDeclaration(); 3959 3960 // Make the canonical definition visible. 3961 if (auto *OldTD = Old->getDescribedVarTemplate()) 3962 makeMergedDefinitionVisible(OldTD); 3963 makeMergedDefinitionVisible(Old); 3964 return false; 3965 } else { 3966 Diag(New->getLocation(), diag::err_redefinition) << New; 3967 notePreviousDefinition(Old, New->getLocation()); 3968 New->setInvalidDecl(); 3969 return true; 3970 } 3971 } 3972 3973 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3974 /// no declarator (e.g. "struct foo;") is parsed. 3975 Decl * 3976 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3977 RecordDecl *&AnonRecord) { 3978 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3979 AnonRecord); 3980 } 3981 3982 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3983 // disambiguate entities defined in different scopes. 3984 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3985 // compatibility. 3986 // We will pick our mangling number depending on which version of MSVC is being 3987 // targeted. 3988 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3989 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3990 ? S->getMSCurManglingNumber() 3991 : S->getMSLastManglingNumber(); 3992 } 3993 3994 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3995 if (!Context.getLangOpts().CPlusPlus) 3996 return; 3997 3998 if (isa<CXXRecordDecl>(Tag->getParent())) { 3999 // If this tag is the direct child of a class, number it if 4000 // it is anonymous. 4001 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4002 return; 4003 MangleNumberingContext &MCtx = 4004 Context.getManglingNumberContext(Tag->getParent()); 4005 Context.setManglingNumber( 4006 Tag, MCtx.getManglingNumber( 4007 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4008 return; 4009 } 4010 4011 // If this tag isn't a direct child of a class, number it if it is local. 4012 Decl *ManglingContextDecl; 4013 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4014 Tag->getDeclContext(), ManglingContextDecl)) { 4015 Context.setManglingNumber( 4016 Tag, MCtx->getManglingNumber( 4017 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4018 } 4019 } 4020 4021 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4022 TypedefNameDecl *NewTD) { 4023 if (TagFromDeclSpec->isInvalidDecl()) 4024 return; 4025 4026 // Do nothing if the tag already has a name for linkage purposes. 4027 if (TagFromDeclSpec->hasNameForLinkage()) 4028 return; 4029 4030 // A well-formed anonymous tag must always be a TUK_Definition. 4031 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4032 4033 // The type must match the tag exactly; no qualifiers allowed. 4034 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4035 Context.getTagDeclType(TagFromDeclSpec))) { 4036 if (getLangOpts().CPlusPlus) 4037 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4038 return; 4039 } 4040 4041 // If we've already computed linkage for the anonymous tag, then 4042 // adding a typedef name for the anonymous decl can change that 4043 // linkage, which might be a serious problem. Diagnose this as 4044 // unsupported and ignore the typedef name. TODO: we should 4045 // pursue this as a language defect and establish a formal rule 4046 // for how to handle it. 4047 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4048 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4049 4050 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4051 tagLoc = getLocForEndOfToken(tagLoc); 4052 4053 llvm::SmallString<40> textToInsert; 4054 textToInsert += ' '; 4055 textToInsert += NewTD->getIdentifier()->getName(); 4056 Diag(tagLoc, diag::note_typedef_changes_linkage) 4057 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4058 return; 4059 } 4060 4061 // Otherwise, set this is the anon-decl typedef for the tag. 4062 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4063 } 4064 4065 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4066 switch (T) { 4067 case DeclSpec::TST_class: 4068 return 0; 4069 case DeclSpec::TST_struct: 4070 return 1; 4071 case DeclSpec::TST_interface: 4072 return 2; 4073 case DeclSpec::TST_union: 4074 return 3; 4075 case DeclSpec::TST_enum: 4076 return 4; 4077 default: 4078 llvm_unreachable("unexpected type specifier"); 4079 } 4080 } 4081 4082 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4083 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4084 /// parameters to cope with template friend declarations. 4085 Decl * 4086 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4087 MultiTemplateParamsArg TemplateParams, 4088 bool IsExplicitInstantiation, 4089 RecordDecl *&AnonRecord) { 4090 Decl *TagD = nullptr; 4091 TagDecl *Tag = nullptr; 4092 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4093 DS.getTypeSpecType() == DeclSpec::TST_struct || 4094 DS.getTypeSpecType() == DeclSpec::TST_interface || 4095 DS.getTypeSpecType() == DeclSpec::TST_union || 4096 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4097 TagD = DS.getRepAsDecl(); 4098 4099 if (!TagD) // We probably had an error 4100 return nullptr; 4101 4102 // Note that the above type specs guarantee that the 4103 // type rep is a Decl, whereas in many of the others 4104 // it's a Type. 4105 if (isa<TagDecl>(TagD)) 4106 Tag = cast<TagDecl>(TagD); 4107 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4108 Tag = CTD->getTemplatedDecl(); 4109 } 4110 4111 if (Tag) { 4112 handleTagNumbering(Tag, S); 4113 Tag->setFreeStanding(); 4114 if (Tag->isInvalidDecl()) 4115 return Tag; 4116 } 4117 4118 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4119 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4120 // or incomplete types shall not be restrict-qualified." 4121 if (TypeQuals & DeclSpec::TQ_restrict) 4122 Diag(DS.getRestrictSpecLoc(), 4123 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4124 << DS.getSourceRange(); 4125 } 4126 4127 if (DS.isInlineSpecified()) 4128 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4129 << getLangOpts().CPlusPlus1z; 4130 4131 if (DS.isConstexprSpecified()) { 4132 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4133 // and definitions of functions and variables. 4134 if (Tag) 4135 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4136 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4137 else 4138 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4139 // Don't emit warnings after this error. 4140 return TagD; 4141 } 4142 4143 if (DS.isConceptSpecified()) { 4144 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4145 // either a function concept and its definition or a variable concept and 4146 // its initializer. 4147 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4148 return TagD; 4149 } 4150 4151 DiagnoseFunctionSpecifiers(DS); 4152 4153 if (DS.isFriendSpecified()) { 4154 // If we're dealing with a decl but not a TagDecl, assume that 4155 // whatever routines created it handled the friendship aspect. 4156 if (TagD && !Tag) 4157 return nullptr; 4158 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4159 } 4160 4161 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4162 bool IsExplicitSpecialization = 4163 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4164 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4165 !IsExplicitInstantiation && !IsExplicitSpecialization && 4166 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4167 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4168 // nested-name-specifier unless it is an explicit instantiation 4169 // or an explicit specialization. 4170 // 4171 // FIXME: We allow class template partial specializations here too, per the 4172 // obvious intent of DR1819. 4173 // 4174 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4175 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4176 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4177 return nullptr; 4178 } 4179 4180 // Track whether this decl-specifier declares anything. 4181 bool DeclaresAnything = true; 4182 4183 // Handle anonymous struct definitions. 4184 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4185 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4186 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4187 if (getLangOpts().CPlusPlus || 4188 Record->getDeclContext()->isRecord()) { 4189 // If CurContext is a DeclContext that can contain statements, 4190 // RecursiveASTVisitor won't visit the decls that 4191 // BuildAnonymousStructOrUnion() will put into CurContext. 4192 // Also store them here so that they can be part of the 4193 // DeclStmt that gets created in this case. 4194 // FIXME: Also return the IndirectFieldDecls created by 4195 // BuildAnonymousStructOr union, for the same reason? 4196 if (CurContext->isFunctionOrMethod()) 4197 AnonRecord = Record; 4198 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4199 Context.getPrintingPolicy()); 4200 } 4201 4202 DeclaresAnything = false; 4203 } 4204 } 4205 4206 // C11 6.7.2.1p2: 4207 // A struct-declaration that does not declare an anonymous structure or 4208 // anonymous union shall contain a struct-declarator-list. 4209 // 4210 // This rule also existed in C89 and C99; the grammar for struct-declaration 4211 // did not permit a struct-declaration without a struct-declarator-list. 4212 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4213 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4214 // Check for Microsoft C extension: anonymous struct/union member. 4215 // Handle 2 kinds of anonymous struct/union: 4216 // struct STRUCT; 4217 // union UNION; 4218 // and 4219 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4220 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4221 if ((Tag && Tag->getDeclName()) || 4222 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4223 RecordDecl *Record = nullptr; 4224 if (Tag) 4225 Record = dyn_cast<RecordDecl>(Tag); 4226 else if (const RecordType *RT = 4227 DS.getRepAsType().get()->getAsStructureType()) 4228 Record = RT->getDecl(); 4229 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4230 Record = UT->getDecl(); 4231 4232 if (Record && getLangOpts().MicrosoftExt) { 4233 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4234 << Record->isUnion() << DS.getSourceRange(); 4235 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4236 } 4237 4238 DeclaresAnything = false; 4239 } 4240 } 4241 4242 // Skip all the checks below if we have a type error. 4243 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4244 (TagD && TagD->isInvalidDecl())) 4245 return TagD; 4246 4247 if (getLangOpts().CPlusPlus && 4248 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4249 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4250 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4251 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4252 DeclaresAnything = false; 4253 4254 if (!DS.isMissingDeclaratorOk()) { 4255 // Customize diagnostic for a typedef missing a name. 4256 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4257 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4258 << DS.getSourceRange(); 4259 else 4260 DeclaresAnything = false; 4261 } 4262 4263 if (DS.isModulePrivateSpecified() && 4264 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4265 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4266 << Tag->getTagKind() 4267 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4268 4269 ActOnDocumentableDecl(TagD); 4270 4271 // C 6.7/2: 4272 // A declaration [...] shall declare at least a declarator [...], a tag, 4273 // or the members of an enumeration. 4274 // C++ [dcl.dcl]p3: 4275 // [If there are no declarators], and except for the declaration of an 4276 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4277 // names into the program, or shall redeclare a name introduced by a 4278 // previous declaration. 4279 if (!DeclaresAnything) { 4280 // In C, we allow this as a (popular) extension / bug. Don't bother 4281 // producing further diagnostics for redundant qualifiers after this. 4282 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4283 return TagD; 4284 } 4285 4286 // C++ [dcl.stc]p1: 4287 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4288 // init-declarator-list of the declaration shall not be empty. 4289 // C++ [dcl.fct.spec]p1: 4290 // If a cv-qualifier appears in a decl-specifier-seq, the 4291 // init-declarator-list of the declaration shall not be empty. 4292 // 4293 // Spurious qualifiers here appear to be valid in C. 4294 unsigned DiagID = diag::warn_standalone_specifier; 4295 if (getLangOpts().CPlusPlus) 4296 DiagID = diag::ext_standalone_specifier; 4297 4298 // Note that a linkage-specification sets a storage class, but 4299 // 'extern "C" struct foo;' is actually valid and not theoretically 4300 // useless. 4301 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4302 if (SCS == DeclSpec::SCS_mutable) 4303 // Since mutable is not a viable storage class specifier in C, there is 4304 // no reason to treat it as an extension. Instead, diagnose as an error. 4305 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4306 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4307 Diag(DS.getStorageClassSpecLoc(), DiagID) 4308 << DeclSpec::getSpecifierName(SCS); 4309 } 4310 4311 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4312 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4313 << DeclSpec::getSpecifierName(TSCS); 4314 if (DS.getTypeQualifiers()) { 4315 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4316 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4317 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4318 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4319 // Restrict is covered above. 4320 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4321 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4322 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4323 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4324 } 4325 4326 // Warn about ignored type attributes, for example: 4327 // __attribute__((aligned)) struct A; 4328 // Attributes should be placed after tag to apply to type declaration. 4329 if (!DS.getAttributes().empty()) { 4330 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4331 if (TypeSpecType == DeclSpec::TST_class || 4332 TypeSpecType == DeclSpec::TST_struct || 4333 TypeSpecType == DeclSpec::TST_interface || 4334 TypeSpecType == DeclSpec::TST_union || 4335 TypeSpecType == DeclSpec::TST_enum) { 4336 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4337 attrs = attrs->getNext()) 4338 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4339 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4340 } 4341 } 4342 4343 return TagD; 4344 } 4345 4346 /// We are trying to inject an anonymous member into the given scope; 4347 /// check if there's an existing declaration that can't be overloaded. 4348 /// 4349 /// \return true if this is a forbidden redeclaration 4350 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4351 Scope *S, 4352 DeclContext *Owner, 4353 DeclarationName Name, 4354 SourceLocation NameLoc, 4355 bool IsUnion) { 4356 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4357 Sema::ForRedeclaration); 4358 if (!SemaRef.LookupName(R, S)) return false; 4359 4360 // Pick a representative declaration. 4361 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4362 assert(PrevDecl && "Expected a non-null Decl"); 4363 4364 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4365 return false; 4366 4367 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4368 << IsUnion << Name; 4369 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4370 4371 return true; 4372 } 4373 4374 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4375 /// anonymous struct or union AnonRecord into the owning context Owner 4376 /// and scope S. This routine will be invoked just after we realize 4377 /// that an unnamed union or struct is actually an anonymous union or 4378 /// struct, e.g., 4379 /// 4380 /// @code 4381 /// union { 4382 /// int i; 4383 /// float f; 4384 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4385 /// // f into the surrounding scope.x 4386 /// @endcode 4387 /// 4388 /// This routine is recursive, injecting the names of nested anonymous 4389 /// structs/unions into the owning context and scope as well. 4390 static bool 4391 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4392 RecordDecl *AnonRecord, AccessSpecifier AS, 4393 SmallVectorImpl<NamedDecl *> &Chaining) { 4394 bool Invalid = false; 4395 4396 // Look every FieldDecl and IndirectFieldDecl with a name. 4397 for (auto *D : AnonRecord->decls()) { 4398 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4399 cast<NamedDecl>(D)->getDeclName()) { 4400 ValueDecl *VD = cast<ValueDecl>(D); 4401 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4402 VD->getLocation(), 4403 AnonRecord->isUnion())) { 4404 // C++ [class.union]p2: 4405 // The names of the members of an anonymous union shall be 4406 // distinct from the names of any other entity in the 4407 // scope in which the anonymous union is declared. 4408 Invalid = true; 4409 } else { 4410 // C++ [class.union]p2: 4411 // For the purpose of name lookup, after the anonymous union 4412 // definition, the members of the anonymous union are 4413 // considered to have been defined in the scope in which the 4414 // anonymous union is declared. 4415 unsigned OldChainingSize = Chaining.size(); 4416 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4417 Chaining.append(IF->chain_begin(), IF->chain_end()); 4418 else 4419 Chaining.push_back(VD); 4420 4421 assert(Chaining.size() >= 2); 4422 NamedDecl **NamedChain = 4423 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4424 for (unsigned i = 0; i < Chaining.size(); i++) 4425 NamedChain[i] = Chaining[i]; 4426 4427 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4428 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4429 VD->getType(), {NamedChain, Chaining.size()}); 4430 4431 for (const auto *Attr : VD->attrs()) 4432 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4433 4434 IndirectField->setAccess(AS); 4435 IndirectField->setImplicit(); 4436 SemaRef.PushOnScopeChains(IndirectField, S); 4437 4438 // That includes picking up the appropriate access specifier. 4439 if (AS != AS_none) IndirectField->setAccess(AS); 4440 4441 Chaining.resize(OldChainingSize); 4442 } 4443 } 4444 } 4445 4446 return Invalid; 4447 } 4448 4449 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4450 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4451 /// illegal input values are mapped to SC_None. 4452 static StorageClass 4453 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4454 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4455 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4456 "Parser allowed 'typedef' as storage class VarDecl."); 4457 switch (StorageClassSpec) { 4458 case DeclSpec::SCS_unspecified: return SC_None; 4459 case DeclSpec::SCS_extern: 4460 if (DS.isExternInLinkageSpec()) 4461 return SC_None; 4462 return SC_Extern; 4463 case DeclSpec::SCS_static: return SC_Static; 4464 case DeclSpec::SCS_auto: return SC_Auto; 4465 case DeclSpec::SCS_register: return SC_Register; 4466 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4467 // Illegal SCSs map to None: error reporting is up to the caller. 4468 case DeclSpec::SCS_mutable: // Fall through. 4469 case DeclSpec::SCS_typedef: return SC_None; 4470 } 4471 llvm_unreachable("unknown storage class specifier"); 4472 } 4473 4474 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4475 assert(Record->hasInClassInitializer()); 4476 4477 for (const auto *I : Record->decls()) { 4478 const auto *FD = dyn_cast<FieldDecl>(I); 4479 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4480 FD = IFD->getAnonField(); 4481 if (FD && FD->hasInClassInitializer()) 4482 return FD->getLocation(); 4483 } 4484 4485 llvm_unreachable("couldn't find in-class initializer"); 4486 } 4487 4488 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4489 SourceLocation DefaultInitLoc) { 4490 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4491 return; 4492 4493 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4494 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4495 } 4496 4497 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4498 CXXRecordDecl *AnonUnion) { 4499 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4500 return; 4501 4502 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4503 } 4504 4505 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4506 /// anonymous structure or union. Anonymous unions are a C++ feature 4507 /// (C++ [class.union]) and a C11 feature; anonymous structures 4508 /// are a C11 feature and GNU C++ extension. 4509 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4510 AccessSpecifier AS, 4511 RecordDecl *Record, 4512 const PrintingPolicy &Policy) { 4513 DeclContext *Owner = Record->getDeclContext(); 4514 4515 // Diagnose whether this anonymous struct/union is an extension. 4516 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4517 Diag(Record->getLocation(), diag::ext_anonymous_union); 4518 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4519 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4520 else if (!Record->isUnion() && !getLangOpts().C11) 4521 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4522 4523 // C and C++ require different kinds of checks for anonymous 4524 // structs/unions. 4525 bool Invalid = false; 4526 if (getLangOpts().CPlusPlus) { 4527 const char *PrevSpec = nullptr; 4528 unsigned DiagID; 4529 if (Record->isUnion()) { 4530 // C++ [class.union]p6: 4531 // Anonymous unions declared in a named namespace or in the 4532 // global namespace shall be declared static. 4533 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4534 (isa<TranslationUnitDecl>(Owner) || 4535 (isa<NamespaceDecl>(Owner) && 4536 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4537 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4538 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4539 4540 // Recover by adding 'static'. 4541 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4542 PrevSpec, DiagID, Policy); 4543 } 4544 // C++ [class.union]p6: 4545 // A storage class is not allowed in a declaration of an 4546 // anonymous union in a class scope. 4547 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4548 isa<RecordDecl>(Owner)) { 4549 Diag(DS.getStorageClassSpecLoc(), 4550 diag::err_anonymous_union_with_storage_spec) 4551 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4552 4553 // Recover by removing the storage specifier. 4554 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4555 SourceLocation(), 4556 PrevSpec, DiagID, Context.getPrintingPolicy()); 4557 } 4558 } 4559 4560 // Ignore const/volatile/restrict qualifiers. 4561 if (DS.getTypeQualifiers()) { 4562 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4563 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4564 << Record->isUnion() << "const" 4565 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4566 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4567 Diag(DS.getVolatileSpecLoc(), 4568 diag::ext_anonymous_struct_union_qualified) 4569 << Record->isUnion() << "volatile" 4570 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4571 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4572 Diag(DS.getRestrictSpecLoc(), 4573 diag::ext_anonymous_struct_union_qualified) 4574 << Record->isUnion() << "restrict" 4575 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4576 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4577 Diag(DS.getAtomicSpecLoc(), 4578 diag::ext_anonymous_struct_union_qualified) 4579 << Record->isUnion() << "_Atomic" 4580 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4581 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4582 Diag(DS.getUnalignedSpecLoc(), 4583 diag::ext_anonymous_struct_union_qualified) 4584 << Record->isUnion() << "__unaligned" 4585 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4586 4587 DS.ClearTypeQualifiers(); 4588 } 4589 4590 // C++ [class.union]p2: 4591 // The member-specification of an anonymous union shall only 4592 // define non-static data members. [Note: nested types and 4593 // functions cannot be declared within an anonymous union. ] 4594 for (auto *Mem : Record->decls()) { 4595 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4596 // C++ [class.union]p3: 4597 // An anonymous union shall not have private or protected 4598 // members (clause 11). 4599 assert(FD->getAccess() != AS_none); 4600 if (FD->getAccess() != AS_public) { 4601 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4602 << Record->isUnion() << (FD->getAccess() == AS_protected); 4603 Invalid = true; 4604 } 4605 4606 // C++ [class.union]p1 4607 // An object of a class with a non-trivial constructor, a non-trivial 4608 // copy constructor, a non-trivial destructor, or a non-trivial copy 4609 // assignment operator cannot be a member of a union, nor can an 4610 // array of such objects. 4611 if (CheckNontrivialField(FD)) 4612 Invalid = true; 4613 } else if (Mem->isImplicit()) { 4614 // Any implicit members are fine. 4615 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4616 // This is a type that showed up in an 4617 // elaborated-type-specifier inside the anonymous struct or 4618 // union, but which actually declares a type outside of the 4619 // anonymous struct or union. It's okay. 4620 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4621 if (!MemRecord->isAnonymousStructOrUnion() && 4622 MemRecord->getDeclName()) { 4623 // Visual C++ allows type definition in anonymous struct or union. 4624 if (getLangOpts().MicrosoftExt) 4625 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4626 << Record->isUnion(); 4627 else { 4628 // This is a nested type declaration. 4629 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4630 << Record->isUnion(); 4631 Invalid = true; 4632 } 4633 } else { 4634 // This is an anonymous type definition within another anonymous type. 4635 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4636 // not part of standard C++. 4637 Diag(MemRecord->getLocation(), 4638 diag::ext_anonymous_record_with_anonymous_type) 4639 << Record->isUnion(); 4640 } 4641 } else if (isa<AccessSpecDecl>(Mem)) { 4642 // Any access specifier is fine. 4643 } else if (isa<StaticAssertDecl>(Mem)) { 4644 // In C++1z, static_assert declarations are also fine. 4645 } else { 4646 // We have something that isn't a non-static data 4647 // member. Complain about it. 4648 unsigned DK = diag::err_anonymous_record_bad_member; 4649 if (isa<TypeDecl>(Mem)) 4650 DK = diag::err_anonymous_record_with_type; 4651 else if (isa<FunctionDecl>(Mem)) 4652 DK = diag::err_anonymous_record_with_function; 4653 else if (isa<VarDecl>(Mem)) 4654 DK = diag::err_anonymous_record_with_static; 4655 4656 // Visual C++ allows type definition in anonymous struct or union. 4657 if (getLangOpts().MicrosoftExt && 4658 DK == diag::err_anonymous_record_with_type) 4659 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4660 << Record->isUnion(); 4661 else { 4662 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4663 Invalid = true; 4664 } 4665 } 4666 } 4667 4668 // C++11 [class.union]p8 (DR1460): 4669 // At most one variant member of a union may have a 4670 // brace-or-equal-initializer. 4671 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4672 Owner->isRecord()) 4673 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4674 cast<CXXRecordDecl>(Record)); 4675 } 4676 4677 if (!Record->isUnion() && !Owner->isRecord()) { 4678 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4679 << getLangOpts().CPlusPlus; 4680 Invalid = true; 4681 } 4682 4683 // Mock up a declarator. 4684 Declarator Dc(DS, Declarator::MemberContext); 4685 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4686 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4687 4688 // Create a declaration for this anonymous struct/union. 4689 NamedDecl *Anon = nullptr; 4690 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4691 Anon = FieldDecl::Create(Context, OwningClass, 4692 DS.getLocStart(), 4693 Record->getLocation(), 4694 /*IdentifierInfo=*/nullptr, 4695 Context.getTypeDeclType(Record), 4696 TInfo, 4697 /*BitWidth=*/nullptr, /*Mutable=*/false, 4698 /*InitStyle=*/ICIS_NoInit); 4699 Anon->setAccess(AS); 4700 if (getLangOpts().CPlusPlus) 4701 FieldCollector->Add(cast<FieldDecl>(Anon)); 4702 } else { 4703 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4704 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4705 if (SCSpec == DeclSpec::SCS_mutable) { 4706 // mutable can only appear on non-static class members, so it's always 4707 // an error here 4708 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4709 Invalid = true; 4710 SC = SC_None; 4711 } 4712 4713 Anon = VarDecl::Create(Context, Owner, 4714 DS.getLocStart(), 4715 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4716 Context.getTypeDeclType(Record), 4717 TInfo, SC); 4718 4719 // Default-initialize the implicit variable. This initialization will be 4720 // trivial in almost all cases, except if a union member has an in-class 4721 // initializer: 4722 // union { int n = 0; }; 4723 ActOnUninitializedDecl(Anon); 4724 } 4725 Anon->setImplicit(); 4726 4727 // Mark this as an anonymous struct/union type. 4728 Record->setAnonymousStructOrUnion(true); 4729 4730 // Add the anonymous struct/union object to the current 4731 // context. We'll be referencing this object when we refer to one of 4732 // its members. 4733 Owner->addDecl(Anon); 4734 4735 // Inject the members of the anonymous struct/union into the owning 4736 // context and into the identifier resolver chain for name lookup 4737 // purposes. 4738 SmallVector<NamedDecl*, 2> Chain; 4739 Chain.push_back(Anon); 4740 4741 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4742 Invalid = true; 4743 4744 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4745 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4746 Decl *ManglingContextDecl; 4747 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4748 NewVD->getDeclContext(), ManglingContextDecl)) { 4749 Context.setManglingNumber( 4750 NewVD, MCtx->getManglingNumber( 4751 NewVD, getMSManglingNumber(getLangOpts(), S))); 4752 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4753 } 4754 } 4755 } 4756 4757 if (Invalid) 4758 Anon->setInvalidDecl(); 4759 4760 return Anon; 4761 } 4762 4763 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4764 /// Microsoft C anonymous structure. 4765 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4766 /// Example: 4767 /// 4768 /// struct A { int a; }; 4769 /// struct B { struct A; int b; }; 4770 /// 4771 /// void foo() { 4772 /// B var; 4773 /// var.a = 3; 4774 /// } 4775 /// 4776 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4777 RecordDecl *Record) { 4778 assert(Record && "expected a record!"); 4779 4780 // Mock up a declarator. 4781 Declarator Dc(DS, Declarator::TypeNameContext); 4782 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4783 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4784 4785 auto *ParentDecl = cast<RecordDecl>(CurContext); 4786 QualType RecTy = Context.getTypeDeclType(Record); 4787 4788 // Create a declaration for this anonymous struct. 4789 NamedDecl *Anon = FieldDecl::Create(Context, 4790 ParentDecl, 4791 DS.getLocStart(), 4792 DS.getLocStart(), 4793 /*IdentifierInfo=*/nullptr, 4794 RecTy, 4795 TInfo, 4796 /*BitWidth=*/nullptr, /*Mutable=*/false, 4797 /*InitStyle=*/ICIS_NoInit); 4798 Anon->setImplicit(); 4799 4800 // Add the anonymous struct object to the current context. 4801 CurContext->addDecl(Anon); 4802 4803 // Inject the members of the anonymous struct into the current 4804 // context and into the identifier resolver chain for name lookup 4805 // purposes. 4806 SmallVector<NamedDecl*, 2> Chain; 4807 Chain.push_back(Anon); 4808 4809 RecordDecl *RecordDef = Record->getDefinition(); 4810 if (RequireCompleteType(Anon->getLocation(), RecTy, 4811 diag::err_field_incomplete) || 4812 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4813 AS_none, Chain)) { 4814 Anon->setInvalidDecl(); 4815 ParentDecl->setInvalidDecl(); 4816 } 4817 4818 return Anon; 4819 } 4820 4821 /// GetNameForDeclarator - Determine the full declaration name for the 4822 /// given Declarator. 4823 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4824 return GetNameFromUnqualifiedId(D.getName()); 4825 } 4826 4827 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4828 DeclarationNameInfo 4829 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4830 DeclarationNameInfo NameInfo; 4831 NameInfo.setLoc(Name.StartLocation); 4832 4833 switch (Name.getKind()) { 4834 4835 case UnqualifiedId::IK_ImplicitSelfParam: 4836 case UnqualifiedId::IK_Identifier: 4837 NameInfo.setName(Name.Identifier); 4838 NameInfo.setLoc(Name.StartLocation); 4839 return NameInfo; 4840 4841 case UnqualifiedId::IK_DeductionGuideName: { 4842 // C++ [temp.deduct.guide]p3: 4843 // The simple-template-id shall name a class template specialization. 4844 // The template-name shall be the same identifier as the template-name 4845 // of the simple-template-id. 4846 // These together intend to imply that the template-name shall name a 4847 // class template. 4848 // FIXME: template<typename T> struct X {}; 4849 // template<typename T> using Y = X<T>; 4850 // Y(int) -> Y<int>; 4851 // satisfies these rules but does not name a class template. 4852 TemplateName TN = Name.TemplateName.get().get(); 4853 auto *Template = TN.getAsTemplateDecl(); 4854 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4855 Diag(Name.StartLocation, 4856 diag::err_deduction_guide_name_not_class_template) 4857 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4858 if (Template) 4859 Diag(Template->getLocation(), diag::note_template_decl_here); 4860 return DeclarationNameInfo(); 4861 } 4862 4863 NameInfo.setName( 4864 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4865 NameInfo.setLoc(Name.StartLocation); 4866 return NameInfo; 4867 } 4868 4869 case UnqualifiedId::IK_OperatorFunctionId: 4870 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4871 Name.OperatorFunctionId.Operator)); 4872 NameInfo.setLoc(Name.StartLocation); 4873 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4874 = Name.OperatorFunctionId.SymbolLocations[0]; 4875 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4876 = Name.EndLocation.getRawEncoding(); 4877 return NameInfo; 4878 4879 case UnqualifiedId::IK_LiteralOperatorId: 4880 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4881 Name.Identifier)); 4882 NameInfo.setLoc(Name.StartLocation); 4883 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4884 return NameInfo; 4885 4886 case UnqualifiedId::IK_ConversionFunctionId: { 4887 TypeSourceInfo *TInfo; 4888 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4889 if (Ty.isNull()) 4890 return DeclarationNameInfo(); 4891 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4892 Context.getCanonicalType(Ty))); 4893 NameInfo.setLoc(Name.StartLocation); 4894 NameInfo.setNamedTypeInfo(TInfo); 4895 return NameInfo; 4896 } 4897 4898 case UnqualifiedId::IK_ConstructorName: { 4899 TypeSourceInfo *TInfo; 4900 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4901 if (Ty.isNull()) 4902 return DeclarationNameInfo(); 4903 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4904 Context.getCanonicalType(Ty))); 4905 NameInfo.setLoc(Name.StartLocation); 4906 NameInfo.setNamedTypeInfo(TInfo); 4907 return NameInfo; 4908 } 4909 4910 case UnqualifiedId::IK_ConstructorTemplateId: { 4911 // In well-formed code, we can only have a constructor 4912 // template-id that refers to the current context, so go there 4913 // to find the actual type being constructed. 4914 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4915 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4916 return DeclarationNameInfo(); 4917 4918 // Determine the type of the class being constructed. 4919 QualType CurClassType = Context.getTypeDeclType(CurClass); 4920 4921 // FIXME: Check two things: that the template-id names the same type as 4922 // CurClassType, and that the template-id does not occur when the name 4923 // was qualified. 4924 4925 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4926 Context.getCanonicalType(CurClassType))); 4927 NameInfo.setLoc(Name.StartLocation); 4928 // FIXME: should we retrieve TypeSourceInfo? 4929 NameInfo.setNamedTypeInfo(nullptr); 4930 return NameInfo; 4931 } 4932 4933 case UnqualifiedId::IK_DestructorName: { 4934 TypeSourceInfo *TInfo; 4935 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4936 if (Ty.isNull()) 4937 return DeclarationNameInfo(); 4938 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4939 Context.getCanonicalType(Ty))); 4940 NameInfo.setLoc(Name.StartLocation); 4941 NameInfo.setNamedTypeInfo(TInfo); 4942 return NameInfo; 4943 } 4944 4945 case UnqualifiedId::IK_TemplateId: { 4946 TemplateName TName = Name.TemplateId->Template.get(); 4947 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4948 return Context.getNameForTemplate(TName, TNameLoc); 4949 } 4950 4951 } // switch (Name.getKind()) 4952 4953 llvm_unreachable("Unknown name kind"); 4954 } 4955 4956 static QualType getCoreType(QualType Ty) { 4957 do { 4958 if (Ty->isPointerType() || Ty->isReferenceType()) 4959 Ty = Ty->getPointeeType(); 4960 else if (Ty->isArrayType()) 4961 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4962 else 4963 return Ty.withoutLocalFastQualifiers(); 4964 } while (true); 4965 } 4966 4967 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4968 /// and Definition have "nearly" matching parameters. This heuristic is 4969 /// used to improve diagnostics in the case where an out-of-line function 4970 /// definition doesn't match any declaration within the class or namespace. 4971 /// Also sets Params to the list of indices to the parameters that differ 4972 /// between the declaration and the definition. If hasSimilarParameters 4973 /// returns true and Params is empty, then all of the parameters match. 4974 static bool hasSimilarParameters(ASTContext &Context, 4975 FunctionDecl *Declaration, 4976 FunctionDecl *Definition, 4977 SmallVectorImpl<unsigned> &Params) { 4978 Params.clear(); 4979 if (Declaration->param_size() != Definition->param_size()) 4980 return false; 4981 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4982 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4983 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4984 4985 // The parameter types are identical 4986 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4987 continue; 4988 4989 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4990 QualType DefParamBaseTy = getCoreType(DefParamTy); 4991 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4992 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4993 4994 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4995 (DeclTyName && DeclTyName == DefTyName)) 4996 Params.push_back(Idx); 4997 else // The two parameters aren't even close 4998 return false; 4999 } 5000 5001 return true; 5002 } 5003 5004 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5005 /// declarator needs to be rebuilt in the current instantiation. 5006 /// Any bits of declarator which appear before the name are valid for 5007 /// consideration here. That's specifically the type in the decl spec 5008 /// and the base type in any member-pointer chunks. 5009 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5010 DeclarationName Name) { 5011 // The types we specifically need to rebuild are: 5012 // - typenames, typeofs, and decltypes 5013 // - types which will become injected class names 5014 // Of course, we also need to rebuild any type referencing such a 5015 // type. It's safest to just say "dependent", but we call out a 5016 // few cases here. 5017 5018 DeclSpec &DS = D.getMutableDeclSpec(); 5019 switch (DS.getTypeSpecType()) { 5020 case DeclSpec::TST_typename: 5021 case DeclSpec::TST_typeofType: 5022 case DeclSpec::TST_underlyingType: 5023 case DeclSpec::TST_atomic: { 5024 // Grab the type from the parser. 5025 TypeSourceInfo *TSI = nullptr; 5026 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5027 if (T.isNull() || !T->isDependentType()) break; 5028 5029 // Make sure there's a type source info. This isn't really much 5030 // of a waste; most dependent types should have type source info 5031 // attached already. 5032 if (!TSI) 5033 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5034 5035 // Rebuild the type in the current instantiation. 5036 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5037 if (!TSI) return true; 5038 5039 // Store the new type back in the decl spec. 5040 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5041 DS.UpdateTypeRep(LocType); 5042 break; 5043 } 5044 5045 case DeclSpec::TST_decltype: 5046 case DeclSpec::TST_typeofExpr: { 5047 Expr *E = DS.getRepAsExpr(); 5048 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5049 if (Result.isInvalid()) return true; 5050 DS.UpdateExprRep(Result.get()); 5051 break; 5052 } 5053 5054 default: 5055 // Nothing to do for these decl specs. 5056 break; 5057 } 5058 5059 // It doesn't matter what order we do this in. 5060 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5061 DeclaratorChunk &Chunk = D.getTypeObject(I); 5062 5063 // The only type information in the declarator which can come 5064 // before the declaration name is the base type of a member 5065 // pointer. 5066 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5067 continue; 5068 5069 // Rebuild the scope specifier in-place. 5070 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5071 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5072 return true; 5073 } 5074 5075 return false; 5076 } 5077 5078 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5079 D.setFunctionDefinitionKind(FDK_Declaration); 5080 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5081 5082 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5083 Dcl && Dcl->getDeclContext()->isFileContext()) 5084 Dcl->setTopLevelDeclInObjCContainer(); 5085 5086 if (getLangOpts().OpenCL) 5087 setCurrentOpenCLExtensionForDecl(Dcl); 5088 5089 return Dcl; 5090 } 5091 5092 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5093 /// If T is the name of a class, then each of the following shall have a 5094 /// name different from T: 5095 /// - every static data member of class T; 5096 /// - every member function of class T 5097 /// - every member of class T that is itself a type; 5098 /// \returns true if the declaration name violates these rules. 5099 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5100 DeclarationNameInfo NameInfo) { 5101 DeclarationName Name = NameInfo.getName(); 5102 5103 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5104 while (Record && Record->isAnonymousStructOrUnion()) 5105 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5106 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5107 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5108 return true; 5109 } 5110 5111 return false; 5112 } 5113 5114 /// \brief Diagnose a declaration whose declarator-id has the given 5115 /// nested-name-specifier. 5116 /// 5117 /// \param SS The nested-name-specifier of the declarator-id. 5118 /// 5119 /// \param DC The declaration context to which the nested-name-specifier 5120 /// resolves. 5121 /// 5122 /// \param Name The name of the entity being declared. 5123 /// 5124 /// \param Loc The location of the name of the entity being declared. 5125 /// 5126 /// \returns true if we cannot safely recover from this error, false otherwise. 5127 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5128 DeclarationName Name, 5129 SourceLocation Loc) { 5130 DeclContext *Cur = CurContext; 5131 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5132 Cur = Cur->getParent(); 5133 5134 // If the user provided a superfluous scope specifier that refers back to the 5135 // class in which the entity is already declared, diagnose and ignore it. 5136 // 5137 // class X { 5138 // void X::f(); 5139 // }; 5140 // 5141 // Note, it was once ill-formed to give redundant qualification in all 5142 // contexts, but that rule was removed by DR482. 5143 if (Cur->Equals(DC)) { 5144 if (Cur->isRecord()) { 5145 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5146 : diag::err_member_extra_qualification) 5147 << Name << FixItHint::CreateRemoval(SS.getRange()); 5148 SS.clear(); 5149 } else { 5150 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5151 } 5152 return false; 5153 } 5154 5155 // Check whether the qualifying scope encloses the scope of the original 5156 // declaration. 5157 if (!Cur->Encloses(DC)) { 5158 if (Cur->isRecord()) 5159 Diag(Loc, diag::err_member_qualification) 5160 << Name << SS.getRange(); 5161 else if (isa<TranslationUnitDecl>(DC)) 5162 Diag(Loc, diag::err_invalid_declarator_global_scope) 5163 << Name << SS.getRange(); 5164 else if (isa<FunctionDecl>(Cur)) 5165 Diag(Loc, diag::err_invalid_declarator_in_function) 5166 << Name << SS.getRange(); 5167 else if (isa<BlockDecl>(Cur)) 5168 Diag(Loc, diag::err_invalid_declarator_in_block) 5169 << Name << SS.getRange(); 5170 else 5171 Diag(Loc, diag::err_invalid_declarator_scope) 5172 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5173 5174 return true; 5175 } 5176 5177 if (Cur->isRecord()) { 5178 // Cannot qualify members within a class. 5179 Diag(Loc, diag::err_member_qualification) 5180 << Name << SS.getRange(); 5181 SS.clear(); 5182 5183 // C++ constructors and destructors with incorrect scopes can break 5184 // our AST invariants by having the wrong underlying types. If 5185 // that's the case, then drop this declaration entirely. 5186 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5187 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5188 !Context.hasSameType(Name.getCXXNameType(), 5189 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5190 return true; 5191 5192 return false; 5193 } 5194 5195 // C++11 [dcl.meaning]p1: 5196 // [...] "The nested-name-specifier of the qualified declarator-id shall 5197 // not begin with a decltype-specifer" 5198 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5199 while (SpecLoc.getPrefix()) 5200 SpecLoc = SpecLoc.getPrefix(); 5201 if (dyn_cast_or_null<DecltypeType>( 5202 SpecLoc.getNestedNameSpecifier()->getAsType())) 5203 Diag(Loc, diag::err_decltype_in_declarator) 5204 << SpecLoc.getTypeLoc().getSourceRange(); 5205 5206 return false; 5207 } 5208 5209 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5210 MultiTemplateParamsArg TemplateParamLists) { 5211 // TODO: consider using NameInfo for diagnostic. 5212 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5213 DeclarationName Name = NameInfo.getName(); 5214 5215 // All of these full declarators require an identifier. If it doesn't have 5216 // one, the ParsedFreeStandingDeclSpec action should be used. 5217 if (D.isDecompositionDeclarator()) { 5218 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5219 } else if (!Name) { 5220 if (!D.isInvalidType()) // Reject this if we think it is valid. 5221 Diag(D.getDeclSpec().getLocStart(), 5222 diag::err_declarator_need_ident) 5223 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5224 return nullptr; 5225 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5226 return nullptr; 5227 5228 // The scope passed in may not be a decl scope. Zip up the scope tree until 5229 // we find one that is. 5230 while ((S->getFlags() & Scope::DeclScope) == 0 || 5231 (S->getFlags() & Scope::TemplateParamScope) != 0) 5232 S = S->getParent(); 5233 5234 DeclContext *DC = CurContext; 5235 if (D.getCXXScopeSpec().isInvalid()) 5236 D.setInvalidType(); 5237 else if (D.getCXXScopeSpec().isSet()) { 5238 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5239 UPPC_DeclarationQualifier)) 5240 return nullptr; 5241 5242 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5243 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5244 if (!DC || isa<EnumDecl>(DC)) { 5245 // If we could not compute the declaration context, it's because the 5246 // declaration context is dependent but does not refer to a class, 5247 // class template, or class template partial specialization. Complain 5248 // and return early, to avoid the coming semantic disaster. 5249 Diag(D.getIdentifierLoc(), 5250 diag::err_template_qualified_declarator_no_match) 5251 << D.getCXXScopeSpec().getScopeRep() 5252 << D.getCXXScopeSpec().getRange(); 5253 return nullptr; 5254 } 5255 bool IsDependentContext = DC->isDependentContext(); 5256 5257 if (!IsDependentContext && 5258 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5259 return nullptr; 5260 5261 // If a class is incomplete, do not parse entities inside it. 5262 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5263 Diag(D.getIdentifierLoc(), 5264 diag::err_member_def_undefined_record) 5265 << Name << DC << D.getCXXScopeSpec().getRange(); 5266 return nullptr; 5267 } 5268 if (!D.getDeclSpec().isFriendSpecified()) { 5269 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5270 Name, D.getIdentifierLoc())) { 5271 if (DC->isRecord()) 5272 return nullptr; 5273 5274 D.setInvalidType(); 5275 } 5276 } 5277 5278 // Check whether we need to rebuild the type of the given 5279 // declaration in the current instantiation. 5280 if (EnteringContext && IsDependentContext && 5281 TemplateParamLists.size() != 0) { 5282 ContextRAII SavedContext(*this, DC); 5283 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5284 D.setInvalidType(); 5285 } 5286 } 5287 5288 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5289 QualType R = TInfo->getType(); 5290 5291 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5292 // If this is a typedef, we'll end up spewing multiple diagnostics. 5293 // Just return early; it's safer. If this is a function, let the 5294 // "constructor cannot have a return type" diagnostic handle it. 5295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5296 return nullptr; 5297 5298 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5299 UPPC_DeclarationType)) 5300 D.setInvalidType(); 5301 5302 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5303 ForRedeclaration); 5304 5305 // See if this is a redefinition of a variable in the same scope. 5306 if (!D.getCXXScopeSpec().isSet()) { 5307 bool IsLinkageLookup = false; 5308 bool CreateBuiltins = false; 5309 5310 // If the declaration we're planning to build will be a function 5311 // or object with linkage, then look for another declaration with 5312 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5313 // 5314 // If the declaration we're planning to build will be declared with 5315 // external linkage in the translation unit, create any builtin with 5316 // the same name. 5317 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5318 /* Do nothing*/; 5319 else if (CurContext->isFunctionOrMethod() && 5320 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5321 R->isFunctionType())) { 5322 IsLinkageLookup = true; 5323 CreateBuiltins = 5324 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5325 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5326 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5327 CreateBuiltins = true; 5328 5329 if (IsLinkageLookup) 5330 Previous.clear(LookupRedeclarationWithLinkage); 5331 5332 LookupName(Previous, S, CreateBuiltins); 5333 } else { // Something like "int foo::x;" 5334 LookupQualifiedName(Previous, DC); 5335 5336 // C++ [dcl.meaning]p1: 5337 // When the declarator-id is qualified, the declaration shall refer to a 5338 // previously declared member of the class or namespace to which the 5339 // qualifier refers (or, in the case of a namespace, of an element of the 5340 // inline namespace set of that namespace (7.3.1)) or to a specialization 5341 // thereof; [...] 5342 // 5343 // Note that we already checked the context above, and that we do not have 5344 // enough information to make sure that Previous contains the declaration 5345 // we want to match. For example, given: 5346 // 5347 // class X { 5348 // void f(); 5349 // void f(float); 5350 // }; 5351 // 5352 // void X::f(int) { } // ill-formed 5353 // 5354 // In this case, Previous will point to the overload set 5355 // containing the two f's declared in X, but neither of them 5356 // matches. 5357 5358 // C++ [dcl.meaning]p1: 5359 // [...] the member shall not merely have been introduced by a 5360 // using-declaration in the scope of the class or namespace nominated by 5361 // the nested-name-specifier of the declarator-id. 5362 RemoveUsingDecls(Previous); 5363 } 5364 5365 if (Previous.isSingleResult() && 5366 Previous.getFoundDecl()->isTemplateParameter()) { 5367 // Maybe we will complain about the shadowed template parameter. 5368 if (!D.isInvalidType()) 5369 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5370 Previous.getFoundDecl()); 5371 5372 // Just pretend that we didn't see the previous declaration. 5373 Previous.clear(); 5374 } 5375 5376 // In C++, the previous declaration we find might be a tag type 5377 // (class or enum). In this case, the new declaration will hide the 5378 // tag type. Note that this does does not apply if we're declaring a 5379 // typedef (C++ [dcl.typedef]p4). 5380 if (Previous.isSingleTagDecl() && 5381 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5382 Previous.clear(); 5383 5384 // Check that there are no default arguments other than in the parameters 5385 // of a function declaration (C++ only). 5386 if (getLangOpts().CPlusPlus) 5387 CheckExtraCXXDefaultArguments(D); 5388 5389 if (D.getDeclSpec().isConceptSpecified()) { 5390 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5391 // applied only to the definition of a function template or variable 5392 // template, declared in namespace scope 5393 if (!TemplateParamLists.size()) { 5394 Diag(D.getDeclSpec().getConceptSpecLoc(), 5395 diag:: err_concept_wrong_decl_kind); 5396 return nullptr; 5397 } 5398 5399 if (!DC->getRedeclContext()->isFileContext()) { 5400 Diag(D.getIdentifierLoc(), 5401 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5402 return nullptr; 5403 } 5404 } 5405 5406 NamedDecl *New; 5407 5408 bool AddToScope = true; 5409 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5410 if (TemplateParamLists.size()) { 5411 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5412 return nullptr; 5413 } 5414 5415 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5416 } else if (R->isFunctionType()) { 5417 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5418 TemplateParamLists, 5419 AddToScope); 5420 } else { 5421 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5422 AddToScope); 5423 } 5424 5425 if (!New) 5426 return nullptr; 5427 5428 // If this has an identifier and is not a function template specialization, 5429 // add it to the scope stack. 5430 if (New->getDeclName() && AddToScope) { 5431 // Only make a locally-scoped extern declaration visible if it is the first 5432 // declaration of this entity. Qualified lookup for such an entity should 5433 // only find this declaration if there is no visible declaration of it. 5434 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5435 PushOnScopeChains(New, S, AddToContext); 5436 if (!AddToContext) 5437 CurContext->addHiddenDecl(New); 5438 } 5439 5440 if (isInOpenMPDeclareTargetContext()) 5441 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5442 5443 return New; 5444 } 5445 5446 /// Helper method to turn variable array types into constant array 5447 /// types in certain situations which would otherwise be errors (for 5448 /// GCC compatibility). 5449 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5450 ASTContext &Context, 5451 bool &SizeIsNegative, 5452 llvm::APSInt &Oversized) { 5453 // This method tries to turn a variable array into a constant 5454 // array even when the size isn't an ICE. This is necessary 5455 // for compatibility with code that depends on gcc's buggy 5456 // constant expression folding, like struct {char x[(int)(char*)2];} 5457 SizeIsNegative = false; 5458 Oversized = 0; 5459 5460 if (T->isDependentType()) 5461 return QualType(); 5462 5463 QualifierCollector Qs; 5464 const Type *Ty = Qs.strip(T); 5465 5466 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5467 QualType Pointee = PTy->getPointeeType(); 5468 QualType FixedType = 5469 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5470 Oversized); 5471 if (FixedType.isNull()) return FixedType; 5472 FixedType = Context.getPointerType(FixedType); 5473 return Qs.apply(Context, FixedType); 5474 } 5475 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5476 QualType Inner = PTy->getInnerType(); 5477 QualType FixedType = 5478 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5479 Oversized); 5480 if (FixedType.isNull()) return FixedType; 5481 FixedType = Context.getParenType(FixedType); 5482 return Qs.apply(Context, FixedType); 5483 } 5484 5485 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5486 if (!VLATy) 5487 return QualType(); 5488 // FIXME: We should probably handle this case 5489 if (VLATy->getElementType()->isVariablyModifiedType()) 5490 return QualType(); 5491 5492 llvm::APSInt Res; 5493 if (!VLATy->getSizeExpr() || 5494 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5495 return QualType(); 5496 5497 // Check whether the array size is negative. 5498 if (Res.isSigned() && Res.isNegative()) { 5499 SizeIsNegative = true; 5500 return QualType(); 5501 } 5502 5503 // Check whether the array is too large to be addressed. 5504 unsigned ActiveSizeBits 5505 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5506 Res); 5507 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5508 Oversized = Res; 5509 return QualType(); 5510 } 5511 5512 return Context.getConstantArrayType(VLATy->getElementType(), 5513 Res, ArrayType::Normal, 0); 5514 } 5515 5516 static void 5517 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5518 SrcTL = SrcTL.getUnqualifiedLoc(); 5519 DstTL = DstTL.getUnqualifiedLoc(); 5520 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5521 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5522 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5523 DstPTL.getPointeeLoc()); 5524 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5525 return; 5526 } 5527 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5528 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5529 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5530 DstPTL.getInnerLoc()); 5531 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5532 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5533 return; 5534 } 5535 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5536 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5537 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5538 TypeLoc DstElemTL = DstATL.getElementLoc(); 5539 DstElemTL.initializeFullCopy(SrcElemTL); 5540 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5541 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5542 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5543 } 5544 5545 /// Helper method to turn variable array types into constant array 5546 /// types in certain situations which would otherwise be errors (for 5547 /// GCC compatibility). 5548 static TypeSourceInfo* 5549 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5550 ASTContext &Context, 5551 bool &SizeIsNegative, 5552 llvm::APSInt &Oversized) { 5553 QualType FixedTy 5554 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5555 SizeIsNegative, Oversized); 5556 if (FixedTy.isNull()) 5557 return nullptr; 5558 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5559 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5560 FixedTInfo->getTypeLoc()); 5561 return FixedTInfo; 5562 } 5563 5564 /// \brief Register the given locally-scoped extern "C" declaration so 5565 /// that it can be found later for redeclarations. We include any extern "C" 5566 /// declaration that is not visible in the translation unit here, not just 5567 /// function-scope declarations. 5568 void 5569 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5570 if (!getLangOpts().CPlusPlus && 5571 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5572 // Don't need to track declarations in the TU in C. 5573 return; 5574 5575 // Note that we have a locally-scoped external with this name. 5576 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5577 } 5578 5579 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5580 // FIXME: We can have multiple results via __attribute__((overloadable)). 5581 auto Result = Context.getExternCContextDecl()->lookup(Name); 5582 return Result.empty() ? nullptr : *Result.begin(); 5583 } 5584 5585 /// \brief Diagnose function specifiers on a declaration of an identifier that 5586 /// does not identify a function. 5587 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5588 // FIXME: We should probably indicate the identifier in question to avoid 5589 // confusion for constructs like "virtual int a(), b;" 5590 if (DS.isVirtualSpecified()) 5591 Diag(DS.getVirtualSpecLoc(), 5592 diag::err_virtual_non_function); 5593 5594 if (DS.isExplicitSpecified()) 5595 Diag(DS.getExplicitSpecLoc(), 5596 diag::err_explicit_non_function); 5597 5598 if (DS.isNoreturnSpecified()) 5599 Diag(DS.getNoreturnSpecLoc(), 5600 diag::err_noreturn_non_function); 5601 } 5602 5603 NamedDecl* 5604 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5605 TypeSourceInfo *TInfo, LookupResult &Previous) { 5606 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5607 if (D.getCXXScopeSpec().isSet()) { 5608 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5609 << D.getCXXScopeSpec().getRange(); 5610 D.setInvalidType(); 5611 // Pretend we didn't see the scope specifier. 5612 DC = CurContext; 5613 Previous.clear(); 5614 } 5615 5616 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5617 5618 if (D.getDeclSpec().isInlineSpecified()) 5619 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5620 << getLangOpts().CPlusPlus1z; 5621 if (D.getDeclSpec().isConstexprSpecified()) 5622 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5623 << 1; 5624 if (D.getDeclSpec().isConceptSpecified()) 5625 Diag(D.getDeclSpec().getConceptSpecLoc(), 5626 diag::err_concept_wrong_decl_kind); 5627 5628 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5629 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5630 Diag(D.getName().StartLocation, 5631 diag::err_deduction_guide_invalid_specifier) 5632 << "typedef"; 5633 else 5634 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5635 << D.getName().getSourceRange(); 5636 return nullptr; 5637 } 5638 5639 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5640 if (!NewTD) return nullptr; 5641 5642 // Handle attributes prior to checking for duplicates in MergeVarDecl 5643 ProcessDeclAttributes(S, NewTD, D); 5644 5645 CheckTypedefForVariablyModifiedType(S, NewTD); 5646 5647 bool Redeclaration = D.isRedeclaration(); 5648 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5649 D.setRedeclaration(Redeclaration); 5650 return ND; 5651 } 5652 5653 void 5654 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5655 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5656 // then it shall have block scope. 5657 // Note that variably modified types must be fixed before merging the decl so 5658 // that redeclarations will match. 5659 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5660 QualType T = TInfo->getType(); 5661 if (T->isVariablyModifiedType()) { 5662 getCurFunction()->setHasBranchProtectedScope(); 5663 5664 if (S->getFnParent() == nullptr) { 5665 bool SizeIsNegative; 5666 llvm::APSInt Oversized; 5667 TypeSourceInfo *FixedTInfo = 5668 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5669 SizeIsNegative, 5670 Oversized); 5671 if (FixedTInfo) { 5672 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5673 NewTD->setTypeSourceInfo(FixedTInfo); 5674 } else { 5675 if (SizeIsNegative) 5676 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5677 else if (T->isVariableArrayType()) 5678 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5679 else if (Oversized.getBoolValue()) 5680 Diag(NewTD->getLocation(), diag::err_array_too_large) 5681 << Oversized.toString(10); 5682 else 5683 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5684 NewTD->setInvalidDecl(); 5685 } 5686 } 5687 } 5688 } 5689 5690 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5691 /// declares a typedef-name, either using the 'typedef' type specifier or via 5692 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5693 NamedDecl* 5694 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5695 LookupResult &Previous, bool &Redeclaration) { 5696 5697 // Find the shadowed declaration before filtering for scope. 5698 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5699 5700 // Merge the decl with the existing one if appropriate. If the decl is 5701 // in an outer scope, it isn't the same thing. 5702 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5703 /*AllowInlineNamespace*/false); 5704 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5705 if (!Previous.empty()) { 5706 Redeclaration = true; 5707 MergeTypedefNameDecl(S, NewTD, Previous); 5708 } 5709 5710 if (ShadowedDecl && !Redeclaration) 5711 CheckShadow(NewTD, ShadowedDecl, Previous); 5712 5713 // If this is the C FILE type, notify the AST context. 5714 if (IdentifierInfo *II = NewTD->getIdentifier()) 5715 if (!NewTD->isInvalidDecl() && 5716 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5717 if (II->isStr("FILE")) 5718 Context.setFILEDecl(NewTD); 5719 else if (II->isStr("jmp_buf")) 5720 Context.setjmp_bufDecl(NewTD); 5721 else if (II->isStr("sigjmp_buf")) 5722 Context.setsigjmp_bufDecl(NewTD); 5723 else if (II->isStr("ucontext_t")) 5724 Context.setucontext_tDecl(NewTD); 5725 } 5726 5727 return NewTD; 5728 } 5729 5730 /// \brief Determines whether the given declaration is an out-of-scope 5731 /// previous declaration. 5732 /// 5733 /// This routine should be invoked when name lookup has found a 5734 /// previous declaration (PrevDecl) that is not in the scope where a 5735 /// new declaration by the same name is being introduced. If the new 5736 /// declaration occurs in a local scope, previous declarations with 5737 /// linkage may still be considered previous declarations (C99 5738 /// 6.2.2p4-5, C++ [basic.link]p6). 5739 /// 5740 /// \param PrevDecl the previous declaration found by name 5741 /// lookup 5742 /// 5743 /// \param DC the context in which the new declaration is being 5744 /// declared. 5745 /// 5746 /// \returns true if PrevDecl is an out-of-scope previous declaration 5747 /// for a new delcaration with the same name. 5748 static bool 5749 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5750 ASTContext &Context) { 5751 if (!PrevDecl) 5752 return false; 5753 5754 if (!PrevDecl->hasLinkage()) 5755 return false; 5756 5757 if (Context.getLangOpts().CPlusPlus) { 5758 // C++ [basic.link]p6: 5759 // If there is a visible declaration of an entity with linkage 5760 // having the same name and type, ignoring entities declared 5761 // outside the innermost enclosing namespace scope, the block 5762 // scope declaration declares that same entity and receives the 5763 // linkage of the previous declaration. 5764 DeclContext *OuterContext = DC->getRedeclContext(); 5765 if (!OuterContext->isFunctionOrMethod()) 5766 // This rule only applies to block-scope declarations. 5767 return false; 5768 5769 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5770 if (PrevOuterContext->isRecord()) 5771 // We found a member function: ignore it. 5772 return false; 5773 5774 // Find the innermost enclosing namespace for the new and 5775 // previous declarations. 5776 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5777 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5778 5779 // The previous declaration is in a different namespace, so it 5780 // isn't the same function. 5781 if (!OuterContext->Equals(PrevOuterContext)) 5782 return false; 5783 } 5784 5785 return true; 5786 } 5787 5788 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5789 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5790 if (!SS.isSet()) return; 5791 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5792 } 5793 5794 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5795 QualType type = decl->getType(); 5796 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5797 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5798 // Various kinds of declaration aren't allowed to be __autoreleasing. 5799 unsigned kind = -1U; 5800 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5801 if (var->hasAttr<BlocksAttr>()) 5802 kind = 0; // __block 5803 else if (!var->hasLocalStorage()) 5804 kind = 1; // global 5805 } else if (isa<ObjCIvarDecl>(decl)) { 5806 kind = 3; // ivar 5807 } else if (isa<FieldDecl>(decl)) { 5808 kind = 2; // field 5809 } 5810 5811 if (kind != -1U) { 5812 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5813 << kind; 5814 } 5815 } else if (lifetime == Qualifiers::OCL_None) { 5816 // Try to infer lifetime. 5817 if (!type->isObjCLifetimeType()) 5818 return false; 5819 5820 lifetime = type->getObjCARCImplicitLifetime(); 5821 type = Context.getLifetimeQualifiedType(type, lifetime); 5822 decl->setType(type); 5823 } 5824 5825 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5826 // Thread-local variables cannot have lifetime. 5827 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5828 var->getTLSKind()) { 5829 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5830 << var->getType(); 5831 return true; 5832 } 5833 } 5834 5835 return false; 5836 } 5837 5838 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5839 // Ensure that an auto decl is deduced otherwise the checks below might cache 5840 // the wrong linkage. 5841 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5842 5843 // 'weak' only applies to declarations with external linkage. 5844 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5845 if (!ND.isExternallyVisible()) { 5846 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5847 ND.dropAttr<WeakAttr>(); 5848 } 5849 } 5850 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5851 if (ND.isExternallyVisible()) { 5852 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5853 ND.dropAttr<WeakRefAttr>(); 5854 ND.dropAttr<AliasAttr>(); 5855 } 5856 } 5857 5858 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5859 if (VD->hasInit()) { 5860 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5861 assert(VD->isThisDeclarationADefinition() && 5862 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5863 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5864 VD->dropAttr<AliasAttr>(); 5865 } 5866 } 5867 } 5868 5869 // 'selectany' only applies to externally visible variable declarations. 5870 // It does not apply to functions. 5871 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5872 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5873 S.Diag(Attr->getLocation(), 5874 diag::err_attribute_selectany_non_extern_data); 5875 ND.dropAttr<SelectAnyAttr>(); 5876 } 5877 } 5878 5879 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5880 // dll attributes require external linkage. Static locals may have external 5881 // linkage but still cannot be explicitly imported or exported. 5882 auto *VD = dyn_cast<VarDecl>(&ND); 5883 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5884 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5885 << &ND << Attr; 5886 ND.setInvalidDecl(); 5887 } 5888 } 5889 5890 // Virtual functions cannot be marked as 'notail'. 5891 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5892 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5893 if (MD->isVirtual()) { 5894 S.Diag(ND.getLocation(), 5895 diag::err_invalid_attribute_on_virtual_function) 5896 << Attr; 5897 ND.dropAttr<NotTailCalledAttr>(); 5898 } 5899 } 5900 5901 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5902 NamedDecl *NewDecl, 5903 bool IsSpecialization, 5904 bool IsDefinition) { 5905 if (OldDecl->isInvalidDecl()) 5906 return; 5907 5908 bool IsTemplate = false; 5909 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5910 OldDecl = OldTD->getTemplatedDecl(); 5911 IsTemplate = true; 5912 if (!IsSpecialization) 5913 IsDefinition = false; 5914 } 5915 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5916 NewDecl = NewTD->getTemplatedDecl(); 5917 IsTemplate = true; 5918 } 5919 5920 if (!OldDecl || !NewDecl) 5921 return; 5922 5923 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5924 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5925 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5926 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5927 5928 // dllimport and dllexport are inheritable attributes so we have to exclude 5929 // inherited attribute instances. 5930 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5931 (NewExportAttr && !NewExportAttr->isInherited()); 5932 5933 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5934 // the only exception being explicit specializations. 5935 // Implicitly generated declarations are also excluded for now because there 5936 // is no other way to switch these to use dllimport or dllexport. 5937 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5938 5939 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5940 // Allow with a warning for free functions and global variables. 5941 bool JustWarn = false; 5942 if (!OldDecl->isCXXClassMember()) { 5943 auto *VD = dyn_cast<VarDecl>(OldDecl); 5944 if (VD && !VD->getDescribedVarTemplate()) 5945 JustWarn = true; 5946 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5947 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5948 JustWarn = true; 5949 } 5950 5951 // We cannot change a declaration that's been used because IR has already 5952 // been emitted. Dllimported functions will still work though (modulo 5953 // address equality) as they can use the thunk. 5954 if (OldDecl->isUsed()) 5955 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5956 JustWarn = false; 5957 5958 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5959 : diag::err_attribute_dll_redeclaration; 5960 S.Diag(NewDecl->getLocation(), DiagID) 5961 << NewDecl 5962 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5963 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5964 if (!JustWarn) { 5965 NewDecl->setInvalidDecl(); 5966 return; 5967 } 5968 } 5969 5970 // A redeclaration is not allowed to drop a dllimport attribute, the only 5971 // exceptions being inline function definitions (except for function 5972 // templates), local extern declarations, qualified friend declarations or 5973 // special MSVC extension: in the last case, the declaration is treated as if 5974 // it were marked dllexport. 5975 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5976 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5977 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5978 // Ignore static data because out-of-line definitions are diagnosed 5979 // separately. 5980 IsStaticDataMember = VD->isStaticDataMember(); 5981 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5982 VarDecl::DeclarationOnly; 5983 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5984 IsInline = FD->isInlined(); 5985 IsQualifiedFriend = FD->getQualifier() && 5986 FD->getFriendObjectKind() == Decl::FOK_Declared; 5987 } 5988 5989 if (OldImportAttr && !HasNewAttr && 5990 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5991 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5992 if (IsMicrosoft && IsDefinition) { 5993 S.Diag(NewDecl->getLocation(), 5994 diag::warn_redeclaration_without_import_attribute) 5995 << NewDecl; 5996 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5997 NewDecl->dropAttr<DLLImportAttr>(); 5998 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5999 NewImportAttr->getRange(), S.Context, 6000 NewImportAttr->getSpellingListIndex())); 6001 } else { 6002 S.Diag(NewDecl->getLocation(), 6003 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6004 << NewDecl << OldImportAttr; 6005 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6006 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6007 OldDecl->dropAttr<DLLImportAttr>(); 6008 NewDecl->dropAttr<DLLImportAttr>(); 6009 } 6010 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6011 // In MinGW, seeing a function declared inline drops the dllimport attribute. 6012 OldDecl->dropAttr<DLLImportAttr>(); 6013 NewDecl->dropAttr<DLLImportAttr>(); 6014 S.Diag(NewDecl->getLocation(), 6015 diag::warn_dllimport_dropped_from_inline_function) 6016 << NewDecl << OldImportAttr; 6017 } 6018 } 6019 6020 /// Given that we are within the definition of the given function, 6021 /// will that definition behave like C99's 'inline', where the 6022 /// definition is discarded except for optimization purposes? 6023 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6024 // Try to avoid calling GetGVALinkageForFunction. 6025 6026 // All cases of this require the 'inline' keyword. 6027 if (!FD->isInlined()) return false; 6028 6029 // This is only possible in C++ with the gnu_inline attribute. 6030 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6031 return false; 6032 6033 // Okay, go ahead and call the relatively-more-expensive function. 6034 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6035 } 6036 6037 /// Determine whether a variable is extern "C" prior to attaching 6038 /// an initializer. We can't just call isExternC() here, because that 6039 /// will also compute and cache whether the declaration is externally 6040 /// visible, which might change when we attach the initializer. 6041 /// 6042 /// This can only be used if the declaration is known to not be a 6043 /// redeclaration of an internal linkage declaration. 6044 /// 6045 /// For instance: 6046 /// 6047 /// auto x = []{}; 6048 /// 6049 /// Attaching the initializer here makes this declaration not externally 6050 /// visible, because its type has internal linkage. 6051 /// 6052 /// FIXME: This is a hack. 6053 template<typename T> 6054 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6055 if (S.getLangOpts().CPlusPlus) { 6056 // In C++, the overloadable attribute negates the effects of extern "C". 6057 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6058 return false; 6059 6060 // So do CUDA's host/device attributes. 6061 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6062 D->template hasAttr<CUDAHostAttr>())) 6063 return false; 6064 } 6065 return D->isExternC(); 6066 } 6067 6068 static bool shouldConsiderLinkage(const VarDecl *VD) { 6069 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6070 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6071 return VD->hasExternalStorage(); 6072 if (DC->isFileContext()) 6073 return true; 6074 if (DC->isRecord()) 6075 return false; 6076 llvm_unreachable("Unexpected context"); 6077 } 6078 6079 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6080 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6081 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6082 isa<OMPDeclareReductionDecl>(DC)) 6083 return true; 6084 if (DC->isRecord()) 6085 return false; 6086 llvm_unreachable("Unexpected context"); 6087 } 6088 6089 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6090 AttributeList::Kind Kind) { 6091 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6092 if (L->getKind() == Kind) 6093 return true; 6094 return false; 6095 } 6096 6097 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6098 AttributeList::Kind Kind) { 6099 // Check decl attributes on the DeclSpec. 6100 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6101 return true; 6102 6103 // Walk the declarator structure, checking decl attributes that were in a type 6104 // position to the decl itself. 6105 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6106 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6107 return true; 6108 } 6109 6110 // Finally, check attributes on the decl itself. 6111 return hasParsedAttr(S, PD.getAttributes(), Kind); 6112 } 6113 6114 /// Adjust the \c DeclContext for a function or variable that might be a 6115 /// function-local external declaration. 6116 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6117 if (!DC->isFunctionOrMethod()) 6118 return false; 6119 6120 // If this is a local extern function or variable declared within a function 6121 // template, don't add it into the enclosing namespace scope until it is 6122 // instantiated; it might have a dependent type right now. 6123 if (DC->isDependentContext()) 6124 return true; 6125 6126 // C++11 [basic.link]p7: 6127 // When a block scope declaration of an entity with linkage is not found to 6128 // refer to some other declaration, then that entity is a member of the 6129 // innermost enclosing namespace. 6130 // 6131 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6132 // semantically-enclosing namespace, not a lexically-enclosing one. 6133 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6134 DC = DC->getParent(); 6135 return true; 6136 } 6137 6138 /// \brief Returns true if given declaration has external C language linkage. 6139 static bool isDeclExternC(const Decl *D) { 6140 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6141 return FD->isExternC(); 6142 if (const auto *VD = dyn_cast<VarDecl>(D)) 6143 return VD->isExternC(); 6144 6145 llvm_unreachable("Unknown type of decl!"); 6146 } 6147 6148 NamedDecl *Sema::ActOnVariableDeclarator( 6149 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6150 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6151 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6152 QualType R = TInfo->getType(); 6153 DeclarationName Name = GetNameForDeclarator(D).getName(); 6154 6155 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6156 6157 if (D.isDecompositionDeclarator()) { 6158 AddToScope = false; 6159 // Take the name of the first declarator as our name for diagnostic 6160 // purposes. 6161 auto &Decomp = D.getDecompositionDeclarator(); 6162 if (!Decomp.bindings().empty()) { 6163 II = Decomp.bindings()[0].Name; 6164 Name = II; 6165 } 6166 } else if (!II) { 6167 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6168 return nullptr; 6169 } 6170 6171 if (getLangOpts().OpenCL) { 6172 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6173 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6174 // argument. 6175 if (R->isImageType() || R->isPipeType()) { 6176 Diag(D.getIdentifierLoc(), 6177 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6178 << R; 6179 D.setInvalidType(); 6180 return nullptr; 6181 } 6182 6183 // OpenCL v1.2 s6.9.r: 6184 // The event type cannot be used to declare a program scope variable. 6185 // OpenCL v2.0 s6.9.q: 6186 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6187 if (NULL == S->getParent()) { 6188 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6189 Diag(D.getIdentifierLoc(), 6190 diag::err_invalid_type_for_program_scope_var) << R; 6191 D.setInvalidType(); 6192 return nullptr; 6193 } 6194 } 6195 6196 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6197 QualType NR = R; 6198 while (NR->isPointerType()) { 6199 if (NR->isFunctionPointerType()) { 6200 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6201 D.setInvalidType(); 6202 break; 6203 } 6204 NR = NR->getPointeeType(); 6205 } 6206 6207 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6208 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6209 // half array type (unless the cl_khr_fp16 extension is enabled). 6210 if (Context.getBaseElementType(R)->isHalfType()) { 6211 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6212 D.setInvalidType(); 6213 } 6214 } 6215 6216 if (R->isSamplerT()) { 6217 // OpenCL v1.2 s6.9.b p4: 6218 // The sampler type cannot be used with the __local and __global address 6219 // space qualifiers. 6220 if (R.getAddressSpace() == LangAS::opencl_local || 6221 R.getAddressSpace() == LangAS::opencl_global) { 6222 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6223 } 6224 6225 // OpenCL v1.2 s6.12.14.1: 6226 // A global sampler must be declared with either the constant address 6227 // space qualifier or with the const qualifier. 6228 if (DC->isTranslationUnit() && 6229 !(R.getAddressSpace() == LangAS::opencl_constant || 6230 R.isConstQualified())) { 6231 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6232 D.setInvalidType(); 6233 } 6234 } 6235 6236 // OpenCL v1.2 s6.9.r: 6237 // The event type cannot be used with the __local, __constant and __global 6238 // address space qualifiers. 6239 if (R->isEventT()) { 6240 if (R.getAddressSpace()) { 6241 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6242 D.setInvalidType(); 6243 } 6244 } 6245 } 6246 6247 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6248 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6249 6250 // dllimport globals without explicit storage class are treated as extern. We 6251 // have to change the storage class this early to get the right DeclContext. 6252 if (SC == SC_None && !DC->isRecord() && 6253 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6254 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6255 SC = SC_Extern; 6256 6257 DeclContext *OriginalDC = DC; 6258 bool IsLocalExternDecl = SC == SC_Extern && 6259 adjustContextForLocalExternDecl(DC); 6260 6261 if (SCSpec == DeclSpec::SCS_mutable) { 6262 // mutable can only appear on non-static class members, so it's always 6263 // an error here 6264 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6265 D.setInvalidType(); 6266 SC = SC_None; 6267 } 6268 6269 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6270 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6271 D.getDeclSpec().getStorageClassSpecLoc())) { 6272 // In C++11, the 'register' storage class specifier is deprecated. 6273 // Suppress the warning in system macros, it's used in macros in some 6274 // popular C system headers, such as in glibc's htonl() macro. 6275 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6276 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6277 : diag::warn_deprecated_register) 6278 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6279 } 6280 6281 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6282 6283 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6284 // C99 6.9p2: The storage-class specifiers auto and register shall not 6285 // appear in the declaration specifiers in an external declaration. 6286 // Global Register+Asm is a GNU extension we support. 6287 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6288 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6289 D.setInvalidType(); 6290 } 6291 } 6292 6293 bool IsMemberSpecialization = false; 6294 bool IsVariableTemplateSpecialization = false; 6295 bool IsPartialSpecialization = false; 6296 bool IsVariableTemplate = false; 6297 VarDecl *NewVD = nullptr; 6298 VarTemplateDecl *NewTemplate = nullptr; 6299 TemplateParameterList *TemplateParams = nullptr; 6300 if (!getLangOpts().CPlusPlus) { 6301 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6302 D.getIdentifierLoc(), II, 6303 R, TInfo, SC); 6304 6305 if (R->getContainedDeducedType()) 6306 ParsingInitForAutoVars.insert(NewVD); 6307 6308 if (D.isInvalidType()) 6309 NewVD->setInvalidDecl(); 6310 } else { 6311 bool Invalid = false; 6312 6313 if (DC->isRecord() && !CurContext->isRecord()) { 6314 // This is an out-of-line definition of a static data member. 6315 switch (SC) { 6316 case SC_None: 6317 break; 6318 case SC_Static: 6319 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6320 diag::err_static_out_of_line) 6321 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6322 break; 6323 case SC_Auto: 6324 case SC_Register: 6325 case SC_Extern: 6326 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6327 // to names of variables declared in a block or to function parameters. 6328 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6329 // of class members 6330 6331 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6332 diag::err_storage_class_for_static_member) 6333 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6334 break; 6335 case SC_PrivateExtern: 6336 llvm_unreachable("C storage class in c++!"); 6337 } 6338 } 6339 6340 if (SC == SC_Static && CurContext->isRecord()) { 6341 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6342 if (RD->isLocalClass()) 6343 Diag(D.getIdentifierLoc(), 6344 diag::err_static_data_member_not_allowed_in_local_class) 6345 << Name << RD->getDeclName(); 6346 6347 // C++98 [class.union]p1: If a union contains a static data member, 6348 // the program is ill-formed. C++11 drops this restriction. 6349 if (RD->isUnion()) 6350 Diag(D.getIdentifierLoc(), 6351 getLangOpts().CPlusPlus11 6352 ? diag::warn_cxx98_compat_static_data_member_in_union 6353 : diag::ext_static_data_member_in_union) << Name; 6354 // We conservatively disallow static data members in anonymous structs. 6355 else if (!RD->getDeclName()) 6356 Diag(D.getIdentifierLoc(), 6357 diag::err_static_data_member_not_allowed_in_anon_struct) 6358 << Name << RD->isUnion(); 6359 } 6360 } 6361 6362 // Match up the template parameter lists with the scope specifier, then 6363 // determine whether we have a template or a template specialization. 6364 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6365 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6366 D.getCXXScopeSpec(), 6367 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6368 ? D.getName().TemplateId 6369 : nullptr, 6370 TemplateParamLists, 6371 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6372 6373 if (TemplateParams) { 6374 if (!TemplateParams->size() && 6375 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6376 // There is an extraneous 'template<>' for this variable. Complain 6377 // about it, but allow the declaration of the variable. 6378 Diag(TemplateParams->getTemplateLoc(), 6379 diag::err_template_variable_noparams) 6380 << II 6381 << SourceRange(TemplateParams->getTemplateLoc(), 6382 TemplateParams->getRAngleLoc()); 6383 TemplateParams = nullptr; 6384 } else { 6385 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6386 // This is an explicit specialization or a partial specialization. 6387 // FIXME: Check that we can declare a specialization here. 6388 IsVariableTemplateSpecialization = true; 6389 IsPartialSpecialization = TemplateParams->size() > 0; 6390 } else { // if (TemplateParams->size() > 0) 6391 // This is a template declaration. 6392 IsVariableTemplate = true; 6393 6394 // Check that we can declare a template here. 6395 if (CheckTemplateDeclScope(S, TemplateParams)) 6396 return nullptr; 6397 6398 // Only C++1y supports variable templates (N3651). 6399 Diag(D.getIdentifierLoc(), 6400 getLangOpts().CPlusPlus14 6401 ? diag::warn_cxx11_compat_variable_template 6402 : diag::ext_variable_template); 6403 } 6404 } 6405 } else { 6406 assert( 6407 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6408 "should have a 'template<>' for this decl"); 6409 } 6410 6411 if (IsVariableTemplateSpecialization) { 6412 SourceLocation TemplateKWLoc = 6413 TemplateParamLists.size() > 0 6414 ? TemplateParamLists[0]->getTemplateLoc() 6415 : SourceLocation(); 6416 DeclResult Res = ActOnVarTemplateSpecialization( 6417 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6418 IsPartialSpecialization); 6419 if (Res.isInvalid()) 6420 return nullptr; 6421 NewVD = cast<VarDecl>(Res.get()); 6422 AddToScope = false; 6423 } else if (D.isDecompositionDeclarator()) { 6424 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6425 D.getIdentifierLoc(), R, TInfo, SC, 6426 Bindings); 6427 } else 6428 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6429 D.getIdentifierLoc(), II, R, TInfo, SC); 6430 6431 // If this is supposed to be a variable template, create it as such. 6432 if (IsVariableTemplate) { 6433 NewTemplate = 6434 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6435 TemplateParams, NewVD); 6436 NewVD->setDescribedVarTemplate(NewTemplate); 6437 } 6438 6439 // If this decl has an auto type in need of deduction, make a note of the 6440 // Decl so we can diagnose uses of it in its own initializer. 6441 if (R->getContainedDeducedType()) 6442 ParsingInitForAutoVars.insert(NewVD); 6443 6444 if (D.isInvalidType() || Invalid) { 6445 NewVD->setInvalidDecl(); 6446 if (NewTemplate) 6447 NewTemplate->setInvalidDecl(); 6448 } 6449 6450 SetNestedNameSpecifier(NewVD, D); 6451 6452 // If we have any template parameter lists that don't directly belong to 6453 // the variable (matching the scope specifier), store them. 6454 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6455 if (TemplateParamLists.size() > VDTemplateParamLists) 6456 NewVD->setTemplateParameterListsInfo( 6457 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6458 6459 if (D.getDeclSpec().isConstexprSpecified()) { 6460 NewVD->setConstexpr(true); 6461 // C++1z [dcl.spec.constexpr]p1: 6462 // A static data member declared with the constexpr specifier is 6463 // implicitly an inline variable. 6464 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6465 NewVD->setImplicitlyInline(); 6466 } 6467 6468 if (D.getDeclSpec().isConceptSpecified()) { 6469 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6470 VTD->setConcept(); 6471 6472 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6473 // be declared with the thread_local, inline, friend, or constexpr 6474 // specifiers, [...] 6475 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6476 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6477 diag::err_concept_decl_invalid_specifiers) 6478 << 0 << 0; 6479 NewVD->setInvalidDecl(true); 6480 } 6481 6482 if (D.getDeclSpec().isConstexprSpecified()) { 6483 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6484 diag::err_concept_decl_invalid_specifiers) 6485 << 0 << 3; 6486 NewVD->setInvalidDecl(true); 6487 } 6488 6489 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6490 // applied only to the definition of a function template or variable 6491 // template, declared in namespace scope. 6492 if (IsVariableTemplateSpecialization) { 6493 Diag(D.getDeclSpec().getConceptSpecLoc(), 6494 diag::err_concept_specified_specialization) 6495 << (IsPartialSpecialization ? 2 : 1); 6496 } 6497 6498 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6499 // following restrictions: 6500 // - The declared type shall have the type bool. 6501 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6502 !NewVD->isInvalidDecl()) { 6503 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6504 NewVD->setInvalidDecl(true); 6505 } 6506 } 6507 } 6508 6509 if (D.getDeclSpec().isInlineSpecified()) { 6510 if (!getLangOpts().CPlusPlus) { 6511 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6512 << 0; 6513 } else if (CurContext->isFunctionOrMethod()) { 6514 // 'inline' is not allowed on block scope variable declaration. 6515 Diag(D.getDeclSpec().getInlineSpecLoc(), 6516 diag::err_inline_declaration_block_scope) << Name 6517 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6518 } else { 6519 Diag(D.getDeclSpec().getInlineSpecLoc(), 6520 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6521 : diag::ext_inline_variable); 6522 NewVD->setInlineSpecified(); 6523 } 6524 } 6525 6526 // Set the lexical context. If the declarator has a C++ scope specifier, the 6527 // lexical context will be different from the semantic context. 6528 NewVD->setLexicalDeclContext(CurContext); 6529 if (NewTemplate) 6530 NewTemplate->setLexicalDeclContext(CurContext); 6531 6532 if (IsLocalExternDecl) { 6533 if (D.isDecompositionDeclarator()) 6534 for (auto *B : Bindings) 6535 B->setLocalExternDecl(); 6536 else 6537 NewVD->setLocalExternDecl(); 6538 } 6539 6540 bool EmitTLSUnsupportedError = false; 6541 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6542 // C++11 [dcl.stc]p4: 6543 // When thread_local is applied to a variable of block scope the 6544 // storage-class-specifier static is implied if it does not appear 6545 // explicitly. 6546 // Core issue: 'static' is not implied if the variable is declared 6547 // 'extern'. 6548 if (NewVD->hasLocalStorage() && 6549 (SCSpec != DeclSpec::SCS_unspecified || 6550 TSCS != DeclSpec::TSCS_thread_local || 6551 !DC->isFunctionOrMethod())) 6552 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6553 diag::err_thread_non_global) 6554 << DeclSpec::getSpecifierName(TSCS); 6555 else if (!Context.getTargetInfo().isTLSSupported()) { 6556 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6557 // Postpone error emission until we've collected attributes required to 6558 // figure out whether it's a host or device variable and whether the 6559 // error should be ignored. 6560 EmitTLSUnsupportedError = true; 6561 // We still need to mark the variable as TLS so it shows up in AST with 6562 // proper storage class for other tools to use even if we're not going 6563 // to emit any code for it. 6564 NewVD->setTSCSpec(TSCS); 6565 } else 6566 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6567 diag::err_thread_unsupported); 6568 } else 6569 NewVD->setTSCSpec(TSCS); 6570 } 6571 6572 // C99 6.7.4p3 6573 // An inline definition of a function with external linkage shall 6574 // not contain a definition of a modifiable object with static or 6575 // thread storage duration... 6576 // We only apply this when the function is required to be defined 6577 // elsewhere, i.e. when the function is not 'extern inline'. Note 6578 // that a local variable with thread storage duration still has to 6579 // be marked 'static'. Also note that it's possible to get these 6580 // semantics in C++ using __attribute__((gnu_inline)). 6581 if (SC == SC_Static && S->getFnParent() != nullptr && 6582 !NewVD->getType().isConstQualified()) { 6583 FunctionDecl *CurFD = getCurFunctionDecl(); 6584 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6585 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6586 diag::warn_static_local_in_extern_inline); 6587 MaybeSuggestAddingStaticToDecl(CurFD); 6588 } 6589 } 6590 6591 if (D.getDeclSpec().isModulePrivateSpecified()) { 6592 if (IsVariableTemplateSpecialization) 6593 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6594 << (IsPartialSpecialization ? 1 : 0) 6595 << FixItHint::CreateRemoval( 6596 D.getDeclSpec().getModulePrivateSpecLoc()); 6597 else if (IsMemberSpecialization) 6598 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6599 << 2 6600 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6601 else if (NewVD->hasLocalStorage()) 6602 Diag(NewVD->getLocation(), diag::err_module_private_local) 6603 << 0 << NewVD->getDeclName() 6604 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6605 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6606 else { 6607 NewVD->setModulePrivate(); 6608 if (NewTemplate) 6609 NewTemplate->setModulePrivate(); 6610 for (auto *B : Bindings) 6611 B->setModulePrivate(); 6612 } 6613 } 6614 6615 // Handle attributes prior to checking for duplicates in MergeVarDecl 6616 ProcessDeclAttributes(S, NewVD, D); 6617 6618 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6619 if (EmitTLSUnsupportedError && 6620 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6621 (getLangOpts().OpenMPIsDevice && 6622 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6623 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6624 diag::err_thread_unsupported); 6625 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6626 // storage [duration]." 6627 if (SC == SC_None && S->getFnParent() != nullptr && 6628 (NewVD->hasAttr<CUDASharedAttr>() || 6629 NewVD->hasAttr<CUDAConstantAttr>())) { 6630 NewVD->setStorageClass(SC_Static); 6631 } 6632 } 6633 6634 // Ensure that dllimport globals without explicit storage class are treated as 6635 // extern. The storage class is set above using parsed attributes. Now we can 6636 // check the VarDecl itself. 6637 assert(!NewVD->hasAttr<DLLImportAttr>() || 6638 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6639 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6640 6641 // In auto-retain/release, infer strong retension for variables of 6642 // retainable type. 6643 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6644 NewVD->setInvalidDecl(); 6645 6646 // Handle GNU asm-label extension (encoded as an attribute). 6647 if (Expr *E = (Expr*)D.getAsmLabel()) { 6648 // The parser guarantees this is a string. 6649 StringLiteral *SE = cast<StringLiteral>(E); 6650 StringRef Label = SE->getString(); 6651 if (S->getFnParent() != nullptr) { 6652 switch (SC) { 6653 case SC_None: 6654 case SC_Auto: 6655 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6656 break; 6657 case SC_Register: 6658 // Local Named register 6659 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6660 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6661 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6662 break; 6663 case SC_Static: 6664 case SC_Extern: 6665 case SC_PrivateExtern: 6666 break; 6667 } 6668 } else if (SC == SC_Register) { 6669 // Global Named register 6670 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6671 const auto &TI = Context.getTargetInfo(); 6672 bool HasSizeMismatch; 6673 6674 if (!TI.isValidGCCRegisterName(Label)) 6675 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6676 else if (!TI.validateGlobalRegisterVariable(Label, 6677 Context.getTypeSize(R), 6678 HasSizeMismatch)) 6679 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6680 else if (HasSizeMismatch) 6681 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6682 } 6683 6684 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6685 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6686 NewVD->setInvalidDecl(true); 6687 } 6688 } 6689 6690 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6691 Context, Label, 0)); 6692 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6693 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6694 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6695 if (I != ExtnameUndeclaredIdentifiers.end()) { 6696 if (isDeclExternC(NewVD)) { 6697 NewVD->addAttr(I->second); 6698 ExtnameUndeclaredIdentifiers.erase(I); 6699 } else 6700 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6701 << /*Variable*/1 << NewVD; 6702 } 6703 } 6704 6705 // Find the shadowed declaration before filtering for scope. 6706 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6707 ? getShadowedDeclaration(NewVD, Previous) 6708 : nullptr; 6709 6710 // Don't consider existing declarations that are in a different 6711 // scope and are out-of-semantic-context declarations (if the new 6712 // declaration has linkage). 6713 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6714 D.getCXXScopeSpec().isNotEmpty() || 6715 IsMemberSpecialization || 6716 IsVariableTemplateSpecialization); 6717 6718 // Check whether the previous declaration is in the same block scope. This 6719 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6720 if (getLangOpts().CPlusPlus && 6721 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6722 NewVD->setPreviousDeclInSameBlockScope( 6723 Previous.isSingleResult() && !Previous.isShadowed() && 6724 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6725 6726 if (!getLangOpts().CPlusPlus) { 6727 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6728 } else { 6729 // If this is an explicit specialization of a static data member, check it. 6730 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6731 CheckMemberSpecialization(NewVD, Previous)) 6732 NewVD->setInvalidDecl(); 6733 6734 // Merge the decl with the existing one if appropriate. 6735 if (!Previous.empty()) { 6736 if (Previous.isSingleResult() && 6737 isa<FieldDecl>(Previous.getFoundDecl()) && 6738 D.getCXXScopeSpec().isSet()) { 6739 // The user tried to define a non-static data member 6740 // out-of-line (C++ [dcl.meaning]p1). 6741 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6742 << D.getCXXScopeSpec().getRange(); 6743 Previous.clear(); 6744 NewVD->setInvalidDecl(); 6745 } 6746 } else if (D.getCXXScopeSpec().isSet()) { 6747 // No previous declaration in the qualifying scope. 6748 Diag(D.getIdentifierLoc(), diag::err_no_member) 6749 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6750 << D.getCXXScopeSpec().getRange(); 6751 NewVD->setInvalidDecl(); 6752 } 6753 6754 if (!IsVariableTemplateSpecialization) 6755 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6756 6757 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6758 // an explicit specialization (14.8.3) or a partial specialization of a 6759 // concept definition. 6760 if (IsVariableTemplateSpecialization && 6761 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6762 Previous.isSingleResult()) { 6763 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6764 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6765 if (VarTmpl->isConcept()) { 6766 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6767 << 1 /*variable*/ 6768 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6769 : 1 /*explicitly specialized*/); 6770 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6771 NewVD->setInvalidDecl(); 6772 } 6773 } 6774 } 6775 6776 if (NewTemplate) { 6777 VarTemplateDecl *PrevVarTemplate = 6778 NewVD->getPreviousDecl() 6779 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6780 : nullptr; 6781 6782 // Check the template parameter list of this declaration, possibly 6783 // merging in the template parameter list from the previous variable 6784 // template declaration. 6785 if (CheckTemplateParameterList( 6786 TemplateParams, 6787 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6788 : nullptr, 6789 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6790 DC->isDependentContext()) 6791 ? TPC_ClassTemplateMember 6792 : TPC_VarTemplate)) 6793 NewVD->setInvalidDecl(); 6794 6795 // If we are providing an explicit specialization of a static variable 6796 // template, make a note of that. 6797 if (PrevVarTemplate && 6798 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6799 PrevVarTemplate->setMemberSpecialization(); 6800 } 6801 } 6802 6803 // Diagnose shadowed variables iff this isn't a redeclaration. 6804 if (ShadowedDecl && !D.isRedeclaration()) 6805 CheckShadow(NewVD, ShadowedDecl, Previous); 6806 6807 ProcessPragmaWeak(S, NewVD); 6808 6809 // If this is the first declaration of an extern C variable, update 6810 // the map of such variables. 6811 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6812 isIncompleteDeclExternC(*this, NewVD)) 6813 RegisterLocallyScopedExternCDecl(NewVD, S); 6814 6815 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6816 Decl *ManglingContextDecl; 6817 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6818 NewVD->getDeclContext(), ManglingContextDecl)) { 6819 Context.setManglingNumber( 6820 NewVD, MCtx->getManglingNumber( 6821 NewVD, getMSManglingNumber(getLangOpts(), S))); 6822 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6823 } 6824 } 6825 6826 // Special handling of variable named 'main'. 6827 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6828 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6829 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6830 6831 // C++ [basic.start.main]p3 6832 // A program that declares a variable main at global scope is ill-formed. 6833 if (getLangOpts().CPlusPlus) 6834 Diag(D.getLocStart(), diag::err_main_global_variable); 6835 6836 // In C, and external-linkage variable named main results in undefined 6837 // behavior. 6838 else if (NewVD->hasExternalFormalLinkage()) 6839 Diag(D.getLocStart(), diag::warn_main_redefined); 6840 } 6841 6842 if (D.isRedeclaration() && !Previous.empty()) { 6843 checkDLLAttributeRedeclaration( 6844 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6845 IsMemberSpecialization, D.isFunctionDefinition()); 6846 } 6847 6848 if (NewTemplate) { 6849 if (NewVD->isInvalidDecl()) 6850 NewTemplate->setInvalidDecl(); 6851 ActOnDocumentableDecl(NewTemplate); 6852 return NewTemplate; 6853 } 6854 6855 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6856 CompleteMemberSpecialization(NewVD, Previous); 6857 6858 return NewVD; 6859 } 6860 6861 /// Enum describing the %select options in diag::warn_decl_shadow. 6862 enum ShadowedDeclKind { 6863 SDK_Local, 6864 SDK_Global, 6865 SDK_StaticMember, 6866 SDK_Field, 6867 SDK_Typedef, 6868 SDK_Using 6869 }; 6870 6871 /// Determine what kind of declaration we're shadowing. 6872 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6873 const DeclContext *OldDC) { 6874 if (isa<TypeAliasDecl>(ShadowedDecl)) 6875 return SDK_Using; 6876 else if (isa<TypedefDecl>(ShadowedDecl)) 6877 return SDK_Typedef; 6878 else if (isa<RecordDecl>(OldDC)) 6879 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6880 6881 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6882 } 6883 6884 /// Return the location of the capture if the given lambda captures the given 6885 /// variable \p VD, or an invalid source location otherwise. 6886 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6887 const VarDecl *VD) { 6888 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6889 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6890 return Capture.getLocation(); 6891 } 6892 return SourceLocation(); 6893 } 6894 6895 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6896 const LookupResult &R) { 6897 // Only diagnose if we're shadowing an unambiguous field or variable. 6898 if (R.getResultKind() != LookupResult::Found) 6899 return false; 6900 6901 // Return false if warning is ignored. 6902 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6903 } 6904 6905 /// \brief Return the declaration shadowed by the given variable \p D, or null 6906 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6907 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6908 const LookupResult &R) { 6909 if (!shouldWarnIfShadowedDecl(Diags, R)) 6910 return nullptr; 6911 6912 // Don't diagnose declarations at file scope. 6913 if (D->hasGlobalStorage()) 6914 return nullptr; 6915 6916 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6917 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6918 ? ShadowedDecl 6919 : nullptr; 6920 } 6921 6922 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6923 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6924 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6925 const LookupResult &R) { 6926 // Don't warn if typedef declaration is part of a class 6927 if (D->getDeclContext()->isRecord()) 6928 return nullptr; 6929 6930 if (!shouldWarnIfShadowedDecl(Diags, R)) 6931 return nullptr; 6932 6933 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6934 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6935 } 6936 6937 /// \brief Diagnose variable or built-in function shadowing. Implements 6938 /// -Wshadow. 6939 /// 6940 /// This method is called whenever a VarDecl is added to a "useful" 6941 /// scope. 6942 /// 6943 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6944 /// \param R the lookup of the name 6945 /// 6946 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6947 const LookupResult &R) { 6948 DeclContext *NewDC = D->getDeclContext(); 6949 6950 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6951 // Fields are not shadowed by variables in C++ static methods. 6952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6953 if (MD->isStatic()) 6954 return; 6955 6956 // Fields shadowed by constructor parameters are a special case. Usually 6957 // the constructor initializes the field with the parameter. 6958 if (isa<CXXConstructorDecl>(NewDC)) 6959 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6960 // Remember that this was shadowed so we can either warn about its 6961 // modification or its existence depending on warning settings. 6962 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6963 return; 6964 } 6965 } 6966 6967 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6968 if (shadowedVar->isExternC()) { 6969 // For shadowing external vars, make sure that we point to the global 6970 // declaration, not a locally scoped extern declaration. 6971 for (auto I : shadowedVar->redecls()) 6972 if (I->isFileVarDecl()) { 6973 ShadowedDecl = I; 6974 break; 6975 } 6976 } 6977 6978 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 6979 6980 unsigned WarningDiag = diag::warn_decl_shadow; 6981 SourceLocation CaptureLoc; 6982 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6983 isa<CXXMethodDecl>(NewDC)) { 6984 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6985 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6986 if (RD->getLambdaCaptureDefault() == LCD_None) { 6987 // Try to avoid warnings for lambdas with an explicit capture list. 6988 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6989 // Warn only when the lambda captures the shadowed decl explicitly. 6990 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6991 if (CaptureLoc.isInvalid()) 6992 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6993 } else { 6994 // Remember that this was shadowed so we can avoid the warning if the 6995 // shadowed decl isn't captured and the warning settings allow it. 6996 cast<LambdaScopeInfo>(getCurFunction()) 6997 ->ShadowingDecls.push_back( 6998 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 6999 return; 7000 } 7001 } 7002 } 7003 } 7004 7005 // Only warn about certain kinds of shadowing for class members. 7006 if (NewDC && NewDC->isRecord()) { 7007 // In particular, don't warn about shadowing non-class members. 7008 if (!OldDC->isRecord()) 7009 return; 7010 7011 // TODO: should we warn about static data members shadowing 7012 // static data members from base classes? 7013 7014 // TODO: don't diagnose for inaccessible shadowed members. 7015 // This is hard to do perfectly because we might friend the 7016 // shadowing context, but that's just a false negative. 7017 } 7018 7019 7020 DeclarationName Name = R.getLookupName(); 7021 7022 // Emit warning and note. 7023 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7024 return; 7025 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7026 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7027 if (!CaptureLoc.isInvalid()) 7028 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7029 << Name << /*explicitly*/ 1; 7030 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7031 } 7032 7033 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7034 /// when these variables are captured by the lambda. 7035 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7036 for (const auto &Shadow : LSI->ShadowingDecls) { 7037 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7038 // Try to avoid the warning when the shadowed decl isn't captured. 7039 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7040 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7041 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7042 ? diag::warn_decl_shadow_uncaptured_local 7043 : diag::warn_decl_shadow) 7044 << Shadow.VD->getDeclName() 7045 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7046 if (!CaptureLoc.isInvalid()) 7047 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7048 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7049 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7050 } 7051 } 7052 7053 /// \brief Check -Wshadow without the advantage of a previous lookup. 7054 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7055 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7056 return; 7057 7058 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7059 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7060 LookupName(R, S); 7061 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7062 CheckShadow(D, ShadowedDecl, R); 7063 } 7064 7065 /// Check if 'E', which is an expression that is about to be modified, refers 7066 /// to a constructor parameter that shadows a field. 7067 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7068 // Quickly ignore expressions that can't be shadowing ctor parameters. 7069 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7070 return; 7071 E = E->IgnoreParenImpCasts(); 7072 auto *DRE = dyn_cast<DeclRefExpr>(E); 7073 if (!DRE) 7074 return; 7075 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7076 auto I = ShadowingDecls.find(D); 7077 if (I == ShadowingDecls.end()) 7078 return; 7079 const NamedDecl *ShadowedDecl = I->second; 7080 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7081 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7082 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7083 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7084 7085 // Avoid issuing multiple warnings about the same decl. 7086 ShadowingDecls.erase(I); 7087 } 7088 7089 /// Check for conflict between this global or extern "C" declaration and 7090 /// previous global or extern "C" declarations. This is only used in C++. 7091 template<typename T> 7092 static bool checkGlobalOrExternCConflict( 7093 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7094 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7095 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7096 7097 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7098 // The common case: this global doesn't conflict with any extern "C" 7099 // declaration. 7100 return false; 7101 } 7102 7103 if (Prev) { 7104 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7105 // Both the old and new declarations have C language linkage. This is a 7106 // redeclaration. 7107 Previous.clear(); 7108 Previous.addDecl(Prev); 7109 return true; 7110 } 7111 7112 // This is a global, non-extern "C" declaration, and there is a previous 7113 // non-global extern "C" declaration. Diagnose if this is a variable 7114 // declaration. 7115 if (!isa<VarDecl>(ND)) 7116 return false; 7117 } else { 7118 // The declaration is extern "C". Check for any declaration in the 7119 // translation unit which might conflict. 7120 if (IsGlobal) { 7121 // We have already performed the lookup into the translation unit. 7122 IsGlobal = false; 7123 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7124 I != E; ++I) { 7125 if (isa<VarDecl>(*I)) { 7126 Prev = *I; 7127 break; 7128 } 7129 } 7130 } else { 7131 DeclContext::lookup_result R = 7132 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7133 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7134 I != E; ++I) { 7135 if (isa<VarDecl>(*I)) { 7136 Prev = *I; 7137 break; 7138 } 7139 // FIXME: If we have any other entity with this name in global scope, 7140 // the declaration is ill-formed, but that is a defect: it breaks the 7141 // 'stat' hack, for instance. Only variables can have mangled name 7142 // clashes with extern "C" declarations, so only they deserve a 7143 // diagnostic. 7144 } 7145 } 7146 7147 if (!Prev) 7148 return false; 7149 } 7150 7151 // Use the first declaration's location to ensure we point at something which 7152 // is lexically inside an extern "C" linkage-spec. 7153 assert(Prev && "should have found a previous declaration to diagnose"); 7154 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7155 Prev = FD->getFirstDecl(); 7156 else 7157 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7158 7159 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7160 << IsGlobal << ND; 7161 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7162 << IsGlobal; 7163 return false; 7164 } 7165 7166 /// Apply special rules for handling extern "C" declarations. Returns \c true 7167 /// if we have found that this is a redeclaration of some prior entity. 7168 /// 7169 /// Per C++ [dcl.link]p6: 7170 /// Two declarations [for a function or variable] with C language linkage 7171 /// with the same name that appear in different scopes refer to the same 7172 /// [entity]. An entity with C language linkage shall not be declared with 7173 /// the same name as an entity in global scope. 7174 template<typename T> 7175 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7176 LookupResult &Previous) { 7177 if (!S.getLangOpts().CPlusPlus) { 7178 // In C, when declaring a global variable, look for a corresponding 'extern' 7179 // variable declared in function scope. We don't need this in C++, because 7180 // we find local extern decls in the surrounding file-scope DeclContext. 7181 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7182 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7183 Previous.clear(); 7184 Previous.addDecl(Prev); 7185 return true; 7186 } 7187 } 7188 return false; 7189 } 7190 7191 // A declaration in the translation unit can conflict with an extern "C" 7192 // declaration. 7193 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7194 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7195 7196 // An extern "C" declaration can conflict with a declaration in the 7197 // translation unit or can be a redeclaration of an extern "C" declaration 7198 // in another scope. 7199 if (isIncompleteDeclExternC(S,ND)) 7200 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7201 7202 // Neither global nor extern "C": nothing to do. 7203 return false; 7204 } 7205 7206 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7207 // If the decl is already known invalid, don't check it. 7208 if (NewVD->isInvalidDecl()) 7209 return; 7210 7211 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7212 QualType T = TInfo->getType(); 7213 7214 // Defer checking an 'auto' type until its initializer is attached. 7215 if (T->isUndeducedType()) 7216 return; 7217 7218 if (NewVD->hasAttrs()) 7219 CheckAlignasUnderalignment(NewVD); 7220 7221 if (T->isObjCObjectType()) { 7222 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7223 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7224 T = Context.getObjCObjectPointerType(T); 7225 NewVD->setType(T); 7226 } 7227 7228 // Emit an error if an address space was applied to decl with local storage. 7229 // This includes arrays of objects with address space qualifiers, but not 7230 // automatic variables that point to other address spaces. 7231 // ISO/IEC TR 18037 S5.1.2 7232 if (!getLangOpts().OpenCL 7233 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7234 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7235 NewVD->setInvalidDecl(); 7236 return; 7237 } 7238 7239 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7240 // scope. 7241 if (getLangOpts().OpenCLVersion == 120 && 7242 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7243 NewVD->isStaticLocal()) { 7244 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7245 NewVD->setInvalidDecl(); 7246 return; 7247 } 7248 7249 if (getLangOpts().OpenCL) { 7250 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7251 if (NewVD->hasAttr<BlocksAttr>()) { 7252 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7253 return; 7254 } 7255 7256 if (T->isBlockPointerType()) { 7257 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7258 // can't use 'extern' storage class. 7259 if (!T.isConstQualified()) { 7260 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7261 << 0 /*const*/; 7262 NewVD->setInvalidDecl(); 7263 return; 7264 } 7265 if (NewVD->hasExternalStorage()) { 7266 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7267 NewVD->setInvalidDecl(); 7268 return; 7269 } 7270 } 7271 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7272 // __constant address space. 7273 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7274 // variables inside a function can also be declared in the global 7275 // address space. 7276 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7277 NewVD->hasExternalStorage()) { 7278 if (!T->isSamplerT() && 7279 !(T.getAddressSpace() == LangAS::opencl_constant || 7280 (T.getAddressSpace() == LangAS::opencl_global && 7281 getLangOpts().OpenCLVersion == 200))) { 7282 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7283 if (getLangOpts().OpenCLVersion == 200) 7284 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7285 << Scope << "global or constant"; 7286 else 7287 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7288 << Scope << "constant"; 7289 NewVD->setInvalidDecl(); 7290 return; 7291 } 7292 } else { 7293 if (T.getAddressSpace() == LangAS::opencl_global) { 7294 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7295 << 1 /*is any function*/ << "global"; 7296 NewVD->setInvalidDecl(); 7297 return; 7298 } 7299 if (T.getAddressSpace() == LangAS::opencl_constant || 7300 T.getAddressSpace() == LangAS::opencl_local) { 7301 FunctionDecl *FD = getCurFunctionDecl(); 7302 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7303 // in functions. 7304 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7305 if (T.getAddressSpace() == LangAS::opencl_constant) 7306 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7307 << 0 /*non-kernel only*/ << "constant"; 7308 else 7309 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7310 << 0 /*non-kernel only*/ << "local"; 7311 NewVD->setInvalidDecl(); 7312 return; 7313 } 7314 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7315 // in the outermost scope of a kernel function. 7316 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7317 if (!getCurScope()->isFunctionScope()) { 7318 if (T.getAddressSpace() == LangAS::opencl_constant) 7319 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7320 << "constant"; 7321 else 7322 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7323 << "local"; 7324 NewVD->setInvalidDecl(); 7325 return; 7326 } 7327 } 7328 } else if (T.getAddressSpace() != LangAS::Default) { 7329 // Do not allow other address spaces on automatic variable. 7330 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7331 NewVD->setInvalidDecl(); 7332 return; 7333 } 7334 } 7335 } 7336 7337 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7338 && !NewVD->hasAttr<BlocksAttr>()) { 7339 if (getLangOpts().getGC() != LangOptions::NonGC) 7340 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7341 else { 7342 assert(!getLangOpts().ObjCAutoRefCount); 7343 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7344 } 7345 } 7346 7347 bool isVM = T->isVariablyModifiedType(); 7348 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7349 NewVD->hasAttr<BlocksAttr>()) 7350 getCurFunction()->setHasBranchProtectedScope(); 7351 7352 if ((isVM && NewVD->hasLinkage()) || 7353 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7354 bool SizeIsNegative; 7355 llvm::APSInt Oversized; 7356 TypeSourceInfo *FixedTInfo = 7357 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7358 SizeIsNegative, Oversized); 7359 if (!FixedTInfo && T->isVariableArrayType()) { 7360 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7361 // FIXME: This won't give the correct result for 7362 // int a[10][n]; 7363 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7364 7365 if (NewVD->isFileVarDecl()) 7366 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7367 << SizeRange; 7368 else if (NewVD->isStaticLocal()) 7369 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7370 << SizeRange; 7371 else 7372 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7373 << SizeRange; 7374 NewVD->setInvalidDecl(); 7375 return; 7376 } 7377 7378 if (!FixedTInfo) { 7379 if (NewVD->isFileVarDecl()) 7380 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7381 else 7382 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7383 NewVD->setInvalidDecl(); 7384 return; 7385 } 7386 7387 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7388 NewVD->setType(FixedTInfo->getType()); 7389 NewVD->setTypeSourceInfo(FixedTInfo); 7390 } 7391 7392 if (T->isVoidType()) { 7393 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7394 // of objects and functions. 7395 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7396 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7397 << T; 7398 NewVD->setInvalidDecl(); 7399 return; 7400 } 7401 } 7402 7403 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7404 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7405 NewVD->setInvalidDecl(); 7406 return; 7407 } 7408 7409 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7410 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7411 NewVD->setInvalidDecl(); 7412 return; 7413 } 7414 7415 if (NewVD->isConstexpr() && !T->isDependentType() && 7416 RequireLiteralType(NewVD->getLocation(), T, 7417 diag::err_constexpr_var_non_literal)) { 7418 NewVD->setInvalidDecl(); 7419 return; 7420 } 7421 } 7422 7423 /// \brief Perform semantic checking on a newly-created variable 7424 /// declaration. 7425 /// 7426 /// This routine performs all of the type-checking required for a 7427 /// variable declaration once it has been built. It is used both to 7428 /// check variables after they have been parsed and their declarators 7429 /// have been translated into a declaration, and to check variables 7430 /// that have been instantiated from a template. 7431 /// 7432 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7433 /// 7434 /// Returns true if the variable declaration is a redeclaration. 7435 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7436 CheckVariableDeclarationType(NewVD); 7437 7438 // If the decl is already known invalid, don't check it. 7439 if (NewVD->isInvalidDecl()) 7440 return false; 7441 7442 // If we did not find anything by this name, look for a non-visible 7443 // extern "C" declaration with the same name. 7444 if (Previous.empty() && 7445 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7446 Previous.setShadowed(); 7447 7448 if (!Previous.empty()) { 7449 MergeVarDecl(NewVD, Previous); 7450 return true; 7451 } 7452 return false; 7453 } 7454 7455 namespace { 7456 struct FindOverriddenMethod { 7457 Sema *S; 7458 CXXMethodDecl *Method; 7459 7460 /// Member lookup function that determines whether a given C++ 7461 /// method overrides a method in a base class, to be used with 7462 /// CXXRecordDecl::lookupInBases(). 7463 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7464 RecordDecl *BaseRecord = 7465 Specifier->getType()->getAs<RecordType>()->getDecl(); 7466 7467 DeclarationName Name = Method->getDeclName(); 7468 7469 // FIXME: Do we care about other names here too? 7470 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7471 // We really want to find the base class destructor here. 7472 QualType T = S->Context.getTypeDeclType(BaseRecord); 7473 CanQualType CT = S->Context.getCanonicalType(T); 7474 7475 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7476 } 7477 7478 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7479 Path.Decls = Path.Decls.slice(1)) { 7480 NamedDecl *D = Path.Decls.front(); 7481 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7482 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7483 return true; 7484 } 7485 } 7486 7487 return false; 7488 } 7489 }; 7490 7491 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7492 } // end anonymous namespace 7493 7494 /// \brief Report an error regarding overriding, along with any relevant 7495 /// overriden methods. 7496 /// 7497 /// \param DiagID the primary error to report. 7498 /// \param MD the overriding method. 7499 /// \param OEK which overrides to include as notes. 7500 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7501 OverrideErrorKind OEK = OEK_All) { 7502 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7503 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7504 E = MD->end_overridden_methods(); 7505 I != E; ++I) { 7506 // This check (& the OEK parameter) could be replaced by a predicate, but 7507 // without lambdas that would be overkill. This is still nicer than writing 7508 // out the diag loop 3 times. 7509 if ((OEK == OEK_All) || 7510 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7511 (OEK == OEK_Deleted && (*I)->isDeleted())) 7512 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7513 } 7514 } 7515 7516 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7517 /// and if so, check that it's a valid override and remember it. 7518 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7519 // Look for methods in base classes that this method might override. 7520 CXXBasePaths Paths; 7521 FindOverriddenMethod FOM; 7522 FOM.Method = MD; 7523 FOM.S = this; 7524 bool hasDeletedOverridenMethods = false; 7525 bool hasNonDeletedOverridenMethods = false; 7526 bool AddedAny = false; 7527 if (DC->lookupInBases(FOM, Paths)) { 7528 for (auto *I : Paths.found_decls()) { 7529 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7530 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7531 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7532 !CheckOverridingFunctionAttributes(MD, OldMD) && 7533 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7534 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7535 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7536 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7537 AddedAny = true; 7538 } 7539 } 7540 } 7541 } 7542 7543 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7544 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7545 } 7546 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7547 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7548 } 7549 7550 return AddedAny; 7551 } 7552 7553 namespace { 7554 // Struct for holding all of the extra arguments needed by 7555 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7556 struct ActOnFDArgs { 7557 Scope *S; 7558 Declarator &D; 7559 MultiTemplateParamsArg TemplateParamLists; 7560 bool AddToScope; 7561 }; 7562 } // end anonymous namespace 7563 7564 namespace { 7565 7566 // Callback to only accept typo corrections that have a non-zero edit distance. 7567 // Also only accept corrections that have the same parent decl. 7568 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7569 public: 7570 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7571 CXXRecordDecl *Parent) 7572 : Context(Context), OriginalFD(TypoFD), 7573 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7574 7575 bool ValidateCandidate(const TypoCorrection &candidate) override { 7576 if (candidate.getEditDistance() == 0) 7577 return false; 7578 7579 SmallVector<unsigned, 1> MismatchedParams; 7580 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7581 CDeclEnd = candidate.end(); 7582 CDecl != CDeclEnd; ++CDecl) { 7583 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7584 7585 if (FD && !FD->hasBody() && 7586 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7587 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7588 CXXRecordDecl *Parent = MD->getParent(); 7589 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7590 return true; 7591 } else if (!ExpectedParent) { 7592 return true; 7593 } 7594 } 7595 } 7596 7597 return false; 7598 } 7599 7600 private: 7601 ASTContext &Context; 7602 FunctionDecl *OriginalFD; 7603 CXXRecordDecl *ExpectedParent; 7604 }; 7605 7606 } // end anonymous namespace 7607 7608 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7609 TypoCorrectedFunctionDefinitions.insert(F); 7610 } 7611 7612 /// \brief Generate diagnostics for an invalid function redeclaration. 7613 /// 7614 /// This routine handles generating the diagnostic messages for an invalid 7615 /// function redeclaration, including finding possible similar declarations 7616 /// or performing typo correction if there are no previous declarations with 7617 /// the same name. 7618 /// 7619 /// Returns a NamedDecl iff typo correction was performed and substituting in 7620 /// the new declaration name does not cause new errors. 7621 static NamedDecl *DiagnoseInvalidRedeclaration( 7622 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7623 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7624 DeclarationName Name = NewFD->getDeclName(); 7625 DeclContext *NewDC = NewFD->getDeclContext(); 7626 SmallVector<unsigned, 1> MismatchedParams; 7627 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7628 TypoCorrection Correction; 7629 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7630 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7631 : diag::err_member_decl_does_not_match; 7632 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7633 IsLocalFriend ? Sema::LookupLocalFriendName 7634 : Sema::LookupOrdinaryName, 7635 Sema::ForRedeclaration); 7636 7637 NewFD->setInvalidDecl(); 7638 if (IsLocalFriend) 7639 SemaRef.LookupName(Prev, S); 7640 else 7641 SemaRef.LookupQualifiedName(Prev, NewDC); 7642 assert(!Prev.isAmbiguous() && 7643 "Cannot have an ambiguity in previous-declaration lookup"); 7644 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7645 if (!Prev.empty()) { 7646 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7647 Func != FuncEnd; ++Func) { 7648 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7649 if (FD && 7650 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7651 // Add 1 to the index so that 0 can mean the mismatch didn't 7652 // involve a parameter 7653 unsigned ParamNum = 7654 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7655 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7656 } 7657 } 7658 // If the qualified name lookup yielded nothing, try typo correction 7659 } else if ((Correction = SemaRef.CorrectTypo( 7660 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7661 &ExtraArgs.D.getCXXScopeSpec(), 7662 llvm::make_unique<DifferentNameValidatorCCC>( 7663 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7664 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7665 // Set up everything for the call to ActOnFunctionDeclarator 7666 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7667 ExtraArgs.D.getIdentifierLoc()); 7668 Previous.clear(); 7669 Previous.setLookupName(Correction.getCorrection()); 7670 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7671 CDeclEnd = Correction.end(); 7672 CDecl != CDeclEnd; ++CDecl) { 7673 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7674 if (FD && !FD->hasBody() && 7675 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7676 Previous.addDecl(FD); 7677 } 7678 } 7679 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7680 7681 NamedDecl *Result; 7682 // Retry building the function declaration with the new previous 7683 // declarations, and with errors suppressed. 7684 { 7685 // Trap errors. 7686 Sema::SFINAETrap Trap(SemaRef); 7687 7688 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7689 // pieces need to verify the typo-corrected C++ declaration and hopefully 7690 // eliminate the need for the parameter pack ExtraArgs. 7691 Result = SemaRef.ActOnFunctionDeclarator( 7692 ExtraArgs.S, ExtraArgs.D, 7693 Correction.getCorrectionDecl()->getDeclContext(), 7694 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7695 ExtraArgs.AddToScope); 7696 7697 if (Trap.hasErrorOccurred()) 7698 Result = nullptr; 7699 } 7700 7701 if (Result) { 7702 // Determine which correction we picked. 7703 Decl *Canonical = Result->getCanonicalDecl(); 7704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7705 I != E; ++I) 7706 if ((*I)->getCanonicalDecl() == Canonical) 7707 Correction.setCorrectionDecl(*I); 7708 7709 // Let Sema know about the correction. 7710 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7711 SemaRef.diagnoseTypo( 7712 Correction, 7713 SemaRef.PDiag(IsLocalFriend 7714 ? diag::err_no_matching_local_friend_suggest 7715 : diag::err_member_decl_does_not_match_suggest) 7716 << Name << NewDC << IsDefinition); 7717 return Result; 7718 } 7719 7720 // Pretend the typo correction never occurred 7721 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7722 ExtraArgs.D.getIdentifierLoc()); 7723 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7724 Previous.clear(); 7725 Previous.setLookupName(Name); 7726 } 7727 7728 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7729 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7730 7731 bool NewFDisConst = false; 7732 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7733 NewFDisConst = NewMD->isConst(); 7734 7735 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7736 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7737 NearMatch != NearMatchEnd; ++NearMatch) { 7738 FunctionDecl *FD = NearMatch->first; 7739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7740 bool FDisConst = MD && MD->isConst(); 7741 bool IsMember = MD || !IsLocalFriend; 7742 7743 // FIXME: These notes are poorly worded for the local friend case. 7744 if (unsigned Idx = NearMatch->second) { 7745 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7746 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7747 if (Loc.isInvalid()) Loc = FD->getLocation(); 7748 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7749 : diag::note_local_decl_close_param_match) 7750 << Idx << FDParam->getType() 7751 << NewFD->getParamDecl(Idx - 1)->getType(); 7752 } else if (FDisConst != NewFDisConst) { 7753 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7754 << NewFDisConst << FD->getSourceRange().getEnd(); 7755 } else 7756 SemaRef.Diag(FD->getLocation(), 7757 IsMember ? diag::note_member_def_close_match 7758 : diag::note_local_decl_close_match); 7759 } 7760 return nullptr; 7761 } 7762 7763 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7764 switch (D.getDeclSpec().getStorageClassSpec()) { 7765 default: llvm_unreachable("Unknown storage class!"); 7766 case DeclSpec::SCS_auto: 7767 case DeclSpec::SCS_register: 7768 case DeclSpec::SCS_mutable: 7769 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7770 diag::err_typecheck_sclass_func); 7771 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7772 D.setInvalidType(); 7773 break; 7774 case DeclSpec::SCS_unspecified: break; 7775 case DeclSpec::SCS_extern: 7776 if (D.getDeclSpec().isExternInLinkageSpec()) 7777 return SC_None; 7778 return SC_Extern; 7779 case DeclSpec::SCS_static: { 7780 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7781 // C99 6.7.1p5: 7782 // The declaration of an identifier for a function that has 7783 // block scope shall have no explicit storage-class specifier 7784 // other than extern 7785 // See also (C++ [dcl.stc]p4). 7786 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7787 diag::err_static_block_func); 7788 break; 7789 } else 7790 return SC_Static; 7791 } 7792 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7793 } 7794 7795 // No explicit storage class has already been returned 7796 return SC_None; 7797 } 7798 7799 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7800 DeclContext *DC, QualType &R, 7801 TypeSourceInfo *TInfo, 7802 StorageClass SC, 7803 bool &IsVirtualOkay) { 7804 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7805 DeclarationName Name = NameInfo.getName(); 7806 7807 FunctionDecl *NewFD = nullptr; 7808 bool isInline = D.getDeclSpec().isInlineSpecified(); 7809 7810 if (!SemaRef.getLangOpts().CPlusPlus) { 7811 // Determine whether the function was written with a 7812 // prototype. This true when: 7813 // - there is a prototype in the declarator, or 7814 // - the type R of the function is some kind of typedef or other non- 7815 // attributed reference to a type name (which eventually refers to a 7816 // function type). 7817 bool HasPrototype = 7818 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7819 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7820 7821 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7822 D.getLocStart(), NameInfo, R, 7823 TInfo, SC, isInline, 7824 HasPrototype, false); 7825 if (D.isInvalidType()) 7826 NewFD->setInvalidDecl(); 7827 7828 return NewFD; 7829 } 7830 7831 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7832 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7833 7834 // Check that the return type is not an abstract class type. 7835 // For record types, this is done by the AbstractClassUsageDiagnoser once 7836 // the class has been completely parsed. 7837 if (!DC->isRecord() && 7838 SemaRef.RequireNonAbstractType( 7839 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7840 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7841 D.setInvalidType(); 7842 7843 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7844 // This is a C++ constructor declaration. 7845 assert(DC->isRecord() && 7846 "Constructors can only be declared in a member context"); 7847 7848 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7849 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7850 D.getLocStart(), NameInfo, 7851 R, TInfo, isExplicit, isInline, 7852 /*isImplicitlyDeclared=*/false, 7853 isConstexpr); 7854 7855 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7856 // This is a C++ destructor declaration. 7857 if (DC->isRecord()) { 7858 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7859 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7860 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7861 SemaRef.Context, Record, 7862 D.getLocStart(), 7863 NameInfo, R, TInfo, isInline, 7864 /*isImplicitlyDeclared=*/false); 7865 7866 // If the class is complete, then we now create the implicit exception 7867 // specification. If the class is incomplete or dependent, we can't do 7868 // it yet. 7869 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7870 Record->getDefinition() && !Record->isBeingDefined() && 7871 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7872 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7873 } 7874 7875 IsVirtualOkay = true; 7876 return NewDD; 7877 7878 } else { 7879 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7880 D.setInvalidType(); 7881 7882 // Create a FunctionDecl to satisfy the function definition parsing 7883 // code path. 7884 return FunctionDecl::Create(SemaRef.Context, DC, 7885 D.getLocStart(), 7886 D.getIdentifierLoc(), Name, R, TInfo, 7887 SC, isInline, 7888 /*hasPrototype=*/true, isConstexpr); 7889 } 7890 7891 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7892 if (!DC->isRecord()) { 7893 SemaRef.Diag(D.getIdentifierLoc(), 7894 diag::err_conv_function_not_member); 7895 return nullptr; 7896 } 7897 7898 SemaRef.CheckConversionDeclarator(D, R, SC); 7899 IsVirtualOkay = true; 7900 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7901 D.getLocStart(), NameInfo, 7902 R, TInfo, isInline, isExplicit, 7903 isConstexpr, SourceLocation()); 7904 7905 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7906 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7907 7908 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7909 isExplicit, NameInfo, R, TInfo, 7910 D.getLocEnd()); 7911 } else if (DC->isRecord()) { 7912 // If the name of the function is the same as the name of the record, 7913 // then this must be an invalid constructor that has a return type. 7914 // (The parser checks for a return type and makes the declarator a 7915 // constructor if it has no return type). 7916 if (Name.getAsIdentifierInfo() && 7917 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7918 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7919 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7920 << SourceRange(D.getIdentifierLoc()); 7921 return nullptr; 7922 } 7923 7924 // This is a C++ method declaration. 7925 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7926 cast<CXXRecordDecl>(DC), 7927 D.getLocStart(), NameInfo, R, 7928 TInfo, SC, isInline, 7929 isConstexpr, SourceLocation()); 7930 IsVirtualOkay = !Ret->isStatic(); 7931 return Ret; 7932 } else { 7933 bool isFriend = 7934 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7935 if (!isFriend && SemaRef.CurContext->isRecord()) 7936 return nullptr; 7937 7938 // Determine whether the function was written with a 7939 // prototype. This true when: 7940 // - we're in C++ (where every function has a prototype), 7941 return FunctionDecl::Create(SemaRef.Context, DC, 7942 D.getLocStart(), 7943 NameInfo, R, TInfo, SC, isInline, 7944 true/*HasPrototype*/, isConstexpr); 7945 } 7946 } 7947 7948 enum OpenCLParamType { 7949 ValidKernelParam, 7950 PtrPtrKernelParam, 7951 PtrKernelParam, 7952 InvalidAddrSpacePtrKernelParam, 7953 InvalidKernelParam, 7954 RecordKernelParam 7955 }; 7956 7957 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7958 if (PT->isPointerType()) { 7959 QualType PointeeType = PT->getPointeeType(); 7960 if (PointeeType->isPointerType()) 7961 return PtrPtrKernelParam; 7962 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7963 PointeeType.getAddressSpace() == 0) 7964 return InvalidAddrSpacePtrKernelParam; 7965 return PtrKernelParam; 7966 } 7967 7968 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7969 // be used as builtin types. 7970 7971 if (PT->isImageType()) 7972 return PtrKernelParam; 7973 7974 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 7975 return InvalidKernelParam; 7976 7977 // OpenCL extension spec v1.2 s9.5: 7978 // This extension adds support for half scalar and vector types as built-in 7979 // types that can be used for arithmetic operations, conversions etc. 7980 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7981 return InvalidKernelParam; 7982 7983 if (PT->isRecordType()) 7984 return RecordKernelParam; 7985 7986 return ValidKernelParam; 7987 } 7988 7989 static void checkIsValidOpenCLKernelParameter( 7990 Sema &S, 7991 Declarator &D, 7992 ParmVarDecl *Param, 7993 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7994 QualType PT = Param->getType(); 7995 7996 // Cache the valid types we encounter to avoid rechecking structs that are 7997 // used again 7998 if (ValidTypes.count(PT.getTypePtr())) 7999 return; 8000 8001 switch (getOpenCLKernelParameterType(S, PT)) { 8002 case PtrPtrKernelParam: 8003 // OpenCL v1.2 s6.9.a: 8004 // A kernel function argument cannot be declared as a 8005 // pointer to a pointer type. 8006 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8007 D.setInvalidType(); 8008 return; 8009 8010 case InvalidAddrSpacePtrKernelParam: 8011 // OpenCL v1.0 s6.5: 8012 // __kernel function arguments declared to be a pointer of a type can point 8013 // to one of the following address spaces only : __global, __local or 8014 // __constant. 8015 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8016 D.setInvalidType(); 8017 return; 8018 8019 // OpenCL v1.2 s6.9.k: 8020 // Arguments to kernel functions in a program cannot be declared with the 8021 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8022 // uintptr_t or a struct and/or union that contain fields declared to be 8023 // one of these built-in scalar types. 8024 8025 case InvalidKernelParam: 8026 // OpenCL v1.2 s6.8 n: 8027 // A kernel function argument cannot be declared 8028 // of event_t type. 8029 // Do not diagnose half type since it is diagnosed as invalid argument 8030 // type for any function elsewhere. 8031 if (!PT->isHalfType()) 8032 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8033 D.setInvalidType(); 8034 return; 8035 8036 case PtrKernelParam: 8037 case ValidKernelParam: 8038 ValidTypes.insert(PT.getTypePtr()); 8039 return; 8040 8041 case RecordKernelParam: 8042 break; 8043 } 8044 8045 // Track nested structs we will inspect 8046 SmallVector<const Decl *, 4> VisitStack; 8047 8048 // Track where we are in the nested structs. Items will migrate from 8049 // VisitStack to HistoryStack as we do the DFS for bad field. 8050 SmallVector<const FieldDecl *, 4> HistoryStack; 8051 HistoryStack.push_back(nullptr); 8052 8053 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8054 VisitStack.push_back(PD); 8055 8056 assert(VisitStack.back() && "First decl null?"); 8057 8058 do { 8059 const Decl *Next = VisitStack.pop_back_val(); 8060 if (!Next) { 8061 assert(!HistoryStack.empty()); 8062 // Found a marker, we have gone up a level 8063 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8064 ValidTypes.insert(Hist->getType().getTypePtr()); 8065 8066 continue; 8067 } 8068 8069 // Adds everything except the original parameter declaration (which is not a 8070 // field itself) to the history stack. 8071 const RecordDecl *RD; 8072 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8073 HistoryStack.push_back(Field); 8074 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8075 } else { 8076 RD = cast<RecordDecl>(Next); 8077 } 8078 8079 // Add a null marker so we know when we've gone back up a level 8080 VisitStack.push_back(nullptr); 8081 8082 for (const auto *FD : RD->fields()) { 8083 QualType QT = FD->getType(); 8084 8085 if (ValidTypes.count(QT.getTypePtr())) 8086 continue; 8087 8088 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8089 if (ParamType == ValidKernelParam) 8090 continue; 8091 8092 if (ParamType == RecordKernelParam) { 8093 VisitStack.push_back(FD); 8094 continue; 8095 } 8096 8097 // OpenCL v1.2 s6.9.p: 8098 // Arguments to kernel functions that are declared to be a struct or union 8099 // do not allow OpenCL objects to be passed as elements of the struct or 8100 // union. 8101 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8102 ParamType == InvalidAddrSpacePtrKernelParam) { 8103 S.Diag(Param->getLocation(), 8104 diag::err_record_with_pointers_kernel_param) 8105 << PT->isUnionType() 8106 << PT; 8107 } else { 8108 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8109 } 8110 8111 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8112 << PD->getDeclName(); 8113 8114 // We have an error, now let's go back up through history and show where 8115 // the offending field came from 8116 for (ArrayRef<const FieldDecl *>::const_iterator 8117 I = HistoryStack.begin() + 1, 8118 E = HistoryStack.end(); 8119 I != E; ++I) { 8120 const FieldDecl *OuterField = *I; 8121 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8122 << OuterField->getType(); 8123 } 8124 8125 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8126 << QT->isPointerType() 8127 << QT; 8128 D.setInvalidType(); 8129 return; 8130 } 8131 } while (!VisitStack.empty()); 8132 } 8133 8134 /// Find the DeclContext in which a tag is implicitly declared if we see an 8135 /// elaborated type specifier in the specified context, and lookup finds 8136 /// nothing. 8137 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8138 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8139 DC = DC->getParent(); 8140 return DC; 8141 } 8142 8143 /// Find the Scope in which a tag is implicitly declared if we see an 8144 /// elaborated type specifier in the specified context, and lookup finds 8145 /// nothing. 8146 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8147 while (S->isClassScope() || 8148 (LangOpts.CPlusPlus && 8149 S->isFunctionPrototypeScope()) || 8150 ((S->getFlags() & Scope::DeclScope) == 0) || 8151 (S->getEntity() && S->getEntity()->isTransparentContext())) 8152 S = S->getParent(); 8153 return S; 8154 } 8155 8156 NamedDecl* 8157 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8158 TypeSourceInfo *TInfo, LookupResult &Previous, 8159 MultiTemplateParamsArg TemplateParamLists, 8160 bool &AddToScope) { 8161 QualType R = TInfo->getType(); 8162 8163 assert(R.getTypePtr()->isFunctionType()); 8164 8165 // TODO: consider using NameInfo for diagnostic. 8166 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8167 DeclarationName Name = NameInfo.getName(); 8168 StorageClass SC = getFunctionStorageClass(*this, D); 8169 8170 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8171 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8172 diag::err_invalid_thread) 8173 << DeclSpec::getSpecifierName(TSCS); 8174 8175 if (D.isFirstDeclarationOfMember()) 8176 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8177 D.getIdentifierLoc()); 8178 8179 bool isFriend = false; 8180 FunctionTemplateDecl *FunctionTemplate = nullptr; 8181 bool isMemberSpecialization = false; 8182 bool isFunctionTemplateSpecialization = false; 8183 8184 bool isDependentClassScopeExplicitSpecialization = false; 8185 bool HasExplicitTemplateArgs = false; 8186 TemplateArgumentListInfo TemplateArgs; 8187 8188 bool isVirtualOkay = false; 8189 8190 DeclContext *OriginalDC = DC; 8191 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8192 8193 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8194 isVirtualOkay); 8195 if (!NewFD) return nullptr; 8196 8197 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8198 NewFD->setTopLevelDeclInObjCContainer(); 8199 8200 // Set the lexical context. If this is a function-scope declaration, or has a 8201 // C++ scope specifier, or is the object of a friend declaration, the lexical 8202 // context will be different from the semantic context. 8203 NewFD->setLexicalDeclContext(CurContext); 8204 8205 if (IsLocalExternDecl) 8206 NewFD->setLocalExternDecl(); 8207 8208 if (getLangOpts().CPlusPlus) { 8209 bool isInline = D.getDeclSpec().isInlineSpecified(); 8210 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8211 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8212 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8213 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8214 isFriend = D.getDeclSpec().isFriendSpecified(); 8215 if (isFriend && !isInline && D.isFunctionDefinition()) { 8216 // C++ [class.friend]p5 8217 // A function can be defined in a friend declaration of a 8218 // class . . . . Such a function is implicitly inline. 8219 NewFD->setImplicitlyInline(); 8220 } 8221 8222 // If this is a method defined in an __interface, and is not a constructor 8223 // or an overloaded operator, then set the pure flag (isVirtual will already 8224 // return true). 8225 if (const CXXRecordDecl *Parent = 8226 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8227 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8228 NewFD->setPure(true); 8229 8230 // C++ [class.union]p2 8231 // A union can have member functions, but not virtual functions. 8232 if (isVirtual && Parent->isUnion()) 8233 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8234 } 8235 8236 SetNestedNameSpecifier(NewFD, D); 8237 isMemberSpecialization = false; 8238 isFunctionTemplateSpecialization = false; 8239 if (D.isInvalidType()) 8240 NewFD->setInvalidDecl(); 8241 8242 // Match up the template parameter lists with the scope specifier, then 8243 // determine whether we have a template or a template specialization. 8244 bool Invalid = false; 8245 if (TemplateParameterList *TemplateParams = 8246 MatchTemplateParametersToScopeSpecifier( 8247 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8248 D.getCXXScopeSpec(), 8249 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8250 ? D.getName().TemplateId 8251 : nullptr, 8252 TemplateParamLists, isFriend, isMemberSpecialization, 8253 Invalid)) { 8254 if (TemplateParams->size() > 0) { 8255 // This is a function template 8256 8257 // Check that we can declare a template here. 8258 if (CheckTemplateDeclScope(S, TemplateParams)) 8259 NewFD->setInvalidDecl(); 8260 8261 // A destructor cannot be a template. 8262 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8263 Diag(NewFD->getLocation(), diag::err_destructor_template); 8264 NewFD->setInvalidDecl(); 8265 } 8266 8267 // If we're adding a template to a dependent context, we may need to 8268 // rebuilding some of the types used within the template parameter list, 8269 // now that we know what the current instantiation is. 8270 if (DC->isDependentContext()) { 8271 ContextRAII SavedContext(*this, DC); 8272 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8273 Invalid = true; 8274 } 8275 8276 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8277 NewFD->getLocation(), 8278 Name, TemplateParams, 8279 NewFD); 8280 FunctionTemplate->setLexicalDeclContext(CurContext); 8281 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8282 8283 // For source fidelity, store the other template param lists. 8284 if (TemplateParamLists.size() > 1) { 8285 NewFD->setTemplateParameterListsInfo(Context, 8286 TemplateParamLists.drop_back(1)); 8287 } 8288 } else { 8289 // This is a function template specialization. 8290 isFunctionTemplateSpecialization = true; 8291 // For source fidelity, store all the template param lists. 8292 if (TemplateParamLists.size() > 0) 8293 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8294 8295 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8296 if (isFriend) { 8297 // We want to remove the "template<>", found here. 8298 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8299 8300 // If we remove the template<> and the name is not a 8301 // template-id, we're actually silently creating a problem: 8302 // the friend declaration will refer to an untemplated decl, 8303 // and clearly the user wants a template specialization. So 8304 // we need to insert '<>' after the name. 8305 SourceLocation InsertLoc; 8306 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8307 InsertLoc = D.getName().getSourceRange().getEnd(); 8308 InsertLoc = getLocForEndOfToken(InsertLoc); 8309 } 8310 8311 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8312 << Name << RemoveRange 8313 << FixItHint::CreateRemoval(RemoveRange) 8314 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8315 } 8316 } 8317 } 8318 else { 8319 // All template param lists were matched against the scope specifier: 8320 // this is NOT (an explicit specialization of) a template. 8321 if (TemplateParamLists.size() > 0) 8322 // For source fidelity, store all the template param lists. 8323 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8324 } 8325 8326 if (Invalid) { 8327 NewFD->setInvalidDecl(); 8328 if (FunctionTemplate) 8329 FunctionTemplate->setInvalidDecl(); 8330 } 8331 8332 // C++ [dcl.fct.spec]p5: 8333 // The virtual specifier shall only be used in declarations of 8334 // nonstatic class member functions that appear within a 8335 // member-specification of a class declaration; see 10.3. 8336 // 8337 if (isVirtual && !NewFD->isInvalidDecl()) { 8338 if (!isVirtualOkay) { 8339 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8340 diag::err_virtual_non_function); 8341 } else if (!CurContext->isRecord()) { 8342 // 'virtual' was specified outside of the class. 8343 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8344 diag::err_virtual_out_of_class) 8345 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8346 } else if (NewFD->getDescribedFunctionTemplate()) { 8347 // C++ [temp.mem]p3: 8348 // A member function template shall not be virtual. 8349 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8350 diag::err_virtual_member_function_template) 8351 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8352 } else { 8353 // Okay: Add virtual to the method. 8354 NewFD->setVirtualAsWritten(true); 8355 } 8356 8357 if (getLangOpts().CPlusPlus14 && 8358 NewFD->getReturnType()->isUndeducedType()) 8359 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8360 } 8361 8362 if (getLangOpts().CPlusPlus14 && 8363 (NewFD->isDependentContext() || 8364 (isFriend && CurContext->isDependentContext())) && 8365 NewFD->getReturnType()->isUndeducedType()) { 8366 // If the function template is referenced directly (for instance, as a 8367 // member of the current instantiation), pretend it has a dependent type. 8368 // This is not really justified by the standard, but is the only sane 8369 // thing to do. 8370 // FIXME: For a friend function, we have not marked the function as being 8371 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8372 const FunctionProtoType *FPT = 8373 NewFD->getType()->castAs<FunctionProtoType>(); 8374 QualType Result = 8375 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8376 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8377 FPT->getExtProtoInfo())); 8378 } 8379 8380 // C++ [dcl.fct.spec]p3: 8381 // The inline specifier shall not appear on a block scope function 8382 // declaration. 8383 if (isInline && !NewFD->isInvalidDecl()) { 8384 if (CurContext->isFunctionOrMethod()) { 8385 // 'inline' is not allowed on block scope function declaration. 8386 Diag(D.getDeclSpec().getInlineSpecLoc(), 8387 diag::err_inline_declaration_block_scope) << Name 8388 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8389 } 8390 } 8391 8392 // C++ [dcl.fct.spec]p6: 8393 // The explicit specifier shall be used only in the declaration of a 8394 // constructor or conversion function within its class definition; 8395 // see 12.3.1 and 12.3.2. 8396 if (isExplicit && !NewFD->isInvalidDecl() && 8397 !isa<CXXDeductionGuideDecl>(NewFD)) { 8398 if (!CurContext->isRecord()) { 8399 // 'explicit' was specified outside of the class. 8400 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8401 diag::err_explicit_out_of_class) 8402 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8403 } else if (!isa<CXXConstructorDecl>(NewFD) && 8404 !isa<CXXConversionDecl>(NewFD)) { 8405 // 'explicit' was specified on a function that wasn't a constructor 8406 // or conversion function. 8407 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8408 diag::err_explicit_non_ctor_or_conv_function) 8409 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8410 } 8411 } 8412 8413 if (isConstexpr) { 8414 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8415 // are implicitly inline. 8416 NewFD->setImplicitlyInline(); 8417 8418 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8419 // be either constructors or to return a literal type. Therefore, 8420 // destructors cannot be declared constexpr. 8421 if (isa<CXXDestructorDecl>(NewFD)) 8422 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8423 } 8424 8425 if (isConcept) { 8426 // This is a function concept. 8427 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8428 FTD->setConcept(); 8429 8430 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8431 // applied only to the definition of a function template [...] 8432 if (!D.isFunctionDefinition()) { 8433 Diag(D.getDeclSpec().getConceptSpecLoc(), 8434 diag::err_function_concept_not_defined); 8435 NewFD->setInvalidDecl(); 8436 } 8437 8438 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8439 // have no exception-specification and is treated as if it were specified 8440 // with noexcept(true) (15.4). [...] 8441 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8442 if (FPT->hasExceptionSpec()) { 8443 SourceRange Range; 8444 if (D.isFunctionDeclarator()) 8445 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8446 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8447 << FixItHint::CreateRemoval(Range); 8448 NewFD->setInvalidDecl(); 8449 } else { 8450 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8451 } 8452 8453 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8454 // following restrictions: 8455 // - The declared return type shall have the type bool. 8456 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8457 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8458 NewFD->setInvalidDecl(); 8459 } 8460 8461 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8462 // following restrictions: 8463 // - The declaration's parameter list shall be equivalent to an empty 8464 // parameter list. 8465 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8466 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8467 } 8468 8469 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8470 // implicity defined to be a constexpr declaration (implicitly inline) 8471 NewFD->setImplicitlyInline(); 8472 8473 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8474 // be declared with the thread_local, inline, friend, or constexpr 8475 // specifiers, [...] 8476 if (isInline) { 8477 Diag(D.getDeclSpec().getInlineSpecLoc(), 8478 diag::err_concept_decl_invalid_specifiers) 8479 << 1 << 1; 8480 NewFD->setInvalidDecl(true); 8481 } 8482 8483 if (isFriend) { 8484 Diag(D.getDeclSpec().getFriendSpecLoc(), 8485 diag::err_concept_decl_invalid_specifiers) 8486 << 1 << 2; 8487 NewFD->setInvalidDecl(true); 8488 } 8489 8490 if (isConstexpr) { 8491 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8492 diag::err_concept_decl_invalid_specifiers) 8493 << 1 << 3; 8494 NewFD->setInvalidDecl(true); 8495 } 8496 8497 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8498 // applied only to the definition of a function template or variable 8499 // template, declared in namespace scope. 8500 if (isFunctionTemplateSpecialization) { 8501 Diag(D.getDeclSpec().getConceptSpecLoc(), 8502 diag::err_concept_specified_specialization) << 1; 8503 NewFD->setInvalidDecl(true); 8504 return NewFD; 8505 } 8506 } 8507 8508 // If __module_private__ was specified, mark the function accordingly. 8509 if (D.getDeclSpec().isModulePrivateSpecified()) { 8510 if (isFunctionTemplateSpecialization) { 8511 SourceLocation ModulePrivateLoc 8512 = D.getDeclSpec().getModulePrivateSpecLoc(); 8513 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8514 << 0 8515 << FixItHint::CreateRemoval(ModulePrivateLoc); 8516 } else { 8517 NewFD->setModulePrivate(); 8518 if (FunctionTemplate) 8519 FunctionTemplate->setModulePrivate(); 8520 } 8521 } 8522 8523 if (isFriend) { 8524 if (FunctionTemplate) { 8525 FunctionTemplate->setObjectOfFriendDecl(); 8526 FunctionTemplate->setAccess(AS_public); 8527 } 8528 NewFD->setObjectOfFriendDecl(); 8529 NewFD->setAccess(AS_public); 8530 } 8531 8532 // If a function is defined as defaulted or deleted, mark it as such now. 8533 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8534 // definition kind to FDK_Definition. 8535 switch (D.getFunctionDefinitionKind()) { 8536 case FDK_Declaration: 8537 case FDK_Definition: 8538 break; 8539 8540 case FDK_Defaulted: 8541 NewFD->setDefaulted(); 8542 break; 8543 8544 case FDK_Deleted: 8545 NewFD->setDeletedAsWritten(); 8546 break; 8547 } 8548 8549 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8550 D.isFunctionDefinition()) { 8551 // C++ [class.mfct]p2: 8552 // A member function may be defined (8.4) in its class definition, in 8553 // which case it is an inline member function (7.1.2) 8554 NewFD->setImplicitlyInline(); 8555 } 8556 8557 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8558 !CurContext->isRecord()) { 8559 // C++ [class.static]p1: 8560 // A data or function member of a class may be declared static 8561 // in a class definition, in which case it is a static member of 8562 // the class. 8563 8564 // Complain about the 'static' specifier if it's on an out-of-line 8565 // member function definition. 8566 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8567 diag::err_static_out_of_line) 8568 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8569 } 8570 8571 // C++11 [except.spec]p15: 8572 // A deallocation function with no exception-specification is treated 8573 // as if it were specified with noexcept(true). 8574 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8575 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8576 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8577 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8578 NewFD->setType(Context.getFunctionType( 8579 FPT->getReturnType(), FPT->getParamTypes(), 8580 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8581 } 8582 8583 // Filter out previous declarations that don't match the scope. 8584 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8585 D.getCXXScopeSpec().isNotEmpty() || 8586 isMemberSpecialization || 8587 isFunctionTemplateSpecialization); 8588 8589 // Handle GNU asm-label extension (encoded as an attribute). 8590 if (Expr *E = (Expr*) D.getAsmLabel()) { 8591 // The parser guarantees this is a string. 8592 StringLiteral *SE = cast<StringLiteral>(E); 8593 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8594 SE->getString(), 0)); 8595 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8596 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8597 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8598 if (I != ExtnameUndeclaredIdentifiers.end()) { 8599 if (isDeclExternC(NewFD)) { 8600 NewFD->addAttr(I->second); 8601 ExtnameUndeclaredIdentifiers.erase(I); 8602 } else 8603 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8604 << /*Variable*/0 << NewFD; 8605 } 8606 } 8607 8608 // Copy the parameter declarations from the declarator D to the function 8609 // declaration NewFD, if they are available. First scavenge them into Params. 8610 SmallVector<ParmVarDecl*, 16> Params; 8611 unsigned FTIIdx; 8612 if (D.isFunctionDeclarator(FTIIdx)) { 8613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8614 8615 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8616 // function that takes no arguments, not a function that takes a 8617 // single void argument. 8618 // We let through "const void" here because Sema::GetTypeForDeclarator 8619 // already checks for that case. 8620 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8621 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8622 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8623 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8624 Param->setDeclContext(NewFD); 8625 Params.push_back(Param); 8626 8627 if (Param->isInvalidDecl()) 8628 NewFD->setInvalidDecl(); 8629 } 8630 } 8631 8632 if (!getLangOpts().CPlusPlus) { 8633 // In C, find all the tag declarations from the prototype and move them 8634 // into the function DeclContext. Remove them from the surrounding tag 8635 // injection context of the function, which is typically but not always 8636 // the TU. 8637 DeclContext *PrototypeTagContext = 8638 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8639 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8640 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8641 8642 // We don't want to reparent enumerators. Look at their parent enum 8643 // instead. 8644 if (!TD) { 8645 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8646 TD = cast<EnumDecl>(ECD->getDeclContext()); 8647 } 8648 if (!TD) 8649 continue; 8650 DeclContext *TagDC = TD->getLexicalDeclContext(); 8651 if (!TagDC->containsDecl(TD)) 8652 continue; 8653 TagDC->removeDecl(TD); 8654 TD->setDeclContext(NewFD); 8655 NewFD->addDecl(TD); 8656 8657 // Preserve the lexical DeclContext if it is not the surrounding tag 8658 // injection context of the FD. In this example, the semantic context of 8659 // E will be f and the lexical context will be S, while both the 8660 // semantic and lexical contexts of S will be f: 8661 // void f(struct S { enum E { a } f; } s); 8662 if (TagDC != PrototypeTagContext) 8663 TD->setLexicalDeclContext(TagDC); 8664 } 8665 } 8666 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8667 // When we're declaring a function with a typedef, typeof, etc as in the 8668 // following example, we'll need to synthesize (unnamed) 8669 // parameters for use in the declaration. 8670 // 8671 // @code 8672 // typedef void fn(int); 8673 // fn f; 8674 // @endcode 8675 8676 // Synthesize a parameter for each argument type. 8677 for (const auto &AI : FT->param_types()) { 8678 ParmVarDecl *Param = 8679 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8680 Param->setScopeInfo(0, Params.size()); 8681 Params.push_back(Param); 8682 } 8683 } else { 8684 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8685 "Should not need args for typedef of non-prototype fn"); 8686 } 8687 8688 // Finally, we know we have the right number of parameters, install them. 8689 NewFD->setParams(Params); 8690 8691 if (D.getDeclSpec().isNoreturnSpecified()) 8692 NewFD->addAttr( 8693 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8694 Context, 0)); 8695 8696 // Functions returning a variably modified type violate C99 6.7.5.2p2 8697 // because all functions have linkage. 8698 if (!NewFD->isInvalidDecl() && 8699 NewFD->getReturnType()->isVariablyModifiedType()) { 8700 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8701 NewFD->setInvalidDecl(); 8702 } 8703 8704 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8705 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8706 !NewFD->hasAttr<SectionAttr>()) { 8707 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8708 PragmaClangTextSection.SectionName, 8709 PragmaClangTextSection.PragmaLocation)); 8710 } 8711 8712 // Apply an implicit SectionAttr if #pragma code_seg is active. 8713 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8714 !NewFD->hasAttr<SectionAttr>()) { 8715 NewFD->addAttr( 8716 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8717 CodeSegStack.CurrentValue->getString(), 8718 CodeSegStack.CurrentPragmaLocation)); 8719 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8720 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8721 ASTContext::PSF_Read, 8722 NewFD)) 8723 NewFD->dropAttr<SectionAttr>(); 8724 } 8725 8726 // Handle attributes. 8727 ProcessDeclAttributes(S, NewFD, D); 8728 8729 if (getLangOpts().OpenCL) { 8730 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8731 // type declaration will generate a compilation error. 8732 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8733 if (AddressSpace == LangAS::opencl_local || 8734 AddressSpace == LangAS::opencl_global || 8735 AddressSpace == LangAS::opencl_constant) { 8736 Diag(NewFD->getLocation(), 8737 diag::err_opencl_return_value_with_address_space); 8738 NewFD->setInvalidDecl(); 8739 } 8740 } 8741 8742 if (!getLangOpts().CPlusPlus) { 8743 // Perform semantic checking on the function declaration. 8744 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8745 CheckMain(NewFD, D.getDeclSpec()); 8746 8747 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8748 CheckMSVCRTEntryPoint(NewFD); 8749 8750 if (!NewFD->isInvalidDecl()) 8751 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8752 isMemberSpecialization)); 8753 else if (!Previous.empty()) 8754 // Recover gracefully from an invalid redeclaration. 8755 D.setRedeclaration(true); 8756 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8757 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8758 "previous declaration set still overloaded"); 8759 8760 // Diagnose no-prototype function declarations with calling conventions that 8761 // don't support variadic calls. Only do this in C and do it after merging 8762 // possibly prototyped redeclarations. 8763 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8764 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8765 CallingConv CC = FT->getExtInfo().getCC(); 8766 if (!supportsVariadicCall(CC)) { 8767 // Windows system headers sometimes accidentally use stdcall without 8768 // (void) parameters, so we relax this to a warning. 8769 int DiagID = 8770 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8771 Diag(NewFD->getLocation(), DiagID) 8772 << FunctionType::getNameForCallConv(CC); 8773 } 8774 } 8775 } else { 8776 // C++11 [replacement.functions]p3: 8777 // The program's definitions shall not be specified as inline. 8778 // 8779 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8780 // 8781 // Suppress the diagnostic if the function is __attribute__((used)), since 8782 // that forces an external definition to be emitted. 8783 if (D.getDeclSpec().isInlineSpecified() && 8784 NewFD->isReplaceableGlobalAllocationFunction() && 8785 !NewFD->hasAttr<UsedAttr>()) 8786 Diag(D.getDeclSpec().getInlineSpecLoc(), 8787 diag::ext_operator_new_delete_declared_inline) 8788 << NewFD->getDeclName(); 8789 8790 // If the declarator is a template-id, translate the parser's template 8791 // argument list into our AST format. 8792 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8793 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8794 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8795 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8796 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8797 TemplateId->NumArgs); 8798 translateTemplateArguments(TemplateArgsPtr, 8799 TemplateArgs); 8800 8801 HasExplicitTemplateArgs = true; 8802 8803 if (NewFD->isInvalidDecl()) { 8804 HasExplicitTemplateArgs = false; 8805 } else if (FunctionTemplate) { 8806 // Function template with explicit template arguments. 8807 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8808 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8809 8810 HasExplicitTemplateArgs = false; 8811 } else { 8812 assert((isFunctionTemplateSpecialization || 8813 D.getDeclSpec().isFriendSpecified()) && 8814 "should have a 'template<>' for this decl"); 8815 // "friend void foo<>(int);" is an implicit specialization decl. 8816 isFunctionTemplateSpecialization = true; 8817 } 8818 } else if (isFriend && isFunctionTemplateSpecialization) { 8819 // This combination is only possible in a recovery case; the user 8820 // wrote something like: 8821 // template <> friend void foo(int); 8822 // which we're recovering from as if the user had written: 8823 // friend void foo<>(int); 8824 // Go ahead and fake up a template id. 8825 HasExplicitTemplateArgs = true; 8826 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8827 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8828 } 8829 8830 // We do not add HD attributes to specializations here because 8831 // they may have different constexpr-ness compared to their 8832 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8833 // may end up with different effective targets. Instead, a 8834 // specialization inherits its target attributes from its template 8835 // in the CheckFunctionTemplateSpecialization() call below. 8836 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8837 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8838 8839 // If it's a friend (and only if it's a friend), it's possible 8840 // that either the specialized function type or the specialized 8841 // template is dependent, and therefore matching will fail. In 8842 // this case, don't check the specialization yet. 8843 bool InstantiationDependent = false; 8844 if (isFunctionTemplateSpecialization && isFriend && 8845 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8846 TemplateSpecializationType::anyDependentTemplateArguments( 8847 TemplateArgs, 8848 InstantiationDependent))) { 8849 assert(HasExplicitTemplateArgs && 8850 "friend function specialization without template args"); 8851 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8852 Previous)) 8853 NewFD->setInvalidDecl(); 8854 } else if (isFunctionTemplateSpecialization) { 8855 if (CurContext->isDependentContext() && CurContext->isRecord() 8856 && !isFriend) { 8857 isDependentClassScopeExplicitSpecialization = true; 8858 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8859 diag::ext_function_specialization_in_class : 8860 diag::err_function_specialization_in_class) 8861 << NewFD->getDeclName(); 8862 } else if (CheckFunctionTemplateSpecialization(NewFD, 8863 (HasExplicitTemplateArgs ? &TemplateArgs 8864 : nullptr), 8865 Previous)) 8866 NewFD->setInvalidDecl(); 8867 8868 // C++ [dcl.stc]p1: 8869 // A storage-class-specifier shall not be specified in an explicit 8870 // specialization (14.7.3) 8871 FunctionTemplateSpecializationInfo *Info = 8872 NewFD->getTemplateSpecializationInfo(); 8873 if (Info && SC != SC_None) { 8874 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8875 Diag(NewFD->getLocation(), 8876 diag::err_explicit_specialization_inconsistent_storage_class) 8877 << SC 8878 << FixItHint::CreateRemoval( 8879 D.getDeclSpec().getStorageClassSpecLoc()); 8880 8881 else 8882 Diag(NewFD->getLocation(), 8883 diag::ext_explicit_specialization_storage_class) 8884 << FixItHint::CreateRemoval( 8885 D.getDeclSpec().getStorageClassSpecLoc()); 8886 } 8887 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8888 if (CheckMemberSpecialization(NewFD, Previous)) 8889 NewFD->setInvalidDecl(); 8890 } 8891 8892 // Perform semantic checking on the function declaration. 8893 if (!isDependentClassScopeExplicitSpecialization) { 8894 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8895 CheckMain(NewFD, D.getDeclSpec()); 8896 8897 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8898 CheckMSVCRTEntryPoint(NewFD); 8899 8900 if (!NewFD->isInvalidDecl()) 8901 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8902 isMemberSpecialization)); 8903 else if (!Previous.empty()) 8904 // Recover gracefully from an invalid redeclaration. 8905 D.setRedeclaration(true); 8906 } 8907 8908 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8909 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8910 "previous declaration set still overloaded"); 8911 8912 NamedDecl *PrincipalDecl = (FunctionTemplate 8913 ? cast<NamedDecl>(FunctionTemplate) 8914 : NewFD); 8915 8916 if (isFriend && NewFD->getPreviousDecl()) { 8917 AccessSpecifier Access = AS_public; 8918 if (!NewFD->isInvalidDecl()) 8919 Access = NewFD->getPreviousDecl()->getAccess(); 8920 8921 NewFD->setAccess(Access); 8922 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8923 } 8924 8925 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8926 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8927 PrincipalDecl->setNonMemberOperator(); 8928 8929 // If we have a function template, check the template parameter 8930 // list. This will check and merge default template arguments. 8931 if (FunctionTemplate) { 8932 FunctionTemplateDecl *PrevTemplate = 8933 FunctionTemplate->getPreviousDecl(); 8934 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8935 PrevTemplate ? PrevTemplate->getTemplateParameters() 8936 : nullptr, 8937 D.getDeclSpec().isFriendSpecified() 8938 ? (D.isFunctionDefinition() 8939 ? TPC_FriendFunctionTemplateDefinition 8940 : TPC_FriendFunctionTemplate) 8941 : (D.getCXXScopeSpec().isSet() && 8942 DC && DC->isRecord() && 8943 DC->isDependentContext()) 8944 ? TPC_ClassTemplateMember 8945 : TPC_FunctionTemplate); 8946 } 8947 8948 if (NewFD->isInvalidDecl()) { 8949 // Ignore all the rest of this. 8950 } else if (!D.isRedeclaration()) { 8951 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8952 AddToScope }; 8953 // Fake up an access specifier if it's supposed to be a class member. 8954 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8955 NewFD->setAccess(AS_public); 8956 8957 // Qualified decls generally require a previous declaration. 8958 if (D.getCXXScopeSpec().isSet()) { 8959 // ...with the major exception of templated-scope or 8960 // dependent-scope friend declarations. 8961 8962 // TODO: we currently also suppress this check in dependent 8963 // contexts because (1) the parameter depth will be off when 8964 // matching friend templates and (2) we might actually be 8965 // selecting a friend based on a dependent factor. But there 8966 // are situations where these conditions don't apply and we 8967 // can actually do this check immediately. 8968 if (isFriend && 8969 (TemplateParamLists.size() || 8970 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8971 CurContext->isDependentContext())) { 8972 // ignore these 8973 } else { 8974 // The user tried to provide an out-of-line definition for a 8975 // function that is a member of a class or namespace, but there 8976 // was no such member function declared (C++ [class.mfct]p2, 8977 // C++ [namespace.memdef]p2). For example: 8978 // 8979 // class X { 8980 // void f() const; 8981 // }; 8982 // 8983 // void X::f() { } // ill-formed 8984 // 8985 // Complain about this problem, and attempt to suggest close 8986 // matches (e.g., those that differ only in cv-qualifiers and 8987 // whether the parameter types are references). 8988 8989 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8990 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8991 AddToScope = ExtraArgs.AddToScope; 8992 return Result; 8993 } 8994 } 8995 8996 // Unqualified local friend declarations are required to resolve 8997 // to something. 8998 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8999 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9000 *this, Previous, NewFD, ExtraArgs, true, S)) { 9001 AddToScope = ExtraArgs.AddToScope; 9002 return Result; 9003 } 9004 } 9005 } else if (!D.isFunctionDefinition() && 9006 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9007 !isFriend && !isFunctionTemplateSpecialization && 9008 !isMemberSpecialization) { 9009 // An out-of-line member function declaration must also be a 9010 // definition (C++ [class.mfct]p2). 9011 // Note that this is not the case for explicit specializations of 9012 // function templates or member functions of class templates, per 9013 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9014 // extension for compatibility with old SWIG code which likes to 9015 // generate them. 9016 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9017 << D.getCXXScopeSpec().getRange(); 9018 } 9019 } 9020 9021 ProcessPragmaWeak(S, NewFD); 9022 checkAttributesAfterMerging(*this, *NewFD); 9023 9024 AddKnownFunctionAttributes(NewFD); 9025 9026 if (NewFD->hasAttr<OverloadableAttr>() && 9027 !NewFD->getType()->getAs<FunctionProtoType>()) { 9028 Diag(NewFD->getLocation(), 9029 diag::err_attribute_overloadable_no_prototype) 9030 << NewFD; 9031 9032 // Turn this into a variadic function with no parameters. 9033 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9034 FunctionProtoType::ExtProtoInfo EPI( 9035 Context.getDefaultCallingConvention(true, false)); 9036 EPI.Variadic = true; 9037 EPI.ExtInfo = FT->getExtInfo(); 9038 9039 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9040 NewFD->setType(R); 9041 } 9042 9043 // If there's a #pragma GCC visibility in scope, and this isn't a class 9044 // member, set the visibility of this function. 9045 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9046 AddPushedVisibilityAttribute(NewFD); 9047 9048 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9049 // marking the function. 9050 AddCFAuditedAttribute(NewFD); 9051 9052 // If this is a function definition, check if we have to apply optnone due to 9053 // a pragma. 9054 if(D.isFunctionDefinition()) 9055 AddRangeBasedOptnone(NewFD); 9056 9057 // If this is the first declaration of an extern C variable, update 9058 // the map of such variables. 9059 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9060 isIncompleteDeclExternC(*this, NewFD)) 9061 RegisterLocallyScopedExternCDecl(NewFD, S); 9062 9063 // Set this FunctionDecl's range up to the right paren. 9064 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9065 9066 if (D.isRedeclaration() && !Previous.empty()) { 9067 checkDLLAttributeRedeclaration( 9068 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9069 isMemberSpecialization || isFunctionTemplateSpecialization, 9070 D.isFunctionDefinition()); 9071 } 9072 9073 if (getLangOpts().CUDA) { 9074 IdentifierInfo *II = NewFD->getIdentifier(); 9075 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9076 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9077 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9078 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9079 9080 Context.setcudaConfigureCallDecl(NewFD); 9081 } 9082 9083 // Variadic functions, other than a *declaration* of printf, are not allowed 9084 // in device-side CUDA code, unless someone passed 9085 // -fcuda-allow-variadic-functions. 9086 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9087 (NewFD->hasAttr<CUDADeviceAttr>() || 9088 NewFD->hasAttr<CUDAGlobalAttr>()) && 9089 !(II && II->isStr("printf") && NewFD->isExternC() && 9090 !D.isFunctionDefinition())) { 9091 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9092 } 9093 } 9094 9095 MarkUnusedFileScopedDecl(NewFD); 9096 9097 if (getLangOpts().CPlusPlus) { 9098 if (FunctionTemplate) { 9099 if (NewFD->isInvalidDecl()) 9100 FunctionTemplate->setInvalidDecl(); 9101 return FunctionTemplate; 9102 } 9103 9104 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9105 CompleteMemberSpecialization(NewFD, Previous); 9106 } 9107 9108 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9109 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9110 if ((getLangOpts().OpenCLVersion >= 120) 9111 && (SC == SC_Static)) { 9112 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9113 D.setInvalidType(); 9114 } 9115 9116 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9117 if (!NewFD->getReturnType()->isVoidType()) { 9118 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9119 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9120 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9121 : FixItHint()); 9122 D.setInvalidType(); 9123 } 9124 9125 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9126 for (auto Param : NewFD->parameters()) 9127 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9128 } 9129 for (const ParmVarDecl *Param : NewFD->parameters()) { 9130 QualType PT = Param->getType(); 9131 9132 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9133 // types. 9134 if (getLangOpts().OpenCLVersion >= 200) { 9135 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9136 QualType ElemTy = PipeTy->getElementType(); 9137 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9138 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9139 D.setInvalidType(); 9140 } 9141 } 9142 } 9143 } 9144 9145 // Here we have an function template explicit specialization at class scope. 9146 // The actually specialization will be postponed to template instatiation 9147 // time via the ClassScopeFunctionSpecializationDecl node. 9148 if (isDependentClassScopeExplicitSpecialization) { 9149 ClassScopeFunctionSpecializationDecl *NewSpec = 9150 ClassScopeFunctionSpecializationDecl::Create( 9151 Context, CurContext, SourceLocation(), 9152 cast<CXXMethodDecl>(NewFD), 9153 HasExplicitTemplateArgs, TemplateArgs); 9154 CurContext->addDecl(NewSpec); 9155 AddToScope = false; 9156 } 9157 9158 return NewFD; 9159 } 9160 9161 /// \brief Checks if the new declaration declared in dependent context must be 9162 /// put in the same redeclaration chain as the specified declaration. 9163 /// 9164 /// \param D Declaration that is checked. 9165 /// \param PrevDecl Previous declaration found with proper lookup method for the 9166 /// same declaration name. 9167 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9168 /// belongs to. 9169 /// 9170 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9171 // Any declarations should be put into redeclaration chains except for 9172 // friend declaration in a dependent context that names a function in 9173 // namespace scope. 9174 // 9175 // This allows to compile code like: 9176 // 9177 // void func(); 9178 // template<typename T> class C1 { friend void func() { } }; 9179 // template<typename T> class C2 { friend void func() { } }; 9180 // 9181 // This code snippet is a valid code unless both templates are instantiated. 9182 return !(D->getLexicalDeclContext()->isDependentContext() && 9183 D->getDeclContext()->isFileContext() && 9184 D->getFriendObjectKind() != Decl::FOK_None); 9185 } 9186 9187 /// \brief Perform semantic checking of a new function declaration. 9188 /// 9189 /// Performs semantic analysis of the new function declaration 9190 /// NewFD. This routine performs all semantic checking that does not 9191 /// require the actual declarator involved in the declaration, and is 9192 /// used both for the declaration of functions as they are parsed 9193 /// (called via ActOnDeclarator) and for the declaration of functions 9194 /// that have been instantiated via C++ template instantiation (called 9195 /// via InstantiateDecl). 9196 /// 9197 /// \param IsMemberSpecialization whether this new function declaration is 9198 /// a member specialization (that replaces any definition provided by the 9199 /// previous declaration). 9200 /// 9201 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9202 /// 9203 /// \returns true if the function declaration is a redeclaration. 9204 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9205 LookupResult &Previous, 9206 bool IsMemberSpecialization) { 9207 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9208 "Variably modified return types are not handled here"); 9209 9210 // Determine whether the type of this function should be merged with 9211 // a previous visible declaration. This never happens for functions in C++, 9212 // and always happens in C if the previous declaration was visible. 9213 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9214 !Previous.isShadowed(); 9215 9216 bool Redeclaration = false; 9217 NamedDecl *OldDecl = nullptr; 9218 bool MayNeedOverloadableChecks = false; 9219 9220 // Merge or overload the declaration with an existing declaration of 9221 // the same name, if appropriate. 9222 if (!Previous.empty()) { 9223 // Determine whether NewFD is an overload of PrevDecl or 9224 // a declaration that requires merging. If it's an overload, 9225 // there's no more work to do here; we'll just add the new 9226 // function to the scope. 9227 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9228 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9229 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9230 Redeclaration = true; 9231 OldDecl = Candidate; 9232 } 9233 } else { 9234 MayNeedOverloadableChecks = true; 9235 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9236 /*NewIsUsingDecl*/ false)) { 9237 case Ovl_Match: 9238 Redeclaration = true; 9239 break; 9240 9241 case Ovl_NonFunction: 9242 Redeclaration = true; 9243 break; 9244 9245 case Ovl_Overload: 9246 Redeclaration = false; 9247 break; 9248 } 9249 } 9250 } 9251 9252 // Check for a previous extern "C" declaration with this name. 9253 if (!Redeclaration && 9254 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9255 if (!Previous.empty()) { 9256 // This is an extern "C" declaration with the same name as a previous 9257 // declaration, and thus redeclares that entity... 9258 Redeclaration = true; 9259 OldDecl = Previous.getFoundDecl(); 9260 MergeTypeWithPrevious = false; 9261 9262 // ... except in the presence of __attribute__((overloadable)). 9263 if (OldDecl->hasAttr<OverloadableAttr>() || 9264 NewFD->hasAttr<OverloadableAttr>()) { 9265 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9266 MayNeedOverloadableChecks = true; 9267 Redeclaration = false; 9268 OldDecl = nullptr; 9269 } 9270 } 9271 } 9272 } 9273 9274 // C++11 [dcl.constexpr]p8: 9275 // A constexpr specifier for a non-static member function that is not 9276 // a constructor declares that member function to be const. 9277 // 9278 // This needs to be delayed until we know whether this is an out-of-line 9279 // definition of a static member function. 9280 // 9281 // This rule is not present in C++1y, so we produce a backwards 9282 // compatibility warning whenever it happens in C++11. 9283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9284 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9285 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9286 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9287 CXXMethodDecl *OldMD = nullptr; 9288 if (OldDecl) 9289 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9290 if (!OldMD || !OldMD->isStatic()) { 9291 const FunctionProtoType *FPT = 9292 MD->getType()->castAs<FunctionProtoType>(); 9293 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9294 EPI.TypeQuals |= Qualifiers::Const; 9295 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9296 FPT->getParamTypes(), EPI)); 9297 9298 // Warn that we did this, if we're not performing template instantiation. 9299 // In that case, we'll have warned already when the template was defined. 9300 if (!inTemplateInstantiation()) { 9301 SourceLocation AddConstLoc; 9302 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9303 .IgnoreParens().getAs<FunctionTypeLoc>()) 9304 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9305 9306 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9307 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9308 } 9309 } 9310 } 9311 9312 if (Redeclaration) { 9313 // NewFD and OldDecl represent declarations that need to be 9314 // merged. 9315 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9316 NewFD->setInvalidDecl(); 9317 return Redeclaration; 9318 } 9319 9320 Previous.clear(); 9321 Previous.addDecl(OldDecl); 9322 9323 if (FunctionTemplateDecl *OldTemplateDecl 9324 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9325 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9326 FunctionTemplateDecl *NewTemplateDecl 9327 = NewFD->getDescribedFunctionTemplate(); 9328 assert(NewTemplateDecl && "Template/non-template mismatch"); 9329 if (CXXMethodDecl *Method 9330 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9331 Method->setAccess(OldTemplateDecl->getAccess()); 9332 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9333 } 9334 9335 // If this is an explicit specialization of a member that is a function 9336 // template, mark it as a member specialization. 9337 if (IsMemberSpecialization && 9338 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9339 NewTemplateDecl->setMemberSpecialization(); 9340 assert(OldTemplateDecl->isMemberSpecialization()); 9341 // Explicit specializations of a member template do not inherit deleted 9342 // status from the parent member template that they are specializing. 9343 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9344 FunctionDecl *const OldTemplatedDecl = 9345 OldTemplateDecl->getTemplatedDecl(); 9346 // FIXME: This assert will not hold in the presence of modules. 9347 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9348 // FIXME: We need an update record for this AST mutation. 9349 OldTemplatedDecl->setDeletedAsWritten(false); 9350 } 9351 } 9352 9353 } else { 9354 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9355 // This needs to happen first so that 'inline' propagates. 9356 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9357 if (isa<CXXMethodDecl>(NewFD)) 9358 NewFD->setAccess(OldDecl->getAccess()); 9359 } 9360 } 9361 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9362 !NewFD->getAttr<OverloadableAttr>()) { 9363 assert((Previous.empty() || 9364 llvm::any_of(Previous, 9365 [](const NamedDecl *ND) { 9366 return ND->hasAttr<OverloadableAttr>(); 9367 })) && 9368 "Non-redecls shouldn't happen without overloadable present"); 9369 9370 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9371 const auto *FD = dyn_cast<FunctionDecl>(ND); 9372 return FD && !FD->hasAttr<OverloadableAttr>(); 9373 }); 9374 9375 if (OtherUnmarkedIter != Previous.end()) { 9376 Diag(NewFD->getLocation(), 9377 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9378 Diag((*OtherUnmarkedIter)->getLocation(), 9379 diag::note_attribute_overloadable_prev_overload) 9380 << false; 9381 9382 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9383 } 9384 } 9385 9386 // Semantic checking for this function declaration (in isolation). 9387 9388 if (getLangOpts().CPlusPlus) { 9389 // C++-specific checks. 9390 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9391 CheckConstructor(Constructor); 9392 } else if (CXXDestructorDecl *Destructor = 9393 dyn_cast<CXXDestructorDecl>(NewFD)) { 9394 CXXRecordDecl *Record = Destructor->getParent(); 9395 QualType ClassType = Context.getTypeDeclType(Record); 9396 9397 // FIXME: Shouldn't we be able to perform this check even when the class 9398 // type is dependent? Both gcc and edg can handle that. 9399 if (!ClassType->isDependentType()) { 9400 DeclarationName Name 9401 = Context.DeclarationNames.getCXXDestructorName( 9402 Context.getCanonicalType(ClassType)); 9403 if (NewFD->getDeclName() != Name) { 9404 Diag(NewFD->getLocation(), diag::err_destructor_name); 9405 NewFD->setInvalidDecl(); 9406 return Redeclaration; 9407 } 9408 } 9409 } else if (CXXConversionDecl *Conversion 9410 = dyn_cast<CXXConversionDecl>(NewFD)) { 9411 ActOnConversionDeclarator(Conversion); 9412 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9413 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9414 CheckDeductionGuideTemplate(TD); 9415 9416 // A deduction guide is not on the list of entities that can be 9417 // explicitly specialized. 9418 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9419 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9420 << /*explicit specialization*/ 1; 9421 } 9422 9423 // Find any virtual functions that this function overrides. 9424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9425 if (!Method->isFunctionTemplateSpecialization() && 9426 !Method->getDescribedFunctionTemplate() && 9427 Method->isCanonicalDecl()) { 9428 if (AddOverriddenMethods(Method->getParent(), Method)) { 9429 // If the function was marked as "static", we have a problem. 9430 if (NewFD->getStorageClass() == SC_Static) { 9431 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9432 } 9433 } 9434 } 9435 9436 if (Method->isStatic()) 9437 checkThisInStaticMemberFunctionType(Method); 9438 } 9439 9440 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9441 if (NewFD->isOverloadedOperator() && 9442 CheckOverloadedOperatorDeclaration(NewFD)) { 9443 NewFD->setInvalidDecl(); 9444 return Redeclaration; 9445 } 9446 9447 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9448 if (NewFD->getLiteralIdentifier() && 9449 CheckLiteralOperatorDeclaration(NewFD)) { 9450 NewFD->setInvalidDecl(); 9451 return Redeclaration; 9452 } 9453 9454 // In C++, check default arguments now that we have merged decls. Unless 9455 // the lexical context is the class, because in this case this is done 9456 // during delayed parsing anyway. 9457 if (!CurContext->isRecord()) 9458 CheckCXXDefaultArguments(NewFD); 9459 9460 // If this function declares a builtin function, check the type of this 9461 // declaration against the expected type for the builtin. 9462 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9463 ASTContext::GetBuiltinTypeError Error; 9464 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9465 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9466 // If the type of the builtin differs only in its exception 9467 // specification, that's OK. 9468 // FIXME: If the types do differ in this way, it would be better to 9469 // retain the 'noexcept' form of the type. 9470 if (!T.isNull() && 9471 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9472 NewFD->getType())) 9473 // The type of this function differs from the type of the builtin, 9474 // so forget about the builtin entirely. 9475 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9476 } 9477 9478 // If this function is declared as being extern "C", then check to see if 9479 // the function returns a UDT (class, struct, or union type) that is not C 9480 // compatible, and if it does, warn the user. 9481 // But, issue any diagnostic on the first declaration only. 9482 if (Previous.empty() && NewFD->isExternC()) { 9483 QualType R = NewFD->getReturnType(); 9484 if (R->isIncompleteType() && !R->isVoidType()) 9485 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9486 << NewFD << R; 9487 else if (!R.isPODType(Context) && !R->isVoidType() && 9488 !R->isObjCObjectPointerType()) 9489 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9490 } 9491 9492 // C++1z [dcl.fct]p6: 9493 // [...] whether the function has a non-throwing exception-specification 9494 // [is] part of the function type 9495 // 9496 // This results in an ABI break between C++14 and C++17 for functions whose 9497 // declared type includes an exception-specification in a parameter or 9498 // return type. (Exception specifications on the function itself are OK in 9499 // most cases, and exception specifications are not permitted in most other 9500 // contexts where they could make it into a mangling.) 9501 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9502 auto HasNoexcept = [&](QualType T) -> bool { 9503 // Strip off declarator chunks that could be between us and a function 9504 // type. We don't need to look far, exception specifications are very 9505 // restricted prior to C++17. 9506 if (auto *RT = T->getAs<ReferenceType>()) 9507 T = RT->getPointeeType(); 9508 else if (T->isAnyPointerType()) 9509 T = T->getPointeeType(); 9510 else if (auto *MPT = T->getAs<MemberPointerType>()) 9511 T = MPT->getPointeeType(); 9512 if (auto *FPT = T->getAs<FunctionProtoType>()) 9513 if (FPT->isNothrow(Context)) 9514 return true; 9515 return false; 9516 }; 9517 9518 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9519 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9520 for (QualType T : FPT->param_types()) 9521 AnyNoexcept |= HasNoexcept(T); 9522 if (AnyNoexcept) 9523 Diag(NewFD->getLocation(), 9524 diag::warn_cxx1z_compat_exception_spec_in_signature) 9525 << NewFD; 9526 } 9527 9528 if (!Redeclaration && LangOpts.CUDA) 9529 checkCUDATargetOverload(NewFD, Previous); 9530 } 9531 return Redeclaration; 9532 } 9533 9534 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9535 // C++11 [basic.start.main]p3: 9536 // A program that [...] declares main to be inline, static or 9537 // constexpr is ill-formed. 9538 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9539 // appear in a declaration of main. 9540 // static main is not an error under C99, but we should warn about it. 9541 // We accept _Noreturn main as an extension. 9542 if (FD->getStorageClass() == SC_Static) 9543 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9544 ? diag::err_static_main : diag::warn_static_main) 9545 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9546 if (FD->isInlineSpecified()) 9547 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9548 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9549 if (DS.isNoreturnSpecified()) { 9550 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9551 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9552 Diag(NoreturnLoc, diag::ext_noreturn_main); 9553 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9554 << FixItHint::CreateRemoval(NoreturnRange); 9555 } 9556 if (FD->isConstexpr()) { 9557 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9558 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9559 FD->setConstexpr(false); 9560 } 9561 9562 if (getLangOpts().OpenCL) { 9563 Diag(FD->getLocation(), diag::err_opencl_no_main) 9564 << FD->hasAttr<OpenCLKernelAttr>(); 9565 FD->setInvalidDecl(); 9566 return; 9567 } 9568 9569 QualType T = FD->getType(); 9570 assert(T->isFunctionType() && "function decl is not of function type"); 9571 const FunctionType* FT = T->castAs<FunctionType>(); 9572 9573 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9574 // In C with GNU extensions we allow main() to have non-integer return 9575 // type, but we should warn about the extension, and we disable the 9576 // implicit-return-zero rule. 9577 9578 // GCC in C mode accepts qualified 'int'. 9579 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9580 FD->setHasImplicitReturnZero(true); 9581 else { 9582 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9583 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9584 if (RTRange.isValid()) 9585 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9586 << FixItHint::CreateReplacement(RTRange, "int"); 9587 } 9588 } else { 9589 // In C and C++, main magically returns 0 if you fall off the end; 9590 // set the flag which tells us that. 9591 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9592 9593 // All the standards say that main() should return 'int'. 9594 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9595 FD->setHasImplicitReturnZero(true); 9596 else { 9597 // Otherwise, this is just a flat-out error. 9598 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9599 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9600 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9601 : FixItHint()); 9602 FD->setInvalidDecl(true); 9603 } 9604 } 9605 9606 // Treat protoless main() as nullary. 9607 if (isa<FunctionNoProtoType>(FT)) return; 9608 9609 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9610 unsigned nparams = FTP->getNumParams(); 9611 assert(FD->getNumParams() == nparams); 9612 9613 bool HasExtraParameters = (nparams > 3); 9614 9615 if (FTP->isVariadic()) { 9616 Diag(FD->getLocation(), diag::ext_variadic_main); 9617 // FIXME: if we had information about the location of the ellipsis, we 9618 // could add a FixIt hint to remove it as a parameter. 9619 } 9620 9621 // Darwin passes an undocumented fourth argument of type char**. If 9622 // other platforms start sprouting these, the logic below will start 9623 // getting shifty. 9624 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9625 HasExtraParameters = false; 9626 9627 if (HasExtraParameters) { 9628 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9629 FD->setInvalidDecl(true); 9630 nparams = 3; 9631 } 9632 9633 // FIXME: a lot of the following diagnostics would be improved 9634 // if we had some location information about types. 9635 9636 QualType CharPP = 9637 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9638 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9639 9640 for (unsigned i = 0; i < nparams; ++i) { 9641 QualType AT = FTP->getParamType(i); 9642 9643 bool mismatch = true; 9644 9645 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9646 mismatch = false; 9647 else if (Expected[i] == CharPP) { 9648 // As an extension, the following forms are okay: 9649 // char const ** 9650 // char const * const * 9651 // char * const * 9652 9653 QualifierCollector qs; 9654 const PointerType* PT; 9655 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9656 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9657 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9658 Context.CharTy)) { 9659 qs.removeConst(); 9660 mismatch = !qs.empty(); 9661 } 9662 } 9663 9664 if (mismatch) { 9665 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9666 // TODO: suggest replacing given type with expected type 9667 FD->setInvalidDecl(true); 9668 } 9669 } 9670 9671 if (nparams == 1 && !FD->isInvalidDecl()) { 9672 Diag(FD->getLocation(), diag::warn_main_one_arg); 9673 } 9674 9675 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9676 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9677 FD->setInvalidDecl(); 9678 } 9679 } 9680 9681 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9682 QualType T = FD->getType(); 9683 assert(T->isFunctionType() && "function decl is not of function type"); 9684 const FunctionType *FT = T->castAs<FunctionType>(); 9685 9686 // Set an implicit return of 'zero' if the function can return some integral, 9687 // enumeration, pointer or nullptr type. 9688 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9689 FT->getReturnType()->isAnyPointerType() || 9690 FT->getReturnType()->isNullPtrType()) 9691 // DllMain is exempt because a return value of zero means it failed. 9692 if (FD->getName() != "DllMain") 9693 FD->setHasImplicitReturnZero(true); 9694 9695 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9696 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9697 FD->setInvalidDecl(); 9698 } 9699 } 9700 9701 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9702 // FIXME: Need strict checking. In C89, we need to check for 9703 // any assignment, increment, decrement, function-calls, or 9704 // commas outside of a sizeof. In C99, it's the same list, 9705 // except that the aforementioned are allowed in unevaluated 9706 // expressions. Everything else falls under the 9707 // "may accept other forms of constant expressions" exception. 9708 // (We never end up here for C++, so the constant expression 9709 // rules there don't matter.) 9710 const Expr *Culprit; 9711 if (Init->isConstantInitializer(Context, false, &Culprit)) 9712 return false; 9713 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9714 << Culprit->getSourceRange(); 9715 return true; 9716 } 9717 9718 namespace { 9719 // Visits an initialization expression to see if OrigDecl is evaluated in 9720 // its own initialization and throws a warning if it does. 9721 class SelfReferenceChecker 9722 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9723 Sema &S; 9724 Decl *OrigDecl; 9725 bool isRecordType; 9726 bool isPODType; 9727 bool isReferenceType; 9728 9729 bool isInitList; 9730 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9731 9732 public: 9733 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9734 9735 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9736 S(S), OrigDecl(OrigDecl) { 9737 isPODType = false; 9738 isRecordType = false; 9739 isReferenceType = false; 9740 isInitList = false; 9741 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9742 isPODType = VD->getType().isPODType(S.Context); 9743 isRecordType = VD->getType()->isRecordType(); 9744 isReferenceType = VD->getType()->isReferenceType(); 9745 } 9746 } 9747 9748 // For most expressions, just call the visitor. For initializer lists, 9749 // track the index of the field being initialized since fields are 9750 // initialized in order allowing use of previously initialized fields. 9751 void CheckExpr(Expr *E) { 9752 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9753 if (!InitList) { 9754 Visit(E); 9755 return; 9756 } 9757 9758 // Track and increment the index here. 9759 isInitList = true; 9760 InitFieldIndex.push_back(0); 9761 for (auto Child : InitList->children()) { 9762 CheckExpr(cast<Expr>(Child)); 9763 ++InitFieldIndex.back(); 9764 } 9765 InitFieldIndex.pop_back(); 9766 } 9767 9768 // Returns true if MemberExpr is checked and no further checking is needed. 9769 // Returns false if additional checking is required. 9770 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9771 llvm::SmallVector<FieldDecl*, 4> Fields; 9772 Expr *Base = E; 9773 bool ReferenceField = false; 9774 9775 // Get the field memebers used. 9776 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9777 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9778 if (!FD) 9779 return false; 9780 Fields.push_back(FD); 9781 if (FD->getType()->isReferenceType()) 9782 ReferenceField = true; 9783 Base = ME->getBase()->IgnoreParenImpCasts(); 9784 } 9785 9786 // Keep checking only if the base Decl is the same. 9787 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9788 if (!DRE || DRE->getDecl() != OrigDecl) 9789 return false; 9790 9791 // A reference field can be bound to an unininitialized field. 9792 if (CheckReference && !ReferenceField) 9793 return true; 9794 9795 // Convert FieldDecls to their index number. 9796 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9797 for (const FieldDecl *I : llvm::reverse(Fields)) 9798 UsedFieldIndex.push_back(I->getFieldIndex()); 9799 9800 // See if a warning is needed by checking the first difference in index 9801 // numbers. If field being used has index less than the field being 9802 // initialized, then the use is safe. 9803 for (auto UsedIter = UsedFieldIndex.begin(), 9804 UsedEnd = UsedFieldIndex.end(), 9805 OrigIter = InitFieldIndex.begin(), 9806 OrigEnd = InitFieldIndex.end(); 9807 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9808 if (*UsedIter < *OrigIter) 9809 return true; 9810 if (*UsedIter > *OrigIter) 9811 break; 9812 } 9813 9814 // TODO: Add a different warning which will print the field names. 9815 HandleDeclRefExpr(DRE); 9816 return true; 9817 } 9818 9819 // For most expressions, the cast is directly above the DeclRefExpr. 9820 // For conditional operators, the cast can be outside the conditional 9821 // operator if both expressions are DeclRefExpr's. 9822 void HandleValue(Expr *E) { 9823 E = E->IgnoreParens(); 9824 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9825 HandleDeclRefExpr(DRE); 9826 return; 9827 } 9828 9829 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9830 Visit(CO->getCond()); 9831 HandleValue(CO->getTrueExpr()); 9832 HandleValue(CO->getFalseExpr()); 9833 return; 9834 } 9835 9836 if (BinaryConditionalOperator *BCO = 9837 dyn_cast<BinaryConditionalOperator>(E)) { 9838 Visit(BCO->getCond()); 9839 HandleValue(BCO->getFalseExpr()); 9840 return; 9841 } 9842 9843 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9844 HandleValue(OVE->getSourceExpr()); 9845 return; 9846 } 9847 9848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9849 if (BO->getOpcode() == BO_Comma) { 9850 Visit(BO->getLHS()); 9851 HandleValue(BO->getRHS()); 9852 return; 9853 } 9854 } 9855 9856 if (isa<MemberExpr>(E)) { 9857 if (isInitList) { 9858 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9859 false /*CheckReference*/)) 9860 return; 9861 } 9862 9863 Expr *Base = E->IgnoreParenImpCasts(); 9864 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9865 // Check for static member variables and don't warn on them. 9866 if (!isa<FieldDecl>(ME->getMemberDecl())) 9867 return; 9868 Base = ME->getBase()->IgnoreParenImpCasts(); 9869 } 9870 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9871 HandleDeclRefExpr(DRE); 9872 return; 9873 } 9874 9875 Visit(E); 9876 } 9877 9878 // Reference types not handled in HandleValue are handled here since all 9879 // uses of references are bad, not just r-value uses. 9880 void VisitDeclRefExpr(DeclRefExpr *E) { 9881 if (isReferenceType) 9882 HandleDeclRefExpr(E); 9883 } 9884 9885 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9886 if (E->getCastKind() == CK_LValueToRValue) { 9887 HandleValue(E->getSubExpr()); 9888 return; 9889 } 9890 9891 Inherited::VisitImplicitCastExpr(E); 9892 } 9893 9894 void VisitMemberExpr(MemberExpr *E) { 9895 if (isInitList) { 9896 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9897 return; 9898 } 9899 9900 // Don't warn on arrays since they can be treated as pointers. 9901 if (E->getType()->canDecayToPointerType()) return; 9902 9903 // Warn when a non-static method call is followed by non-static member 9904 // field accesses, which is followed by a DeclRefExpr. 9905 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9906 bool Warn = (MD && !MD->isStatic()); 9907 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9908 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9909 if (!isa<FieldDecl>(ME->getMemberDecl())) 9910 Warn = false; 9911 Base = ME->getBase()->IgnoreParenImpCasts(); 9912 } 9913 9914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9915 if (Warn) 9916 HandleDeclRefExpr(DRE); 9917 return; 9918 } 9919 9920 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9921 // Visit that expression. 9922 Visit(Base); 9923 } 9924 9925 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9926 Expr *Callee = E->getCallee(); 9927 9928 if (isa<UnresolvedLookupExpr>(Callee)) 9929 return Inherited::VisitCXXOperatorCallExpr(E); 9930 9931 Visit(Callee); 9932 for (auto Arg: E->arguments()) 9933 HandleValue(Arg->IgnoreParenImpCasts()); 9934 } 9935 9936 void VisitUnaryOperator(UnaryOperator *E) { 9937 // For POD record types, addresses of its own members are well-defined. 9938 if (E->getOpcode() == UO_AddrOf && isRecordType && 9939 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9940 if (!isPODType) 9941 HandleValue(E->getSubExpr()); 9942 return; 9943 } 9944 9945 if (E->isIncrementDecrementOp()) { 9946 HandleValue(E->getSubExpr()); 9947 return; 9948 } 9949 9950 Inherited::VisitUnaryOperator(E); 9951 } 9952 9953 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9954 9955 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9956 if (E->getConstructor()->isCopyConstructor()) { 9957 Expr *ArgExpr = E->getArg(0); 9958 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9959 if (ILE->getNumInits() == 1) 9960 ArgExpr = ILE->getInit(0); 9961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9962 if (ICE->getCastKind() == CK_NoOp) 9963 ArgExpr = ICE->getSubExpr(); 9964 HandleValue(ArgExpr); 9965 return; 9966 } 9967 Inherited::VisitCXXConstructExpr(E); 9968 } 9969 9970 void VisitCallExpr(CallExpr *E) { 9971 // Treat std::move as a use. 9972 if (E->getNumArgs() == 1) { 9973 if (FunctionDecl *FD = E->getDirectCallee()) { 9974 if (FD->isInStdNamespace() && FD->getIdentifier() && 9975 FD->getIdentifier()->isStr("move")) { 9976 HandleValue(E->getArg(0)); 9977 return; 9978 } 9979 } 9980 } 9981 9982 Inherited::VisitCallExpr(E); 9983 } 9984 9985 void VisitBinaryOperator(BinaryOperator *E) { 9986 if (E->isCompoundAssignmentOp()) { 9987 HandleValue(E->getLHS()); 9988 Visit(E->getRHS()); 9989 return; 9990 } 9991 9992 Inherited::VisitBinaryOperator(E); 9993 } 9994 9995 // A custom visitor for BinaryConditionalOperator is needed because the 9996 // regular visitor would check the condition and true expression separately 9997 // but both point to the same place giving duplicate diagnostics. 9998 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9999 Visit(E->getCond()); 10000 Visit(E->getFalseExpr()); 10001 } 10002 10003 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10004 Decl* ReferenceDecl = DRE->getDecl(); 10005 if (OrigDecl != ReferenceDecl) return; 10006 unsigned diag; 10007 if (isReferenceType) { 10008 diag = diag::warn_uninit_self_reference_in_reference_init; 10009 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10010 diag = diag::warn_static_self_reference_in_init; 10011 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10012 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10013 DRE->getDecl()->getType()->isRecordType()) { 10014 diag = diag::warn_uninit_self_reference_in_init; 10015 } else { 10016 // Local variables will be handled by the CFG analysis. 10017 return; 10018 } 10019 10020 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10021 S.PDiag(diag) 10022 << DRE->getNameInfo().getName() 10023 << OrigDecl->getLocation() 10024 << DRE->getSourceRange()); 10025 } 10026 }; 10027 10028 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10029 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10030 bool DirectInit) { 10031 // Parameters arguments are occassionially constructed with itself, 10032 // for instance, in recursive functions. Skip them. 10033 if (isa<ParmVarDecl>(OrigDecl)) 10034 return; 10035 10036 E = E->IgnoreParens(); 10037 10038 // Skip checking T a = a where T is not a record or reference type. 10039 // Doing so is a way to silence uninitialized warnings. 10040 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10042 if (ICE->getCastKind() == CK_LValueToRValue) 10043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10044 if (DRE->getDecl() == OrigDecl) 10045 return; 10046 10047 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10048 } 10049 } // end anonymous namespace 10050 10051 namespace { 10052 // Simple wrapper to add the name of a variable or (if no variable is 10053 // available) a DeclarationName into a diagnostic. 10054 struct VarDeclOrName { 10055 VarDecl *VDecl; 10056 DeclarationName Name; 10057 10058 friend const Sema::SemaDiagnosticBuilder & 10059 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10060 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10061 } 10062 }; 10063 } // end anonymous namespace 10064 10065 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10066 DeclarationName Name, QualType Type, 10067 TypeSourceInfo *TSI, 10068 SourceRange Range, bool DirectInit, 10069 Expr *Init) { 10070 bool IsInitCapture = !VDecl; 10071 assert((!VDecl || !VDecl->isInitCapture()) && 10072 "init captures are expected to be deduced prior to initialization"); 10073 10074 VarDeclOrName VN{VDecl, Name}; 10075 10076 DeducedType *Deduced = Type->getContainedDeducedType(); 10077 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10078 10079 // C++11 [dcl.spec.auto]p3 10080 if (!Init) { 10081 assert(VDecl && "no init for init capture deduction?"); 10082 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10083 << VDecl->getDeclName() << Type; 10084 return QualType(); 10085 } 10086 10087 ArrayRef<Expr*> DeduceInits = Init; 10088 if (DirectInit) { 10089 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10090 DeduceInits = PL->exprs(); 10091 } 10092 10093 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10094 assert(VDecl && "non-auto type for init capture deduction?"); 10095 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10096 InitializationKind Kind = InitializationKind::CreateForInit( 10097 VDecl->getLocation(), DirectInit, Init); 10098 // FIXME: Initialization should not be taking a mutable list of inits. 10099 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10100 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10101 InitsCopy); 10102 } 10103 10104 if (DirectInit) { 10105 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10106 DeduceInits = IL->inits(); 10107 } 10108 10109 // Deduction only works if we have exactly one source expression. 10110 if (DeduceInits.empty()) { 10111 // It isn't possible to write this directly, but it is possible to 10112 // end up in this situation with "auto x(some_pack...);" 10113 Diag(Init->getLocStart(), IsInitCapture 10114 ? diag::err_init_capture_no_expression 10115 : diag::err_auto_var_init_no_expression) 10116 << VN << Type << Range; 10117 return QualType(); 10118 } 10119 10120 if (DeduceInits.size() > 1) { 10121 Diag(DeduceInits[1]->getLocStart(), 10122 IsInitCapture ? diag::err_init_capture_multiple_expressions 10123 : diag::err_auto_var_init_multiple_expressions) 10124 << VN << Type << Range; 10125 return QualType(); 10126 } 10127 10128 Expr *DeduceInit = DeduceInits[0]; 10129 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10130 Diag(Init->getLocStart(), IsInitCapture 10131 ? diag::err_init_capture_paren_braces 10132 : diag::err_auto_var_init_paren_braces) 10133 << isa<InitListExpr>(Init) << VN << Type << Range; 10134 return QualType(); 10135 } 10136 10137 // Expressions default to 'id' when we're in a debugger. 10138 bool DefaultedAnyToId = false; 10139 if (getLangOpts().DebuggerCastResultToId && 10140 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10141 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10142 if (Result.isInvalid()) { 10143 return QualType(); 10144 } 10145 Init = Result.get(); 10146 DefaultedAnyToId = true; 10147 } 10148 10149 // C++ [dcl.decomp]p1: 10150 // If the assignment-expression [...] has array type A and no ref-qualifier 10151 // is present, e has type cv A 10152 if (VDecl && isa<DecompositionDecl>(VDecl) && 10153 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10154 DeduceInit->getType()->isConstantArrayType()) 10155 return Context.getQualifiedType(DeduceInit->getType(), 10156 Type.getQualifiers()); 10157 10158 QualType DeducedType; 10159 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10160 if (!IsInitCapture) 10161 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10162 else if (isa<InitListExpr>(Init)) 10163 Diag(Range.getBegin(), 10164 diag::err_init_capture_deduction_failure_from_init_list) 10165 << VN 10166 << (DeduceInit->getType().isNull() ? TSI->getType() 10167 : DeduceInit->getType()) 10168 << DeduceInit->getSourceRange(); 10169 else 10170 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10171 << VN << TSI->getType() 10172 << (DeduceInit->getType().isNull() ? TSI->getType() 10173 : DeduceInit->getType()) 10174 << DeduceInit->getSourceRange(); 10175 } 10176 10177 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10178 // 'id' instead of a specific object type prevents most of our usual 10179 // checks. 10180 // We only want to warn outside of template instantiations, though: 10181 // inside a template, the 'id' could have come from a parameter. 10182 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10183 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10184 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10185 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10186 } 10187 10188 return DeducedType; 10189 } 10190 10191 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10192 Expr *Init) { 10193 QualType DeducedType = deduceVarTypeFromInitializer( 10194 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10195 VDecl->getSourceRange(), DirectInit, Init); 10196 if (DeducedType.isNull()) { 10197 VDecl->setInvalidDecl(); 10198 return true; 10199 } 10200 10201 VDecl->setType(DeducedType); 10202 assert(VDecl->isLinkageValid()); 10203 10204 // In ARC, infer lifetime. 10205 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10206 VDecl->setInvalidDecl(); 10207 10208 // If this is a redeclaration, check that the type we just deduced matches 10209 // the previously declared type. 10210 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10211 // We never need to merge the type, because we cannot form an incomplete 10212 // array of auto, nor deduce such a type. 10213 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10214 } 10215 10216 // Check the deduced type is valid for a variable declaration. 10217 CheckVariableDeclarationType(VDecl); 10218 return VDecl->isInvalidDecl(); 10219 } 10220 10221 /// AddInitializerToDecl - Adds the initializer Init to the 10222 /// declaration dcl. If DirectInit is true, this is C++ direct 10223 /// initialization rather than copy initialization. 10224 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10225 // If there is no declaration, there was an error parsing it. Just ignore 10226 // the initializer. 10227 if (!RealDecl || RealDecl->isInvalidDecl()) { 10228 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10229 return; 10230 } 10231 10232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10233 // Pure-specifiers are handled in ActOnPureSpecifier. 10234 Diag(Method->getLocation(), diag::err_member_function_initialization) 10235 << Method->getDeclName() << Init->getSourceRange(); 10236 Method->setInvalidDecl(); 10237 return; 10238 } 10239 10240 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10241 if (!VDecl) { 10242 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10243 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10244 RealDecl->setInvalidDecl(); 10245 return; 10246 } 10247 10248 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10249 if (VDecl->getType()->isUndeducedType()) { 10250 // Attempt typo correction early so that the type of the init expression can 10251 // be deduced based on the chosen correction if the original init contains a 10252 // TypoExpr. 10253 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10254 if (!Res.isUsable()) { 10255 RealDecl->setInvalidDecl(); 10256 return; 10257 } 10258 Init = Res.get(); 10259 10260 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10261 return; 10262 } 10263 10264 // dllimport cannot be used on variable definitions. 10265 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10266 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10267 VDecl->setInvalidDecl(); 10268 return; 10269 } 10270 10271 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10272 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10273 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10274 VDecl->setInvalidDecl(); 10275 return; 10276 } 10277 10278 if (!VDecl->getType()->isDependentType()) { 10279 // A definition must end up with a complete type, which means it must be 10280 // complete with the restriction that an array type might be completed by 10281 // the initializer; note that later code assumes this restriction. 10282 QualType BaseDeclType = VDecl->getType(); 10283 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10284 BaseDeclType = Array->getElementType(); 10285 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10286 diag::err_typecheck_decl_incomplete_type)) { 10287 RealDecl->setInvalidDecl(); 10288 return; 10289 } 10290 10291 // The variable can not have an abstract class type. 10292 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10293 diag::err_abstract_type_in_decl, 10294 AbstractVariableType)) 10295 VDecl->setInvalidDecl(); 10296 } 10297 10298 // If adding the initializer will turn this declaration into a definition, 10299 // and we already have a definition for this variable, diagnose or otherwise 10300 // handle the situation. 10301 VarDecl *Def; 10302 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10303 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10304 !VDecl->isThisDeclarationADemotedDefinition() && 10305 checkVarDeclRedefinition(Def, VDecl)) 10306 return; 10307 10308 if (getLangOpts().CPlusPlus) { 10309 // C++ [class.static.data]p4 10310 // If a static data member is of const integral or const 10311 // enumeration type, its declaration in the class definition can 10312 // specify a constant-initializer which shall be an integral 10313 // constant expression (5.19). In that case, the member can appear 10314 // in integral constant expressions. The member shall still be 10315 // defined in a namespace scope if it is used in the program and the 10316 // namespace scope definition shall not contain an initializer. 10317 // 10318 // We already performed a redefinition check above, but for static 10319 // data members we also need to check whether there was an in-class 10320 // declaration with an initializer. 10321 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10322 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10323 << VDecl->getDeclName(); 10324 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10325 diag::note_previous_initializer) 10326 << 0; 10327 return; 10328 } 10329 10330 if (VDecl->hasLocalStorage()) 10331 getCurFunction()->setHasBranchProtectedScope(); 10332 10333 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10334 VDecl->setInvalidDecl(); 10335 return; 10336 } 10337 } 10338 10339 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10340 // a kernel function cannot be initialized." 10341 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10342 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10343 VDecl->setInvalidDecl(); 10344 return; 10345 } 10346 10347 // Get the decls type and save a reference for later, since 10348 // CheckInitializerTypes may change it. 10349 QualType DclT = VDecl->getType(), SavT = DclT; 10350 10351 // Expressions default to 'id' when we're in a debugger 10352 // and we are assigning it to a variable of Objective-C pointer type. 10353 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10354 Init->getType() == Context.UnknownAnyTy) { 10355 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10356 if (Result.isInvalid()) { 10357 VDecl->setInvalidDecl(); 10358 return; 10359 } 10360 Init = Result.get(); 10361 } 10362 10363 // Perform the initialization. 10364 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10365 if (!VDecl->isInvalidDecl()) { 10366 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10367 InitializationKind Kind = InitializationKind::CreateForInit( 10368 VDecl->getLocation(), DirectInit, Init); 10369 10370 MultiExprArg Args = Init; 10371 if (CXXDirectInit) 10372 Args = MultiExprArg(CXXDirectInit->getExprs(), 10373 CXXDirectInit->getNumExprs()); 10374 10375 // Try to correct any TypoExprs in the initialization arguments. 10376 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10377 ExprResult Res = CorrectDelayedTyposInExpr( 10378 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10379 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10380 return Init.Failed() ? ExprError() : E; 10381 }); 10382 if (Res.isInvalid()) { 10383 VDecl->setInvalidDecl(); 10384 } else if (Res.get() != Args[Idx]) { 10385 Args[Idx] = Res.get(); 10386 } 10387 } 10388 if (VDecl->isInvalidDecl()) 10389 return; 10390 10391 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10392 /*TopLevelOfInitList=*/false, 10393 /*TreatUnavailableAsInvalid=*/false); 10394 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10395 if (Result.isInvalid()) { 10396 VDecl->setInvalidDecl(); 10397 return; 10398 } 10399 10400 Init = Result.getAs<Expr>(); 10401 } 10402 10403 // Check for self-references within variable initializers. 10404 // Variables declared within a function/method body (except for references) 10405 // are handled by a dataflow analysis. 10406 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10407 VDecl->getType()->isReferenceType()) { 10408 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10409 } 10410 10411 // If the type changed, it means we had an incomplete type that was 10412 // completed by the initializer. For example: 10413 // int ary[] = { 1, 3, 5 }; 10414 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10415 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10416 VDecl->setType(DclT); 10417 10418 if (!VDecl->isInvalidDecl()) { 10419 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10420 10421 if (VDecl->hasAttr<BlocksAttr>()) 10422 checkRetainCycles(VDecl, Init); 10423 10424 // It is safe to assign a weak reference into a strong variable. 10425 // Although this code can still have problems: 10426 // id x = self.weakProp; 10427 // id y = self.weakProp; 10428 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10429 // paths through the function. This should be revisited if 10430 // -Wrepeated-use-of-weak is made flow-sensitive. 10431 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10432 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10433 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10434 Init->getLocStart())) 10435 getCurFunction()->markSafeWeakUse(Init); 10436 } 10437 10438 // The initialization is usually a full-expression. 10439 // 10440 // FIXME: If this is a braced initialization of an aggregate, it is not 10441 // an expression, and each individual field initializer is a separate 10442 // full-expression. For instance, in: 10443 // 10444 // struct Temp { ~Temp(); }; 10445 // struct S { S(Temp); }; 10446 // struct T { S a, b; } t = { Temp(), Temp() } 10447 // 10448 // we should destroy the first Temp before constructing the second. 10449 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10450 false, 10451 VDecl->isConstexpr()); 10452 if (Result.isInvalid()) { 10453 VDecl->setInvalidDecl(); 10454 return; 10455 } 10456 Init = Result.get(); 10457 10458 // Attach the initializer to the decl. 10459 VDecl->setInit(Init); 10460 10461 if (VDecl->isLocalVarDecl()) { 10462 // Don't check the initializer if the declaration is malformed. 10463 if (VDecl->isInvalidDecl()) { 10464 // do nothing 10465 10466 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10467 // This is true even in OpenCL C++. 10468 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10469 CheckForConstantInitializer(Init, DclT); 10470 10471 // Otherwise, C++ does not restrict the initializer. 10472 } else if (getLangOpts().CPlusPlus) { 10473 // do nothing 10474 10475 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10476 // static storage duration shall be constant expressions or string literals. 10477 } else if (VDecl->getStorageClass() == SC_Static) { 10478 CheckForConstantInitializer(Init, DclT); 10479 10480 // C89 is stricter than C99 for aggregate initializers. 10481 // C89 6.5.7p3: All the expressions [...] in an initializer list 10482 // for an object that has aggregate or union type shall be 10483 // constant expressions. 10484 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10485 isa<InitListExpr>(Init)) { 10486 const Expr *Culprit; 10487 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10488 Diag(Culprit->getExprLoc(), 10489 diag::ext_aggregate_init_not_constant) 10490 << Culprit->getSourceRange(); 10491 } 10492 } 10493 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10494 VDecl->getLexicalDeclContext()->isRecord()) { 10495 // This is an in-class initialization for a static data member, e.g., 10496 // 10497 // struct S { 10498 // static const int value = 17; 10499 // }; 10500 10501 // C++ [class.mem]p4: 10502 // A member-declarator can contain a constant-initializer only 10503 // if it declares a static member (9.4) of const integral or 10504 // const enumeration type, see 9.4.2. 10505 // 10506 // C++11 [class.static.data]p3: 10507 // If a non-volatile non-inline const static data member is of integral 10508 // or enumeration type, its declaration in the class definition can 10509 // specify a brace-or-equal-initializer in which every initializer-clause 10510 // that is an assignment-expression is a constant expression. A static 10511 // data member of literal type can be declared in the class definition 10512 // with the constexpr specifier; if so, its declaration shall specify a 10513 // brace-or-equal-initializer in which every initializer-clause that is 10514 // an assignment-expression is a constant expression. 10515 10516 // Do nothing on dependent types. 10517 if (DclT->isDependentType()) { 10518 10519 // Allow any 'static constexpr' members, whether or not they are of literal 10520 // type. We separately check that every constexpr variable is of literal 10521 // type. 10522 } else if (VDecl->isConstexpr()) { 10523 10524 // Require constness. 10525 } else if (!DclT.isConstQualified()) { 10526 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10527 << Init->getSourceRange(); 10528 VDecl->setInvalidDecl(); 10529 10530 // We allow integer constant expressions in all cases. 10531 } else if (DclT->isIntegralOrEnumerationType()) { 10532 // Check whether the expression is a constant expression. 10533 SourceLocation Loc; 10534 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10535 // In C++11, a non-constexpr const static data member with an 10536 // in-class initializer cannot be volatile. 10537 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10538 else if (Init->isValueDependent()) 10539 ; // Nothing to check. 10540 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10541 ; // Ok, it's an ICE! 10542 else if (Init->isEvaluatable(Context)) { 10543 // If we can constant fold the initializer through heroics, accept it, 10544 // but report this as a use of an extension for -pedantic. 10545 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10546 << Init->getSourceRange(); 10547 } else { 10548 // Otherwise, this is some crazy unknown case. Report the issue at the 10549 // location provided by the isIntegerConstantExpr failed check. 10550 Diag(Loc, diag::err_in_class_initializer_non_constant) 10551 << Init->getSourceRange(); 10552 VDecl->setInvalidDecl(); 10553 } 10554 10555 // We allow foldable floating-point constants as an extension. 10556 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10557 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10558 // it anyway and provide a fixit to add the 'constexpr'. 10559 if (getLangOpts().CPlusPlus11) { 10560 Diag(VDecl->getLocation(), 10561 diag::ext_in_class_initializer_float_type_cxx11) 10562 << DclT << Init->getSourceRange(); 10563 Diag(VDecl->getLocStart(), 10564 diag::note_in_class_initializer_float_type_cxx11) 10565 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10566 } else { 10567 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10568 << DclT << Init->getSourceRange(); 10569 10570 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10571 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10572 << Init->getSourceRange(); 10573 VDecl->setInvalidDecl(); 10574 } 10575 } 10576 10577 // Suggest adding 'constexpr' in C++11 for literal types. 10578 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10579 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10580 << DclT << Init->getSourceRange() 10581 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10582 VDecl->setConstexpr(true); 10583 10584 } else { 10585 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10586 << DclT << Init->getSourceRange(); 10587 VDecl->setInvalidDecl(); 10588 } 10589 } else if (VDecl->isFileVarDecl()) { 10590 // In C, extern is typically used to avoid tentative definitions when 10591 // declaring variables in headers, but adding an intializer makes it a 10592 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10593 // In C++, extern is often used to give implictly static const variables 10594 // external linkage, so don't warn in that case. If selectany is present, 10595 // this might be header code intended for C and C++ inclusion, so apply the 10596 // C++ rules. 10597 if (VDecl->getStorageClass() == SC_Extern && 10598 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10599 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10600 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10601 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10602 Diag(VDecl->getLocation(), diag::warn_extern_init); 10603 10604 // C99 6.7.8p4. All file scoped initializers need to be constant. 10605 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10606 CheckForConstantInitializer(Init, DclT); 10607 } 10608 10609 // We will represent direct-initialization similarly to copy-initialization: 10610 // int x(1); -as-> int x = 1; 10611 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10612 // 10613 // Clients that want to distinguish between the two forms, can check for 10614 // direct initializer using VarDecl::getInitStyle(). 10615 // A major benefit is that clients that don't particularly care about which 10616 // exactly form was it (like the CodeGen) can handle both cases without 10617 // special case code. 10618 10619 // C++ 8.5p11: 10620 // The form of initialization (using parentheses or '=') is generally 10621 // insignificant, but does matter when the entity being initialized has a 10622 // class type. 10623 if (CXXDirectInit) { 10624 assert(DirectInit && "Call-style initializer must be direct init."); 10625 VDecl->setInitStyle(VarDecl::CallInit); 10626 } else if (DirectInit) { 10627 // This must be list-initialization. No other way is direct-initialization. 10628 VDecl->setInitStyle(VarDecl::ListInit); 10629 } 10630 10631 CheckCompleteVariableDeclaration(VDecl); 10632 } 10633 10634 /// ActOnInitializerError - Given that there was an error parsing an 10635 /// initializer for the given declaration, try to return to some form 10636 /// of sanity. 10637 void Sema::ActOnInitializerError(Decl *D) { 10638 // Our main concern here is re-establishing invariants like "a 10639 // variable's type is either dependent or complete". 10640 if (!D || D->isInvalidDecl()) return; 10641 10642 VarDecl *VD = dyn_cast<VarDecl>(D); 10643 if (!VD) return; 10644 10645 // Bindings are not usable if we can't make sense of the initializer. 10646 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10647 for (auto *BD : DD->bindings()) 10648 BD->setInvalidDecl(); 10649 10650 // Auto types are meaningless if we can't make sense of the initializer. 10651 if (ParsingInitForAutoVars.count(D)) { 10652 D->setInvalidDecl(); 10653 return; 10654 } 10655 10656 QualType Ty = VD->getType(); 10657 if (Ty->isDependentType()) return; 10658 10659 // Require a complete type. 10660 if (RequireCompleteType(VD->getLocation(), 10661 Context.getBaseElementType(Ty), 10662 diag::err_typecheck_decl_incomplete_type)) { 10663 VD->setInvalidDecl(); 10664 return; 10665 } 10666 10667 // Require a non-abstract type. 10668 if (RequireNonAbstractType(VD->getLocation(), Ty, 10669 diag::err_abstract_type_in_decl, 10670 AbstractVariableType)) { 10671 VD->setInvalidDecl(); 10672 return; 10673 } 10674 10675 // Don't bother complaining about constructors or destructors, 10676 // though. 10677 } 10678 10679 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10680 // If there is no declaration, there was an error parsing it. Just ignore it. 10681 if (!RealDecl) 10682 return; 10683 10684 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10685 QualType Type = Var->getType(); 10686 10687 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10688 if (isa<DecompositionDecl>(RealDecl)) { 10689 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10690 Var->setInvalidDecl(); 10691 return; 10692 } 10693 10694 if (Type->isUndeducedType() && 10695 DeduceVariableDeclarationType(Var, false, nullptr)) 10696 return; 10697 10698 // C++11 [class.static.data]p3: A static data member can be declared with 10699 // the constexpr specifier; if so, its declaration shall specify 10700 // a brace-or-equal-initializer. 10701 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10702 // the definition of a variable [...] or the declaration of a static data 10703 // member. 10704 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10705 !Var->isThisDeclarationADemotedDefinition()) { 10706 if (Var->isStaticDataMember()) { 10707 // C++1z removes the relevant rule; the in-class declaration is always 10708 // a definition there. 10709 if (!getLangOpts().CPlusPlus1z) { 10710 Diag(Var->getLocation(), 10711 diag::err_constexpr_static_mem_var_requires_init) 10712 << Var->getDeclName(); 10713 Var->setInvalidDecl(); 10714 return; 10715 } 10716 } else { 10717 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10718 Var->setInvalidDecl(); 10719 return; 10720 } 10721 } 10722 10723 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10724 // definition having the concept specifier is called a variable concept. A 10725 // concept definition refers to [...] a variable concept and its initializer. 10726 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10727 if (VTD->isConcept()) { 10728 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10729 Var->setInvalidDecl(); 10730 return; 10731 } 10732 } 10733 10734 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10735 // be initialized. 10736 if (!Var->isInvalidDecl() && 10737 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10738 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10739 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10740 Var->setInvalidDecl(); 10741 return; 10742 } 10743 10744 switch (Var->isThisDeclarationADefinition()) { 10745 case VarDecl::Definition: 10746 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10747 break; 10748 10749 // We have an out-of-line definition of a static data member 10750 // that has an in-class initializer, so we type-check this like 10751 // a declaration. 10752 // 10753 // Fall through 10754 10755 case VarDecl::DeclarationOnly: 10756 // It's only a declaration. 10757 10758 // Block scope. C99 6.7p7: If an identifier for an object is 10759 // declared with no linkage (C99 6.2.2p6), the type for the 10760 // object shall be complete. 10761 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10762 !Var->hasLinkage() && !Var->isInvalidDecl() && 10763 RequireCompleteType(Var->getLocation(), Type, 10764 diag::err_typecheck_decl_incomplete_type)) 10765 Var->setInvalidDecl(); 10766 10767 // Make sure that the type is not abstract. 10768 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10769 RequireNonAbstractType(Var->getLocation(), Type, 10770 diag::err_abstract_type_in_decl, 10771 AbstractVariableType)) 10772 Var->setInvalidDecl(); 10773 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10774 Var->getStorageClass() == SC_PrivateExtern) { 10775 Diag(Var->getLocation(), diag::warn_private_extern); 10776 Diag(Var->getLocation(), diag::note_private_extern); 10777 } 10778 10779 return; 10780 10781 case VarDecl::TentativeDefinition: 10782 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10783 // object that has file scope without an initializer, and without a 10784 // storage-class specifier or with the storage-class specifier "static", 10785 // constitutes a tentative definition. Note: A tentative definition with 10786 // external linkage is valid (C99 6.2.2p5). 10787 if (!Var->isInvalidDecl()) { 10788 if (const IncompleteArrayType *ArrayT 10789 = Context.getAsIncompleteArrayType(Type)) { 10790 if (RequireCompleteType(Var->getLocation(), 10791 ArrayT->getElementType(), 10792 diag::err_illegal_decl_array_incomplete_type)) 10793 Var->setInvalidDecl(); 10794 } else if (Var->getStorageClass() == SC_Static) { 10795 // C99 6.9.2p3: If the declaration of an identifier for an object is 10796 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10797 // declared type shall not be an incomplete type. 10798 // NOTE: code such as the following 10799 // static struct s; 10800 // struct s { int a; }; 10801 // is accepted by gcc. Hence here we issue a warning instead of 10802 // an error and we do not invalidate the static declaration. 10803 // NOTE: to avoid multiple warnings, only check the first declaration. 10804 if (Var->isFirstDecl()) 10805 RequireCompleteType(Var->getLocation(), Type, 10806 diag::ext_typecheck_decl_incomplete_type); 10807 } 10808 } 10809 10810 // Record the tentative definition; we're done. 10811 if (!Var->isInvalidDecl()) 10812 TentativeDefinitions.push_back(Var); 10813 return; 10814 } 10815 10816 // Provide a specific diagnostic for uninitialized variable 10817 // definitions with incomplete array type. 10818 if (Type->isIncompleteArrayType()) { 10819 Diag(Var->getLocation(), 10820 diag::err_typecheck_incomplete_array_needs_initializer); 10821 Var->setInvalidDecl(); 10822 return; 10823 } 10824 10825 // Provide a specific diagnostic for uninitialized variable 10826 // definitions with reference type. 10827 if (Type->isReferenceType()) { 10828 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10829 << Var->getDeclName() 10830 << SourceRange(Var->getLocation(), Var->getLocation()); 10831 Var->setInvalidDecl(); 10832 return; 10833 } 10834 10835 // Do not attempt to type-check the default initializer for a 10836 // variable with dependent type. 10837 if (Type->isDependentType()) 10838 return; 10839 10840 if (Var->isInvalidDecl()) 10841 return; 10842 10843 if (!Var->hasAttr<AliasAttr>()) { 10844 if (RequireCompleteType(Var->getLocation(), 10845 Context.getBaseElementType(Type), 10846 diag::err_typecheck_decl_incomplete_type)) { 10847 Var->setInvalidDecl(); 10848 return; 10849 } 10850 } else { 10851 return; 10852 } 10853 10854 // The variable can not have an abstract class type. 10855 if (RequireNonAbstractType(Var->getLocation(), Type, 10856 diag::err_abstract_type_in_decl, 10857 AbstractVariableType)) { 10858 Var->setInvalidDecl(); 10859 return; 10860 } 10861 10862 // Check for jumps past the implicit initializer. C++0x 10863 // clarifies that this applies to a "variable with automatic 10864 // storage duration", not a "local variable". 10865 // C++11 [stmt.dcl]p3 10866 // A program that jumps from a point where a variable with automatic 10867 // storage duration is not in scope to a point where it is in scope is 10868 // ill-formed unless the variable has scalar type, class type with a 10869 // trivial default constructor and a trivial destructor, a cv-qualified 10870 // version of one of these types, or an array of one of the preceding 10871 // types and is declared without an initializer. 10872 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10873 if (const RecordType *Record 10874 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10875 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10876 // Mark the function for further checking even if the looser rules of 10877 // C++11 do not require such checks, so that we can diagnose 10878 // incompatibilities with C++98. 10879 if (!CXXRecord->isPOD()) 10880 getCurFunction()->setHasBranchProtectedScope(); 10881 } 10882 } 10883 10884 // C++03 [dcl.init]p9: 10885 // If no initializer is specified for an object, and the 10886 // object is of (possibly cv-qualified) non-POD class type (or 10887 // array thereof), the object shall be default-initialized; if 10888 // the object is of const-qualified type, the underlying class 10889 // type shall have a user-declared default 10890 // constructor. Otherwise, if no initializer is specified for 10891 // a non- static object, the object and its subobjects, if 10892 // any, have an indeterminate initial value); if the object 10893 // or any of its subobjects are of const-qualified type, the 10894 // program is ill-formed. 10895 // C++0x [dcl.init]p11: 10896 // If no initializer is specified for an object, the object is 10897 // default-initialized; [...]. 10898 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10899 InitializationKind Kind 10900 = InitializationKind::CreateDefault(Var->getLocation()); 10901 10902 InitializationSequence InitSeq(*this, Entity, Kind, None); 10903 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10904 if (Init.isInvalid()) 10905 Var->setInvalidDecl(); 10906 else if (Init.get()) { 10907 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10908 // This is important for template substitution. 10909 Var->setInitStyle(VarDecl::CallInit); 10910 } 10911 10912 CheckCompleteVariableDeclaration(Var); 10913 } 10914 } 10915 10916 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10917 // If there is no declaration, there was an error parsing it. Ignore it. 10918 if (!D) 10919 return; 10920 10921 VarDecl *VD = dyn_cast<VarDecl>(D); 10922 if (!VD) { 10923 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10924 D->setInvalidDecl(); 10925 return; 10926 } 10927 10928 VD->setCXXForRangeDecl(true); 10929 10930 // for-range-declaration cannot be given a storage class specifier. 10931 int Error = -1; 10932 switch (VD->getStorageClass()) { 10933 case SC_None: 10934 break; 10935 case SC_Extern: 10936 Error = 0; 10937 break; 10938 case SC_Static: 10939 Error = 1; 10940 break; 10941 case SC_PrivateExtern: 10942 Error = 2; 10943 break; 10944 case SC_Auto: 10945 Error = 3; 10946 break; 10947 case SC_Register: 10948 Error = 4; 10949 break; 10950 } 10951 if (Error != -1) { 10952 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10953 << VD->getDeclName() << Error; 10954 D->setInvalidDecl(); 10955 } 10956 } 10957 10958 StmtResult 10959 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10960 IdentifierInfo *Ident, 10961 ParsedAttributes &Attrs, 10962 SourceLocation AttrEnd) { 10963 // C++1y [stmt.iter]p1: 10964 // A range-based for statement of the form 10965 // for ( for-range-identifier : for-range-initializer ) statement 10966 // is equivalent to 10967 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10968 DeclSpec DS(Attrs.getPool().getFactory()); 10969 10970 const char *PrevSpec; 10971 unsigned DiagID; 10972 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10973 getPrintingPolicy()); 10974 10975 Declarator D(DS, Declarator::ForContext); 10976 D.SetIdentifier(Ident, IdentLoc); 10977 D.takeAttributes(Attrs, AttrEnd); 10978 10979 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10980 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10981 EmptyAttrs, IdentLoc); 10982 Decl *Var = ActOnDeclarator(S, D); 10983 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10984 FinalizeDeclaration(Var); 10985 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10986 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10987 } 10988 10989 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10990 if (var->isInvalidDecl()) return; 10991 10992 if (getLangOpts().OpenCL) { 10993 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10994 // initialiser 10995 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10996 !var->hasInit()) { 10997 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10998 << 1 /*Init*/; 10999 var->setInvalidDecl(); 11000 return; 11001 } 11002 } 11003 11004 // In Objective-C, don't allow jumps past the implicit initialization of a 11005 // local retaining variable. 11006 if (getLangOpts().ObjC1 && 11007 var->hasLocalStorage()) { 11008 switch (var->getType().getObjCLifetime()) { 11009 case Qualifiers::OCL_None: 11010 case Qualifiers::OCL_ExplicitNone: 11011 case Qualifiers::OCL_Autoreleasing: 11012 break; 11013 11014 case Qualifiers::OCL_Weak: 11015 case Qualifiers::OCL_Strong: 11016 getCurFunction()->setHasBranchProtectedScope(); 11017 break; 11018 } 11019 } 11020 11021 // Warn about externally-visible variables being defined without a 11022 // prior declaration. We only want to do this for global 11023 // declarations, but we also specifically need to avoid doing it for 11024 // class members because the linkage of an anonymous class can 11025 // change if it's later given a typedef name. 11026 if (var->isThisDeclarationADefinition() && 11027 var->getDeclContext()->getRedeclContext()->isFileContext() && 11028 var->isExternallyVisible() && var->hasLinkage() && 11029 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11030 var->getLocation())) { 11031 // Find a previous declaration that's not a definition. 11032 VarDecl *prev = var->getPreviousDecl(); 11033 while (prev && prev->isThisDeclarationADefinition()) 11034 prev = prev->getPreviousDecl(); 11035 11036 if (!prev) 11037 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11038 } 11039 11040 // Cache the result of checking for constant initialization. 11041 Optional<bool> CacheHasConstInit; 11042 const Expr *CacheCulprit; 11043 auto checkConstInit = [&]() mutable { 11044 if (!CacheHasConstInit) 11045 CacheHasConstInit = var->getInit()->isConstantInitializer( 11046 Context, var->getType()->isReferenceType(), &CacheCulprit); 11047 return *CacheHasConstInit; 11048 }; 11049 11050 if (var->getTLSKind() == VarDecl::TLS_Static) { 11051 if (var->getType().isDestructedType()) { 11052 // GNU C++98 edits for __thread, [basic.start.term]p3: 11053 // The type of an object with thread storage duration shall not 11054 // have a non-trivial destructor. 11055 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11056 if (getLangOpts().CPlusPlus11) 11057 Diag(var->getLocation(), diag::note_use_thread_local); 11058 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11059 if (!checkConstInit()) { 11060 // GNU C++98 edits for __thread, [basic.start.init]p4: 11061 // An object of thread storage duration shall not require dynamic 11062 // initialization. 11063 // FIXME: Need strict checking here. 11064 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11065 << CacheCulprit->getSourceRange(); 11066 if (getLangOpts().CPlusPlus11) 11067 Diag(var->getLocation(), diag::note_use_thread_local); 11068 } 11069 } 11070 } 11071 11072 // Apply section attributes and pragmas to global variables. 11073 bool GlobalStorage = var->hasGlobalStorage(); 11074 if (GlobalStorage && var->isThisDeclarationADefinition() && 11075 !inTemplateInstantiation()) { 11076 PragmaStack<StringLiteral *> *Stack = nullptr; 11077 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11078 if (var->getType().isConstQualified()) 11079 Stack = &ConstSegStack; 11080 else if (!var->getInit()) { 11081 Stack = &BSSSegStack; 11082 SectionFlags |= ASTContext::PSF_Write; 11083 } else { 11084 Stack = &DataSegStack; 11085 SectionFlags |= ASTContext::PSF_Write; 11086 } 11087 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11088 var->addAttr(SectionAttr::CreateImplicit( 11089 Context, SectionAttr::Declspec_allocate, 11090 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11091 } 11092 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11093 if (UnifySection(SA->getName(), SectionFlags, var)) 11094 var->dropAttr<SectionAttr>(); 11095 11096 // Apply the init_seg attribute if this has an initializer. If the 11097 // initializer turns out to not be dynamic, we'll end up ignoring this 11098 // attribute. 11099 if (CurInitSeg && var->getInit()) 11100 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11101 CurInitSegLoc)); 11102 } 11103 11104 // All the following checks are C++ only. 11105 if (!getLangOpts().CPlusPlus) { 11106 // If this variable must be emitted, add it as an initializer for the 11107 // current module. 11108 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11109 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11110 return; 11111 } 11112 11113 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11114 CheckCompleteDecompositionDeclaration(DD); 11115 11116 QualType type = var->getType(); 11117 if (type->isDependentType()) return; 11118 11119 // __block variables might require us to capture a copy-initializer. 11120 if (var->hasAttr<BlocksAttr>()) { 11121 // It's currently invalid to ever have a __block variable with an 11122 // array type; should we diagnose that here? 11123 11124 // Regardless, we don't want to ignore array nesting when 11125 // constructing this copy. 11126 if (type->isStructureOrClassType()) { 11127 EnterExpressionEvaluationContext scope( 11128 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11129 SourceLocation poi = var->getLocation(); 11130 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11131 ExprResult result 11132 = PerformMoveOrCopyInitialization( 11133 InitializedEntity::InitializeBlock(poi, type, false), 11134 var, var->getType(), varRef, /*AllowNRVO=*/true); 11135 if (!result.isInvalid()) { 11136 result = MaybeCreateExprWithCleanups(result); 11137 Expr *init = result.getAs<Expr>(); 11138 Context.setBlockVarCopyInits(var, init); 11139 } 11140 } 11141 } 11142 11143 Expr *Init = var->getInit(); 11144 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11145 QualType baseType = Context.getBaseElementType(type); 11146 11147 if (Init && !Init->isValueDependent()) { 11148 if (var->isConstexpr()) { 11149 SmallVector<PartialDiagnosticAt, 8> Notes; 11150 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11151 SourceLocation DiagLoc = var->getLocation(); 11152 // If the note doesn't add any useful information other than a source 11153 // location, fold it into the primary diagnostic. 11154 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11155 diag::note_invalid_subexpr_in_const_expr) { 11156 DiagLoc = Notes[0].first; 11157 Notes.clear(); 11158 } 11159 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11160 << var << Init->getSourceRange(); 11161 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11162 Diag(Notes[I].first, Notes[I].second); 11163 } 11164 } else if (var->isUsableInConstantExpressions(Context)) { 11165 // Check whether the initializer of a const variable of integral or 11166 // enumeration type is an ICE now, since we can't tell whether it was 11167 // initialized by a constant expression if we check later. 11168 var->checkInitIsICE(); 11169 } 11170 11171 // Don't emit further diagnostics about constexpr globals since they 11172 // were just diagnosed. 11173 if (!var->isConstexpr() && GlobalStorage && 11174 var->hasAttr<RequireConstantInitAttr>()) { 11175 // FIXME: Need strict checking in C++03 here. 11176 bool DiagErr = getLangOpts().CPlusPlus11 11177 ? !var->checkInitIsICE() : !checkConstInit(); 11178 if (DiagErr) { 11179 auto attr = var->getAttr<RequireConstantInitAttr>(); 11180 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11181 << Init->getSourceRange(); 11182 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11183 << attr->getRange(); 11184 if (getLangOpts().CPlusPlus11) { 11185 APValue Value; 11186 SmallVector<PartialDiagnosticAt, 8> Notes; 11187 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11188 for (auto &it : Notes) 11189 Diag(it.first, it.second); 11190 } else { 11191 Diag(CacheCulprit->getExprLoc(), 11192 diag::note_invalid_subexpr_in_const_expr) 11193 << CacheCulprit->getSourceRange(); 11194 } 11195 } 11196 } 11197 else if (!var->isConstexpr() && IsGlobal && 11198 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11199 var->getLocation())) { 11200 // Warn about globals which don't have a constant initializer. Don't 11201 // warn about globals with a non-trivial destructor because we already 11202 // warned about them. 11203 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11204 if (!(RD && !RD->hasTrivialDestructor())) { 11205 if (!checkConstInit()) 11206 Diag(var->getLocation(), diag::warn_global_constructor) 11207 << Init->getSourceRange(); 11208 } 11209 } 11210 } 11211 11212 // Require the destructor. 11213 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11214 FinalizeVarWithDestructor(var, recordType); 11215 11216 // If this variable must be emitted, add it as an initializer for the current 11217 // module. 11218 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11219 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11220 } 11221 11222 /// \brief Determines if a variable's alignment is dependent. 11223 static bool hasDependentAlignment(VarDecl *VD) { 11224 if (VD->getType()->isDependentType()) 11225 return true; 11226 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11227 if (I->isAlignmentDependent()) 11228 return true; 11229 return false; 11230 } 11231 11232 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11233 /// any semantic actions necessary after any initializer has been attached. 11234 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11235 // Note that we are no longer parsing the initializer for this declaration. 11236 ParsingInitForAutoVars.erase(ThisDecl); 11237 11238 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11239 if (!VD) 11240 return; 11241 11242 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11243 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11244 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11245 if (PragmaClangBSSSection.Valid) 11246 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11247 PragmaClangBSSSection.SectionName, 11248 PragmaClangBSSSection.PragmaLocation)); 11249 if (PragmaClangDataSection.Valid) 11250 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11251 PragmaClangDataSection.SectionName, 11252 PragmaClangDataSection.PragmaLocation)); 11253 if (PragmaClangRodataSection.Valid) 11254 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11255 PragmaClangRodataSection.SectionName, 11256 PragmaClangRodataSection.PragmaLocation)); 11257 } 11258 11259 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11260 for (auto *BD : DD->bindings()) { 11261 FinalizeDeclaration(BD); 11262 } 11263 } 11264 11265 checkAttributesAfterMerging(*this, *VD); 11266 11267 // Perform TLS alignment check here after attributes attached to the variable 11268 // which may affect the alignment have been processed. Only perform the check 11269 // if the target has a maximum TLS alignment (zero means no constraints). 11270 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11271 // Protect the check so that it's not performed on dependent types and 11272 // dependent alignments (we can't determine the alignment in that case). 11273 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11274 !VD->isInvalidDecl()) { 11275 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11276 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11277 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11278 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11279 << (unsigned)MaxAlignChars.getQuantity(); 11280 } 11281 } 11282 } 11283 11284 if (VD->isStaticLocal()) { 11285 if (FunctionDecl *FD = 11286 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11287 // Static locals inherit dll attributes from their function. 11288 if (Attr *A = getDLLAttr(FD)) { 11289 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11290 NewAttr->setInherited(true); 11291 VD->addAttr(NewAttr); 11292 } 11293 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11294 // function, only __shared__ variables may be declared with 11295 // static storage class. 11296 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11297 CUDADiagIfDeviceCode(VD->getLocation(), 11298 diag::err_device_static_local_var) 11299 << CurrentCUDATarget()) 11300 VD->setInvalidDecl(); 11301 } 11302 } 11303 11304 // Perform check for initializers of device-side global variables. 11305 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11306 // 7.5). We must also apply the same checks to all __shared__ 11307 // variables whether they are local or not. CUDA also allows 11308 // constant initializers for __constant__ and __device__ variables. 11309 if (getLangOpts().CUDA) { 11310 const Expr *Init = VD->getInit(); 11311 if (Init && VD->hasGlobalStorage()) { 11312 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11313 VD->hasAttr<CUDASharedAttr>()) { 11314 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11315 bool AllowedInit = false; 11316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11317 AllowedInit = 11318 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11319 // We'll allow constant initializers even if it's a non-empty 11320 // constructor according to CUDA rules. This deviates from NVCC, 11321 // but allows us to handle things like constexpr constructors. 11322 if (!AllowedInit && 11323 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11324 AllowedInit = VD->getInit()->isConstantInitializer( 11325 Context, VD->getType()->isReferenceType()); 11326 11327 // Also make sure that destructor, if there is one, is empty. 11328 if (AllowedInit) 11329 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11330 AllowedInit = 11331 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11332 11333 if (!AllowedInit) { 11334 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11335 ? diag::err_shared_var_init 11336 : diag::err_dynamic_var_init) 11337 << Init->getSourceRange(); 11338 VD->setInvalidDecl(); 11339 } 11340 } else { 11341 // This is a host-side global variable. Check that the initializer is 11342 // callable from the host side. 11343 const FunctionDecl *InitFn = nullptr; 11344 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11345 InitFn = CE->getConstructor(); 11346 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11347 InitFn = CE->getDirectCallee(); 11348 } 11349 if (InitFn) { 11350 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11351 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11352 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11353 << InitFnTarget << InitFn; 11354 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11355 VD->setInvalidDecl(); 11356 } 11357 } 11358 } 11359 } 11360 } 11361 11362 // Grab the dllimport or dllexport attribute off of the VarDecl. 11363 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11364 11365 // Imported static data members cannot be defined out-of-line. 11366 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11367 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11368 VD->isThisDeclarationADefinition()) { 11369 // We allow definitions of dllimport class template static data members 11370 // with a warning. 11371 CXXRecordDecl *Context = 11372 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11373 bool IsClassTemplateMember = 11374 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11375 Context->getDescribedClassTemplate(); 11376 11377 Diag(VD->getLocation(), 11378 IsClassTemplateMember 11379 ? diag::warn_attribute_dllimport_static_field_definition 11380 : diag::err_attribute_dllimport_static_field_definition); 11381 Diag(IA->getLocation(), diag::note_attribute); 11382 if (!IsClassTemplateMember) 11383 VD->setInvalidDecl(); 11384 } 11385 } 11386 11387 // dllimport/dllexport variables cannot be thread local, their TLS index 11388 // isn't exported with the variable. 11389 if (DLLAttr && VD->getTLSKind()) { 11390 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11391 if (F && getDLLAttr(F)) { 11392 assert(VD->isStaticLocal()); 11393 // But if this is a static local in a dlimport/dllexport function, the 11394 // function will never be inlined, which means the var would never be 11395 // imported, so having it marked import/export is safe. 11396 } else { 11397 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11398 << DLLAttr; 11399 VD->setInvalidDecl(); 11400 } 11401 } 11402 11403 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11404 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11405 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11406 VD->dropAttr<UsedAttr>(); 11407 } 11408 } 11409 11410 const DeclContext *DC = VD->getDeclContext(); 11411 // If there's a #pragma GCC visibility in scope, and this isn't a class 11412 // member, set the visibility of this variable. 11413 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11414 AddPushedVisibilityAttribute(VD); 11415 11416 // FIXME: Warn on unused var template partial specializations. 11417 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11418 MarkUnusedFileScopedDecl(VD); 11419 11420 // Now we have parsed the initializer and can update the table of magic 11421 // tag values. 11422 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11423 !VD->getType()->isIntegralOrEnumerationType()) 11424 return; 11425 11426 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11427 const Expr *MagicValueExpr = VD->getInit(); 11428 if (!MagicValueExpr) { 11429 continue; 11430 } 11431 llvm::APSInt MagicValueInt; 11432 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11433 Diag(I->getRange().getBegin(), 11434 diag::err_type_tag_for_datatype_not_ice) 11435 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11436 continue; 11437 } 11438 if (MagicValueInt.getActiveBits() > 64) { 11439 Diag(I->getRange().getBegin(), 11440 diag::err_type_tag_for_datatype_too_large) 11441 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11442 continue; 11443 } 11444 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11445 RegisterTypeTagForDatatype(I->getArgumentKind(), 11446 MagicValue, 11447 I->getMatchingCType(), 11448 I->getLayoutCompatible(), 11449 I->getMustBeNull()); 11450 } 11451 } 11452 11453 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11454 auto *VD = dyn_cast<VarDecl>(DD); 11455 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11456 } 11457 11458 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11459 ArrayRef<Decl *> Group) { 11460 SmallVector<Decl*, 8> Decls; 11461 11462 if (DS.isTypeSpecOwned()) 11463 Decls.push_back(DS.getRepAsDecl()); 11464 11465 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11466 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11467 bool DiagnosedMultipleDecomps = false; 11468 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11469 bool DiagnosedNonDeducedAuto = false; 11470 11471 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11472 if (Decl *D = Group[i]) { 11473 // For declarators, there are some additional syntactic-ish checks we need 11474 // to perform. 11475 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11476 if (!FirstDeclaratorInGroup) 11477 FirstDeclaratorInGroup = DD; 11478 if (!FirstDecompDeclaratorInGroup) 11479 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11480 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11481 !hasDeducedAuto(DD)) 11482 FirstNonDeducedAutoInGroup = DD; 11483 11484 if (FirstDeclaratorInGroup != DD) { 11485 // A decomposition declaration cannot be combined with any other 11486 // declaration in the same group. 11487 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11488 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11489 diag::err_decomp_decl_not_alone) 11490 << FirstDeclaratorInGroup->getSourceRange() 11491 << DD->getSourceRange(); 11492 DiagnosedMultipleDecomps = true; 11493 } 11494 11495 // A declarator that uses 'auto' in any way other than to declare a 11496 // variable with a deduced type cannot be combined with any other 11497 // declarator in the same group. 11498 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11499 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11500 diag::err_auto_non_deduced_not_alone) 11501 << FirstNonDeducedAutoInGroup->getType() 11502 ->hasAutoForTrailingReturnType() 11503 << FirstDeclaratorInGroup->getSourceRange() 11504 << DD->getSourceRange(); 11505 DiagnosedNonDeducedAuto = true; 11506 } 11507 } 11508 } 11509 11510 Decls.push_back(D); 11511 } 11512 } 11513 11514 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11515 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11516 handleTagNumbering(Tag, S); 11517 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11518 getLangOpts().CPlusPlus) 11519 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11520 } 11521 } 11522 11523 return BuildDeclaratorGroup(Decls); 11524 } 11525 11526 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11527 /// group, performing any necessary semantic checking. 11528 Sema::DeclGroupPtrTy 11529 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11530 // C++14 [dcl.spec.auto]p7: (DR1347) 11531 // If the type that replaces the placeholder type is not the same in each 11532 // deduction, the program is ill-formed. 11533 if (Group.size() > 1) { 11534 QualType Deduced; 11535 VarDecl *DeducedDecl = nullptr; 11536 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11537 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11538 if (!D || D->isInvalidDecl()) 11539 break; 11540 DeducedType *DT = D->getType()->getContainedDeducedType(); 11541 if (!DT || DT->getDeducedType().isNull()) 11542 continue; 11543 if (Deduced.isNull()) { 11544 Deduced = DT->getDeducedType(); 11545 DeducedDecl = D; 11546 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11547 auto *AT = dyn_cast<AutoType>(DT); 11548 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11549 diag::err_auto_different_deductions) 11550 << (AT ? (unsigned)AT->getKeyword() : 3) 11551 << Deduced << DeducedDecl->getDeclName() 11552 << DT->getDeducedType() << D->getDeclName() 11553 << DeducedDecl->getInit()->getSourceRange() 11554 << D->getInit()->getSourceRange(); 11555 D->setInvalidDecl(); 11556 break; 11557 } 11558 } 11559 } 11560 11561 ActOnDocumentableDecls(Group); 11562 11563 return DeclGroupPtrTy::make( 11564 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11565 } 11566 11567 void Sema::ActOnDocumentableDecl(Decl *D) { 11568 ActOnDocumentableDecls(D); 11569 } 11570 11571 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11572 // Don't parse the comment if Doxygen diagnostics are ignored. 11573 if (Group.empty() || !Group[0]) 11574 return; 11575 11576 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11577 Group[0]->getLocation()) && 11578 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11579 Group[0]->getLocation())) 11580 return; 11581 11582 if (Group.size() >= 2) { 11583 // This is a decl group. Normally it will contain only declarations 11584 // produced from declarator list. But in case we have any definitions or 11585 // additional declaration references: 11586 // 'typedef struct S {} S;' 11587 // 'typedef struct S *S;' 11588 // 'struct S *pS;' 11589 // FinalizeDeclaratorGroup adds these as separate declarations. 11590 Decl *MaybeTagDecl = Group[0]; 11591 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11592 Group = Group.slice(1); 11593 } 11594 } 11595 11596 // See if there are any new comments that are not attached to a decl. 11597 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11598 if (!Comments.empty() && 11599 !Comments.back()->isAttached()) { 11600 // There is at least one comment that not attached to a decl. 11601 // Maybe it should be attached to one of these decls? 11602 // 11603 // Note that this way we pick up not only comments that precede the 11604 // declaration, but also comments that *follow* the declaration -- thanks to 11605 // the lookahead in the lexer: we've consumed the semicolon and looked 11606 // ahead through comments. 11607 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11608 Context.getCommentForDecl(Group[i], &PP); 11609 } 11610 } 11611 11612 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11613 /// to introduce parameters into function prototype scope. 11614 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11615 const DeclSpec &DS = D.getDeclSpec(); 11616 11617 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11618 11619 // C++03 [dcl.stc]p2 also permits 'auto'. 11620 StorageClass SC = SC_None; 11621 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11622 SC = SC_Register; 11623 } else if (getLangOpts().CPlusPlus && 11624 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11625 SC = SC_Auto; 11626 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11627 Diag(DS.getStorageClassSpecLoc(), 11628 diag::err_invalid_storage_class_in_func_decl); 11629 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11630 } 11631 11632 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11633 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11634 << DeclSpec::getSpecifierName(TSCS); 11635 if (DS.isInlineSpecified()) 11636 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11637 << getLangOpts().CPlusPlus1z; 11638 if (DS.isConstexprSpecified()) 11639 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11640 << 0; 11641 if (DS.isConceptSpecified()) 11642 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11643 11644 DiagnoseFunctionSpecifiers(DS); 11645 11646 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11647 QualType parmDeclType = TInfo->getType(); 11648 11649 if (getLangOpts().CPlusPlus) { 11650 // Check that there are no default arguments inside the type of this 11651 // parameter. 11652 CheckExtraCXXDefaultArguments(D); 11653 11654 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11655 if (D.getCXXScopeSpec().isSet()) { 11656 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11657 << D.getCXXScopeSpec().getRange(); 11658 D.getCXXScopeSpec().clear(); 11659 } 11660 } 11661 11662 // Ensure we have a valid name 11663 IdentifierInfo *II = nullptr; 11664 if (D.hasName()) { 11665 II = D.getIdentifier(); 11666 if (!II) { 11667 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11668 << GetNameForDeclarator(D).getName(); 11669 D.setInvalidType(true); 11670 } 11671 } 11672 11673 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11674 if (II) { 11675 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11676 ForRedeclaration); 11677 LookupName(R, S); 11678 if (R.isSingleResult()) { 11679 NamedDecl *PrevDecl = R.getFoundDecl(); 11680 if (PrevDecl->isTemplateParameter()) { 11681 // Maybe we will complain about the shadowed template parameter. 11682 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11683 // Just pretend that we didn't see the previous declaration. 11684 PrevDecl = nullptr; 11685 } else if (S->isDeclScope(PrevDecl)) { 11686 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11687 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11688 11689 // Recover by removing the name 11690 II = nullptr; 11691 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11692 D.setInvalidType(true); 11693 } 11694 } 11695 } 11696 11697 // Temporarily put parameter variables in the translation unit, not 11698 // the enclosing context. This prevents them from accidentally 11699 // looking like class members in C++. 11700 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11701 D.getLocStart(), 11702 D.getIdentifierLoc(), II, 11703 parmDeclType, TInfo, 11704 SC); 11705 11706 if (D.isInvalidType()) 11707 New->setInvalidDecl(); 11708 11709 assert(S->isFunctionPrototypeScope()); 11710 assert(S->getFunctionPrototypeDepth() >= 1); 11711 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11712 S->getNextFunctionPrototypeIndex()); 11713 11714 // Add the parameter declaration into this scope. 11715 S->AddDecl(New); 11716 if (II) 11717 IdResolver.AddDecl(New); 11718 11719 ProcessDeclAttributes(S, New, D); 11720 11721 if (D.getDeclSpec().isModulePrivateSpecified()) 11722 Diag(New->getLocation(), diag::err_module_private_local) 11723 << 1 << New->getDeclName() 11724 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11725 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11726 11727 if (New->hasAttr<BlocksAttr>()) { 11728 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11729 } 11730 return New; 11731 } 11732 11733 /// \brief Synthesizes a variable for a parameter arising from a 11734 /// typedef. 11735 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11736 SourceLocation Loc, 11737 QualType T) { 11738 /* FIXME: setting StartLoc == Loc. 11739 Would it be worth to modify callers so as to provide proper source 11740 location for the unnamed parameters, embedding the parameter's type? */ 11741 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11742 T, Context.getTrivialTypeSourceInfo(T, Loc), 11743 SC_None, nullptr); 11744 Param->setImplicit(); 11745 return Param; 11746 } 11747 11748 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11749 // Don't diagnose unused-parameter errors in template instantiations; we 11750 // will already have done so in the template itself. 11751 if (inTemplateInstantiation()) 11752 return; 11753 11754 for (const ParmVarDecl *Parameter : Parameters) { 11755 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11756 !Parameter->hasAttr<UnusedAttr>()) { 11757 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11758 << Parameter->getDeclName(); 11759 } 11760 } 11761 } 11762 11763 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11764 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11765 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11766 return; 11767 11768 // Warn if the return value is pass-by-value and larger than the specified 11769 // threshold. 11770 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11771 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11772 if (Size > LangOpts.NumLargeByValueCopy) 11773 Diag(D->getLocation(), diag::warn_return_value_size) 11774 << D->getDeclName() << Size; 11775 } 11776 11777 // Warn if any parameter is pass-by-value and larger than the specified 11778 // threshold. 11779 for (const ParmVarDecl *Parameter : Parameters) { 11780 QualType T = Parameter->getType(); 11781 if (T->isDependentType() || !T.isPODType(Context)) 11782 continue; 11783 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11784 if (Size > LangOpts.NumLargeByValueCopy) 11785 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11786 << Parameter->getDeclName() << Size; 11787 } 11788 } 11789 11790 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11791 SourceLocation NameLoc, IdentifierInfo *Name, 11792 QualType T, TypeSourceInfo *TSInfo, 11793 StorageClass SC) { 11794 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11795 if (getLangOpts().ObjCAutoRefCount && 11796 T.getObjCLifetime() == Qualifiers::OCL_None && 11797 T->isObjCLifetimeType()) { 11798 11799 Qualifiers::ObjCLifetime lifetime; 11800 11801 // Special cases for arrays: 11802 // - if it's const, use __unsafe_unretained 11803 // - otherwise, it's an error 11804 if (T->isArrayType()) { 11805 if (!T.isConstQualified()) { 11806 DelayedDiagnostics.add( 11807 sema::DelayedDiagnostic::makeForbiddenType( 11808 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11809 } 11810 lifetime = Qualifiers::OCL_ExplicitNone; 11811 } else { 11812 lifetime = T->getObjCARCImplicitLifetime(); 11813 } 11814 T = Context.getLifetimeQualifiedType(T, lifetime); 11815 } 11816 11817 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11818 Context.getAdjustedParameterType(T), 11819 TSInfo, SC, nullptr); 11820 11821 // Parameters can not be abstract class types. 11822 // For record types, this is done by the AbstractClassUsageDiagnoser once 11823 // the class has been completely parsed. 11824 if (!CurContext->isRecord() && 11825 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11826 AbstractParamType)) 11827 New->setInvalidDecl(); 11828 11829 // Parameter declarators cannot be interface types. All ObjC objects are 11830 // passed by reference. 11831 if (T->isObjCObjectType()) { 11832 SourceLocation TypeEndLoc = 11833 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11834 Diag(NameLoc, 11835 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11836 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11837 T = Context.getObjCObjectPointerType(T); 11838 New->setType(T); 11839 } 11840 11841 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11842 // duration shall not be qualified by an address-space qualifier." 11843 // Since all parameters have automatic store duration, they can not have 11844 // an address space. 11845 if (T.getAddressSpace() != 0) { 11846 // OpenCL allows function arguments declared to be an array of a type 11847 // to be qualified with an address space. 11848 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11849 Diag(NameLoc, diag::err_arg_with_address_space); 11850 New->setInvalidDecl(); 11851 } 11852 } 11853 11854 return New; 11855 } 11856 11857 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11858 SourceLocation LocAfterDecls) { 11859 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11860 11861 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11862 // for a K&R function. 11863 if (!FTI.hasPrototype) { 11864 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11865 --i; 11866 if (FTI.Params[i].Param == nullptr) { 11867 SmallString<256> Code; 11868 llvm::raw_svector_ostream(Code) 11869 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11870 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11871 << FTI.Params[i].Ident 11872 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11873 11874 // Implicitly declare the argument as type 'int' for lack of a better 11875 // type. 11876 AttributeFactory attrs; 11877 DeclSpec DS(attrs); 11878 const char* PrevSpec; // unused 11879 unsigned DiagID; // unused 11880 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11881 DiagID, Context.getPrintingPolicy()); 11882 // Use the identifier location for the type source range. 11883 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11884 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11885 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11886 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11887 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11888 } 11889 } 11890 } 11891 } 11892 11893 Decl * 11894 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11895 MultiTemplateParamsArg TemplateParameterLists, 11896 SkipBodyInfo *SkipBody) { 11897 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11898 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11899 Scope *ParentScope = FnBodyScope->getParent(); 11900 11901 D.setFunctionDefinitionKind(FDK_Definition); 11902 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11903 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11904 } 11905 11906 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11907 Consumer.HandleInlineFunctionDefinition(D); 11908 } 11909 11910 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11911 const FunctionDecl*& PossibleZeroParamPrototype) { 11912 // Don't warn about invalid declarations. 11913 if (FD->isInvalidDecl()) 11914 return false; 11915 11916 // Or declarations that aren't global. 11917 if (!FD->isGlobal()) 11918 return false; 11919 11920 // Don't warn about C++ member functions. 11921 if (isa<CXXMethodDecl>(FD)) 11922 return false; 11923 11924 // Don't warn about 'main'. 11925 if (FD->isMain()) 11926 return false; 11927 11928 // Don't warn about inline functions. 11929 if (FD->isInlined()) 11930 return false; 11931 11932 // Don't warn about function templates. 11933 if (FD->getDescribedFunctionTemplate()) 11934 return false; 11935 11936 // Don't warn about function template specializations. 11937 if (FD->isFunctionTemplateSpecialization()) 11938 return false; 11939 11940 // Don't warn for OpenCL kernels. 11941 if (FD->hasAttr<OpenCLKernelAttr>()) 11942 return false; 11943 11944 // Don't warn on explicitly deleted functions. 11945 if (FD->isDeleted()) 11946 return false; 11947 11948 bool MissingPrototype = true; 11949 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11950 Prev; Prev = Prev->getPreviousDecl()) { 11951 // Ignore any declarations that occur in function or method 11952 // scope, because they aren't visible from the header. 11953 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11954 continue; 11955 11956 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11957 if (FD->getNumParams() == 0) 11958 PossibleZeroParamPrototype = Prev; 11959 break; 11960 } 11961 11962 return MissingPrototype; 11963 } 11964 11965 void 11966 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11967 const FunctionDecl *EffectiveDefinition, 11968 SkipBodyInfo *SkipBody) { 11969 const FunctionDecl *Definition = EffectiveDefinition; 11970 if (!Definition) 11971 if (!FD->isDefined(Definition)) 11972 return; 11973 11974 if (canRedefineFunction(Definition, getLangOpts())) 11975 return; 11976 11977 // Don't emit an error when this is redefinition of a typo-corrected 11978 // definition. 11979 if (TypoCorrectedFunctionDefinitions.count(Definition)) 11980 return; 11981 11982 // If we don't have a visible definition of the function, and it's inline or 11983 // a template, skip the new definition. 11984 if (SkipBody && !hasVisibleDefinition(Definition) && 11985 (Definition->getFormalLinkage() == InternalLinkage || 11986 Definition->isInlined() || 11987 Definition->getDescribedFunctionTemplate() || 11988 Definition->getNumTemplateParameterLists())) { 11989 SkipBody->ShouldSkip = true; 11990 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11991 makeMergedDefinitionVisible(TD); 11992 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 11993 return; 11994 } 11995 11996 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11997 Definition->getStorageClass() == SC_Extern) 11998 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11999 << FD->getDeclName() << getLangOpts().CPlusPlus; 12000 else 12001 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12002 12003 Diag(Definition->getLocation(), diag::note_previous_definition); 12004 FD->setInvalidDecl(); 12005 } 12006 12007 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12008 Sema &S) { 12009 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12010 12011 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12012 LSI->CallOperator = CallOperator; 12013 LSI->Lambda = LambdaClass; 12014 LSI->ReturnType = CallOperator->getReturnType(); 12015 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12016 12017 if (LCD == LCD_None) 12018 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12019 else if (LCD == LCD_ByCopy) 12020 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12021 else if (LCD == LCD_ByRef) 12022 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12023 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12024 12025 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12026 LSI->Mutable = !CallOperator->isConst(); 12027 12028 // Add the captures to the LSI so they can be noted as already 12029 // captured within tryCaptureVar. 12030 auto I = LambdaClass->field_begin(); 12031 for (const auto &C : LambdaClass->captures()) { 12032 if (C.capturesVariable()) { 12033 VarDecl *VD = C.getCapturedVar(); 12034 if (VD->isInitCapture()) 12035 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12036 QualType CaptureType = VD->getType(); 12037 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12038 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12039 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12040 /*EllipsisLoc*/C.isPackExpansion() 12041 ? C.getEllipsisLoc() : SourceLocation(), 12042 CaptureType, /*Expr*/ nullptr); 12043 12044 } else if (C.capturesThis()) { 12045 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12046 /*Expr*/ nullptr, 12047 C.getCaptureKind() == LCK_StarThis); 12048 } else { 12049 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12050 } 12051 ++I; 12052 } 12053 } 12054 12055 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12056 SkipBodyInfo *SkipBody) { 12057 if (!D) 12058 return D; 12059 FunctionDecl *FD = nullptr; 12060 12061 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12062 FD = FunTmpl->getTemplatedDecl(); 12063 else 12064 FD = cast<FunctionDecl>(D); 12065 12066 // Check for defining attributes before the check for redefinition. 12067 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12068 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12069 FD->dropAttr<AliasAttr>(); 12070 FD->setInvalidDecl(); 12071 } 12072 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12073 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12074 FD->dropAttr<IFuncAttr>(); 12075 FD->setInvalidDecl(); 12076 } 12077 12078 // See if this is a redefinition. 12079 if (!FD->isLateTemplateParsed()) { 12080 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12081 12082 // If we're skipping the body, we're done. Don't enter the scope. 12083 if (SkipBody && SkipBody->ShouldSkip) 12084 return D; 12085 } 12086 12087 // Mark this function as "will have a body eventually". This lets users to 12088 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12089 // this function. 12090 FD->setWillHaveBody(); 12091 12092 // If we are instantiating a generic lambda call operator, push 12093 // a LambdaScopeInfo onto the function stack. But use the information 12094 // that's already been calculated (ActOnLambdaExpr) to prime the current 12095 // LambdaScopeInfo. 12096 // When the template operator is being specialized, the LambdaScopeInfo, 12097 // has to be properly restored so that tryCaptureVariable doesn't try 12098 // and capture any new variables. In addition when calculating potential 12099 // captures during transformation of nested lambdas, it is necessary to 12100 // have the LSI properly restored. 12101 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12102 assert(inTemplateInstantiation() && 12103 "There should be an active template instantiation on the stack " 12104 "when instantiating a generic lambda!"); 12105 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12106 } else { 12107 // Enter a new function scope 12108 PushFunctionScope(); 12109 } 12110 12111 // Builtin functions cannot be defined. 12112 if (unsigned BuiltinID = FD->getBuiltinID()) { 12113 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12114 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12115 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12116 FD->setInvalidDecl(); 12117 } 12118 } 12119 12120 // The return type of a function definition must be complete 12121 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12122 QualType ResultType = FD->getReturnType(); 12123 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12124 !FD->isInvalidDecl() && 12125 RequireCompleteType(FD->getLocation(), ResultType, 12126 diag::err_func_def_incomplete_result)) 12127 FD->setInvalidDecl(); 12128 12129 if (FnBodyScope) 12130 PushDeclContext(FnBodyScope, FD); 12131 12132 // Check the validity of our function parameters 12133 CheckParmsForFunctionDef(FD->parameters(), 12134 /*CheckParameterNames=*/true); 12135 12136 // Add non-parameter declarations already in the function to the current 12137 // scope. 12138 if (FnBodyScope) { 12139 for (Decl *NPD : FD->decls()) { 12140 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12141 if (!NonParmDecl) 12142 continue; 12143 assert(!isa<ParmVarDecl>(NonParmDecl) && 12144 "parameters should not be in newly created FD yet"); 12145 12146 // If the decl has a name, make it accessible in the current scope. 12147 if (NonParmDecl->getDeclName()) 12148 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12149 12150 // Similarly, dive into enums and fish their constants out, making them 12151 // accessible in this scope. 12152 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12153 for (auto *EI : ED->enumerators()) 12154 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12155 } 12156 } 12157 } 12158 12159 // Introduce our parameters into the function scope 12160 for (auto Param : FD->parameters()) { 12161 Param->setOwningFunction(FD); 12162 12163 // If this has an identifier, add it to the scope stack. 12164 if (Param->getIdentifier() && FnBodyScope) { 12165 CheckShadow(FnBodyScope, Param); 12166 12167 PushOnScopeChains(Param, FnBodyScope); 12168 } 12169 } 12170 12171 // Ensure that the function's exception specification is instantiated. 12172 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12173 ResolveExceptionSpec(D->getLocation(), FPT); 12174 12175 // dllimport cannot be applied to non-inline function definitions. 12176 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12177 !FD->isTemplateInstantiation()) { 12178 assert(!FD->hasAttr<DLLExportAttr>()); 12179 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12180 FD->setInvalidDecl(); 12181 return D; 12182 } 12183 // We want to attach documentation to original Decl (which might be 12184 // a function template). 12185 ActOnDocumentableDecl(D); 12186 if (getCurLexicalContext()->isObjCContainer() && 12187 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12188 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12189 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12190 12191 return D; 12192 } 12193 12194 /// \brief Given the set of return statements within a function body, 12195 /// compute the variables that are subject to the named return value 12196 /// optimization. 12197 /// 12198 /// Each of the variables that is subject to the named return value 12199 /// optimization will be marked as NRVO variables in the AST, and any 12200 /// return statement that has a marked NRVO variable as its NRVO candidate can 12201 /// use the named return value optimization. 12202 /// 12203 /// This function applies a very simplistic algorithm for NRVO: if every return 12204 /// statement in the scope of a variable has the same NRVO candidate, that 12205 /// candidate is an NRVO variable. 12206 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12207 ReturnStmt **Returns = Scope->Returns.data(); 12208 12209 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12210 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12211 if (!NRVOCandidate->isNRVOVariable()) 12212 Returns[I]->setNRVOCandidate(nullptr); 12213 } 12214 } 12215 } 12216 12217 bool Sema::canDelayFunctionBody(const Declarator &D) { 12218 // We can't delay parsing the body of a constexpr function template (yet). 12219 if (D.getDeclSpec().isConstexprSpecified()) 12220 return false; 12221 12222 // We can't delay parsing the body of a function template with a deduced 12223 // return type (yet). 12224 if (D.getDeclSpec().hasAutoTypeSpec()) { 12225 // If the placeholder introduces a non-deduced trailing return type, 12226 // we can still delay parsing it. 12227 if (D.getNumTypeObjects()) { 12228 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12229 if (Outer.Kind == DeclaratorChunk::Function && 12230 Outer.Fun.hasTrailingReturnType()) { 12231 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12232 return Ty.isNull() || !Ty->isUndeducedType(); 12233 } 12234 } 12235 return false; 12236 } 12237 12238 return true; 12239 } 12240 12241 bool Sema::canSkipFunctionBody(Decl *D) { 12242 // We cannot skip the body of a function (or function template) which is 12243 // constexpr, since we may need to evaluate its body in order to parse the 12244 // rest of the file. 12245 // We cannot skip the body of a function with an undeduced return type, 12246 // because any callers of that function need to know the type. 12247 if (const FunctionDecl *FD = D->getAsFunction()) 12248 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12249 return false; 12250 return Consumer.shouldSkipFunctionBody(D); 12251 } 12252 12253 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12254 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12255 FD->setHasSkippedBody(); 12256 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12257 MD->setHasSkippedBody(); 12258 return Decl; 12259 } 12260 12261 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12262 return ActOnFinishFunctionBody(D, BodyArg, false); 12263 } 12264 12265 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12266 bool IsInstantiation) { 12267 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12268 12269 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12270 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12271 12272 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12273 CheckCompletedCoroutineBody(FD, Body); 12274 12275 if (FD) { 12276 FD->setBody(Body); 12277 FD->setWillHaveBody(false); 12278 12279 if (getLangOpts().CPlusPlus14) { 12280 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12281 FD->getReturnType()->isUndeducedType()) { 12282 // If the function has a deduced result type but contains no 'return' 12283 // statements, the result type as written must be exactly 'auto', and 12284 // the deduced result type is 'void'. 12285 if (!FD->getReturnType()->getAs<AutoType>()) { 12286 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12287 << FD->getReturnType(); 12288 FD->setInvalidDecl(); 12289 } else { 12290 // Substitute 'void' for the 'auto' in the type. 12291 TypeLoc ResultType = getReturnTypeLoc(FD); 12292 Context.adjustDeducedFunctionResultType( 12293 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12294 } 12295 } 12296 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12297 // In C++11, we don't use 'auto' deduction rules for lambda call 12298 // operators because we don't support return type deduction. 12299 auto *LSI = getCurLambda(); 12300 if (LSI->HasImplicitReturnType) { 12301 deduceClosureReturnType(*LSI); 12302 12303 // C++11 [expr.prim.lambda]p4: 12304 // [...] if there are no return statements in the compound-statement 12305 // [the deduced type is] the type void 12306 QualType RetType = 12307 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12308 12309 // Update the return type to the deduced type. 12310 const FunctionProtoType *Proto = 12311 FD->getType()->getAs<FunctionProtoType>(); 12312 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12313 Proto->getExtProtoInfo())); 12314 } 12315 } 12316 12317 // The only way to be included in UndefinedButUsed is if there is an 12318 // ODR use before the definition. Avoid the expensive map lookup if this 12319 // is the first declaration. 12320 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12321 if (!FD->isExternallyVisible()) 12322 UndefinedButUsed.erase(FD); 12323 else if (FD->isInlined() && 12324 !LangOpts.GNUInline && 12325 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12326 UndefinedButUsed.erase(FD); 12327 } 12328 12329 // If the function implicitly returns zero (like 'main') or is naked, 12330 // don't complain about missing return statements. 12331 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12332 WP.disableCheckFallThrough(); 12333 12334 // MSVC permits the use of pure specifier (=0) on function definition, 12335 // defined at class scope, warn about this non-standard construct. 12336 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12337 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12338 12339 if (!FD->isInvalidDecl()) { 12340 // Don't diagnose unused parameters of defaulted or deleted functions. 12341 if (!FD->isDeleted() && !FD->isDefaulted()) 12342 DiagnoseUnusedParameters(FD->parameters()); 12343 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12344 FD->getReturnType(), FD); 12345 12346 // If this is a structor, we need a vtable. 12347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12348 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12349 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12350 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12351 12352 // Try to apply the named return value optimization. We have to check 12353 // if we can do this here because lambdas keep return statements around 12354 // to deduce an implicit return type. 12355 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12356 !FD->isDependentContext()) 12357 computeNRVO(Body, getCurFunction()); 12358 } 12359 12360 // GNU warning -Wmissing-prototypes: 12361 // Warn if a global function is defined without a previous 12362 // prototype declaration. This warning is issued even if the 12363 // definition itself provides a prototype. The aim is to detect 12364 // global functions that fail to be declared in header files. 12365 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12366 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12367 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12368 12369 if (PossibleZeroParamPrototype) { 12370 // We found a declaration that is not a prototype, 12371 // but that could be a zero-parameter prototype 12372 if (TypeSourceInfo *TI = 12373 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12374 TypeLoc TL = TI->getTypeLoc(); 12375 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12376 Diag(PossibleZeroParamPrototype->getLocation(), 12377 diag::note_declaration_not_a_prototype) 12378 << PossibleZeroParamPrototype 12379 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12380 } 12381 } 12382 12383 // GNU warning -Wstrict-prototypes 12384 // Warn if K&R function is defined without a previous declaration. 12385 // This warning is issued only if the definition itself does not provide 12386 // a prototype. Only K&R definitions do not provide a prototype. 12387 // An empty list in a function declarator that is part of a definition 12388 // of that function specifies that the function has no parameters 12389 // (C99 6.7.5.3p14) 12390 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12391 !LangOpts.CPlusPlus) { 12392 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12393 TypeLoc TL = TI->getTypeLoc(); 12394 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12395 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12396 } 12397 } 12398 12399 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12400 const CXXMethodDecl *KeyFunction; 12401 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12402 MD->isVirtual() && 12403 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12404 MD == KeyFunction->getCanonicalDecl()) { 12405 // Update the key-function state if necessary for this ABI. 12406 if (FD->isInlined() && 12407 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12408 Context.setNonKeyFunction(MD); 12409 12410 // If the newly-chosen key function is already defined, then we 12411 // need to mark the vtable as used retroactively. 12412 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12413 const FunctionDecl *Definition; 12414 if (KeyFunction && KeyFunction->isDefined(Definition)) 12415 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12416 } else { 12417 // We just defined they key function; mark the vtable as used. 12418 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12419 } 12420 } 12421 } 12422 12423 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12424 "Function parsing confused"); 12425 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12426 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12427 MD->setBody(Body); 12428 if (!MD->isInvalidDecl()) { 12429 DiagnoseUnusedParameters(MD->parameters()); 12430 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12431 MD->getReturnType(), MD); 12432 12433 if (Body) 12434 computeNRVO(Body, getCurFunction()); 12435 } 12436 if (getCurFunction()->ObjCShouldCallSuper) { 12437 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12438 << MD->getSelector().getAsString(); 12439 getCurFunction()->ObjCShouldCallSuper = false; 12440 } 12441 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12442 const ObjCMethodDecl *InitMethod = nullptr; 12443 bool isDesignated = 12444 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12445 assert(isDesignated && InitMethod); 12446 (void)isDesignated; 12447 12448 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12449 auto IFace = MD->getClassInterface(); 12450 if (!IFace) 12451 return false; 12452 auto SuperD = IFace->getSuperClass(); 12453 if (!SuperD) 12454 return false; 12455 return SuperD->getIdentifier() == 12456 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12457 }; 12458 // Don't issue this warning for unavailable inits or direct subclasses 12459 // of NSObject. 12460 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12461 Diag(MD->getLocation(), 12462 diag::warn_objc_designated_init_missing_super_call); 12463 Diag(InitMethod->getLocation(), 12464 diag::note_objc_designated_init_marked_here); 12465 } 12466 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12467 } 12468 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12469 // Don't issue this warning for unavaialable inits. 12470 if (!MD->isUnavailable()) 12471 Diag(MD->getLocation(), 12472 diag::warn_objc_secondary_init_missing_init_call); 12473 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12474 } 12475 } else { 12476 return nullptr; 12477 } 12478 12479 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12480 DiagnoseUnguardedAvailabilityViolations(dcl); 12481 12482 assert(!getCurFunction()->ObjCShouldCallSuper && 12483 "This should only be set for ObjC methods, which should have been " 12484 "handled in the block above."); 12485 12486 // Verify and clean out per-function state. 12487 if (Body && (!FD || !FD->isDefaulted())) { 12488 // C++ constructors that have function-try-blocks can't have return 12489 // statements in the handlers of that block. (C++ [except.handle]p14) 12490 // Verify this. 12491 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12492 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12493 12494 // Verify that gotos and switch cases don't jump into scopes illegally. 12495 if (getCurFunction()->NeedsScopeChecking() && 12496 !PP.isCodeCompletionEnabled()) 12497 DiagnoseInvalidJumps(Body); 12498 12499 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12500 if (!Destructor->getParent()->isDependentType()) 12501 CheckDestructor(Destructor); 12502 12503 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12504 Destructor->getParent()); 12505 } 12506 12507 // If any errors have occurred, clear out any temporaries that may have 12508 // been leftover. This ensures that these temporaries won't be picked up for 12509 // deletion in some later function. 12510 if (getDiagnostics().hasErrorOccurred() || 12511 getDiagnostics().getSuppressAllDiagnostics()) { 12512 DiscardCleanupsInEvaluationContext(); 12513 } 12514 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12515 !isa<FunctionTemplateDecl>(dcl)) { 12516 // Since the body is valid, issue any analysis-based warnings that are 12517 // enabled. 12518 ActivePolicy = &WP; 12519 } 12520 12521 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12522 (!CheckConstexprFunctionDecl(FD) || 12523 !CheckConstexprFunctionBody(FD, Body))) 12524 FD->setInvalidDecl(); 12525 12526 if (FD && FD->hasAttr<NakedAttr>()) { 12527 for (const Stmt *S : Body->children()) { 12528 // Allow local register variables without initializer as they don't 12529 // require prologue. 12530 bool RegisterVariables = false; 12531 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12532 for (const auto *Decl : DS->decls()) { 12533 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12534 RegisterVariables = 12535 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12536 if (!RegisterVariables) 12537 break; 12538 } 12539 } 12540 } 12541 if (RegisterVariables) 12542 continue; 12543 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12544 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12545 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12546 FD->setInvalidDecl(); 12547 break; 12548 } 12549 } 12550 } 12551 12552 assert(ExprCleanupObjects.size() == 12553 ExprEvalContexts.back().NumCleanupObjects && 12554 "Leftover temporaries in function"); 12555 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12556 assert(MaybeODRUseExprs.empty() && 12557 "Leftover expressions for odr-use checking"); 12558 } 12559 12560 if (!IsInstantiation) 12561 PopDeclContext(); 12562 12563 PopFunctionScopeInfo(ActivePolicy, dcl); 12564 // If any errors have occurred, clear out any temporaries that may have 12565 // been leftover. This ensures that these temporaries won't be picked up for 12566 // deletion in some later function. 12567 if (getDiagnostics().hasErrorOccurred()) { 12568 DiscardCleanupsInEvaluationContext(); 12569 } 12570 12571 return dcl; 12572 } 12573 12574 /// When we finish delayed parsing of an attribute, we must attach it to the 12575 /// relevant Decl. 12576 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12577 ParsedAttributes &Attrs) { 12578 // Always attach attributes to the underlying decl. 12579 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12580 D = TD->getTemplatedDecl(); 12581 ProcessDeclAttributeList(S, D, Attrs.getList()); 12582 12583 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12584 if (Method->isStatic()) 12585 checkThisInStaticMemberFunctionAttributes(Method); 12586 } 12587 12588 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12589 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12590 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12591 IdentifierInfo &II, Scope *S) { 12592 // Before we produce a declaration for an implicitly defined 12593 // function, see whether there was a locally-scoped declaration of 12594 // this name as a function or variable. If so, use that 12595 // (non-visible) declaration, and complain about it. 12596 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12597 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12598 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12599 return ExternCPrev; 12600 } 12601 12602 // Extension in C99. Legal in C90, but warn about it. 12603 unsigned diag_id; 12604 if (II.getName().startswith("__builtin_")) 12605 diag_id = diag::warn_builtin_unknown; 12606 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 12607 else if (getLangOpts().OpenCL) 12608 diag_id = diag::err_opencl_implicit_function_decl; 12609 else if (getLangOpts().C99) 12610 diag_id = diag::ext_implicit_function_decl; 12611 else 12612 diag_id = diag::warn_implicit_function_decl; 12613 Diag(Loc, diag_id) << &II; 12614 12615 // Because typo correction is expensive, only do it if the implicit 12616 // function declaration is going to be treated as an error. 12617 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12618 TypoCorrection Corrected; 12619 if (S && 12620 (Corrected = CorrectTypo( 12621 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12622 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12623 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12624 /*ErrorRecovery*/false); 12625 } 12626 12627 // Set a Declarator for the implicit definition: int foo(); 12628 const char *Dummy; 12629 AttributeFactory attrFactory; 12630 DeclSpec DS(attrFactory); 12631 unsigned DiagID; 12632 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12633 Context.getPrintingPolicy()); 12634 (void)Error; // Silence warning. 12635 assert(!Error && "Error setting up implicit decl!"); 12636 SourceLocation NoLoc; 12637 Declarator D(DS, Declarator::BlockContext); 12638 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12639 /*IsAmbiguous=*/false, 12640 /*LParenLoc=*/NoLoc, 12641 /*Params=*/nullptr, 12642 /*NumParams=*/0, 12643 /*EllipsisLoc=*/NoLoc, 12644 /*RParenLoc=*/NoLoc, 12645 /*TypeQuals=*/0, 12646 /*RefQualifierIsLvalueRef=*/true, 12647 /*RefQualifierLoc=*/NoLoc, 12648 /*ConstQualifierLoc=*/NoLoc, 12649 /*VolatileQualifierLoc=*/NoLoc, 12650 /*RestrictQualifierLoc=*/NoLoc, 12651 /*MutableLoc=*/NoLoc, 12652 EST_None, 12653 /*ESpecRange=*/SourceRange(), 12654 /*Exceptions=*/nullptr, 12655 /*ExceptionRanges=*/nullptr, 12656 /*NumExceptions=*/0, 12657 /*NoexceptExpr=*/nullptr, 12658 /*ExceptionSpecTokens=*/nullptr, 12659 /*DeclsInPrototype=*/None, 12660 Loc, Loc, D), 12661 DS.getAttributes(), 12662 SourceLocation()); 12663 D.SetIdentifier(&II, Loc); 12664 12665 // Insert this function into translation-unit scope. 12666 12667 DeclContext *PrevDC = CurContext; 12668 CurContext = Context.getTranslationUnitDecl(); 12669 12670 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12671 FD->setImplicit(); 12672 12673 CurContext = PrevDC; 12674 12675 AddKnownFunctionAttributes(FD); 12676 12677 return FD; 12678 } 12679 12680 /// \brief Adds any function attributes that we know a priori based on 12681 /// the declaration of this function. 12682 /// 12683 /// These attributes can apply both to implicitly-declared builtins 12684 /// (like __builtin___printf_chk) or to library-declared functions 12685 /// like NSLog or printf. 12686 /// 12687 /// We need to check for duplicate attributes both here and where user-written 12688 /// attributes are applied to declarations. 12689 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12690 if (FD->isInvalidDecl()) 12691 return; 12692 12693 // If this is a built-in function, map its builtin attributes to 12694 // actual attributes. 12695 if (unsigned BuiltinID = FD->getBuiltinID()) { 12696 // Handle printf-formatting attributes. 12697 unsigned FormatIdx; 12698 bool HasVAListArg; 12699 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12700 if (!FD->hasAttr<FormatAttr>()) { 12701 const char *fmt = "printf"; 12702 unsigned int NumParams = FD->getNumParams(); 12703 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12704 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12705 fmt = "NSString"; 12706 FD->addAttr(FormatAttr::CreateImplicit(Context, 12707 &Context.Idents.get(fmt), 12708 FormatIdx+1, 12709 HasVAListArg ? 0 : FormatIdx+2, 12710 FD->getLocation())); 12711 } 12712 } 12713 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12714 HasVAListArg)) { 12715 if (!FD->hasAttr<FormatAttr>()) 12716 FD->addAttr(FormatAttr::CreateImplicit(Context, 12717 &Context.Idents.get("scanf"), 12718 FormatIdx+1, 12719 HasVAListArg ? 0 : FormatIdx+2, 12720 FD->getLocation())); 12721 } 12722 12723 // Mark const if we don't care about errno and that is the only 12724 // thing preventing the function from being const. This allows 12725 // IRgen to use LLVM intrinsics for such functions. 12726 if (!getLangOpts().MathErrno && 12727 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12728 if (!FD->hasAttr<ConstAttr>()) 12729 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12730 } 12731 12732 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12733 !FD->hasAttr<ReturnsTwiceAttr>()) 12734 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12735 FD->getLocation())); 12736 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12737 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12738 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12739 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12740 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12741 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12742 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12743 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12744 // Add the appropriate attribute, depending on the CUDA compilation mode 12745 // and which target the builtin belongs to. For example, during host 12746 // compilation, aux builtins are __device__, while the rest are __host__. 12747 if (getLangOpts().CUDAIsDevice != 12748 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12749 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12750 else 12751 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12752 } 12753 } 12754 12755 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12756 // throw, add an implicit nothrow attribute to any extern "C" function we come 12757 // across. 12758 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12759 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12760 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12761 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12762 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12763 } 12764 12765 IdentifierInfo *Name = FD->getIdentifier(); 12766 if (!Name) 12767 return; 12768 if ((!getLangOpts().CPlusPlus && 12769 FD->getDeclContext()->isTranslationUnit()) || 12770 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12771 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12772 LinkageSpecDecl::lang_c)) { 12773 // Okay: this could be a libc/libm/Objective-C function we know 12774 // about. 12775 } else 12776 return; 12777 12778 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12779 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12780 // target-specific builtins, perhaps? 12781 if (!FD->hasAttr<FormatAttr>()) 12782 FD->addAttr(FormatAttr::CreateImplicit(Context, 12783 &Context.Idents.get("printf"), 2, 12784 Name->isStr("vasprintf") ? 0 : 3, 12785 FD->getLocation())); 12786 } 12787 12788 if (Name->isStr("__CFStringMakeConstantString")) { 12789 // We already have a __builtin___CFStringMakeConstantString, 12790 // but builds that use -fno-constant-cfstrings don't go through that. 12791 if (!FD->hasAttr<FormatArgAttr>()) 12792 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12793 FD->getLocation())); 12794 } 12795 } 12796 12797 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12798 TypeSourceInfo *TInfo) { 12799 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12800 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12801 12802 if (!TInfo) { 12803 assert(D.isInvalidType() && "no declarator info for valid type"); 12804 TInfo = Context.getTrivialTypeSourceInfo(T); 12805 } 12806 12807 // Scope manipulation handled by caller. 12808 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12809 D.getLocStart(), 12810 D.getIdentifierLoc(), 12811 D.getIdentifier(), 12812 TInfo); 12813 12814 // Bail out immediately if we have an invalid declaration. 12815 if (D.isInvalidType()) { 12816 NewTD->setInvalidDecl(); 12817 return NewTD; 12818 } 12819 12820 if (D.getDeclSpec().isModulePrivateSpecified()) { 12821 if (CurContext->isFunctionOrMethod()) 12822 Diag(NewTD->getLocation(), diag::err_module_private_local) 12823 << 2 << NewTD->getDeclName() 12824 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12825 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12826 else 12827 NewTD->setModulePrivate(); 12828 } 12829 12830 // C++ [dcl.typedef]p8: 12831 // If the typedef declaration defines an unnamed class (or 12832 // enum), the first typedef-name declared by the declaration 12833 // to be that class type (or enum type) is used to denote the 12834 // class type (or enum type) for linkage purposes only. 12835 // We need to check whether the type was declared in the declaration. 12836 switch (D.getDeclSpec().getTypeSpecType()) { 12837 case TST_enum: 12838 case TST_struct: 12839 case TST_interface: 12840 case TST_union: 12841 case TST_class: { 12842 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12843 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12844 break; 12845 } 12846 12847 default: 12848 break; 12849 } 12850 12851 return NewTD; 12852 } 12853 12854 /// \brief Check that this is a valid underlying type for an enum declaration. 12855 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12856 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12857 QualType T = TI->getType(); 12858 12859 if (T->isDependentType()) 12860 return false; 12861 12862 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12863 if (BT->isInteger()) 12864 return false; 12865 12866 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12867 return true; 12868 } 12869 12870 /// Check whether this is a valid redeclaration of a previous enumeration. 12871 /// \return true if the redeclaration was invalid. 12872 bool Sema::CheckEnumRedeclaration( 12873 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12874 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12875 bool IsFixed = !EnumUnderlyingTy.isNull(); 12876 12877 if (IsScoped != Prev->isScoped()) { 12878 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12879 << Prev->isScoped(); 12880 Diag(Prev->getLocation(), diag::note_previous_declaration); 12881 return true; 12882 } 12883 12884 if (IsFixed && Prev->isFixed()) { 12885 if (!EnumUnderlyingTy->isDependentType() && 12886 !Prev->getIntegerType()->isDependentType() && 12887 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12888 Prev->getIntegerType())) { 12889 // TODO: Highlight the underlying type of the redeclaration. 12890 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12891 << EnumUnderlyingTy << Prev->getIntegerType(); 12892 Diag(Prev->getLocation(), diag::note_previous_declaration) 12893 << Prev->getIntegerTypeRange(); 12894 return true; 12895 } 12896 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12897 ; 12898 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12899 ; 12900 } else if (IsFixed != Prev->isFixed()) { 12901 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12902 << Prev->isFixed(); 12903 Diag(Prev->getLocation(), diag::note_previous_declaration); 12904 return true; 12905 } 12906 12907 return false; 12908 } 12909 12910 /// \brief Get diagnostic %select index for tag kind for 12911 /// redeclaration diagnostic message. 12912 /// WARNING: Indexes apply to particular diagnostics only! 12913 /// 12914 /// \returns diagnostic %select index. 12915 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12916 switch (Tag) { 12917 case TTK_Struct: return 0; 12918 case TTK_Interface: return 1; 12919 case TTK_Class: return 2; 12920 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12921 } 12922 } 12923 12924 /// \brief Determine if tag kind is a class-key compatible with 12925 /// class for redeclaration (class, struct, or __interface). 12926 /// 12927 /// \returns true iff the tag kind is compatible. 12928 static bool isClassCompatTagKind(TagTypeKind Tag) 12929 { 12930 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12931 } 12932 12933 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12934 TagTypeKind TTK) { 12935 if (isa<TypedefDecl>(PrevDecl)) 12936 return NTK_Typedef; 12937 else if (isa<TypeAliasDecl>(PrevDecl)) 12938 return NTK_TypeAlias; 12939 else if (isa<ClassTemplateDecl>(PrevDecl)) 12940 return NTK_Template; 12941 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12942 return NTK_TypeAliasTemplate; 12943 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12944 return NTK_TemplateTemplateArgument; 12945 switch (TTK) { 12946 case TTK_Struct: 12947 case TTK_Interface: 12948 case TTK_Class: 12949 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12950 case TTK_Union: 12951 return NTK_NonUnion; 12952 case TTK_Enum: 12953 return NTK_NonEnum; 12954 } 12955 llvm_unreachable("invalid TTK"); 12956 } 12957 12958 /// \brief Determine whether a tag with a given kind is acceptable 12959 /// as a redeclaration of the given tag declaration. 12960 /// 12961 /// \returns true if the new tag kind is acceptable, false otherwise. 12962 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12963 TagTypeKind NewTag, bool isDefinition, 12964 SourceLocation NewTagLoc, 12965 const IdentifierInfo *Name) { 12966 // C++ [dcl.type.elab]p3: 12967 // The class-key or enum keyword present in the 12968 // elaborated-type-specifier shall agree in kind with the 12969 // declaration to which the name in the elaborated-type-specifier 12970 // refers. This rule also applies to the form of 12971 // elaborated-type-specifier that declares a class-name or 12972 // friend class since it can be construed as referring to the 12973 // definition of the class. Thus, in any 12974 // elaborated-type-specifier, the enum keyword shall be used to 12975 // refer to an enumeration (7.2), the union class-key shall be 12976 // used to refer to a union (clause 9), and either the class or 12977 // struct class-key shall be used to refer to a class (clause 9) 12978 // declared using the class or struct class-key. 12979 TagTypeKind OldTag = Previous->getTagKind(); 12980 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12981 if (OldTag == NewTag) 12982 return true; 12983 12984 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12985 // Warn about the struct/class tag mismatch. 12986 bool isTemplate = false; 12987 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12988 isTemplate = Record->getDescribedClassTemplate(); 12989 12990 if (inTemplateInstantiation()) { 12991 // In a template instantiation, do not offer fix-its for tag mismatches 12992 // since they usually mess up the template instead of fixing the problem. 12993 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12994 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12995 << getRedeclDiagFromTagKind(OldTag); 12996 return true; 12997 } 12998 12999 if (isDefinition) { 13000 // On definitions, check previous tags and issue a fix-it for each 13001 // one that doesn't match the current tag. 13002 if (Previous->getDefinition()) { 13003 // Don't suggest fix-its for redefinitions. 13004 return true; 13005 } 13006 13007 bool previousMismatch = false; 13008 for (auto I : Previous->redecls()) { 13009 if (I->getTagKind() != NewTag) { 13010 if (!previousMismatch) { 13011 previousMismatch = true; 13012 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13013 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13014 << getRedeclDiagFromTagKind(I->getTagKind()); 13015 } 13016 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13017 << getRedeclDiagFromTagKind(NewTag) 13018 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13019 TypeWithKeyword::getTagTypeKindName(NewTag)); 13020 } 13021 } 13022 return true; 13023 } 13024 13025 // Check for a previous definition. If current tag and definition 13026 // are same type, do nothing. If no definition, but disagree with 13027 // with previous tag type, give a warning, but no fix-it. 13028 const TagDecl *Redecl = Previous->getDefinition() ? 13029 Previous->getDefinition() : Previous; 13030 if (Redecl->getTagKind() == NewTag) { 13031 return true; 13032 } 13033 13034 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13035 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13036 << getRedeclDiagFromTagKind(OldTag); 13037 Diag(Redecl->getLocation(), diag::note_previous_use); 13038 13039 // If there is a previous definition, suggest a fix-it. 13040 if (Previous->getDefinition()) { 13041 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13042 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13043 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13044 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13045 } 13046 13047 return true; 13048 } 13049 return false; 13050 } 13051 13052 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13053 /// from an outer enclosing namespace or file scope inside a friend declaration. 13054 /// This should provide the commented out code in the following snippet: 13055 /// namespace N { 13056 /// struct X; 13057 /// namespace M { 13058 /// struct Y { friend struct /*N::*/ X; }; 13059 /// } 13060 /// } 13061 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13062 SourceLocation NameLoc) { 13063 // While the decl is in a namespace, do repeated lookup of that name and see 13064 // if we get the same namespace back. If we do not, continue until 13065 // translation unit scope, at which point we have a fully qualified NNS. 13066 SmallVector<IdentifierInfo *, 4> Namespaces; 13067 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13068 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13069 // This tag should be declared in a namespace, which can only be enclosed by 13070 // other namespaces. Bail if there's an anonymous namespace in the chain. 13071 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13072 if (!Namespace || Namespace->isAnonymousNamespace()) 13073 return FixItHint(); 13074 IdentifierInfo *II = Namespace->getIdentifier(); 13075 Namespaces.push_back(II); 13076 NamedDecl *Lookup = SemaRef.LookupSingleName( 13077 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13078 if (Lookup == Namespace) 13079 break; 13080 } 13081 13082 // Once we have all the namespaces, reverse them to go outermost first, and 13083 // build an NNS. 13084 SmallString<64> Insertion; 13085 llvm::raw_svector_ostream OS(Insertion); 13086 if (DC->isTranslationUnit()) 13087 OS << "::"; 13088 std::reverse(Namespaces.begin(), Namespaces.end()); 13089 for (auto *II : Namespaces) 13090 OS << II->getName() << "::"; 13091 return FixItHint::CreateInsertion(NameLoc, Insertion); 13092 } 13093 13094 /// \brief Determine whether a tag originally declared in context \p OldDC can 13095 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13096 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13097 /// using-declaration). 13098 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13099 DeclContext *NewDC) { 13100 OldDC = OldDC->getRedeclContext(); 13101 NewDC = NewDC->getRedeclContext(); 13102 13103 if (OldDC->Equals(NewDC)) 13104 return true; 13105 13106 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13107 // encloses the other). 13108 if (S.getLangOpts().MSVCCompat && 13109 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13110 return true; 13111 13112 return false; 13113 } 13114 13115 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13116 /// former case, Name will be non-null. In the later case, Name will be null. 13117 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13118 /// reference/declaration/definition of a tag. 13119 /// 13120 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13121 /// trailing-type-specifier) other than one in an alias-declaration. 13122 /// 13123 /// \param SkipBody If non-null, will be set to indicate if the caller should 13124 /// skip the definition of this tag and treat it as if it were a declaration. 13125 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13126 SourceLocation KWLoc, CXXScopeSpec &SS, 13127 IdentifierInfo *Name, SourceLocation NameLoc, 13128 AttributeList *Attr, AccessSpecifier AS, 13129 SourceLocation ModulePrivateLoc, 13130 MultiTemplateParamsArg TemplateParameterLists, 13131 bool &OwnedDecl, bool &IsDependent, 13132 SourceLocation ScopedEnumKWLoc, 13133 bool ScopedEnumUsesClassTag, 13134 TypeResult UnderlyingType, 13135 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13136 SkipBodyInfo *SkipBody) { 13137 // If this is not a definition, it must have a name. 13138 IdentifierInfo *OrigName = Name; 13139 assert((Name != nullptr || TUK == TUK_Definition) && 13140 "Nameless record must be a definition!"); 13141 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13142 13143 OwnedDecl = false; 13144 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13145 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13146 13147 // FIXME: Check member specializations more carefully. 13148 bool isMemberSpecialization = false; 13149 bool Invalid = false; 13150 13151 // We only need to do this matching if we have template parameters 13152 // or a scope specifier, which also conveniently avoids this work 13153 // for non-C++ cases. 13154 if (TemplateParameterLists.size() > 0 || 13155 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13156 if (TemplateParameterList *TemplateParams = 13157 MatchTemplateParametersToScopeSpecifier( 13158 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13159 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13160 if (Kind == TTK_Enum) { 13161 Diag(KWLoc, diag::err_enum_template); 13162 return nullptr; 13163 } 13164 13165 if (TemplateParams->size() > 0) { 13166 // This is a declaration or definition of a class template (which may 13167 // be a member of another template). 13168 13169 if (Invalid) 13170 return nullptr; 13171 13172 OwnedDecl = false; 13173 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13174 SS, Name, NameLoc, Attr, 13175 TemplateParams, AS, 13176 ModulePrivateLoc, 13177 /*FriendLoc*/SourceLocation(), 13178 TemplateParameterLists.size()-1, 13179 TemplateParameterLists.data(), 13180 SkipBody); 13181 return Result.get(); 13182 } else { 13183 // The "template<>" header is extraneous. 13184 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13185 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13186 isMemberSpecialization = true; 13187 } 13188 } 13189 } 13190 13191 // Figure out the underlying type if this a enum declaration. We need to do 13192 // this early, because it's needed to detect if this is an incompatible 13193 // redeclaration. 13194 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13195 bool EnumUnderlyingIsImplicit = false; 13196 13197 if (Kind == TTK_Enum) { 13198 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13199 // No underlying type explicitly specified, or we failed to parse the 13200 // type, default to int. 13201 EnumUnderlying = Context.IntTy.getTypePtr(); 13202 else if (UnderlyingType.get()) { 13203 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13204 // integral type; any cv-qualification is ignored. 13205 TypeSourceInfo *TI = nullptr; 13206 GetTypeFromParser(UnderlyingType.get(), &TI); 13207 EnumUnderlying = TI; 13208 13209 if (CheckEnumUnderlyingType(TI)) 13210 // Recover by falling back to int. 13211 EnumUnderlying = Context.IntTy.getTypePtr(); 13212 13213 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13214 UPPC_FixedUnderlyingType)) 13215 EnumUnderlying = Context.IntTy.getTypePtr(); 13216 13217 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13218 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13219 // Microsoft enums are always of int type. 13220 EnumUnderlying = Context.IntTy.getTypePtr(); 13221 EnumUnderlyingIsImplicit = true; 13222 } 13223 } 13224 } 13225 13226 DeclContext *SearchDC = CurContext; 13227 DeclContext *DC = CurContext; 13228 bool isStdBadAlloc = false; 13229 bool isStdAlignValT = false; 13230 13231 RedeclarationKind Redecl = ForRedeclaration; 13232 if (TUK == TUK_Friend || TUK == TUK_Reference) 13233 Redecl = NotForRedeclaration; 13234 13235 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13236 /// implemented asks for structural equivalence checking, the returned decl 13237 /// here is passed back to the parser, allowing the tag body to be parsed. 13238 auto createTagFromNewDecl = [&]() -> TagDecl * { 13239 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13240 // If there is an identifier, use the location of the identifier as the 13241 // location of the decl, otherwise use the location of the struct/union 13242 // keyword. 13243 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13244 TagDecl *New = nullptr; 13245 13246 if (Kind == TTK_Enum) { 13247 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13248 ScopedEnum, ScopedEnumUsesClassTag, 13249 !EnumUnderlying.isNull()); 13250 // If this is an undefined enum, bail. 13251 if (TUK != TUK_Definition && !Invalid) 13252 return nullptr; 13253 if (EnumUnderlying) { 13254 EnumDecl *ED = cast<EnumDecl>(New); 13255 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13256 ED->setIntegerTypeSourceInfo(TI); 13257 else 13258 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13259 ED->setPromotionType(ED->getIntegerType()); 13260 } 13261 } else { // struct/union 13262 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13263 nullptr); 13264 } 13265 13266 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13267 // Add alignment attributes if necessary; these attributes are checked 13268 // when the ASTContext lays out the structure. 13269 // 13270 // It is important for implementing the correct semantics that this 13271 // happen here (in ActOnTag). The #pragma pack stack is 13272 // maintained as a result of parser callbacks which can occur at 13273 // many points during the parsing of a struct declaration (because 13274 // the #pragma tokens are effectively skipped over during the 13275 // parsing of the struct). 13276 if (TUK == TUK_Definition) { 13277 AddAlignmentAttributesForRecord(RD); 13278 AddMsStructLayoutForRecord(RD); 13279 } 13280 } 13281 return New; 13282 }; 13283 13284 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13285 if (Name && SS.isNotEmpty()) { 13286 // We have a nested-name tag ('struct foo::bar'). 13287 13288 // Check for invalid 'foo::'. 13289 if (SS.isInvalid()) { 13290 Name = nullptr; 13291 goto CreateNewDecl; 13292 } 13293 13294 // If this is a friend or a reference to a class in a dependent 13295 // context, don't try to make a decl for it. 13296 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13297 DC = computeDeclContext(SS, false); 13298 if (!DC) { 13299 IsDependent = true; 13300 return nullptr; 13301 } 13302 } else { 13303 DC = computeDeclContext(SS, true); 13304 if (!DC) { 13305 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13306 << SS.getRange(); 13307 return nullptr; 13308 } 13309 } 13310 13311 if (RequireCompleteDeclContext(SS, DC)) 13312 return nullptr; 13313 13314 SearchDC = DC; 13315 // Look-up name inside 'foo::'. 13316 LookupQualifiedName(Previous, DC); 13317 13318 if (Previous.isAmbiguous()) 13319 return nullptr; 13320 13321 if (Previous.empty()) { 13322 // Name lookup did not find anything. However, if the 13323 // nested-name-specifier refers to the current instantiation, 13324 // and that current instantiation has any dependent base 13325 // classes, we might find something at instantiation time: treat 13326 // this as a dependent elaborated-type-specifier. 13327 // But this only makes any sense for reference-like lookups. 13328 if (Previous.wasNotFoundInCurrentInstantiation() && 13329 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13330 IsDependent = true; 13331 return nullptr; 13332 } 13333 13334 // A tag 'foo::bar' must already exist. 13335 Diag(NameLoc, diag::err_not_tag_in_scope) 13336 << Kind << Name << DC << SS.getRange(); 13337 Name = nullptr; 13338 Invalid = true; 13339 goto CreateNewDecl; 13340 } 13341 } else if (Name) { 13342 // C++14 [class.mem]p14: 13343 // If T is the name of a class, then each of the following shall have a 13344 // name different from T: 13345 // -- every member of class T that is itself a type 13346 if (TUK != TUK_Reference && TUK != TUK_Friend && 13347 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13348 return nullptr; 13349 13350 // If this is a named struct, check to see if there was a previous forward 13351 // declaration or definition. 13352 // FIXME: We're looking into outer scopes here, even when we 13353 // shouldn't be. Doing so can result in ambiguities that we 13354 // shouldn't be diagnosing. 13355 LookupName(Previous, S); 13356 13357 // When declaring or defining a tag, ignore ambiguities introduced 13358 // by types using'ed into this scope. 13359 if (Previous.isAmbiguous() && 13360 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13361 LookupResult::Filter F = Previous.makeFilter(); 13362 while (F.hasNext()) { 13363 NamedDecl *ND = F.next(); 13364 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13365 SearchDC->getRedeclContext())) 13366 F.erase(); 13367 } 13368 F.done(); 13369 } 13370 13371 // C++11 [namespace.memdef]p3: 13372 // If the name in a friend declaration is neither qualified nor 13373 // a template-id and the declaration is a function or an 13374 // elaborated-type-specifier, the lookup to determine whether 13375 // the entity has been previously declared shall not consider 13376 // any scopes outside the innermost enclosing namespace. 13377 // 13378 // MSVC doesn't implement the above rule for types, so a friend tag 13379 // declaration may be a redeclaration of a type declared in an enclosing 13380 // scope. They do implement this rule for friend functions. 13381 // 13382 // Does it matter that this should be by scope instead of by 13383 // semantic context? 13384 if (!Previous.empty() && TUK == TUK_Friend) { 13385 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13386 LookupResult::Filter F = Previous.makeFilter(); 13387 bool FriendSawTagOutsideEnclosingNamespace = false; 13388 while (F.hasNext()) { 13389 NamedDecl *ND = F.next(); 13390 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13391 if (DC->isFileContext() && 13392 !EnclosingNS->Encloses(ND->getDeclContext())) { 13393 if (getLangOpts().MSVCCompat) 13394 FriendSawTagOutsideEnclosingNamespace = true; 13395 else 13396 F.erase(); 13397 } 13398 } 13399 F.done(); 13400 13401 // Diagnose this MSVC extension in the easy case where lookup would have 13402 // unambiguously found something outside the enclosing namespace. 13403 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13404 NamedDecl *ND = Previous.getFoundDecl(); 13405 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13406 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13407 } 13408 } 13409 13410 // Note: there used to be some attempt at recovery here. 13411 if (Previous.isAmbiguous()) 13412 return nullptr; 13413 13414 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13415 // FIXME: This makes sure that we ignore the contexts associated 13416 // with C structs, unions, and enums when looking for a matching 13417 // tag declaration or definition. See the similar lookup tweak 13418 // in Sema::LookupName; is there a better way to deal with this? 13419 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13420 SearchDC = SearchDC->getParent(); 13421 } 13422 } 13423 13424 if (Previous.isSingleResult() && 13425 Previous.getFoundDecl()->isTemplateParameter()) { 13426 // Maybe we will complain about the shadowed template parameter. 13427 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13428 // Just pretend that we didn't see the previous declaration. 13429 Previous.clear(); 13430 } 13431 13432 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13433 DC->Equals(getStdNamespace())) { 13434 if (Name->isStr("bad_alloc")) { 13435 // This is a declaration of or a reference to "std::bad_alloc". 13436 isStdBadAlloc = true; 13437 13438 // If std::bad_alloc has been implicitly declared (but made invisible to 13439 // name lookup), fill in this implicit declaration as the previous 13440 // declaration, so that the declarations get chained appropriately. 13441 if (Previous.empty() && StdBadAlloc) 13442 Previous.addDecl(getStdBadAlloc()); 13443 } else if (Name->isStr("align_val_t")) { 13444 isStdAlignValT = true; 13445 if (Previous.empty() && StdAlignValT) 13446 Previous.addDecl(getStdAlignValT()); 13447 } 13448 } 13449 13450 // If we didn't find a previous declaration, and this is a reference 13451 // (or friend reference), move to the correct scope. In C++, we 13452 // also need to do a redeclaration lookup there, just in case 13453 // there's a shadow friend decl. 13454 if (Name && Previous.empty() && 13455 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13456 if (Invalid) goto CreateNewDecl; 13457 assert(SS.isEmpty()); 13458 13459 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13460 // C++ [basic.scope.pdecl]p5: 13461 // -- for an elaborated-type-specifier of the form 13462 // 13463 // class-key identifier 13464 // 13465 // if the elaborated-type-specifier is used in the 13466 // decl-specifier-seq or parameter-declaration-clause of a 13467 // function defined in namespace scope, the identifier is 13468 // declared as a class-name in the namespace that contains 13469 // the declaration; otherwise, except as a friend 13470 // declaration, the identifier is declared in the smallest 13471 // non-class, non-function-prototype scope that contains the 13472 // declaration. 13473 // 13474 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13475 // C structs and unions. 13476 // 13477 // It is an error in C++ to declare (rather than define) an enum 13478 // type, including via an elaborated type specifier. We'll 13479 // diagnose that later; for now, declare the enum in the same 13480 // scope as we would have picked for any other tag type. 13481 // 13482 // GNU C also supports this behavior as part of its incomplete 13483 // enum types extension, while GNU C++ does not. 13484 // 13485 // Find the context where we'll be declaring the tag. 13486 // FIXME: We would like to maintain the current DeclContext as the 13487 // lexical context, 13488 SearchDC = getTagInjectionContext(SearchDC); 13489 13490 // Find the scope where we'll be declaring the tag. 13491 S = getTagInjectionScope(S, getLangOpts()); 13492 } else { 13493 assert(TUK == TUK_Friend); 13494 // C++ [namespace.memdef]p3: 13495 // If a friend declaration in a non-local class first declares a 13496 // class or function, the friend class or function is a member of 13497 // the innermost enclosing namespace. 13498 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13499 } 13500 13501 // In C++, we need to do a redeclaration lookup to properly 13502 // diagnose some problems. 13503 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13504 // hidden declaration so that we don't get ambiguity errors when using a 13505 // type declared by an elaborated-type-specifier. In C that is not correct 13506 // and we should instead merge compatible types found by lookup. 13507 if (getLangOpts().CPlusPlus) { 13508 Previous.setRedeclarationKind(ForRedeclaration); 13509 LookupQualifiedName(Previous, SearchDC); 13510 } else { 13511 Previous.setRedeclarationKind(ForRedeclaration); 13512 LookupName(Previous, S); 13513 } 13514 } 13515 13516 // If we have a known previous declaration to use, then use it. 13517 if (Previous.empty() && SkipBody && SkipBody->Previous) 13518 Previous.addDecl(SkipBody->Previous); 13519 13520 if (!Previous.empty()) { 13521 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13522 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13523 13524 // It's okay to have a tag decl in the same scope as a typedef 13525 // which hides a tag decl in the same scope. Finding this 13526 // insanity with a redeclaration lookup can only actually happen 13527 // in C++. 13528 // 13529 // This is also okay for elaborated-type-specifiers, which is 13530 // technically forbidden by the current standard but which is 13531 // okay according to the likely resolution of an open issue; 13532 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13533 if (getLangOpts().CPlusPlus) { 13534 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13535 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13536 TagDecl *Tag = TT->getDecl(); 13537 if (Tag->getDeclName() == Name && 13538 Tag->getDeclContext()->getRedeclContext() 13539 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13540 PrevDecl = Tag; 13541 Previous.clear(); 13542 Previous.addDecl(Tag); 13543 Previous.resolveKind(); 13544 } 13545 } 13546 } 13547 } 13548 13549 // If this is a redeclaration of a using shadow declaration, it must 13550 // declare a tag in the same context. In MSVC mode, we allow a 13551 // redefinition if either context is within the other. 13552 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13553 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13554 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13555 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13556 !(OldTag && isAcceptableTagRedeclContext( 13557 *this, OldTag->getDeclContext(), SearchDC))) { 13558 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13559 Diag(Shadow->getTargetDecl()->getLocation(), 13560 diag::note_using_decl_target); 13561 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13562 << 0; 13563 // Recover by ignoring the old declaration. 13564 Previous.clear(); 13565 goto CreateNewDecl; 13566 } 13567 } 13568 13569 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13570 // If this is a use of a previous tag, or if the tag is already declared 13571 // in the same scope (so that the definition/declaration completes or 13572 // rementions the tag), reuse the decl. 13573 if (TUK == TUK_Reference || TUK == TUK_Friend || 13574 isDeclInScope(DirectPrevDecl, SearchDC, S, 13575 SS.isNotEmpty() || isMemberSpecialization)) { 13576 // Make sure that this wasn't declared as an enum and now used as a 13577 // struct or something similar. 13578 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13579 TUK == TUK_Definition, KWLoc, 13580 Name)) { 13581 bool SafeToContinue 13582 = (PrevTagDecl->getTagKind() != TTK_Enum && 13583 Kind != TTK_Enum); 13584 if (SafeToContinue) 13585 Diag(KWLoc, diag::err_use_with_wrong_tag) 13586 << Name 13587 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13588 PrevTagDecl->getKindName()); 13589 else 13590 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13591 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13592 13593 if (SafeToContinue) 13594 Kind = PrevTagDecl->getTagKind(); 13595 else { 13596 // Recover by making this an anonymous redefinition. 13597 Name = nullptr; 13598 Previous.clear(); 13599 Invalid = true; 13600 } 13601 } 13602 13603 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13604 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13605 13606 // If this is an elaborated-type-specifier for a scoped enumeration, 13607 // the 'class' keyword is not necessary and not permitted. 13608 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13609 if (ScopedEnum) 13610 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13611 << PrevEnum->isScoped() 13612 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13613 return PrevTagDecl; 13614 } 13615 13616 QualType EnumUnderlyingTy; 13617 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13618 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13619 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13620 EnumUnderlyingTy = QualType(T, 0); 13621 13622 // All conflicts with previous declarations are recovered by 13623 // returning the previous declaration, unless this is a definition, 13624 // in which case we want the caller to bail out. 13625 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13626 ScopedEnum, EnumUnderlyingTy, 13627 EnumUnderlyingIsImplicit, PrevEnum)) 13628 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13629 } 13630 13631 // C++11 [class.mem]p1: 13632 // A member shall not be declared twice in the member-specification, 13633 // except that a nested class or member class template can be declared 13634 // and then later defined. 13635 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13636 S->isDeclScope(PrevDecl)) { 13637 Diag(NameLoc, diag::ext_member_redeclared); 13638 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13639 } 13640 13641 if (!Invalid) { 13642 // If this is a use, just return the declaration we found, unless 13643 // we have attributes. 13644 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13645 if (Attr) { 13646 // FIXME: Diagnose these attributes. For now, we create a new 13647 // declaration to hold them. 13648 } else if (TUK == TUK_Reference && 13649 (PrevTagDecl->getFriendObjectKind() == 13650 Decl::FOK_Undeclared || 13651 PrevDecl->getOwningModule() != getCurrentModule()) && 13652 SS.isEmpty()) { 13653 // This declaration is a reference to an existing entity, but 13654 // has different visibility from that entity: it either makes 13655 // a friend visible or it makes a type visible in a new module. 13656 // In either case, create a new declaration. We only do this if 13657 // the declaration would have meant the same thing if no prior 13658 // declaration were found, that is, if it was found in the same 13659 // scope where we would have injected a declaration. 13660 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13661 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13662 return PrevTagDecl; 13663 // This is in the injected scope, create a new declaration in 13664 // that scope. 13665 S = getTagInjectionScope(S, getLangOpts()); 13666 } else { 13667 return PrevTagDecl; 13668 } 13669 } 13670 13671 // Diagnose attempts to redefine a tag. 13672 if (TUK == TUK_Definition) { 13673 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13674 // If we're defining a specialization and the previous definition 13675 // is from an implicit instantiation, don't emit an error 13676 // here; we'll catch this in the general case below. 13677 bool IsExplicitSpecializationAfterInstantiation = false; 13678 if (isMemberSpecialization) { 13679 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13680 IsExplicitSpecializationAfterInstantiation = 13681 RD->getTemplateSpecializationKind() != 13682 TSK_ExplicitSpecialization; 13683 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13684 IsExplicitSpecializationAfterInstantiation = 13685 ED->getTemplateSpecializationKind() != 13686 TSK_ExplicitSpecialization; 13687 } 13688 13689 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 13690 // not keep more that one definition around (merge them). However, 13691 // ensure the decl passes the structural compatibility check in 13692 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 13693 NamedDecl *Hidden = nullptr; 13694 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 13695 // There is a definition of this tag, but it is not visible. We 13696 // explicitly make use of C++'s one definition rule here, and 13697 // assume that this definition is identical to the hidden one 13698 // we already have. Make the existing definition visible and 13699 // use it in place of this one. 13700 if (!getLangOpts().CPlusPlus) { 13701 // Postpone making the old definition visible until after we 13702 // complete parsing the new one and do the structural 13703 // comparison. 13704 SkipBody->CheckSameAsPrevious = true; 13705 SkipBody->New = createTagFromNewDecl(); 13706 SkipBody->Previous = Hidden; 13707 } else { 13708 SkipBody->ShouldSkip = true; 13709 makeMergedDefinitionVisible(Hidden); 13710 } 13711 return Def; 13712 } else if (!IsExplicitSpecializationAfterInstantiation) { 13713 // A redeclaration in function prototype scope in C isn't 13714 // visible elsewhere, so merely issue a warning. 13715 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13716 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13717 else 13718 Diag(NameLoc, diag::err_redefinition) << Name; 13719 notePreviousDefinition(Def, 13720 NameLoc.isValid() ? NameLoc : KWLoc); 13721 // If this is a redefinition, recover by making this 13722 // struct be anonymous, which will make any later 13723 // references get the previous definition. 13724 Name = nullptr; 13725 Previous.clear(); 13726 Invalid = true; 13727 } 13728 } else { 13729 // If the type is currently being defined, complain 13730 // about a nested redefinition. 13731 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13732 if (TD->isBeingDefined()) { 13733 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13734 Diag(PrevTagDecl->getLocation(), 13735 diag::note_previous_definition); 13736 Name = nullptr; 13737 Previous.clear(); 13738 Invalid = true; 13739 } 13740 } 13741 13742 // Okay, this is definition of a previously declared or referenced 13743 // tag. We're going to create a new Decl for it. 13744 } 13745 13746 // Okay, we're going to make a redeclaration. If this is some kind 13747 // of reference, make sure we build the redeclaration in the same DC 13748 // as the original, and ignore the current access specifier. 13749 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13750 SearchDC = PrevTagDecl->getDeclContext(); 13751 AS = AS_none; 13752 } 13753 } 13754 // If we get here we have (another) forward declaration or we 13755 // have a definition. Just create a new decl. 13756 13757 } else { 13758 // If we get here, this is a definition of a new tag type in a nested 13759 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13760 // new decl/type. We set PrevDecl to NULL so that the entities 13761 // have distinct types. 13762 Previous.clear(); 13763 } 13764 // If we get here, we're going to create a new Decl. If PrevDecl 13765 // is non-NULL, it's a definition of the tag declared by 13766 // PrevDecl. If it's NULL, we have a new definition. 13767 13768 // Otherwise, PrevDecl is not a tag, but was found with tag 13769 // lookup. This is only actually possible in C++, where a few 13770 // things like templates still live in the tag namespace. 13771 } else { 13772 // Use a better diagnostic if an elaborated-type-specifier 13773 // found the wrong kind of type on the first 13774 // (non-redeclaration) lookup. 13775 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13776 !Previous.isForRedeclaration()) { 13777 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13778 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13779 << Kind; 13780 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13781 Invalid = true; 13782 13783 // Otherwise, only diagnose if the declaration is in scope. 13784 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13785 SS.isNotEmpty() || isMemberSpecialization)) { 13786 // do nothing 13787 13788 // Diagnose implicit declarations introduced by elaborated types. 13789 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13790 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13791 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13792 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13793 Invalid = true; 13794 13795 // Otherwise it's a declaration. Call out a particularly common 13796 // case here. 13797 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13798 unsigned Kind = 0; 13799 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13800 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13801 << Name << Kind << TND->getUnderlyingType(); 13802 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13803 Invalid = true; 13804 13805 // Otherwise, diagnose. 13806 } else { 13807 // The tag name clashes with something else in the target scope, 13808 // issue an error and recover by making this tag be anonymous. 13809 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13810 notePreviousDefinition(PrevDecl, NameLoc); 13811 Name = nullptr; 13812 Invalid = true; 13813 } 13814 13815 // The existing declaration isn't relevant to us; we're in a 13816 // new scope, so clear out the previous declaration. 13817 Previous.clear(); 13818 } 13819 } 13820 13821 CreateNewDecl: 13822 13823 TagDecl *PrevDecl = nullptr; 13824 if (Previous.isSingleResult()) 13825 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13826 13827 // If there is an identifier, use the location of the identifier as the 13828 // location of the decl, otherwise use the location of the struct/union 13829 // keyword. 13830 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13831 13832 // Otherwise, create a new declaration. If there is a previous 13833 // declaration of the same entity, the two will be linked via 13834 // PrevDecl. 13835 TagDecl *New; 13836 13837 bool IsForwardReference = false; 13838 if (Kind == TTK_Enum) { 13839 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13840 // enum X { A, B, C } D; D should chain to X. 13841 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13842 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13843 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13844 13845 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13846 StdAlignValT = cast<EnumDecl>(New); 13847 13848 // If this is an undefined enum, warn. 13849 if (TUK != TUK_Definition && !Invalid) { 13850 TagDecl *Def; 13851 if (!EnumUnderlyingIsImplicit && 13852 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13853 cast<EnumDecl>(New)->isFixed()) { 13854 // C++0x: 7.2p2: opaque-enum-declaration. 13855 // Conflicts are diagnosed above. Do nothing. 13856 } 13857 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13858 Diag(Loc, diag::ext_forward_ref_enum_def) 13859 << New; 13860 Diag(Def->getLocation(), diag::note_previous_definition); 13861 } else { 13862 unsigned DiagID = diag::ext_forward_ref_enum; 13863 if (getLangOpts().MSVCCompat) 13864 DiagID = diag::ext_ms_forward_ref_enum; 13865 else if (getLangOpts().CPlusPlus) 13866 DiagID = diag::err_forward_ref_enum; 13867 Diag(Loc, DiagID); 13868 13869 // If this is a forward-declared reference to an enumeration, make a 13870 // note of it; we won't actually be introducing the declaration into 13871 // the declaration context. 13872 if (TUK == TUK_Reference) 13873 IsForwardReference = true; 13874 } 13875 } 13876 13877 if (EnumUnderlying) { 13878 EnumDecl *ED = cast<EnumDecl>(New); 13879 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13880 ED->setIntegerTypeSourceInfo(TI); 13881 else 13882 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13883 ED->setPromotionType(ED->getIntegerType()); 13884 } 13885 } else { 13886 // struct/union/class 13887 13888 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13889 // struct X { int A; } D; D should chain to X. 13890 if (getLangOpts().CPlusPlus) { 13891 // FIXME: Look for a way to use RecordDecl for simple structs. 13892 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13893 cast_or_null<CXXRecordDecl>(PrevDecl)); 13894 13895 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13896 StdBadAlloc = cast<CXXRecordDecl>(New); 13897 } else 13898 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13899 cast_or_null<RecordDecl>(PrevDecl)); 13900 } 13901 13902 // C++11 [dcl.type]p3: 13903 // A type-specifier-seq shall not define a class or enumeration [...]. 13904 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 13905 TUK == TUK_Definition) { 13906 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13907 << Context.getTagDeclType(New); 13908 Invalid = true; 13909 } 13910 13911 // Maybe add qualifier info. 13912 if (SS.isNotEmpty()) { 13913 if (SS.isSet()) { 13914 // If this is either a declaration or a definition, check the 13915 // nested-name-specifier against the current context. We don't do this 13916 // for explicit specializations, because they have similar checking 13917 // (with more specific diagnostics) in the call to 13918 // CheckMemberSpecialization, below. 13919 if (!isMemberSpecialization && 13920 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13921 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13922 Invalid = true; 13923 13924 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13925 if (TemplateParameterLists.size() > 0) { 13926 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13927 } 13928 } 13929 else 13930 Invalid = true; 13931 } 13932 13933 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13934 // Add alignment attributes if necessary; these attributes are checked when 13935 // the ASTContext lays out the structure. 13936 // 13937 // It is important for implementing the correct semantics that this 13938 // happen here (in ActOnTag). The #pragma pack stack is 13939 // maintained as a result of parser callbacks which can occur at 13940 // many points during the parsing of a struct declaration (because 13941 // the #pragma tokens are effectively skipped over during the 13942 // parsing of the struct). 13943 if (TUK == TUK_Definition) { 13944 AddAlignmentAttributesForRecord(RD); 13945 AddMsStructLayoutForRecord(RD); 13946 } 13947 } 13948 13949 if (ModulePrivateLoc.isValid()) { 13950 if (isMemberSpecialization) 13951 Diag(New->getLocation(), diag::err_module_private_specialization) 13952 << 2 13953 << FixItHint::CreateRemoval(ModulePrivateLoc); 13954 // __module_private__ does not apply to local classes. However, we only 13955 // diagnose this as an error when the declaration specifiers are 13956 // freestanding. Here, we just ignore the __module_private__. 13957 else if (!SearchDC->isFunctionOrMethod()) 13958 New->setModulePrivate(); 13959 } 13960 13961 // If this is a specialization of a member class (of a class template), 13962 // check the specialization. 13963 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13964 Invalid = true; 13965 13966 // If we're declaring or defining a tag in function prototype scope in C, 13967 // note that this type can only be used within the function and add it to 13968 // the list of decls to inject into the function definition scope. 13969 if ((Name || Kind == TTK_Enum) && 13970 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13971 if (getLangOpts().CPlusPlus) { 13972 // C++ [dcl.fct]p6: 13973 // Types shall not be defined in return or parameter types. 13974 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13975 Diag(Loc, diag::err_type_defined_in_param_type) 13976 << Name; 13977 Invalid = true; 13978 } 13979 } else if (!PrevDecl) { 13980 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13981 } 13982 } 13983 13984 if (Invalid) 13985 New->setInvalidDecl(); 13986 13987 // Set the lexical context. If the tag has a C++ scope specifier, the 13988 // lexical context will be different from the semantic context. 13989 New->setLexicalDeclContext(CurContext); 13990 13991 // Mark this as a friend decl if applicable. 13992 // In Microsoft mode, a friend declaration also acts as a forward 13993 // declaration so we always pass true to setObjectOfFriendDecl to make 13994 // the tag name visible. 13995 if (TUK == TUK_Friend) 13996 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13997 13998 // Set the access specifier. 13999 if (!Invalid && SearchDC->isRecord()) 14000 SetMemberAccessSpecifier(New, PrevDecl, AS); 14001 14002 if (TUK == TUK_Definition) 14003 New->startDefinition(); 14004 14005 if (Attr) 14006 ProcessDeclAttributeList(S, New, Attr); 14007 AddPragmaAttributes(S, New); 14008 14009 // If this has an identifier, add it to the scope stack. 14010 if (TUK == TUK_Friend) { 14011 // We might be replacing an existing declaration in the lookup tables; 14012 // if so, borrow its access specifier. 14013 if (PrevDecl) 14014 New->setAccess(PrevDecl->getAccess()); 14015 14016 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14017 DC->makeDeclVisibleInContext(New); 14018 if (Name) // can be null along some error paths 14019 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14020 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14021 } else if (Name) { 14022 S = getNonFieldDeclScope(S); 14023 PushOnScopeChains(New, S, !IsForwardReference); 14024 if (IsForwardReference) 14025 SearchDC->makeDeclVisibleInContext(New); 14026 } else { 14027 CurContext->addDecl(New); 14028 } 14029 14030 // If this is the C FILE type, notify the AST context. 14031 if (IdentifierInfo *II = New->getIdentifier()) 14032 if (!New->isInvalidDecl() && 14033 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14034 II->isStr("FILE")) 14035 Context.setFILEDecl(New); 14036 14037 if (PrevDecl) 14038 mergeDeclAttributes(New, PrevDecl); 14039 14040 // If there's a #pragma GCC visibility in scope, set the visibility of this 14041 // record. 14042 AddPushedVisibilityAttribute(New); 14043 14044 if (isMemberSpecialization && !New->isInvalidDecl()) 14045 CompleteMemberSpecialization(New, Previous); 14046 14047 OwnedDecl = true; 14048 // In C++, don't return an invalid declaration. We can't recover well from 14049 // the cases where we make the type anonymous. 14050 if (Invalid && getLangOpts().CPlusPlus) { 14051 if (New->isBeingDefined()) 14052 if (auto RD = dyn_cast<RecordDecl>(New)) 14053 RD->completeDefinition(); 14054 return nullptr; 14055 } else { 14056 return New; 14057 } 14058 } 14059 14060 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14061 AdjustDeclIfTemplate(TagD); 14062 TagDecl *Tag = cast<TagDecl>(TagD); 14063 14064 // Enter the tag context. 14065 PushDeclContext(S, Tag); 14066 14067 ActOnDocumentableDecl(TagD); 14068 14069 // If there's a #pragma GCC visibility in scope, set the visibility of this 14070 // record. 14071 AddPushedVisibilityAttribute(Tag); 14072 } 14073 14074 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14075 SkipBodyInfo &SkipBody) { 14076 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14077 return false; 14078 14079 // Make the previous decl visible. 14080 makeMergedDefinitionVisible(SkipBody.Previous); 14081 return true; 14082 } 14083 14084 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14085 assert(isa<ObjCContainerDecl>(IDecl) && 14086 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14087 DeclContext *OCD = cast<DeclContext>(IDecl); 14088 assert(getContainingDC(OCD) == CurContext && 14089 "The next DeclContext should be lexically contained in the current one."); 14090 CurContext = OCD; 14091 return IDecl; 14092 } 14093 14094 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14095 SourceLocation FinalLoc, 14096 bool IsFinalSpelledSealed, 14097 SourceLocation LBraceLoc) { 14098 AdjustDeclIfTemplate(TagD); 14099 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14100 14101 FieldCollector->StartClass(); 14102 14103 if (!Record->getIdentifier()) 14104 return; 14105 14106 if (FinalLoc.isValid()) 14107 Record->addAttr(new (Context) 14108 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14109 14110 // C++ [class]p2: 14111 // [...] The class-name is also inserted into the scope of the 14112 // class itself; this is known as the injected-class-name. For 14113 // purposes of access checking, the injected-class-name is treated 14114 // as if it were a public member name. 14115 CXXRecordDecl *InjectedClassName 14116 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14117 Record->getLocStart(), Record->getLocation(), 14118 Record->getIdentifier(), 14119 /*PrevDecl=*/nullptr, 14120 /*DelayTypeCreation=*/true); 14121 Context.getTypeDeclType(InjectedClassName, Record); 14122 InjectedClassName->setImplicit(); 14123 InjectedClassName->setAccess(AS_public); 14124 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14125 InjectedClassName->setDescribedClassTemplate(Template); 14126 PushOnScopeChains(InjectedClassName, S); 14127 assert(InjectedClassName->isInjectedClassName() && 14128 "Broken injected-class-name"); 14129 } 14130 14131 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14132 SourceRange BraceRange) { 14133 AdjustDeclIfTemplate(TagD); 14134 TagDecl *Tag = cast<TagDecl>(TagD); 14135 Tag->setBraceRange(BraceRange); 14136 14137 // Make sure we "complete" the definition even it is invalid. 14138 if (Tag->isBeingDefined()) { 14139 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14140 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14141 RD->completeDefinition(); 14142 } 14143 14144 if (isa<CXXRecordDecl>(Tag)) { 14145 FieldCollector->FinishClass(); 14146 } 14147 14148 // Exit this scope of this tag's definition. 14149 PopDeclContext(); 14150 14151 if (getCurLexicalContext()->isObjCContainer() && 14152 Tag->getDeclContext()->isFileContext()) 14153 Tag->setTopLevelDeclInObjCContainer(); 14154 14155 // Notify the consumer that we've defined a tag. 14156 if (!Tag->isInvalidDecl()) 14157 Consumer.HandleTagDeclDefinition(Tag); 14158 } 14159 14160 void Sema::ActOnObjCContainerFinishDefinition() { 14161 // Exit this scope of this interface definition. 14162 PopDeclContext(); 14163 } 14164 14165 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14166 assert(DC == CurContext && "Mismatch of container contexts"); 14167 OriginalLexicalContext = DC; 14168 ActOnObjCContainerFinishDefinition(); 14169 } 14170 14171 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14172 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14173 OriginalLexicalContext = nullptr; 14174 } 14175 14176 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14177 AdjustDeclIfTemplate(TagD); 14178 TagDecl *Tag = cast<TagDecl>(TagD); 14179 Tag->setInvalidDecl(); 14180 14181 // Make sure we "complete" the definition even it is invalid. 14182 if (Tag->isBeingDefined()) { 14183 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14184 RD->completeDefinition(); 14185 } 14186 14187 // We're undoing ActOnTagStartDefinition here, not 14188 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14189 // the FieldCollector. 14190 14191 PopDeclContext(); 14192 } 14193 14194 // Note that FieldName may be null for anonymous bitfields. 14195 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14196 IdentifierInfo *FieldName, 14197 QualType FieldTy, bool IsMsStruct, 14198 Expr *BitWidth, bool *ZeroWidth) { 14199 // Default to true; that shouldn't confuse checks for emptiness 14200 if (ZeroWidth) 14201 *ZeroWidth = true; 14202 14203 // C99 6.7.2.1p4 - verify the field type. 14204 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14205 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14206 // Handle incomplete types with specific error. 14207 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14208 return ExprError(); 14209 if (FieldName) 14210 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14211 << FieldName << FieldTy << BitWidth->getSourceRange(); 14212 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14213 << FieldTy << BitWidth->getSourceRange(); 14214 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14215 UPPC_BitFieldWidth)) 14216 return ExprError(); 14217 14218 // If the bit-width is type- or value-dependent, don't try to check 14219 // it now. 14220 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14221 return BitWidth; 14222 14223 llvm::APSInt Value; 14224 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14225 if (ICE.isInvalid()) 14226 return ICE; 14227 BitWidth = ICE.get(); 14228 14229 if (Value != 0 && ZeroWidth) 14230 *ZeroWidth = false; 14231 14232 // Zero-width bitfield is ok for anonymous field. 14233 if (Value == 0 && FieldName) 14234 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14235 14236 if (Value.isSigned() && Value.isNegative()) { 14237 if (FieldName) 14238 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14239 << FieldName << Value.toString(10); 14240 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14241 << Value.toString(10); 14242 } 14243 14244 if (!FieldTy->isDependentType()) { 14245 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14246 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14247 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14248 14249 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14250 // ABI. 14251 bool CStdConstraintViolation = 14252 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14253 bool MSBitfieldViolation = 14254 Value.ugt(TypeStorageSize) && 14255 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14256 if (CStdConstraintViolation || MSBitfieldViolation) { 14257 unsigned DiagWidth = 14258 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14259 if (FieldName) 14260 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14261 << FieldName << (unsigned)Value.getZExtValue() 14262 << !CStdConstraintViolation << DiagWidth; 14263 14264 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14265 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14266 << DiagWidth; 14267 } 14268 14269 // Warn on types where the user might conceivably expect to get all 14270 // specified bits as value bits: that's all integral types other than 14271 // 'bool'. 14272 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14273 if (FieldName) 14274 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14275 << FieldName << (unsigned)Value.getZExtValue() 14276 << (unsigned)TypeWidth; 14277 else 14278 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14279 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14280 } 14281 } 14282 14283 return BitWidth; 14284 } 14285 14286 /// ActOnField - Each field of a C struct/union is passed into this in order 14287 /// to create a FieldDecl object for it. 14288 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14289 Declarator &D, Expr *BitfieldWidth) { 14290 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14291 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14292 /*InitStyle=*/ICIS_NoInit, AS_public); 14293 return Res; 14294 } 14295 14296 /// HandleField - Analyze a field of a C struct or a C++ data member. 14297 /// 14298 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14299 SourceLocation DeclStart, 14300 Declarator &D, Expr *BitWidth, 14301 InClassInitStyle InitStyle, 14302 AccessSpecifier AS) { 14303 if (D.isDecompositionDeclarator()) { 14304 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14305 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14306 << Decomp.getSourceRange(); 14307 return nullptr; 14308 } 14309 14310 IdentifierInfo *II = D.getIdentifier(); 14311 SourceLocation Loc = DeclStart; 14312 if (II) Loc = D.getIdentifierLoc(); 14313 14314 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14315 QualType T = TInfo->getType(); 14316 if (getLangOpts().CPlusPlus) { 14317 CheckExtraCXXDefaultArguments(D); 14318 14319 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14320 UPPC_DataMemberType)) { 14321 D.setInvalidType(); 14322 T = Context.IntTy; 14323 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14324 } 14325 } 14326 14327 // TR 18037 does not allow fields to be declared with address spaces. 14328 if (T.getQualifiers().hasAddressSpace()) { 14329 Diag(Loc, diag::err_field_with_address_space); 14330 D.setInvalidType(); 14331 } 14332 14333 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14334 // used as structure or union field: image, sampler, event or block types. 14335 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14336 T->isSamplerT() || T->isBlockPointerType())) { 14337 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14338 D.setInvalidType(); 14339 } 14340 14341 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14342 14343 if (D.getDeclSpec().isInlineSpecified()) 14344 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14345 << getLangOpts().CPlusPlus1z; 14346 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14347 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14348 diag::err_invalid_thread) 14349 << DeclSpec::getSpecifierName(TSCS); 14350 14351 // Check to see if this name was declared as a member previously 14352 NamedDecl *PrevDecl = nullptr; 14353 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14354 LookupName(Previous, S); 14355 switch (Previous.getResultKind()) { 14356 case LookupResult::Found: 14357 case LookupResult::FoundUnresolvedValue: 14358 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14359 break; 14360 14361 case LookupResult::FoundOverloaded: 14362 PrevDecl = Previous.getRepresentativeDecl(); 14363 break; 14364 14365 case LookupResult::NotFound: 14366 case LookupResult::NotFoundInCurrentInstantiation: 14367 case LookupResult::Ambiguous: 14368 break; 14369 } 14370 Previous.suppressDiagnostics(); 14371 14372 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14373 // Maybe we will complain about the shadowed template parameter. 14374 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14375 // Just pretend that we didn't see the previous declaration. 14376 PrevDecl = nullptr; 14377 } 14378 14379 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14380 PrevDecl = nullptr; 14381 14382 bool Mutable 14383 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14384 SourceLocation TSSL = D.getLocStart(); 14385 FieldDecl *NewFD 14386 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14387 TSSL, AS, PrevDecl, &D); 14388 14389 if (NewFD->isInvalidDecl()) 14390 Record->setInvalidDecl(); 14391 14392 if (D.getDeclSpec().isModulePrivateSpecified()) 14393 NewFD->setModulePrivate(); 14394 14395 if (NewFD->isInvalidDecl() && PrevDecl) { 14396 // Don't introduce NewFD into scope; there's already something 14397 // with the same name in the same scope. 14398 } else if (II) { 14399 PushOnScopeChains(NewFD, S); 14400 } else 14401 Record->addDecl(NewFD); 14402 14403 return NewFD; 14404 } 14405 14406 /// \brief Build a new FieldDecl and check its well-formedness. 14407 /// 14408 /// This routine builds a new FieldDecl given the fields name, type, 14409 /// record, etc. \p PrevDecl should refer to any previous declaration 14410 /// with the same name and in the same scope as the field to be 14411 /// created. 14412 /// 14413 /// \returns a new FieldDecl. 14414 /// 14415 /// \todo The Declarator argument is a hack. It will be removed once 14416 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14417 TypeSourceInfo *TInfo, 14418 RecordDecl *Record, SourceLocation Loc, 14419 bool Mutable, Expr *BitWidth, 14420 InClassInitStyle InitStyle, 14421 SourceLocation TSSL, 14422 AccessSpecifier AS, NamedDecl *PrevDecl, 14423 Declarator *D) { 14424 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14425 bool InvalidDecl = false; 14426 if (D) InvalidDecl = D->isInvalidType(); 14427 14428 // If we receive a broken type, recover by assuming 'int' and 14429 // marking this declaration as invalid. 14430 if (T.isNull()) { 14431 InvalidDecl = true; 14432 T = Context.IntTy; 14433 } 14434 14435 QualType EltTy = Context.getBaseElementType(T); 14436 if (!EltTy->isDependentType()) { 14437 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14438 // Fields of incomplete type force their record to be invalid. 14439 Record->setInvalidDecl(); 14440 InvalidDecl = true; 14441 } else { 14442 NamedDecl *Def; 14443 EltTy->isIncompleteType(&Def); 14444 if (Def && Def->isInvalidDecl()) { 14445 Record->setInvalidDecl(); 14446 InvalidDecl = true; 14447 } 14448 } 14449 } 14450 14451 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14452 if (BitWidth && getLangOpts().OpenCL) { 14453 Diag(Loc, diag::err_opencl_bitfields); 14454 InvalidDecl = true; 14455 } 14456 14457 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14458 // than a variably modified type. 14459 if (!InvalidDecl && T->isVariablyModifiedType()) { 14460 bool SizeIsNegative; 14461 llvm::APSInt Oversized; 14462 14463 TypeSourceInfo *FixedTInfo = 14464 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14465 SizeIsNegative, 14466 Oversized); 14467 if (FixedTInfo) { 14468 Diag(Loc, diag::warn_illegal_constant_array_size); 14469 TInfo = FixedTInfo; 14470 T = FixedTInfo->getType(); 14471 } else { 14472 if (SizeIsNegative) 14473 Diag(Loc, diag::err_typecheck_negative_array_size); 14474 else if (Oversized.getBoolValue()) 14475 Diag(Loc, diag::err_array_too_large) 14476 << Oversized.toString(10); 14477 else 14478 Diag(Loc, diag::err_typecheck_field_variable_size); 14479 InvalidDecl = true; 14480 } 14481 } 14482 14483 // Fields can not have abstract class types 14484 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14485 diag::err_abstract_type_in_decl, 14486 AbstractFieldType)) 14487 InvalidDecl = true; 14488 14489 bool ZeroWidth = false; 14490 if (InvalidDecl) 14491 BitWidth = nullptr; 14492 // If this is declared as a bit-field, check the bit-field. 14493 if (BitWidth) { 14494 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14495 &ZeroWidth).get(); 14496 if (!BitWidth) { 14497 InvalidDecl = true; 14498 BitWidth = nullptr; 14499 ZeroWidth = false; 14500 } 14501 } 14502 14503 // Check that 'mutable' is consistent with the type of the declaration. 14504 if (!InvalidDecl && Mutable) { 14505 unsigned DiagID = 0; 14506 if (T->isReferenceType()) 14507 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14508 : diag::err_mutable_reference; 14509 else if (T.isConstQualified()) 14510 DiagID = diag::err_mutable_const; 14511 14512 if (DiagID) { 14513 SourceLocation ErrLoc = Loc; 14514 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14515 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14516 Diag(ErrLoc, DiagID); 14517 if (DiagID != diag::ext_mutable_reference) { 14518 Mutable = false; 14519 InvalidDecl = true; 14520 } 14521 } 14522 } 14523 14524 // C++11 [class.union]p8 (DR1460): 14525 // At most one variant member of a union may have a 14526 // brace-or-equal-initializer. 14527 if (InitStyle != ICIS_NoInit) 14528 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14529 14530 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14531 BitWidth, Mutable, InitStyle); 14532 if (InvalidDecl) 14533 NewFD->setInvalidDecl(); 14534 14535 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14536 Diag(Loc, diag::err_duplicate_member) << II; 14537 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14538 NewFD->setInvalidDecl(); 14539 } 14540 14541 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14542 if (Record->isUnion()) { 14543 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14544 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14545 if (RDecl->getDefinition()) { 14546 // C++ [class.union]p1: An object of a class with a non-trivial 14547 // constructor, a non-trivial copy constructor, a non-trivial 14548 // destructor, or a non-trivial copy assignment operator 14549 // cannot be a member of a union, nor can an array of such 14550 // objects. 14551 if (CheckNontrivialField(NewFD)) 14552 NewFD->setInvalidDecl(); 14553 } 14554 } 14555 14556 // C++ [class.union]p1: If a union contains a member of reference type, 14557 // the program is ill-formed, except when compiling with MSVC extensions 14558 // enabled. 14559 if (EltTy->isReferenceType()) { 14560 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14561 diag::ext_union_member_of_reference_type : 14562 diag::err_union_member_of_reference_type) 14563 << NewFD->getDeclName() << EltTy; 14564 if (!getLangOpts().MicrosoftExt) 14565 NewFD->setInvalidDecl(); 14566 } 14567 } 14568 } 14569 14570 // FIXME: We need to pass in the attributes given an AST 14571 // representation, not a parser representation. 14572 if (D) { 14573 // FIXME: The current scope is almost... but not entirely... correct here. 14574 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14575 14576 if (NewFD->hasAttrs()) 14577 CheckAlignasUnderalignment(NewFD); 14578 } 14579 14580 // In auto-retain/release, infer strong retension for fields of 14581 // retainable type. 14582 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14583 NewFD->setInvalidDecl(); 14584 14585 if (T.isObjCGCWeak()) 14586 Diag(Loc, diag::warn_attribute_weak_on_field); 14587 14588 NewFD->setAccess(AS); 14589 return NewFD; 14590 } 14591 14592 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14593 assert(FD); 14594 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14595 14596 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14597 return false; 14598 14599 QualType EltTy = Context.getBaseElementType(FD->getType()); 14600 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14601 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14602 if (RDecl->getDefinition()) { 14603 // We check for copy constructors before constructors 14604 // because otherwise we'll never get complaints about 14605 // copy constructors. 14606 14607 CXXSpecialMember member = CXXInvalid; 14608 // We're required to check for any non-trivial constructors. Since the 14609 // implicit default constructor is suppressed if there are any 14610 // user-declared constructors, we just need to check that there is a 14611 // trivial default constructor and a trivial copy constructor. (We don't 14612 // worry about move constructors here, since this is a C++98 check.) 14613 if (RDecl->hasNonTrivialCopyConstructor()) 14614 member = CXXCopyConstructor; 14615 else if (!RDecl->hasTrivialDefaultConstructor()) 14616 member = CXXDefaultConstructor; 14617 else if (RDecl->hasNonTrivialCopyAssignment()) 14618 member = CXXCopyAssignment; 14619 else if (RDecl->hasNonTrivialDestructor()) 14620 member = CXXDestructor; 14621 14622 if (member != CXXInvalid) { 14623 if (!getLangOpts().CPlusPlus11 && 14624 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14625 // Objective-C++ ARC: it is an error to have a non-trivial field of 14626 // a union. However, system headers in Objective-C programs 14627 // occasionally have Objective-C lifetime objects within unions, 14628 // and rather than cause the program to fail, we make those 14629 // members unavailable. 14630 SourceLocation Loc = FD->getLocation(); 14631 if (getSourceManager().isInSystemHeader(Loc)) { 14632 if (!FD->hasAttr<UnavailableAttr>()) 14633 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14634 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14635 return false; 14636 } 14637 } 14638 14639 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14640 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14641 diag::err_illegal_union_or_anon_struct_member) 14642 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14643 DiagnoseNontrivial(RDecl, member); 14644 return !getLangOpts().CPlusPlus11; 14645 } 14646 } 14647 } 14648 14649 return false; 14650 } 14651 14652 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14653 /// AST enum value. 14654 static ObjCIvarDecl::AccessControl 14655 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14656 switch (ivarVisibility) { 14657 default: llvm_unreachable("Unknown visitibility kind"); 14658 case tok::objc_private: return ObjCIvarDecl::Private; 14659 case tok::objc_public: return ObjCIvarDecl::Public; 14660 case tok::objc_protected: return ObjCIvarDecl::Protected; 14661 case tok::objc_package: return ObjCIvarDecl::Package; 14662 } 14663 } 14664 14665 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14666 /// in order to create an IvarDecl object for it. 14667 Decl *Sema::ActOnIvar(Scope *S, 14668 SourceLocation DeclStart, 14669 Declarator &D, Expr *BitfieldWidth, 14670 tok::ObjCKeywordKind Visibility) { 14671 14672 IdentifierInfo *II = D.getIdentifier(); 14673 Expr *BitWidth = (Expr*)BitfieldWidth; 14674 SourceLocation Loc = DeclStart; 14675 if (II) Loc = D.getIdentifierLoc(); 14676 14677 // FIXME: Unnamed fields can be handled in various different ways, for 14678 // example, unnamed unions inject all members into the struct namespace! 14679 14680 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14681 QualType T = TInfo->getType(); 14682 14683 if (BitWidth) { 14684 // 6.7.2.1p3, 6.7.2.1p4 14685 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14686 if (!BitWidth) 14687 D.setInvalidType(); 14688 } else { 14689 // Not a bitfield. 14690 14691 // validate II. 14692 14693 } 14694 if (T->isReferenceType()) { 14695 Diag(Loc, diag::err_ivar_reference_type); 14696 D.setInvalidType(); 14697 } 14698 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14699 // than a variably modified type. 14700 else if (T->isVariablyModifiedType()) { 14701 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14702 D.setInvalidType(); 14703 } 14704 14705 // Get the visibility (access control) for this ivar. 14706 ObjCIvarDecl::AccessControl ac = 14707 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14708 : ObjCIvarDecl::None; 14709 // Must set ivar's DeclContext to its enclosing interface. 14710 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14711 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14712 return nullptr; 14713 ObjCContainerDecl *EnclosingContext; 14714 if (ObjCImplementationDecl *IMPDecl = 14715 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14716 if (LangOpts.ObjCRuntime.isFragile()) { 14717 // Case of ivar declared in an implementation. Context is that of its class. 14718 EnclosingContext = IMPDecl->getClassInterface(); 14719 assert(EnclosingContext && "Implementation has no class interface!"); 14720 } 14721 else 14722 EnclosingContext = EnclosingDecl; 14723 } else { 14724 if (ObjCCategoryDecl *CDecl = 14725 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14726 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14727 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14728 return nullptr; 14729 } 14730 } 14731 EnclosingContext = EnclosingDecl; 14732 } 14733 14734 // Construct the decl. 14735 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14736 DeclStart, Loc, II, T, 14737 TInfo, ac, (Expr *)BitfieldWidth); 14738 14739 if (II) { 14740 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14741 ForRedeclaration); 14742 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14743 && !isa<TagDecl>(PrevDecl)) { 14744 Diag(Loc, diag::err_duplicate_member) << II; 14745 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14746 NewID->setInvalidDecl(); 14747 } 14748 } 14749 14750 // Process attributes attached to the ivar. 14751 ProcessDeclAttributes(S, NewID, D); 14752 14753 if (D.isInvalidType()) 14754 NewID->setInvalidDecl(); 14755 14756 // In ARC, infer 'retaining' for ivars of retainable type. 14757 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14758 NewID->setInvalidDecl(); 14759 14760 if (D.getDeclSpec().isModulePrivateSpecified()) 14761 NewID->setModulePrivate(); 14762 14763 if (II) { 14764 // FIXME: When interfaces are DeclContexts, we'll need to add 14765 // these to the interface. 14766 S->AddDecl(NewID); 14767 IdResolver.AddDecl(NewID); 14768 } 14769 14770 if (LangOpts.ObjCRuntime.isNonFragile() && 14771 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14772 Diag(Loc, diag::warn_ivars_in_interface); 14773 14774 return NewID; 14775 } 14776 14777 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14778 /// class and class extensions. For every class \@interface and class 14779 /// extension \@interface, if the last ivar is a bitfield of any type, 14780 /// then add an implicit `char :0` ivar to the end of that interface. 14781 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14782 SmallVectorImpl<Decl *> &AllIvarDecls) { 14783 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14784 return; 14785 14786 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14787 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14788 14789 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14790 return; 14791 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14792 if (!ID) { 14793 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14794 if (!CD->IsClassExtension()) 14795 return; 14796 } 14797 // No need to add this to end of @implementation. 14798 else 14799 return; 14800 } 14801 // All conditions are met. Add a new bitfield to the tail end of ivars. 14802 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14803 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14804 14805 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14806 DeclLoc, DeclLoc, nullptr, 14807 Context.CharTy, 14808 Context.getTrivialTypeSourceInfo(Context.CharTy, 14809 DeclLoc), 14810 ObjCIvarDecl::Private, BW, 14811 true); 14812 AllIvarDecls.push_back(Ivar); 14813 } 14814 14815 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14816 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14817 SourceLocation RBrac, AttributeList *Attr) { 14818 assert(EnclosingDecl && "missing record or interface decl"); 14819 14820 // If this is an Objective-C @implementation or category and we have 14821 // new fields here we should reset the layout of the interface since 14822 // it will now change. 14823 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14824 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14825 switch (DC->getKind()) { 14826 default: break; 14827 case Decl::ObjCCategory: 14828 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14829 break; 14830 case Decl::ObjCImplementation: 14831 Context. 14832 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14833 break; 14834 } 14835 } 14836 14837 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14838 14839 // Start counting up the number of named members; make sure to include 14840 // members of anonymous structs and unions in the total. 14841 unsigned NumNamedMembers = 0; 14842 if (Record) { 14843 for (const auto *I : Record->decls()) { 14844 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14845 if (IFD->getDeclName()) 14846 ++NumNamedMembers; 14847 } 14848 } 14849 14850 // Verify that all the fields are okay. 14851 SmallVector<FieldDecl*, 32> RecFields; 14852 14853 bool ObjCFieldLifetimeErrReported = false; 14854 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14855 i != end; ++i) { 14856 FieldDecl *FD = cast<FieldDecl>(*i); 14857 14858 // Get the type for the field. 14859 const Type *FDTy = FD->getType().getTypePtr(); 14860 14861 if (!FD->isAnonymousStructOrUnion()) { 14862 // Remember all fields written by the user. 14863 RecFields.push_back(FD); 14864 } 14865 14866 // If the field is already invalid for some reason, don't emit more 14867 // diagnostics about it. 14868 if (FD->isInvalidDecl()) { 14869 EnclosingDecl->setInvalidDecl(); 14870 continue; 14871 } 14872 14873 // C99 6.7.2.1p2: 14874 // A structure or union shall not contain a member with 14875 // incomplete or function type (hence, a structure shall not 14876 // contain an instance of itself, but may contain a pointer to 14877 // an instance of itself), except that the last member of a 14878 // structure with more than one named member may have incomplete 14879 // array type; such a structure (and any union containing, 14880 // possibly recursively, a member that is such a structure) 14881 // shall not be a member of a structure or an element of an 14882 // array. 14883 if (FDTy->isFunctionType()) { 14884 // Field declared as a function. 14885 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14886 << FD->getDeclName(); 14887 FD->setInvalidDecl(); 14888 EnclosingDecl->setInvalidDecl(); 14889 continue; 14890 } else if (FDTy->isIncompleteArrayType() && Record && 14891 ((i + 1 == Fields.end() && !Record->isUnion()) || 14892 ((getLangOpts().MicrosoftExt || 14893 getLangOpts().CPlusPlus) && 14894 (i + 1 == Fields.end() || Record->isUnion())))) { 14895 // Flexible array member. 14896 // Microsoft and g++ is more permissive regarding flexible array. 14897 // It will accept flexible array in union and also 14898 // as the sole element of a struct/class. 14899 unsigned DiagID = 0; 14900 if (Record->isUnion()) 14901 DiagID = getLangOpts().MicrosoftExt 14902 ? diag::ext_flexible_array_union_ms 14903 : getLangOpts().CPlusPlus 14904 ? diag::ext_flexible_array_union_gnu 14905 : diag::err_flexible_array_union; 14906 else if (NumNamedMembers < 1) 14907 DiagID = getLangOpts().MicrosoftExt 14908 ? diag::ext_flexible_array_empty_aggregate_ms 14909 : getLangOpts().CPlusPlus 14910 ? diag::ext_flexible_array_empty_aggregate_gnu 14911 : diag::err_flexible_array_empty_aggregate; 14912 14913 if (DiagID) 14914 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14915 << Record->getTagKind(); 14916 // While the layout of types that contain virtual bases is not specified 14917 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14918 // virtual bases after the derived members. This would make a flexible 14919 // array member declared at the end of an object not adjacent to the end 14920 // of the type. 14921 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14922 if (RD->getNumVBases() != 0) 14923 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14924 << FD->getDeclName() << Record->getTagKind(); 14925 if (!getLangOpts().C99) 14926 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14927 << FD->getDeclName() << Record->getTagKind(); 14928 14929 // If the element type has a non-trivial destructor, we would not 14930 // implicitly destroy the elements, so disallow it for now. 14931 // 14932 // FIXME: GCC allows this. We should probably either implicitly delete 14933 // the destructor of the containing class, or just allow this. 14934 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14935 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14936 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14937 << FD->getDeclName() << FD->getType(); 14938 FD->setInvalidDecl(); 14939 EnclosingDecl->setInvalidDecl(); 14940 continue; 14941 } 14942 // Okay, we have a legal flexible array member at the end of the struct. 14943 Record->setHasFlexibleArrayMember(true); 14944 } else if (!FDTy->isDependentType() && 14945 RequireCompleteType(FD->getLocation(), FD->getType(), 14946 diag::err_field_incomplete)) { 14947 // Incomplete type 14948 FD->setInvalidDecl(); 14949 EnclosingDecl->setInvalidDecl(); 14950 continue; 14951 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14952 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14953 // A type which contains a flexible array member is considered to be a 14954 // flexible array member. 14955 Record->setHasFlexibleArrayMember(true); 14956 if (!Record->isUnion()) { 14957 // If this is a struct/class and this is not the last element, reject 14958 // it. Note that GCC supports variable sized arrays in the middle of 14959 // structures. 14960 if (i + 1 != Fields.end()) 14961 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14962 << FD->getDeclName() << FD->getType(); 14963 else { 14964 // We support flexible arrays at the end of structs in 14965 // other structs as an extension. 14966 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14967 << FD->getDeclName(); 14968 } 14969 } 14970 } 14971 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14972 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14973 diag::err_abstract_type_in_decl, 14974 AbstractIvarType)) { 14975 // Ivars can not have abstract class types 14976 FD->setInvalidDecl(); 14977 } 14978 if (Record && FDTTy->getDecl()->hasObjectMember()) 14979 Record->setHasObjectMember(true); 14980 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14981 Record->setHasVolatileMember(true); 14982 } else if (FDTy->isObjCObjectType()) { 14983 /// A field cannot be an Objective-c object 14984 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14985 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14986 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14987 FD->setType(T); 14988 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 14989 Record && !ObjCFieldLifetimeErrReported && 14990 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14991 // It's an error in ARC or Weak if a field has lifetime. 14992 // We don't want to report this in a system header, though, 14993 // so we just make the field unavailable. 14994 // FIXME: that's really not sufficient; we need to make the type 14995 // itself invalid to, say, initialize or copy. 14996 QualType T = FD->getType(); 14997 if (T.hasNonTrivialObjCLifetime()) { 14998 SourceLocation loc = FD->getLocation(); 14999 if (getSourceManager().isInSystemHeader(loc)) { 15000 if (!FD->hasAttr<UnavailableAttr>()) { 15001 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15002 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15003 } 15004 } else { 15005 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15006 << T->isBlockPointerType() << Record->getTagKind(); 15007 } 15008 ObjCFieldLifetimeErrReported = true; 15009 } 15010 } else if (getLangOpts().ObjC1 && 15011 getLangOpts().getGC() != LangOptions::NonGC && 15012 Record && !Record->hasObjectMember()) { 15013 if (FD->getType()->isObjCObjectPointerType() || 15014 FD->getType().isObjCGCStrong()) 15015 Record->setHasObjectMember(true); 15016 else if (Context.getAsArrayType(FD->getType())) { 15017 QualType BaseType = Context.getBaseElementType(FD->getType()); 15018 if (BaseType->isRecordType() && 15019 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15020 Record->setHasObjectMember(true); 15021 else if (BaseType->isObjCObjectPointerType() || 15022 BaseType.isObjCGCStrong()) 15023 Record->setHasObjectMember(true); 15024 } 15025 } 15026 if (Record && FD->getType().isVolatileQualified()) 15027 Record->setHasVolatileMember(true); 15028 // Keep track of the number of named members. 15029 if (FD->getIdentifier()) 15030 ++NumNamedMembers; 15031 } 15032 15033 // Okay, we successfully defined 'Record'. 15034 if (Record) { 15035 bool Completed = false; 15036 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15037 if (!CXXRecord->isInvalidDecl()) { 15038 // Set access bits correctly on the directly-declared conversions. 15039 for (CXXRecordDecl::conversion_iterator 15040 I = CXXRecord->conversion_begin(), 15041 E = CXXRecord->conversion_end(); I != E; ++I) 15042 I.setAccess((*I)->getAccess()); 15043 } 15044 15045 if (!CXXRecord->isDependentType()) { 15046 if (CXXRecord->hasUserDeclaredDestructor()) { 15047 // Adjust user-defined destructor exception spec. 15048 if (getLangOpts().CPlusPlus11) 15049 AdjustDestructorExceptionSpec(CXXRecord, 15050 CXXRecord->getDestructor()); 15051 } 15052 15053 if (!CXXRecord->isInvalidDecl()) { 15054 // Add any implicitly-declared members to this class. 15055 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15056 15057 // If we have virtual base classes, we may end up finding multiple 15058 // final overriders for a given virtual function. Check for this 15059 // problem now. 15060 if (CXXRecord->getNumVBases()) { 15061 CXXFinalOverriderMap FinalOverriders; 15062 CXXRecord->getFinalOverriders(FinalOverriders); 15063 15064 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15065 MEnd = FinalOverriders.end(); 15066 M != MEnd; ++M) { 15067 for (OverridingMethods::iterator SO = M->second.begin(), 15068 SOEnd = M->second.end(); 15069 SO != SOEnd; ++SO) { 15070 assert(SO->second.size() > 0 && 15071 "Virtual function without overridding functions?"); 15072 if (SO->second.size() == 1) 15073 continue; 15074 15075 // C++ [class.virtual]p2: 15076 // In a derived class, if a virtual member function of a base 15077 // class subobject has more than one final overrider the 15078 // program is ill-formed. 15079 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15080 << (const NamedDecl *)M->first << Record; 15081 Diag(M->first->getLocation(), 15082 diag::note_overridden_virtual_function); 15083 for (OverridingMethods::overriding_iterator 15084 OM = SO->second.begin(), 15085 OMEnd = SO->second.end(); 15086 OM != OMEnd; ++OM) 15087 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15088 << (const NamedDecl *)M->first << OM->Method->getParent(); 15089 15090 Record->setInvalidDecl(); 15091 } 15092 } 15093 CXXRecord->completeDefinition(&FinalOverriders); 15094 Completed = true; 15095 } 15096 } 15097 } 15098 } 15099 15100 if (!Completed) 15101 Record->completeDefinition(); 15102 15103 // We may have deferred checking for a deleted destructor. Check now. 15104 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15105 auto *Dtor = CXXRecord->getDestructor(); 15106 if (Dtor && Dtor->isImplicit() && 15107 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 15108 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15109 } 15110 15111 if (Record->hasAttrs()) { 15112 CheckAlignasUnderalignment(Record); 15113 15114 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15115 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15116 IA->getRange(), IA->getBestCase(), 15117 IA->getSemanticSpelling()); 15118 } 15119 15120 // Check if the structure/union declaration is a type that can have zero 15121 // size in C. For C this is a language extension, for C++ it may cause 15122 // compatibility problems. 15123 bool CheckForZeroSize; 15124 if (!getLangOpts().CPlusPlus) { 15125 CheckForZeroSize = true; 15126 } else { 15127 // For C++ filter out types that cannot be referenced in C code. 15128 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15129 CheckForZeroSize = 15130 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15131 !CXXRecord->isDependentType() && 15132 CXXRecord->isCLike(); 15133 } 15134 if (CheckForZeroSize) { 15135 bool ZeroSize = true; 15136 bool IsEmpty = true; 15137 unsigned NonBitFields = 0; 15138 for (RecordDecl::field_iterator I = Record->field_begin(), 15139 E = Record->field_end(); 15140 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15141 IsEmpty = false; 15142 if (I->isUnnamedBitfield()) { 15143 if (I->getBitWidthValue(Context) > 0) 15144 ZeroSize = false; 15145 } else { 15146 ++NonBitFields; 15147 QualType FieldType = I->getType(); 15148 if (FieldType->isIncompleteType() || 15149 !Context.getTypeSizeInChars(FieldType).isZero()) 15150 ZeroSize = false; 15151 } 15152 } 15153 15154 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15155 // allowed in C++, but warn if its declaration is inside 15156 // extern "C" block. 15157 if (ZeroSize) { 15158 Diag(RecLoc, getLangOpts().CPlusPlus ? 15159 diag::warn_zero_size_struct_union_in_extern_c : 15160 diag::warn_zero_size_struct_union_compat) 15161 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15162 } 15163 15164 // Structs without named members are extension in C (C99 6.7.2.1p7), 15165 // but are accepted by GCC. 15166 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15167 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15168 diag::ext_no_named_members_in_struct_union) 15169 << Record->isUnion(); 15170 } 15171 } 15172 } else { 15173 ObjCIvarDecl **ClsFields = 15174 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15175 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15176 ID->setEndOfDefinitionLoc(RBrac); 15177 // Add ivar's to class's DeclContext. 15178 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15179 ClsFields[i]->setLexicalDeclContext(ID); 15180 ID->addDecl(ClsFields[i]); 15181 } 15182 // Must enforce the rule that ivars in the base classes may not be 15183 // duplicates. 15184 if (ID->getSuperClass()) 15185 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15186 } else if (ObjCImplementationDecl *IMPDecl = 15187 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15188 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15189 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15190 // Ivar declared in @implementation never belongs to the implementation. 15191 // Only it is in implementation's lexical context. 15192 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15193 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15194 IMPDecl->setIvarLBraceLoc(LBrac); 15195 IMPDecl->setIvarRBraceLoc(RBrac); 15196 } else if (ObjCCategoryDecl *CDecl = 15197 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15198 // case of ivars in class extension; all other cases have been 15199 // reported as errors elsewhere. 15200 // FIXME. Class extension does not have a LocEnd field. 15201 // CDecl->setLocEnd(RBrac); 15202 // Add ivar's to class extension's DeclContext. 15203 // Diagnose redeclaration of private ivars. 15204 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15205 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15206 if (IDecl) { 15207 if (const ObjCIvarDecl *ClsIvar = 15208 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15209 Diag(ClsFields[i]->getLocation(), 15210 diag::err_duplicate_ivar_declaration); 15211 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15212 continue; 15213 } 15214 for (const auto *Ext : IDecl->known_extensions()) { 15215 if (const ObjCIvarDecl *ClsExtIvar 15216 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15217 Diag(ClsFields[i]->getLocation(), 15218 diag::err_duplicate_ivar_declaration); 15219 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15220 continue; 15221 } 15222 } 15223 } 15224 ClsFields[i]->setLexicalDeclContext(CDecl); 15225 CDecl->addDecl(ClsFields[i]); 15226 } 15227 CDecl->setIvarLBraceLoc(LBrac); 15228 CDecl->setIvarRBraceLoc(RBrac); 15229 } 15230 } 15231 15232 if (Attr) 15233 ProcessDeclAttributeList(S, Record, Attr); 15234 } 15235 15236 /// \brief Determine whether the given integral value is representable within 15237 /// the given type T. 15238 static bool isRepresentableIntegerValue(ASTContext &Context, 15239 llvm::APSInt &Value, 15240 QualType T) { 15241 assert(T->isIntegralType(Context) && "Integral type required!"); 15242 unsigned BitWidth = Context.getIntWidth(T); 15243 15244 if (Value.isUnsigned() || Value.isNonNegative()) { 15245 if (T->isSignedIntegerOrEnumerationType()) 15246 --BitWidth; 15247 return Value.getActiveBits() <= BitWidth; 15248 } 15249 return Value.getMinSignedBits() <= BitWidth; 15250 } 15251 15252 // \brief Given an integral type, return the next larger integral type 15253 // (or a NULL type of no such type exists). 15254 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15255 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15256 // enum checking below. 15257 assert(T->isIntegralType(Context) && "Integral type required!"); 15258 const unsigned NumTypes = 4; 15259 QualType SignedIntegralTypes[NumTypes] = { 15260 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15261 }; 15262 QualType UnsignedIntegralTypes[NumTypes] = { 15263 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15264 Context.UnsignedLongLongTy 15265 }; 15266 15267 unsigned BitWidth = Context.getTypeSize(T); 15268 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15269 : UnsignedIntegralTypes; 15270 for (unsigned I = 0; I != NumTypes; ++I) 15271 if (Context.getTypeSize(Types[I]) > BitWidth) 15272 return Types[I]; 15273 15274 return QualType(); 15275 } 15276 15277 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15278 EnumConstantDecl *LastEnumConst, 15279 SourceLocation IdLoc, 15280 IdentifierInfo *Id, 15281 Expr *Val) { 15282 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15283 llvm::APSInt EnumVal(IntWidth); 15284 QualType EltTy; 15285 15286 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15287 Val = nullptr; 15288 15289 if (Val) 15290 Val = DefaultLvalueConversion(Val).get(); 15291 15292 if (Val) { 15293 if (Enum->isDependentType() || Val->isTypeDependent()) 15294 EltTy = Context.DependentTy; 15295 else { 15296 SourceLocation ExpLoc; 15297 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15298 !getLangOpts().MSVCCompat) { 15299 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15300 // constant-expression in the enumerator-definition shall be a converted 15301 // constant expression of the underlying type. 15302 EltTy = Enum->getIntegerType(); 15303 ExprResult Converted = 15304 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15305 CCEK_Enumerator); 15306 if (Converted.isInvalid()) 15307 Val = nullptr; 15308 else 15309 Val = Converted.get(); 15310 } else if (!Val->isValueDependent() && 15311 !(Val = VerifyIntegerConstantExpression(Val, 15312 &EnumVal).get())) { 15313 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15314 } else { 15315 if (Enum->isFixed()) { 15316 EltTy = Enum->getIntegerType(); 15317 15318 // In Obj-C and Microsoft mode, require the enumeration value to be 15319 // representable in the underlying type of the enumeration. In C++11, 15320 // we perform a non-narrowing conversion as part of converted constant 15321 // expression checking. 15322 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15323 if (getLangOpts().MSVCCompat) { 15324 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15325 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15326 } else 15327 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15328 } else 15329 Val = ImpCastExprToType(Val, EltTy, 15330 EltTy->isBooleanType() ? 15331 CK_IntegralToBoolean : CK_IntegralCast) 15332 .get(); 15333 } else if (getLangOpts().CPlusPlus) { 15334 // C++11 [dcl.enum]p5: 15335 // If the underlying type is not fixed, the type of each enumerator 15336 // is the type of its initializing value: 15337 // - If an initializer is specified for an enumerator, the 15338 // initializing value has the same type as the expression. 15339 EltTy = Val->getType(); 15340 } else { 15341 // C99 6.7.2.2p2: 15342 // The expression that defines the value of an enumeration constant 15343 // shall be an integer constant expression that has a value 15344 // representable as an int. 15345 15346 // Complain if the value is not representable in an int. 15347 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15348 Diag(IdLoc, diag::ext_enum_value_not_int) 15349 << EnumVal.toString(10) << Val->getSourceRange() 15350 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15351 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15352 // Force the type of the expression to 'int'. 15353 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15354 } 15355 EltTy = Val->getType(); 15356 } 15357 } 15358 } 15359 } 15360 15361 if (!Val) { 15362 if (Enum->isDependentType()) 15363 EltTy = Context.DependentTy; 15364 else if (!LastEnumConst) { 15365 // C++0x [dcl.enum]p5: 15366 // If the underlying type is not fixed, the type of each enumerator 15367 // is the type of its initializing value: 15368 // - If no initializer is specified for the first enumerator, the 15369 // initializing value has an unspecified integral type. 15370 // 15371 // GCC uses 'int' for its unspecified integral type, as does 15372 // C99 6.7.2.2p3. 15373 if (Enum->isFixed()) { 15374 EltTy = Enum->getIntegerType(); 15375 } 15376 else { 15377 EltTy = Context.IntTy; 15378 } 15379 } else { 15380 // Assign the last value + 1. 15381 EnumVal = LastEnumConst->getInitVal(); 15382 ++EnumVal; 15383 EltTy = LastEnumConst->getType(); 15384 15385 // Check for overflow on increment. 15386 if (EnumVal < LastEnumConst->getInitVal()) { 15387 // C++0x [dcl.enum]p5: 15388 // If the underlying type is not fixed, the type of each enumerator 15389 // is the type of its initializing value: 15390 // 15391 // - Otherwise the type of the initializing value is the same as 15392 // the type of the initializing value of the preceding enumerator 15393 // unless the incremented value is not representable in that type, 15394 // in which case the type is an unspecified integral type 15395 // sufficient to contain the incremented value. If no such type 15396 // exists, the program is ill-formed. 15397 QualType T = getNextLargerIntegralType(Context, EltTy); 15398 if (T.isNull() || Enum->isFixed()) { 15399 // There is no integral type larger enough to represent this 15400 // value. Complain, then allow the value to wrap around. 15401 EnumVal = LastEnumConst->getInitVal(); 15402 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15403 ++EnumVal; 15404 if (Enum->isFixed()) 15405 // When the underlying type is fixed, this is ill-formed. 15406 Diag(IdLoc, diag::err_enumerator_wrapped) 15407 << EnumVal.toString(10) 15408 << EltTy; 15409 else 15410 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15411 << EnumVal.toString(10); 15412 } else { 15413 EltTy = T; 15414 } 15415 15416 // Retrieve the last enumerator's value, extent that type to the 15417 // type that is supposed to be large enough to represent the incremented 15418 // value, then increment. 15419 EnumVal = LastEnumConst->getInitVal(); 15420 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15421 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15422 ++EnumVal; 15423 15424 // If we're not in C++, diagnose the overflow of enumerator values, 15425 // which in C99 means that the enumerator value is not representable in 15426 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15427 // permits enumerator values that are representable in some larger 15428 // integral type. 15429 if (!getLangOpts().CPlusPlus && !T.isNull()) 15430 Diag(IdLoc, diag::warn_enum_value_overflow); 15431 } else if (!getLangOpts().CPlusPlus && 15432 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15433 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15434 Diag(IdLoc, diag::ext_enum_value_not_int) 15435 << EnumVal.toString(10) << 1; 15436 } 15437 } 15438 } 15439 15440 if (!EltTy->isDependentType()) { 15441 // Make the enumerator value match the signedness and size of the 15442 // enumerator's type. 15443 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15444 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15445 } 15446 15447 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15448 Val, EnumVal); 15449 } 15450 15451 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15452 SourceLocation IILoc) { 15453 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15454 !getLangOpts().CPlusPlus) 15455 return SkipBodyInfo(); 15456 15457 // We have an anonymous enum definition. Look up the first enumerator to 15458 // determine if we should merge the definition with an existing one and 15459 // skip the body. 15460 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15461 ForRedeclaration); 15462 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15463 if (!PrevECD) 15464 return SkipBodyInfo(); 15465 15466 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15467 NamedDecl *Hidden; 15468 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15469 SkipBodyInfo Skip; 15470 Skip.Previous = Hidden; 15471 return Skip; 15472 } 15473 15474 return SkipBodyInfo(); 15475 } 15476 15477 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15478 SourceLocation IdLoc, IdentifierInfo *Id, 15479 AttributeList *Attr, 15480 SourceLocation EqualLoc, Expr *Val) { 15481 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15482 EnumConstantDecl *LastEnumConst = 15483 cast_or_null<EnumConstantDecl>(lastEnumConst); 15484 15485 // The scope passed in may not be a decl scope. Zip up the scope tree until 15486 // we find one that is. 15487 S = getNonFieldDeclScope(S); 15488 15489 // Verify that there isn't already something declared with this name in this 15490 // scope. 15491 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15492 ForRedeclaration); 15493 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15494 // Maybe we will complain about the shadowed template parameter. 15495 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15496 // Just pretend that we didn't see the previous declaration. 15497 PrevDecl = nullptr; 15498 } 15499 15500 // C++ [class.mem]p15: 15501 // If T is the name of a class, then each of the following shall have a name 15502 // different from T: 15503 // - every enumerator of every member of class T that is an unscoped 15504 // enumerated type 15505 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15506 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15507 DeclarationNameInfo(Id, IdLoc)); 15508 15509 EnumConstantDecl *New = 15510 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15511 if (!New) 15512 return nullptr; 15513 15514 if (PrevDecl) { 15515 // When in C++, we may get a TagDecl with the same name; in this case the 15516 // enum constant will 'hide' the tag. 15517 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15518 "Received TagDecl when not in C++!"); 15519 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15520 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15521 if (isa<EnumConstantDecl>(PrevDecl)) 15522 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15523 else 15524 Diag(IdLoc, diag::err_redefinition) << Id; 15525 notePreviousDefinition(PrevDecl, IdLoc); 15526 return nullptr; 15527 } 15528 } 15529 15530 // Process attributes. 15531 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15532 AddPragmaAttributes(S, New); 15533 15534 // Register this decl in the current scope stack. 15535 New->setAccess(TheEnumDecl->getAccess()); 15536 PushOnScopeChains(New, S); 15537 15538 ActOnDocumentableDecl(New); 15539 15540 return New; 15541 } 15542 15543 // Returns true when the enum initial expression does not trigger the 15544 // duplicate enum warning. A few common cases are exempted as follows: 15545 // Element2 = Element1 15546 // Element2 = Element1 + 1 15547 // Element2 = Element1 - 1 15548 // Where Element2 and Element1 are from the same enum. 15549 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15550 Expr *InitExpr = ECD->getInitExpr(); 15551 if (!InitExpr) 15552 return true; 15553 InitExpr = InitExpr->IgnoreImpCasts(); 15554 15555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15556 if (!BO->isAdditiveOp()) 15557 return true; 15558 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15559 if (!IL) 15560 return true; 15561 if (IL->getValue() != 1) 15562 return true; 15563 15564 InitExpr = BO->getLHS(); 15565 } 15566 15567 // This checks if the elements are from the same enum. 15568 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15569 if (!DRE) 15570 return true; 15571 15572 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15573 if (!EnumConstant) 15574 return true; 15575 15576 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15577 Enum) 15578 return true; 15579 15580 return false; 15581 } 15582 15583 namespace { 15584 struct DupKey { 15585 int64_t val; 15586 bool isTombstoneOrEmptyKey; 15587 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15588 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15589 }; 15590 15591 static DupKey GetDupKey(const llvm::APSInt& Val) { 15592 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15593 false); 15594 } 15595 15596 struct DenseMapInfoDupKey { 15597 static DupKey getEmptyKey() { return DupKey(0, true); } 15598 static DupKey getTombstoneKey() { return DupKey(1, true); } 15599 static unsigned getHashValue(const DupKey Key) { 15600 return (unsigned)(Key.val * 37); 15601 } 15602 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15603 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15604 LHS.val == RHS.val; 15605 } 15606 }; 15607 } // end anonymous namespace 15608 15609 // Emits a warning when an element is implicitly set a value that 15610 // a previous element has already been set to. 15611 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15612 EnumDecl *Enum, 15613 QualType EnumType) { 15614 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15615 return; 15616 // Avoid anonymous enums 15617 if (!Enum->getIdentifier()) 15618 return; 15619 15620 // Only check for small enums. 15621 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15622 return; 15623 15624 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15625 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15626 15627 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15628 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15629 ValueToVectorMap; 15630 15631 DuplicatesVector DupVector; 15632 ValueToVectorMap EnumMap; 15633 15634 // Populate the EnumMap with all values represented by enum constants without 15635 // an initialier. 15636 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15637 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15638 15639 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15640 // this constant. Skip this enum since it may be ill-formed. 15641 if (!ECD) { 15642 return; 15643 } 15644 15645 if (ECD->getInitExpr()) 15646 continue; 15647 15648 DupKey Key = GetDupKey(ECD->getInitVal()); 15649 DeclOrVector &Entry = EnumMap[Key]; 15650 15651 // First time encountering this value. 15652 if (Entry.isNull()) 15653 Entry = ECD; 15654 } 15655 15656 // Create vectors for any values that has duplicates. 15657 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15658 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15659 if (!ValidDuplicateEnum(ECD, Enum)) 15660 continue; 15661 15662 DupKey Key = GetDupKey(ECD->getInitVal()); 15663 15664 DeclOrVector& Entry = EnumMap[Key]; 15665 if (Entry.isNull()) 15666 continue; 15667 15668 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15669 // Ensure constants are different. 15670 if (D == ECD) 15671 continue; 15672 15673 // Create new vector and push values onto it. 15674 ECDVector *Vec = new ECDVector(); 15675 Vec->push_back(D); 15676 Vec->push_back(ECD); 15677 15678 // Update entry to point to the duplicates vector. 15679 Entry = Vec; 15680 15681 // Store the vector somewhere we can consult later for quick emission of 15682 // diagnostics. 15683 DupVector.push_back(Vec); 15684 continue; 15685 } 15686 15687 ECDVector *Vec = Entry.get<ECDVector*>(); 15688 // Make sure constants are not added more than once. 15689 if (*Vec->begin() == ECD) 15690 continue; 15691 15692 Vec->push_back(ECD); 15693 } 15694 15695 // Emit diagnostics. 15696 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15697 DupVectorEnd = DupVector.end(); 15698 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15699 ECDVector *Vec = *DupVectorIter; 15700 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15701 15702 // Emit warning for one enum constant. 15703 ECDVector::iterator I = Vec->begin(); 15704 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15705 << (*I)->getName() << (*I)->getInitVal().toString(10) 15706 << (*I)->getSourceRange(); 15707 ++I; 15708 15709 // Emit one note for each of the remaining enum constants with 15710 // the same value. 15711 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15712 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15713 << (*I)->getName() << (*I)->getInitVal().toString(10) 15714 << (*I)->getSourceRange(); 15715 delete Vec; 15716 } 15717 } 15718 15719 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15720 bool AllowMask) const { 15721 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15722 assert(ED->isCompleteDefinition() && "expected enum definition"); 15723 15724 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15725 llvm::APInt &FlagBits = R.first->second; 15726 15727 if (R.second) { 15728 for (auto *E : ED->enumerators()) { 15729 const auto &EVal = E->getInitVal(); 15730 // Only single-bit enumerators introduce new flag values. 15731 if (EVal.isPowerOf2()) 15732 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15733 } 15734 } 15735 15736 // A value is in a flag enum if either its bits are a subset of the enum's 15737 // flag bits (the first condition) or we are allowing masks and the same is 15738 // true of its complement (the second condition). When masks are allowed, we 15739 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15740 // 15741 // While it's true that any value could be used as a mask, the assumption is 15742 // that a mask will have all of the insignificant bits set. Anything else is 15743 // likely a logic error. 15744 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15745 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15746 } 15747 15748 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15749 Decl *EnumDeclX, 15750 ArrayRef<Decl *> Elements, 15751 Scope *S, AttributeList *Attr) { 15752 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15753 QualType EnumType = Context.getTypeDeclType(Enum); 15754 15755 if (Attr) 15756 ProcessDeclAttributeList(S, Enum, Attr); 15757 15758 if (Enum->isDependentType()) { 15759 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15760 EnumConstantDecl *ECD = 15761 cast_or_null<EnumConstantDecl>(Elements[i]); 15762 if (!ECD) continue; 15763 15764 ECD->setType(EnumType); 15765 } 15766 15767 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15768 return; 15769 } 15770 15771 // TODO: If the result value doesn't fit in an int, it must be a long or long 15772 // long value. ISO C does not support this, but GCC does as an extension, 15773 // emit a warning. 15774 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15775 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15776 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15777 15778 // Verify that all the values are okay, compute the size of the values, and 15779 // reverse the list. 15780 unsigned NumNegativeBits = 0; 15781 unsigned NumPositiveBits = 0; 15782 15783 // Keep track of whether all elements have type int. 15784 bool AllElementsInt = true; 15785 15786 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15787 EnumConstantDecl *ECD = 15788 cast_or_null<EnumConstantDecl>(Elements[i]); 15789 if (!ECD) continue; // Already issued a diagnostic. 15790 15791 const llvm::APSInt &InitVal = ECD->getInitVal(); 15792 15793 // Keep track of the size of positive and negative values. 15794 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15795 NumPositiveBits = std::max(NumPositiveBits, 15796 (unsigned)InitVal.getActiveBits()); 15797 else 15798 NumNegativeBits = std::max(NumNegativeBits, 15799 (unsigned)InitVal.getMinSignedBits()); 15800 15801 // Keep track of whether every enum element has type int (very commmon). 15802 if (AllElementsInt) 15803 AllElementsInt = ECD->getType() == Context.IntTy; 15804 } 15805 15806 // Figure out the type that should be used for this enum. 15807 QualType BestType; 15808 unsigned BestWidth; 15809 15810 // C++0x N3000 [conv.prom]p3: 15811 // An rvalue of an unscoped enumeration type whose underlying 15812 // type is not fixed can be converted to an rvalue of the first 15813 // of the following types that can represent all the values of 15814 // the enumeration: int, unsigned int, long int, unsigned long 15815 // int, long long int, or unsigned long long int. 15816 // C99 6.4.4.3p2: 15817 // An identifier declared as an enumeration constant has type int. 15818 // The C99 rule is modified by a gcc extension 15819 QualType BestPromotionType; 15820 15821 bool Packed = Enum->hasAttr<PackedAttr>(); 15822 // -fshort-enums is the equivalent to specifying the packed attribute on all 15823 // enum definitions. 15824 if (LangOpts.ShortEnums) 15825 Packed = true; 15826 15827 if (Enum->isFixed()) { 15828 BestType = Enum->getIntegerType(); 15829 if (BestType->isPromotableIntegerType()) 15830 BestPromotionType = Context.getPromotedIntegerType(BestType); 15831 else 15832 BestPromotionType = BestType; 15833 15834 BestWidth = Context.getIntWidth(BestType); 15835 } 15836 else if (NumNegativeBits) { 15837 // If there is a negative value, figure out the smallest integer type (of 15838 // int/long/longlong) that fits. 15839 // If it's packed, check also if it fits a char or a short. 15840 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15841 BestType = Context.SignedCharTy; 15842 BestWidth = CharWidth; 15843 } else if (Packed && NumNegativeBits <= ShortWidth && 15844 NumPositiveBits < ShortWidth) { 15845 BestType = Context.ShortTy; 15846 BestWidth = ShortWidth; 15847 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15848 BestType = Context.IntTy; 15849 BestWidth = IntWidth; 15850 } else { 15851 BestWidth = Context.getTargetInfo().getLongWidth(); 15852 15853 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15854 BestType = Context.LongTy; 15855 } else { 15856 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15857 15858 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15859 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15860 BestType = Context.LongLongTy; 15861 } 15862 } 15863 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15864 } else { 15865 // If there is no negative value, figure out the smallest type that fits 15866 // all of the enumerator values. 15867 // If it's packed, check also if it fits a char or a short. 15868 if (Packed && NumPositiveBits <= CharWidth) { 15869 BestType = Context.UnsignedCharTy; 15870 BestPromotionType = Context.IntTy; 15871 BestWidth = CharWidth; 15872 } else if (Packed && NumPositiveBits <= ShortWidth) { 15873 BestType = Context.UnsignedShortTy; 15874 BestPromotionType = Context.IntTy; 15875 BestWidth = ShortWidth; 15876 } else if (NumPositiveBits <= IntWidth) { 15877 BestType = Context.UnsignedIntTy; 15878 BestWidth = IntWidth; 15879 BestPromotionType 15880 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15881 ? Context.UnsignedIntTy : Context.IntTy; 15882 } else if (NumPositiveBits <= 15883 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15884 BestType = Context.UnsignedLongTy; 15885 BestPromotionType 15886 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15887 ? Context.UnsignedLongTy : Context.LongTy; 15888 } else { 15889 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15890 assert(NumPositiveBits <= BestWidth && 15891 "How could an initializer get larger than ULL?"); 15892 BestType = Context.UnsignedLongLongTy; 15893 BestPromotionType 15894 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15895 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15896 } 15897 } 15898 15899 // Loop over all of the enumerator constants, changing their types to match 15900 // the type of the enum if needed. 15901 for (auto *D : Elements) { 15902 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15903 if (!ECD) continue; // Already issued a diagnostic. 15904 15905 // Standard C says the enumerators have int type, but we allow, as an 15906 // extension, the enumerators to be larger than int size. If each 15907 // enumerator value fits in an int, type it as an int, otherwise type it the 15908 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15909 // that X has type 'int', not 'unsigned'. 15910 15911 // Determine whether the value fits into an int. 15912 llvm::APSInt InitVal = ECD->getInitVal(); 15913 15914 // If it fits into an integer type, force it. Otherwise force it to match 15915 // the enum decl type. 15916 QualType NewTy; 15917 unsigned NewWidth; 15918 bool NewSign; 15919 if (!getLangOpts().CPlusPlus && 15920 !Enum->isFixed() && 15921 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15922 NewTy = Context.IntTy; 15923 NewWidth = IntWidth; 15924 NewSign = true; 15925 } else if (ECD->getType() == BestType) { 15926 // Already the right type! 15927 if (getLangOpts().CPlusPlus) 15928 // C++ [dcl.enum]p4: Following the closing brace of an 15929 // enum-specifier, each enumerator has the type of its 15930 // enumeration. 15931 ECD->setType(EnumType); 15932 continue; 15933 } else { 15934 NewTy = BestType; 15935 NewWidth = BestWidth; 15936 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15937 } 15938 15939 // Adjust the APSInt value. 15940 InitVal = InitVal.extOrTrunc(NewWidth); 15941 InitVal.setIsSigned(NewSign); 15942 ECD->setInitVal(InitVal); 15943 15944 // Adjust the Expr initializer and type. 15945 if (ECD->getInitExpr() && 15946 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15947 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15948 CK_IntegralCast, 15949 ECD->getInitExpr(), 15950 /*base paths*/ nullptr, 15951 VK_RValue)); 15952 if (getLangOpts().CPlusPlus) 15953 // C++ [dcl.enum]p4: Following the closing brace of an 15954 // enum-specifier, each enumerator has the type of its 15955 // enumeration. 15956 ECD->setType(EnumType); 15957 else 15958 ECD->setType(NewTy); 15959 } 15960 15961 Enum->completeDefinition(BestType, BestPromotionType, 15962 NumPositiveBits, NumNegativeBits); 15963 15964 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15965 15966 if (Enum->isClosedFlag()) { 15967 for (Decl *D : Elements) { 15968 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15969 if (!ECD) continue; // Already issued a diagnostic. 15970 15971 llvm::APSInt InitVal = ECD->getInitVal(); 15972 if (InitVal != 0 && !InitVal.isPowerOf2() && 15973 !IsValueInFlagEnum(Enum, InitVal, true)) 15974 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15975 << ECD << Enum; 15976 } 15977 } 15978 15979 // Now that the enum type is defined, ensure it's not been underaligned. 15980 if (Enum->hasAttrs()) 15981 CheckAlignasUnderalignment(Enum); 15982 } 15983 15984 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15985 SourceLocation StartLoc, 15986 SourceLocation EndLoc) { 15987 StringLiteral *AsmString = cast<StringLiteral>(expr); 15988 15989 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15990 AsmString, StartLoc, 15991 EndLoc); 15992 CurContext->addDecl(New); 15993 return New; 15994 } 15995 15996 static void checkModuleImportContext(Sema &S, Module *M, 15997 SourceLocation ImportLoc, DeclContext *DC, 15998 bool FromInclude = false) { 15999 SourceLocation ExternCLoc; 16000 16001 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16002 switch (LSD->getLanguage()) { 16003 case LinkageSpecDecl::lang_c: 16004 if (ExternCLoc.isInvalid()) 16005 ExternCLoc = LSD->getLocStart(); 16006 break; 16007 case LinkageSpecDecl::lang_cxx: 16008 break; 16009 } 16010 DC = LSD->getParent(); 16011 } 16012 16013 while (isa<LinkageSpecDecl>(DC)) 16014 DC = DC->getParent(); 16015 16016 if (!isa<TranslationUnitDecl>(DC)) { 16017 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16018 ? diag::ext_module_import_not_at_top_level_noop 16019 : diag::err_module_import_not_at_top_level_fatal) 16020 << M->getFullModuleName() << DC; 16021 S.Diag(cast<Decl>(DC)->getLocStart(), 16022 diag::note_module_import_not_at_top_level) << DC; 16023 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16024 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16025 << M->getFullModuleName(); 16026 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16027 } 16028 } 16029 16030 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16031 SourceLocation ModuleLoc, 16032 ModuleDeclKind MDK, 16033 ModuleIdPath Path) { 16034 // A module implementation unit requires that we are not compiling a module 16035 // of any kind. A module interface unit requires that we are not compiling a 16036 // module map. 16037 switch (getLangOpts().getCompilingModule()) { 16038 case LangOptions::CMK_None: 16039 // It's OK to compile a module interface as a normal translation unit. 16040 break; 16041 16042 case LangOptions::CMK_ModuleInterface: 16043 if (MDK != ModuleDeclKind::Implementation) 16044 break; 16045 16046 // We were asked to compile a module interface unit but this is a module 16047 // implementation unit. That indicates the 'export' is missing. 16048 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16049 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16050 break; 16051 16052 case LangOptions::CMK_ModuleMap: 16053 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16054 return nullptr; 16055 } 16056 16057 // FIXME: Most of this work should be done by the preprocessor rather than 16058 // here, in order to support macro import. 16059 16060 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16061 // modules, the dots here are just another character that can appear in a 16062 // module name. 16063 std::string ModuleName; 16064 for (auto &Piece : Path) { 16065 if (!ModuleName.empty()) 16066 ModuleName += "."; 16067 ModuleName += Piece.first->getName(); 16068 } 16069 16070 // FIXME: If we've already seen a module-declaration, report an error. 16071 16072 // If a module name was explicitly specified on the command line, it must be 16073 // correct. 16074 if (!getLangOpts().CurrentModule.empty() && 16075 getLangOpts().CurrentModule != ModuleName) { 16076 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16077 << SourceRange(Path.front().second, Path.back().second) 16078 << getLangOpts().CurrentModule; 16079 return nullptr; 16080 } 16081 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16082 16083 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16084 Module *Mod; 16085 16086 switch (MDK) { 16087 case ModuleDeclKind::Module: { 16088 // FIXME: Check we're not in a submodule. 16089 16090 // We can't have parsed or imported a definition of this module or parsed a 16091 // module map defining it already. 16092 if (auto *M = Map.findModule(ModuleName)) { 16093 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16094 if (M->DefinitionLoc.isValid()) 16095 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16096 else if (const auto *FE = M->getASTFile()) 16097 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16098 << FE->getName(); 16099 return nullptr; 16100 } 16101 16102 // Create a Module for the module that we're defining. 16103 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 16104 assert(Mod && "module creation should not fail"); 16105 break; 16106 } 16107 16108 case ModuleDeclKind::Partition: 16109 // FIXME: Check we are in a submodule of the named module. 16110 return nullptr; 16111 16112 case ModuleDeclKind::Implementation: 16113 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16114 PP.getIdentifierInfo(ModuleName), Path[0].second); 16115 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16116 /*IsIncludeDirective=*/false); 16117 if (!Mod) 16118 return nullptr; 16119 break; 16120 } 16121 16122 // Enter the semantic scope of the module. 16123 ModuleScopes.push_back({}); 16124 ModuleScopes.back().Module = Mod; 16125 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16126 VisibleModules.setVisible(Mod, ModuleLoc); 16127 16128 // From now on, we have an owning module for all declarations we see. 16129 // However, those declarations are module-private unless explicitly 16130 // exported. 16131 Context.getTranslationUnitDecl()->setLocalOwningModule(Mod); 16132 16133 // FIXME: Create a ModuleDecl. 16134 return nullptr; 16135 } 16136 16137 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16138 SourceLocation ImportLoc, 16139 ModuleIdPath Path) { 16140 Module *Mod = 16141 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16142 /*IsIncludeDirective=*/false); 16143 if (!Mod) 16144 return true; 16145 16146 VisibleModules.setVisible(Mod, ImportLoc); 16147 16148 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16149 16150 // FIXME: we should support importing a submodule within a different submodule 16151 // of the same top-level module. Until we do, make it an error rather than 16152 // silently ignoring the import. 16153 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16154 // warn on a redundant import of the current module? 16155 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16156 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16157 Diag(ImportLoc, getLangOpts().isCompilingModule() 16158 ? diag::err_module_self_import 16159 : diag::err_module_import_in_implementation) 16160 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16161 16162 SmallVector<SourceLocation, 2> IdentifierLocs; 16163 Module *ModCheck = Mod; 16164 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16165 // If we've run out of module parents, just drop the remaining identifiers. 16166 // We need the length to be consistent. 16167 if (!ModCheck) 16168 break; 16169 ModCheck = ModCheck->Parent; 16170 16171 IdentifierLocs.push_back(Path[I].second); 16172 } 16173 16174 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16175 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 16176 Mod, IdentifierLocs); 16177 if (!ModuleScopes.empty()) 16178 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16179 TU->addDecl(Import); 16180 return Import; 16181 } 16182 16183 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16184 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16185 BuildModuleInclude(DirectiveLoc, Mod); 16186 } 16187 16188 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16189 // Determine whether we're in the #include buffer for a module. The #includes 16190 // in that buffer do not qualify as module imports; they're just an 16191 // implementation detail of us building the module. 16192 // 16193 // FIXME: Should we even get ActOnModuleInclude calls for those? 16194 bool IsInModuleIncludes = 16195 TUKind == TU_Module && 16196 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16197 16198 bool ShouldAddImport = !IsInModuleIncludes; 16199 16200 // If this module import was due to an inclusion directive, create an 16201 // implicit import declaration to capture it in the AST. 16202 if (ShouldAddImport) { 16203 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16204 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16205 DirectiveLoc, Mod, 16206 DirectiveLoc); 16207 if (!ModuleScopes.empty()) 16208 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16209 TU->addDecl(ImportD); 16210 Consumer.HandleImplicitImportDecl(ImportD); 16211 } 16212 16213 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16214 VisibleModules.setVisible(Mod, DirectiveLoc); 16215 } 16216 16217 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16218 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16219 16220 ModuleScopes.push_back({}); 16221 ModuleScopes.back().Module = Mod; 16222 if (getLangOpts().ModulesLocalVisibility) 16223 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16224 16225 VisibleModules.setVisible(Mod, DirectiveLoc); 16226 16227 // The enclosing context is now part of this module. 16228 // FIXME: Consider creating a child DeclContext to hold the entities 16229 // lexically within the module. 16230 if (getLangOpts().trackLocalOwningModule()) { 16231 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16232 cast<Decl>(DC)->setModuleOwnershipKind( 16233 getLangOpts().ModulesLocalVisibility 16234 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16235 : Decl::ModuleOwnershipKind::Visible); 16236 cast<Decl>(DC)->setLocalOwningModule(Mod); 16237 } 16238 } 16239 } 16240 16241 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16242 if (getLangOpts().ModulesLocalVisibility) { 16243 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16244 // Leaving a module hides namespace names, so our visible namespace cache 16245 // is now out of date. 16246 VisibleNamespaceCache.clear(); 16247 } 16248 16249 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16250 "left the wrong module scope"); 16251 ModuleScopes.pop_back(); 16252 16253 // We got to the end of processing a local module. Create an 16254 // ImportDecl as we would for an imported module. 16255 FileID File = getSourceManager().getFileID(EomLoc); 16256 SourceLocation DirectiveLoc; 16257 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16258 // We reached the end of a #included module header. Use the #include loc. 16259 assert(File != getSourceManager().getMainFileID() && 16260 "end of submodule in main source file"); 16261 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16262 } else { 16263 // We reached an EOM pragma. Use the pragma location. 16264 DirectiveLoc = EomLoc; 16265 } 16266 BuildModuleInclude(DirectiveLoc, Mod); 16267 16268 // Any further declarations are in whatever module we returned to. 16269 if (getLangOpts().trackLocalOwningModule()) { 16270 // The parser guarantees that this is the same context that we entered 16271 // the module within. 16272 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16273 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16274 if (!getCurrentModule()) 16275 cast<Decl>(DC)->setModuleOwnershipKind( 16276 Decl::ModuleOwnershipKind::Unowned); 16277 } 16278 } 16279 } 16280 16281 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16282 Module *Mod) { 16283 // Bail if we're not allowed to implicitly import a module here. 16284 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16285 VisibleModules.isVisible(Mod)) 16286 return; 16287 16288 // Create the implicit import declaration. 16289 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16290 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16291 Loc, Mod, Loc); 16292 TU->addDecl(ImportD); 16293 Consumer.HandleImplicitImportDecl(ImportD); 16294 16295 // Make the module visible. 16296 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16297 VisibleModules.setVisible(Mod, Loc); 16298 } 16299 16300 /// We have parsed the start of an export declaration, including the '{' 16301 /// (if present). 16302 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16303 SourceLocation LBraceLoc) { 16304 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16305 16306 // C++ Modules TS draft: 16307 // An export-declaration shall appear in the purview of a module other than 16308 // the global module. 16309 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16310 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16311 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16312 16313 // An export-declaration [...] shall not contain more than one 16314 // export keyword. 16315 // 16316 // The intent here is that an export-declaration cannot appear within another 16317 // export-declaration. 16318 if (D->isExported()) 16319 Diag(ExportLoc, diag::err_export_within_export); 16320 16321 CurContext->addDecl(D); 16322 PushDeclContext(S, D); 16323 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16324 return D; 16325 } 16326 16327 /// Complete the definition of an export declaration. 16328 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16329 auto *ED = cast<ExportDecl>(D); 16330 if (RBraceLoc.isValid()) 16331 ED->setRBraceLoc(RBraceLoc); 16332 16333 // FIXME: Diagnose export of internal-linkage declaration (including 16334 // anonymous namespace). 16335 16336 PopDeclContext(); 16337 return D; 16338 } 16339 16340 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16341 IdentifierInfo* AliasName, 16342 SourceLocation PragmaLoc, 16343 SourceLocation NameLoc, 16344 SourceLocation AliasNameLoc) { 16345 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16346 LookupOrdinaryName); 16347 AsmLabelAttr *Attr = 16348 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16349 16350 // If a declaration that: 16351 // 1) declares a function or a variable 16352 // 2) has external linkage 16353 // already exists, add a label attribute to it. 16354 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16355 if (isDeclExternC(PrevDecl)) 16356 PrevDecl->addAttr(Attr); 16357 else 16358 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16359 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16360 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16361 } else 16362 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16363 } 16364 16365 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16366 SourceLocation PragmaLoc, 16367 SourceLocation NameLoc) { 16368 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16369 16370 if (PrevDecl) { 16371 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16372 } else { 16373 (void)WeakUndeclaredIdentifiers.insert( 16374 std::pair<IdentifierInfo*,WeakInfo> 16375 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16376 } 16377 } 16378 16379 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16380 IdentifierInfo* AliasName, 16381 SourceLocation PragmaLoc, 16382 SourceLocation NameLoc, 16383 SourceLocation AliasNameLoc) { 16384 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16385 LookupOrdinaryName); 16386 WeakInfo W = WeakInfo(Name, NameLoc); 16387 16388 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16389 if (!PrevDecl->hasAttr<AliasAttr>()) 16390 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16391 DeclApplyPragmaWeak(TUScope, ND, W); 16392 } else { 16393 (void)WeakUndeclaredIdentifiers.insert( 16394 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16395 } 16396 } 16397 16398 Decl *Sema::getObjCDeclContext() const { 16399 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16400 } 16401