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 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } // end anonymous namespace 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw___float128: 112 case tok::kw_wchar_t: 113 case tok::kw_bool: 114 case tok::kw___underlying_type: 115 case tok::kw___auto_type: 116 return true; 117 118 case tok::annot_typename: 119 case tok::kw_char16_t: 120 case tok::kw_char32_t: 121 case tok::kw_typeof: 122 case tok::annot_decltype: 123 case tok::kw_decltype: 124 return getLangOpts().CPlusPlus; 125 126 default: 127 break; 128 } 129 130 return false; 131 } 132 133 namespace { 134 enum class UnqualifiedTypeNameLookupResult { 135 NotFound, 136 FoundNonType, 137 FoundType 138 }; 139 } // end anonymous namespace 140 141 /// \brief Tries to perform unqualified lookup of the type decls in bases for 142 /// dependent class. 143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 144 /// type decl, \a FoundType if only type decls are found. 145 static UnqualifiedTypeNameLookupResult 146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 147 SourceLocation NameLoc, 148 const CXXRecordDecl *RD) { 149 if (!RD->hasDefinition()) 150 return UnqualifiedTypeNameLookupResult::NotFound; 151 // Look for type decls in base classes. 152 UnqualifiedTypeNameLookupResult FoundTypeDecl = 153 UnqualifiedTypeNameLookupResult::NotFound; 154 for (const auto &Base : RD->bases()) { 155 const CXXRecordDecl *BaseRD = nullptr; 156 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 157 BaseRD = BaseTT->getAsCXXRecordDecl(); 158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 159 // Look for type decls in dependent base classes that have known primary 160 // templates. 161 if (!TST || !TST->isDependentType()) 162 continue; 163 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 164 if (!TD) 165 continue; 166 if (auto *BasePrimaryTemplate = 167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 169 BaseRD = BasePrimaryTemplate; 170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 171 if (const ClassTemplatePartialSpecializationDecl *PS = 172 CTD->findPartialSpecialization(Base.getType())) 173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 174 BaseRD = PS; 175 } 176 } 177 } 178 if (BaseRD) { 179 for (NamedDecl *ND : BaseRD->lookup(&II)) { 180 if (!isa<TypeDecl>(ND)) 181 return UnqualifiedTypeNameLookupResult::FoundNonType; 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 } 184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 186 case UnqualifiedTypeNameLookupResult::FoundNonType: 187 return UnqualifiedTypeNameLookupResult::FoundNonType; 188 case UnqualifiedTypeNameLookupResult::FoundType: 189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 190 break; 191 case UnqualifiedTypeNameLookupResult::NotFound: 192 break; 193 } 194 } 195 } 196 } 197 198 return FoundTypeDecl; 199 } 200 201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 202 const IdentifierInfo &II, 203 SourceLocation NameLoc) { 204 // Lookup in the parent class template context, if any. 205 const CXXRecordDecl *RD = nullptr; 206 UnqualifiedTypeNameLookupResult FoundTypeDecl = 207 UnqualifiedTypeNameLookupResult::NotFound; 208 for (DeclContext *DC = S.CurContext; 209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 210 DC = DC->getParent()) { 211 // Look for type decls in dependent base classes that have known primary 212 // templates. 213 RD = dyn_cast<CXXRecordDecl>(DC); 214 if (RD && RD->getDescribedClassTemplate()) 215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 216 } 217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 218 return nullptr; 219 220 // We found some types in dependent base classes. Recover as if the user 221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 222 // lookup during template instantiation. 223 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 224 225 ASTContext &Context = S.Context; 226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 227 cast<Type>(Context.getRecordType(RD))); 228 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 229 230 CXXScopeSpec SS; 231 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 233 TypeLocBuilder Builder; 234 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 235 DepTL.setNameLoc(NameLoc); 236 DepTL.setElaboratedKeywordLoc(SourceLocation()); 237 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 238 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 239 } 240 241 /// \brief If the identifier refers to a type name within this scope, 242 /// return the declaration of that type. 243 /// 244 /// This routine performs ordinary name lookup of the identifier II 245 /// within the given scope, with optional C++ scope specifier SS, to 246 /// determine whether the name refers to a type. If so, returns an 247 /// opaque pointer (actually a QualType) corresponding to that 248 /// type. Otherwise, returns NULL. 249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 250 Scope *S, CXXScopeSpec *SS, 251 bool isClassName, bool HasTrailingDot, 252 ParsedType ObjectTypePtr, 253 bool IsCtorOrDtorName, 254 bool WantNontrivialTypeSourceInfo, 255 IdentifierInfo **CorrectedII) { 256 // Determine where we will perform name lookup. 257 DeclContext *LookupCtx = nullptr; 258 if (ObjectTypePtr) { 259 QualType ObjectType = ObjectTypePtr.get(); 260 if (ObjectType->isRecordType()) 261 LookupCtx = computeDeclContext(ObjectType); 262 } else if (SS && SS->isNotEmpty()) { 263 LookupCtx = computeDeclContext(*SS, false); 264 265 if (!LookupCtx) { 266 if (isDependentScopeSpecifier(*SS)) { 267 // C++ [temp.res]p3: 268 // A qualified-id that refers to a type and in which the 269 // nested-name-specifier depends on a template-parameter (14.6.2) 270 // shall be prefixed by the keyword typename to indicate that the 271 // qualified-id denotes a type, forming an 272 // elaborated-type-specifier (7.1.5.3). 273 // 274 // We therefore do not perform any name lookup if the result would 275 // refer to a member of an unknown specialization. 276 if (!isClassName && !IsCtorOrDtorName) 277 return nullptr; 278 279 // We know from the grammar that this name refers to a type, 280 // so build a dependent node to describe the type. 281 if (WantNontrivialTypeSourceInfo) 282 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 283 284 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 285 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 286 II, NameLoc); 287 return ParsedType::make(T); 288 } 289 290 return nullptr; 291 } 292 293 if (!LookupCtx->isDependentContext() && 294 RequireCompleteDeclContext(*SS, LookupCtx)) 295 return nullptr; 296 } 297 298 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 299 // lookup for class-names. 300 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 301 LookupOrdinaryName; 302 LookupResult Result(*this, &II, NameLoc, Kind); 303 if (LookupCtx) { 304 // Perform "qualified" name lookup into the declaration context we 305 // computed, which is either the type of the base of a member access 306 // expression or the declaration context associated with a prior 307 // nested-name-specifier. 308 LookupQualifiedName(Result, LookupCtx); 309 310 if (ObjectTypePtr && Result.empty()) { 311 // C++ [basic.lookup.classref]p3: 312 // If the unqualified-id is ~type-name, the type-name is looked up 313 // in the context of the entire postfix-expression. If the type T of 314 // the object expression is of a class type C, the type-name is also 315 // looked up in the scope of class C. At least one of the lookups shall 316 // find a name that refers to (possibly cv-qualified) T. 317 LookupName(Result, S); 318 } 319 } else { 320 // Perform unqualified name lookup. 321 LookupName(Result, S); 322 323 // For unqualified lookup in a class template in MSVC mode, look into 324 // dependent base classes where the primary class template is known. 325 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 326 if (ParsedType TypeInBase = 327 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 328 return TypeInBase; 329 } 330 } 331 332 NamedDecl *IIDecl = nullptr; 333 switch (Result.getResultKind()) { 334 case LookupResult::NotFound: 335 case LookupResult::NotFoundInCurrentInstantiation: 336 if (CorrectedII) { 337 TypoCorrection Correction = CorrectTypo( 338 Result.getLookupNameInfo(), Kind, S, SS, 339 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 340 CTK_ErrorRecovery); 341 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 342 TemplateTy Template; 343 bool MemberOfUnknownSpecialization; 344 UnqualifiedId TemplateName; 345 TemplateName.setIdentifier(NewII, NameLoc); 346 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 347 CXXScopeSpec NewSS, *NewSSPtr = SS; 348 if (SS && NNS) { 349 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 350 NewSSPtr = &NewSS; 351 } 352 if (Correction && (NNS || NewII != &II) && 353 // Ignore a correction to a template type as the to-be-corrected 354 // identifier is not a template (typo correction for template names 355 // is handled elsewhere). 356 !(getLangOpts().CPlusPlus && NewSSPtr && 357 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 358 Template, MemberOfUnknownSpecialization))) { 359 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 360 isClassName, HasTrailingDot, ObjectTypePtr, 361 IsCtorOrDtorName, 362 WantNontrivialTypeSourceInfo); 363 if (Ty) { 364 diagnoseTypo(Correction, 365 PDiag(diag::err_unknown_type_or_class_name_suggest) 366 << Result.getLookupName() << isClassName); 367 if (SS && NNS) 368 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 369 *CorrectedII = NewII; 370 return Ty; 371 } 372 } 373 } 374 // If typo correction failed or was not performed, fall through 375 case LookupResult::FoundOverloaded: 376 case LookupResult::FoundUnresolvedValue: 377 Result.suppressDiagnostics(); 378 return nullptr; 379 380 case LookupResult::Ambiguous: 381 // Recover from type-hiding ambiguities by hiding the type. We'll 382 // do the lookup again when looking for an object, and we can 383 // diagnose the error then. If we don't do this, then the error 384 // about hiding the type will be immediately followed by an error 385 // that only makes sense if the identifier was treated like a type. 386 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 387 Result.suppressDiagnostics(); 388 return nullptr; 389 } 390 391 // Look to see if we have a type anywhere in the list of results. 392 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 393 Res != ResEnd; ++Res) { 394 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 395 if (!IIDecl || 396 (*Res)->getLocation().getRawEncoding() < 397 IIDecl->getLocation().getRawEncoding()) 398 IIDecl = *Res; 399 } 400 } 401 402 if (!IIDecl) { 403 // None of the entities we found is a type, so there is no way 404 // to even assume that the result is a type. In this case, don't 405 // complain about the ambiguity. The parser will either try to 406 // perform this lookup again (e.g., as an object name), which 407 // will produce the ambiguity, or will complain that it expected 408 // a type name. 409 Result.suppressDiagnostics(); 410 return nullptr; 411 } 412 413 // We found a type within the ambiguous lookup; diagnose the 414 // ambiguity and then return that type. This might be the right 415 // answer, or it might not be, but it suppresses any attempt to 416 // perform the name lookup again. 417 break; 418 419 case LookupResult::Found: 420 IIDecl = Result.getFoundDecl(); 421 break; 422 } 423 424 assert(IIDecl && "Didn't find decl"); 425 426 QualType T; 427 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 428 DiagnoseUseOfDecl(IIDecl, NameLoc); 429 430 T = Context.getTypeDeclType(TD); 431 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 432 433 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 434 // constructor or destructor name (in such a case, the scope specifier 435 // will be attached to the enclosing Expr or Decl node). 436 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 437 if (WantNontrivialTypeSourceInfo) { 438 // Construct a type with type-source information. 439 TypeLocBuilder Builder; 440 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 441 442 T = getElaboratedType(ETK_None, *SS, T); 443 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 444 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 445 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 446 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 447 } else { 448 T = getElaboratedType(ETK_None, *SS, T); 449 } 450 } 451 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 452 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 453 if (!HasTrailingDot) 454 T = Context.getObjCInterfaceType(IDecl); 455 } 456 457 if (T.isNull()) { 458 // If it's not plausibly a type, suppress diagnostics. 459 Result.suppressDiagnostics(); 460 return nullptr; 461 } 462 return ParsedType::make(T); 463 } 464 465 // Builds a fake NNS for the given decl context. 466 static NestedNameSpecifier * 467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 468 for (;; DC = DC->getLookupParent()) { 469 DC = DC->getPrimaryContext(); 470 auto *ND = dyn_cast<NamespaceDecl>(DC); 471 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 472 return NestedNameSpecifier::Create(Context, nullptr, ND); 473 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 474 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 475 RD->getTypeForDecl()); 476 else if (isa<TranslationUnitDecl>(DC)) 477 return NestedNameSpecifier::GlobalSpecifier(Context); 478 } 479 llvm_unreachable("something isn't in TU scope?"); 480 } 481 482 /// Find the parent class with dependent bases of the innermost enclosing method 483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 484 /// up allowing unqualified dependent type names at class-level, which MSVC 485 /// correctly rejects. 486 static const CXXRecordDecl * 487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 488 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 489 DC = DC->getPrimaryContext(); 490 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 491 if (MD->getParent()->hasAnyDependentBases()) 492 return MD->getParent(); 493 } 494 return nullptr; 495 } 496 497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 498 SourceLocation NameLoc, 499 bool IsTemplateTypeArg) { 500 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 501 502 NestedNameSpecifier *NNS = nullptr; 503 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 504 // If we weren't able to parse a default template argument, delay lookup 505 // until instantiation time by making a non-dependent DependentTypeName. We 506 // pretend we saw a NestedNameSpecifier referring to the current scope, and 507 // lookup is retried. 508 // FIXME: This hurts our diagnostic quality, since we get errors like "no 509 // type named 'Foo' in 'current_namespace'" when the user didn't write any 510 // name specifiers. 511 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 512 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 513 } else if (const CXXRecordDecl *RD = 514 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 515 // Build a DependentNameType that will perform lookup into RD at 516 // instantiation time. 517 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 518 RD->getTypeForDecl()); 519 520 // Diagnose that this identifier was undeclared, and retry the lookup during 521 // template instantiation. 522 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 523 << RD; 524 } else { 525 // This is not a situation that we should recover from. 526 return ParsedType(); 527 } 528 529 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 530 531 // Build type location information. We synthesized the qualifier, so we have 532 // to build a fake NestedNameSpecifierLoc. 533 NestedNameSpecifierLocBuilder NNSLocBuilder; 534 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 535 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 536 537 TypeLocBuilder Builder; 538 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 539 DepTL.setNameLoc(NameLoc); 540 DepTL.setElaboratedKeywordLoc(SourceLocation()); 541 DepTL.setQualifierLoc(QualifierLoc); 542 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 543 } 544 545 /// isTagName() - This method is called *for error recovery purposes only* 546 /// to determine if the specified name is a valid tag name ("struct foo"). If 547 /// so, this returns the TST for the tag corresponding to it (TST_enum, 548 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 549 /// cases in C where the user forgot to specify the tag. 550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 551 // Do a tag name lookup in this scope. 552 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 553 LookupName(R, S, false); 554 R.suppressDiagnostics(); 555 if (R.getResultKind() == LookupResult::Found) 556 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 557 switch (TD->getTagKind()) { 558 case TTK_Struct: return DeclSpec::TST_struct; 559 case TTK_Interface: return DeclSpec::TST_interface; 560 case TTK_Union: return DeclSpec::TST_union; 561 case TTK_Class: return DeclSpec::TST_class; 562 case TTK_Enum: return DeclSpec::TST_enum; 563 } 564 } 565 566 return DeclSpec::TST_unspecified; 567 } 568 569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 571 /// then downgrade the missing typename error to a warning. 572 /// This is needed for MSVC compatibility; Example: 573 /// @code 574 /// template<class T> class A { 575 /// public: 576 /// typedef int TYPE; 577 /// }; 578 /// template<class T> class B : public A<T> { 579 /// public: 580 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 581 /// }; 582 /// @endcode 583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 584 if (CurContext->isRecord()) { 585 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 586 return true; 587 588 const Type *Ty = SS->getScopeRep()->getAsType(); 589 590 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 591 for (const auto &Base : RD->bases()) 592 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 593 return true; 594 return S->isFunctionPrototypeScope(); 595 } 596 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 597 } 598 599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 600 SourceLocation IILoc, 601 Scope *S, 602 CXXScopeSpec *SS, 603 ParsedType &SuggestedType, 604 bool AllowClassTemplates) { 605 // We don't have anything to suggest (yet). 606 SuggestedType = nullptr; 607 608 // There may have been a typo in the name of the type. Look up typo 609 // results, in case we have something that we can suggest. 610 if (TypoCorrection Corrected = 611 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 612 llvm::make_unique<TypeNameValidatorCCC>( 613 false, false, AllowClassTemplates), 614 CTK_ErrorRecovery)) { 615 if (Corrected.isKeyword()) { 616 // We corrected to a keyword. 617 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 618 II = Corrected.getCorrectionAsIdentifierInfo(); 619 } else { 620 // We found a similarly-named type or interface; suggest that. 621 if (!SS || !SS->isSet()) { 622 diagnoseTypo(Corrected, 623 PDiag(diag::err_unknown_typename_suggest) << II); 624 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 625 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 626 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 627 II->getName().equals(CorrectedStr); 628 diagnoseTypo(Corrected, 629 PDiag(diag::err_unknown_nested_typename_suggest) 630 << II << DC << DroppedSpecifier << SS->getRange()); 631 } else { 632 llvm_unreachable("could not have corrected a typo here"); 633 } 634 635 CXXScopeSpec tmpSS; 636 if (Corrected.getCorrectionSpecifier()) 637 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 638 SourceRange(IILoc)); 639 SuggestedType = 640 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 641 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 642 /*IsCtorOrDtorName=*/false, 643 /*NonTrivialTypeSourceInfo=*/true); 644 } 645 return; 646 } 647 648 if (getLangOpts().CPlusPlus) { 649 // See if II is a class template that the user forgot to pass arguments to. 650 UnqualifiedId Name; 651 Name.setIdentifier(II, IILoc); 652 CXXScopeSpec EmptySS; 653 TemplateTy TemplateResult; 654 bool MemberOfUnknownSpecialization; 655 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 656 Name, nullptr, true, TemplateResult, 657 MemberOfUnknownSpecialization) == TNK_Type_template) { 658 TemplateName TplName = TemplateResult.get(); 659 Diag(IILoc, diag::err_template_missing_args) << TplName; 660 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 661 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 662 << TplDecl->getTemplateParameters()->getSourceRange(); 663 } 664 return; 665 } 666 } 667 668 // FIXME: Should we move the logic that tries to recover from a missing tag 669 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 670 671 if (!SS || (!SS->isSet() && !SS->isInvalid())) 672 Diag(IILoc, diag::err_unknown_typename) << II; 673 else if (DeclContext *DC = computeDeclContext(*SS, false)) 674 Diag(IILoc, diag::err_typename_nested_not_found) 675 << II << DC << SS->getRange(); 676 else if (isDependentScopeSpecifier(*SS)) { 677 unsigned DiagID = diag::err_typename_missing; 678 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 679 DiagID = diag::ext_typename_missing; 680 681 Diag(SS->getRange().getBegin(), DiagID) 682 << SS->getScopeRep() << II->getName() 683 << SourceRange(SS->getRange().getBegin(), IILoc) 684 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 685 SuggestedType = ActOnTypenameType(S, SourceLocation(), 686 *SS, *II, IILoc).get(); 687 } else { 688 assert(SS && SS->isInvalid() && 689 "Invalid scope specifier has already been diagnosed"); 690 } 691 } 692 693 /// \brief Determine whether the given result set contains either a type name 694 /// or 695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 696 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 697 NextToken.is(tok::less); 698 699 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 700 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 701 return true; 702 703 if (CheckTemplate && isa<TemplateDecl>(*I)) 704 return true; 705 } 706 707 return false; 708 } 709 710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 711 Scope *S, CXXScopeSpec &SS, 712 IdentifierInfo *&Name, 713 SourceLocation NameLoc) { 714 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 715 SemaRef.LookupParsedName(R, S, &SS); 716 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 717 StringRef FixItTagName; 718 switch (Tag->getTagKind()) { 719 case TTK_Class: 720 FixItTagName = "class "; 721 break; 722 723 case TTK_Enum: 724 FixItTagName = "enum "; 725 break; 726 727 case TTK_Struct: 728 FixItTagName = "struct "; 729 break; 730 731 case TTK_Interface: 732 FixItTagName = "__interface "; 733 break; 734 735 case TTK_Union: 736 FixItTagName = "union "; 737 break; 738 } 739 740 StringRef TagName = FixItTagName.drop_back(); 741 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 742 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 743 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 744 745 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 746 I != IEnd; ++I) 747 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 748 << Name << TagName; 749 750 // Replace lookup results with just the tag decl. 751 Result.clear(Sema::LookupTagName); 752 SemaRef.LookupParsedName(Result, S, &SS); 753 return true; 754 } 755 756 return false; 757 } 758 759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 761 QualType T, SourceLocation NameLoc) { 762 ASTContext &Context = S.Context; 763 764 TypeLocBuilder Builder; 765 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 766 767 T = S.getElaboratedType(ETK_None, SS, T); 768 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 769 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 770 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 771 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 772 } 773 774 Sema::NameClassification 775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 776 SourceLocation NameLoc, const Token &NextToken, 777 bool IsAddressOfOperand, 778 std::unique_ptr<CorrectionCandidateCallback> CCC) { 779 DeclarationNameInfo NameInfo(Name, NameLoc); 780 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 781 782 if (NextToken.is(tok::coloncolon)) { 783 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 784 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 785 } 786 787 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 788 LookupParsedName(Result, S, &SS, !CurMethod); 789 790 // For unqualified lookup in a class template in MSVC mode, look into 791 // dependent base classes where the primary class template is known. 792 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 793 if (ParsedType TypeInBase = 794 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 795 return TypeInBase; 796 } 797 798 // Perform lookup for Objective-C instance variables (including automatically 799 // synthesized instance variables), if we're in an Objective-C method. 800 // FIXME: This lookup really, really needs to be folded in to the normal 801 // unqualified lookup mechanism. 802 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 803 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 804 if (E.get() || E.isInvalid()) 805 return E; 806 } 807 808 bool SecondTry = false; 809 bool IsFilteredTemplateName = false; 810 811 Corrected: 812 switch (Result.getResultKind()) { 813 case LookupResult::NotFound: 814 // If an unqualified-id is followed by a '(', then we have a function 815 // call. 816 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 817 // In C++, this is an ADL-only call. 818 // FIXME: Reference? 819 if (getLangOpts().CPlusPlus) 820 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 821 822 // C90 6.3.2.2: 823 // If the expression that precedes the parenthesized argument list in a 824 // function call consists solely of an identifier, and if no 825 // declaration is visible for this identifier, the identifier is 826 // implicitly declared exactly as if, in the innermost block containing 827 // the function call, the declaration 828 // 829 // extern int identifier (); 830 // 831 // appeared. 832 // 833 // We also allow this in C99 as an extension. 834 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 835 Result.addDecl(D); 836 Result.resolveKind(); 837 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 838 } 839 } 840 841 // In C, we first see whether there is a tag type by the same name, in 842 // which case it's likely that the user just forgot to write "enum", 843 // "struct", or "union". 844 if (!getLangOpts().CPlusPlus && !SecondTry && 845 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 846 break; 847 } 848 849 // Perform typo correction to determine if there is another name that is 850 // close to this name. 851 if (!SecondTry && CCC) { 852 SecondTry = true; 853 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 854 Result.getLookupKind(), S, 855 &SS, std::move(CCC), 856 CTK_ErrorRecovery)) { 857 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 858 unsigned QualifiedDiag = diag::err_no_member_suggest; 859 860 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 861 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 862 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 863 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 864 UnqualifiedDiag = diag::err_no_template_suggest; 865 QualifiedDiag = diag::err_no_member_template_suggest; 866 } else if (UnderlyingFirstDecl && 867 (isa<TypeDecl>(UnderlyingFirstDecl) || 868 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 869 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 870 UnqualifiedDiag = diag::err_unknown_typename_suggest; 871 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 872 } 873 874 if (SS.isEmpty()) { 875 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 876 } else {// FIXME: is this even reachable? Test it. 877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 878 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 879 Name->getName().equals(CorrectedStr); 880 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 881 << Name << computeDeclContext(SS, false) 882 << DroppedSpecifier << SS.getRange()); 883 } 884 885 // Update the name, so that the caller has the new name. 886 Name = Corrected.getCorrectionAsIdentifierInfo(); 887 888 // Typo correction corrected to a keyword. 889 if (Corrected.isKeyword()) 890 return Name; 891 892 // Also update the LookupResult... 893 // FIXME: This should probably go away at some point 894 Result.clear(); 895 Result.setLookupName(Corrected.getCorrection()); 896 if (FirstDecl) 897 Result.addDecl(FirstDecl); 898 899 // If we found an Objective-C instance variable, let 900 // LookupInObjCMethod build the appropriate expression to 901 // reference the ivar. 902 // FIXME: This is a gross hack. 903 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 904 Result.clear(); 905 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 906 return E; 907 } 908 909 goto Corrected; 910 } 911 } 912 913 // We failed to correct; just fall through and let the parser deal with it. 914 Result.suppressDiagnostics(); 915 return NameClassification::Unknown(); 916 917 case LookupResult::NotFoundInCurrentInstantiation: { 918 // We performed name lookup into the current instantiation, and there were 919 // dependent bases, so we treat this result the same way as any other 920 // dependent nested-name-specifier. 921 922 // C++ [temp.res]p2: 923 // A name used in a template declaration or definition and that is 924 // dependent on a template-parameter is assumed not to name a type 925 // unless the applicable name lookup finds a type name or the name is 926 // qualified by the keyword typename. 927 // 928 // FIXME: If the next token is '<', we might want to ask the parser to 929 // perform some heroics to see if we actually have a 930 // template-argument-list, which would indicate a missing 'template' 931 // keyword here. 932 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 933 NameInfo, IsAddressOfOperand, 934 /*TemplateArgs=*/nullptr); 935 } 936 937 case LookupResult::Found: 938 case LookupResult::FoundOverloaded: 939 case LookupResult::FoundUnresolvedValue: 940 break; 941 942 case LookupResult::Ambiguous: 943 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 944 hasAnyAcceptableTemplateNames(Result)) { 945 // C++ [temp.local]p3: 946 // A lookup that finds an injected-class-name (10.2) can result in an 947 // ambiguity in certain cases (for example, if it is found in more than 948 // one base class). If all of the injected-class-names that are found 949 // refer to specializations of the same class template, and if the name 950 // is followed by a template-argument-list, the reference refers to the 951 // class template itself and not a specialization thereof, and is not 952 // ambiguous. 953 // 954 // This filtering can make an ambiguous result into an unambiguous one, 955 // so try again after filtering out template names. 956 FilterAcceptableTemplateNames(Result); 957 if (!Result.isAmbiguous()) { 958 IsFilteredTemplateName = true; 959 break; 960 } 961 } 962 963 // Diagnose the ambiguity and return an error. 964 return NameClassification::Error(); 965 } 966 967 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 968 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 969 // C++ [temp.names]p3: 970 // After name lookup (3.4) finds that a name is a template-name or that 971 // an operator-function-id or a literal- operator-id refers to a set of 972 // overloaded functions any member of which is a function template if 973 // this is followed by a <, the < is always taken as the delimiter of a 974 // template-argument-list and never as the less-than operator. 975 if (!IsFilteredTemplateName) 976 FilterAcceptableTemplateNames(Result); 977 978 if (!Result.empty()) { 979 bool IsFunctionTemplate; 980 bool IsVarTemplate; 981 TemplateName Template; 982 if (Result.end() - Result.begin() > 1) { 983 IsFunctionTemplate = true; 984 Template = Context.getOverloadedTemplateName(Result.begin(), 985 Result.end()); 986 } else { 987 TemplateDecl *TD 988 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 989 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 990 IsVarTemplate = isa<VarTemplateDecl>(TD); 991 992 if (SS.isSet() && !SS.isInvalid()) 993 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 994 /*TemplateKeyword=*/false, 995 TD); 996 else 997 Template = TemplateName(TD); 998 } 999 1000 if (IsFunctionTemplate) { 1001 // Function templates always go through overload resolution, at which 1002 // point we'll perform the various checks (e.g., accessibility) we need 1003 // to based on which function we selected. 1004 Result.suppressDiagnostics(); 1005 1006 return NameClassification::FunctionTemplate(Template); 1007 } 1008 1009 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1010 : NameClassification::TypeTemplate(Template); 1011 } 1012 } 1013 1014 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1015 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1018 QualType T = Context.getTypeDeclType(Type); 1019 if (SS.isNotEmpty()) 1020 return buildNestedType(*this, SS, T, NameLoc); 1021 return ParsedType::make(T); 1022 } 1023 1024 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1025 if (!Class) { 1026 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1027 if (ObjCCompatibleAliasDecl *Alias = 1028 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1029 Class = Alias->getClassInterface(); 1030 } 1031 1032 if (Class) { 1033 DiagnoseUseOfDecl(Class, NameLoc); 1034 1035 if (NextToken.is(tok::period)) { 1036 // Interface. <something> is parsed as a property reference expression. 1037 // Just return "unknown" as a fall-through for now. 1038 Result.suppressDiagnostics(); 1039 return NameClassification::Unknown(); 1040 } 1041 1042 QualType T = Context.getObjCInterfaceType(Class); 1043 return ParsedType::make(T); 1044 } 1045 1046 // We can have a type template here if we're classifying a template argument. 1047 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1048 return NameClassification::TypeTemplate( 1049 TemplateName(cast<TemplateDecl>(FirstDecl))); 1050 1051 // Check for a tag type hidden by a non-type decl in a few cases where it 1052 // seems likely a type is wanted instead of the non-type that was found. 1053 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1054 if ((NextToken.is(tok::identifier) || 1055 (NextIsOp && 1056 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1057 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1058 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1059 DiagnoseUseOfDecl(Type, NameLoc); 1060 QualType T = Context.getTypeDeclType(Type); 1061 if (SS.isNotEmpty()) 1062 return buildNestedType(*this, SS, T, NameLoc); 1063 return ParsedType::make(T); 1064 } 1065 1066 if (FirstDecl->isCXXClassMember()) 1067 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1068 nullptr, S); 1069 1070 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1071 return BuildDeclarationNameExpr(SS, Result, ADL); 1072 } 1073 1074 // Determines the context to return to after temporarily entering a 1075 // context. This depends in an unnecessarily complicated way on the 1076 // exact ordering of callbacks from the parser. 1077 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1078 1079 // Functions defined inline within classes aren't parsed until we've 1080 // finished parsing the top-level class, so the top-level class is 1081 // the context we'll need to return to. 1082 // A Lambda call operator whose parent is a class must not be treated 1083 // as an inline member function. A Lambda can be used legally 1084 // either as an in-class member initializer or a default argument. These 1085 // are parsed once the class has been marked complete and so the containing 1086 // context would be the nested class (when the lambda is defined in one); 1087 // If the class is not complete, then the lambda is being used in an 1088 // ill-formed fashion (such as to specify the width of a bit-field, or 1089 // in an array-bound) - in which case we still want to return the 1090 // lexically containing DC (which could be a nested class). 1091 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1092 DC = DC->getLexicalParent(); 1093 1094 // A function not defined within a class will always return to its 1095 // lexical context. 1096 if (!isa<CXXRecordDecl>(DC)) 1097 return DC; 1098 1099 // A C++ inline method/friend is parsed *after* the topmost class 1100 // it was declared in is fully parsed ("complete"); the topmost 1101 // class is the context we need to return to. 1102 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1103 DC = RD; 1104 1105 // Return the declaration context of the topmost class the inline method is 1106 // declared in. 1107 return DC; 1108 } 1109 1110 return DC->getLexicalParent(); 1111 } 1112 1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1114 assert(getContainingDC(DC) == CurContext && 1115 "The next DeclContext should be lexically contained in the current one."); 1116 CurContext = DC; 1117 S->setEntity(DC); 1118 } 1119 1120 void Sema::PopDeclContext() { 1121 assert(CurContext && "DeclContext imbalance!"); 1122 1123 CurContext = getContainingDC(CurContext); 1124 assert(CurContext && "Popped translation unit!"); 1125 } 1126 1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1128 Decl *D) { 1129 // Unlike PushDeclContext, the context to which we return is not necessarily 1130 // the containing DC of TD, because the new context will be some pre-existing 1131 // TagDecl definition instead of a fresh one. 1132 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1133 CurContext = cast<TagDecl>(D)->getDefinition(); 1134 assert(CurContext && "skipping definition of undefined tag"); 1135 // Start lookups from the parent of the current context; we don't want to look 1136 // into the pre-existing complete definition. 1137 S->setEntity(CurContext->getLookupParent()); 1138 return Result; 1139 } 1140 1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1142 CurContext = static_cast<decltype(CurContext)>(Context); 1143 } 1144 1145 /// EnterDeclaratorContext - Used when we must lookup names in the context 1146 /// of a declarator's nested name specifier. 1147 /// 1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1149 // C++0x [basic.lookup.unqual]p13: 1150 // A name used in the definition of a static data member of class 1151 // X (after the qualified-id of the static member) is looked up as 1152 // if the name was used in a member function of X. 1153 // C++0x [basic.lookup.unqual]p14: 1154 // If a variable member of a namespace is defined outside of the 1155 // scope of its namespace then any name used in the definition of 1156 // the variable member (after the declarator-id) is looked up as 1157 // if the definition of the variable member occurred in its 1158 // namespace. 1159 // Both of these imply that we should push a scope whose context 1160 // is the semantic context of the declaration. We can't use 1161 // PushDeclContext here because that context is not necessarily 1162 // lexically contained in the current context. Fortunately, 1163 // the containing scope should have the appropriate information. 1164 1165 assert(!S->getEntity() && "scope already has entity"); 1166 1167 #ifndef NDEBUG 1168 Scope *Ancestor = S->getParent(); 1169 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1170 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1171 #endif 1172 1173 CurContext = DC; 1174 S->setEntity(DC); 1175 } 1176 1177 void Sema::ExitDeclaratorContext(Scope *S) { 1178 assert(S->getEntity() == CurContext && "Context imbalance!"); 1179 1180 // Switch back to the lexical context. The safety of this is 1181 // enforced by an assert in EnterDeclaratorContext. 1182 Scope *Ancestor = S->getParent(); 1183 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1184 CurContext = Ancestor->getEntity(); 1185 1186 // We don't need to do anything with the scope, which is going to 1187 // disappear. 1188 } 1189 1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1191 // We assume that the caller has already called 1192 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1193 FunctionDecl *FD = D->getAsFunction(); 1194 if (!FD) 1195 return; 1196 1197 // Same implementation as PushDeclContext, but enters the context 1198 // from the lexical parent, rather than the top-level class. 1199 assert(CurContext == FD->getLexicalParent() && 1200 "The next DeclContext should be lexically contained in the current one."); 1201 CurContext = FD; 1202 S->setEntity(CurContext); 1203 1204 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1205 ParmVarDecl *Param = FD->getParamDecl(P); 1206 // If the parameter has an identifier, then add it to the scope 1207 if (Param->getIdentifier()) { 1208 S->AddDecl(Param); 1209 IdResolver.AddDecl(Param); 1210 } 1211 } 1212 } 1213 1214 void Sema::ActOnExitFunctionContext() { 1215 // Same implementation as PopDeclContext, but returns to the lexical parent, 1216 // rather than the top-level class. 1217 assert(CurContext && "DeclContext imbalance!"); 1218 CurContext = CurContext->getLexicalParent(); 1219 assert(CurContext && "Popped translation unit!"); 1220 } 1221 1222 /// \brief Determine whether we allow overloading of the function 1223 /// PrevDecl with another declaration. 1224 /// 1225 /// This routine determines whether overloading is possible, not 1226 /// whether some new function is actually an overload. It will return 1227 /// true in C++ (where we can always provide overloads) or, as an 1228 /// extension, in C when the previous function is already an 1229 /// overloaded function declaration or has the "overloadable" 1230 /// attribute. 1231 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1232 ASTContext &Context) { 1233 if (Context.getLangOpts().CPlusPlus) 1234 return true; 1235 1236 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1237 return true; 1238 1239 return (Previous.getResultKind() == LookupResult::Found 1240 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1241 } 1242 1243 /// Add this decl to the scope shadowed decl chains. 1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1245 // Move up the scope chain until we find the nearest enclosing 1246 // non-transparent context. The declaration will be introduced into this 1247 // scope. 1248 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1249 S = S->getParent(); 1250 1251 // Add scoped declarations into their context, so that they can be 1252 // found later. Declarations without a context won't be inserted 1253 // into any context. 1254 if (AddToContext) 1255 CurContext->addDecl(D); 1256 1257 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1258 // are function-local declarations. 1259 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1260 !D->getDeclContext()->getRedeclContext()->Equals( 1261 D->getLexicalDeclContext()->getRedeclContext()) && 1262 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1263 return; 1264 1265 // Template instantiations should also not be pushed into scope. 1266 if (isa<FunctionDecl>(D) && 1267 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1268 return; 1269 1270 // If this replaces anything in the current scope, 1271 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1272 IEnd = IdResolver.end(); 1273 for (; I != IEnd; ++I) { 1274 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1275 S->RemoveDecl(*I); 1276 IdResolver.RemoveDecl(*I); 1277 1278 // Should only need to replace one decl. 1279 break; 1280 } 1281 } 1282 1283 S->AddDecl(D); 1284 1285 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1286 // Implicitly-generated labels may end up getting generated in an order that 1287 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1288 // the label at the appropriate place in the identifier chain. 1289 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1290 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1291 if (IDC == CurContext) { 1292 if (!S->isDeclScope(*I)) 1293 continue; 1294 } else if (IDC->Encloses(CurContext)) 1295 break; 1296 } 1297 1298 IdResolver.InsertDeclAfter(I, D); 1299 } else { 1300 IdResolver.AddDecl(D); 1301 } 1302 } 1303 1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1305 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1306 TUScope->AddDecl(D); 1307 } 1308 1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1310 bool AllowInlineNamespace) { 1311 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1312 } 1313 1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1315 DeclContext *TargetDC = DC->getPrimaryContext(); 1316 do { 1317 if (DeclContext *ScopeDC = S->getEntity()) 1318 if (ScopeDC->getPrimaryContext() == TargetDC) 1319 return S; 1320 } while ((S = S->getParent())); 1321 1322 return nullptr; 1323 } 1324 1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1326 DeclContext*, 1327 ASTContext&); 1328 1329 /// Filters out lookup results that don't fall within the given scope 1330 /// as determined by isDeclInScope. 1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1332 bool ConsiderLinkage, 1333 bool AllowInlineNamespace) { 1334 LookupResult::Filter F = R.makeFilter(); 1335 while (F.hasNext()) { 1336 NamedDecl *D = F.next(); 1337 1338 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1339 continue; 1340 1341 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1342 continue; 1343 1344 F.erase(); 1345 } 1346 1347 F.done(); 1348 } 1349 1350 static bool isUsingDecl(NamedDecl *D) { 1351 return isa<UsingShadowDecl>(D) || 1352 isa<UnresolvedUsingTypenameDecl>(D) || 1353 isa<UnresolvedUsingValueDecl>(D); 1354 } 1355 1356 /// Removes using shadow declarations from the lookup results. 1357 static void RemoveUsingDecls(LookupResult &R) { 1358 LookupResult::Filter F = R.makeFilter(); 1359 while (F.hasNext()) 1360 if (isUsingDecl(F.next())) 1361 F.erase(); 1362 1363 F.done(); 1364 } 1365 1366 /// \brief Check for this common pattern: 1367 /// @code 1368 /// class S { 1369 /// S(const S&); // DO NOT IMPLEMENT 1370 /// void operator=(const S&); // DO NOT IMPLEMENT 1371 /// }; 1372 /// @endcode 1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1374 // FIXME: Should check for private access too but access is set after we get 1375 // the decl here. 1376 if (D->doesThisDeclarationHaveABody()) 1377 return false; 1378 1379 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1380 return CD->isCopyConstructor(); 1381 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1382 return Method->isCopyAssignmentOperator(); 1383 return false; 1384 } 1385 1386 // We need this to handle 1387 // 1388 // typedef struct { 1389 // void *foo() { return 0; } 1390 // } A; 1391 // 1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1393 // for example. If 'A', foo will have external linkage. If we have '*A', 1394 // foo will have no linkage. Since we can't know until we get to the end 1395 // of the typedef, this function finds out if D might have non-external linkage. 1396 // Callers should verify at the end of the TU if it D has external linkage or 1397 // not. 1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1399 const DeclContext *DC = D->getDeclContext(); 1400 while (!DC->isTranslationUnit()) { 1401 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1402 if (!RD->hasNameForLinkage()) 1403 return true; 1404 } 1405 DC = DC->getParent(); 1406 } 1407 1408 return !D->isExternallyVisible(); 1409 } 1410 1411 // FIXME: This needs to be refactored; some other isInMainFile users want 1412 // these semantics. 1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1414 if (S.TUKind != TU_Complete) 1415 return false; 1416 return S.SourceMgr.isInMainFile(Loc); 1417 } 1418 1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1420 assert(D); 1421 1422 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1423 return false; 1424 1425 // Ignore all entities declared within templates, and out-of-line definitions 1426 // of members of class templates. 1427 if (D->getDeclContext()->isDependentContext() || 1428 D->getLexicalDeclContext()->isDependentContext()) 1429 return false; 1430 1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1432 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1433 return false; 1434 1435 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1436 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1437 return false; 1438 } else { 1439 // 'static inline' functions are defined in headers; don't warn. 1440 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1441 return false; 1442 } 1443 1444 if (FD->doesThisDeclarationHaveABody() && 1445 Context.DeclMustBeEmitted(FD)) 1446 return false; 1447 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1448 // Constants and utility variables are defined in headers with internal 1449 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1450 // like "inline".) 1451 if (!isMainFileLoc(*this, VD->getLocation())) 1452 return false; 1453 1454 if (Context.DeclMustBeEmitted(VD)) 1455 return false; 1456 1457 if (VD->isStaticDataMember() && 1458 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1459 return false; 1460 1461 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1462 return false; 1463 } else { 1464 return false; 1465 } 1466 1467 // Only warn for unused decls internal to the translation unit. 1468 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1469 // for inline functions defined in the main source file, for instance. 1470 return mightHaveNonExternalLinkage(D); 1471 } 1472 1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1474 if (!D) 1475 return; 1476 1477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1478 const FunctionDecl *First = FD->getFirstDecl(); 1479 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1480 return; // First should already be in the vector. 1481 } 1482 1483 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1484 const VarDecl *First = VD->getFirstDecl(); 1485 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1486 return; // First should already be in the vector. 1487 } 1488 1489 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1490 UnusedFileScopedDecls.push_back(D); 1491 } 1492 1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1494 if (D->isInvalidDecl()) 1495 return false; 1496 1497 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1498 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1499 return false; 1500 1501 if (isa<LabelDecl>(D)) 1502 return true; 1503 1504 // Except for labels, we only care about unused decls that are local to 1505 // functions. 1506 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1507 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1508 // For dependent types, the diagnostic is deferred. 1509 WithinFunction = 1510 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1511 if (!WithinFunction) 1512 return false; 1513 1514 if (isa<TypedefNameDecl>(D)) 1515 return true; 1516 1517 // White-list anything that isn't a local variable. 1518 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1519 return false; 1520 1521 // Types of valid local variables should be complete, so this should succeed. 1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1523 1524 // White-list anything with an __attribute__((unused)) type. 1525 const auto *Ty = VD->getType().getTypePtr(); 1526 1527 // Only look at the outermost level of typedef. 1528 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1529 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1530 return false; 1531 } 1532 1533 // If we failed to complete the type for some reason, or if the type is 1534 // dependent, don't diagnose the variable. 1535 if (Ty->isIncompleteType() || Ty->isDependentType()) 1536 return false; 1537 1538 // Look at the element type to ensure that the warning behaviour is 1539 // consistent for both scalars and arrays. 1540 Ty = Ty->getBaseElementTypeUnsafe(); 1541 1542 if (const TagType *TT = Ty->getAs<TagType>()) { 1543 const TagDecl *Tag = TT->getDecl(); 1544 if (Tag->hasAttr<UnusedAttr>()) 1545 return false; 1546 1547 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1548 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1549 return false; 1550 1551 if (const Expr *Init = VD->getInit()) { 1552 if (const ExprWithCleanups *Cleanups = 1553 dyn_cast<ExprWithCleanups>(Init)) 1554 Init = Cleanups->getSubExpr(); 1555 const CXXConstructExpr *Construct = 1556 dyn_cast<CXXConstructExpr>(Init); 1557 if (Construct && !Construct->isElidable()) { 1558 CXXConstructorDecl *CD = Construct->getConstructor(); 1559 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1560 return false; 1561 } 1562 } 1563 } 1564 } 1565 1566 // TODO: __attribute__((unused)) templates? 1567 } 1568 1569 return true; 1570 } 1571 1572 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1573 FixItHint &Hint) { 1574 if (isa<LabelDecl>(D)) { 1575 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1576 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1577 if (AfterColon.isInvalid()) 1578 return; 1579 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1580 getCharRange(D->getLocStart(), AfterColon)); 1581 } 1582 } 1583 1584 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1585 if (D->getTypeForDecl()->isDependentType()) 1586 return; 1587 1588 for (auto *TmpD : D->decls()) { 1589 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1590 DiagnoseUnusedDecl(T); 1591 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1592 DiagnoseUnusedNestedTypedefs(R); 1593 } 1594 } 1595 1596 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1597 /// unless they are marked attr(unused). 1598 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1599 if (!ShouldDiagnoseUnusedDecl(D)) 1600 return; 1601 1602 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1603 // typedefs can be referenced later on, so the diagnostics are emitted 1604 // at end-of-translation-unit. 1605 UnusedLocalTypedefNameCandidates.insert(TD); 1606 return; 1607 } 1608 1609 FixItHint Hint; 1610 GenerateFixForUnusedDecl(D, Context, Hint); 1611 1612 unsigned DiagID; 1613 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1614 DiagID = diag::warn_unused_exception_param; 1615 else if (isa<LabelDecl>(D)) 1616 DiagID = diag::warn_unused_label; 1617 else 1618 DiagID = diag::warn_unused_variable; 1619 1620 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1621 } 1622 1623 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1624 // Verify that we have no forward references left. If so, there was a goto 1625 // or address of a label taken, but no definition of it. Label fwd 1626 // definitions are indicated with a null substmt which is also not a resolved 1627 // MS inline assembly label name. 1628 bool Diagnose = false; 1629 if (L->isMSAsmLabel()) 1630 Diagnose = !L->isResolvedMSAsmLabel(); 1631 else 1632 Diagnose = L->getStmt() == nullptr; 1633 if (Diagnose) 1634 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1635 } 1636 1637 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1638 S->mergeNRVOIntoParent(); 1639 1640 if (S->decl_empty()) return; 1641 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1642 "Scope shouldn't contain decls!"); 1643 1644 for (auto *TmpD : S->decls()) { 1645 assert(TmpD && "This decl didn't get pushed??"); 1646 1647 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1648 NamedDecl *D = cast<NamedDecl>(TmpD); 1649 1650 if (!D->getDeclName()) continue; 1651 1652 // Diagnose unused variables in this scope. 1653 if (!S->hasUnrecoverableErrorOccurred()) { 1654 DiagnoseUnusedDecl(D); 1655 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1656 DiagnoseUnusedNestedTypedefs(RD); 1657 } 1658 1659 // If this was a forward reference to a label, verify it was defined. 1660 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1661 CheckPoppedLabel(LD, *this); 1662 1663 // Remove this name from our lexical scope, and warn on it if we haven't 1664 // already. 1665 IdResolver.RemoveDecl(D); 1666 auto ShadowI = ShadowingDecls.find(D); 1667 if (ShadowI != ShadowingDecls.end()) { 1668 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1669 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1670 << D << FD << FD->getParent(); 1671 Diag(FD->getLocation(), diag::note_previous_declaration); 1672 } 1673 ShadowingDecls.erase(ShadowI); 1674 } 1675 } 1676 } 1677 1678 /// \brief Look for an Objective-C class in the translation unit. 1679 /// 1680 /// \param Id The name of the Objective-C class we're looking for. If 1681 /// typo-correction fixes this name, the Id will be updated 1682 /// to the fixed name. 1683 /// 1684 /// \param IdLoc The location of the name in the translation unit. 1685 /// 1686 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1687 /// if there is no class with the given name. 1688 /// 1689 /// \returns The declaration of the named Objective-C class, or NULL if the 1690 /// class could not be found. 1691 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1692 SourceLocation IdLoc, 1693 bool DoTypoCorrection) { 1694 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1695 // creation from this context. 1696 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1697 1698 if (!IDecl && DoTypoCorrection) { 1699 // Perform typo correction at the given location, but only if we 1700 // find an Objective-C class name. 1701 if (TypoCorrection C = CorrectTypo( 1702 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1703 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1704 CTK_ErrorRecovery)) { 1705 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1706 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1707 Id = IDecl->getIdentifier(); 1708 } 1709 } 1710 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1711 // This routine must always return a class definition, if any. 1712 if (Def && Def->getDefinition()) 1713 Def = Def->getDefinition(); 1714 return Def; 1715 } 1716 1717 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1718 /// from S, where a non-field would be declared. This routine copes 1719 /// with the difference between C and C++ scoping rules in structs and 1720 /// unions. For example, the following code is well-formed in C but 1721 /// ill-formed in C++: 1722 /// @code 1723 /// struct S6 { 1724 /// enum { BAR } e; 1725 /// }; 1726 /// 1727 /// void test_S6() { 1728 /// struct S6 a; 1729 /// a.e = BAR; 1730 /// } 1731 /// @endcode 1732 /// For the declaration of BAR, this routine will return a different 1733 /// scope. The scope S will be the scope of the unnamed enumeration 1734 /// within S6. In C++, this routine will return the scope associated 1735 /// with S6, because the enumeration's scope is a transparent 1736 /// context but structures can contain non-field names. In C, this 1737 /// routine will return the translation unit scope, since the 1738 /// enumeration's scope is a transparent context and structures cannot 1739 /// contain non-field names. 1740 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1741 while (((S->getFlags() & Scope::DeclScope) == 0) || 1742 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1743 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1744 S = S->getParent(); 1745 return S; 1746 } 1747 1748 /// \brief Looks up the declaration of "struct objc_super" and 1749 /// saves it for later use in building builtin declaration of 1750 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1751 /// pre-existing declaration exists no action takes place. 1752 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1753 IdentifierInfo *II) { 1754 if (!II->isStr("objc_msgSendSuper")) 1755 return; 1756 ASTContext &Context = ThisSema.Context; 1757 1758 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1759 SourceLocation(), Sema::LookupTagName); 1760 ThisSema.LookupName(Result, S); 1761 if (Result.getResultKind() == LookupResult::Found) 1762 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1763 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1764 } 1765 1766 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1767 switch (Error) { 1768 case ASTContext::GE_None: 1769 return ""; 1770 case ASTContext::GE_Missing_stdio: 1771 return "stdio.h"; 1772 case ASTContext::GE_Missing_setjmp: 1773 return "setjmp.h"; 1774 case ASTContext::GE_Missing_ucontext: 1775 return "ucontext.h"; 1776 } 1777 llvm_unreachable("unhandled error kind"); 1778 } 1779 1780 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1781 /// file scope. lazily create a decl for it. ForRedeclaration is true 1782 /// if we're creating this built-in in anticipation of redeclaring the 1783 /// built-in. 1784 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1785 Scope *S, bool ForRedeclaration, 1786 SourceLocation Loc) { 1787 LookupPredefedObjCSuperType(*this, S, II); 1788 1789 ASTContext::GetBuiltinTypeError Error; 1790 QualType R = Context.GetBuiltinType(ID, Error); 1791 if (Error) { 1792 if (ForRedeclaration) 1793 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1794 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1795 return nullptr; 1796 } 1797 1798 if (!ForRedeclaration && 1799 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1800 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1801 Diag(Loc, diag::ext_implicit_lib_function_decl) 1802 << Context.BuiltinInfo.getName(ID) << R; 1803 if (Context.BuiltinInfo.getHeaderName(ID) && 1804 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1805 Diag(Loc, diag::note_include_header_or_declare) 1806 << Context.BuiltinInfo.getHeaderName(ID) 1807 << Context.BuiltinInfo.getName(ID); 1808 } 1809 1810 if (R.isNull()) 1811 return nullptr; 1812 1813 DeclContext *Parent = Context.getTranslationUnitDecl(); 1814 if (getLangOpts().CPlusPlus) { 1815 LinkageSpecDecl *CLinkageDecl = 1816 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1817 LinkageSpecDecl::lang_c, false); 1818 CLinkageDecl->setImplicit(); 1819 Parent->addDecl(CLinkageDecl); 1820 Parent = CLinkageDecl; 1821 } 1822 1823 FunctionDecl *New = FunctionDecl::Create(Context, 1824 Parent, 1825 Loc, Loc, II, R, /*TInfo=*/nullptr, 1826 SC_Extern, 1827 false, 1828 R->isFunctionProtoType()); 1829 New->setImplicit(); 1830 1831 // Create Decl objects for each parameter, adding them to the 1832 // FunctionDecl. 1833 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1834 SmallVector<ParmVarDecl*, 16> Params; 1835 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1836 ParmVarDecl *parm = 1837 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1838 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1839 SC_None, nullptr); 1840 parm->setScopeInfo(0, i); 1841 Params.push_back(parm); 1842 } 1843 New->setParams(Params); 1844 } 1845 1846 AddKnownFunctionAttributes(New); 1847 RegisterLocallyScopedExternCDecl(New, S); 1848 1849 // TUScope is the translation-unit scope to insert this function into. 1850 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1851 // relate Scopes to DeclContexts, and probably eliminate CurContext 1852 // entirely, but we're not there yet. 1853 DeclContext *SavedContext = CurContext; 1854 CurContext = Parent; 1855 PushOnScopeChains(New, TUScope); 1856 CurContext = SavedContext; 1857 return New; 1858 } 1859 1860 /// Typedef declarations don't have linkage, but they still denote the same 1861 /// entity if their types are the same. 1862 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1863 /// isSameEntity. 1864 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1865 TypedefNameDecl *Decl, 1866 LookupResult &Previous) { 1867 // This is only interesting when modules are enabled. 1868 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1869 return; 1870 1871 // Empty sets are uninteresting. 1872 if (Previous.empty()) 1873 return; 1874 1875 LookupResult::Filter Filter = Previous.makeFilter(); 1876 while (Filter.hasNext()) { 1877 NamedDecl *Old = Filter.next(); 1878 1879 // Non-hidden declarations are never ignored. 1880 if (S.isVisible(Old)) 1881 continue; 1882 1883 // Declarations of the same entity are not ignored, even if they have 1884 // different linkages. 1885 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1886 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1887 Decl->getUnderlyingType())) 1888 continue; 1889 1890 // If both declarations give a tag declaration a typedef name for linkage 1891 // purposes, then they declare the same entity. 1892 if (S.getLangOpts().CPlusPlus && 1893 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1894 Decl->getAnonDeclWithTypedefName()) 1895 continue; 1896 } 1897 1898 Filter.erase(); 1899 } 1900 1901 Filter.done(); 1902 } 1903 1904 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1905 QualType OldType; 1906 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1907 OldType = OldTypedef->getUnderlyingType(); 1908 else 1909 OldType = Context.getTypeDeclType(Old); 1910 QualType NewType = New->getUnderlyingType(); 1911 1912 if (NewType->isVariablyModifiedType()) { 1913 // Must not redefine a typedef with a variably-modified type. 1914 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1915 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1916 << Kind << NewType; 1917 if (Old->getLocation().isValid()) 1918 Diag(Old->getLocation(), diag::note_previous_definition); 1919 New->setInvalidDecl(); 1920 return true; 1921 } 1922 1923 if (OldType != NewType && 1924 !OldType->isDependentType() && 1925 !NewType->isDependentType() && 1926 !Context.hasSameType(OldType, NewType)) { 1927 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1928 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1929 << Kind << NewType << OldType; 1930 if (Old->getLocation().isValid()) 1931 Diag(Old->getLocation(), diag::note_previous_definition); 1932 New->setInvalidDecl(); 1933 return true; 1934 } 1935 return false; 1936 } 1937 1938 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1939 /// same name and scope as a previous declaration 'Old'. Figure out 1940 /// how to resolve this situation, merging decls or emitting 1941 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1942 /// 1943 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1944 LookupResult &OldDecls) { 1945 // If the new decl is known invalid already, don't bother doing any 1946 // merging checks. 1947 if (New->isInvalidDecl()) return; 1948 1949 // Allow multiple definitions for ObjC built-in typedefs. 1950 // FIXME: Verify the underlying types are equivalent! 1951 if (getLangOpts().ObjC1) { 1952 const IdentifierInfo *TypeID = New->getIdentifier(); 1953 switch (TypeID->getLength()) { 1954 default: break; 1955 case 2: 1956 { 1957 if (!TypeID->isStr("id")) 1958 break; 1959 QualType T = New->getUnderlyingType(); 1960 if (!T->isPointerType()) 1961 break; 1962 if (!T->isVoidPointerType()) { 1963 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1964 if (!PT->isStructureType()) 1965 break; 1966 } 1967 Context.setObjCIdRedefinitionType(T); 1968 // Install the built-in type for 'id', ignoring the current definition. 1969 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1970 return; 1971 } 1972 case 5: 1973 if (!TypeID->isStr("Class")) 1974 break; 1975 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1976 // Install the built-in type for 'Class', ignoring the current definition. 1977 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1978 return; 1979 case 3: 1980 if (!TypeID->isStr("SEL")) 1981 break; 1982 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1983 // Install the built-in type for 'SEL', ignoring the current definition. 1984 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1985 return; 1986 } 1987 // Fall through - the typedef name was not a builtin type. 1988 } 1989 1990 // Verify the old decl was also a type. 1991 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1992 if (!Old) { 1993 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1994 << New->getDeclName(); 1995 1996 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1997 if (OldD->getLocation().isValid()) 1998 Diag(OldD->getLocation(), diag::note_previous_definition); 1999 2000 return New->setInvalidDecl(); 2001 } 2002 2003 // If the old declaration is invalid, just give up here. 2004 if (Old->isInvalidDecl()) 2005 return New->setInvalidDecl(); 2006 2007 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2008 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2009 auto *NewTag = New->getAnonDeclWithTypedefName(); 2010 NamedDecl *Hidden = nullptr; 2011 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2012 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2013 !hasVisibleDefinition(OldTag, &Hidden)) { 2014 // There is a definition of this tag, but it is not visible. Use it 2015 // instead of our tag. 2016 New->setTypeForDecl(OldTD->getTypeForDecl()); 2017 if (OldTD->isModed()) 2018 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2019 OldTD->getUnderlyingType()); 2020 else 2021 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2022 2023 // Make the old tag definition visible. 2024 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2025 2026 // If this was an unscoped enumeration, yank all of its enumerators 2027 // out of the scope. 2028 if (isa<EnumDecl>(NewTag)) { 2029 Scope *EnumScope = getNonFieldDeclScope(S); 2030 for (auto *D : NewTag->decls()) { 2031 auto *ED = cast<EnumConstantDecl>(D); 2032 assert(EnumScope->isDeclScope(ED)); 2033 EnumScope->RemoveDecl(ED); 2034 IdResolver.RemoveDecl(ED); 2035 ED->getLexicalDeclContext()->removeDecl(ED); 2036 } 2037 } 2038 } 2039 } 2040 2041 // If the typedef types are not identical, reject them in all languages and 2042 // with any extensions enabled. 2043 if (isIncompatibleTypedef(Old, New)) 2044 return; 2045 2046 // The types match. Link up the redeclaration chain and merge attributes if 2047 // the old declaration was a typedef. 2048 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2049 New->setPreviousDecl(Typedef); 2050 mergeDeclAttributes(New, Old); 2051 } 2052 2053 if (getLangOpts().MicrosoftExt) 2054 return; 2055 2056 if (getLangOpts().CPlusPlus) { 2057 // C++ [dcl.typedef]p2: 2058 // In a given non-class scope, a typedef specifier can be used to 2059 // redefine the name of any type declared in that scope to refer 2060 // to the type to which it already refers. 2061 if (!isa<CXXRecordDecl>(CurContext)) 2062 return; 2063 2064 // C++0x [dcl.typedef]p4: 2065 // In a given class scope, a typedef specifier can be used to redefine 2066 // any class-name declared in that scope that is not also a typedef-name 2067 // to refer to the type to which it already refers. 2068 // 2069 // This wording came in via DR424, which was a correction to the 2070 // wording in DR56, which accidentally banned code like: 2071 // 2072 // struct S { 2073 // typedef struct A { } A; 2074 // }; 2075 // 2076 // in the C++03 standard. We implement the C++0x semantics, which 2077 // allow the above but disallow 2078 // 2079 // struct S { 2080 // typedef int I; 2081 // typedef int I; 2082 // }; 2083 // 2084 // since that was the intent of DR56. 2085 if (!isa<TypedefNameDecl>(Old)) 2086 return; 2087 2088 Diag(New->getLocation(), diag::err_redefinition) 2089 << New->getDeclName(); 2090 Diag(Old->getLocation(), diag::note_previous_definition); 2091 return New->setInvalidDecl(); 2092 } 2093 2094 // Modules always permit redefinition of typedefs, as does C11. 2095 if (getLangOpts().Modules || getLangOpts().C11) 2096 return; 2097 2098 // If we have a redefinition of a typedef in C, emit a warning. This warning 2099 // is normally mapped to an error, but can be controlled with 2100 // -Wtypedef-redefinition. If either the original or the redefinition is 2101 // in a system header, don't emit this for compatibility with GCC. 2102 if (getDiagnostics().getSuppressSystemWarnings() && 2103 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2104 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2105 return; 2106 2107 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2108 << New->getDeclName(); 2109 Diag(Old->getLocation(), diag::note_previous_definition); 2110 } 2111 2112 /// DeclhasAttr - returns true if decl Declaration already has the target 2113 /// attribute. 2114 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2115 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2116 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2117 for (const auto *i : D->attrs()) 2118 if (i->getKind() == A->getKind()) { 2119 if (Ann) { 2120 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2121 return true; 2122 continue; 2123 } 2124 // FIXME: Don't hardcode this check 2125 if (OA && isa<OwnershipAttr>(i)) 2126 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2127 return true; 2128 } 2129 2130 return false; 2131 } 2132 2133 static bool isAttributeTargetADefinition(Decl *D) { 2134 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2135 return VD->isThisDeclarationADefinition(); 2136 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2137 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2138 return true; 2139 } 2140 2141 /// Merge alignment attributes from \p Old to \p New, taking into account the 2142 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2143 /// 2144 /// \return \c true if any attributes were added to \p New. 2145 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2146 // Look for alignas attributes on Old, and pick out whichever attribute 2147 // specifies the strictest alignment requirement. 2148 AlignedAttr *OldAlignasAttr = nullptr; 2149 AlignedAttr *OldStrictestAlignAttr = nullptr; 2150 unsigned OldAlign = 0; 2151 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2152 // FIXME: We have no way of representing inherited dependent alignments 2153 // in a case like: 2154 // template<int A, int B> struct alignas(A) X; 2155 // template<int A, int B> struct alignas(B) X {}; 2156 // For now, we just ignore any alignas attributes which are not on the 2157 // definition in such a case. 2158 if (I->isAlignmentDependent()) 2159 return false; 2160 2161 if (I->isAlignas()) 2162 OldAlignasAttr = I; 2163 2164 unsigned Align = I->getAlignment(S.Context); 2165 if (Align > OldAlign) { 2166 OldAlign = Align; 2167 OldStrictestAlignAttr = I; 2168 } 2169 } 2170 2171 // Look for alignas attributes on New. 2172 AlignedAttr *NewAlignasAttr = nullptr; 2173 unsigned NewAlign = 0; 2174 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2175 if (I->isAlignmentDependent()) 2176 return false; 2177 2178 if (I->isAlignas()) 2179 NewAlignasAttr = I; 2180 2181 unsigned Align = I->getAlignment(S.Context); 2182 if (Align > NewAlign) 2183 NewAlign = Align; 2184 } 2185 2186 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2187 // Both declarations have 'alignas' attributes. We require them to match. 2188 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2189 // fall short. (If two declarations both have alignas, they must both match 2190 // every definition, and so must match each other if there is a definition.) 2191 2192 // If either declaration only contains 'alignas(0)' specifiers, then it 2193 // specifies the natural alignment for the type. 2194 if (OldAlign == 0 || NewAlign == 0) { 2195 QualType Ty; 2196 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2197 Ty = VD->getType(); 2198 else 2199 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2200 2201 if (OldAlign == 0) 2202 OldAlign = S.Context.getTypeAlign(Ty); 2203 if (NewAlign == 0) 2204 NewAlign = S.Context.getTypeAlign(Ty); 2205 } 2206 2207 if (OldAlign != NewAlign) { 2208 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2209 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2210 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2211 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2212 } 2213 } 2214 2215 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2216 // C++11 [dcl.align]p6: 2217 // if any declaration of an entity has an alignment-specifier, 2218 // every defining declaration of that entity shall specify an 2219 // equivalent alignment. 2220 // C11 6.7.5/7: 2221 // If the definition of an object does not have an alignment 2222 // specifier, any other declaration of that object shall also 2223 // have no alignment specifier. 2224 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2225 << OldAlignasAttr; 2226 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2227 << OldAlignasAttr; 2228 } 2229 2230 bool AnyAdded = false; 2231 2232 // Ensure we have an attribute representing the strictest alignment. 2233 if (OldAlign > NewAlign) { 2234 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2235 Clone->setInherited(true); 2236 New->addAttr(Clone); 2237 AnyAdded = true; 2238 } 2239 2240 // Ensure we have an alignas attribute if the old declaration had one. 2241 if (OldAlignasAttr && !NewAlignasAttr && 2242 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2243 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2244 Clone->setInherited(true); 2245 New->addAttr(Clone); 2246 AnyAdded = true; 2247 } 2248 2249 return AnyAdded; 2250 } 2251 2252 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2253 const InheritableAttr *Attr, 2254 Sema::AvailabilityMergeKind AMK) { 2255 // This function copies an attribute Attr from a previous declaration to the 2256 // new declaration D if the new declaration doesn't itself have that attribute 2257 // yet or if that attribute allows duplicates. 2258 // If you're adding a new attribute that requires logic different from 2259 // "use explicit attribute on decl if present, else use attribute from 2260 // previous decl", for example if the attribute needs to be consistent 2261 // between redeclarations, you need to call a custom merge function here. 2262 InheritableAttr *NewAttr = nullptr; 2263 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2264 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2265 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2266 AA->isImplicit(), AA->getIntroduced(), 2267 AA->getDeprecated(), 2268 AA->getObsoleted(), AA->getUnavailable(), 2269 AA->getMessage(), AA->getStrict(), 2270 AA->getReplacement(), AMK, 2271 AttrSpellingListIndex); 2272 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2273 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2274 AttrSpellingListIndex); 2275 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2276 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2277 AttrSpellingListIndex); 2278 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2279 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2280 AttrSpellingListIndex); 2281 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2282 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2283 AttrSpellingListIndex); 2284 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2285 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2286 FA->getFormatIdx(), FA->getFirstArg(), 2287 AttrSpellingListIndex); 2288 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2289 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2290 AttrSpellingListIndex); 2291 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2292 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2293 AttrSpellingListIndex, 2294 IA->getSemanticSpelling()); 2295 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2296 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2297 &S.Context.Idents.get(AA->getSpelling()), 2298 AttrSpellingListIndex); 2299 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2300 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2301 isa<CUDAGlobalAttr>(Attr))) { 2302 // CUDA target attributes are part of function signature for 2303 // overloading purposes and must not be merged. 2304 return false; 2305 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2306 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2307 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2308 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2309 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2310 NewAttr = S.mergeInternalLinkageAttr( 2311 D, InternalLinkageA->getRange(), 2312 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2313 AttrSpellingListIndex); 2314 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2315 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2316 &S.Context.Idents.get(CommonA->getSpelling()), 2317 AttrSpellingListIndex); 2318 else if (isa<AlignedAttr>(Attr)) 2319 // AlignedAttrs are handled separately, because we need to handle all 2320 // such attributes on a declaration at the same time. 2321 NewAttr = nullptr; 2322 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2323 (AMK == Sema::AMK_Override || 2324 AMK == Sema::AMK_ProtocolImplementation)) 2325 NewAttr = nullptr; 2326 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2327 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2328 UA->getGuid()); 2329 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2330 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2331 2332 if (NewAttr) { 2333 NewAttr->setInherited(true); 2334 D->addAttr(NewAttr); 2335 if (isa<MSInheritanceAttr>(NewAttr)) 2336 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2337 return true; 2338 } 2339 2340 return false; 2341 } 2342 2343 static const Decl *getDefinition(const Decl *D) { 2344 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2345 return TD->getDefinition(); 2346 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2347 const VarDecl *Def = VD->getDefinition(); 2348 if (Def) 2349 return Def; 2350 return VD->getActingDefinition(); 2351 } 2352 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2353 return FD->getDefinition(); 2354 return nullptr; 2355 } 2356 2357 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2358 for (const auto *Attribute : D->attrs()) 2359 if (Attribute->getKind() == Kind) 2360 return true; 2361 return false; 2362 } 2363 2364 /// checkNewAttributesAfterDef - If we already have a definition, check that 2365 /// there are no new attributes in this declaration. 2366 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2367 if (!New->hasAttrs()) 2368 return; 2369 2370 const Decl *Def = getDefinition(Old); 2371 if (!Def || Def == New) 2372 return; 2373 2374 AttrVec &NewAttributes = New->getAttrs(); 2375 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2376 const Attr *NewAttribute = NewAttributes[I]; 2377 2378 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2379 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2380 Sema::SkipBodyInfo SkipBody; 2381 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2382 2383 // If we're skipping this definition, drop the "alias" attribute. 2384 if (SkipBody.ShouldSkip) { 2385 NewAttributes.erase(NewAttributes.begin() + I); 2386 --E; 2387 continue; 2388 } 2389 } else { 2390 VarDecl *VD = cast<VarDecl>(New); 2391 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2392 VarDecl::TentativeDefinition 2393 ? diag::err_alias_after_tentative 2394 : diag::err_redefinition; 2395 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2396 S.Diag(Def->getLocation(), diag::note_previous_definition); 2397 VD->setInvalidDecl(); 2398 } 2399 ++I; 2400 continue; 2401 } 2402 2403 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2404 // Tentative definitions are only interesting for the alias check above. 2405 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2406 ++I; 2407 continue; 2408 } 2409 } 2410 2411 if (hasAttribute(Def, NewAttribute->getKind())) { 2412 ++I; 2413 continue; // regular attr merging will take care of validating this. 2414 } 2415 2416 if (isa<C11NoReturnAttr>(NewAttribute)) { 2417 // C's _Noreturn is allowed to be added to a function after it is defined. 2418 ++I; 2419 continue; 2420 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2421 if (AA->isAlignas()) { 2422 // C++11 [dcl.align]p6: 2423 // if any declaration of an entity has an alignment-specifier, 2424 // every defining declaration of that entity shall specify an 2425 // equivalent alignment. 2426 // C11 6.7.5/7: 2427 // If the definition of an object does not have an alignment 2428 // specifier, any other declaration of that object shall also 2429 // have no alignment specifier. 2430 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2431 << AA; 2432 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2433 << AA; 2434 NewAttributes.erase(NewAttributes.begin() + I); 2435 --E; 2436 continue; 2437 } 2438 } 2439 2440 S.Diag(NewAttribute->getLocation(), 2441 diag::warn_attribute_precede_definition); 2442 S.Diag(Def->getLocation(), diag::note_previous_definition); 2443 NewAttributes.erase(NewAttributes.begin() + I); 2444 --E; 2445 } 2446 } 2447 2448 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2449 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2450 AvailabilityMergeKind AMK) { 2451 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2452 UsedAttr *NewAttr = OldAttr->clone(Context); 2453 NewAttr->setInherited(true); 2454 New->addAttr(NewAttr); 2455 } 2456 2457 if (!Old->hasAttrs() && !New->hasAttrs()) 2458 return; 2459 2460 // Attributes declared post-definition are currently ignored. 2461 checkNewAttributesAfterDef(*this, New, Old); 2462 2463 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2464 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2465 if (OldA->getLabel() != NewA->getLabel()) { 2466 // This redeclaration changes __asm__ label. 2467 Diag(New->getLocation(), diag::err_different_asm_label); 2468 Diag(OldA->getLocation(), diag::note_previous_declaration); 2469 } 2470 } else if (Old->isUsed()) { 2471 // This redeclaration adds an __asm__ label to a declaration that has 2472 // already been ODR-used. 2473 Diag(New->getLocation(), diag::err_late_asm_label_name) 2474 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2475 } 2476 } 2477 2478 // Re-declaration cannot add abi_tag's. 2479 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2480 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2481 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2482 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2483 NewTag) == OldAbiTagAttr->tags_end()) { 2484 Diag(NewAbiTagAttr->getLocation(), 2485 diag::err_new_abi_tag_on_redeclaration) 2486 << NewTag; 2487 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2488 } 2489 } 2490 } else { 2491 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2492 Diag(Old->getLocation(), diag::note_previous_declaration); 2493 } 2494 } 2495 2496 if (!Old->hasAttrs()) 2497 return; 2498 2499 bool foundAny = New->hasAttrs(); 2500 2501 // Ensure that any moving of objects within the allocated map is done before 2502 // we process them. 2503 if (!foundAny) New->setAttrs(AttrVec()); 2504 2505 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2506 // Ignore deprecated/unavailable/availability attributes if requested. 2507 AvailabilityMergeKind LocalAMK = AMK_None; 2508 if (isa<DeprecatedAttr>(I) || 2509 isa<UnavailableAttr>(I) || 2510 isa<AvailabilityAttr>(I)) { 2511 switch (AMK) { 2512 case AMK_None: 2513 continue; 2514 2515 case AMK_Redeclaration: 2516 case AMK_Override: 2517 case AMK_ProtocolImplementation: 2518 LocalAMK = AMK; 2519 break; 2520 } 2521 } 2522 2523 // Already handled. 2524 if (isa<UsedAttr>(I)) 2525 continue; 2526 2527 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2528 foundAny = true; 2529 } 2530 2531 if (mergeAlignedAttrs(*this, New, Old)) 2532 foundAny = true; 2533 2534 if (!foundAny) New->dropAttrs(); 2535 } 2536 2537 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2538 /// to the new one. 2539 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2540 const ParmVarDecl *oldDecl, 2541 Sema &S) { 2542 // C++11 [dcl.attr.depend]p2: 2543 // The first declaration of a function shall specify the 2544 // carries_dependency attribute for its declarator-id if any declaration 2545 // of the function specifies the carries_dependency attribute. 2546 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2547 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2548 S.Diag(CDA->getLocation(), 2549 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2550 // Find the first declaration of the parameter. 2551 // FIXME: Should we build redeclaration chains for function parameters? 2552 const FunctionDecl *FirstFD = 2553 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2554 const ParmVarDecl *FirstVD = 2555 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2556 S.Diag(FirstVD->getLocation(), 2557 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2558 } 2559 2560 if (!oldDecl->hasAttrs()) 2561 return; 2562 2563 bool foundAny = newDecl->hasAttrs(); 2564 2565 // Ensure that any moving of objects within the allocated map is 2566 // done before we process them. 2567 if (!foundAny) newDecl->setAttrs(AttrVec()); 2568 2569 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2570 if (!DeclHasAttr(newDecl, I)) { 2571 InheritableAttr *newAttr = 2572 cast<InheritableParamAttr>(I->clone(S.Context)); 2573 newAttr->setInherited(true); 2574 newDecl->addAttr(newAttr); 2575 foundAny = true; 2576 } 2577 } 2578 2579 if (!foundAny) newDecl->dropAttrs(); 2580 } 2581 2582 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2583 const ParmVarDecl *OldParam, 2584 Sema &S) { 2585 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2586 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2587 if (*Oldnullability != *Newnullability) { 2588 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2589 << DiagNullabilityKind( 2590 *Newnullability, 2591 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2592 != 0)) 2593 << DiagNullabilityKind( 2594 *Oldnullability, 2595 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2596 != 0)); 2597 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2598 } 2599 } else { 2600 QualType NewT = NewParam->getType(); 2601 NewT = S.Context.getAttributedType( 2602 AttributedType::getNullabilityAttrKind(*Oldnullability), 2603 NewT, NewT); 2604 NewParam->setType(NewT); 2605 } 2606 } 2607 } 2608 2609 namespace { 2610 2611 /// Used in MergeFunctionDecl to keep track of function parameters in 2612 /// C. 2613 struct GNUCompatibleParamWarning { 2614 ParmVarDecl *OldParm; 2615 ParmVarDecl *NewParm; 2616 QualType PromotedType; 2617 }; 2618 2619 } // end anonymous namespace 2620 2621 /// getSpecialMember - get the special member enum for a method. 2622 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2623 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2624 if (Ctor->isDefaultConstructor()) 2625 return Sema::CXXDefaultConstructor; 2626 2627 if (Ctor->isCopyConstructor()) 2628 return Sema::CXXCopyConstructor; 2629 2630 if (Ctor->isMoveConstructor()) 2631 return Sema::CXXMoveConstructor; 2632 } else if (isa<CXXDestructorDecl>(MD)) { 2633 return Sema::CXXDestructor; 2634 } else if (MD->isCopyAssignmentOperator()) { 2635 return Sema::CXXCopyAssignment; 2636 } else if (MD->isMoveAssignmentOperator()) { 2637 return Sema::CXXMoveAssignment; 2638 } 2639 2640 return Sema::CXXInvalid; 2641 } 2642 2643 // Determine whether the previous declaration was a definition, implicit 2644 // declaration, or a declaration. 2645 template <typename T> 2646 static std::pair<diag::kind, SourceLocation> 2647 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2648 diag::kind PrevDiag; 2649 SourceLocation OldLocation = Old->getLocation(); 2650 if (Old->isThisDeclarationADefinition()) 2651 PrevDiag = diag::note_previous_definition; 2652 else if (Old->isImplicit()) { 2653 PrevDiag = diag::note_previous_implicit_declaration; 2654 if (OldLocation.isInvalid()) 2655 OldLocation = New->getLocation(); 2656 } else 2657 PrevDiag = diag::note_previous_declaration; 2658 return std::make_pair(PrevDiag, OldLocation); 2659 } 2660 2661 /// canRedefineFunction - checks if a function can be redefined. Currently, 2662 /// only extern inline functions can be redefined, and even then only in 2663 /// GNU89 mode. 2664 static bool canRedefineFunction(const FunctionDecl *FD, 2665 const LangOptions& LangOpts) { 2666 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2667 !LangOpts.CPlusPlus && 2668 FD->isInlineSpecified() && 2669 FD->getStorageClass() == SC_Extern); 2670 } 2671 2672 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2673 const AttributedType *AT = T->getAs<AttributedType>(); 2674 while (AT && !AT->isCallingConv()) 2675 AT = AT->getModifiedType()->getAs<AttributedType>(); 2676 return AT; 2677 } 2678 2679 template <typename T> 2680 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2681 const DeclContext *DC = Old->getDeclContext(); 2682 if (DC->isRecord()) 2683 return false; 2684 2685 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2686 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2687 return true; 2688 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2689 return true; 2690 return false; 2691 } 2692 2693 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2694 static bool isExternC(VarTemplateDecl *) { return false; } 2695 2696 /// \brief Check whether a redeclaration of an entity introduced by a 2697 /// using-declaration is valid, given that we know it's not an overload 2698 /// (nor a hidden tag declaration). 2699 template<typename ExpectedDecl> 2700 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2701 ExpectedDecl *New) { 2702 // C++11 [basic.scope.declarative]p4: 2703 // Given a set of declarations in a single declarative region, each of 2704 // which specifies the same unqualified name, 2705 // -- they shall all refer to the same entity, or all refer to functions 2706 // and function templates; or 2707 // -- exactly one declaration shall declare a class name or enumeration 2708 // name that is not a typedef name and the other declarations shall all 2709 // refer to the same variable or enumerator, or all refer to functions 2710 // and function templates; in this case the class name or enumeration 2711 // name is hidden (3.3.10). 2712 2713 // C++11 [namespace.udecl]p14: 2714 // If a function declaration in namespace scope or block scope has the 2715 // same name and the same parameter-type-list as a function introduced 2716 // by a using-declaration, and the declarations do not declare the same 2717 // function, the program is ill-formed. 2718 2719 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2720 if (Old && 2721 !Old->getDeclContext()->getRedeclContext()->Equals( 2722 New->getDeclContext()->getRedeclContext()) && 2723 !(isExternC(Old) && isExternC(New))) 2724 Old = nullptr; 2725 2726 if (!Old) { 2727 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2728 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2729 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2730 return true; 2731 } 2732 return false; 2733 } 2734 2735 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2736 const FunctionDecl *B) { 2737 assert(A->getNumParams() == B->getNumParams()); 2738 2739 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2740 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2741 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2742 if (AttrA == AttrB) 2743 return true; 2744 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2745 }; 2746 2747 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2748 } 2749 2750 /// MergeFunctionDecl - We just parsed a function 'New' from 2751 /// declarator D which has the same name and scope as a previous 2752 /// declaration 'Old'. Figure out how to resolve this situation, 2753 /// merging decls or emitting diagnostics as appropriate. 2754 /// 2755 /// In C++, New and Old must be declarations that are not 2756 /// overloaded. Use IsOverload to determine whether New and Old are 2757 /// overloaded, and to select the Old declaration that New should be 2758 /// merged with. 2759 /// 2760 /// Returns true if there was an error, false otherwise. 2761 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2762 Scope *S, bool MergeTypeWithOld) { 2763 // Verify the old decl was also a function. 2764 FunctionDecl *Old = OldD->getAsFunction(); 2765 if (!Old) { 2766 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2767 if (New->getFriendObjectKind()) { 2768 Diag(New->getLocation(), diag::err_using_decl_friend); 2769 Diag(Shadow->getTargetDecl()->getLocation(), 2770 diag::note_using_decl_target); 2771 Diag(Shadow->getUsingDecl()->getLocation(), 2772 diag::note_using_decl) << 0; 2773 return true; 2774 } 2775 2776 // Check whether the two declarations might declare the same function. 2777 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2778 return true; 2779 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2780 } else { 2781 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2782 << New->getDeclName(); 2783 Diag(OldD->getLocation(), diag::note_previous_definition); 2784 return true; 2785 } 2786 } 2787 2788 // If the old declaration is invalid, just give up here. 2789 if (Old->isInvalidDecl()) 2790 return true; 2791 2792 diag::kind PrevDiag; 2793 SourceLocation OldLocation; 2794 std::tie(PrevDiag, OldLocation) = 2795 getNoteDiagForInvalidRedeclaration(Old, New); 2796 2797 // Don't complain about this if we're in GNU89 mode and the old function 2798 // is an extern inline function. 2799 // Don't complain about specializations. They are not supposed to have 2800 // storage classes. 2801 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2802 New->getStorageClass() == SC_Static && 2803 Old->hasExternalFormalLinkage() && 2804 !New->getTemplateSpecializationInfo() && 2805 !canRedefineFunction(Old, getLangOpts())) { 2806 if (getLangOpts().MicrosoftExt) { 2807 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2808 Diag(OldLocation, PrevDiag); 2809 } else { 2810 Diag(New->getLocation(), diag::err_static_non_static) << New; 2811 Diag(OldLocation, PrevDiag); 2812 return true; 2813 } 2814 } 2815 2816 if (New->hasAttr<InternalLinkageAttr>() && 2817 !Old->hasAttr<InternalLinkageAttr>()) { 2818 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2819 << New->getDeclName(); 2820 Diag(Old->getLocation(), diag::note_previous_definition); 2821 New->dropAttr<InternalLinkageAttr>(); 2822 } 2823 2824 // If a function is first declared with a calling convention, but is later 2825 // declared or defined without one, all following decls assume the calling 2826 // convention of the first. 2827 // 2828 // It's OK if a function is first declared without a calling convention, 2829 // but is later declared or defined with the default calling convention. 2830 // 2831 // To test if either decl has an explicit calling convention, we look for 2832 // AttributedType sugar nodes on the type as written. If they are missing or 2833 // were canonicalized away, we assume the calling convention was implicit. 2834 // 2835 // Note also that we DO NOT return at this point, because we still have 2836 // other tests to run. 2837 QualType OldQType = Context.getCanonicalType(Old->getType()); 2838 QualType NewQType = Context.getCanonicalType(New->getType()); 2839 const FunctionType *OldType = cast<FunctionType>(OldQType); 2840 const FunctionType *NewType = cast<FunctionType>(NewQType); 2841 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2842 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2843 bool RequiresAdjustment = false; 2844 2845 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2846 FunctionDecl *First = Old->getFirstDecl(); 2847 const FunctionType *FT = 2848 First->getType().getCanonicalType()->castAs<FunctionType>(); 2849 FunctionType::ExtInfo FI = FT->getExtInfo(); 2850 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2851 if (!NewCCExplicit) { 2852 // Inherit the CC from the previous declaration if it was specified 2853 // there but not here. 2854 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2855 RequiresAdjustment = true; 2856 } else { 2857 // Calling conventions aren't compatible, so complain. 2858 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2859 Diag(New->getLocation(), diag::err_cconv_change) 2860 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2861 << !FirstCCExplicit 2862 << (!FirstCCExplicit ? "" : 2863 FunctionType::getNameForCallConv(FI.getCC())); 2864 2865 // Put the note on the first decl, since it is the one that matters. 2866 Diag(First->getLocation(), diag::note_previous_declaration); 2867 return true; 2868 } 2869 } 2870 2871 // FIXME: diagnose the other way around? 2872 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2873 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2874 RequiresAdjustment = true; 2875 } 2876 2877 // Merge regparm attribute. 2878 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2879 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2880 if (NewTypeInfo.getHasRegParm()) { 2881 Diag(New->getLocation(), diag::err_regparm_mismatch) 2882 << NewType->getRegParmType() 2883 << OldType->getRegParmType(); 2884 Diag(OldLocation, diag::note_previous_declaration); 2885 return true; 2886 } 2887 2888 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2889 RequiresAdjustment = true; 2890 } 2891 2892 // Merge ns_returns_retained attribute. 2893 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2894 if (NewTypeInfo.getProducesResult()) { 2895 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2896 Diag(OldLocation, diag::note_previous_declaration); 2897 return true; 2898 } 2899 2900 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2901 RequiresAdjustment = true; 2902 } 2903 2904 if (RequiresAdjustment) { 2905 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2906 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2907 New->setType(QualType(AdjustedType, 0)); 2908 NewQType = Context.getCanonicalType(New->getType()); 2909 NewType = cast<FunctionType>(NewQType); 2910 } 2911 2912 // If this redeclaration makes the function inline, we may need to add it to 2913 // UndefinedButUsed. 2914 if (!Old->isInlined() && New->isInlined() && 2915 !New->hasAttr<GNUInlineAttr>() && 2916 !getLangOpts().GNUInline && 2917 Old->isUsed(false) && 2918 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2919 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2920 SourceLocation())); 2921 2922 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2923 // about it. 2924 if (New->hasAttr<GNUInlineAttr>() && 2925 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2926 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2927 } 2928 2929 // If pass_object_size params don't match up perfectly, this isn't a valid 2930 // redeclaration. 2931 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2932 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2933 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2934 << New->getDeclName(); 2935 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2936 return true; 2937 } 2938 2939 if (getLangOpts().CPlusPlus) { 2940 // C++1z [over.load]p2 2941 // Certain function declarations cannot be overloaded: 2942 // -- Function declarations that differ only in the return type, 2943 // the exception specification, or both cannot be overloaded. 2944 2945 // Check the exception specifications match. This may recompute the type of 2946 // both Old and New if it resolved exception specifications, so grab the 2947 // types again after this. Because this updates the type, we do this before 2948 // any of the other checks below, which may update the "de facto" NewQType 2949 // but do not necessarily update the type of New. 2950 if (CheckEquivalentExceptionSpec(Old, New)) 2951 return true; 2952 // If exceptions are disabled, we might not have resolved the exception spec 2953 // of one or both declarations. Do so now in C++1z, so that we can properly 2954 // compare the types. 2955 if (getLangOpts().CPlusPlus1z) { 2956 for (QualType T : {Old->getType(), New->getType()}) 2957 if (auto *FPT = T->getAs<FunctionProtoType>()) 2958 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 2959 ResolveExceptionSpec(New->getLocation(), FPT); 2960 } 2961 OldQType = Context.getCanonicalType(Old->getType()); 2962 NewQType = Context.getCanonicalType(New->getType()); 2963 2964 // Go back to the type source info to compare the declared return types, 2965 // per C++1y [dcl.type.auto]p13: 2966 // Redeclarations or specializations of a function or function template 2967 // with a declared return type that uses a placeholder type shall also 2968 // use that placeholder, not a deduced type. 2969 QualType OldDeclaredReturnType = 2970 (Old->getTypeSourceInfo() 2971 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2972 : OldType)->getReturnType(); 2973 QualType NewDeclaredReturnType = 2974 (New->getTypeSourceInfo() 2975 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2976 : NewType)->getReturnType(); 2977 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2978 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2979 New->isLocalExternDecl())) { 2980 QualType ResQT; 2981 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2982 OldDeclaredReturnType->isObjCObjectPointerType()) 2983 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2984 if (ResQT.isNull()) { 2985 if (New->isCXXClassMember() && New->isOutOfLine()) 2986 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2987 << New << New->getReturnTypeSourceRange(); 2988 else 2989 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2990 << New->getReturnTypeSourceRange(); 2991 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2992 << Old->getReturnTypeSourceRange(); 2993 return true; 2994 } 2995 else 2996 NewQType = ResQT; 2997 } 2998 2999 QualType OldReturnType = OldType->getReturnType(); 3000 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3001 if (OldReturnType != NewReturnType) { 3002 // If this function has a deduced return type and has already been 3003 // defined, copy the deduced value from the old declaration. 3004 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3005 if (OldAT && OldAT->isDeduced()) { 3006 New->setType( 3007 SubstAutoType(New->getType(), 3008 OldAT->isDependentType() ? Context.DependentTy 3009 : OldAT->getDeducedType())); 3010 NewQType = Context.getCanonicalType( 3011 SubstAutoType(NewQType, 3012 OldAT->isDependentType() ? Context.DependentTy 3013 : OldAT->getDeducedType())); 3014 } 3015 } 3016 3017 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3018 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3019 if (OldMethod && NewMethod) { 3020 // Preserve triviality. 3021 NewMethod->setTrivial(OldMethod->isTrivial()); 3022 3023 // MSVC allows explicit template specialization at class scope: 3024 // 2 CXXMethodDecls referring to the same function will be injected. 3025 // We don't want a redeclaration error. 3026 bool IsClassScopeExplicitSpecialization = 3027 OldMethod->isFunctionTemplateSpecialization() && 3028 NewMethod->isFunctionTemplateSpecialization(); 3029 bool isFriend = NewMethod->getFriendObjectKind(); 3030 3031 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3032 !IsClassScopeExplicitSpecialization) { 3033 // -- Member function declarations with the same name and the 3034 // same parameter types cannot be overloaded if any of them 3035 // is a static member function declaration. 3036 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3037 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3038 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3039 return true; 3040 } 3041 3042 // C++ [class.mem]p1: 3043 // [...] A member shall not be declared twice in the 3044 // member-specification, except that a nested class or member 3045 // class template can be declared and then later defined. 3046 if (ActiveTemplateInstantiations.empty()) { 3047 unsigned NewDiag; 3048 if (isa<CXXConstructorDecl>(OldMethod)) 3049 NewDiag = diag::err_constructor_redeclared; 3050 else if (isa<CXXDestructorDecl>(NewMethod)) 3051 NewDiag = diag::err_destructor_redeclared; 3052 else if (isa<CXXConversionDecl>(NewMethod)) 3053 NewDiag = diag::err_conv_function_redeclared; 3054 else 3055 NewDiag = diag::err_member_redeclared; 3056 3057 Diag(New->getLocation(), NewDiag); 3058 } else { 3059 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3060 << New << New->getType(); 3061 } 3062 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3063 return true; 3064 3065 // Complain if this is an explicit declaration of a special 3066 // member that was initially declared implicitly. 3067 // 3068 // As an exception, it's okay to befriend such methods in order 3069 // to permit the implicit constructor/destructor/operator calls. 3070 } else if (OldMethod->isImplicit()) { 3071 if (isFriend) { 3072 NewMethod->setImplicit(); 3073 } else { 3074 Diag(NewMethod->getLocation(), 3075 diag::err_definition_of_implicitly_declared_member) 3076 << New << getSpecialMember(OldMethod); 3077 return true; 3078 } 3079 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3080 Diag(NewMethod->getLocation(), 3081 diag::err_definition_of_explicitly_defaulted_member) 3082 << getSpecialMember(OldMethod); 3083 return true; 3084 } 3085 } 3086 3087 // C++11 [dcl.attr.noreturn]p1: 3088 // The first declaration of a function shall specify the noreturn 3089 // attribute if any declaration of that function specifies the noreturn 3090 // attribute. 3091 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3092 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3093 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3094 Diag(Old->getFirstDecl()->getLocation(), 3095 diag::note_noreturn_missing_first_decl); 3096 } 3097 3098 // C++11 [dcl.attr.depend]p2: 3099 // The first declaration of a function shall specify the 3100 // carries_dependency attribute for its declarator-id if any declaration 3101 // of the function specifies the carries_dependency attribute. 3102 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3103 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3104 Diag(CDA->getLocation(), 3105 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3106 Diag(Old->getFirstDecl()->getLocation(), 3107 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3108 } 3109 3110 // (C++98 8.3.5p3): 3111 // All declarations for a function shall agree exactly in both the 3112 // return type and the parameter-type-list. 3113 // We also want to respect all the extended bits except noreturn. 3114 3115 // noreturn should now match unless the old type info didn't have it. 3116 QualType OldQTypeForComparison = OldQType; 3117 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3118 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3119 const FunctionType *OldTypeForComparison 3120 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3121 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3122 assert(OldQTypeForComparison.isCanonical()); 3123 } 3124 3125 if (haveIncompatibleLanguageLinkages(Old, New)) { 3126 // As a special case, retain the language linkage from previous 3127 // declarations of a friend function as an extension. 3128 // 3129 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3130 // and is useful because there's otherwise no way to specify language 3131 // linkage within class scope. 3132 // 3133 // Check cautiously as the friend object kind isn't yet complete. 3134 if (New->getFriendObjectKind() != Decl::FOK_None) { 3135 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3136 Diag(OldLocation, PrevDiag); 3137 } else { 3138 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3139 Diag(OldLocation, PrevDiag); 3140 return true; 3141 } 3142 } 3143 3144 if (OldQTypeForComparison == NewQType) 3145 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3146 3147 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3148 New->isLocalExternDecl()) { 3149 // It's OK if we couldn't merge types for a local function declaraton 3150 // if either the old or new type is dependent. We'll merge the types 3151 // when we instantiate the function. 3152 return false; 3153 } 3154 3155 // Fall through for conflicting redeclarations and redefinitions. 3156 } 3157 3158 // C: Function types need to be compatible, not identical. This handles 3159 // duplicate function decls like "void f(int); void f(enum X);" properly. 3160 if (!getLangOpts().CPlusPlus && 3161 Context.typesAreCompatible(OldQType, NewQType)) { 3162 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3163 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3164 const FunctionProtoType *OldProto = nullptr; 3165 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3166 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3167 // The old declaration provided a function prototype, but the 3168 // new declaration does not. Merge in the prototype. 3169 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3170 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3171 NewQType = 3172 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3173 OldProto->getExtProtoInfo()); 3174 New->setType(NewQType); 3175 New->setHasInheritedPrototype(); 3176 3177 // Synthesize parameters with the same types. 3178 SmallVector<ParmVarDecl*, 16> Params; 3179 for (const auto &ParamType : OldProto->param_types()) { 3180 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3181 SourceLocation(), nullptr, 3182 ParamType, /*TInfo=*/nullptr, 3183 SC_None, nullptr); 3184 Param->setScopeInfo(0, Params.size()); 3185 Param->setImplicit(); 3186 Params.push_back(Param); 3187 } 3188 3189 New->setParams(Params); 3190 } 3191 3192 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3193 } 3194 3195 // GNU C permits a K&R definition to follow a prototype declaration 3196 // if the declared types of the parameters in the K&R definition 3197 // match the types in the prototype declaration, even when the 3198 // promoted types of the parameters from the K&R definition differ 3199 // from the types in the prototype. GCC then keeps the types from 3200 // the prototype. 3201 // 3202 // If a variadic prototype is followed by a non-variadic K&R definition, 3203 // the K&R definition becomes variadic. This is sort of an edge case, but 3204 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3205 // C99 6.9.1p8. 3206 if (!getLangOpts().CPlusPlus && 3207 Old->hasPrototype() && !New->hasPrototype() && 3208 New->getType()->getAs<FunctionProtoType>() && 3209 Old->getNumParams() == New->getNumParams()) { 3210 SmallVector<QualType, 16> ArgTypes; 3211 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3212 const FunctionProtoType *OldProto 3213 = Old->getType()->getAs<FunctionProtoType>(); 3214 const FunctionProtoType *NewProto 3215 = New->getType()->getAs<FunctionProtoType>(); 3216 3217 // Determine whether this is the GNU C extension. 3218 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3219 NewProto->getReturnType()); 3220 bool LooseCompatible = !MergedReturn.isNull(); 3221 for (unsigned Idx = 0, End = Old->getNumParams(); 3222 LooseCompatible && Idx != End; ++Idx) { 3223 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3224 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3225 if (Context.typesAreCompatible(OldParm->getType(), 3226 NewProto->getParamType(Idx))) { 3227 ArgTypes.push_back(NewParm->getType()); 3228 } else if (Context.typesAreCompatible(OldParm->getType(), 3229 NewParm->getType(), 3230 /*CompareUnqualified=*/true)) { 3231 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3232 NewProto->getParamType(Idx) }; 3233 Warnings.push_back(Warn); 3234 ArgTypes.push_back(NewParm->getType()); 3235 } else 3236 LooseCompatible = false; 3237 } 3238 3239 if (LooseCompatible) { 3240 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3241 Diag(Warnings[Warn].NewParm->getLocation(), 3242 diag::ext_param_promoted_not_compatible_with_prototype) 3243 << Warnings[Warn].PromotedType 3244 << Warnings[Warn].OldParm->getType(); 3245 if (Warnings[Warn].OldParm->getLocation().isValid()) 3246 Diag(Warnings[Warn].OldParm->getLocation(), 3247 diag::note_previous_declaration); 3248 } 3249 3250 if (MergeTypeWithOld) 3251 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3252 OldProto->getExtProtoInfo())); 3253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3254 } 3255 3256 // Fall through to diagnose conflicting types. 3257 } 3258 3259 // A function that has already been declared has been redeclared or 3260 // defined with a different type; show an appropriate diagnostic. 3261 3262 // If the previous declaration was an implicitly-generated builtin 3263 // declaration, then at the very least we should use a specialized note. 3264 unsigned BuiltinID; 3265 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3266 // If it's actually a library-defined builtin function like 'malloc' 3267 // or 'printf', just warn about the incompatible redeclaration. 3268 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3269 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3270 Diag(OldLocation, diag::note_previous_builtin_declaration) 3271 << Old << Old->getType(); 3272 3273 // If this is a global redeclaration, just forget hereafter 3274 // about the "builtin-ness" of the function. 3275 // 3276 // Doing this for local extern declarations is problematic. If 3277 // the builtin declaration remains visible, a second invalid 3278 // local declaration will produce a hard error; if it doesn't 3279 // remain visible, a single bogus local redeclaration (which is 3280 // actually only a warning) could break all the downstream code. 3281 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3282 New->getIdentifier()->revertBuiltin(); 3283 3284 return false; 3285 } 3286 3287 PrevDiag = diag::note_previous_builtin_declaration; 3288 } 3289 3290 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3291 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3292 return true; 3293 } 3294 3295 /// \brief Completes the merge of two function declarations that are 3296 /// known to be compatible. 3297 /// 3298 /// This routine handles the merging of attributes and other 3299 /// properties of function declarations from the old declaration to 3300 /// the new declaration, once we know that New is in fact a 3301 /// redeclaration of Old. 3302 /// 3303 /// \returns false 3304 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3305 Scope *S, bool MergeTypeWithOld) { 3306 // Merge the attributes 3307 mergeDeclAttributes(New, Old); 3308 3309 // Merge "pure" flag. 3310 if (Old->isPure()) 3311 New->setPure(); 3312 3313 // Merge "used" flag. 3314 if (Old->getMostRecentDecl()->isUsed(false)) 3315 New->setIsUsed(); 3316 3317 // Merge attributes from the parameters. These can mismatch with K&R 3318 // declarations. 3319 if (New->getNumParams() == Old->getNumParams()) 3320 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3321 ParmVarDecl *NewParam = New->getParamDecl(i); 3322 ParmVarDecl *OldParam = Old->getParamDecl(i); 3323 mergeParamDeclAttributes(NewParam, OldParam, *this); 3324 mergeParamDeclTypes(NewParam, OldParam, *this); 3325 } 3326 3327 if (getLangOpts().CPlusPlus) 3328 return MergeCXXFunctionDecl(New, Old, S); 3329 3330 // Merge the function types so the we get the composite types for the return 3331 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3332 // was visible. 3333 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3334 if (!Merged.isNull() && MergeTypeWithOld) 3335 New->setType(Merged); 3336 3337 return false; 3338 } 3339 3340 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3341 ObjCMethodDecl *oldMethod) { 3342 // Merge the attributes, including deprecated/unavailable 3343 AvailabilityMergeKind MergeKind = 3344 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3345 ? AMK_ProtocolImplementation 3346 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3347 : AMK_Override; 3348 3349 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3350 3351 // Merge attributes from the parameters. 3352 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3353 oe = oldMethod->param_end(); 3354 for (ObjCMethodDecl::param_iterator 3355 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3356 ni != ne && oi != oe; ++ni, ++oi) 3357 mergeParamDeclAttributes(*ni, *oi, *this); 3358 3359 CheckObjCMethodOverride(newMethod, oldMethod); 3360 } 3361 3362 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3363 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3364 3365 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3366 ? diag::err_redefinition_different_type 3367 : diag::err_redeclaration_different_type) 3368 << New->getDeclName() << New->getType() << Old->getType(); 3369 3370 diag::kind PrevDiag; 3371 SourceLocation OldLocation; 3372 std::tie(PrevDiag, OldLocation) 3373 = getNoteDiagForInvalidRedeclaration(Old, New); 3374 S.Diag(OldLocation, PrevDiag); 3375 New->setInvalidDecl(); 3376 } 3377 3378 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3379 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3380 /// emitting diagnostics as appropriate. 3381 /// 3382 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3383 /// to here in AddInitializerToDecl. We can't check them before the initializer 3384 /// is attached. 3385 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3386 bool MergeTypeWithOld) { 3387 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3388 return; 3389 3390 QualType MergedT; 3391 if (getLangOpts().CPlusPlus) { 3392 if (New->getType()->isUndeducedType()) { 3393 // We don't know what the new type is until the initializer is attached. 3394 return; 3395 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3396 // These could still be something that needs exception specs checked. 3397 return MergeVarDeclExceptionSpecs(New, Old); 3398 } 3399 // C++ [basic.link]p10: 3400 // [...] the types specified by all declarations referring to a given 3401 // object or function shall be identical, except that declarations for an 3402 // array object can specify array types that differ by the presence or 3403 // absence of a major array bound (8.3.4). 3404 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3405 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3406 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3407 3408 // We are merging a variable declaration New into Old. If it has an array 3409 // bound, and that bound differs from Old's bound, we should diagnose the 3410 // mismatch. 3411 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3412 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3413 PrevVD = PrevVD->getPreviousDecl()) { 3414 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3415 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3416 continue; 3417 3418 if (!Context.hasSameType(NewArray, PrevVDTy)) 3419 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3420 } 3421 } 3422 3423 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3424 if (Context.hasSameType(OldArray->getElementType(), 3425 NewArray->getElementType())) 3426 MergedT = New->getType(); 3427 } 3428 // FIXME: Check visibility. New is hidden but has a complete type. If New 3429 // has no array bound, it should not inherit one from Old, if Old is not 3430 // visible. 3431 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3432 if (Context.hasSameType(OldArray->getElementType(), 3433 NewArray->getElementType())) 3434 MergedT = Old->getType(); 3435 } 3436 } 3437 else if (New->getType()->isObjCObjectPointerType() && 3438 Old->getType()->isObjCObjectPointerType()) { 3439 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3440 Old->getType()); 3441 } 3442 } else { 3443 // C 6.2.7p2: 3444 // All declarations that refer to the same object or function shall have 3445 // compatible type. 3446 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3447 } 3448 if (MergedT.isNull()) { 3449 // It's OK if we couldn't merge types if either type is dependent, for a 3450 // block-scope variable. In other cases (static data members of class 3451 // templates, variable templates, ...), we require the types to be 3452 // equivalent. 3453 // FIXME: The C++ standard doesn't say anything about this. 3454 if ((New->getType()->isDependentType() || 3455 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3456 // If the old type was dependent, we can't merge with it, so the new type 3457 // becomes dependent for now. We'll reproduce the original type when we 3458 // instantiate the TypeSourceInfo for the variable. 3459 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3460 New->setType(Context.DependentTy); 3461 return; 3462 } 3463 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3464 } 3465 3466 // Don't actually update the type on the new declaration if the old 3467 // declaration was an extern declaration in a different scope. 3468 if (MergeTypeWithOld) 3469 New->setType(MergedT); 3470 } 3471 3472 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3473 LookupResult &Previous) { 3474 // C11 6.2.7p4: 3475 // For an identifier with internal or external linkage declared 3476 // in a scope in which a prior declaration of that identifier is 3477 // visible, if the prior declaration specifies internal or 3478 // external linkage, the type of the identifier at the later 3479 // declaration becomes the composite type. 3480 // 3481 // If the variable isn't visible, we do not merge with its type. 3482 if (Previous.isShadowed()) 3483 return false; 3484 3485 if (S.getLangOpts().CPlusPlus) { 3486 // C++11 [dcl.array]p3: 3487 // If there is a preceding declaration of the entity in the same 3488 // scope in which the bound was specified, an omitted array bound 3489 // is taken to be the same as in that earlier declaration. 3490 return NewVD->isPreviousDeclInSameBlockScope() || 3491 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3492 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3493 } else { 3494 // If the old declaration was function-local, don't merge with its 3495 // type unless we're in the same function. 3496 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3497 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3498 } 3499 } 3500 3501 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3502 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3503 /// situation, merging decls or emitting diagnostics as appropriate. 3504 /// 3505 /// Tentative definition rules (C99 6.9.2p2) are checked by 3506 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3507 /// definitions here, since the initializer hasn't been attached. 3508 /// 3509 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3510 // If the new decl is already invalid, don't do any other checking. 3511 if (New->isInvalidDecl()) 3512 return; 3513 3514 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3515 return; 3516 3517 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3518 3519 // Verify the old decl was also a variable or variable template. 3520 VarDecl *Old = nullptr; 3521 VarTemplateDecl *OldTemplate = nullptr; 3522 if (Previous.isSingleResult()) { 3523 if (NewTemplate) { 3524 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3525 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3526 3527 if (auto *Shadow = 3528 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3529 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3530 return New->setInvalidDecl(); 3531 } else { 3532 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3533 3534 if (auto *Shadow = 3535 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3536 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3537 return New->setInvalidDecl(); 3538 } 3539 } 3540 if (!Old) { 3541 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3542 << New->getDeclName(); 3543 Diag(Previous.getRepresentativeDecl()->getLocation(), 3544 diag::note_previous_definition); 3545 return New->setInvalidDecl(); 3546 } 3547 3548 // Ensure the template parameters are compatible. 3549 if (NewTemplate && 3550 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3551 OldTemplate->getTemplateParameters(), 3552 /*Complain=*/true, TPL_TemplateMatch)) 3553 return New->setInvalidDecl(); 3554 3555 // C++ [class.mem]p1: 3556 // A member shall not be declared twice in the member-specification [...] 3557 // 3558 // Here, we need only consider static data members. 3559 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3560 Diag(New->getLocation(), diag::err_duplicate_member) 3561 << New->getIdentifier(); 3562 Diag(Old->getLocation(), diag::note_previous_declaration); 3563 New->setInvalidDecl(); 3564 } 3565 3566 mergeDeclAttributes(New, Old); 3567 // Warn if an already-declared variable is made a weak_import in a subsequent 3568 // declaration 3569 if (New->hasAttr<WeakImportAttr>() && 3570 Old->getStorageClass() == SC_None && 3571 !Old->hasAttr<WeakImportAttr>()) { 3572 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3573 Diag(Old->getLocation(), diag::note_previous_definition); 3574 // Remove weak_import attribute on new declaration. 3575 New->dropAttr<WeakImportAttr>(); 3576 } 3577 3578 if (New->hasAttr<InternalLinkageAttr>() && 3579 !Old->hasAttr<InternalLinkageAttr>()) { 3580 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3581 << New->getDeclName(); 3582 Diag(Old->getLocation(), diag::note_previous_definition); 3583 New->dropAttr<InternalLinkageAttr>(); 3584 } 3585 3586 // Merge the types. 3587 VarDecl *MostRecent = Old->getMostRecentDecl(); 3588 if (MostRecent != Old) { 3589 MergeVarDeclTypes(New, MostRecent, 3590 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3591 if (New->isInvalidDecl()) 3592 return; 3593 } 3594 3595 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3596 if (New->isInvalidDecl()) 3597 return; 3598 3599 diag::kind PrevDiag; 3600 SourceLocation OldLocation; 3601 std::tie(PrevDiag, OldLocation) = 3602 getNoteDiagForInvalidRedeclaration(Old, New); 3603 3604 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3605 if (New->getStorageClass() == SC_Static && 3606 !New->isStaticDataMember() && 3607 Old->hasExternalFormalLinkage()) { 3608 if (getLangOpts().MicrosoftExt) { 3609 Diag(New->getLocation(), diag::ext_static_non_static) 3610 << New->getDeclName(); 3611 Diag(OldLocation, PrevDiag); 3612 } else { 3613 Diag(New->getLocation(), diag::err_static_non_static) 3614 << New->getDeclName(); 3615 Diag(OldLocation, PrevDiag); 3616 return New->setInvalidDecl(); 3617 } 3618 } 3619 // C99 6.2.2p4: 3620 // For an identifier declared with the storage-class specifier 3621 // extern in a scope in which a prior declaration of that 3622 // identifier is visible,23) if the prior declaration specifies 3623 // internal or external linkage, the linkage of the identifier at 3624 // the later declaration is the same as the linkage specified at 3625 // the prior declaration. If no prior declaration is visible, or 3626 // if the prior declaration specifies no linkage, then the 3627 // identifier has external linkage. 3628 if (New->hasExternalStorage() && Old->hasLinkage()) 3629 /* Okay */; 3630 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3631 !New->isStaticDataMember() && 3632 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3633 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3634 Diag(OldLocation, PrevDiag); 3635 return New->setInvalidDecl(); 3636 } 3637 3638 // Check if extern is followed by non-extern and vice-versa. 3639 if (New->hasExternalStorage() && 3640 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3641 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3642 Diag(OldLocation, PrevDiag); 3643 return New->setInvalidDecl(); 3644 } 3645 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3646 !New->hasExternalStorage()) { 3647 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3648 Diag(OldLocation, PrevDiag); 3649 return New->setInvalidDecl(); 3650 } 3651 3652 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3653 3654 // FIXME: The test for external storage here seems wrong? We still 3655 // need to check for mismatches. 3656 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3657 // Don't complain about out-of-line definitions of static members. 3658 !(Old->getLexicalDeclContext()->isRecord() && 3659 !New->getLexicalDeclContext()->isRecord())) { 3660 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3661 Diag(OldLocation, PrevDiag); 3662 return New->setInvalidDecl(); 3663 } 3664 3665 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3666 if (VarDecl *Def = Old->getDefinition()) { 3667 // C++1z [dcl.fcn.spec]p4: 3668 // If the definition of a variable appears in a translation unit before 3669 // its first declaration as inline, the program is ill-formed. 3670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3671 Diag(Def->getLocation(), diag::note_previous_definition); 3672 } 3673 } 3674 3675 // If this redeclaration makes the function inline, we may need to add it to 3676 // UndefinedButUsed. 3677 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3678 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3679 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3680 SourceLocation())); 3681 3682 if (New->getTLSKind() != Old->getTLSKind()) { 3683 if (!Old->getTLSKind()) { 3684 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3685 Diag(OldLocation, PrevDiag); 3686 } else if (!New->getTLSKind()) { 3687 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3688 Diag(OldLocation, PrevDiag); 3689 } else { 3690 // Do not allow redeclaration to change the variable between requiring 3691 // static and dynamic initialization. 3692 // FIXME: GCC allows this, but uses the TLS keyword on the first 3693 // declaration to determine the kind. Do we need to be compatible here? 3694 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3695 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3696 Diag(OldLocation, PrevDiag); 3697 } 3698 } 3699 3700 // C++ doesn't have tentative definitions, so go right ahead and check here. 3701 if (getLangOpts().CPlusPlus && 3702 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3703 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3704 Old->getCanonicalDecl()->isConstexpr()) { 3705 // This definition won't be a definition any more once it's been merged. 3706 Diag(New->getLocation(), 3707 diag::warn_deprecated_redundant_constexpr_static_def); 3708 } else if (VarDecl *Def = Old->getDefinition()) { 3709 if (checkVarDeclRedefinition(Def, New)) 3710 return; 3711 } 3712 } 3713 3714 if (haveIncompatibleLanguageLinkages(Old, New)) { 3715 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3716 Diag(OldLocation, PrevDiag); 3717 New->setInvalidDecl(); 3718 return; 3719 } 3720 3721 // Merge "used" flag. 3722 if (Old->getMostRecentDecl()->isUsed(false)) 3723 New->setIsUsed(); 3724 3725 // Keep a chain of previous declarations. 3726 New->setPreviousDecl(Old); 3727 if (NewTemplate) 3728 NewTemplate->setPreviousDecl(OldTemplate); 3729 3730 // Inherit access appropriately. 3731 New->setAccess(Old->getAccess()); 3732 if (NewTemplate) 3733 NewTemplate->setAccess(New->getAccess()); 3734 3735 if (Old->isInline()) 3736 New->setImplicitlyInline(); 3737 } 3738 3739 /// We've just determined that \p Old and \p New both appear to be definitions 3740 /// of the same variable. Either diagnose or fix the problem. 3741 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3742 if (!hasVisibleDefinition(Old) && 3743 (New->getFormalLinkage() == InternalLinkage || 3744 New->isInline() || 3745 New->getDescribedVarTemplate() || 3746 New->getNumTemplateParameterLists() || 3747 New->getDeclContext()->isDependentContext())) { 3748 // The previous definition is hidden, and multiple definitions are 3749 // permitted (in separate TUs). Demote this to a declaration. 3750 New->demoteThisDefinitionToDeclaration(); 3751 3752 // Make the canonical definition visible. 3753 if (auto *OldTD = Old->getDescribedVarTemplate()) 3754 makeMergedDefinitionVisible(OldTD, New->getLocation()); 3755 makeMergedDefinitionVisible(Old, New->getLocation()); 3756 return false; 3757 } else { 3758 Diag(New->getLocation(), diag::err_redefinition) << New; 3759 Diag(Old->getLocation(), diag::note_previous_definition); 3760 New->setInvalidDecl(); 3761 return true; 3762 } 3763 } 3764 3765 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3766 /// no declarator (e.g. "struct foo;") is parsed. 3767 Decl * 3768 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3769 RecordDecl *&AnonRecord) { 3770 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3771 AnonRecord); 3772 } 3773 3774 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3775 // disambiguate entities defined in different scopes. 3776 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3777 // compatibility. 3778 // We will pick our mangling number depending on which version of MSVC is being 3779 // targeted. 3780 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3781 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3782 ? S->getMSCurManglingNumber() 3783 : S->getMSLastManglingNumber(); 3784 } 3785 3786 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3787 if (!Context.getLangOpts().CPlusPlus) 3788 return; 3789 3790 if (isa<CXXRecordDecl>(Tag->getParent())) { 3791 // If this tag is the direct child of a class, number it if 3792 // it is anonymous. 3793 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3794 return; 3795 MangleNumberingContext &MCtx = 3796 Context.getManglingNumberContext(Tag->getParent()); 3797 Context.setManglingNumber( 3798 Tag, MCtx.getManglingNumber( 3799 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3800 return; 3801 } 3802 3803 // If this tag isn't a direct child of a class, number it if it is local. 3804 Decl *ManglingContextDecl; 3805 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3806 Tag->getDeclContext(), ManglingContextDecl)) { 3807 Context.setManglingNumber( 3808 Tag, MCtx->getManglingNumber( 3809 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3810 } 3811 } 3812 3813 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3814 TypedefNameDecl *NewTD) { 3815 if (TagFromDeclSpec->isInvalidDecl()) 3816 return; 3817 3818 // Do nothing if the tag already has a name for linkage purposes. 3819 if (TagFromDeclSpec->hasNameForLinkage()) 3820 return; 3821 3822 // A well-formed anonymous tag must always be a TUK_Definition. 3823 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3824 3825 // The type must match the tag exactly; no qualifiers allowed. 3826 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3827 Context.getTagDeclType(TagFromDeclSpec))) { 3828 if (getLangOpts().CPlusPlus) 3829 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3830 return; 3831 } 3832 3833 // If we've already computed linkage for the anonymous tag, then 3834 // adding a typedef name for the anonymous decl can change that 3835 // linkage, which might be a serious problem. Diagnose this as 3836 // unsupported and ignore the typedef name. TODO: we should 3837 // pursue this as a language defect and establish a formal rule 3838 // for how to handle it. 3839 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3840 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3841 3842 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3843 tagLoc = getLocForEndOfToken(tagLoc); 3844 3845 llvm::SmallString<40> textToInsert; 3846 textToInsert += ' '; 3847 textToInsert += NewTD->getIdentifier()->getName(); 3848 Diag(tagLoc, diag::note_typedef_changes_linkage) 3849 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3850 return; 3851 } 3852 3853 // Otherwise, set this is the anon-decl typedef for the tag. 3854 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3855 } 3856 3857 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3858 switch (T) { 3859 case DeclSpec::TST_class: 3860 return 0; 3861 case DeclSpec::TST_struct: 3862 return 1; 3863 case DeclSpec::TST_interface: 3864 return 2; 3865 case DeclSpec::TST_union: 3866 return 3; 3867 case DeclSpec::TST_enum: 3868 return 4; 3869 default: 3870 llvm_unreachable("unexpected type specifier"); 3871 } 3872 } 3873 3874 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3875 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3876 /// parameters to cope with template friend declarations. 3877 Decl * 3878 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3879 MultiTemplateParamsArg TemplateParams, 3880 bool IsExplicitInstantiation, 3881 RecordDecl *&AnonRecord) { 3882 Decl *TagD = nullptr; 3883 TagDecl *Tag = nullptr; 3884 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3885 DS.getTypeSpecType() == DeclSpec::TST_struct || 3886 DS.getTypeSpecType() == DeclSpec::TST_interface || 3887 DS.getTypeSpecType() == DeclSpec::TST_union || 3888 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3889 TagD = DS.getRepAsDecl(); 3890 3891 if (!TagD) // We probably had an error 3892 return nullptr; 3893 3894 // Note that the above type specs guarantee that the 3895 // type rep is a Decl, whereas in many of the others 3896 // it's a Type. 3897 if (isa<TagDecl>(TagD)) 3898 Tag = cast<TagDecl>(TagD); 3899 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3900 Tag = CTD->getTemplatedDecl(); 3901 } 3902 3903 if (Tag) { 3904 handleTagNumbering(Tag, S); 3905 Tag->setFreeStanding(); 3906 if (Tag->isInvalidDecl()) 3907 return Tag; 3908 } 3909 3910 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3911 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3912 // or incomplete types shall not be restrict-qualified." 3913 if (TypeQuals & DeclSpec::TQ_restrict) 3914 Diag(DS.getRestrictSpecLoc(), 3915 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3916 << DS.getSourceRange(); 3917 } 3918 3919 if (DS.isInlineSpecified()) 3920 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3921 << getLangOpts().CPlusPlus1z; 3922 3923 if (DS.isConstexprSpecified()) { 3924 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3925 // and definitions of functions and variables. 3926 if (Tag) 3927 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3928 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3929 else 3930 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3931 // Don't emit warnings after this error. 3932 return TagD; 3933 } 3934 3935 if (DS.isConceptSpecified()) { 3936 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3937 // either a function concept and its definition or a variable concept and 3938 // its initializer. 3939 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3940 return TagD; 3941 } 3942 3943 DiagnoseFunctionSpecifiers(DS); 3944 3945 if (DS.isFriendSpecified()) { 3946 // If we're dealing with a decl but not a TagDecl, assume that 3947 // whatever routines created it handled the friendship aspect. 3948 if (TagD && !Tag) 3949 return nullptr; 3950 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3951 } 3952 3953 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3954 bool IsExplicitSpecialization = 3955 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3956 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3957 !IsExplicitInstantiation && !IsExplicitSpecialization && 3958 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3959 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3960 // nested-name-specifier unless it is an explicit instantiation 3961 // or an explicit specialization. 3962 // 3963 // FIXME: We allow class template partial specializations here too, per the 3964 // obvious intent of DR1819. 3965 // 3966 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3967 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3968 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3969 return nullptr; 3970 } 3971 3972 // Track whether this decl-specifier declares anything. 3973 bool DeclaresAnything = true; 3974 3975 // Handle anonymous struct definitions. 3976 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3977 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3978 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3979 if (getLangOpts().CPlusPlus || 3980 Record->getDeclContext()->isRecord()) { 3981 // If CurContext is a DeclContext that can contain statements, 3982 // RecursiveASTVisitor won't visit the decls that 3983 // BuildAnonymousStructOrUnion() will put into CurContext. 3984 // Also store them here so that they can be part of the 3985 // DeclStmt that gets created in this case. 3986 // FIXME: Also return the IndirectFieldDecls created by 3987 // BuildAnonymousStructOr union, for the same reason? 3988 if (CurContext->isFunctionOrMethod()) 3989 AnonRecord = Record; 3990 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3991 Context.getPrintingPolicy()); 3992 } 3993 3994 DeclaresAnything = false; 3995 } 3996 } 3997 3998 // C11 6.7.2.1p2: 3999 // A struct-declaration that does not declare an anonymous structure or 4000 // anonymous union shall contain a struct-declarator-list. 4001 // 4002 // This rule also existed in C89 and C99; the grammar for struct-declaration 4003 // did not permit a struct-declaration without a struct-declarator-list. 4004 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4005 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4006 // Check for Microsoft C extension: anonymous struct/union member. 4007 // Handle 2 kinds of anonymous struct/union: 4008 // struct STRUCT; 4009 // union UNION; 4010 // and 4011 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4012 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4013 if ((Tag && Tag->getDeclName()) || 4014 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4015 RecordDecl *Record = nullptr; 4016 if (Tag) 4017 Record = dyn_cast<RecordDecl>(Tag); 4018 else if (const RecordType *RT = 4019 DS.getRepAsType().get()->getAsStructureType()) 4020 Record = RT->getDecl(); 4021 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4022 Record = UT->getDecl(); 4023 4024 if (Record && getLangOpts().MicrosoftExt) { 4025 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4026 << Record->isUnion() << DS.getSourceRange(); 4027 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4028 } 4029 4030 DeclaresAnything = false; 4031 } 4032 } 4033 4034 // Skip all the checks below if we have a type error. 4035 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4036 (TagD && TagD->isInvalidDecl())) 4037 return TagD; 4038 4039 if (getLangOpts().CPlusPlus && 4040 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4041 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4042 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4043 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4044 DeclaresAnything = false; 4045 4046 if (!DS.isMissingDeclaratorOk()) { 4047 // Customize diagnostic for a typedef missing a name. 4048 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4049 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4050 << DS.getSourceRange(); 4051 else 4052 DeclaresAnything = false; 4053 } 4054 4055 if (DS.isModulePrivateSpecified() && 4056 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4057 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4058 << Tag->getTagKind() 4059 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4060 4061 ActOnDocumentableDecl(TagD); 4062 4063 // C 6.7/2: 4064 // A declaration [...] shall declare at least a declarator [...], a tag, 4065 // or the members of an enumeration. 4066 // C++ [dcl.dcl]p3: 4067 // [If there are no declarators], and except for the declaration of an 4068 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4069 // names into the program, or shall redeclare a name introduced by a 4070 // previous declaration. 4071 if (!DeclaresAnything) { 4072 // In C, we allow this as a (popular) extension / bug. Don't bother 4073 // producing further diagnostics for redundant qualifiers after this. 4074 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4075 return TagD; 4076 } 4077 4078 // C++ [dcl.stc]p1: 4079 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4080 // init-declarator-list of the declaration shall not be empty. 4081 // C++ [dcl.fct.spec]p1: 4082 // If a cv-qualifier appears in a decl-specifier-seq, the 4083 // init-declarator-list of the declaration shall not be empty. 4084 // 4085 // Spurious qualifiers here appear to be valid in C. 4086 unsigned DiagID = diag::warn_standalone_specifier; 4087 if (getLangOpts().CPlusPlus) 4088 DiagID = diag::ext_standalone_specifier; 4089 4090 // Note that a linkage-specification sets a storage class, but 4091 // 'extern "C" struct foo;' is actually valid and not theoretically 4092 // useless. 4093 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4094 if (SCS == DeclSpec::SCS_mutable) 4095 // Since mutable is not a viable storage class specifier in C, there is 4096 // no reason to treat it as an extension. Instead, diagnose as an error. 4097 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4098 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4099 Diag(DS.getStorageClassSpecLoc(), DiagID) 4100 << DeclSpec::getSpecifierName(SCS); 4101 } 4102 4103 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4104 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4105 << DeclSpec::getSpecifierName(TSCS); 4106 if (DS.getTypeQualifiers()) { 4107 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4108 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4109 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4110 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4111 // Restrict is covered above. 4112 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4113 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4114 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4115 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4116 } 4117 4118 // Warn about ignored type attributes, for example: 4119 // __attribute__((aligned)) struct A; 4120 // Attributes should be placed after tag to apply to type declaration. 4121 if (!DS.getAttributes().empty()) { 4122 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4123 if (TypeSpecType == DeclSpec::TST_class || 4124 TypeSpecType == DeclSpec::TST_struct || 4125 TypeSpecType == DeclSpec::TST_interface || 4126 TypeSpecType == DeclSpec::TST_union || 4127 TypeSpecType == DeclSpec::TST_enum) { 4128 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4129 attrs = attrs->getNext()) 4130 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4131 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4132 } 4133 } 4134 4135 return TagD; 4136 } 4137 4138 /// We are trying to inject an anonymous member into the given scope; 4139 /// check if there's an existing declaration that can't be overloaded. 4140 /// 4141 /// \return true if this is a forbidden redeclaration 4142 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4143 Scope *S, 4144 DeclContext *Owner, 4145 DeclarationName Name, 4146 SourceLocation NameLoc, 4147 bool IsUnion) { 4148 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4149 Sema::ForRedeclaration); 4150 if (!SemaRef.LookupName(R, S)) return false; 4151 4152 // Pick a representative declaration. 4153 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4154 assert(PrevDecl && "Expected a non-null Decl"); 4155 4156 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4157 return false; 4158 4159 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4160 << IsUnion << Name; 4161 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4162 4163 return true; 4164 } 4165 4166 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4167 /// anonymous struct or union AnonRecord into the owning context Owner 4168 /// and scope S. This routine will be invoked just after we realize 4169 /// that an unnamed union or struct is actually an anonymous union or 4170 /// struct, e.g., 4171 /// 4172 /// @code 4173 /// union { 4174 /// int i; 4175 /// float f; 4176 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4177 /// // f into the surrounding scope.x 4178 /// @endcode 4179 /// 4180 /// This routine is recursive, injecting the names of nested anonymous 4181 /// structs/unions into the owning context and scope as well. 4182 static bool 4183 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4184 RecordDecl *AnonRecord, AccessSpecifier AS, 4185 SmallVectorImpl<NamedDecl *> &Chaining) { 4186 bool Invalid = false; 4187 4188 // Look every FieldDecl and IndirectFieldDecl with a name. 4189 for (auto *D : AnonRecord->decls()) { 4190 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4191 cast<NamedDecl>(D)->getDeclName()) { 4192 ValueDecl *VD = cast<ValueDecl>(D); 4193 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4194 VD->getLocation(), 4195 AnonRecord->isUnion())) { 4196 // C++ [class.union]p2: 4197 // The names of the members of an anonymous union shall be 4198 // distinct from the names of any other entity in the 4199 // scope in which the anonymous union is declared. 4200 Invalid = true; 4201 } else { 4202 // C++ [class.union]p2: 4203 // For the purpose of name lookup, after the anonymous union 4204 // definition, the members of the anonymous union are 4205 // considered to have been defined in the scope in which the 4206 // anonymous union is declared. 4207 unsigned OldChainingSize = Chaining.size(); 4208 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4209 Chaining.append(IF->chain_begin(), IF->chain_end()); 4210 else 4211 Chaining.push_back(VD); 4212 4213 assert(Chaining.size() >= 2); 4214 NamedDecl **NamedChain = 4215 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4216 for (unsigned i = 0; i < Chaining.size(); i++) 4217 NamedChain[i] = Chaining[i]; 4218 4219 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4220 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4221 VD->getType(), {NamedChain, Chaining.size()}); 4222 4223 for (const auto *Attr : VD->attrs()) 4224 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4225 4226 IndirectField->setAccess(AS); 4227 IndirectField->setImplicit(); 4228 SemaRef.PushOnScopeChains(IndirectField, S); 4229 4230 // That includes picking up the appropriate access specifier. 4231 if (AS != AS_none) IndirectField->setAccess(AS); 4232 4233 Chaining.resize(OldChainingSize); 4234 } 4235 } 4236 } 4237 4238 return Invalid; 4239 } 4240 4241 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4242 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4243 /// illegal input values are mapped to SC_None. 4244 static StorageClass 4245 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4246 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4247 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4248 "Parser allowed 'typedef' as storage class VarDecl."); 4249 switch (StorageClassSpec) { 4250 case DeclSpec::SCS_unspecified: return SC_None; 4251 case DeclSpec::SCS_extern: 4252 if (DS.isExternInLinkageSpec()) 4253 return SC_None; 4254 return SC_Extern; 4255 case DeclSpec::SCS_static: return SC_Static; 4256 case DeclSpec::SCS_auto: return SC_Auto; 4257 case DeclSpec::SCS_register: return SC_Register; 4258 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4259 // Illegal SCSs map to None: error reporting is up to the caller. 4260 case DeclSpec::SCS_mutable: // Fall through. 4261 case DeclSpec::SCS_typedef: return SC_None; 4262 } 4263 llvm_unreachable("unknown storage class specifier"); 4264 } 4265 4266 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4267 assert(Record->hasInClassInitializer()); 4268 4269 for (const auto *I : Record->decls()) { 4270 const auto *FD = dyn_cast<FieldDecl>(I); 4271 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4272 FD = IFD->getAnonField(); 4273 if (FD && FD->hasInClassInitializer()) 4274 return FD->getLocation(); 4275 } 4276 4277 llvm_unreachable("couldn't find in-class initializer"); 4278 } 4279 4280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4281 SourceLocation DefaultInitLoc) { 4282 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4283 return; 4284 4285 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4286 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4287 } 4288 4289 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4290 CXXRecordDecl *AnonUnion) { 4291 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4292 return; 4293 4294 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4295 } 4296 4297 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4298 /// anonymous structure or union. Anonymous unions are a C++ feature 4299 /// (C++ [class.union]) and a C11 feature; anonymous structures 4300 /// are a C11 feature and GNU C++ extension. 4301 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4302 AccessSpecifier AS, 4303 RecordDecl *Record, 4304 const PrintingPolicy &Policy) { 4305 DeclContext *Owner = Record->getDeclContext(); 4306 4307 // Diagnose whether this anonymous struct/union is an extension. 4308 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4309 Diag(Record->getLocation(), diag::ext_anonymous_union); 4310 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4311 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4312 else if (!Record->isUnion() && !getLangOpts().C11) 4313 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4314 4315 // C and C++ require different kinds of checks for anonymous 4316 // structs/unions. 4317 bool Invalid = false; 4318 if (getLangOpts().CPlusPlus) { 4319 const char *PrevSpec = nullptr; 4320 unsigned DiagID; 4321 if (Record->isUnion()) { 4322 // C++ [class.union]p6: 4323 // Anonymous unions declared in a named namespace or in the 4324 // global namespace shall be declared static. 4325 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4326 (isa<TranslationUnitDecl>(Owner) || 4327 (isa<NamespaceDecl>(Owner) && 4328 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4329 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4330 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4331 4332 // Recover by adding 'static'. 4333 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4334 PrevSpec, DiagID, Policy); 4335 } 4336 // C++ [class.union]p6: 4337 // A storage class is not allowed in a declaration of an 4338 // anonymous union in a class scope. 4339 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4340 isa<RecordDecl>(Owner)) { 4341 Diag(DS.getStorageClassSpecLoc(), 4342 diag::err_anonymous_union_with_storage_spec) 4343 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4344 4345 // Recover by removing the storage specifier. 4346 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4347 SourceLocation(), 4348 PrevSpec, DiagID, Context.getPrintingPolicy()); 4349 } 4350 } 4351 4352 // Ignore const/volatile/restrict qualifiers. 4353 if (DS.getTypeQualifiers()) { 4354 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4355 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4356 << Record->isUnion() << "const" 4357 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4358 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4359 Diag(DS.getVolatileSpecLoc(), 4360 diag::ext_anonymous_struct_union_qualified) 4361 << Record->isUnion() << "volatile" 4362 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4363 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4364 Diag(DS.getRestrictSpecLoc(), 4365 diag::ext_anonymous_struct_union_qualified) 4366 << Record->isUnion() << "restrict" 4367 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4368 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4369 Diag(DS.getAtomicSpecLoc(), 4370 diag::ext_anonymous_struct_union_qualified) 4371 << Record->isUnion() << "_Atomic" 4372 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4373 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4374 Diag(DS.getUnalignedSpecLoc(), 4375 diag::ext_anonymous_struct_union_qualified) 4376 << Record->isUnion() << "__unaligned" 4377 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4378 4379 DS.ClearTypeQualifiers(); 4380 } 4381 4382 // C++ [class.union]p2: 4383 // The member-specification of an anonymous union shall only 4384 // define non-static data members. [Note: nested types and 4385 // functions cannot be declared within an anonymous union. ] 4386 for (auto *Mem : Record->decls()) { 4387 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4388 // C++ [class.union]p3: 4389 // An anonymous union shall not have private or protected 4390 // members (clause 11). 4391 assert(FD->getAccess() != AS_none); 4392 if (FD->getAccess() != AS_public) { 4393 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4394 << Record->isUnion() << (FD->getAccess() == AS_protected); 4395 Invalid = true; 4396 } 4397 4398 // C++ [class.union]p1 4399 // An object of a class with a non-trivial constructor, a non-trivial 4400 // copy constructor, a non-trivial destructor, or a non-trivial copy 4401 // assignment operator cannot be a member of a union, nor can an 4402 // array of such objects. 4403 if (CheckNontrivialField(FD)) 4404 Invalid = true; 4405 } else if (Mem->isImplicit()) { 4406 // Any implicit members are fine. 4407 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4408 // This is a type that showed up in an 4409 // elaborated-type-specifier inside the anonymous struct or 4410 // union, but which actually declares a type outside of the 4411 // anonymous struct or union. It's okay. 4412 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4413 if (!MemRecord->isAnonymousStructOrUnion() && 4414 MemRecord->getDeclName()) { 4415 // Visual C++ allows type definition in anonymous struct or union. 4416 if (getLangOpts().MicrosoftExt) 4417 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4418 << Record->isUnion(); 4419 else { 4420 // This is a nested type declaration. 4421 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4422 << Record->isUnion(); 4423 Invalid = true; 4424 } 4425 } else { 4426 // This is an anonymous type definition within another anonymous type. 4427 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4428 // not part of standard C++. 4429 Diag(MemRecord->getLocation(), 4430 diag::ext_anonymous_record_with_anonymous_type) 4431 << Record->isUnion(); 4432 } 4433 } else if (isa<AccessSpecDecl>(Mem)) { 4434 // Any access specifier is fine. 4435 } else if (isa<StaticAssertDecl>(Mem)) { 4436 // In C++1z, static_assert declarations are also fine. 4437 } else { 4438 // We have something that isn't a non-static data 4439 // member. Complain about it. 4440 unsigned DK = diag::err_anonymous_record_bad_member; 4441 if (isa<TypeDecl>(Mem)) 4442 DK = diag::err_anonymous_record_with_type; 4443 else if (isa<FunctionDecl>(Mem)) 4444 DK = diag::err_anonymous_record_with_function; 4445 else if (isa<VarDecl>(Mem)) 4446 DK = diag::err_anonymous_record_with_static; 4447 4448 // Visual C++ allows type definition in anonymous struct or union. 4449 if (getLangOpts().MicrosoftExt && 4450 DK == diag::err_anonymous_record_with_type) 4451 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4452 << Record->isUnion(); 4453 else { 4454 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4455 Invalid = true; 4456 } 4457 } 4458 } 4459 4460 // C++11 [class.union]p8 (DR1460): 4461 // At most one variant member of a union may have a 4462 // brace-or-equal-initializer. 4463 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4464 Owner->isRecord()) 4465 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4466 cast<CXXRecordDecl>(Record)); 4467 } 4468 4469 if (!Record->isUnion() && !Owner->isRecord()) { 4470 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4471 << getLangOpts().CPlusPlus; 4472 Invalid = true; 4473 } 4474 4475 // Mock up a declarator. 4476 Declarator Dc(DS, Declarator::MemberContext); 4477 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4478 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4479 4480 // Create a declaration for this anonymous struct/union. 4481 NamedDecl *Anon = nullptr; 4482 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4483 Anon = FieldDecl::Create(Context, OwningClass, 4484 DS.getLocStart(), 4485 Record->getLocation(), 4486 /*IdentifierInfo=*/nullptr, 4487 Context.getTypeDeclType(Record), 4488 TInfo, 4489 /*BitWidth=*/nullptr, /*Mutable=*/false, 4490 /*InitStyle=*/ICIS_NoInit); 4491 Anon->setAccess(AS); 4492 if (getLangOpts().CPlusPlus) 4493 FieldCollector->Add(cast<FieldDecl>(Anon)); 4494 } else { 4495 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4496 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4497 if (SCSpec == DeclSpec::SCS_mutable) { 4498 // mutable can only appear on non-static class members, so it's always 4499 // an error here 4500 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4501 Invalid = true; 4502 SC = SC_None; 4503 } 4504 4505 Anon = VarDecl::Create(Context, Owner, 4506 DS.getLocStart(), 4507 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4508 Context.getTypeDeclType(Record), 4509 TInfo, SC); 4510 4511 // Default-initialize the implicit variable. This initialization will be 4512 // trivial in almost all cases, except if a union member has an in-class 4513 // initializer: 4514 // union { int n = 0; }; 4515 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4516 } 4517 Anon->setImplicit(); 4518 4519 // Mark this as an anonymous struct/union type. 4520 Record->setAnonymousStructOrUnion(true); 4521 4522 // Add the anonymous struct/union object to the current 4523 // context. We'll be referencing this object when we refer to one of 4524 // its members. 4525 Owner->addDecl(Anon); 4526 4527 // Inject the members of the anonymous struct/union into the owning 4528 // context and into the identifier resolver chain for name lookup 4529 // purposes. 4530 SmallVector<NamedDecl*, 2> Chain; 4531 Chain.push_back(Anon); 4532 4533 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4534 Invalid = true; 4535 4536 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4537 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4538 Decl *ManglingContextDecl; 4539 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4540 NewVD->getDeclContext(), ManglingContextDecl)) { 4541 Context.setManglingNumber( 4542 NewVD, MCtx->getManglingNumber( 4543 NewVD, getMSManglingNumber(getLangOpts(), S))); 4544 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4545 } 4546 } 4547 } 4548 4549 if (Invalid) 4550 Anon->setInvalidDecl(); 4551 4552 return Anon; 4553 } 4554 4555 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4556 /// Microsoft C anonymous structure. 4557 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4558 /// Example: 4559 /// 4560 /// struct A { int a; }; 4561 /// struct B { struct A; int b; }; 4562 /// 4563 /// void foo() { 4564 /// B var; 4565 /// var.a = 3; 4566 /// } 4567 /// 4568 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4569 RecordDecl *Record) { 4570 assert(Record && "expected a record!"); 4571 4572 // Mock up a declarator. 4573 Declarator Dc(DS, Declarator::TypeNameContext); 4574 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4575 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4576 4577 auto *ParentDecl = cast<RecordDecl>(CurContext); 4578 QualType RecTy = Context.getTypeDeclType(Record); 4579 4580 // Create a declaration for this anonymous struct. 4581 NamedDecl *Anon = FieldDecl::Create(Context, 4582 ParentDecl, 4583 DS.getLocStart(), 4584 DS.getLocStart(), 4585 /*IdentifierInfo=*/nullptr, 4586 RecTy, 4587 TInfo, 4588 /*BitWidth=*/nullptr, /*Mutable=*/false, 4589 /*InitStyle=*/ICIS_NoInit); 4590 Anon->setImplicit(); 4591 4592 // Add the anonymous struct object to the current context. 4593 CurContext->addDecl(Anon); 4594 4595 // Inject the members of the anonymous struct into the current 4596 // context and into the identifier resolver chain for name lookup 4597 // purposes. 4598 SmallVector<NamedDecl*, 2> Chain; 4599 Chain.push_back(Anon); 4600 4601 RecordDecl *RecordDef = Record->getDefinition(); 4602 if (RequireCompleteType(Anon->getLocation(), RecTy, 4603 diag::err_field_incomplete) || 4604 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4605 AS_none, Chain)) { 4606 Anon->setInvalidDecl(); 4607 ParentDecl->setInvalidDecl(); 4608 } 4609 4610 return Anon; 4611 } 4612 4613 /// GetNameForDeclarator - Determine the full declaration name for the 4614 /// given Declarator. 4615 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4616 return GetNameFromUnqualifiedId(D.getName()); 4617 } 4618 4619 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4620 DeclarationNameInfo 4621 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4622 DeclarationNameInfo NameInfo; 4623 NameInfo.setLoc(Name.StartLocation); 4624 4625 switch (Name.getKind()) { 4626 4627 case UnqualifiedId::IK_ImplicitSelfParam: 4628 case UnqualifiedId::IK_Identifier: 4629 NameInfo.setName(Name.Identifier); 4630 NameInfo.setLoc(Name.StartLocation); 4631 return NameInfo; 4632 4633 case UnqualifiedId::IK_OperatorFunctionId: 4634 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4635 Name.OperatorFunctionId.Operator)); 4636 NameInfo.setLoc(Name.StartLocation); 4637 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4638 = Name.OperatorFunctionId.SymbolLocations[0]; 4639 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4640 = Name.EndLocation.getRawEncoding(); 4641 return NameInfo; 4642 4643 case UnqualifiedId::IK_LiteralOperatorId: 4644 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4645 Name.Identifier)); 4646 NameInfo.setLoc(Name.StartLocation); 4647 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4648 return NameInfo; 4649 4650 case UnqualifiedId::IK_ConversionFunctionId: { 4651 TypeSourceInfo *TInfo; 4652 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4653 if (Ty.isNull()) 4654 return DeclarationNameInfo(); 4655 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4656 Context.getCanonicalType(Ty))); 4657 NameInfo.setLoc(Name.StartLocation); 4658 NameInfo.setNamedTypeInfo(TInfo); 4659 return NameInfo; 4660 } 4661 4662 case UnqualifiedId::IK_ConstructorName: { 4663 TypeSourceInfo *TInfo; 4664 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4665 if (Ty.isNull()) 4666 return DeclarationNameInfo(); 4667 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4668 Context.getCanonicalType(Ty))); 4669 NameInfo.setLoc(Name.StartLocation); 4670 NameInfo.setNamedTypeInfo(TInfo); 4671 return NameInfo; 4672 } 4673 4674 case UnqualifiedId::IK_ConstructorTemplateId: { 4675 // In well-formed code, we can only have a constructor 4676 // template-id that refers to the current context, so go there 4677 // to find the actual type being constructed. 4678 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4679 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4680 return DeclarationNameInfo(); 4681 4682 // Determine the type of the class being constructed. 4683 QualType CurClassType = Context.getTypeDeclType(CurClass); 4684 4685 // FIXME: Check two things: that the template-id names the same type as 4686 // CurClassType, and that the template-id does not occur when the name 4687 // was qualified. 4688 4689 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4690 Context.getCanonicalType(CurClassType))); 4691 NameInfo.setLoc(Name.StartLocation); 4692 // FIXME: should we retrieve TypeSourceInfo? 4693 NameInfo.setNamedTypeInfo(nullptr); 4694 return NameInfo; 4695 } 4696 4697 case UnqualifiedId::IK_DestructorName: { 4698 TypeSourceInfo *TInfo; 4699 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4700 if (Ty.isNull()) 4701 return DeclarationNameInfo(); 4702 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4703 Context.getCanonicalType(Ty))); 4704 NameInfo.setLoc(Name.StartLocation); 4705 NameInfo.setNamedTypeInfo(TInfo); 4706 return NameInfo; 4707 } 4708 4709 case UnqualifiedId::IK_TemplateId: { 4710 TemplateName TName = Name.TemplateId->Template.get(); 4711 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4712 return Context.getNameForTemplate(TName, TNameLoc); 4713 } 4714 4715 } // switch (Name.getKind()) 4716 4717 llvm_unreachable("Unknown name kind"); 4718 } 4719 4720 static QualType getCoreType(QualType Ty) { 4721 do { 4722 if (Ty->isPointerType() || Ty->isReferenceType()) 4723 Ty = Ty->getPointeeType(); 4724 else if (Ty->isArrayType()) 4725 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4726 else 4727 return Ty.withoutLocalFastQualifiers(); 4728 } while (true); 4729 } 4730 4731 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4732 /// and Definition have "nearly" matching parameters. This heuristic is 4733 /// used to improve diagnostics in the case where an out-of-line function 4734 /// definition doesn't match any declaration within the class or namespace. 4735 /// Also sets Params to the list of indices to the parameters that differ 4736 /// between the declaration and the definition. If hasSimilarParameters 4737 /// returns true and Params is empty, then all of the parameters match. 4738 static bool hasSimilarParameters(ASTContext &Context, 4739 FunctionDecl *Declaration, 4740 FunctionDecl *Definition, 4741 SmallVectorImpl<unsigned> &Params) { 4742 Params.clear(); 4743 if (Declaration->param_size() != Definition->param_size()) 4744 return false; 4745 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4746 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4747 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4748 4749 // The parameter types are identical 4750 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4751 continue; 4752 4753 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4754 QualType DefParamBaseTy = getCoreType(DefParamTy); 4755 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4756 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4757 4758 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4759 (DeclTyName && DeclTyName == DefTyName)) 4760 Params.push_back(Idx); 4761 else // The two parameters aren't even close 4762 return false; 4763 } 4764 4765 return true; 4766 } 4767 4768 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4769 /// declarator needs to be rebuilt in the current instantiation. 4770 /// Any bits of declarator which appear before the name are valid for 4771 /// consideration here. That's specifically the type in the decl spec 4772 /// and the base type in any member-pointer chunks. 4773 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4774 DeclarationName Name) { 4775 // The types we specifically need to rebuild are: 4776 // - typenames, typeofs, and decltypes 4777 // - types which will become injected class names 4778 // Of course, we also need to rebuild any type referencing such a 4779 // type. It's safest to just say "dependent", but we call out a 4780 // few cases here. 4781 4782 DeclSpec &DS = D.getMutableDeclSpec(); 4783 switch (DS.getTypeSpecType()) { 4784 case DeclSpec::TST_typename: 4785 case DeclSpec::TST_typeofType: 4786 case DeclSpec::TST_underlyingType: 4787 case DeclSpec::TST_atomic: { 4788 // Grab the type from the parser. 4789 TypeSourceInfo *TSI = nullptr; 4790 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4791 if (T.isNull() || !T->isDependentType()) break; 4792 4793 // Make sure there's a type source info. This isn't really much 4794 // of a waste; most dependent types should have type source info 4795 // attached already. 4796 if (!TSI) 4797 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4798 4799 // Rebuild the type in the current instantiation. 4800 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4801 if (!TSI) return true; 4802 4803 // Store the new type back in the decl spec. 4804 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4805 DS.UpdateTypeRep(LocType); 4806 break; 4807 } 4808 4809 case DeclSpec::TST_decltype: 4810 case DeclSpec::TST_typeofExpr: { 4811 Expr *E = DS.getRepAsExpr(); 4812 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4813 if (Result.isInvalid()) return true; 4814 DS.UpdateExprRep(Result.get()); 4815 break; 4816 } 4817 4818 default: 4819 // Nothing to do for these decl specs. 4820 break; 4821 } 4822 4823 // It doesn't matter what order we do this in. 4824 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4825 DeclaratorChunk &Chunk = D.getTypeObject(I); 4826 4827 // The only type information in the declarator which can come 4828 // before the declaration name is the base type of a member 4829 // pointer. 4830 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4831 continue; 4832 4833 // Rebuild the scope specifier in-place. 4834 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4835 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4836 return true; 4837 } 4838 4839 return false; 4840 } 4841 4842 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4843 D.setFunctionDefinitionKind(FDK_Declaration); 4844 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4845 4846 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4847 Dcl && Dcl->getDeclContext()->isFileContext()) 4848 Dcl->setTopLevelDeclInObjCContainer(); 4849 4850 return Dcl; 4851 } 4852 4853 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4854 /// If T is the name of a class, then each of the following shall have a 4855 /// name different from T: 4856 /// - every static data member of class T; 4857 /// - every member function of class T 4858 /// - every member of class T that is itself a type; 4859 /// \returns true if the declaration name violates these rules. 4860 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4861 DeclarationNameInfo NameInfo) { 4862 DeclarationName Name = NameInfo.getName(); 4863 4864 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4865 while (Record && Record->isAnonymousStructOrUnion()) 4866 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4867 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4868 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4869 return true; 4870 } 4871 4872 return false; 4873 } 4874 4875 /// \brief Diagnose a declaration whose declarator-id has the given 4876 /// nested-name-specifier. 4877 /// 4878 /// \param SS The nested-name-specifier of the declarator-id. 4879 /// 4880 /// \param DC The declaration context to which the nested-name-specifier 4881 /// resolves. 4882 /// 4883 /// \param Name The name of the entity being declared. 4884 /// 4885 /// \param Loc The location of the name of the entity being declared. 4886 /// 4887 /// \returns true if we cannot safely recover from this error, false otherwise. 4888 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4889 DeclarationName Name, 4890 SourceLocation Loc) { 4891 DeclContext *Cur = CurContext; 4892 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4893 Cur = Cur->getParent(); 4894 4895 // If the user provided a superfluous scope specifier that refers back to the 4896 // class in which the entity is already declared, diagnose and ignore it. 4897 // 4898 // class X { 4899 // void X::f(); 4900 // }; 4901 // 4902 // Note, it was once ill-formed to give redundant qualification in all 4903 // contexts, but that rule was removed by DR482. 4904 if (Cur->Equals(DC)) { 4905 if (Cur->isRecord()) { 4906 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4907 : diag::err_member_extra_qualification) 4908 << Name << FixItHint::CreateRemoval(SS.getRange()); 4909 SS.clear(); 4910 } else { 4911 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4912 } 4913 return false; 4914 } 4915 4916 // Check whether the qualifying scope encloses the scope of the original 4917 // declaration. 4918 if (!Cur->Encloses(DC)) { 4919 if (Cur->isRecord()) 4920 Diag(Loc, diag::err_member_qualification) 4921 << Name << SS.getRange(); 4922 else if (isa<TranslationUnitDecl>(DC)) 4923 Diag(Loc, diag::err_invalid_declarator_global_scope) 4924 << Name << SS.getRange(); 4925 else if (isa<FunctionDecl>(Cur)) 4926 Diag(Loc, diag::err_invalid_declarator_in_function) 4927 << Name << SS.getRange(); 4928 else if (isa<BlockDecl>(Cur)) 4929 Diag(Loc, diag::err_invalid_declarator_in_block) 4930 << Name << SS.getRange(); 4931 else 4932 Diag(Loc, diag::err_invalid_declarator_scope) 4933 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4934 4935 return true; 4936 } 4937 4938 if (Cur->isRecord()) { 4939 // Cannot qualify members within a class. 4940 Diag(Loc, diag::err_member_qualification) 4941 << Name << SS.getRange(); 4942 SS.clear(); 4943 4944 // C++ constructors and destructors with incorrect scopes can break 4945 // our AST invariants by having the wrong underlying types. If 4946 // that's the case, then drop this declaration entirely. 4947 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4948 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4949 !Context.hasSameType(Name.getCXXNameType(), 4950 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4951 return true; 4952 4953 return false; 4954 } 4955 4956 // C++11 [dcl.meaning]p1: 4957 // [...] "The nested-name-specifier of the qualified declarator-id shall 4958 // not begin with a decltype-specifer" 4959 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4960 while (SpecLoc.getPrefix()) 4961 SpecLoc = SpecLoc.getPrefix(); 4962 if (dyn_cast_or_null<DecltypeType>( 4963 SpecLoc.getNestedNameSpecifier()->getAsType())) 4964 Diag(Loc, diag::err_decltype_in_declarator) 4965 << SpecLoc.getTypeLoc().getSourceRange(); 4966 4967 return false; 4968 } 4969 4970 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4971 MultiTemplateParamsArg TemplateParamLists) { 4972 // TODO: consider using NameInfo for diagnostic. 4973 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4974 DeclarationName Name = NameInfo.getName(); 4975 4976 // All of these full declarators require an identifier. If it doesn't have 4977 // one, the ParsedFreeStandingDeclSpec action should be used. 4978 if (D.isDecompositionDeclarator()) { 4979 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 4980 } else if (!Name) { 4981 if (!D.isInvalidType()) // Reject this if we think it is valid. 4982 Diag(D.getDeclSpec().getLocStart(), 4983 diag::err_declarator_need_ident) 4984 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4985 return nullptr; 4986 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4987 return nullptr; 4988 4989 // The scope passed in may not be a decl scope. Zip up the scope tree until 4990 // we find one that is. 4991 while ((S->getFlags() & Scope::DeclScope) == 0 || 4992 (S->getFlags() & Scope::TemplateParamScope) != 0) 4993 S = S->getParent(); 4994 4995 DeclContext *DC = CurContext; 4996 if (D.getCXXScopeSpec().isInvalid()) 4997 D.setInvalidType(); 4998 else if (D.getCXXScopeSpec().isSet()) { 4999 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5000 UPPC_DeclarationQualifier)) 5001 return nullptr; 5002 5003 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5004 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5005 if (!DC || isa<EnumDecl>(DC)) { 5006 // If we could not compute the declaration context, it's because the 5007 // declaration context is dependent but does not refer to a class, 5008 // class template, or class template partial specialization. Complain 5009 // and return early, to avoid the coming semantic disaster. 5010 Diag(D.getIdentifierLoc(), 5011 diag::err_template_qualified_declarator_no_match) 5012 << D.getCXXScopeSpec().getScopeRep() 5013 << D.getCXXScopeSpec().getRange(); 5014 return nullptr; 5015 } 5016 bool IsDependentContext = DC->isDependentContext(); 5017 5018 if (!IsDependentContext && 5019 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5020 return nullptr; 5021 5022 // If a class is incomplete, do not parse entities inside it. 5023 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5024 Diag(D.getIdentifierLoc(), 5025 diag::err_member_def_undefined_record) 5026 << Name << DC << D.getCXXScopeSpec().getRange(); 5027 return nullptr; 5028 } 5029 if (!D.getDeclSpec().isFriendSpecified()) { 5030 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5031 Name, D.getIdentifierLoc())) { 5032 if (DC->isRecord()) 5033 return nullptr; 5034 5035 D.setInvalidType(); 5036 } 5037 } 5038 5039 // Check whether we need to rebuild the type of the given 5040 // declaration in the current instantiation. 5041 if (EnteringContext && IsDependentContext && 5042 TemplateParamLists.size() != 0) { 5043 ContextRAII SavedContext(*this, DC); 5044 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5045 D.setInvalidType(); 5046 } 5047 } 5048 5049 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5050 QualType R = TInfo->getType(); 5051 5052 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5053 // If this is a typedef, we'll end up spewing multiple diagnostics. 5054 // Just return early; it's safer. If this is a function, let the 5055 // "constructor cannot have a return type" diagnostic handle it. 5056 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5057 return nullptr; 5058 5059 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5060 UPPC_DeclarationType)) 5061 D.setInvalidType(); 5062 5063 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5064 ForRedeclaration); 5065 5066 // See if this is a redefinition of a variable in the same scope. 5067 if (!D.getCXXScopeSpec().isSet()) { 5068 bool IsLinkageLookup = false; 5069 bool CreateBuiltins = false; 5070 5071 // If the declaration we're planning to build will be a function 5072 // or object with linkage, then look for another declaration with 5073 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5074 // 5075 // If the declaration we're planning to build will be declared with 5076 // external linkage in the translation unit, create any builtin with 5077 // the same name. 5078 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5079 /* Do nothing*/; 5080 else if (CurContext->isFunctionOrMethod() && 5081 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5082 R->isFunctionType())) { 5083 IsLinkageLookup = true; 5084 CreateBuiltins = 5085 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5086 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5087 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5088 CreateBuiltins = true; 5089 5090 if (IsLinkageLookup) 5091 Previous.clear(LookupRedeclarationWithLinkage); 5092 5093 LookupName(Previous, S, CreateBuiltins); 5094 } else { // Something like "int foo::x;" 5095 LookupQualifiedName(Previous, DC); 5096 5097 // C++ [dcl.meaning]p1: 5098 // When the declarator-id is qualified, the declaration shall refer to a 5099 // previously declared member of the class or namespace to which the 5100 // qualifier refers (or, in the case of a namespace, of an element of the 5101 // inline namespace set of that namespace (7.3.1)) or to a specialization 5102 // thereof; [...] 5103 // 5104 // Note that we already checked the context above, and that we do not have 5105 // enough information to make sure that Previous contains the declaration 5106 // we want to match. For example, given: 5107 // 5108 // class X { 5109 // void f(); 5110 // void f(float); 5111 // }; 5112 // 5113 // void X::f(int) { } // ill-formed 5114 // 5115 // In this case, Previous will point to the overload set 5116 // containing the two f's declared in X, but neither of them 5117 // matches. 5118 5119 // C++ [dcl.meaning]p1: 5120 // [...] the member shall not merely have been introduced by a 5121 // using-declaration in the scope of the class or namespace nominated by 5122 // the nested-name-specifier of the declarator-id. 5123 RemoveUsingDecls(Previous); 5124 } 5125 5126 if (Previous.isSingleResult() && 5127 Previous.getFoundDecl()->isTemplateParameter()) { 5128 // Maybe we will complain about the shadowed template parameter. 5129 if (!D.isInvalidType()) 5130 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5131 Previous.getFoundDecl()); 5132 5133 // Just pretend that we didn't see the previous declaration. 5134 Previous.clear(); 5135 } 5136 5137 // In C++, the previous declaration we find might be a tag type 5138 // (class or enum). In this case, the new declaration will hide the 5139 // tag type. Note that this does does not apply if we're declaring a 5140 // typedef (C++ [dcl.typedef]p4). 5141 if (Previous.isSingleTagDecl() && 5142 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5143 Previous.clear(); 5144 5145 // Check that there are no default arguments other than in the parameters 5146 // of a function declaration (C++ only). 5147 if (getLangOpts().CPlusPlus) 5148 CheckExtraCXXDefaultArguments(D); 5149 5150 if (D.getDeclSpec().isConceptSpecified()) { 5151 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5152 // applied only to the definition of a function template or variable 5153 // template, declared in namespace scope 5154 if (!TemplateParamLists.size()) { 5155 Diag(D.getDeclSpec().getConceptSpecLoc(), 5156 diag:: err_concept_wrong_decl_kind); 5157 return nullptr; 5158 } 5159 5160 if (!DC->getRedeclContext()->isFileContext()) { 5161 Diag(D.getIdentifierLoc(), 5162 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5163 return nullptr; 5164 } 5165 } 5166 5167 NamedDecl *New; 5168 5169 bool AddToScope = true; 5170 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5171 if (TemplateParamLists.size()) { 5172 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5173 return nullptr; 5174 } 5175 5176 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5177 } else if (R->isFunctionType()) { 5178 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5179 TemplateParamLists, 5180 AddToScope); 5181 } else { 5182 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5183 AddToScope); 5184 } 5185 5186 if (!New) 5187 return nullptr; 5188 5189 // If this has an identifier and is not a function template specialization, 5190 // add it to the scope stack. 5191 if (New->getDeclName() && AddToScope) { 5192 // Only make a locally-scoped extern declaration visible if it is the first 5193 // declaration of this entity. Qualified lookup for such an entity should 5194 // only find this declaration if there is no visible declaration of it. 5195 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5196 PushOnScopeChains(New, S, AddToContext); 5197 if (!AddToContext) 5198 CurContext->addHiddenDecl(New); 5199 } 5200 5201 if (isInOpenMPDeclareTargetContext()) 5202 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5203 5204 return New; 5205 } 5206 5207 /// Helper method to turn variable array types into constant array 5208 /// types in certain situations which would otherwise be errors (for 5209 /// GCC compatibility). 5210 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5211 ASTContext &Context, 5212 bool &SizeIsNegative, 5213 llvm::APSInt &Oversized) { 5214 // This method tries to turn a variable array into a constant 5215 // array even when the size isn't an ICE. This is necessary 5216 // for compatibility with code that depends on gcc's buggy 5217 // constant expression folding, like struct {char x[(int)(char*)2];} 5218 SizeIsNegative = false; 5219 Oversized = 0; 5220 5221 if (T->isDependentType()) 5222 return QualType(); 5223 5224 QualifierCollector Qs; 5225 const Type *Ty = Qs.strip(T); 5226 5227 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5228 QualType Pointee = PTy->getPointeeType(); 5229 QualType FixedType = 5230 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5231 Oversized); 5232 if (FixedType.isNull()) return FixedType; 5233 FixedType = Context.getPointerType(FixedType); 5234 return Qs.apply(Context, FixedType); 5235 } 5236 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5237 QualType Inner = PTy->getInnerType(); 5238 QualType FixedType = 5239 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5240 Oversized); 5241 if (FixedType.isNull()) return FixedType; 5242 FixedType = Context.getParenType(FixedType); 5243 return Qs.apply(Context, FixedType); 5244 } 5245 5246 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5247 if (!VLATy) 5248 return QualType(); 5249 // FIXME: We should probably handle this case 5250 if (VLATy->getElementType()->isVariablyModifiedType()) 5251 return QualType(); 5252 5253 llvm::APSInt Res; 5254 if (!VLATy->getSizeExpr() || 5255 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5256 return QualType(); 5257 5258 // Check whether the array size is negative. 5259 if (Res.isSigned() && Res.isNegative()) { 5260 SizeIsNegative = true; 5261 return QualType(); 5262 } 5263 5264 // Check whether the array is too large to be addressed. 5265 unsigned ActiveSizeBits 5266 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5267 Res); 5268 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5269 Oversized = Res; 5270 return QualType(); 5271 } 5272 5273 return Context.getConstantArrayType(VLATy->getElementType(), 5274 Res, ArrayType::Normal, 0); 5275 } 5276 5277 static void 5278 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5279 SrcTL = SrcTL.getUnqualifiedLoc(); 5280 DstTL = DstTL.getUnqualifiedLoc(); 5281 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5282 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5283 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5284 DstPTL.getPointeeLoc()); 5285 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5286 return; 5287 } 5288 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5289 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5290 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5291 DstPTL.getInnerLoc()); 5292 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5293 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5294 return; 5295 } 5296 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5297 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5298 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5299 TypeLoc DstElemTL = DstATL.getElementLoc(); 5300 DstElemTL.initializeFullCopy(SrcElemTL); 5301 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5302 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5303 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5304 } 5305 5306 /// Helper method to turn variable array types into constant array 5307 /// types in certain situations which would otherwise be errors (for 5308 /// GCC compatibility). 5309 static TypeSourceInfo* 5310 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5311 ASTContext &Context, 5312 bool &SizeIsNegative, 5313 llvm::APSInt &Oversized) { 5314 QualType FixedTy 5315 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5316 SizeIsNegative, Oversized); 5317 if (FixedTy.isNull()) 5318 return nullptr; 5319 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5320 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5321 FixedTInfo->getTypeLoc()); 5322 return FixedTInfo; 5323 } 5324 5325 /// \brief Register the given locally-scoped extern "C" declaration so 5326 /// that it can be found later for redeclarations. We include any extern "C" 5327 /// declaration that is not visible in the translation unit here, not just 5328 /// function-scope declarations. 5329 void 5330 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5331 if (!getLangOpts().CPlusPlus && 5332 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5333 // Don't need to track declarations in the TU in C. 5334 return; 5335 5336 // Note that we have a locally-scoped external with this name. 5337 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5338 } 5339 5340 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5341 // FIXME: We can have multiple results via __attribute__((overloadable)). 5342 auto Result = Context.getExternCContextDecl()->lookup(Name); 5343 return Result.empty() ? nullptr : *Result.begin(); 5344 } 5345 5346 /// \brief Diagnose function specifiers on a declaration of an identifier that 5347 /// does not identify a function. 5348 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5349 // FIXME: We should probably indicate the identifier in question to avoid 5350 // confusion for constructs like "virtual int a(), b;" 5351 if (DS.isVirtualSpecified()) 5352 Diag(DS.getVirtualSpecLoc(), 5353 diag::err_virtual_non_function); 5354 5355 if (DS.isExplicitSpecified()) 5356 Diag(DS.getExplicitSpecLoc(), 5357 diag::err_explicit_non_function); 5358 5359 if (DS.isNoreturnSpecified()) 5360 Diag(DS.getNoreturnSpecLoc(), 5361 diag::err_noreturn_non_function); 5362 } 5363 5364 NamedDecl* 5365 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5366 TypeSourceInfo *TInfo, LookupResult &Previous) { 5367 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5368 if (D.getCXXScopeSpec().isSet()) { 5369 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5370 << D.getCXXScopeSpec().getRange(); 5371 D.setInvalidType(); 5372 // Pretend we didn't see the scope specifier. 5373 DC = CurContext; 5374 Previous.clear(); 5375 } 5376 5377 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5378 5379 if (D.getDeclSpec().isInlineSpecified()) 5380 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5381 << getLangOpts().CPlusPlus1z; 5382 if (D.getDeclSpec().isConstexprSpecified()) 5383 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5384 << 1; 5385 if (D.getDeclSpec().isConceptSpecified()) 5386 Diag(D.getDeclSpec().getConceptSpecLoc(), 5387 diag::err_concept_wrong_decl_kind); 5388 5389 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5390 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5391 << D.getName().getSourceRange(); 5392 return nullptr; 5393 } 5394 5395 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5396 if (!NewTD) return nullptr; 5397 5398 // Handle attributes prior to checking for duplicates in MergeVarDecl 5399 ProcessDeclAttributes(S, NewTD, D); 5400 5401 CheckTypedefForVariablyModifiedType(S, NewTD); 5402 5403 bool Redeclaration = D.isRedeclaration(); 5404 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5405 D.setRedeclaration(Redeclaration); 5406 return ND; 5407 } 5408 5409 void 5410 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5411 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5412 // then it shall have block scope. 5413 // Note that variably modified types must be fixed before merging the decl so 5414 // that redeclarations will match. 5415 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5416 QualType T = TInfo->getType(); 5417 if (T->isVariablyModifiedType()) { 5418 getCurFunction()->setHasBranchProtectedScope(); 5419 5420 if (S->getFnParent() == nullptr) { 5421 bool SizeIsNegative; 5422 llvm::APSInt Oversized; 5423 TypeSourceInfo *FixedTInfo = 5424 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5425 SizeIsNegative, 5426 Oversized); 5427 if (FixedTInfo) { 5428 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5429 NewTD->setTypeSourceInfo(FixedTInfo); 5430 } else { 5431 if (SizeIsNegative) 5432 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5433 else if (T->isVariableArrayType()) 5434 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5435 else if (Oversized.getBoolValue()) 5436 Diag(NewTD->getLocation(), diag::err_array_too_large) 5437 << Oversized.toString(10); 5438 else 5439 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5440 NewTD->setInvalidDecl(); 5441 } 5442 } 5443 } 5444 } 5445 5446 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5447 /// declares a typedef-name, either using the 'typedef' type specifier or via 5448 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5449 NamedDecl* 5450 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5451 LookupResult &Previous, bool &Redeclaration) { 5452 // Merge the decl with the existing one if appropriate. If the decl is 5453 // in an outer scope, it isn't the same thing. 5454 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5455 /*AllowInlineNamespace*/false); 5456 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5457 if (!Previous.empty()) { 5458 Redeclaration = true; 5459 MergeTypedefNameDecl(S, NewTD, Previous); 5460 } 5461 5462 // If this is the C FILE type, notify the AST context. 5463 if (IdentifierInfo *II = NewTD->getIdentifier()) 5464 if (!NewTD->isInvalidDecl() && 5465 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5466 if (II->isStr("FILE")) 5467 Context.setFILEDecl(NewTD); 5468 else if (II->isStr("jmp_buf")) 5469 Context.setjmp_bufDecl(NewTD); 5470 else if (II->isStr("sigjmp_buf")) 5471 Context.setsigjmp_bufDecl(NewTD); 5472 else if (II->isStr("ucontext_t")) 5473 Context.setucontext_tDecl(NewTD); 5474 } 5475 5476 return NewTD; 5477 } 5478 5479 /// \brief Determines whether the given declaration is an out-of-scope 5480 /// previous declaration. 5481 /// 5482 /// This routine should be invoked when name lookup has found a 5483 /// previous declaration (PrevDecl) that is not in the scope where a 5484 /// new declaration by the same name is being introduced. If the new 5485 /// declaration occurs in a local scope, previous declarations with 5486 /// linkage may still be considered previous declarations (C99 5487 /// 6.2.2p4-5, C++ [basic.link]p6). 5488 /// 5489 /// \param PrevDecl the previous declaration found by name 5490 /// lookup 5491 /// 5492 /// \param DC the context in which the new declaration is being 5493 /// declared. 5494 /// 5495 /// \returns true if PrevDecl is an out-of-scope previous declaration 5496 /// for a new delcaration with the same name. 5497 static bool 5498 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5499 ASTContext &Context) { 5500 if (!PrevDecl) 5501 return false; 5502 5503 if (!PrevDecl->hasLinkage()) 5504 return false; 5505 5506 if (Context.getLangOpts().CPlusPlus) { 5507 // C++ [basic.link]p6: 5508 // If there is a visible declaration of an entity with linkage 5509 // having the same name and type, ignoring entities declared 5510 // outside the innermost enclosing namespace scope, the block 5511 // scope declaration declares that same entity and receives the 5512 // linkage of the previous declaration. 5513 DeclContext *OuterContext = DC->getRedeclContext(); 5514 if (!OuterContext->isFunctionOrMethod()) 5515 // This rule only applies to block-scope declarations. 5516 return false; 5517 5518 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5519 if (PrevOuterContext->isRecord()) 5520 // We found a member function: ignore it. 5521 return false; 5522 5523 // Find the innermost enclosing namespace for the new and 5524 // previous declarations. 5525 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5526 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5527 5528 // The previous declaration is in a different namespace, so it 5529 // isn't the same function. 5530 if (!OuterContext->Equals(PrevOuterContext)) 5531 return false; 5532 } 5533 5534 return true; 5535 } 5536 5537 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5538 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5539 if (!SS.isSet()) return; 5540 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5541 } 5542 5543 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5544 QualType type = decl->getType(); 5545 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5546 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5547 // Various kinds of declaration aren't allowed to be __autoreleasing. 5548 unsigned kind = -1U; 5549 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5550 if (var->hasAttr<BlocksAttr>()) 5551 kind = 0; // __block 5552 else if (!var->hasLocalStorage()) 5553 kind = 1; // global 5554 } else if (isa<ObjCIvarDecl>(decl)) { 5555 kind = 3; // ivar 5556 } else if (isa<FieldDecl>(decl)) { 5557 kind = 2; // field 5558 } 5559 5560 if (kind != -1U) { 5561 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5562 << kind; 5563 } 5564 } else if (lifetime == Qualifiers::OCL_None) { 5565 // Try to infer lifetime. 5566 if (!type->isObjCLifetimeType()) 5567 return false; 5568 5569 lifetime = type->getObjCARCImplicitLifetime(); 5570 type = Context.getLifetimeQualifiedType(type, lifetime); 5571 decl->setType(type); 5572 } 5573 5574 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5575 // Thread-local variables cannot have lifetime. 5576 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5577 var->getTLSKind()) { 5578 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5579 << var->getType(); 5580 return true; 5581 } 5582 } 5583 5584 return false; 5585 } 5586 5587 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5588 // Ensure that an auto decl is deduced otherwise the checks below might cache 5589 // the wrong linkage. 5590 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5591 5592 // 'weak' only applies to declarations with external linkage. 5593 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5594 if (!ND.isExternallyVisible()) { 5595 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5596 ND.dropAttr<WeakAttr>(); 5597 } 5598 } 5599 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5600 if (ND.isExternallyVisible()) { 5601 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5602 ND.dropAttr<WeakRefAttr>(); 5603 ND.dropAttr<AliasAttr>(); 5604 } 5605 } 5606 5607 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5608 if (VD->hasInit()) { 5609 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5610 assert(VD->isThisDeclarationADefinition() && 5611 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5612 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5613 VD->dropAttr<AliasAttr>(); 5614 } 5615 } 5616 } 5617 5618 // 'selectany' only applies to externally visible variable declarations. 5619 // It does not apply to functions. 5620 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5621 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5622 S.Diag(Attr->getLocation(), 5623 diag::err_attribute_selectany_non_extern_data); 5624 ND.dropAttr<SelectAnyAttr>(); 5625 } 5626 } 5627 5628 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5629 // dll attributes require external linkage. Static locals may have external 5630 // linkage but still cannot be explicitly imported or exported. 5631 auto *VD = dyn_cast<VarDecl>(&ND); 5632 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5633 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5634 << &ND << Attr; 5635 ND.setInvalidDecl(); 5636 } 5637 } 5638 5639 // Virtual functions cannot be marked as 'notail'. 5640 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5641 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5642 if (MD->isVirtual()) { 5643 S.Diag(ND.getLocation(), 5644 diag::err_invalid_attribute_on_virtual_function) 5645 << Attr; 5646 ND.dropAttr<NotTailCalledAttr>(); 5647 } 5648 } 5649 5650 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5651 NamedDecl *NewDecl, 5652 bool IsSpecialization, 5653 bool IsDefinition) { 5654 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5655 OldDecl = OldTD->getTemplatedDecl(); 5656 if (!IsSpecialization) 5657 IsDefinition = false; 5658 } 5659 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5660 NewDecl = NewTD->getTemplatedDecl(); 5661 5662 if (!OldDecl || !NewDecl) 5663 return; 5664 5665 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5666 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5667 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5668 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5669 5670 // dllimport and dllexport are inheritable attributes so we have to exclude 5671 // inherited attribute instances. 5672 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5673 (NewExportAttr && !NewExportAttr->isInherited()); 5674 5675 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5676 // the only exception being explicit specializations. 5677 // Implicitly generated declarations are also excluded for now because there 5678 // is no other way to switch these to use dllimport or dllexport. 5679 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5680 5681 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5682 // Allow with a warning for free functions and global variables. 5683 bool JustWarn = false; 5684 if (!OldDecl->isCXXClassMember()) { 5685 auto *VD = dyn_cast<VarDecl>(OldDecl); 5686 if (VD && !VD->getDescribedVarTemplate()) 5687 JustWarn = true; 5688 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5689 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5690 JustWarn = true; 5691 } 5692 5693 // We cannot change a declaration that's been used because IR has already 5694 // been emitted. Dllimported functions will still work though (modulo 5695 // address equality) as they can use the thunk. 5696 if (OldDecl->isUsed()) 5697 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5698 JustWarn = false; 5699 5700 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5701 : diag::err_attribute_dll_redeclaration; 5702 S.Diag(NewDecl->getLocation(), DiagID) 5703 << NewDecl 5704 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5705 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5706 if (!JustWarn) { 5707 NewDecl->setInvalidDecl(); 5708 return; 5709 } 5710 } 5711 5712 // A redeclaration is not allowed to drop a dllimport attribute, the only 5713 // exceptions being inline function definitions, local extern declarations, 5714 // qualified friend declarations or special MSVC extension: in the last case, 5715 // the declaration is treated as if it were marked dllexport. 5716 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5717 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5718 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5719 // Ignore static data because out-of-line definitions are diagnosed 5720 // separately. 5721 IsStaticDataMember = VD->isStaticDataMember(); 5722 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5723 VarDecl::DeclarationOnly; 5724 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5725 IsInline = FD->isInlined(); 5726 IsQualifiedFriend = FD->getQualifier() && 5727 FD->getFriendObjectKind() == Decl::FOK_Declared; 5728 } 5729 5730 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5731 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5732 if (IsMicrosoft && IsDefinition) { 5733 S.Diag(NewDecl->getLocation(), 5734 diag::warn_redeclaration_without_import_attribute) 5735 << NewDecl; 5736 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5737 NewDecl->dropAttr<DLLImportAttr>(); 5738 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5739 NewImportAttr->getRange(), S.Context, 5740 NewImportAttr->getSpellingListIndex())); 5741 } else { 5742 S.Diag(NewDecl->getLocation(), 5743 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5744 << NewDecl << OldImportAttr; 5745 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5746 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5747 OldDecl->dropAttr<DLLImportAttr>(); 5748 NewDecl->dropAttr<DLLImportAttr>(); 5749 } 5750 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5751 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5752 OldDecl->dropAttr<DLLImportAttr>(); 5753 NewDecl->dropAttr<DLLImportAttr>(); 5754 S.Diag(NewDecl->getLocation(), 5755 diag::warn_dllimport_dropped_from_inline_function) 5756 << NewDecl << OldImportAttr; 5757 } 5758 } 5759 5760 /// Given that we are within the definition of the given function, 5761 /// will that definition behave like C99's 'inline', where the 5762 /// definition is discarded except for optimization purposes? 5763 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5764 // Try to avoid calling GetGVALinkageForFunction. 5765 5766 // All cases of this require the 'inline' keyword. 5767 if (!FD->isInlined()) return false; 5768 5769 // This is only possible in C++ with the gnu_inline attribute. 5770 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5771 return false; 5772 5773 // Okay, go ahead and call the relatively-more-expensive function. 5774 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5775 } 5776 5777 /// Determine whether a variable is extern "C" prior to attaching 5778 /// an initializer. We can't just call isExternC() here, because that 5779 /// will also compute and cache whether the declaration is externally 5780 /// visible, which might change when we attach the initializer. 5781 /// 5782 /// This can only be used if the declaration is known to not be a 5783 /// redeclaration of an internal linkage declaration. 5784 /// 5785 /// For instance: 5786 /// 5787 /// auto x = []{}; 5788 /// 5789 /// Attaching the initializer here makes this declaration not externally 5790 /// visible, because its type has internal linkage. 5791 /// 5792 /// FIXME: This is a hack. 5793 template<typename T> 5794 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5795 if (S.getLangOpts().CPlusPlus) { 5796 // In C++, the overloadable attribute negates the effects of extern "C". 5797 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5798 return false; 5799 5800 // So do CUDA's host/device attributes. 5801 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5802 D->template hasAttr<CUDAHostAttr>())) 5803 return false; 5804 } 5805 return D->isExternC(); 5806 } 5807 5808 static bool shouldConsiderLinkage(const VarDecl *VD) { 5809 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5810 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5811 return VD->hasExternalStorage(); 5812 if (DC->isFileContext()) 5813 return true; 5814 if (DC->isRecord()) 5815 return false; 5816 llvm_unreachable("Unexpected context"); 5817 } 5818 5819 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5820 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5821 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5822 isa<OMPDeclareReductionDecl>(DC)) 5823 return true; 5824 if (DC->isRecord()) 5825 return false; 5826 llvm_unreachable("Unexpected context"); 5827 } 5828 5829 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5830 AttributeList::Kind Kind) { 5831 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5832 if (L->getKind() == Kind) 5833 return true; 5834 return false; 5835 } 5836 5837 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5838 AttributeList::Kind Kind) { 5839 // Check decl attributes on the DeclSpec. 5840 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5841 return true; 5842 5843 // Walk the declarator structure, checking decl attributes that were in a type 5844 // position to the decl itself. 5845 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5846 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5847 return true; 5848 } 5849 5850 // Finally, check attributes on the decl itself. 5851 return hasParsedAttr(S, PD.getAttributes(), Kind); 5852 } 5853 5854 /// Adjust the \c DeclContext for a function or variable that might be a 5855 /// function-local external declaration. 5856 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5857 if (!DC->isFunctionOrMethod()) 5858 return false; 5859 5860 // If this is a local extern function or variable declared within a function 5861 // template, don't add it into the enclosing namespace scope until it is 5862 // instantiated; it might have a dependent type right now. 5863 if (DC->isDependentContext()) 5864 return true; 5865 5866 // C++11 [basic.link]p7: 5867 // When a block scope declaration of an entity with linkage is not found to 5868 // refer to some other declaration, then that entity is a member of the 5869 // innermost enclosing namespace. 5870 // 5871 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5872 // semantically-enclosing namespace, not a lexically-enclosing one. 5873 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5874 DC = DC->getParent(); 5875 return true; 5876 } 5877 5878 /// \brief Returns true if given declaration has external C language linkage. 5879 static bool isDeclExternC(const Decl *D) { 5880 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5881 return FD->isExternC(); 5882 if (const auto *VD = dyn_cast<VarDecl>(D)) 5883 return VD->isExternC(); 5884 5885 llvm_unreachable("Unknown type of decl!"); 5886 } 5887 5888 NamedDecl *Sema::ActOnVariableDeclarator( 5889 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5890 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5891 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5892 QualType R = TInfo->getType(); 5893 DeclarationName Name = GetNameForDeclarator(D).getName(); 5894 5895 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5896 5897 if (D.isDecompositionDeclarator()) { 5898 AddToScope = false; 5899 // Take the name of the first declarator as our name for diagnostic 5900 // purposes. 5901 auto &Decomp = D.getDecompositionDeclarator(); 5902 if (!Decomp.bindings().empty()) { 5903 II = Decomp.bindings()[0].Name; 5904 Name = II; 5905 } 5906 } else if (!II) { 5907 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5908 << Name; 5909 return nullptr; 5910 } 5911 5912 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5913 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5914 // argument. 5915 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5916 Diag(D.getIdentifierLoc(), 5917 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5918 << R; 5919 D.setInvalidType(); 5920 return nullptr; 5921 } 5922 5923 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5924 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5925 5926 // dllimport globals without explicit storage class are treated as extern. We 5927 // have to change the storage class this early to get the right DeclContext. 5928 if (SC == SC_None && !DC->isRecord() && 5929 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5930 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5931 SC = SC_Extern; 5932 5933 DeclContext *OriginalDC = DC; 5934 bool IsLocalExternDecl = SC == SC_Extern && 5935 adjustContextForLocalExternDecl(DC); 5936 5937 if (getLangOpts().OpenCL) { 5938 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5939 QualType NR = R; 5940 while (NR->isPointerType()) { 5941 if (NR->isFunctionPointerType()) { 5942 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5943 D.setInvalidType(); 5944 break; 5945 } 5946 NR = NR->getPointeeType(); 5947 } 5948 5949 if (!getOpenCLOptions().cl_khr_fp16) { 5950 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5951 // half array type (unless the cl_khr_fp16 extension is enabled). 5952 if (Context.getBaseElementType(R)->isHalfType()) { 5953 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5954 D.setInvalidType(); 5955 } 5956 } 5957 } 5958 5959 if (SCSpec == DeclSpec::SCS_mutable) { 5960 // mutable can only appear on non-static class members, so it's always 5961 // an error here 5962 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5963 D.setInvalidType(); 5964 SC = SC_None; 5965 } 5966 5967 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5968 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5969 D.getDeclSpec().getStorageClassSpecLoc())) { 5970 // In C++11, the 'register' storage class specifier is deprecated. 5971 // Suppress the warning in system macros, it's used in macros in some 5972 // popular C system headers, such as in glibc's htonl() macro. 5973 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5974 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5975 : diag::warn_deprecated_register) 5976 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5977 } 5978 5979 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5980 5981 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5982 // C99 6.9p2: The storage-class specifiers auto and register shall not 5983 // appear in the declaration specifiers in an external declaration. 5984 // Global Register+Asm is a GNU extension we support. 5985 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5986 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5987 D.setInvalidType(); 5988 } 5989 } 5990 5991 if (getLangOpts().OpenCL) { 5992 // OpenCL v1.2 s6.9.b p4: 5993 // The sampler type cannot be used with the __local and __global address 5994 // space qualifiers. 5995 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5996 R.getAddressSpace() == LangAS::opencl_global)) { 5997 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5998 } 5999 6000 // OpenCL 1.2 spec, p6.9 r: 6001 // The event type cannot be used to declare a program scope variable. 6002 // The event type cannot be used with the __local, __constant and __global 6003 // address space qualifiers. 6004 if (R->isEventT()) { 6005 if (S->getParent() == nullptr) { 6006 Diag(D.getLocStart(), diag::err_event_t_global_var); 6007 D.setInvalidType(); 6008 } 6009 6010 if (R.getAddressSpace()) { 6011 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6012 D.setInvalidType(); 6013 } 6014 } 6015 } 6016 6017 bool IsExplicitSpecialization = false; 6018 bool IsVariableTemplateSpecialization = false; 6019 bool IsPartialSpecialization = false; 6020 bool IsVariableTemplate = false; 6021 VarDecl *NewVD = nullptr; 6022 VarTemplateDecl *NewTemplate = nullptr; 6023 TemplateParameterList *TemplateParams = nullptr; 6024 if (!getLangOpts().CPlusPlus) { 6025 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6026 D.getIdentifierLoc(), II, 6027 R, TInfo, SC); 6028 6029 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6030 ParsingInitForAutoVars.insert(NewVD); 6031 6032 if (D.isInvalidType()) 6033 NewVD->setInvalidDecl(); 6034 } else { 6035 bool Invalid = false; 6036 6037 if (DC->isRecord() && !CurContext->isRecord()) { 6038 // This is an out-of-line definition of a static data member. 6039 switch (SC) { 6040 case SC_None: 6041 break; 6042 case SC_Static: 6043 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6044 diag::err_static_out_of_line) 6045 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6046 break; 6047 case SC_Auto: 6048 case SC_Register: 6049 case SC_Extern: 6050 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6051 // to names of variables declared in a block or to function parameters. 6052 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6053 // of class members 6054 6055 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6056 diag::err_storage_class_for_static_member) 6057 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6058 break; 6059 case SC_PrivateExtern: 6060 llvm_unreachable("C storage class in c++!"); 6061 } 6062 } 6063 6064 if (SC == SC_Static && CurContext->isRecord()) { 6065 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6066 if (RD->isLocalClass()) 6067 Diag(D.getIdentifierLoc(), 6068 diag::err_static_data_member_not_allowed_in_local_class) 6069 << Name << RD->getDeclName(); 6070 6071 // C++98 [class.union]p1: If a union contains a static data member, 6072 // the program is ill-formed. C++11 drops this restriction. 6073 if (RD->isUnion()) 6074 Diag(D.getIdentifierLoc(), 6075 getLangOpts().CPlusPlus11 6076 ? diag::warn_cxx98_compat_static_data_member_in_union 6077 : diag::ext_static_data_member_in_union) << Name; 6078 // We conservatively disallow static data members in anonymous structs. 6079 else if (!RD->getDeclName()) 6080 Diag(D.getIdentifierLoc(), 6081 diag::err_static_data_member_not_allowed_in_anon_struct) 6082 << Name << RD->isUnion(); 6083 } 6084 } 6085 6086 // Match up the template parameter lists with the scope specifier, then 6087 // determine whether we have a template or a template specialization. 6088 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6089 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6090 D.getCXXScopeSpec(), 6091 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6092 ? D.getName().TemplateId 6093 : nullptr, 6094 TemplateParamLists, 6095 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6096 6097 if (TemplateParams) { 6098 if (!TemplateParams->size() && 6099 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6100 // There is an extraneous 'template<>' for this variable. Complain 6101 // about it, but allow the declaration of the variable. 6102 Diag(TemplateParams->getTemplateLoc(), 6103 diag::err_template_variable_noparams) 6104 << II 6105 << SourceRange(TemplateParams->getTemplateLoc(), 6106 TemplateParams->getRAngleLoc()); 6107 TemplateParams = nullptr; 6108 } else { 6109 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6110 // This is an explicit specialization or a partial specialization. 6111 // FIXME: Check that we can declare a specialization here. 6112 IsVariableTemplateSpecialization = true; 6113 IsPartialSpecialization = TemplateParams->size() > 0; 6114 } else { // if (TemplateParams->size() > 0) 6115 // This is a template declaration. 6116 IsVariableTemplate = true; 6117 6118 // Check that we can declare a template here. 6119 if (CheckTemplateDeclScope(S, TemplateParams)) 6120 return nullptr; 6121 6122 // Only C++1y supports variable templates (N3651). 6123 Diag(D.getIdentifierLoc(), 6124 getLangOpts().CPlusPlus14 6125 ? diag::warn_cxx11_compat_variable_template 6126 : diag::ext_variable_template); 6127 } 6128 } 6129 } else { 6130 assert( 6131 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6132 "should have a 'template<>' for this decl"); 6133 } 6134 6135 if (IsVariableTemplateSpecialization) { 6136 SourceLocation TemplateKWLoc = 6137 TemplateParamLists.size() > 0 6138 ? TemplateParamLists[0]->getTemplateLoc() 6139 : SourceLocation(); 6140 DeclResult Res = ActOnVarTemplateSpecialization( 6141 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6142 IsPartialSpecialization); 6143 if (Res.isInvalid()) 6144 return nullptr; 6145 NewVD = cast<VarDecl>(Res.get()); 6146 AddToScope = false; 6147 } else if (D.isDecompositionDeclarator()) { 6148 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6149 D.getIdentifierLoc(), R, TInfo, SC, 6150 Bindings); 6151 } else 6152 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6153 D.getIdentifierLoc(), II, R, TInfo, SC); 6154 6155 // If this is supposed to be a variable template, create it as such. 6156 if (IsVariableTemplate) { 6157 NewTemplate = 6158 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6159 TemplateParams, NewVD); 6160 NewVD->setDescribedVarTemplate(NewTemplate); 6161 } 6162 6163 // If this decl has an auto type in need of deduction, make a note of the 6164 // Decl so we can diagnose uses of it in its own initializer. 6165 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6166 ParsingInitForAutoVars.insert(NewVD); 6167 6168 if (D.isInvalidType() || Invalid) { 6169 NewVD->setInvalidDecl(); 6170 if (NewTemplate) 6171 NewTemplate->setInvalidDecl(); 6172 } 6173 6174 SetNestedNameSpecifier(NewVD, D); 6175 6176 // If we have any template parameter lists that don't directly belong to 6177 // the variable (matching the scope specifier), store them. 6178 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6179 if (TemplateParamLists.size() > VDTemplateParamLists) 6180 NewVD->setTemplateParameterListsInfo( 6181 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6182 6183 if (D.getDeclSpec().isConstexprSpecified()) { 6184 NewVD->setConstexpr(true); 6185 // C++1z [dcl.spec.constexpr]p1: 6186 // A static data member declared with the constexpr specifier is 6187 // implicitly an inline variable. 6188 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6189 NewVD->setImplicitlyInline(); 6190 } 6191 6192 if (D.getDeclSpec().isConceptSpecified()) { 6193 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6194 VTD->setConcept(); 6195 6196 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6197 // be declared with the thread_local, inline, friend, or constexpr 6198 // specifiers, [...] 6199 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6200 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6201 diag::err_concept_decl_invalid_specifiers) 6202 << 0 << 0; 6203 NewVD->setInvalidDecl(true); 6204 } 6205 6206 if (D.getDeclSpec().isConstexprSpecified()) { 6207 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6208 diag::err_concept_decl_invalid_specifiers) 6209 << 0 << 3; 6210 NewVD->setInvalidDecl(true); 6211 } 6212 6213 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6214 // applied only to the definition of a function template or variable 6215 // template, declared in namespace scope. 6216 if (IsVariableTemplateSpecialization) { 6217 Diag(D.getDeclSpec().getConceptSpecLoc(), 6218 diag::err_concept_specified_specialization) 6219 << (IsPartialSpecialization ? 2 : 1); 6220 } 6221 6222 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6223 // following restrictions: 6224 // - The declared type shall have the type bool. 6225 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6226 !NewVD->isInvalidDecl()) { 6227 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6228 NewVD->setInvalidDecl(true); 6229 } 6230 } 6231 } 6232 6233 if (D.getDeclSpec().isInlineSpecified()) { 6234 if (!getLangOpts().CPlusPlus) { 6235 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6236 << 0; 6237 } else if (CurContext->isFunctionOrMethod()) { 6238 // 'inline' is not allowed on block scope variable declaration. 6239 Diag(D.getDeclSpec().getInlineSpecLoc(), 6240 diag::err_inline_declaration_block_scope) << Name 6241 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6242 } else { 6243 Diag(D.getDeclSpec().getInlineSpecLoc(), 6244 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6245 : diag::ext_inline_variable); 6246 NewVD->setInlineSpecified(); 6247 } 6248 } 6249 6250 // Set the lexical context. If the declarator has a C++ scope specifier, the 6251 // lexical context will be different from the semantic context. 6252 NewVD->setLexicalDeclContext(CurContext); 6253 if (NewTemplate) 6254 NewTemplate->setLexicalDeclContext(CurContext); 6255 6256 if (IsLocalExternDecl) { 6257 if (D.isDecompositionDeclarator()) 6258 for (auto *B : Bindings) 6259 B->setLocalExternDecl(); 6260 else 6261 NewVD->setLocalExternDecl(); 6262 } 6263 6264 bool EmitTLSUnsupportedError = false; 6265 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6266 // C++11 [dcl.stc]p4: 6267 // When thread_local is applied to a variable of block scope the 6268 // storage-class-specifier static is implied if it does not appear 6269 // explicitly. 6270 // Core issue: 'static' is not implied if the variable is declared 6271 // 'extern'. 6272 if (NewVD->hasLocalStorage() && 6273 (SCSpec != DeclSpec::SCS_unspecified || 6274 TSCS != DeclSpec::TSCS_thread_local || 6275 !DC->isFunctionOrMethod())) 6276 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6277 diag::err_thread_non_global) 6278 << DeclSpec::getSpecifierName(TSCS); 6279 else if (!Context.getTargetInfo().isTLSSupported()) { 6280 if (getLangOpts().CUDA) { 6281 // Postpone error emission until we've collected attributes required to 6282 // figure out whether it's a host or device variable and whether the 6283 // error should be ignored. 6284 EmitTLSUnsupportedError = true; 6285 // We still need to mark the variable as TLS so it shows up in AST with 6286 // proper storage class for other tools to use even if we're not going 6287 // to emit any code for it. 6288 NewVD->setTSCSpec(TSCS); 6289 } else 6290 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6291 diag::err_thread_unsupported); 6292 } else 6293 NewVD->setTSCSpec(TSCS); 6294 } 6295 6296 // C99 6.7.4p3 6297 // An inline definition of a function with external linkage shall 6298 // not contain a definition of a modifiable object with static or 6299 // thread storage duration... 6300 // We only apply this when the function is required to be defined 6301 // elsewhere, i.e. when the function is not 'extern inline'. Note 6302 // that a local variable with thread storage duration still has to 6303 // be marked 'static'. Also note that it's possible to get these 6304 // semantics in C++ using __attribute__((gnu_inline)). 6305 if (SC == SC_Static && S->getFnParent() != nullptr && 6306 !NewVD->getType().isConstQualified()) { 6307 FunctionDecl *CurFD = getCurFunctionDecl(); 6308 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6309 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6310 diag::warn_static_local_in_extern_inline); 6311 MaybeSuggestAddingStaticToDecl(CurFD); 6312 } 6313 } 6314 6315 if (D.getDeclSpec().isModulePrivateSpecified()) { 6316 if (IsVariableTemplateSpecialization) 6317 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6318 << (IsPartialSpecialization ? 1 : 0) 6319 << FixItHint::CreateRemoval( 6320 D.getDeclSpec().getModulePrivateSpecLoc()); 6321 else if (IsExplicitSpecialization) 6322 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6323 << 2 6324 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6325 else if (NewVD->hasLocalStorage()) 6326 Diag(NewVD->getLocation(), diag::err_module_private_local) 6327 << 0 << NewVD->getDeclName() 6328 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6330 else { 6331 NewVD->setModulePrivate(); 6332 if (NewTemplate) 6333 NewTemplate->setModulePrivate(); 6334 for (auto *B : Bindings) 6335 B->setModulePrivate(); 6336 } 6337 } 6338 6339 // Handle attributes prior to checking for duplicates in MergeVarDecl 6340 ProcessDeclAttributes(S, NewVD, D); 6341 6342 if (getLangOpts().CUDA) { 6343 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6344 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6345 diag::err_thread_unsupported); 6346 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6347 // storage [duration]." 6348 if (SC == SC_None && S->getFnParent() != nullptr && 6349 (NewVD->hasAttr<CUDASharedAttr>() || 6350 NewVD->hasAttr<CUDAConstantAttr>())) { 6351 NewVD->setStorageClass(SC_Static); 6352 } 6353 } 6354 6355 // Ensure that dllimport globals without explicit storage class are treated as 6356 // extern. The storage class is set above using parsed attributes. Now we can 6357 // check the VarDecl itself. 6358 assert(!NewVD->hasAttr<DLLImportAttr>() || 6359 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6360 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6361 6362 // In auto-retain/release, infer strong retension for variables of 6363 // retainable type. 6364 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6365 NewVD->setInvalidDecl(); 6366 6367 // Handle GNU asm-label extension (encoded as an attribute). 6368 if (Expr *E = (Expr*)D.getAsmLabel()) { 6369 // The parser guarantees this is a string. 6370 StringLiteral *SE = cast<StringLiteral>(E); 6371 StringRef Label = SE->getString(); 6372 if (S->getFnParent() != nullptr) { 6373 switch (SC) { 6374 case SC_None: 6375 case SC_Auto: 6376 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6377 break; 6378 case SC_Register: 6379 // Local Named register 6380 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6381 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6382 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6383 break; 6384 case SC_Static: 6385 case SC_Extern: 6386 case SC_PrivateExtern: 6387 break; 6388 } 6389 } else if (SC == SC_Register) { 6390 // Global Named register 6391 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6392 const auto &TI = Context.getTargetInfo(); 6393 bool HasSizeMismatch; 6394 6395 if (!TI.isValidGCCRegisterName(Label)) 6396 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6397 else if (!TI.validateGlobalRegisterVariable(Label, 6398 Context.getTypeSize(R), 6399 HasSizeMismatch)) 6400 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6401 else if (HasSizeMismatch) 6402 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6403 } 6404 6405 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6406 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6407 NewVD->setInvalidDecl(true); 6408 } 6409 } 6410 6411 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6412 Context, Label, 0)); 6413 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6414 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6415 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6416 if (I != ExtnameUndeclaredIdentifiers.end()) { 6417 if (isDeclExternC(NewVD)) { 6418 NewVD->addAttr(I->second); 6419 ExtnameUndeclaredIdentifiers.erase(I); 6420 } else 6421 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6422 << /*Variable*/1 << NewVD; 6423 } 6424 } 6425 6426 // Diagnose shadowed variables before filtering for scope. 6427 if (D.getCXXScopeSpec().isEmpty()) 6428 CheckShadow(S, NewVD, Previous); 6429 6430 // Don't consider existing declarations that are in a different 6431 // scope and are out-of-semantic-context declarations (if the new 6432 // declaration has linkage). 6433 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6434 D.getCXXScopeSpec().isNotEmpty() || 6435 IsExplicitSpecialization || 6436 IsVariableTemplateSpecialization); 6437 6438 // Check whether the previous declaration is in the same block scope. This 6439 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6440 if (getLangOpts().CPlusPlus && 6441 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6442 NewVD->setPreviousDeclInSameBlockScope( 6443 Previous.isSingleResult() && !Previous.isShadowed() && 6444 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6445 6446 if (!getLangOpts().CPlusPlus) { 6447 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6448 } else { 6449 // If this is an explicit specialization of a static data member, check it. 6450 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6451 CheckMemberSpecialization(NewVD, Previous)) 6452 NewVD->setInvalidDecl(); 6453 6454 // Merge the decl with the existing one if appropriate. 6455 if (!Previous.empty()) { 6456 if (Previous.isSingleResult() && 6457 isa<FieldDecl>(Previous.getFoundDecl()) && 6458 D.getCXXScopeSpec().isSet()) { 6459 // The user tried to define a non-static data member 6460 // out-of-line (C++ [dcl.meaning]p1). 6461 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6462 << D.getCXXScopeSpec().getRange(); 6463 Previous.clear(); 6464 NewVD->setInvalidDecl(); 6465 } 6466 } else if (D.getCXXScopeSpec().isSet()) { 6467 // No previous declaration in the qualifying scope. 6468 Diag(D.getIdentifierLoc(), diag::err_no_member) 6469 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6470 << D.getCXXScopeSpec().getRange(); 6471 NewVD->setInvalidDecl(); 6472 } 6473 6474 if (!IsVariableTemplateSpecialization) 6475 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6476 6477 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6478 // an explicit specialization (14.8.3) or a partial specialization of a 6479 // concept definition. 6480 if (IsVariableTemplateSpecialization && 6481 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6482 Previous.isSingleResult()) { 6483 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6484 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6485 if (VarTmpl->isConcept()) { 6486 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6487 << 1 /*variable*/ 6488 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6489 : 1 /*explicitly specialized*/); 6490 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6491 NewVD->setInvalidDecl(); 6492 } 6493 } 6494 } 6495 6496 if (NewTemplate) { 6497 VarTemplateDecl *PrevVarTemplate = 6498 NewVD->getPreviousDecl() 6499 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6500 : nullptr; 6501 6502 // Check the template parameter list of this declaration, possibly 6503 // merging in the template parameter list from the previous variable 6504 // template declaration. 6505 if (CheckTemplateParameterList( 6506 TemplateParams, 6507 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6508 : nullptr, 6509 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6510 DC->isDependentContext()) 6511 ? TPC_ClassTemplateMember 6512 : TPC_VarTemplate)) 6513 NewVD->setInvalidDecl(); 6514 6515 // If we are providing an explicit specialization of a static variable 6516 // template, make a note of that. 6517 if (PrevVarTemplate && 6518 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6519 PrevVarTemplate->setMemberSpecialization(); 6520 } 6521 } 6522 6523 ProcessPragmaWeak(S, NewVD); 6524 6525 // If this is the first declaration of an extern C variable, update 6526 // the map of such variables. 6527 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6528 isIncompleteDeclExternC(*this, NewVD)) 6529 RegisterLocallyScopedExternCDecl(NewVD, S); 6530 6531 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6532 Decl *ManglingContextDecl; 6533 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6534 NewVD->getDeclContext(), ManglingContextDecl)) { 6535 Context.setManglingNumber( 6536 NewVD, MCtx->getManglingNumber( 6537 NewVD, getMSManglingNumber(getLangOpts(), S))); 6538 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6539 } 6540 } 6541 6542 // Special handling of variable named 'main'. 6543 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6544 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6545 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6546 6547 // C++ [basic.start.main]p3 6548 // A program that declares a variable main at global scope is ill-formed. 6549 if (getLangOpts().CPlusPlus) 6550 Diag(D.getLocStart(), diag::err_main_global_variable); 6551 6552 // In C, and external-linkage variable named main results in undefined 6553 // behavior. 6554 else if (NewVD->hasExternalFormalLinkage()) 6555 Diag(D.getLocStart(), diag::warn_main_redefined); 6556 } 6557 6558 if (D.isRedeclaration() && !Previous.empty()) { 6559 checkDLLAttributeRedeclaration( 6560 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6561 IsExplicitSpecialization, D.isFunctionDefinition()); 6562 } 6563 6564 if (NewTemplate) { 6565 if (NewVD->isInvalidDecl()) 6566 NewTemplate->setInvalidDecl(); 6567 ActOnDocumentableDecl(NewTemplate); 6568 return NewTemplate; 6569 } 6570 6571 return NewVD; 6572 } 6573 6574 /// Enum describing the %select options in diag::warn_decl_shadow. 6575 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6576 6577 /// Determine what kind of declaration we're shadowing. 6578 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6579 const DeclContext *OldDC) { 6580 if (isa<RecordDecl>(OldDC)) 6581 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6582 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6583 } 6584 6585 /// Return the location of the capture if the given lambda captures the given 6586 /// variable \p VD, or an invalid source location otherwise. 6587 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6588 const VarDecl *VD) { 6589 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6590 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6591 return Capture.getLocation(); 6592 } 6593 return SourceLocation(); 6594 } 6595 6596 /// \brief Diagnose variable or built-in function shadowing. Implements 6597 /// -Wshadow. 6598 /// 6599 /// This method is called whenever a VarDecl is added to a "useful" 6600 /// scope. 6601 /// 6602 /// \param S the scope in which the shadowing name is being declared 6603 /// \param R the lookup of the name 6604 /// 6605 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6606 // Return if warning is ignored. 6607 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6608 return; 6609 6610 // Don't diagnose declarations at file scope. 6611 if (D->hasGlobalStorage()) 6612 return; 6613 6614 DeclContext *NewDC = D->getDeclContext(); 6615 6616 // Only diagnose if we're shadowing an unambiguous field or variable. 6617 if (R.getResultKind() != LookupResult::Found) 6618 return; 6619 6620 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6621 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6622 return; 6623 6624 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6625 // Fields are not shadowed by variables in C++ static methods. 6626 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6627 if (MD->isStatic()) 6628 return; 6629 6630 // Fields shadowed by constructor parameters are a special case. Usually 6631 // the constructor initializes the field with the parameter. 6632 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6633 // Remember that this was shadowed so we can either warn about its 6634 // modification or its existence depending on warning settings. 6635 D = D->getCanonicalDecl(); 6636 ShadowingDecls.insert({D, FD}); 6637 return; 6638 } 6639 } 6640 6641 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6642 if (shadowedVar->isExternC()) { 6643 // For shadowing external vars, make sure that we point to the global 6644 // declaration, not a locally scoped extern declaration. 6645 for (auto I : shadowedVar->redecls()) 6646 if (I->isFileVarDecl()) { 6647 ShadowedDecl = I; 6648 break; 6649 } 6650 } 6651 6652 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6653 6654 unsigned WarningDiag = diag::warn_decl_shadow; 6655 SourceLocation CaptureLoc; 6656 if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) { 6657 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6658 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6659 if (RD->getLambdaCaptureDefault() == LCD_None) { 6660 // Try to avoid warnings for lambdas with an explicit capture list. 6661 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6662 // Warn only when the lambda captures the shadowed decl explicitly. 6663 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6664 if (CaptureLoc.isInvalid()) 6665 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6666 } else { 6667 // Remember that this was shadowed so we can avoid the warning if the 6668 // shadowed decl isn't captured and the warning settings allow it. 6669 cast<LambdaScopeInfo>(getCurFunction()) 6670 ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)}); 6671 return; 6672 } 6673 } 6674 } 6675 } 6676 6677 // Only warn about certain kinds of shadowing for class members. 6678 if (NewDC && NewDC->isRecord()) { 6679 // In particular, don't warn about shadowing non-class members. 6680 if (!OldDC->isRecord()) 6681 return; 6682 6683 // TODO: should we warn about static data members shadowing 6684 // static data members from base classes? 6685 6686 // TODO: don't diagnose for inaccessible shadowed members. 6687 // This is hard to do perfectly because we might friend the 6688 // shadowing context, but that's just a false negative. 6689 } 6690 6691 6692 DeclarationName Name = R.getLookupName(); 6693 6694 // Emit warning and note. 6695 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6696 return; 6697 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6698 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6699 if (!CaptureLoc.isInvalid()) 6700 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6701 << Name << /*explicitly*/ 1; 6702 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6703 } 6704 6705 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 6706 /// when these variables are captured by the lambda. 6707 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 6708 for (const auto &Shadow : LSI->ShadowingDecls) { 6709 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 6710 // Try to avoid the warning when the shadowed decl isn't captured. 6711 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 6712 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6713 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 6714 ? diag::warn_decl_shadow_uncaptured_local 6715 : diag::warn_decl_shadow) 6716 << Shadow.VD->getDeclName() 6717 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 6718 if (!CaptureLoc.isInvalid()) 6719 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6720 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 6721 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6722 } 6723 } 6724 6725 /// \brief Check -Wshadow without the advantage of a previous lookup. 6726 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6727 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6728 return; 6729 6730 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6731 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6732 LookupName(R, S); 6733 CheckShadow(S, D, R); 6734 } 6735 6736 /// Check if 'E', which is an expression that is about to be modified, refers 6737 /// to a constructor parameter that shadows a field. 6738 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6739 // Quickly ignore expressions that can't be shadowing ctor parameters. 6740 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6741 return; 6742 E = E->IgnoreParenImpCasts(); 6743 auto *DRE = dyn_cast<DeclRefExpr>(E); 6744 if (!DRE) 6745 return; 6746 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6747 auto I = ShadowingDecls.find(D); 6748 if (I == ShadowingDecls.end()) 6749 return; 6750 const NamedDecl *ShadowedDecl = I->second; 6751 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6752 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6753 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6754 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6755 6756 // Avoid issuing multiple warnings about the same decl. 6757 ShadowingDecls.erase(I); 6758 } 6759 6760 /// Check for conflict between this global or extern "C" declaration and 6761 /// previous global or extern "C" declarations. This is only used in C++. 6762 template<typename T> 6763 static bool checkGlobalOrExternCConflict( 6764 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6765 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6766 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6767 6768 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6769 // The common case: this global doesn't conflict with any extern "C" 6770 // declaration. 6771 return false; 6772 } 6773 6774 if (Prev) { 6775 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6776 // Both the old and new declarations have C language linkage. This is a 6777 // redeclaration. 6778 Previous.clear(); 6779 Previous.addDecl(Prev); 6780 return true; 6781 } 6782 6783 // This is a global, non-extern "C" declaration, and there is a previous 6784 // non-global extern "C" declaration. Diagnose if this is a variable 6785 // declaration. 6786 if (!isa<VarDecl>(ND)) 6787 return false; 6788 } else { 6789 // The declaration is extern "C". Check for any declaration in the 6790 // translation unit which might conflict. 6791 if (IsGlobal) { 6792 // We have already performed the lookup into the translation unit. 6793 IsGlobal = false; 6794 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6795 I != E; ++I) { 6796 if (isa<VarDecl>(*I)) { 6797 Prev = *I; 6798 break; 6799 } 6800 } 6801 } else { 6802 DeclContext::lookup_result R = 6803 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6804 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6805 I != E; ++I) { 6806 if (isa<VarDecl>(*I)) { 6807 Prev = *I; 6808 break; 6809 } 6810 // FIXME: If we have any other entity with this name in global scope, 6811 // the declaration is ill-formed, but that is a defect: it breaks the 6812 // 'stat' hack, for instance. Only variables can have mangled name 6813 // clashes with extern "C" declarations, so only they deserve a 6814 // diagnostic. 6815 } 6816 } 6817 6818 if (!Prev) 6819 return false; 6820 } 6821 6822 // Use the first declaration's location to ensure we point at something which 6823 // is lexically inside an extern "C" linkage-spec. 6824 assert(Prev && "should have found a previous declaration to diagnose"); 6825 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6826 Prev = FD->getFirstDecl(); 6827 else 6828 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6829 6830 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6831 << IsGlobal << ND; 6832 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6833 << IsGlobal; 6834 return false; 6835 } 6836 6837 /// Apply special rules for handling extern "C" declarations. Returns \c true 6838 /// if we have found that this is a redeclaration of some prior entity. 6839 /// 6840 /// Per C++ [dcl.link]p6: 6841 /// Two declarations [for a function or variable] with C language linkage 6842 /// with the same name that appear in different scopes refer to the same 6843 /// [entity]. An entity with C language linkage shall not be declared with 6844 /// the same name as an entity in global scope. 6845 template<typename T> 6846 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6847 LookupResult &Previous) { 6848 if (!S.getLangOpts().CPlusPlus) { 6849 // In C, when declaring a global variable, look for a corresponding 'extern' 6850 // variable declared in function scope. We don't need this in C++, because 6851 // we find local extern decls in the surrounding file-scope DeclContext. 6852 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6853 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6854 Previous.clear(); 6855 Previous.addDecl(Prev); 6856 return true; 6857 } 6858 } 6859 return false; 6860 } 6861 6862 // A declaration in the translation unit can conflict with an extern "C" 6863 // declaration. 6864 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6865 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6866 6867 // An extern "C" declaration can conflict with a declaration in the 6868 // translation unit or can be a redeclaration of an extern "C" declaration 6869 // in another scope. 6870 if (isIncompleteDeclExternC(S,ND)) 6871 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6872 6873 // Neither global nor extern "C": nothing to do. 6874 return false; 6875 } 6876 6877 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6878 // If the decl is already known invalid, don't check it. 6879 if (NewVD->isInvalidDecl()) 6880 return; 6881 6882 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6883 QualType T = TInfo->getType(); 6884 6885 // Defer checking an 'auto' type until its initializer is attached. 6886 if (T->isUndeducedType()) 6887 return; 6888 6889 if (NewVD->hasAttrs()) 6890 CheckAlignasUnderalignment(NewVD); 6891 6892 if (T->isObjCObjectType()) { 6893 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6894 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6895 T = Context.getObjCObjectPointerType(T); 6896 NewVD->setType(T); 6897 } 6898 6899 // Emit an error if an address space was applied to decl with local storage. 6900 // This includes arrays of objects with address space qualifiers, but not 6901 // automatic variables that point to other address spaces. 6902 // ISO/IEC TR 18037 S5.1.2 6903 if (!getLangOpts().OpenCL 6904 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6905 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6906 NewVD->setInvalidDecl(); 6907 return; 6908 } 6909 6910 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6911 // scope. 6912 if (getLangOpts().OpenCLVersion == 120 && 6913 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6914 NewVD->isStaticLocal()) { 6915 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6916 NewVD->setInvalidDecl(); 6917 return; 6918 } 6919 6920 if (getLangOpts().OpenCL) { 6921 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6922 if (NewVD->hasAttr<BlocksAttr>()) { 6923 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6924 return; 6925 } 6926 6927 if (T->isBlockPointerType()) { 6928 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6929 // can't use 'extern' storage class. 6930 if (!T.isConstQualified()) { 6931 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6932 << 0 /*const*/; 6933 NewVD->setInvalidDecl(); 6934 return; 6935 } 6936 if (NewVD->hasExternalStorage()) { 6937 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6938 NewVD->setInvalidDecl(); 6939 return; 6940 } 6941 } 6942 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6943 // __constant address space. 6944 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6945 // variables inside a function can also be declared in the global 6946 // address space. 6947 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6948 NewVD->hasExternalStorage()) { 6949 if (!T->isSamplerT() && 6950 !(T.getAddressSpace() == LangAS::opencl_constant || 6951 (T.getAddressSpace() == LangAS::opencl_global && 6952 getLangOpts().OpenCLVersion == 200))) { 6953 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6954 if (getLangOpts().OpenCLVersion == 200) 6955 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6956 << Scope << "global or constant"; 6957 else 6958 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6959 << Scope << "constant"; 6960 NewVD->setInvalidDecl(); 6961 return; 6962 } 6963 } else { 6964 if (T.getAddressSpace() == LangAS::opencl_global) { 6965 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6966 << 1 /*is any function*/ << "global"; 6967 NewVD->setInvalidDecl(); 6968 return; 6969 } 6970 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6971 // in functions. 6972 if (T.getAddressSpace() == LangAS::opencl_constant || 6973 T.getAddressSpace() == LangAS::opencl_local) { 6974 FunctionDecl *FD = getCurFunctionDecl(); 6975 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6976 if (T.getAddressSpace() == LangAS::opencl_constant) 6977 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6978 << 0 /*non-kernel only*/ << "constant"; 6979 else 6980 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6981 << 0 /*non-kernel only*/ << "local"; 6982 NewVD->setInvalidDecl(); 6983 return; 6984 } 6985 } 6986 } 6987 } 6988 6989 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6990 && !NewVD->hasAttr<BlocksAttr>()) { 6991 if (getLangOpts().getGC() != LangOptions::NonGC) 6992 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6993 else { 6994 assert(!getLangOpts().ObjCAutoRefCount); 6995 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6996 } 6997 } 6998 6999 bool isVM = T->isVariablyModifiedType(); 7000 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7001 NewVD->hasAttr<BlocksAttr>()) 7002 getCurFunction()->setHasBranchProtectedScope(); 7003 7004 if ((isVM && NewVD->hasLinkage()) || 7005 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7006 bool SizeIsNegative; 7007 llvm::APSInt Oversized; 7008 TypeSourceInfo *FixedTInfo = 7009 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7010 SizeIsNegative, Oversized); 7011 if (!FixedTInfo && T->isVariableArrayType()) { 7012 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7013 // FIXME: This won't give the correct result for 7014 // int a[10][n]; 7015 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7016 7017 if (NewVD->isFileVarDecl()) 7018 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7019 << SizeRange; 7020 else if (NewVD->isStaticLocal()) 7021 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7022 << SizeRange; 7023 else 7024 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7025 << SizeRange; 7026 NewVD->setInvalidDecl(); 7027 return; 7028 } 7029 7030 if (!FixedTInfo) { 7031 if (NewVD->isFileVarDecl()) 7032 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7033 else 7034 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7035 NewVD->setInvalidDecl(); 7036 return; 7037 } 7038 7039 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7040 NewVD->setType(FixedTInfo->getType()); 7041 NewVD->setTypeSourceInfo(FixedTInfo); 7042 } 7043 7044 if (T->isVoidType()) { 7045 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7046 // of objects and functions. 7047 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7048 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7049 << T; 7050 NewVD->setInvalidDecl(); 7051 return; 7052 } 7053 } 7054 7055 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7056 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7057 NewVD->setInvalidDecl(); 7058 return; 7059 } 7060 7061 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7062 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7063 NewVD->setInvalidDecl(); 7064 return; 7065 } 7066 7067 if (NewVD->isConstexpr() && !T->isDependentType() && 7068 RequireLiteralType(NewVD->getLocation(), T, 7069 diag::err_constexpr_var_non_literal)) { 7070 NewVD->setInvalidDecl(); 7071 return; 7072 } 7073 } 7074 7075 /// \brief Perform semantic checking on a newly-created variable 7076 /// declaration. 7077 /// 7078 /// This routine performs all of the type-checking required for a 7079 /// variable declaration once it has been built. It is used both to 7080 /// check variables after they have been parsed and their declarators 7081 /// have been translated into a declaration, and to check variables 7082 /// that have been instantiated from a template. 7083 /// 7084 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7085 /// 7086 /// Returns true if the variable declaration is a redeclaration. 7087 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7088 CheckVariableDeclarationType(NewVD); 7089 7090 // If the decl is already known invalid, don't check it. 7091 if (NewVD->isInvalidDecl()) 7092 return false; 7093 7094 // If we did not find anything by this name, look for a non-visible 7095 // extern "C" declaration with the same name. 7096 if (Previous.empty() && 7097 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7098 Previous.setShadowed(); 7099 7100 if (!Previous.empty()) { 7101 MergeVarDecl(NewVD, Previous); 7102 return true; 7103 } 7104 return false; 7105 } 7106 7107 namespace { 7108 struct FindOverriddenMethod { 7109 Sema *S; 7110 CXXMethodDecl *Method; 7111 7112 /// Member lookup function that determines whether a given C++ 7113 /// method overrides a method in a base class, to be used with 7114 /// CXXRecordDecl::lookupInBases(). 7115 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7116 RecordDecl *BaseRecord = 7117 Specifier->getType()->getAs<RecordType>()->getDecl(); 7118 7119 DeclarationName Name = Method->getDeclName(); 7120 7121 // FIXME: Do we care about other names here too? 7122 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7123 // We really want to find the base class destructor here. 7124 QualType T = S->Context.getTypeDeclType(BaseRecord); 7125 CanQualType CT = S->Context.getCanonicalType(T); 7126 7127 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7128 } 7129 7130 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7131 Path.Decls = Path.Decls.slice(1)) { 7132 NamedDecl *D = Path.Decls.front(); 7133 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7134 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7135 return true; 7136 } 7137 } 7138 7139 return false; 7140 } 7141 }; 7142 7143 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7144 } // end anonymous namespace 7145 7146 /// \brief Report an error regarding overriding, along with any relevant 7147 /// overriden methods. 7148 /// 7149 /// \param DiagID the primary error to report. 7150 /// \param MD the overriding method. 7151 /// \param OEK which overrides to include as notes. 7152 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7153 OverrideErrorKind OEK = OEK_All) { 7154 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7155 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7156 E = MD->end_overridden_methods(); 7157 I != E; ++I) { 7158 // This check (& the OEK parameter) could be replaced by a predicate, but 7159 // without lambdas that would be overkill. This is still nicer than writing 7160 // out the diag loop 3 times. 7161 if ((OEK == OEK_All) || 7162 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7163 (OEK == OEK_Deleted && (*I)->isDeleted())) 7164 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7165 } 7166 } 7167 7168 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7169 /// and if so, check that it's a valid override and remember it. 7170 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7171 // Look for methods in base classes that this method might override. 7172 CXXBasePaths Paths; 7173 FindOverriddenMethod FOM; 7174 FOM.Method = MD; 7175 FOM.S = this; 7176 bool hasDeletedOverridenMethods = false; 7177 bool hasNonDeletedOverridenMethods = false; 7178 bool AddedAny = false; 7179 if (DC->lookupInBases(FOM, Paths)) { 7180 for (auto *I : Paths.found_decls()) { 7181 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7182 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7183 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7184 !CheckOverridingFunctionAttributes(MD, OldMD) && 7185 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7186 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7187 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7188 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7189 AddedAny = true; 7190 } 7191 } 7192 } 7193 } 7194 7195 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7196 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7197 } 7198 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7199 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7200 } 7201 7202 return AddedAny; 7203 } 7204 7205 namespace { 7206 // Struct for holding all of the extra arguments needed by 7207 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7208 struct ActOnFDArgs { 7209 Scope *S; 7210 Declarator &D; 7211 MultiTemplateParamsArg TemplateParamLists; 7212 bool AddToScope; 7213 }; 7214 } // end anonymous namespace 7215 7216 namespace { 7217 7218 // Callback to only accept typo corrections that have a non-zero edit distance. 7219 // Also only accept corrections that have the same parent decl. 7220 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7221 public: 7222 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7223 CXXRecordDecl *Parent) 7224 : Context(Context), OriginalFD(TypoFD), 7225 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7226 7227 bool ValidateCandidate(const TypoCorrection &candidate) override { 7228 if (candidate.getEditDistance() == 0) 7229 return false; 7230 7231 SmallVector<unsigned, 1> MismatchedParams; 7232 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7233 CDeclEnd = candidate.end(); 7234 CDecl != CDeclEnd; ++CDecl) { 7235 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7236 7237 if (FD && !FD->hasBody() && 7238 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7239 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7240 CXXRecordDecl *Parent = MD->getParent(); 7241 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7242 return true; 7243 } else if (!ExpectedParent) { 7244 return true; 7245 } 7246 } 7247 } 7248 7249 return false; 7250 } 7251 7252 private: 7253 ASTContext &Context; 7254 FunctionDecl *OriginalFD; 7255 CXXRecordDecl *ExpectedParent; 7256 }; 7257 7258 } // end anonymous namespace 7259 7260 /// \brief Generate diagnostics for an invalid function redeclaration. 7261 /// 7262 /// This routine handles generating the diagnostic messages for an invalid 7263 /// function redeclaration, including finding possible similar declarations 7264 /// or performing typo correction if there are no previous declarations with 7265 /// the same name. 7266 /// 7267 /// Returns a NamedDecl iff typo correction was performed and substituting in 7268 /// the new declaration name does not cause new errors. 7269 static NamedDecl *DiagnoseInvalidRedeclaration( 7270 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7271 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7272 DeclarationName Name = NewFD->getDeclName(); 7273 DeclContext *NewDC = NewFD->getDeclContext(); 7274 SmallVector<unsigned, 1> MismatchedParams; 7275 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7276 TypoCorrection Correction; 7277 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7278 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7279 : diag::err_member_decl_does_not_match; 7280 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7281 IsLocalFriend ? Sema::LookupLocalFriendName 7282 : Sema::LookupOrdinaryName, 7283 Sema::ForRedeclaration); 7284 7285 NewFD->setInvalidDecl(); 7286 if (IsLocalFriend) 7287 SemaRef.LookupName(Prev, S); 7288 else 7289 SemaRef.LookupQualifiedName(Prev, NewDC); 7290 assert(!Prev.isAmbiguous() && 7291 "Cannot have an ambiguity in previous-declaration lookup"); 7292 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7293 if (!Prev.empty()) { 7294 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7295 Func != FuncEnd; ++Func) { 7296 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7297 if (FD && 7298 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7299 // Add 1 to the index so that 0 can mean the mismatch didn't 7300 // involve a parameter 7301 unsigned ParamNum = 7302 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7303 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7304 } 7305 } 7306 // If the qualified name lookup yielded nothing, try typo correction 7307 } else if ((Correction = SemaRef.CorrectTypo( 7308 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7309 &ExtraArgs.D.getCXXScopeSpec(), 7310 llvm::make_unique<DifferentNameValidatorCCC>( 7311 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7312 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7313 // Set up everything for the call to ActOnFunctionDeclarator 7314 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7315 ExtraArgs.D.getIdentifierLoc()); 7316 Previous.clear(); 7317 Previous.setLookupName(Correction.getCorrection()); 7318 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7319 CDeclEnd = Correction.end(); 7320 CDecl != CDeclEnd; ++CDecl) { 7321 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7322 if (FD && !FD->hasBody() && 7323 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7324 Previous.addDecl(FD); 7325 } 7326 } 7327 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7328 7329 NamedDecl *Result; 7330 // Retry building the function declaration with the new previous 7331 // declarations, and with errors suppressed. 7332 { 7333 // Trap errors. 7334 Sema::SFINAETrap Trap(SemaRef); 7335 7336 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7337 // pieces need to verify the typo-corrected C++ declaration and hopefully 7338 // eliminate the need for the parameter pack ExtraArgs. 7339 Result = SemaRef.ActOnFunctionDeclarator( 7340 ExtraArgs.S, ExtraArgs.D, 7341 Correction.getCorrectionDecl()->getDeclContext(), 7342 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7343 ExtraArgs.AddToScope); 7344 7345 if (Trap.hasErrorOccurred()) 7346 Result = nullptr; 7347 } 7348 7349 if (Result) { 7350 // Determine which correction we picked. 7351 Decl *Canonical = Result->getCanonicalDecl(); 7352 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7353 I != E; ++I) 7354 if ((*I)->getCanonicalDecl() == Canonical) 7355 Correction.setCorrectionDecl(*I); 7356 7357 SemaRef.diagnoseTypo( 7358 Correction, 7359 SemaRef.PDiag(IsLocalFriend 7360 ? diag::err_no_matching_local_friend_suggest 7361 : diag::err_member_decl_does_not_match_suggest) 7362 << Name << NewDC << IsDefinition); 7363 return Result; 7364 } 7365 7366 // Pretend the typo correction never occurred 7367 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7368 ExtraArgs.D.getIdentifierLoc()); 7369 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7370 Previous.clear(); 7371 Previous.setLookupName(Name); 7372 } 7373 7374 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7375 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7376 7377 bool NewFDisConst = false; 7378 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7379 NewFDisConst = NewMD->isConst(); 7380 7381 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7382 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7383 NearMatch != NearMatchEnd; ++NearMatch) { 7384 FunctionDecl *FD = NearMatch->first; 7385 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7386 bool FDisConst = MD && MD->isConst(); 7387 bool IsMember = MD || !IsLocalFriend; 7388 7389 // FIXME: These notes are poorly worded for the local friend case. 7390 if (unsigned Idx = NearMatch->second) { 7391 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7392 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7393 if (Loc.isInvalid()) Loc = FD->getLocation(); 7394 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7395 : diag::note_local_decl_close_param_match) 7396 << Idx << FDParam->getType() 7397 << NewFD->getParamDecl(Idx - 1)->getType(); 7398 } else if (FDisConst != NewFDisConst) { 7399 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7400 << NewFDisConst << FD->getSourceRange().getEnd(); 7401 } else 7402 SemaRef.Diag(FD->getLocation(), 7403 IsMember ? diag::note_member_def_close_match 7404 : diag::note_local_decl_close_match); 7405 } 7406 return nullptr; 7407 } 7408 7409 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7410 switch (D.getDeclSpec().getStorageClassSpec()) { 7411 default: llvm_unreachable("Unknown storage class!"); 7412 case DeclSpec::SCS_auto: 7413 case DeclSpec::SCS_register: 7414 case DeclSpec::SCS_mutable: 7415 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7416 diag::err_typecheck_sclass_func); 7417 D.setInvalidType(); 7418 break; 7419 case DeclSpec::SCS_unspecified: break; 7420 case DeclSpec::SCS_extern: 7421 if (D.getDeclSpec().isExternInLinkageSpec()) 7422 return SC_None; 7423 return SC_Extern; 7424 case DeclSpec::SCS_static: { 7425 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7426 // C99 6.7.1p5: 7427 // The declaration of an identifier for a function that has 7428 // block scope shall have no explicit storage-class specifier 7429 // other than extern 7430 // See also (C++ [dcl.stc]p4). 7431 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7432 diag::err_static_block_func); 7433 break; 7434 } else 7435 return SC_Static; 7436 } 7437 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7438 } 7439 7440 // No explicit storage class has already been returned 7441 return SC_None; 7442 } 7443 7444 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7445 DeclContext *DC, QualType &R, 7446 TypeSourceInfo *TInfo, 7447 StorageClass SC, 7448 bool &IsVirtualOkay) { 7449 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7450 DeclarationName Name = NameInfo.getName(); 7451 7452 FunctionDecl *NewFD = nullptr; 7453 bool isInline = D.getDeclSpec().isInlineSpecified(); 7454 7455 if (!SemaRef.getLangOpts().CPlusPlus) { 7456 // Determine whether the function was written with a 7457 // prototype. This true when: 7458 // - there is a prototype in the declarator, or 7459 // - the type R of the function is some kind of typedef or other reference 7460 // to a type name (which eventually refers to a function type). 7461 bool HasPrototype = 7462 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7463 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7464 7465 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7466 D.getLocStart(), NameInfo, R, 7467 TInfo, SC, isInline, 7468 HasPrototype, false); 7469 if (D.isInvalidType()) 7470 NewFD->setInvalidDecl(); 7471 7472 return NewFD; 7473 } 7474 7475 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7476 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7477 7478 // Check that the return type is not an abstract class type. 7479 // For record types, this is done by the AbstractClassUsageDiagnoser once 7480 // the class has been completely parsed. 7481 if (!DC->isRecord() && 7482 SemaRef.RequireNonAbstractType( 7483 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7484 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7485 D.setInvalidType(); 7486 7487 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7488 // This is a C++ constructor declaration. 7489 assert(DC->isRecord() && 7490 "Constructors can only be declared in a member context"); 7491 7492 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7493 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7494 D.getLocStart(), NameInfo, 7495 R, TInfo, isExplicit, isInline, 7496 /*isImplicitlyDeclared=*/false, 7497 isConstexpr); 7498 7499 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7500 // This is a C++ destructor declaration. 7501 if (DC->isRecord()) { 7502 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7503 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7504 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7505 SemaRef.Context, Record, 7506 D.getLocStart(), 7507 NameInfo, R, TInfo, isInline, 7508 /*isImplicitlyDeclared=*/false); 7509 7510 // If the class is complete, then we now create the implicit exception 7511 // specification. If the class is incomplete or dependent, we can't do 7512 // it yet. 7513 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7514 Record->getDefinition() && !Record->isBeingDefined() && 7515 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7516 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7517 } 7518 7519 IsVirtualOkay = true; 7520 return NewDD; 7521 7522 } else { 7523 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7524 D.setInvalidType(); 7525 7526 // Create a FunctionDecl to satisfy the function definition parsing 7527 // code path. 7528 return FunctionDecl::Create(SemaRef.Context, DC, 7529 D.getLocStart(), 7530 D.getIdentifierLoc(), Name, R, TInfo, 7531 SC, isInline, 7532 /*hasPrototype=*/true, isConstexpr); 7533 } 7534 7535 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7536 if (!DC->isRecord()) { 7537 SemaRef.Diag(D.getIdentifierLoc(), 7538 diag::err_conv_function_not_member); 7539 return nullptr; 7540 } 7541 7542 SemaRef.CheckConversionDeclarator(D, R, SC); 7543 IsVirtualOkay = true; 7544 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7545 D.getLocStart(), NameInfo, 7546 R, TInfo, isInline, isExplicit, 7547 isConstexpr, SourceLocation()); 7548 7549 } else if (DC->isRecord()) { 7550 // If the name of the function is the same as the name of the record, 7551 // then this must be an invalid constructor that has a return type. 7552 // (The parser checks for a return type and makes the declarator a 7553 // constructor if it has no return type). 7554 if (Name.getAsIdentifierInfo() && 7555 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7556 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7557 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7558 << SourceRange(D.getIdentifierLoc()); 7559 return nullptr; 7560 } 7561 7562 // This is a C++ method declaration. 7563 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7564 cast<CXXRecordDecl>(DC), 7565 D.getLocStart(), NameInfo, R, 7566 TInfo, SC, isInline, 7567 isConstexpr, SourceLocation()); 7568 IsVirtualOkay = !Ret->isStatic(); 7569 return Ret; 7570 } else { 7571 bool isFriend = 7572 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7573 if (!isFriend && SemaRef.CurContext->isRecord()) 7574 return nullptr; 7575 7576 // Determine whether the function was written with a 7577 // prototype. This true when: 7578 // - we're in C++ (where every function has a prototype), 7579 return FunctionDecl::Create(SemaRef.Context, DC, 7580 D.getLocStart(), 7581 NameInfo, R, TInfo, SC, isInline, 7582 true/*HasPrototype*/, isConstexpr); 7583 } 7584 } 7585 7586 enum OpenCLParamType { 7587 ValidKernelParam, 7588 PtrPtrKernelParam, 7589 PtrKernelParam, 7590 PrivatePtrKernelParam, 7591 InvalidKernelParam, 7592 RecordKernelParam 7593 }; 7594 7595 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7596 if (PT->isPointerType()) { 7597 QualType PointeeType = PT->getPointeeType(); 7598 if (PointeeType->isPointerType()) 7599 return PtrPtrKernelParam; 7600 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7601 : PtrKernelParam; 7602 } 7603 7604 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7605 // be used as builtin types. 7606 7607 if (PT->isImageType()) 7608 return PtrKernelParam; 7609 7610 if (PT->isBooleanType()) 7611 return InvalidKernelParam; 7612 7613 if (PT->isEventT()) 7614 return InvalidKernelParam; 7615 7616 // OpenCL extension spec v1.2 s9.5: 7617 // This extension adds support for half scalar and vector types as built-in 7618 // types that can be used for arithmetic operations, conversions etc. 7619 if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType()) 7620 return InvalidKernelParam; 7621 7622 if (PT->isRecordType()) 7623 return RecordKernelParam; 7624 7625 return ValidKernelParam; 7626 } 7627 7628 static void checkIsValidOpenCLKernelParameter( 7629 Sema &S, 7630 Declarator &D, 7631 ParmVarDecl *Param, 7632 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7633 QualType PT = Param->getType(); 7634 7635 // Cache the valid types we encounter to avoid rechecking structs that are 7636 // used again 7637 if (ValidTypes.count(PT.getTypePtr())) 7638 return; 7639 7640 switch (getOpenCLKernelParameterType(S, PT)) { 7641 case PtrPtrKernelParam: 7642 // OpenCL v1.2 s6.9.a: 7643 // A kernel function argument cannot be declared as a 7644 // pointer to a pointer type. 7645 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7646 D.setInvalidType(); 7647 return; 7648 7649 case PrivatePtrKernelParam: 7650 // OpenCL v1.2 s6.9.a: 7651 // A kernel function argument cannot be declared as a 7652 // pointer to the private address space. 7653 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7654 D.setInvalidType(); 7655 return; 7656 7657 // OpenCL v1.2 s6.9.k: 7658 // Arguments to kernel functions in a program cannot be declared with the 7659 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7660 // uintptr_t or a struct and/or union that contain fields declared to be 7661 // one of these built-in scalar types. 7662 7663 case InvalidKernelParam: 7664 // OpenCL v1.2 s6.8 n: 7665 // A kernel function argument cannot be declared 7666 // of event_t type. 7667 // Do not diagnose half type since it is diagnosed as invalid argument 7668 // type for any function elsewhere. 7669 if (!PT->isHalfType()) 7670 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7671 D.setInvalidType(); 7672 return; 7673 7674 case PtrKernelParam: 7675 case ValidKernelParam: 7676 ValidTypes.insert(PT.getTypePtr()); 7677 return; 7678 7679 case RecordKernelParam: 7680 break; 7681 } 7682 7683 // Track nested structs we will inspect 7684 SmallVector<const Decl *, 4> VisitStack; 7685 7686 // Track where we are in the nested structs. Items will migrate from 7687 // VisitStack to HistoryStack as we do the DFS for bad field. 7688 SmallVector<const FieldDecl *, 4> HistoryStack; 7689 HistoryStack.push_back(nullptr); 7690 7691 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7692 VisitStack.push_back(PD); 7693 7694 assert(VisitStack.back() && "First decl null?"); 7695 7696 do { 7697 const Decl *Next = VisitStack.pop_back_val(); 7698 if (!Next) { 7699 assert(!HistoryStack.empty()); 7700 // Found a marker, we have gone up a level 7701 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7702 ValidTypes.insert(Hist->getType().getTypePtr()); 7703 7704 continue; 7705 } 7706 7707 // Adds everything except the original parameter declaration (which is not a 7708 // field itself) to the history stack. 7709 const RecordDecl *RD; 7710 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7711 HistoryStack.push_back(Field); 7712 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7713 } else { 7714 RD = cast<RecordDecl>(Next); 7715 } 7716 7717 // Add a null marker so we know when we've gone back up a level 7718 VisitStack.push_back(nullptr); 7719 7720 for (const auto *FD : RD->fields()) { 7721 QualType QT = FD->getType(); 7722 7723 if (ValidTypes.count(QT.getTypePtr())) 7724 continue; 7725 7726 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7727 if (ParamType == ValidKernelParam) 7728 continue; 7729 7730 if (ParamType == RecordKernelParam) { 7731 VisitStack.push_back(FD); 7732 continue; 7733 } 7734 7735 // OpenCL v1.2 s6.9.p: 7736 // Arguments to kernel functions that are declared to be a struct or union 7737 // do not allow OpenCL objects to be passed as elements of the struct or 7738 // union. 7739 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7740 ParamType == PrivatePtrKernelParam) { 7741 S.Diag(Param->getLocation(), 7742 diag::err_record_with_pointers_kernel_param) 7743 << PT->isUnionType() 7744 << PT; 7745 } else { 7746 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7747 } 7748 7749 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7750 << PD->getDeclName(); 7751 7752 // We have an error, now let's go back up through history and show where 7753 // the offending field came from 7754 for (ArrayRef<const FieldDecl *>::const_iterator 7755 I = HistoryStack.begin() + 1, 7756 E = HistoryStack.end(); 7757 I != E; ++I) { 7758 const FieldDecl *OuterField = *I; 7759 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7760 << OuterField->getType(); 7761 } 7762 7763 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7764 << QT->isPointerType() 7765 << QT; 7766 D.setInvalidType(); 7767 return; 7768 } 7769 } while (!VisitStack.empty()); 7770 } 7771 7772 NamedDecl* 7773 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7774 TypeSourceInfo *TInfo, LookupResult &Previous, 7775 MultiTemplateParamsArg TemplateParamLists, 7776 bool &AddToScope) { 7777 QualType R = TInfo->getType(); 7778 7779 assert(R.getTypePtr()->isFunctionType()); 7780 7781 // TODO: consider using NameInfo for diagnostic. 7782 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7783 DeclarationName Name = NameInfo.getName(); 7784 StorageClass SC = getFunctionStorageClass(*this, D); 7785 7786 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7787 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7788 diag::err_invalid_thread) 7789 << DeclSpec::getSpecifierName(TSCS); 7790 7791 if (D.isFirstDeclarationOfMember()) 7792 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7793 D.getIdentifierLoc()); 7794 7795 bool isFriend = false; 7796 FunctionTemplateDecl *FunctionTemplate = nullptr; 7797 bool isExplicitSpecialization = false; 7798 bool isFunctionTemplateSpecialization = false; 7799 7800 bool isDependentClassScopeExplicitSpecialization = false; 7801 bool HasExplicitTemplateArgs = false; 7802 TemplateArgumentListInfo TemplateArgs; 7803 7804 bool isVirtualOkay = false; 7805 7806 DeclContext *OriginalDC = DC; 7807 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7808 7809 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7810 isVirtualOkay); 7811 if (!NewFD) return nullptr; 7812 7813 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7814 NewFD->setTopLevelDeclInObjCContainer(); 7815 7816 // Set the lexical context. If this is a function-scope declaration, or has a 7817 // C++ scope specifier, or is the object of a friend declaration, the lexical 7818 // context will be different from the semantic context. 7819 NewFD->setLexicalDeclContext(CurContext); 7820 7821 if (IsLocalExternDecl) 7822 NewFD->setLocalExternDecl(); 7823 7824 if (getLangOpts().CPlusPlus) { 7825 bool isInline = D.getDeclSpec().isInlineSpecified(); 7826 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7827 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7828 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7829 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7830 isFriend = D.getDeclSpec().isFriendSpecified(); 7831 if (isFriend && !isInline && D.isFunctionDefinition()) { 7832 // C++ [class.friend]p5 7833 // A function can be defined in a friend declaration of a 7834 // class . . . . Such a function is implicitly inline. 7835 NewFD->setImplicitlyInline(); 7836 } 7837 7838 // If this is a method defined in an __interface, and is not a constructor 7839 // or an overloaded operator, then set the pure flag (isVirtual will already 7840 // return true). 7841 if (const CXXRecordDecl *Parent = 7842 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7843 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7844 NewFD->setPure(true); 7845 7846 // C++ [class.union]p2 7847 // A union can have member functions, but not virtual functions. 7848 if (isVirtual && Parent->isUnion()) 7849 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7850 } 7851 7852 SetNestedNameSpecifier(NewFD, D); 7853 isExplicitSpecialization = false; 7854 isFunctionTemplateSpecialization = false; 7855 if (D.isInvalidType()) 7856 NewFD->setInvalidDecl(); 7857 7858 // Match up the template parameter lists with the scope specifier, then 7859 // determine whether we have a template or a template specialization. 7860 bool Invalid = false; 7861 if (TemplateParameterList *TemplateParams = 7862 MatchTemplateParametersToScopeSpecifier( 7863 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7864 D.getCXXScopeSpec(), 7865 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7866 ? D.getName().TemplateId 7867 : nullptr, 7868 TemplateParamLists, isFriend, isExplicitSpecialization, 7869 Invalid)) { 7870 if (TemplateParams->size() > 0) { 7871 // This is a function template 7872 7873 // Check that we can declare a template here. 7874 if (CheckTemplateDeclScope(S, TemplateParams)) 7875 NewFD->setInvalidDecl(); 7876 7877 // A destructor cannot be a template. 7878 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7879 Diag(NewFD->getLocation(), diag::err_destructor_template); 7880 NewFD->setInvalidDecl(); 7881 } 7882 7883 // If we're adding a template to a dependent context, we may need to 7884 // rebuilding some of the types used within the template parameter list, 7885 // now that we know what the current instantiation is. 7886 if (DC->isDependentContext()) { 7887 ContextRAII SavedContext(*this, DC); 7888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7889 Invalid = true; 7890 } 7891 7892 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7893 NewFD->getLocation(), 7894 Name, TemplateParams, 7895 NewFD); 7896 FunctionTemplate->setLexicalDeclContext(CurContext); 7897 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7898 7899 // For source fidelity, store the other template param lists. 7900 if (TemplateParamLists.size() > 1) { 7901 NewFD->setTemplateParameterListsInfo(Context, 7902 TemplateParamLists.drop_back(1)); 7903 } 7904 } else { 7905 // This is a function template specialization. 7906 isFunctionTemplateSpecialization = true; 7907 // For source fidelity, store all the template param lists. 7908 if (TemplateParamLists.size() > 0) 7909 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7910 7911 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7912 if (isFriend) { 7913 // We want to remove the "template<>", found here. 7914 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7915 7916 // If we remove the template<> and the name is not a 7917 // template-id, we're actually silently creating a problem: 7918 // the friend declaration will refer to an untemplated decl, 7919 // and clearly the user wants a template specialization. So 7920 // we need to insert '<>' after the name. 7921 SourceLocation InsertLoc; 7922 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7923 InsertLoc = D.getName().getSourceRange().getEnd(); 7924 InsertLoc = getLocForEndOfToken(InsertLoc); 7925 } 7926 7927 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7928 << Name << RemoveRange 7929 << FixItHint::CreateRemoval(RemoveRange) 7930 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7931 } 7932 } 7933 } 7934 else { 7935 // All template param lists were matched against the scope specifier: 7936 // this is NOT (an explicit specialization of) a template. 7937 if (TemplateParamLists.size() > 0) 7938 // For source fidelity, store all the template param lists. 7939 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7940 } 7941 7942 if (Invalid) { 7943 NewFD->setInvalidDecl(); 7944 if (FunctionTemplate) 7945 FunctionTemplate->setInvalidDecl(); 7946 } 7947 7948 // C++ [dcl.fct.spec]p5: 7949 // The virtual specifier shall only be used in declarations of 7950 // nonstatic class member functions that appear within a 7951 // member-specification of a class declaration; see 10.3. 7952 // 7953 if (isVirtual && !NewFD->isInvalidDecl()) { 7954 if (!isVirtualOkay) { 7955 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7956 diag::err_virtual_non_function); 7957 } else if (!CurContext->isRecord()) { 7958 // 'virtual' was specified outside of the class. 7959 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7960 diag::err_virtual_out_of_class) 7961 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7962 } else if (NewFD->getDescribedFunctionTemplate()) { 7963 // C++ [temp.mem]p3: 7964 // A member function template shall not be virtual. 7965 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7966 diag::err_virtual_member_function_template) 7967 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7968 } else { 7969 // Okay: Add virtual to the method. 7970 NewFD->setVirtualAsWritten(true); 7971 } 7972 7973 if (getLangOpts().CPlusPlus14 && 7974 NewFD->getReturnType()->isUndeducedType()) 7975 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7976 } 7977 7978 if (getLangOpts().CPlusPlus14 && 7979 (NewFD->isDependentContext() || 7980 (isFriend && CurContext->isDependentContext())) && 7981 NewFD->getReturnType()->isUndeducedType()) { 7982 // If the function template is referenced directly (for instance, as a 7983 // member of the current instantiation), pretend it has a dependent type. 7984 // This is not really justified by the standard, but is the only sane 7985 // thing to do. 7986 // FIXME: For a friend function, we have not marked the function as being 7987 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7988 const FunctionProtoType *FPT = 7989 NewFD->getType()->castAs<FunctionProtoType>(); 7990 QualType Result = 7991 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7992 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7993 FPT->getExtProtoInfo())); 7994 } 7995 7996 // C++ [dcl.fct.spec]p3: 7997 // The inline specifier shall not appear on a block scope function 7998 // declaration. 7999 if (isInline && !NewFD->isInvalidDecl()) { 8000 if (CurContext->isFunctionOrMethod()) { 8001 // 'inline' is not allowed on block scope function declaration. 8002 Diag(D.getDeclSpec().getInlineSpecLoc(), 8003 diag::err_inline_declaration_block_scope) << Name 8004 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8005 } 8006 } 8007 8008 // C++ [dcl.fct.spec]p6: 8009 // The explicit specifier shall be used only in the declaration of a 8010 // constructor or conversion function within its class definition; 8011 // see 12.3.1 and 12.3.2. 8012 if (isExplicit && !NewFD->isInvalidDecl()) { 8013 if (!CurContext->isRecord()) { 8014 // 'explicit' was specified outside of the class. 8015 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8016 diag::err_explicit_out_of_class) 8017 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8018 } else if (!isa<CXXConstructorDecl>(NewFD) && 8019 !isa<CXXConversionDecl>(NewFD)) { 8020 // 'explicit' was specified on a function that wasn't a constructor 8021 // or conversion function. 8022 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8023 diag::err_explicit_non_ctor_or_conv_function) 8024 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8025 } 8026 } 8027 8028 if (isConstexpr) { 8029 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8030 // are implicitly inline. 8031 NewFD->setImplicitlyInline(); 8032 8033 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8034 // be either constructors or to return a literal type. Therefore, 8035 // destructors cannot be declared constexpr. 8036 if (isa<CXXDestructorDecl>(NewFD)) 8037 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8038 } 8039 8040 if (isConcept) { 8041 // This is a function concept. 8042 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8043 FTD->setConcept(); 8044 8045 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8046 // applied only to the definition of a function template [...] 8047 if (!D.isFunctionDefinition()) { 8048 Diag(D.getDeclSpec().getConceptSpecLoc(), 8049 diag::err_function_concept_not_defined); 8050 NewFD->setInvalidDecl(); 8051 } 8052 8053 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8054 // have no exception-specification and is treated as if it were specified 8055 // with noexcept(true) (15.4). [...] 8056 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8057 if (FPT->hasExceptionSpec()) { 8058 SourceRange Range; 8059 if (D.isFunctionDeclarator()) 8060 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8061 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8062 << FixItHint::CreateRemoval(Range); 8063 NewFD->setInvalidDecl(); 8064 } else { 8065 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8066 } 8067 8068 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8069 // following restrictions: 8070 // - The declared return type shall have the type bool. 8071 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8072 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8073 NewFD->setInvalidDecl(); 8074 } 8075 8076 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8077 // following restrictions: 8078 // - The declaration's parameter list shall be equivalent to an empty 8079 // parameter list. 8080 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8081 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8082 } 8083 8084 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8085 // implicity defined to be a constexpr declaration (implicitly inline) 8086 NewFD->setImplicitlyInline(); 8087 8088 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8089 // be declared with the thread_local, inline, friend, or constexpr 8090 // specifiers, [...] 8091 if (isInline) { 8092 Diag(D.getDeclSpec().getInlineSpecLoc(), 8093 diag::err_concept_decl_invalid_specifiers) 8094 << 1 << 1; 8095 NewFD->setInvalidDecl(true); 8096 } 8097 8098 if (isFriend) { 8099 Diag(D.getDeclSpec().getFriendSpecLoc(), 8100 diag::err_concept_decl_invalid_specifiers) 8101 << 1 << 2; 8102 NewFD->setInvalidDecl(true); 8103 } 8104 8105 if (isConstexpr) { 8106 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8107 diag::err_concept_decl_invalid_specifiers) 8108 << 1 << 3; 8109 NewFD->setInvalidDecl(true); 8110 } 8111 8112 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8113 // applied only to the definition of a function template or variable 8114 // template, declared in namespace scope. 8115 if (isFunctionTemplateSpecialization) { 8116 Diag(D.getDeclSpec().getConceptSpecLoc(), 8117 diag::err_concept_specified_specialization) << 1; 8118 NewFD->setInvalidDecl(true); 8119 return NewFD; 8120 } 8121 } 8122 8123 // If __module_private__ was specified, mark the function accordingly. 8124 if (D.getDeclSpec().isModulePrivateSpecified()) { 8125 if (isFunctionTemplateSpecialization) { 8126 SourceLocation ModulePrivateLoc 8127 = D.getDeclSpec().getModulePrivateSpecLoc(); 8128 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8129 << 0 8130 << FixItHint::CreateRemoval(ModulePrivateLoc); 8131 } else { 8132 NewFD->setModulePrivate(); 8133 if (FunctionTemplate) 8134 FunctionTemplate->setModulePrivate(); 8135 } 8136 } 8137 8138 if (isFriend) { 8139 if (FunctionTemplate) { 8140 FunctionTemplate->setObjectOfFriendDecl(); 8141 FunctionTemplate->setAccess(AS_public); 8142 } 8143 NewFD->setObjectOfFriendDecl(); 8144 NewFD->setAccess(AS_public); 8145 } 8146 8147 // If a function is defined as defaulted or deleted, mark it as such now. 8148 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8149 // definition kind to FDK_Definition. 8150 switch (D.getFunctionDefinitionKind()) { 8151 case FDK_Declaration: 8152 case FDK_Definition: 8153 break; 8154 8155 case FDK_Defaulted: 8156 NewFD->setDefaulted(); 8157 break; 8158 8159 case FDK_Deleted: 8160 NewFD->setDeletedAsWritten(); 8161 break; 8162 } 8163 8164 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8165 D.isFunctionDefinition()) { 8166 // C++ [class.mfct]p2: 8167 // A member function may be defined (8.4) in its class definition, in 8168 // which case it is an inline member function (7.1.2) 8169 NewFD->setImplicitlyInline(); 8170 } 8171 8172 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8173 !CurContext->isRecord()) { 8174 // C++ [class.static]p1: 8175 // A data or function member of a class may be declared static 8176 // in a class definition, in which case it is a static member of 8177 // the class. 8178 8179 // Complain about the 'static' specifier if it's on an out-of-line 8180 // member function definition. 8181 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8182 diag::err_static_out_of_line) 8183 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8184 } 8185 8186 // C++11 [except.spec]p15: 8187 // A deallocation function with no exception-specification is treated 8188 // as if it were specified with noexcept(true). 8189 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8190 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8191 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8192 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8193 NewFD->setType(Context.getFunctionType( 8194 FPT->getReturnType(), FPT->getParamTypes(), 8195 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8196 } 8197 8198 // Filter out previous declarations that don't match the scope. 8199 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8200 D.getCXXScopeSpec().isNotEmpty() || 8201 isExplicitSpecialization || 8202 isFunctionTemplateSpecialization); 8203 8204 // Handle GNU asm-label extension (encoded as an attribute). 8205 if (Expr *E = (Expr*) D.getAsmLabel()) { 8206 // The parser guarantees this is a string. 8207 StringLiteral *SE = cast<StringLiteral>(E); 8208 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8209 SE->getString(), 0)); 8210 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8211 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8212 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8213 if (I != ExtnameUndeclaredIdentifiers.end()) { 8214 if (isDeclExternC(NewFD)) { 8215 NewFD->addAttr(I->second); 8216 ExtnameUndeclaredIdentifiers.erase(I); 8217 } else 8218 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8219 << /*Variable*/0 << NewFD; 8220 } 8221 } 8222 8223 // Copy the parameter declarations from the declarator D to the function 8224 // declaration NewFD, if they are available. First scavenge them into Params. 8225 SmallVector<ParmVarDecl*, 16> Params; 8226 if (D.isFunctionDeclarator()) { 8227 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8228 8229 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8230 // function that takes no arguments, not a function that takes a 8231 // single void argument. 8232 // We let through "const void" here because Sema::GetTypeForDeclarator 8233 // already checks for that case. 8234 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8235 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8236 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8237 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8238 Param->setDeclContext(NewFD); 8239 Params.push_back(Param); 8240 8241 if (Param->isInvalidDecl()) 8242 NewFD->setInvalidDecl(); 8243 } 8244 } 8245 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8246 // When we're declaring a function with a typedef, typeof, etc as in the 8247 // following example, we'll need to synthesize (unnamed) 8248 // parameters for use in the declaration. 8249 // 8250 // @code 8251 // typedef void fn(int); 8252 // fn f; 8253 // @endcode 8254 8255 // Synthesize a parameter for each argument type. 8256 for (const auto &AI : FT->param_types()) { 8257 ParmVarDecl *Param = 8258 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8259 Param->setScopeInfo(0, Params.size()); 8260 Params.push_back(Param); 8261 } 8262 } else { 8263 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8264 "Should not need args for typedef of non-prototype fn"); 8265 } 8266 8267 // Finally, we know we have the right number of parameters, install them. 8268 NewFD->setParams(Params); 8269 8270 // Find all anonymous symbols defined during the declaration of this function 8271 // and add to NewFD. This lets us track decls such 'enum Y' in: 8272 // 8273 // void f(enum Y {AA} x) {} 8274 // 8275 // which would otherwise incorrectly end up in the translation unit scope. 8276 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8277 DeclsInPrototypeScope.clear(); 8278 8279 if (D.getDeclSpec().isNoreturnSpecified()) 8280 NewFD->addAttr( 8281 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8282 Context, 0)); 8283 8284 // Functions returning a variably modified type violate C99 6.7.5.2p2 8285 // because all functions have linkage. 8286 if (!NewFD->isInvalidDecl() && 8287 NewFD->getReturnType()->isVariablyModifiedType()) { 8288 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8289 NewFD->setInvalidDecl(); 8290 } 8291 8292 // Apply an implicit SectionAttr if #pragma code_seg is active. 8293 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8294 !NewFD->hasAttr<SectionAttr>()) { 8295 NewFD->addAttr( 8296 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8297 CodeSegStack.CurrentValue->getString(), 8298 CodeSegStack.CurrentPragmaLocation)); 8299 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8300 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8301 ASTContext::PSF_Read, 8302 NewFD)) 8303 NewFD->dropAttr<SectionAttr>(); 8304 } 8305 8306 // Handle attributes. 8307 ProcessDeclAttributes(S, NewFD, D); 8308 8309 if (getLangOpts().CUDA) 8310 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8311 8312 if (getLangOpts().OpenCL) { 8313 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8314 // type declaration will generate a compilation error. 8315 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8316 if (AddressSpace == LangAS::opencl_local || 8317 AddressSpace == LangAS::opencl_global || 8318 AddressSpace == LangAS::opencl_constant) { 8319 Diag(NewFD->getLocation(), 8320 diag::err_opencl_return_value_with_address_space); 8321 NewFD->setInvalidDecl(); 8322 } 8323 } 8324 8325 if (!getLangOpts().CPlusPlus) { 8326 // Perform semantic checking on the function declaration. 8327 bool isExplicitSpecialization=false; 8328 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8329 CheckMain(NewFD, D.getDeclSpec()); 8330 8331 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8332 CheckMSVCRTEntryPoint(NewFD); 8333 8334 if (!NewFD->isInvalidDecl()) 8335 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8336 isExplicitSpecialization)); 8337 else if (!Previous.empty()) 8338 // Recover gracefully from an invalid redeclaration. 8339 D.setRedeclaration(true); 8340 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8341 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8342 "previous declaration set still overloaded"); 8343 8344 // Diagnose no-prototype function declarations with calling conventions that 8345 // don't support variadic calls. Only do this in C and do it after merging 8346 // possibly prototyped redeclarations. 8347 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8348 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8349 CallingConv CC = FT->getExtInfo().getCC(); 8350 if (!supportsVariadicCall(CC)) { 8351 // Windows system headers sometimes accidentally use stdcall without 8352 // (void) parameters, so we relax this to a warning. 8353 int DiagID = 8354 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8355 Diag(NewFD->getLocation(), DiagID) 8356 << FunctionType::getNameForCallConv(CC); 8357 } 8358 } 8359 } else { 8360 // C++11 [replacement.functions]p3: 8361 // The program's definitions shall not be specified as inline. 8362 // 8363 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8364 // 8365 // Suppress the diagnostic if the function is __attribute__((used)), since 8366 // that forces an external definition to be emitted. 8367 if (D.getDeclSpec().isInlineSpecified() && 8368 NewFD->isReplaceableGlobalAllocationFunction() && 8369 !NewFD->hasAttr<UsedAttr>()) 8370 Diag(D.getDeclSpec().getInlineSpecLoc(), 8371 diag::ext_operator_new_delete_declared_inline) 8372 << NewFD->getDeclName(); 8373 8374 // If the declarator is a template-id, translate the parser's template 8375 // argument list into our AST format. 8376 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8377 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8378 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8379 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8380 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8381 TemplateId->NumArgs); 8382 translateTemplateArguments(TemplateArgsPtr, 8383 TemplateArgs); 8384 8385 HasExplicitTemplateArgs = true; 8386 8387 if (NewFD->isInvalidDecl()) { 8388 HasExplicitTemplateArgs = false; 8389 } else if (FunctionTemplate) { 8390 // Function template with explicit template arguments. 8391 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8392 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8393 8394 HasExplicitTemplateArgs = false; 8395 } else { 8396 assert((isFunctionTemplateSpecialization || 8397 D.getDeclSpec().isFriendSpecified()) && 8398 "should have a 'template<>' for this decl"); 8399 // "friend void foo<>(int);" is an implicit specialization decl. 8400 isFunctionTemplateSpecialization = true; 8401 } 8402 } else if (isFriend && isFunctionTemplateSpecialization) { 8403 // This combination is only possible in a recovery case; the user 8404 // wrote something like: 8405 // template <> friend void foo(int); 8406 // which we're recovering from as if the user had written: 8407 // friend void foo<>(int); 8408 // Go ahead and fake up a template id. 8409 HasExplicitTemplateArgs = true; 8410 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8411 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8412 } 8413 8414 // If it's a friend (and only if it's a friend), it's possible 8415 // that either the specialized function type or the specialized 8416 // template is dependent, and therefore matching will fail. In 8417 // this case, don't check the specialization yet. 8418 bool InstantiationDependent = false; 8419 if (isFunctionTemplateSpecialization && isFriend && 8420 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8421 TemplateSpecializationType::anyDependentTemplateArguments( 8422 TemplateArgs, 8423 InstantiationDependent))) { 8424 assert(HasExplicitTemplateArgs && 8425 "friend function specialization without template args"); 8426 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8427 Previous)) 8428 NewFD->setInvalidDecl(); 8429 } else if (isFunctionTemplateSpecialization) { 8430 if (CurContext->isDependentContext() && CurContext->isRecord() 8431 && !isFriend) { 8432 isDependentClassScopeExplicitSpecialization = true; 8433 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8434 diag::ext_function_specialization_in_class : 8435 diag::err_function_specialization_in_class) 8436 << NewFD->getDeclName(); 8437 } else if (CheckFunctionTemplateSpecialization(NewFD, 8438 (HasExplicitTemplateArgs ? &TemplateArgs 8439 : nullptr), 8440 Previous)) 8441 NewFD->setInvalidDecl(); 8442 8443 // C++ [dcl.stc]p1: 8444 // A storage-class-specifier shall not be specified in an explicit 8445 // specialization (14.7.3) 8446 FunctionTemplateSpecializationInfo *Info = 8447 NewFD->getTemplateSpecializationInfo(); 8448 if (Info && SC != SC_None) { 8449 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8450 Diag(NewFD->getLocation(), 8451 diag::err_explicit_specialization_inconsistent_storage_class) 8452 << SC 8453 << FixItHint::CreateRemoval( 8454 D.getDeclSpec().getStorageClassSpecLoc()); 8455 8456 else 8457 Diag(NewFD->getLocation(), 8458 diag::ext_explicit_specialization_storage_class) 8459 << FixItHint::CreateRemoval( 8460 D.getDeclSpec().getStorageClassSpecLoc()); 8461 } 8462 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8463 if (CheckMemberSpecialization(NewFD, Previous)) 8464 NewFD->setInvalidDecl(); 8465 } 8466 8467 // Perform semantic checking on the function declaration. 8468 if (!isDependentClassScopeExplicitSpecialization) { 8469 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8470 CheckMain(NewFD, D.getDeclSpec()); 8471 8472 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8473 CheckMSVCRTEntryPoint(NewFD); 8474 8475 if (!NewFD->isInvalidDecl()) 8476 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8477 isExplicitSpecialization)); 8478 else if (!Previous.empty()) 8479 // Recover gracefully from an invalid redeclaration. 8480 D.setRedeclaration(true); 8481 } 8482 8483 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8484 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8485 "previous declaration set still overloaded"); 8486 8487 NamedDecl *PrincipalDecl = (FunctionTemplate 8488 ? cast<NamedDecl>(FunctionTemplate) 8489 : NewFD); 8490 8491 if (isFriend && NewFD->getPreviousDecl()) { 8492 AccessSpecifier Access = AS_public; 8493 if (!NewFD->isInvalidDecl()) 8494 Access = NewFD->getPreviousDecl()->getAccess(); 8495 8496 NewFD->setAccess(Access); 8497 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8498 } 8499 8500 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8501 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8502 PrincipalDecl->setNonMemberOperator(); 8503 8504 // If we have a function template, check the template parameter 8505 // list. This will check and merge default template arguments. 8506 if (FunctionTemplate) { 8507 FunctionTemplateDecl *PrevTemplate = 8508 FunctionTemplate->getPreviousDecl(); 8509 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8510 PrevTemplate ? PrevTemplate->getTemplateParameters() 8511 : nullptr, 8512 D.getDeclSpec().isFriendSpecified() 8513 ? (D.isFunctionDefinition() 8514 ? TPC_FriendFunctionTemplateDefinition 8515 : TPC_FriendFunctionTemplate) 8516 : (D.getCXXScopeSpec().isSet() && 8517 DC && DC->isRecord() && 8518 DC->isDependentContext()) 8519 ? TPC_ClassTemplateMember 8520 : TPC_FunctionTemplate); 8521 } 8522 8523 if (NewFD->isInvalidDecl()) { 8524 // Ignore all the rest of this. 8525 } else if (!D.isRedeclaration()) { 8526 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8527 AddToScope }; 8528 // Fake up an access specifier if it's supposed to be a class member. 8529 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8530 NewFD->setAccess(AS_public); 8531 8532 // Qualified decls generally require a previous declaration. 8533 if (D.getCXXScopeSpec().isSet()) { 8534 // ...with the major exception of templated-scope or 8535 // dependent-scope friend declarations. 8536 8537 // TODO: we currently also suppress this check in dependent 8538 // contexts because (1) the parameter depth will be off when 8539 // matching friend templates and (2) we might actually be 8540 // selecting a friend based on a dependent factor. But there 8541 // are situations where these conditions don't apply and we 8542 // can actually do this check immediately. 8543 if (isFriend && 8544 (TemplateParamLists.size() || 8545 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8546 CurContext->isDependentContext())) { 8547 // ignore these 8548 } else { 8549 // The user tried to provide an out-of-line definition for a 8550 // function that is a member of a class or namespace, but there 8551 // was no such member function declared (C++ [class.mfct]p2, 8552 // C++ [namespace.memdef]p2). For example: 8553 // 8554 // class X { 8555 // void f() const; 8556 // }; 8557 // 8558 // void X::f() { } // ill-formed 8559 // 8560 // Complain about this problem, and attempt to suggest close 8561 // matches (e.g., those that differ only in cv-qualifiers and 8562 // whether the parameter types are references). 8563 8564 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8565 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8566 AddToScope = ExtraArgs.AddToScope; 8567 return Result; 8568 } 8569 } 8570 8571 // Unqualified local friend declarations are required to resolve 8572 // to something. 8573 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8574 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8575 *this, Previous, NewFD, ExtraArgs, true, S)) { 8576 AddToScope = ExtraArgs.AddToScope; 8577 return Result; 8578 } 8579 } 8580 } else if (!D.isFunctionDefinition() && 8581 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8582 !isFriend && !isFunctionTemplateSpecialization && 8583 !isExplicitSpecialization) { 8584 // An out-of-line member function declaration must also be a 8585 // definition (C++ [class.mfct]p2). 8586 // Note that this is not the case for explicit specializations of 8587 // function templates or member functions of class templates, per 8588 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8589 // extension for compatibility with old SWIG code which likes to 8590 // generate them. 8591 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8592 << D.getCXXScopeSpec().getRange(); 8593 } 8594 } 8595 8596 ProcessPragmaWeak(S, NewFD); 8597 checkAttributesAfterMerging(*this, *NewFD); 8598 8599 AddKnownFunctionAttributes(NewFD); 8600 8601 if (NewFD->hasAttr<OverloadableAttr>() && 8602 !NewFD->getType()->getAs<FunctionProtoType>()) { 8603 Diag(NewFD->getLocation(), 8604 diag::err_attribute_overloadable_no_prototype) 8605 << NewFD; 8606 8607 // Turn this into a variadic function with no parameters. 8608 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8609 FunctionProtoType::ExtProtoInfo EPI( 8610 Context.getDefaultCallingConvention(true, false)); 8611 EPI.Variadic = true; 8612 EPI.ExtInfo = FT->getExtInfo(); 8613 8614 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8615 NewFD->setType(R); 8616 } 8617 8618 // If there's a #pragma GCC visibility in scope, and this isn't a class 8619 // member, set the visibility of this function. 8620 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8621 AddPushedVisibilityAttribute(NewFD); 8622 8623 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8624 // marking the function. 8625 AddCFAuditedAttribute(NewFD); 8626 8627 // If this is a function definition, check if we have to apply optnone due to 8628 // a pragma. 8629 if(D.isFunctionDefinition()) 8630 AddRangeBasedOptnone(NewFD); 8631 8632 // If this is the first declaration of an extern C variable, update 8633 // the map of such variables. 8634 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8635 isIncompleteDeclExternC(*this, NewFD)) 8636 RegisterLocallyScopedExternCDecl(NewFD, S); 8637 8638 // Set this FunctionDecl's range up to the right paren. 8639 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8640 8641 if (D.isRedeclaration() && !Previous.empty()) { 8642 checkDLLAttributeRedeclaration( 8643 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8644 isExplicitSpecialization || isFunctionTemplateSpecialization, 8645 D.isFunctionDefinition()); 8646 } 8647 8648 if (getLangOpts().CUDA) { 8649 IdentifierInfo *II = NewFD->getIdentifier(); 8650 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8651 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8652 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8653 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8654 8655 Context.setcudaConfigureCallDecl(NewFD); 8656 } 8657 8658 // Variadic functions, other than a *declaration* of printf, are not allowed 8659 // in device-side CUDA code, unless someone passed 8660 // -fcuda-allow-variadic-functions. 8661 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8662 (NewFD->hasAttr<CUDADeviceAttr>() || 8663 NewFD->hasAttr<CUDAGlobalAttr>()) && 8664 !(II && II->isStr("printf") && NewFD->isExternC() && 8665 !D.isFunctionDefinition())) { 8666 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8667 } 8668 } 8669 8670 if (getLangOpts().CPlusPlus) { 8671 if (FunctionTemplate) { 8672 if (NewFD->isInvalidDecl()) 8673 FunctionTemplate->setInvalidDecl(); 8674 return FunctionTemplate; 8675 } 8676 } 8677 8678 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8679 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8680 if ((getLangOpts().OpenCLVersion >= 120) 8681 && (SC == SC_Static)) { 8682 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8683 D.setInvalidType(); 8684 } 8685 8686 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8687 if (!NewFD->getReturnType()->isVoidType()) { 8688 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8689 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8690 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8691 : FixItHint()); 8692 D.setInvalidType(); 8693 } 8694 8695 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8696 for (auto Param : NewFD->parameters()) 8697 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8698 } 8699 for (const ParmVarDecl *Param : NewFD->parameters()) { 8700 QualType PT = Param->getType(); 8701 8702 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8703 // types. 8704 if (getLangOpts().OpenCLVersion >= 200) { 8705 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8706 QualType ElemTy = PipeTy->getElementType(); 8707 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8708 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8709 D.setInvalidType(); 8710 } 8711 } 8712 } 8713 } 8714 8715 MarkUnusedFileScopedDecl(NewFD); 8716 8717 // Here we have an function template explicit specialization at class scope. 8718 // The actually specialization will be postponed to template instatiation 8719 // time via the ClassScopeFunctionSpecializationDecl node. 8720 if (isDependentClassScopeExplicitSpecialization) { 8721 ClassScopeFunctionSpecializationDecl *NewSpec = 8722 ClassScopeFunctionSpecializationDecl::Create( 8723 Context, CurContext, SourceLocation(), 8724 cast<CXXMethodDecl>(NewFD), 8725 HasExplicitTemplateArgs, TemplateArgs); 8726 CurContext->addDecl(NewSpec); 8727 AddToScope = false; 8728 } 8729 8730 return NewFD; 8731 } 8732 8733 /// \brief Checks if the new declaration declared in dependent context must be 8734 /// put in the same redeclaration chain as the specified declaration. 8735 /// 8736 /// \param D Declaration that is checked. 8737 /// \param PrevDecl Previous declaration found with proper lookup method for the 8738 /// same declaration name. 8739 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8740 /// belongs to. 8741 /// 8742 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8743 // Any declarations should be put into redeclaration chains except for 8744 // friend declaration in a dependent context that names a function in 8745 // namespace scope. 8746 // 8747 // This allows to compile code like: 8748 // 8749 // void func(); 8750 // template<typename T> class C1 { friend void func() { } }; 8751 // template<typename T> class C2 { friend void func() { } }; 8752 // 8753 // This code snippet is a valid code unless both templates are instantiated. 8754 return !(D->getLexicalDeclContext()->isDependentContext() && 8755 D->getDeclContext()->isFileContext() && 8756 D->getFriendObjectKind() != Decl::FOK_None); 8757 } 8758 8759 /// \brief Perform semantic checking of a new function declaration. 8760 /// 8761 /// Performs semantic analysis of the new function declaration 8762 /// NewFD. This routine performs all semantic checking that does not 8763 /// require the actual declarator involved in the declaration, and is 8764 /// used both for the declaration of functions as they are parsed 8765 /// (called via ActOnDeclarator) and for the declaration of functions 8766 /// that have been instantiated via C++ template instantiation (called 8767 /// via InstantiateDecl). 8768 /// 8769 /// \param IsExplicitSpecialization whether this new function declaration is 8770 /// an explicit specialization of the previous declaration. 8771 /// 8772 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8773 /// 8774 /// \returns true if the function declaration is a redeclaration. 8775 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8776 LookupResult &Previous, 8777 bool IsExplicitSpecialization) { 8778 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8779 "Variably modified return types are not handled here"); 8780 8781 // Determine whether the type of this function should be merged with 8782 // a previous visible declaration. This never happens for functions in C++, 8783 // and always happens in C if the previous declaration was visible. 8784 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8785 !Previous.isShadowed(); 8786 8787 bool Redeclaration = false; 8788 NamedDecl *OldDecl = nullptr; 8789 8790 // Merge or overload the declaration with an existing declaration of 8791 // the same name, if appropriate. 8792 if (!Previous.empty()) { 8793 // Determine whether NewFD is an overload of PrevDecl or 8794 // a declaration that requires merging. If it's an overload, 8795 // there's no more work to do here; we'll just add the new 8796 // function to the scope. 8797 if (!AllowOverloadingOfFunction(Previous, Context)) { 8798 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8799 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8800 Redeclaration = true; 8801 OldDecl = Candidate; 8802 } 8803 } else { 8804 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8805 /*NewIsUsingDecl*/ false)) { 8806 case Ovl_Match: 8807 Redeclaration = true; 8808 break; 8809 8810 case Ovl_NonFunction: 8811 Redeclaration = true; 8812 break; 8813 8814 case Ovl_Overload: 8815 Redeclaration = false; 8816 break; 8817 } 8818 8819 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8820 // If a function name is overloadable in C, then every function 8821 // with that name must be marked "overloadable". 8822 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8823 << Redeclaration << NewFD; 8824 NamedDecl *OverloadedDecl = nullptr; 8825 if (Redeclaration) 8826 OverloadedDecl = OldDecl; 8827 else if (!Previous.empty()) 8828 OverloadedDecl = Previous.getRepresentativeDecl(); 8829 if (OverloadedDecl) 8830 Diag(OverloadedDecl->getLocation(), 8831 diag::note_attribute_overloadable_prev_overload); 8832 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8833 } 8834 } 8835 } 8836 8837 // Check for a previous extern "C" declaration with this name. 8838 if (!Redeclaration && 8839 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8840 if (!Previous.empty()) { 8841 // This is an extern "C" declaration with the same name as a previous 8842 // declaration, and thus redeclares that entity... 8843 Redeclaration = true; 8844 OldDecl = Previous.getFoundDecl(); 8845 MergeTypeWithPrevious = false; 8846 8847 // ... except in the presence of __attribute__((overloadable)). 8848 if (OldDecl->hasAttr<OverloadableAttr>()) { 8849 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8850 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8851 << Redeclaration << NewFD; 8852 Diag(Previous.getFoundDecl()->getLocation(), 8853 diag::note_attribute_overloadable_prev_overload); 8854 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8855 } 8856 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8857 Redeclaration = false; 8858 OldDecl = nullptr; 8859 } 8860 } 8861 } 8862 } 8863 8864 // C++11 [dcl.constexpr]p8: 8865 // A constexpr specifier for a non-static member function that is not 8866 // a constructor declares that member function to be const. 8867 // 8868 // This needs to be delayed until we know whether this is an out-of-line 8869 // definition of a static member function. 8870 // 8871 // This rule is not present in C++1y, so we produce a backwards 8872 // compatibility warning whenever it happens in C++11. 8873 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8874 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8875 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8876 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8877 CXXMethodDecl *OldMD = nullptr; 8878 if (OldDecl) 8879 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8880 if (!OldMD || !OldMD->isStatic()) { 8881 const FunctionProtoType *FPT = 8882 MD->getType()->castAs<FunctionProtoType>(); 8883 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8884 EPI.TypeQuals |= Qualifiers::Const; 8885 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8886 FPT->getParamTypes(), EPI)); 8887 8888 // Warn that we did this, if we're not performing template instantiation. 8889 // In that case, we'll have warned already when the template was defined. 8890 if (ActiveTemplateInstantiations.empty()) { 8891 SourceLocation AddConstLoc; 8892 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8893 .IgnoreParens().getAs<FunctionTypeLoc>()) 8894 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8895 8896 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8897 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8898 } 8899 } 8900 } 8901 8902 if (Redeclaration) { 8903 // NewFD and OldDecl represent declarations that need to be 8904 // merged. 8905 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8906 NewFD->setInvalidDecl(); 8907 return Redeclaration; 8908 } 8909 8910 Previous.clear(); 8911 Previous.addDecl(OldDecl); 8912 8913 if (FunctionTemplateDecl *OldTemplateDecl 8914 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8915 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8916 FunctionTemplateDecl *NewTemplateDecl 8917 = NewFD->getDescribedFunctionTemplate(); 8918 assert(NewTemplateDecl && "Template/non-template mismatch"); 8919 if (CXXMethodDecl *Method 8920 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8921 Method->setAccess(OldTemplateDecl->getAccess()); 8922 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8923 } 8924 8925 // If this is an explicit specialization of a member that is a function 8926 // template, mark it as a member specialization. 8927 if (IsExplicitSpecialization && 8928 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8929 NewTemplateDecl->setMemberSpecialization(); 8930 assert(OldTemplateDecl->isMemberSpecialization()); 8931 // Explicit specializations of a member template do not inherit deleted 8932 // status from the parent member template that they are specializing. 8933 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8934 FunctionDecl *const OldTemplatedDecl = 8935 OldTemplateDecl->getTemplatedDecl(); 8936 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8937 OldTemplatedDecl->setDeletedAsWritten(false); 8938 } 8939 } 8940 8941 } else { 8942 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 8943 // This needs to happen first so that 'inline' propagates. 8944 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8945 if (isa<CXXMethodDecl>(NewFD)) 8946 NewFD->setAccess(OldDecl->getAccess()); 8947 } 8948 } 8949 } 8950 8951 // Semantic checking for this function declaration (in isolation). 8952 8953 if (getLangOpts().CPlusPlus) { 8954 // C++-specific checks. 8955 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8956 CheckConstructor(Constructor); 8957 } else if (CXXDestructorDecl *Destructor = 8958 dyn_cast<CXXDestructorDecl>(NewFD)) { 8959 CXXRecordDecl *Record = Destructor->getParent(); 8960 QualType ClassType = Context.getTypeDeclType(Record); 8961 8962 // FIXME: Shouldn't we be able to perform this check even when the class 8963 // type is dependent? Both gcc and edg can handle that. 8964 if (!ClassType->isDependentType()) { 8965 DeclarationName Name 8966 = Context.DeclarationNames.getCXXDestructorName( 8967 Context.getCanonicalType(ClassType)); 8968 if (NewFD->getDeclName() != Name) { 8969 Diag(NewFD->getLocation(), diag::err_destructor_name); 8970 NewFD->setInvalidDecl(); 8971 return Redeclaration; 8972 } 8973 } 8974 } else if (CXXConversionDecl *Conversion 8975 = dyn_cast<CXXConversionDecl>(NewFD)) { 8976 ActOnConversionDeclarator(Conversion); 8977 } 8978 8979 // Find any virtual functions that this function overrides. 8980 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8981 if (!Method->isFunctionTemplateSpecialization() && 8982 !Method->getDescribedFunctionTemplate() && 8983 Method->isCanonicalDecl()) { 8984 if (AddOverriddenMethods(Method->getParent(), Method)) { 8985 // If the function was marked as "static", we have a problem. 8986 if (NewFD->getStorageClass() == SC_Static) { 8987 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8988 } 8989 } 8990 } 8991 8992 if (Method->isStatic()) 8993 checkThisInStaticMemberFunctionType(Method); 8994 } 8995 8996 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8997 if (NewFD->isOverloadedOperator() && 8998 CheckOverloadedOperatorDeclaration(NewFD)) { 8999 NewFD->setInvalidDecl(); 9000 return Redeclaration; 9001 } 9002 9003 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9004 if (NewFD->getLiteralIdentifier() && 9005 CheckLiteralOperatorDeclaration(NewFD)) { 9006 NewFD->setInvalidDecl(); 9007 return Redeclaration; 9008 } 9009 9010 // In C++, check default arguments now that we have merged decls. Unless 9011 // the lexical context is the class, because in this case this is done 9012 // during delayed parsing anyway. 9013 if (!CurContext->isRecord()) 9014 CheckCXXDefaultArguments(NewFD); 9015 9016 // If this function declares a builtin function, check the type of this 9017 // declaration against the expected type for the builtin. 9018 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9019 ASTContext::GetBuiltinTypeError Error; 9020 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9021 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9022 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 9023 // The type of this function differs from the type of the builtin, 9024 // so forget about the builtin entirely. 9025 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9026 } 9027 } 9028 9029 // If this function is declared as being extern "C", then check to see if 9030 // the function returns a UDT (class, struct, or union type) that is not C 9031 // compatible, and if it does, warn the user. 9032 // But, issue any diagnostic on the first declaration only. 9033 if (Previous.empty() && NewFD->isExternC()) { 9034 QualType R = NewFD->getReturnType(); 9035 if (R->isIncompleteType() && !R->isVoidType()) 9036 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9037 << NewFD << R; 9038 else if (!R.isPODType(Context) && !R->isVoidType() && 9039 !R->isObjCObjectPointerType()) 9040 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9041 } 9042 9043 // C++1z [dcl.fct]p6: 9044 // [...] whether the function has a non-throwing exception-specification 9045 // [is] part of the function type 9046 // 9047 // This results in an ABI break between C++14 and C++17 for functions whose 9048 // declared type includes an exception-specification in a parameter or 9049 // return type. (Exception specifications on the function itself are OK in 9050 // most cases, and exception specifications are not permitted in most other 9051 // contexts where they could make it into a mangling.) 9052 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9053 auto HasNoexcept = [&](QualType T) -> bool { 9054 // Strip off declarator chunks that could be between us and a function 9055 // type. We don't need to look far, exception specifications are very 9056 // restricted prior to C++17. 9057 if (auto *RT = T->getAs<ReferenceType>()) 9058 T = RT->getPointeeType(); 9059 else if (T->isAnyPointerType()) 9060 T = T->getPointeeType(); 9061 else if (auto *MPT = T->getAs<MemberPointerType>()) 9062 T = MPT->getPointeeType(); 9063 if (auto *FPT = T->getAs<FunctionProtoType>()) 9064 if (FPT->isNothrow(Context)) 9065 return true; 9066 return false; 9067 }; 9068 9069 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9070 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9071 for (QualType T : FPT->param_types()) 9072 AnyNoexcept |= HasNoexcept(T); 9073 if (AnyNoexcept) 9074 Diag(NewFD->getLocation(), 9075 diag::warn_cxx1z_compat_exception_spec_in_signature) 9076 << NewFD; 9077 } 9078 } 9079 return Redeclaration; 9080 } 9081 9082 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9083 // C++11 [basic.start.main]p3: 9084 // A program that [...] declares main to be inline, static or 9085 // constexpr is ill-formed. 9086 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9087 // appear in a declaration of main. 9088 // static main is not an error under C99, but we should warn about it. 9089 // We accept _Noreturn main as an extension. 9090 if (FD->getStorageClass() == SC_Static) 9091 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9092 ? diag::err_static_main : diag::warn_static_main) 9093 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9094 if (FD->isInlineSpecified()) 9095 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9096 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9097 if (DS.isNoreturnSpecified()) { 9098 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9099 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9100 Diag(NoreturnLoc, diag::ext_noreturn_main); 9101 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9102 << FixItHint::CreateRemoval(NoreturnRange); 9103 } 9104 if (FD->isConstexpr()) { 9105 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9106 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9107 FD->setConstexpr(false); 9108 } 9109 9110 if (getLangOpts().OpenCL) { 9111 Diag(FD->getLocation(), diag::err_opencl_no_main) 9112 << FD->hasAttr<OpenCLKernelAttr>(); 9113 FD->setInvalidDecl(); 9114 return; 9115 } 9116 9117 QualType T = FD->getType(); 9118 assert(T->isFunctionType() && "function decl is not of function type"); 9119 const FunctionType* FT = T->castAs<FunctionType>(); 9120 9121 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9122 // In C with GNU extensions we allow main() to have non-integer return 9123 // type, but we should warn about the extension, and we disable the 9124 // implicit-return-zero rule. 9125 9126 // GCC in C mode accepts qualified 'int'. 9127 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9128 FD->setHasImplicitReturnZero(true); 9129 else { 9130 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9131 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9132 if (RTRange.isValid()) 9133 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9134 << FixItHint::CreateReplacement(RTRange, "int"); 9135 } 9136 } else { 9137 // In C and C++, main magically returns 0 if you fall off the end; 9138 // set the flag which tells us that. 9139 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9140 9141 // All the standards say that main() should return 'int'. 9142 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9143 FD->setHasImplicitReturnZero(true); 9144 else { 9145 // Otherwise, this is just a flat-out error. 9146 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9147 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9148 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9149 : FixItHint()); 9150 FD->setInvalidDecl(true); 9151 } 9152 } 9153 9154 // Treat protoless main() as nullary. 9155 if (isa<FunctionNoProtoType>(FT)) return; 9156 9157 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9158 unsigned nparams = FTP->getNumParams(); 9159 assert(FD->getNumParams() == nparams); 9160 9161 bool HasExtraParameters = (nparams > 3); 9162 9163 if (FTP->isVariadic()) { 9164 Diag(FD->getLocation(), diag::ext_variadic_main); 9165 // FIXME: if we had information about the location of the ellipsis, we 9166 // could add a FixIt hint to remove it as a parameter. 9167 } 9168 9169 // Darwin passes an undocumented fourth argument of type char**. If 9170 // other platforms start sprouting these, the logic below will start 9171 // getting shifty. 9172 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9173 HasExtraParameters = false; 9174 9175 if (HasExtraParameters) { 9176 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9177 FD->setInvalidDecl(true); 9178 nparams = 3; 9179 } 9180 9181 // FIXME: a lot of the following diagnostics would be improved 9182 // if we had some location information about types. 9183 9184 QualType CharPP = 9185 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9186 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9187 9188 for (unsigned i = 0; i < nparams; ++i) { 9189 QualType AT = FTP->getParamType(i); 9190 9191 bool mismatch = true; 9192 9193 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9194 mismatch = false; 9195 else if (Expected[i] == CharPP) { 9196 // As an extension, the following forms are okay: 9197 // char const ** 9198 // char const * const * 9199 // char * const * 9200 9201 QualifierCollector qs; 9202 const PointerType* PT; 9203 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9204 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9205 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9206 Context.CharTy)) { 9207 qs.removeConst(); 9208 mismatch = !qs.empty(); 9209 } 9210 } 9211 9212 if (mismatch) { 9213 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9214 // TODO: suggest replacing given type with expected type 9215 FD->setInvalidDecl(true); 9216 } 9217 } 9218 9219 if (nparams == 1 && !FD->isInvalidDecl()) { 9220 Diag(FD->getLocation(), diag::warn_main_one_arg); 9221 } 9222 9223 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9224 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9225 FD->setInvalidDecl(); 9226 } 9227 } 9228 9229 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9230 QualType T = FD->getType(); 9231 assert(T->isFunctionType() && "function decl is not of function type"); 9232 const FunctionType *FT = T->castAs<FunctionType>(); 9233 9234 // Set an implicit return of 'zero' if the function can return some integral, 9235 // enumeration, pointer or nullptr type. 9236 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9237 FT->getReturnType()->isAnyPointerType() || 9238 FT->getReturnType()->isNullPtrType()) 9239 // DllMain is exempt because a return value of zero means it failed. 9240 if (FD->getName() != "DllMain") 9241 FD->setHasImplicitReturnZero(true); 9242 9243 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9244 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9245 FD->setInvalidDecl(); 9246 } 9247 } 9248 9249 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9250 // FIXME: Need strict checking. In C89, we need to check for 9251 // any assignment, increment, decrement, function-calls, or 9252 // commas outside of a sizeof. In C99, it's the same list, 9253 // except that the aforementioned are allowed in unevaluated 9254 // expressions. Everything else falls under the 9255 // "may accept other forms of constant expressions" exception. 9256 // (We never end up here for C++, so the constant expression 9257 // rules there don't matter.) 9258 const Expr *Culprit; 9259 if (Init->isConstantInitializer(Context, false, &Culprit)) 9260 return false; 9261 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9262 << Culprit->getSourceRange(); 9263 return true; 9264 } 9265 9266 namespace { 9267 // Visits an initialization expression to see if OrigDecl is evaluated in 9268 // its own initialization and throws a warning if it does. 9269 class SelfReferenceChecker 9270 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9271 Sema &S; 9272 Decl *OrigDecl; 9273 bool isRecordType; 9274 bool isPODType; 9275 bool isReferenceType; 9276 9277 bool isInitList; 9278 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9279 9280 public: 9281 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9282 9283 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9284 S(S), OrigDecl(OrigDecl) { 9285 isPODType = false; 9286 isRecordType = false; 9287 isReferenceType = false; 9288 isInitList = false; 9289 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9290 isPODType = VD->getType().isPODType(S.Context); 9291 isRecordType = VD->getType()->isRecordType(); 9292 isReferenceType = VD->getType()->isReferenceType(); 9293 } 9294 } 9295 9296 // For most expressions, just call the visitor. For initializer lists, 9297 // track the index of the field being initialized since fields are 9298 // initialized in order allowing use of previously initialized fields. 9299 void CheckExpr(Expr *E) { 9300 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9301 if (!InitList) { 9302 Visit(E); 9303 return; 9304 } 9305 9306 // Track and increment the index here. 9307 isInitList = true; 9308 InitFieldIndex.push_back(0); 9309 for (auto Child : InitList->children()) { 9310 CheckExpr(cast<Expr>(Child)); 9311 ++InitFieldIndex.back(); 9312 } 9313 InitFieldIndex.pop_back(); 9314 } 9315 9316 // Returns true if MemberExpr is checked and no futher checking is needed. 9317 // Returns false if additional checking is required. 9318 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9319 llvm::SmallVector<FieldDecl*, 4> Fields; 9320 Expr *Base = E; 9321 bool ReferenceField = false; 9322 9323 // Get the field memebers used. 9324 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9325 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9326 if (!FD) 9327 return false; 9328 Fields.push_back(FD); 9329 if (FD->getType()->isReferenceType()) 9330 ReferenceField = true; 9331 Base = ME->getBase()->IgnoreParenImpCasts(); 9332 } 9333 9334 // Keep checking only if the base Decl is the same. 9335 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9336 if (!DRE || DRE->getDecl() != OrigDecl) 9337 return false; 9338 9339 // A reference field can be bound to an unininitialized field. 9340 if (CheckReference && !ReferenceField) 9341 return true; 9342 9343 // Convert FieldDecls to their index number. 9344 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9345 for (const FieldDecl *I : llvm::reverse(Fields)) 9346 UsedFieldIndex.push_back(I->getFieldIndex()); 9347 9348 // See if a warning is needed by checking the first difference in index 9349 // numbers. If field being used has index less than the field being 9350 // initialized, then the use is safe. 9351 for (auto UsedIter = UsedFieldIndex.begin(), 9352 UsedEnd = UsedFieldIndex.end(), 9353 OrigIter = InitFieldIndex.begin(), 9354 OrigEnd = InitFieldIndex.end(); 9355 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9356 if (*UsedIter < *OrigIter) 9357 return true; 9358 if (*UsedIter > *OrigIter) 9359 break; 9360 } 9361 9362 // TODO: Add a different warning which will print the field names. 9363 HandleDeclRefExpr(DRE); 9364 return true; 9365 } 9366 9367 // For most expressions, the cast is directly above the DeclRefExpr. 9368 // For conditional operators, the cast can be outside the conditional 9369 // operator if both expressions are DeclRefExpr's. 9370 void HandleValue(Expr *E) { 9371 E = E->IgnoreParens(); 9372 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9373 HandleDeclRefExpr(DRE); 9374 return; 9375 } 9376 9377 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9378 Visit(CO->getCond()); 9379 HandleValue(CO->getTrueExpr()); 9380 HandleValue(CO->getFalseExpr()); 9381 return; 9382 } 9383 9384 if (BinaryConditionalOperator *BCO = 9385 dyn_cast<BinaryConditionalOperator>(E)) { 9386 Visit(BCO->getCond()); 9387 HandleValue(BCO->getFalseExpr()); 9388 return; 9389 } 9390 9391 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9392 HandleValue(OVE->getSourceExpr()); 9393 return; 9394 } 9395 9396 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9397 if (BO->getOpcode() == BO_Comma) { 9398 Visit(BO->getLHS()); 9399 HandleValue(BO->getRHS()); 9400 return; 9401 } 9402 } 9403 9404 if (isa<MemberExpr>(E)) { 9405 if (isInitList) { 9406 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9407 false /*CheckReference*/)) 9408 return; 9409 } 9410 9411 Expr *Base = E->IgnoreParenImpCasts(); 9412 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9413 // Check for static member variables and don't warn on them. 9414 if (!isa<FieldDecl>(ME->getMemberDecl())) 9415 return; 9416 Base = ME->getBase()->IgnoreParenImpCasts(); 9417 } 9418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9419 HandleDeclRefExpr(DRE); 9420 return; 9421 } 9422 9423 Visit(E); 9424 } 9425 9426 // Reference types not handled in HandleValue are handled here since all 9427 // uses of references are bad, not just r-value uses. 9428 void VisitDeclRefExpr(DeclRefExpr *E) { 9429 if (isReferenceType) 9430 HandleDeclRefExpr(E); 9431 } 9432 9433 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9434 if (E->getCastKind() == CK_LValueToRValue) { 9435 HandleValue(E->getSubExpr()); 9436 return; 9437 } 9438 9439 Inherited::VisitImplicitCastExpr(E); 9440 } 9441 9442 void VisitMemberExpr(MemberExpr *E) { 9443 if (isInitList) { 9444 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9445 return; 9446 } 9447 9448 // Don't warn on arrays since they can be treated as pointers. 9449 if (E->getType()->canDecayToPointerType()) return; 9450 9451 // Warn when a non-static method call is followed by non-static member 9452 // field accesses, which is followed by a DeclRefExpr. 9453 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9454 bool Warn = (MD && !MD->isStatic()); 9455 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9456 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9457 if (!isa<FieldDecl>(ME->getMemberDecl())) 9458 Warn = false; 9459 Base = ME->getBase()->IgnoreParenImpCasts(); 9460 } 9461 9462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9463 if (Warn) 9464 HandleDeclRefExpr(DRE); 9465 return; 9466 } 9467 9468 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9469 // Visit that expression. 9470 Visit(Base); 9471 } 9472 9473 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9474 Expr *Callee = E->getCallee(); 9475 9476 if (isa<UnresolvedLookupExpr>(Callee)) 9477 return Inherited::VisitCXXOperatorCallExpr(E); 9478 9479 Visit(Callee); 9480 for (auto Arg: E->arguments()) 9481 HandleValue(Arg->IgnoreParenImpCasts()); 9482 } 9483 9484 void VisitUnaryOperator(UnaryOperator *E) { 9485 // For POD record types, addresses of its own members are well-defined. 9486 if (E->getOpcode() == UO_AddrOf && isRecordType && 9487 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9488 if (!isPODType) 9489 HandleValue(E->getSubExpr()); 9490 return; 9491 } 9492 9493 if (E->isIncrementDecrementOp()) { 9494 HandleValue(E->getSubExpr()); 9495 return; 9496 } 9497 9498 Inherited::VisitUnaryOperator(E); 9499 } 9500 9501 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9502 9503 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9504 if (E->getConstructor()->isCopyConstructor()) { 9505 Expr *ArgExpr = E->getArg(0); 9506 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9507 if (ILE->getNumInits() == 1) 9508 ArgExpr = ILE->getInit(0); 9509 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9510 if (ICE->getCastKind() == CK_NoOp) 9511 ArgExpr = ICE->getSubExpr(); 9512 HandleValue(ArgExpr); 9513 return; 9514 } 9515 Inherited::VisitCXXConstructExpr(E); 9516 } 9517 9518 void VisitCallExpr(CallExpr *E) { 9519 // Treat std::move as a use. 9520 if (E->getNumArgs() == 1) { 9521 if (FunctionDecl *FD = E->getDirectCallee()) { 9522 if (FD->isInStdNamespace() && FD->getIdentifier() && 9523 FD->getIdentifier()->isStr("move")) { 9524 HandleValue(E->getArg(0)); 9525 return; 9526 } 9527 } 9528 } 9529 9530 Inherited::VisitCallExpr(E); 9531 } 9532 9533 void VisitBinaryOperator(BinaryOperator *E) { 9534 if (E->isCompoundAssignmentOp()) { 9535 HandleValue(E->getLHS()); 9536 Visit(E->getRHS()); 9537 return; 9538 } 9539 9540 Inherited::VisitBinaryOperator(E); 9541 } 9542 9543 // A custom visitor for BinaryConditionalOperator is needed because the 9544 // regular visitor would check the condition and true expression separately 9545 // but both point to the same place giving duplicate diagnostics. 9546 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9547 Visit(E->getCond()); 9548 Visit(E->getFalseExpr()); 9549 } 9550 9551 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9552 Decl* ReferenceDecl = DRE->getDecl(); 9553 if (OrigDecl != ReferenceDecl) return; 9554 unsigned diag; 9555 if (isReferenceType) { 9556 diag = diag::warn_uninit_self_reference_in_reference_init; 9557 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9558 diag = diag::warn_static_self_reference_in_init; 9559 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9560 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9561 DRE->getDecl()->getType()->isRecordType()) { 9562 diag = diag::warn_uninit_self_reference_in_init; 9563 } else { 9564 // Local variables will be handled by the CFG analysis. 9565 return; 9566 } 9567 9568 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9569 S.PDiag(diag) 9570 << DRE->getNameInfo().getName() 9571 << OrigDecl->getLocation() 9572 << DRE->getSourceRange()); 9573 } 9574 }; 9575 9576 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9577 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9578 bool DirectInit) { 9579 // Parameters arguments are occassionially constructed with itself, 9580 // for instance, in recursive functions. Skip them. 9581 if (isa<ParmVarDecl>(OrigDecl)) 9582 return; 9583 9584 E = E->IgnoreParens(); 9585 9586 // Skip checking T a = a where T is not a record or reference type. 9587 // Doing so is a way to silence uninitialized warnings. 9588 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9589 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9590 if (ICE->getCastKind() == CK_LValueToRValue) 9591 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9592 if (DRE->getDecl() == OrigDecl) 9593 return; 9594 9595 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9596 } 9597 } // end anonymous namespace 9598 9599 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9600 DeclarationName Name, QualType Type, 9601 TypeSourceInfo *TSI, 9602 SourceRange Range, bool DirectInit, 9603 Expr *Init) { 9604 bool IsInitCapture = !VDecl; 9605 assert((!VDecl || !VDecl->isInitCapture()) && 9606 "init captures are expected to be deduced prior to initialization"); 9607 9608 // FIXME: Deduction for a decomposition declaration does weird things if the 9609 // initializer is an array. 9610 9611 ArrayRef<Expr *> DeduceInits = Init; 9612 if (DirectInit) { 9613 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9614 DeduceInits = PL->exprs(); 9615 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9616 DeduceInits = IL->inits(); 9617 } 9618 9619 // Deduction only works if we have exactly one source expression. 9620 if (DeduceInits.empty()) { 9621 // It isn't possible to write this directly, but it is possible to 9622 // end up in this situation with "auto x(some_pack...);" 9623 Diag(Init->getLocStart(), IsInitCapture 9624 ? diag::err_init_capture_no_expression 9625 : diag::err_auto_var_init_no_expression) 9626 << Name << Type << Range; 9627 return QualType(); 9628 } 9629 9630 if (DeduceInits.size() > 1) { 9631 Diag(DeduceInits[1]->getLocStart(), 9632 IsInitCapture ? diag::err_init_capture_multiple_expressions 9633 : diag::err_auto_var_init_multiple_expressions) 9634 << Name << Type << Range; 9635 return QualType(); 9636 } 9637 9638 Expr *DeduceInit = DeduceInits[0]; 9639 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9640 Diag(Init->getLocStart(), IsInitCapture 9641 ? diag::err_init_capture_paren_braces 9642 : diag::err_auto_var_init_paren_braces) 9643 << isa<InitListExpr>(Init) << Name << Type << Range; 9644 return QualType(); 9645 } 9646 9647 // Expressions default to 'id' when we're in a debugger. 9648 bool DefaultedAnyToId = false; 9649 if (getLangOpts().DebuggerCastResultToId && 9650 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9651 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9652 if (Result.isInvalid()) { 9653 return QualType(); 9654 } 9655 Init = Result.get(); 9656 DefaultedAnyToId = true; 9657 } 9658 9659 QualType DeducedType; 9660 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9661 if (!IsInitCapture) 9662 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9663 else if (isa<InitListExpr>(Init)) 9664 Diag(Range.getBegin(), 9665 diag::err_init_capture_deduction_failure_from_init_list) 9666 << Name 9667 << (DeduceInit->getType().isNull() ? TSI->getType() 9668 : DeduceInit->getType()) 9669 << DeduceInit->getSourceRange(); 9670 else 9671 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9672 << Name << TSI->getType() 9673 << (DeduceInit->getType().isNull() ? TSI->getType() 9674 : DeduceInit->getType()) 9675 << DeduceInit->getSourceRange(); 9676 } 9677 9678 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9679 // 'id' instead of a specific object type prevents most of our usual 9680 // checks. 9681 // We only want to warn outside of template instantiations, though: 9682 // inside a template, the 'id' could have come from a parameter. 9683 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9684 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9685 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9686 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9687 } 9688 9689 return DeducedType; 9690 } 9691 9692 /// AddInitializerToDecl - Adds the initializer Init to the 9693 /// declaration dcl. If DirectInit is true, this is C++ direct 9694 /// initialization rather than copy initialization. 9695 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9696 bool DirectInit, bool TypeMayContainAuto) { 9697 // If there is no declaration, there was an error parsing it. Just ignore 9698 // the initializer. 9699 if (!RealDecl || RealDecl->isInvalidDecl()) { 9700 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9701 return; 9702 } 9703 9704 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9705 // Pure-specifiers are handled in ActOnPureSpecifier. 9706 Diag(Method->getLocation(), diag::err_member_function_initialization) 9707 << Method->getDeclName() << Init->getSourceRange(); 9708 Method->setInvalidDecl(); 9709 return; 9710 } 9711 9712 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9713 if (!VDecl) { 9714 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9715 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9716 RealDecl->setInvalidDecl(); 9717 return; 9718 } 9719 9720 // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not 9721 // permitted. 9722 if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init)) 9723 Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl; 9724 9725 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9726 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9727 // Attempt typo correction early so that the type of the init expression can 9728 // be deduced based on the chosen correction if the original init contains a 9729 // TypoExpr. 9730 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9731 if (!Res.isUsable()) { 9732 RealDecl->setInvalidDecl(); 9733 return; 9734 } 9735 Init = Res.get(); 9736 9737 QualType DeducedType = deduceVarTypeFromInitializer( 9738 VDecl, VDecl->getDeclName(), VDecl->getType(), 9739 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9740 if (DeducedType.isNull()) { 9741 RealDecl->setInvalidDecl(); 9742 return; 9743 } 9744 9745 VDecl->setType(DeducedType); 9746 assert(VDecl->isLinkageValid()); 9747 9748 // In ARC, infer lifetime. 9749 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9750 VDecl->setInvalidDecl(); 9751 9752 // If this is a redeclaration, check that the type we just deduced matches 9753 // the previously declared type. 9754 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9755 // We never need to merge the type, because we cannot form an incomplete 9756 // array of auto, nor deduce such a type. 9757 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9758 } 9759 9760 // Check the deduced type is valid for a variable declaration. 9761 CheckVariableDeclarationType(VDecl); 9762 if (VDecl->isInvalidDecl()) 9763 return; 9764 } 9765 9766 // dllimport cannot be used on variable definitions. 9767 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9768 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9769 VDecl->setInvalidDecl(); 9770 return; 9771 } 9772 9773 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9774 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9775 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9776 VDecl->setInvalidDecl(); 9777 return; 9778 } 9779 9780 if (!VDecl->getType()->isDependentType()) { 9781 // A definition must end up with a complete type, which means it must be 9782 // complete with the restriction that an array type might be completed by 9783 // the initializer; note that later code assumes this restriction. 9784 QualType BaseDeclType = VDecl->getType(); 9785 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9786 BaseDeclType = Array->getElementType(); 9787 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9788 diag::err_typecheck_decl_incomplete_type)) { 9789 RealDecl->setInvalidDecl(); 9790 return; 9791 } 9792 9793 // The variable can not have an abstract class type. 9794 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9795 diag::err_abstract_type_in_decl, 9796 AbstractVariableType)) 9797 VDecl->setInvalidDecl(); 9798 } 9799 9800 // If adding the initializer will turn this declaration into a definition, 9801 // and we already have a definition for this variable, diagnose or otherwise 9802 // handle the situation. 9803 VarDecl *Def; 9804 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9805 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 9806 !VDecl->isThisDeclarationADemotedDefinition() && 9807 checkVarDeclRedefinition(Def, VDecl)) 9808 return; 9809 9810 if (getLangOpts().CPlusPlus) { 9811 // C++ [class.static.data]p4 9812 // If a static data member is of const integral or const 9813 // enumeration type, its declaration in the class definition can 9814 // specify a constant-initializer which shall be an integral 9815 // constant expression (5.19). In that case, the member can appear 9816 // in integral constant expressions. The member shall still be 9817 // defined in a namespace scope if it is used in the program and the 9818 // namespace scope definition shall not contain an initializer. 9819 // 9820 // We already performed a redefinition check above, but for static 9821 // data members we also need to check whether there was an in-class 9822 // declaration with an initializer. 9823 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9824 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9825 << VDecl->getDeclName(); 9826 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9827 diag::note_previous_initializer) 9828 << 0; 9829 return; 9830 } 9831 9832 if (VDecl->hasLocalStorage()) 9833 getCurFunction()->setHasBranchProtectedScope(); 9834 9835 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9836 VDecl->setInvalidDecl(); 9837 return; 9838 } 9839 } 9840 9841 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9842 // a kernel function cannot be initialized." 9843 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9844 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9845 VDecl->setInvalidDecl(); 9846 return; 9847 } 9848 9849 // Get the decls type and save a reference for later, since 9850 // CheckInitializerTypes may change it. 9851 QualType DclT = VDecl->getType(), SavT = DclT; 9852 9853 // Expressions default to 'id' when we're in a debugger 9854 // and we are assigning it to a variable of Objective-C pointer type. 9855 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9856 Init->getType() == Context.UnknownAnyTy) { 9857 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9858 if (Result.isInvalid()) { 9859 VDecl->setInvalidDecl(); 9860 return; 9861 } 9862 Init = Result.get(); 9863 } 9864 9865 // Perform the initialization. 9866 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9867 if (!VDecl->isInvalidDecl()) { 9868 // Handle errors like: int a({0}) 9869 if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 && 9870 !canInitializeWithParenthesizedList(VDecl->getType())) 9871 if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) { 9872 Diag(VDecl->getLocation(), diag::err_list_init_in_parens) 9873 << VDecl->getType() << CXXDirectInit->getSourceRange() 9874 << FixItHint::CreateRemoval(CXXDirectInit->getLocStart()) 9875 << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd()); 9876 Init = IList; 9877 CXXDirectInit = nullptr; 9878 } 9879 9880 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9881 InitializationKind Kind = 9882 DirectInit 9883 ? CXXDirectInit 9884 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9885 Init->getLocStart(), 9886 Init->getLocEnd()) 9887 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9888 : InitializationKind::CreateCopy(VDecl->getLocation(), 9889 Init->getLocStart()); 9890 9891 MultiExprArg Args = Init; 9892 if (CXXDirectInit) 9893 Args = MultiExprArg(CXXDirectInit->getExprs(), 9894 CXXDirectInit->getNumExprs()); 9895 9896 // Try to correct any TypoExprs in the initialization arguments. 9897 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9898 ExprResult Res = CorrectDelayedTyposInExpr( 9899 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9900 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9901 return Init.Failed() ? ExprError() : E; 9902 }); 9903 if (Res.isInvalid()) { 9904 VDecl->setInvalidDecl(); 9905 } else if (Res.get() != Args[Idx]) { 9906 Args[Idx] = Res.get(); 9907 } 9908 } 9909 if (VDecl->isInvalidDecl()) 9910 return; 9911 9912 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9913 /*TopLevelOfInitList=*/false, 9914 /*TreatUnavailableAsInvalid=*/false); 9915 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9916 if (Result.isInvalid()) { 9917 VDecl->setInvalidDecl(); 9918 return; 9919 } 9920 9921 Init = Result.getAs<Expr>(); 9922 } 9923 9924 // Check for self-references within variable initializers. 9925 // Variables declared within a function/method body (except for references) 9926 // are handled by a dataflow analysis. 9927 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9928 VDecl->getType()->isReferenceType()) { 9929 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9930 } 9931 9932 // If the type changed, it means we had an incomplete type that was 9933 // completed by the initializer. For example: 9934 // int ary[] = { 1, 3, 5 }; 9935 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9936 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9937 VDecl->setType(DclT); 9938 9939 if (!VDecl->isInvalidDecl()) { 9940 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9941 9942 if (VDecl->hasAttr<BlocksAttr>()) 9943 checkRetainCycles(VDecl, Init); 9944 9945 // It is safe to assign a weak reference into a strong variable. 9946 // Although this code can still have problems: 9947 // id x = self.weakProp; 9948 // id y = self.weakProp; 9949 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9950 // paths through the function. This should be revisited if 9951 // -Wrepeated-use-of-weak is made flow-sensitive. 9952 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9953 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9954 Init->getLocStart())) 9955 getCurFunction()->markSafeWeakUse(Init); 9956 } 9957 9958 // The initialization is usually a full-expression. 9959 // 9960 // FIXME: If this is a braced initialization of an aggregate, it is not 9961 // an expression, and each individual field initializer is a separate 9962 // full-expression. For instance, in: 9963 // 9964 // struct Temp { ~Temp(); }; 9965 // struct S { S(Temp); }; 9966 // struct T { S a, b; } t = { Temp(), Temp() } 9967 // 9968 // we should destroy the first Temp before constructing the second. 9969 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9970 false, 9971 VDecl->isConstexpr()); 9972 if (Result.isInvalid()) { 9973 VDecl->setInvalidDecl(); 9974 return; 9975 } 9976 Init = Result.get(); 9977 9978 // Attach the initializer to the decl. 9979 VDecl->setInit(Init); 9980 9981 if (VDecl->isLocalVarDecl()) { 9982 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9983 // static storage duration shall be constant expressions or string literals. 9984 // C++ does not have this restriction. 9985 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9986 const Expr *Culprit; 9987 if (VDecl->getStorageClass() == SC_Static) 9988 CheckForConstantInitializer(Init, DclT); 9989 // C89 is stricter than C99 for non-static aggregate types. 9990 // C89 6.5.7p3: All the expressions [...] in an initializer list 9991 // for an object that has aggregate or union type shall be 9992 // constant expressions. 9993 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9994 isa<InitListExpr>(Init) && 9995 !Init->isConstantInitializer(Context, false, &Culprit)) 9996 Diag(Culprit->getExprLoc(), 9997 diag::ext_aggregate_init_not_constant) 9998 << Culprit->getSourceRange(); 9999 } 10000 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10001 VDecl->getLexicalDeclContext()->isRecord()) { 10002 // This is an in-class initialization for a static data member, e.g., 10003 // 10004 // struct S { 10005 // static const int value = 17; 10006 // }; 10007 10008 // C++ [class.mem]p4: 10009 // A member-declarator can contain a constant-initializer only 10010 // if it declares a static member (9.4) of const integral or 10011 // const enumeration type, see 9.4.2. 10012 // 10013 // C++11 [class.static.data]p3: 10014 // If a non-volatile non-inline const static data member is of integral 10015 // or enumeration type, its declaration in the class definition can 10016 // specify a brace-or-equal-initializer in which every initalizer-clause 10017 // that is an assignment-expression is a constant expression. A static 10018 // data member of literal type can be declared in the class definition 10019 // with the constexpr specifier; if so, its declaration shall specify a 10020 // brace-or-equal-initializer in which every initializer-clause that is 10021 // an assignment-expression is a constant expression. 10022 10023 // Do nothing on dependent types. 10024 if (DclT->isDependentType()) { 10025 10026 // Allow any 'static constexpr' members, whether or not they are of literal 10027 // type. We separately check that every constexpr variable is of literal 10028 // type. 10029 } else if (VDecl->isConstexpr()) { 10030 10031 // Require constness. 10032 } else if (!DclT.isConstQualified()) { 10033 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10034 << Init->getSourceRange(); 10035 VDecl->setInvalidDecl(); 10036 10037 // We allow integer constant expressions in all cases. 10038 } else if (DclT->isIntegralOrEnumerationType()) { 10039 // Check whether the expression is a constant expression. 10040 SourceLocation Loc; 10041 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10042 // In C++11, a non-constexpr const static data member with an 10043 // in-class initializer cannot be volatile. 10044 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10045 else if (Init->isValueDependent()) 10046 ; // Nothing to check. 10047 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10048 ; // Ok, it's an ICE! 10049 else if (Init->isEvaluatable(Context)) { 10050 // If we can constant fold the initializer through heroics, accept it, 10051 // but report this as a use of an extension for -pedantic. 10052 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10053 << Init->getSourceRange(); 10054 } else { 10055 // Otherwise, this is some crazy unknown case. Report the issue at the 10056 // location provided by the isIntegerConstantExpr failed check. 10057 Diag(Loc, diag::err_in_class_initializer_non_constant) 10058 << Init->getSourceRange(); 10059 VDecl->setInvalidDecl(); 10060 } 10061 10062 // We allow foldable floating-point constants as an extension. 10063 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10064 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10065 // it anyway and provide a fixit to add the 'constexpr'. 10066 if (getLangOpts().CPlusPlus11) { 10067 Diag(VDecl->getLocation(), 10068 diag::ext_in_class_initializer_float_type_cxx11) 10069 << DclT << Init->getSourceRange(); 10070 Diag(VDecl->getLocStart(), 10071 diag::note_in_class_initializer_float_type_cxx11) 10072 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10073 } else { 10074 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10075 << DclT << Init->getSourceRange(); 10076 10077 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10078 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10079 << Init->getSourceRange(); 10080 VDecl->setInvalidDecl(); 10081 } 10082 } 10083 10084 // Suggest adding 'constexpr' in C++11 for literal types. 10085 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10086 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10087 << DclT << Init->getSourceRange() 10088 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10089 VDecl->setConstexpr(true); 10090 10091 } else { 10092 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10093 << DclT << Init->getSourceRange(); 10094 VDecl->setInvalidDecl(); 10095 } 10096 } else if (VDecl->isFileVarDecl()) { 10097 // In C, extern is typically used to avoid tentative definitions when 10098 // declaring variables in headers, but adding an intializer makes it a 10099 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10100 // In C++, extern is often used to give implictly static const variables 10101 // external linkage, so don't warn in that case. If selectany is present, 10102 // this might be header code intended for C and C++ inclusion, so apply the 10103 // C++ rules. 10104 if (VDecl->getStorageClass() == SC_Extern && 10105 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10106 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10107 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10108 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10109 Diag(VDecl->getLocation(), diag::warn_extern_init); 10110 10111 // C99 6.7.8p4. All file scoped initializers need to be constant. 10112 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10113 CheckForConstantInitializer(Init, DclT); 10114 } 10115 10116 // We will represent direct-initialization similarly to copy-initialization: 10117 // int x(1); -as-> int x = 1; 10118 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10119 // 10120 // Clients that want to distinguish between the two forms, can check for 10121 // direct initializer using VarDecl::getInitStyle(). 10122 // A major benefit is that clients that don't particularly care about which 10123 // exactly form was it (like the CodeGen) can handle both cases without 10124 // special case code. 10125 10126 // C++ 8.5p11: 10127 // The form of initialization (using parentheses or '=') is generally 10128 // insignificant, but does matter when the entity being initialized has a 10129 // class type. 10130 if (CXXDirectInit) { 10131 assert(DirectInit && "Call-style initializer must be direct init."); 10132 VDecl->setInitStyle(VarDecl::CallInit); 10133 } else if (DirectInit) { 10134 // This must be list-initialization. No other way is direct-initialization. 10135 VDecl->setInitStyle(VarDecl::ListInit); 10136 } 10137 10138 CheckCompleteVariableDeclaration(VDecl); 10139 } 10140 10141 /// ActOnInitializerError - Given that there was an error parsing an 10142 /// initializer for the given declaration, try to return to some form 10143 /// of sanity. 10144 void Sema::ActOnInitializerError(Decl *D) { 10145 // Our main concern here is re-establishing invariants like "a 10146 // variable's type is either dependent or complete". 10147 if (!D || D->isInvalidDecl()) return; 10148 10149 VarDecl *VD = dyn_cast<VarDecl>(D); 10150 if (!VD) return; 10151 10152 // Bindings are not usable if we can't make sense of the initializer. 10153 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10154 for (auto *BD : DD->bindings()) 10155 BD->setInvalidDecl(); 10156 10157 // Auto types are meaningless if we can't make sense of the initializer. 10158 if (ParsingInitForAutoVars.count(D)) { 10159 D->setInvalidDecl(); 10160 return; 10161 } 10162 10163 QualType Ty = VD->getType(); 10164 if (Ty->isDependentType()) return; 10165 10166 // Require a complete type. 10167 if (RequireCompleteType(VD->getLocation(), 10168 Context.getBaseElementType(Ty), 10169 diag::err_typecheck_decl_incomplete_type)) { 10170 VD->setInvalidDecl(); 10171 return; 10172 } 10173 10174 // Require a non-abstract type. 10175 if (RequireNonAbstractType(VD->getLocation(), Ty, 10176 diag::err_abstract_type_in_decl, 10177 AbstractVariableType)) { 10178 VD->setInvalidDecl(); 10179 return; 10180 } 10181 10182 // Don't bother complaining about constructors or destructors, 10183 // though. 10184 } 10185 10186 /// Checks if an object of the given type can be initialized with parenthesized 10187 /// init-list. 10188 /// 10189 /// \param TargetType Type of object being initialized. 10190 /// 10191 /// The function is used to detect wrong initializations, such as 'int({0})'. 10192 /// 10193 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) { 10194 return TargetType->isDependentType() || TargetType->isRecordType() || 10195 TargetType->getContainedAutoType(); 10196 } 10197 10198 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 10199 bool TypeMayContainAuto) { 10200 // If there is no declaration, there was an error parsing it. Just ignore it. 10201 if (!RealDecl) 10202 return; 10203 10204 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10205 QualType Type = Var->getType(); 10206 10207 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10208 if (isa<DecompositionDecl>(RealDecl)) { 10209 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10210 Var->setInvalidDecl(); 10211 return; 10212 } 10213 10214 // C++11 [dcl.spec.auto]p3 10215 if (TypeMayContainAuto && Type->getContainedAutoType()) { 10216 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10217 << Var->getDeclName() << Type; 10218 Var->setInvalidDecl(); 10219 return; 10220 } 10221 10222 // C++11 [class.static.data]p3: A static data member can be declared with 10223 // the constexpr specifier; if so, its declaration shall specify 10224 // a brace-or-equal-initializer. 10225 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10226 // the definition of a variable [...] or the declaration of a static data 10227 // member. 10228 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10229 !Var->isThisDeclarationADemotedDefinition()) { 10230 if (Var->isStaticDataMember()) { 10231 // C++1z removes the relevant rule; the in-class declaration is always 10232 // a definition there. 10233 if (!getLangOpts().CPlusPlus1z) { 10234 Diag(Var->getLocation(), 10235 diag::err_constexpr_static_mem_var_requires_init) 10236 << Var->getDeclName(); 10237 Var->setInvalidDecl(); 10238 return; 10239 } 10240 } else { 10241 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10242 Var->setInvalidDecl(); 10243 return; 10244 } 10245 } 10246 10247 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10248 // definition having the concept specifier is called a variable concept. A 10249 // concept definition refers to [...] a variable concept and its initializer. 10250 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10251 if (VTD->isConcept()) { 10252 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10253 Var->setInvalidDecl(); 10254 return; 10255 } 10256 } 10257 10258 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10259 // be initialized. 10260 if (!Var->isInvalidDecl() && 10261 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10262 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10263 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10264 Var->setInvalidDecl(); 10265 return; 10266 } 10267 10268 switch (Var->isThisDeclarationADefinition()) { 10269 case VarDecl::Definition: 10270 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10271 break; 10272 10273 // We have an out-of-line definition of a static data member 10274 // that has an in-class initializer, so we type-check this like 10275 // a declaration. 10276 // 10277 // Fall through 10278 10279 case VarDecl::DeclarationOnly: 10280 // It's only a declaration. 10281 10282 // Block scope. C99 6.7p7: If an identifier for an object is 10283 // declared with no linkage (C99 6.2.2p6), the type for the 10284 // object shall be complete. 10285 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10286 !Var->hasLinkage() && !Var->isInvalidDecl() && 10287 RequireCompleteType(Var->getLocation(), Type, 10288 diag::err_typecheck_decl_incomplete_type)) 10289 Var->setInvalidDecl(); 10290 10291 // Make sure that the type is not abstract. 10292 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10293 RequireNonAbstractType(Var->getLocation(), Type, 10294 diag::err_abstract_type_in_decl, 10295 AbstractVariableType)) 10296 Var->setInvalidDecl(); 10297 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10298 Var->getStorageClass() == SC_PrivateExtern) { 10299 Diag(Var->getLocation(), diag::warn_private_extern); 10300 Diag(Var->getLocation(), diag::note_private_extern); 10301 } 10302 10303 return; 10304 10305 case VarDecl::TentativeDefinition: 10306 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10307 // object that has file scope without an initializer, and without a 10308 // storage-class specifier or with the storage-class specifier "static", 10309 // constitutes a tentative definition. Note: A tentative definition with 10310 // external linkage is valid (C99 6.2.2p5). 10311 if (!Var->isInvalidDecl()) { 10312 if (const IncompleteArrayType *ArrayT 10313 = Context.getAsIncompleteArrayType(Type)) { 10314 if (RequireCompleteType(Var->getLocation(), 10315 ArrayT->getElementType(), 10316 diag::err_illegal_decl_array_incomplete_type)) 10317 Var->setInvalidDecl(); 10318 } else if (Var->getStorageClass() == SC_Static) { 10319 // C99 6.9.2p3: If the declaration of an identifier for an object is 10320 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10321 // declared type shall not be an incomplete type. 10322 // NOTE: code such as the following 10323 // static struct s; 10324 // struct s { int a; }; 10325 // is accepted by gcc. Hence here we issue a warning instead of 10326 // an error and we do not invalidate the static declaration. 10327 // NOTE: to avoid multiple warnings, only check the first declaration. 10328 if (Var->isFirstDecl()) 10329 RequireCompleteType(Var->getLocation(), Type, 10330 diag::ext_typecheck_decl_incomplete_type); 10331 } 10332 } 10333 10334 // Record the tentative definition; we're done. 10335 if (!Var->isInvalidDecl()) 10336 TentativeDefinitions.push_back(Var); 10337 return; 10338 } 10339 10340 // Provide a specific diagnostic for uninitialized variable 10341 // definitions with incomplete array type. 10342 if (Type->isIncompleteArrayType()) { 10343 Diag(Var->getLocation(), 10344 diag::err_typecheck_incomplete_array_needs_initializer); 10345 Var->setInvalidDecl(); 10346 return; 10347 } 10348 10349 // Provide a specific diagnostic for uninitialized variable 10350 // definitions with reference type. 10351 if (Type->isReferenceType()) { 10352 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10353 << Var->getDeclName() 10354 << SourceRange(Var->getLocation(), Var->getLocation()); 10355 Var->setInvalidDecl(); 10356 return; 10357 } 10358 10359 // Do not attempt to type-check the default initializer for a 10360 // variable with dependent type. 10361 if (Type->isDependentType()) 10362 return; 10363 10364 if (Var->isInvalidDecl()) 10365 return; 10366 10367 if (!Var->hasAttr<AliasAttr>()) { 10368 if (RequireCompleteType(Var->getLocation(), 10369 Context.getBaseElementType(Type), 10370 diag::err_typecheck_decl_incomplete_type)) { 10371 Var->setInvalidDecl(); 10372 return; 10373 } 10374 } else { 10375 return; 10376 } 10377 10378 // The variable can not have an abstract class type. 10379 if (RequireNonAbstractType(Var->getLocation(), Type, 10380 diag::err_abstract_type_in_decl, 10381 AbstractVariableType)) { 10382 Var->setInvalidDecl(); 10383 return; 10384 } 10385 10386 // Check for jumps past the implicit initializer. C++0x 10387 // clarifies that this applies to a "variable with automatic 10388 // storage duration", not a "local variable". 10389 // C++11 [stmt.dcl]p3 10390 // A program that jumps from a point where a variable with automatic 10391 // storage duration is not in scope to a point where it is in scope is 10392 // ill-formed unless the variable has scalar type, class type with a 10393 // trivial default constructor and a trivial destructor, a cv-qualified 10394 // version of one of these types, or an array of one of the preceding 10395 // types and is declared without an initializer. 10396 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10397 if (const RecordType *Record 10398 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10399 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10400 // Mark the function for further checking even if the looser rules of 10401 // C++11 do not require such checks, so that we can diagnose 10402 // incompatibilities with C++98. 10403 if (!CXXRecord->isPOD()) 10404 getCurFunction()->setHasBranchProtectedScope(); 10405 } 10406 } 10407 10408 // C++03 [dcl.init]p9: 10409 // If no initializer is specified for an object, and the 10410 // object is of (possibly cv-qualified) non-POD class type (or 10411 // array thereof), the object shall be default-initialized; if 10412 // the object is of const-qualified type, the underlying class 10413 // type shall have a user-declared default 10414 // constructor. Otherwise, if no initializer is specified for 10415 // a non- static object, the object and its subobjects, if 10416 // any, have an indeterminate initial value); if the object 10417 // or any of its subobjects are of const-qualified type, the 10418 // program is ill-formed. 10419 // C++0x [dcl.init]p11: 10420 // If no initializer is specified for an object, the object is 10421 // default-initialized; [...]. 10422 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10423 InitializationKind Kind 10424 = InitializationKind::CreateDefault(Var->getLocation()); 10425 10426 InitializationSequence InitSeq(*this, Entity, Kind, None); 10427 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10428 if (Init.isInvalid()) 10429 Var->setInvalidDecl(); 10430 else if (Init.get()) { 10431 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10432 // This is important for template substitution. 10433 Var->setInitStyle(VarDecl::CallInit); 10434 } 10435 10436 CheckCompleteVariableDeclaration(Var); 10437 } 10438 } 10439 10440 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10441 // If there is no declaration, there was an error parsing it. Ignore it. 10442 if (!D) 10443 return; 10444 10445 VarDecl *VD = dyn_cast<VarDecl>(D); 10446 if (!VD) { 10447 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10448 D->setInvalidDecl(); 10449 return; 10450 } 10451 10452 VD->setCXXForRangeDecl(true); 10453 10454 // for-range-declaration cannot be given a storage class specifier. 10455 int Error = -1; 10456 switch (VD->getStorageClass()) { 10457 case SC_None: 10458 break; 10459 case SC_Extern: 10460 Error = 0; 10461 break; 10462 case SC_Static: 10463 Error = 1; 10464 break; 10465 case SC_PrivateExtern: 10466 Error = 2; 10467 break; 10468 case SC_Auto: 10469 Error = 3; 10470 break; 10471 case SC_Register: 10472 Error = 4; 10473 break; 10474 } 10475 if (Error != -1) { 10476 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10477 << VD->getDeclName() << Error; 10478 D->setInvalidDecl(); 10479 } 10480 } 10481 10482 StmtResult 10483 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10484 IdentifierInfo *Ident, 10485 ParsedAttributes &Attrs, 10486 SourceLocation AttrEnd) { 10487 // C++1y [stmt.iter]p1: 10488 // A range-based for statement of the form 10489 // for ( for-range-identifier : for-range-initializer ) statement 10490 // is equivalent to 10491 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10492 DeclSpec DS(Attrs.getPool().getFactory()); 10493 10494 const char *PrevSpec; 10495 unsigned DiagID; 10496 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10497 getPrintingPolicy()); 10498 10499 Declarator D(DS, Declarator::ForContext); 10500 D.SetIdentifier(Ident, IdentLoc); 10501 D.takeAttributes(Attrs, AttrEnd); 10502 10503 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10504 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10505 EmptyAttrs, IdentLoc); 10506 Decl *Var = ActOnDeclarator(S, D); 10507 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10508 FinalizeDeclaration(Var); 10509 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10510 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10511 } 10512 10513 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10514 if (var->isInvalidDecl()) return; 10515 10516 if (getLangOpts().OpenCL) { 10517 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10518 // initialiser 10519 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10520 !var->hasInit()) { 10521 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10522 << 1 /*Init*/; 10523 var->setInvalidDecl(); 10524 return; 10525 } 10526 } 10527 10528 // In Objective-C, don't allow jumps past the implicit initialization of a 10529 // local retaining variable. 10530 if (getLangOpts().ObjC1 && 10531 var->hasLocalStorage()) { 10532 switch (var->getType().getObjCLifetime()) { 10533 case Qualifiers::OCL_None: 10534 case Qualifiers::OCL_ExplicitNone: 10535 case Qualifiers::OCL_Autoreleasing: 10536 break; 10537 10538 case Qualifiers::OCL_Weak: 10539 case Qualifiers::OCL_Strong: 10540 getCurFunction()->setHasBranchProtectedScope(); 10541 break; 10542 } 10543 } 10544 10545 // Warn about externally-visible variables being defined without a 10546 // prior declaration. We only want to do this for global 10547 // declarations, but we also specifically need to avoid doing it for 10548 // class members because the linkage of an anonymous class can 10549 // change if it's later given a typedef name. 10550 if (var->isThisDeclarationADefinition() && 10551 var->getDeclContext()->getRedeclContext()->isFileContext() && 10552 var->isExternallyVisible() && var->hasLinkage() && 10553 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10554 var->getLocation())) { 10555 // Find a previous declaration that's not a definition. 10556 VarDecl *prev = var->getPreviousDecl(); 10557 while (prev && prev->isThisDeclarationADefinition()) 10558 prev = prev->getPreviousDecl(); 10559 10560 if (!prev) 10561 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10562 } 10563 10564 // Cache the result of checking for constant initialization. 10565 Optional<bool> CacheHasConstInit; 10566 const Expr *CacheCulprit; 10567 auto checkConstInit = [&]() mutable { 10568 if (!CacheHasConstInit) 10569 CacheHasConstInit = var->getInit()->isConstantInitializer( 10570 Context, var->getType()->isReferenceType(), &CacheCulprit); 10571 return *CacheHasConstInit; 10572 }; 10573 10574 if (var->getTLSKind() == VarDecl::TLS_Static) { 10575 if (var->getType().isDestructedType()) { 10576 // GNU C++98 edits for __thread, [basic.start.term]p3: 10577 // The type of an object with thread storage duration shall not 10578 // have a non-trivial destructor. 10579 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10580 if (getLangOpts().CPlusPlus11) 10581 Diag(var->getLocation(), diag::note_use_thread_local); 10582 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10583 if (!checkConstInit()) { 10584 // GNU C++98 edits for __thread, [basic.start.init]p4: 10585 // An object of thread storage duration shall not require dynamic 10586 // initialization. 10587 // FIXME: Need strict checking here. 10588 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10589 << CacheCulprit->getSourceRange(); 10590 if (getLangOpts().CPlusPlus11) 10591 Diag(var->getLocation(), diag::note_use_thread_local); 10592 } 10593 } 10594 } 10595 10596 // Apply section attributes and pragmas to global variables. 10597 bool GlobalStorage = var->hasGlobalStorage(); 10598 if (GlobalStorage && var->isThisDeclarationADefinition() && 10599 ActiveTemplateInstantiations.empty()) { 10600 PragmaStack<StringLiteral *> *Stack = nullptr; 10601 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10602 if (var->getType().isConstQualified()) 10603 Stack = &ConstSegStack; 10604 else if (!var->getInit()) { 10605 Stack = &BSSSegStack; 10606 SectionFlags |= ASTContext::PSF_Write; 10607 } else { 10608 Stack = &DataSegStack; 10609 SectionFlags |= ASTContext::PSF_Write; 10610 } 10611 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10612 var->addAttr(SectionAttr::CreateImplicit( 10613 Context, SectionAttr::Declspec_allocate, 10614 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10615 } 10616 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10617 if (UnifySection(SA->getName(), SectionFlags, var)) 10618 var->dropAttr<SectionAttr>(); 10619 10620 // Apply the init_seg attribute if this has an initializer. If the 10621 // initializer turns out to not be dynamic, we'll end up ignoring this 10622 // attribute. 10623 if (CurInitSeg && var->getInit()) 10624 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10625 CurInitSegLoc)); 10626 } 10627 10628 // All the following checks are C++ only. 10629 if (!getLangOpts().CPlusPlus) { 10630 // If this variable must be emitted, add it as an initializer for the 10631 // current module. 10632 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10633 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10634 return; 10635 } 10636 10637 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10638 CheckCompleteDecompositionDeclaration(DD); 10639 10640 QualType type = var->getType(); 10641 if (type->isDependentType()) return; 10642 10643 // __block variables might require us to capture a copy-initializer. 10644 if (var->hasAttr<BlocksAttr>()) { 10645 // It's currently invalid to ever have a __block variable with an 10646 // array type; should we diagnose that here? 10647 10648 // Regardless, we don't want to ignore array nesting when 10649 // constructing this copy. 10650 if (type->isStructureOrClassType()) { 10651 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10652 SourceLocation poi = var->getLocation(); 10653 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10654 ExprResult result 10655 = PerformMoveOrCopyInitialization( 10656 InitializedEntity::InitializeBlock(poi, type, false), 10657 var, var->getType(), varRef, /*AllowNRVO=*/true); 10658 if (!result.isInvalid()) { 10659 result = MaybeCreateExprWithCleanups(result); 10660 Expr *init = result.getAs<Expr>(); 10661 Context.setBlockVarCopyInits(var, init); 10662 } 10663 } 10664 } 10665 10666 Expr *Init = var->getInit(); 10667 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10668 QualType baseType = Context.getBaseElementType(type); 10669 10670 if (!var->getDeclContext()->isDependentContext() && 10671 Init && !Init->isValueDependent()) { 10672 10673 if (var->isConstexpr()) { 10674 SmallVector<PartialDiagnosticAt, 8> Notes; 10675 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10676 SourceLocation DiagLoc = var->getLocation(); 10677 // If the note doesn't add any useful information other than a source 10678 // location, fold it into the primary diagnostic. 10679 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10680 diag::note_invalid_subexpr_in_const_expr) { 10681 DiagLoc = Notes[0].first; 10682 Notes.clear(); 10683 } 10684 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10685 << var << Init->getSourceRange(); 10686 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10687 Diag(Notes[I].first, Notes[I].second); 10688 } 10689 } else if (var->isUsableInConstantExpressions(Context)) { 10690 // Check whether the initializer of a const variable of integral or 10691 // enumeration type is an ICE now, since we can't tell whether it was 10692 // initialized by a constant expression if we check later. 10693 var->checkInitIsICE(); 10694 } 10695 10696 // Don't emit further diagnostics about constexpr globals since they 10697 // were just diagnosed. 10698 if (!var->isConstexpr() && GlobalStorage && 10699 var->hasAttr<RequireConstantInitAttr>()) { 10700 // FIXME: Need strict checking in C++03 here. 10701 bool DiagErr = getLangOpts().CPlusPlus11 10702 ? !var->checkInitIsICE() : !checkConstInit(); 10703 if (DiagErr) { 10704 auto attr = var->getAttr<RequireConstantInitAttr>(); 10705 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10706 << Init->getSourceRange(); 10707 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10708 << attr->getRange(); 10709 } 10710 } 10711 else if (!var->isConstexpr() && IsGlobal && 10712 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10713 var->getLocation())) { 10714 // Warn about globals which don't have a constant initializer. Don't 10715 // warn about globals with a non-trivial destructor because we already 10716 // warned about them. 10717 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10718 if (!(RD && !RD->hasTrivialDestructor())) { 10719 if (!checkConstInit()) 10720 Diag(var->getLocation(), diag::warn_global_constructor) 10721 << Init->getSourceRange(); 10722 } 10723 } 10724 } 10725 10726 // Require the destructor. 10727 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10728 FinalizeVarWithDestructor(var, recordType); 10729 10730 // If this variable must be emitted, add it as an initializer for the current 10731 // module. 10732 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10733 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10734 } 10735 10736 /// \brief Determines if a variable's alignment is dependent. 10737 static bool hasDependentAlignment(VarDecl *VD) { 10738 if (VD->getType()->isDependentType()) 10739 return true; 10740 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10741 if (I->isAlignmentDependent()) 10742 return true; 10743 return false; 10744 } 10745 10746 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10747 /// any semantic actions necessary after any initializer has been attached. 10748 void 10749 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10750 // Note that we are no longer parsing the initializer for this declaration. 10751 ParsingInitForAutoVars.erase(ThisDecl); 10752 10753 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10754 if (!VD) 10755 return; 10756 10757 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10758 for (auto *BD : DD->bindings()) { 10759 FinalizeDeclaration(BD); 10760 } 10761 } 10762 10763 checkAttributesAfterMerging(*this, *VD); 10764 10765 // Perform TLS alignment check here after attributes attached to the variable 10766 // which may affect the alignment have been processed. Only perform the check 10767 // if the target has a maximum TLS alignment (zero means no constraints). 10768 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10769 // Protect the check so that it's not performed on dependent types and 10770 // dependent alignments (we can't determine the alignment in that case). 10771 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10772 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10773 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10774 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10775 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10776 << (unsigned)MaxAlignChars.getQuantity(); 10777 } 10778 } 10779 } 10780 10781 if (VD->isStaticLocal()) { 10782 if (FunctionDecl *FD = 10783 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10784 // Static locals inherit dll attributes from their function. 10785 if (Attr *A = getDLLAttr(FD)) { 10786 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10787 NewAttr->setInherited(true); 10788 VD->addAttr(NewAttr); 10789 } 10790 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10791 // function, only __shared__ variables may be declared with 10792 // static storage class. 10793 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 10794 CUDADiagIfDeviceCode(VD->getLocation(), 10795 diag::err_device_static_local_var) 10796 << CurrentCUDATarget()) 10797 VD->setInvalidDecl(); 10798 } 10799 } 10800 10801 // Perform check for initializers of device-side global variables. 10802 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10803 // 7.5). We must also apply the same checks to all __shared__ 10804 // variables whether they are local or not. CUDA also allows 10805 // constant initializers for __constant__ and __device__ variables. 10806 if (getLangOpts().CUDA) { 10807 const Expr *Init = VD->getInit(); 10808 if (Init && VD->hasGlobalStorage()) { 10809 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10810 VD->hasAttr<CUDASharedAttr>()) { 10811 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 10812 bool AllowedInit = false; 10813 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10814 AllowedInit = 10815 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10816 // We'll allow constant initializers even if it's a non-empty 10817 // constructor according to CUDA rules. This deviates from NVCC, 10818 // but allows us to handle things like constexpr constructors. 10819 if (!AllowedInit && 10820 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10821 AllowedInit = VD->getInit()->isConstantInitializer( 10822 Context, VD->getType()->isReferenceType()); 10823 10824 // Also make sure that destructor, if there is one, is empty. 10825 if (AllowedInit) 10826 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10827 AllowedInit = 10828 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10829 10830 if (!AllowedInit) { 10831 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10832 ? diag::err_shared_var_init 10833 : diag::err_dynamic_var_init) 10834 << Init->getSourceRange(); 10835 VD->setInvalidDecl(); 10836 } 10837 } else { 10838 // This is a host-side global variable. Check that the initializer is 10839 // callable from the host side. 10840 const FunctionDecl *InitFn = nullptr; 10841 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 10842 InitFn = CE->getConstructor(); 10843 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 10844 InitFn = CE->getDirectCallee(); 10845 } 10846 if (InitFn) { 10847 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 10848 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 10849 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 10850 << InitFnTarget << InitFn; 10851 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 10852 VD->setInvalidDecl(); 10853 } 10854 } 10855 } 10856 } 10857 } 10858 10859 // Grab the dllimport or dllexport attribute off of the VarDecl. 10860 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10861 10862 // Imported static data members cannot be defined out-of-line. 10863 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10864 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10865 VD->isThisDeclarationADefinition()) { 10866 // We allow definitions of dllimport class template static data members 10867 // with a warning. 10868 CXXRecordDecl *Context = 10869 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10870 bool IsClassTemplateMember = 10871 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10872 Context->getDescribedClassTemplate(); 10873 10874 Diag(VD->getLocation(), 10875 IsClassTemplateMember 10876 ? diag::warn_attribute_dllimport_static_field_definition 10877 : diag::err_attribute_dllimport_static_field_definition); 10878 Diag(IA->getLocation(), diag::note_attribute); 10879 if (!IsClassTemplateMember) 10880 VD->setInvalidDecl(); 10881 } 10882 } 10883 10884 // dllimport/dllexport variables cannot be thread local, their TLS index 10885 // isn't exported with the variable. 10886 if (DLLAttr && VD->getTLSKind()) { 10887 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10888 if (F && getDLLAttr(F)) { 10889 assert(VD->isStaticLocal()); 10890 // But if this is a static local in a dlimport/dllexport function, the 10891 // function will never be inlined, which means the var would never be 10892 // imported, so having it marked import/export is safe. 10893 } else { 10894 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10895 << DLLAttr; 10896 VD->setInvalidDecl(); 10897 } 10898 } 10899 10900 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10901 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10902 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10903 VD->dropAttr<UsedAttr>(); 10904 } 10905 } 10906 10907 const DeclContext *DC = VD->getDeclContext(); 10908 // If there's a #pragma GCC visibility in scope, and this isn't a class 10909 // member, set the visibility of this variable. 10910 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10911 AddPushedVisibilityAttribute(VD); 10912 10913 // FIXME: Warn on unused templates. 10914 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10915 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10916 MarkUnusedFileScopedDecl(VD); 10917 10918 // Now we have parsed the initializer and can update the table of magic 10919 // tag values. 10920 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10921 !VD->getType()->isIntegralOrEnumerationType()) 10922 return; 10923 10924 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10925 const Expr *MagicValueExpr = VD->getInit(); 10926 if (!MagicValueExpr) { 10927 continue; 10928 } 10929 llvm::APSInt MagicValueInt; 10930 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10931 Diag(I->getRange().getBegin(), 10932 diag::err_type_tag_for_datatype_not_ice) 10933 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10934 continue; 10935 } 10936 if (MagicValueInt.getActiveBits() > 64) { 10937 Diag(I->getRange().getBegin(), 10938 diag::err_type_tag_for_datatype_too_large) 10939 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10940 continue; 10941 } 10942 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10943 RegisterTypeTagForDatatype(I->getArgumentKind(), 10944 MagicValue, 10945 I->getMatchingCType(), 10946 I->getLayoutCompatible(), 10947 I->getMustBeNull()); 10948 } 10949 } 10950 10951 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10952 ArrayRef<Decl *> Group) { 10953 SmallVector<Decl*, 8> Decls; 10954 10955 if (DS.isTypeSpecOwned()) 10956 Decls.push_back(DS.getRepAsDecl()); 10957 10958 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10959 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 10960 bool DiagnosedMultipleDecomps = false; 10961 10962 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10963 if (Decl *D = Group[i]) { 10964 auto *DD = dyn_cast<DeclaratorDecl>(D); 10965 if (DD && !FirstDeclaratorInGroup) 10966 FirstDeclaratorInGroup = DD; 10967 10968 auto *Decomp = dyn_cast<DecompositionDecl>(D); 10969 if (Decomp && !FirstDecompDeclaratorInGroup) 10970 FirstDecompDeclaratorInGroup = Decomp; 10971 10972 // A decomposition declaration cannot be combined with any other 10973 // declaration in the same group. 10974 auto *OtherDD = FirstDeclaratorInGroup; 10975 if (OtherDD == FirstDecompDeclaratorInGroup) 10976 OtherDD = DD; 10977 if (OtherDD && FirstDecompDeclaratorInGroup && 10978 OtherDD != FirstDecompDeclaratorInGroup && 10979 !DiagnosedMultipleDecomps) { 10980 Diag(FirstDecompDeclaratorInGroup->getLocation(), 10981 diag::err_decomp_decl_not_alone) 10982 << OtherDD->getSourceRange(); 10983 DiagnosedMultipleDecomps = true; 10984 } 10985 10986 Decls.push_back(D); 10987 } 10988 } 10989 10990 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10991 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10992 handleTagNumbering(Tag, S); 10993 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10994 getLangOpts().CPlusPlus) 10995 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10996 } 10997 } 10998 10999 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 11000 } 11001 11002 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11003 /// group, performing any necessary semantic checking. 11004 Sema::DeclGroupPtrTy 11005 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 11006 bool TypeMayContainAuto) { 11007 // C++0x [dcl.spec.auto]p7: 11008 // If the type deduced for the template parameter U is not the same in each 11009 // deduction, the program is ill-formed. 11010 // FIXME: When initializer-list support is added, a distinction is needed 11011 // between the deduced type U and the deduced type which 'auto' stands for. 11012 // auto a = 0, b = { 1, 2, 3 }; 11013 // is legal because the deduced type U is 'int' in both cases. 11014 if (TypeMayContainAuto && Group.size() > 1) { 11015 QualType Deduced; 11016 CanQualType DeducedCanon; 11017 VarDecl *DeducedDecl = nullptr; 11018 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11019 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 11020 AutoType *AT = D->getType()->getContainedAutoType(); 11021 // Don't reissue diagnostics when instantiating a template. 11022 if (AT && D->isInvalidDecl()) 11023 break; 11024 QualType U = AT ? AT->getDeducedType() : QualType(); 11025 if (!U.isNull()) { 11026 CanQualType UCanon = Context.getCanonicalType(U); 11027 if (Deduced.isNull()) { 11028 Deduced = U; 11029 DeducedCanon = UCanon; 11030 DeducedDecl = D; 11031 } else if (DeducedCanon != UCanon) { 11032 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11033 diag::err_auto_different_deductions) 11034 << (unsigned)AT->getKeyword() 11035 << Deduced << DeducedDecl->getDeclName() 11036 << U << D->getDeclName() 11037 << DeducedDecl->getInit()->getSourceRange() 11038 << D->getInit()->getSourceRange(); 11039 D->setInvalidDecl(); 11040 break; 11041 } 11042 } 11043 } 11044 } 11045 } 11046 11047 ActOnDocumentableDecls(Group); 11048 11049 return DeclGroupPtrTy::make( 11050 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11051 } 11052 11053 void Sema::ActOnDocumentableDecl(Decl *D) { 11054 ActOnDocumentableDecls(D); 11055 } 11056 11057 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11058 // Don't parse the comment if Doxygen diagnostics are ignored. 11059 if (Group.empty() || !Group[0]) 11060 return; 11061 11062 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11063 Group[0]->getLocation()) && 11064 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11065 Group[0]->getLocation())) 11066 return; 11067 11068 if (Group.size() >= 2) { 11069 // This is a decl group. Normally it will contain only declarations 11070 // produced from declarator list. But in case we have any definitions or 11071 // additional declaration references: 11072 // 'typedef struct S {} S;' 11073 // 'typedef struct S *S;' 11074 // 'struct S *pS;' 11075 // FinalizeDeclaratorGroup adds these as separate declarations. 11076 Decl *MaybeTagDecl = Group[0]; 11077 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11078 Group = Group.slice(1); 11079 } 11080 } 11081 11082 // See if there are any new comments that are not attached to a decl. 11083 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11084 if (!Comments.empty() && 11085 !Comments.back()->isAttached()) { 11086 // There is at least one comment that not attached to a decl. 11087 // Maybe it should be attached to one of these decls? 11088 // 11089 // Note that this way we pick up not only comments that precede the 11090 // declaration, but also comments that *follow* the declaration -- thanks to 11091 // the lookahead in the lexer: we've consumed the semicolon and looked 11092 // ahead through comments. 11093 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11094 Context.getCommentForDecl(Group[i], &PP); 11095 } 11096 } 11097 11098 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11099 /// to introduce parameters into function prototype scope. 11100 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11101 const DeclSpec &DS = D.getDeclSpec(); 11102 11103 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11104 11105 // C++03 [dcl.stc]p2 also permits 'auto'. 11106 StorageClass SC = SC_None; 11107 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11108 SC = SC_Register; 11109 } else if (getLangOpts().CPlusPlus && 11110 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11111 SC = SC_Auto; 11112 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11113 Diag(DS.getStorageClassSpecLoc(), 11114 diag::err_invalid_storage_class_in_func_decl); 11115 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11116 } 11117 11118 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11119 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11120 << DeclSpec::getSpecifierName(TSCS); 11121 if (DS.isInlineSpecified()) 11122 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11123 << getLangOpts().CPlusPlus1z; 11124 if (DS.isConstexprSpecified()) 11125 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11126 << 0; 11127 if (DS.isConceptSpecified()) 11128 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11129 11130 DiagnoseFunctionSpecifiers(DS); 11131 11132 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11133 QualType parmDeclType = TInfo->getType(); 11134 11135 if (getLangOpts().CPlusPlus) { 11136 // Check that there are no default arguments inside the type of this 11137 // parameter. 11138 CheckExtraCXXDefaultArguments(D); 11139 11140 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11141 if (D.getCXXScopeSpec().isSet()) { 11142 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11143 << D.getCXXScopeSpec().getRange(); 11144 D.getCXXScopeSpec().clear(); 11145 } 11146 } 11147 11148 // Ensure we have a valid name 11149 IdentifierInfo *II = nullptr; 11150 if (D.hasName()) { 11151 II = D.getIdentifier(); 11152 if (!II) { 11153 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11154 << GetNameForDeclarator(D).getName(); 11155 D.setInvalidType(true); 11156 } 11157 } 11158 11159 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11160 if (II) { 11161 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11162 ForRedeclaration); 11163 LookupName(R, S); 11164 if (R.isSingleResult()) { 11165 NamedDecl *PrevDecl = R.getFoundDecl(); 11166 if (PrevDecl->isTemplateParameter()) { 11167 // Maybe we will complain about the shadowed template parameter. 11168 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11169 // Just pretend that we didn't see the previous declaration. 11170 PrevDecl = nullptr; 11171 } else if (S->isDeclScope(PrevDecl)) { 11172 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11173 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11174 11175 // Recover by removing the name 11176 II = nullptr; 11177 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11178 D.setInvalidType(true); 11179 } 11180 } 11181 } 11182 11183 // Temporarily put parameter variables in the translation unit, not 11184 // the enclosing context. This prevents them from accidentally 11185 // looking like class members in C++. 11186 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11187 D.getLocStart(), 11188 D.getIdentifierLoc(), II, 11189 parmDeclType, TInfo, 11190 SC); 11191 11192 if (D.isInvalidType()) 11193 New->setInvalidDecl(); 11194 11195 assert(S->isFunctionPrototypeScope()); 11196 assert(S->getFunctionPrototypeDepth() >= 1); 11197 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11198 S->getNextFunctionPrototypeIndex()); 11199 11200 // Add the parameter declaration into this scope. 11201 S->AddDecl(New); 11202 if (II) 11203 IdResolver.AddDecl(New); 11204 11205 ProcessDeclAttributes(S, New, D); 11206 11207 if (D.getDeclSpec().isModulePrivateSpecified()) 11208 Diag(New->getLocation(), diag::err_module_private_local) 11209 << 1 << New->getDeclName() 11210 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11211 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11212 11213 if (New->hasAttr<BlocksAttr>()) { 11214 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11215 } 11216 return New; 11217 } 11218 11219 /// \brief Synthesizes a variable for a parameter arising from a 11220 /// typedef. 11221 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11222 SourceLocation Loc, 11223 QualType T) { 11224 /* FIXME: setting StartLoc == Loc. 11225 Would it be worth to modify callers so as to provide proper source 11226 location for the unnamed parameters, embedding the parameter's type? */ 11227 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11228 T, Context.getTrivialTypeSourceInfo(T, Loc), 11229 SC_None, nullptr); 11230 Param->setImplicit(); 11231 return Param; 11232 } 11233 11234 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11235 // Don't diagnose unused-parameter errors in template instantiations; we 11236 // will already have done so in the template itself. 11237 if (!ActiveTemplateInstantiations.empty()) 11238 return; 11239 11240 for (const ParmVarDecl *Parameter : Parameters) { 11241 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11242 !Parameter->hasAttr<UnusedAttr>()) { 11243 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11244 << Parameter->getDeclName(); 11245 } 11246 } 11247 } 11248 11249 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11250 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11251 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11252 return; 11253 11254 // Warn if the return value is pass-by-value and larger than the specified 11255 // threshold. 11256 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11257 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11258 if (Size > LangOpts.NumLargeByValueCopy) 11259 Diag(D->getLocation(), diag::warn_return_value_size) 11260 << D->getDeclName() << Size; 11261 } 11262 11263 // Warn if any parameter is pass-by-value and larger than the specified 11264 // threshold. 11265 for (const ParmVarDecl *Parameter : Parameters) { 11266 QualType T = Parameter->getType(); 11267 if (T->isDependentType() || !T.isPODType(Context)) 11268 continue; 11269 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11270 if (Size > LangOpts.NumLargeByValueCopy) 11271 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11272 << Parameter->getDeclName() << Size; 11273 } 11274 } 11275 11276 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11277 SourceLocation NameLoc, IdentifierInfo *Name, 11278 QualType T, TypeSourceInfo *TSInfo, 11279 StorageClass SC) { 11280 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11281 if (getLangOpts().ObjCAutoRefCount && 11282 T.getObjCLifetime() == Qualifiers::OCL_None && 11283 T->isObjCLifetimeType()) { 11284 11285 Qualifiers::ObjCLifetime lifetime; 11286 11287 // Special cases for arrays: 11288 // - if it's const, use __unsafe_unretained 11289 // - otherwise, it's an error 11290 if (T->isArrayType()) { 11291 if (!T.isConstQualified()) { 11292 DelayedDiagnostics.add( 11293 sema::DelayedDiagnostic::makeForbiddenType( 11294 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11295 } 11296 lifetime = Qualifiers::OCL_ExplicitNone; 11297 } else { 11298 lifetime = T->getObjCARCImplicitLifetime(); 11299 } 11300 T = Context.getLifetimeQualifiedType(T, lifetime); 11301 } 11302 11303 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11304 Context.getAdjustedParameterType(T), 11305 TSInfo, SC, nullptr); 11306 11307 // Parameters can not be abstract class types. 11308 // For record types, this is done by the AbstractClassUsageDiagnoser once 11309 // the class has been completely parsed. 11310 if (!CurContext->isRecord() && 11311 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11312 AbstractParamType)) 11313 New->setInvalidDecl(); 11314 11315 // Parameter declarators cannot be interface types. All ObjC objects are 11316 // passed by reference. 11317 if (T->isObjCObjectType()) { 11318 SourceLocation TypeEndLoc = 11319 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11320 Diag(NameLoc, 11321 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11322 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11323 T = Context.getObjCObjectPointerType(T); 11324 New->setType(T); 11325 } 11326 11327 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11328 // duration shall not be qualified by an address-space qualifier." 11329 // Since all parameters have automatic store duration, they can not have 11330 // an address space. 11331 if (T.getAddressSpace() != 0) { 11332 // OpenCL allows function arguments declared to be an array of a type 11333 // to be qualified with an address space. 11334 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11335 Diag(NameLoc, diag::err_arg_with_address_space); 11336 New->setInvalidDecl(); 11337 } 11338 } 11339 11340 return New; 11341 } 11342 11343 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11344 SourceLocation LocAfterDecls) { 11345 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11346 11347 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11348 // for a K&R function. 11349 if (!FTI.hasPrototype) { 11350 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11351 --i; 11352 if (FTI.Params[i].Param == nullptr) { 11353 SmallString<256> Code; 11354 llvm::raw_svector_ostream(Code) 11355 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11356 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11357 << FTI.Params[i].Ident 11358 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11359 11360 // Implicitly declare the argument as type 'int' for lack of a better 11361 // type. 11362 AttributeFactory attrs; 11363 DeclSpec DS(attrs); 11364 const char* PrevSpec; // unused 11365 unsigned DiagID; // unused 11366 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11367 DiagID, Context.getPrintingPolicy()); 11368 // Use the identifier location for the type source range. 11369 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11370 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11371 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11372 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11373 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11374 } 11375 } 11376 } 11377 } 11378 11379 Decl * 11380 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11381 MultiTemplateParamsArg TemplateParameterLists, 11382 SkipBodyInfo *SkipBody) { 11383 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11384 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11385 Scope *ParentScope = FnBodyScope->getParent(); 11386 11387 D.setFunctionDefinitionKind(FDK_Definition); 11388 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11389 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11390 } 11391 11392 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11393 Consumer.HandleInlineFunctionDefinition(D); 11394 } 11395 11396 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11397 const FunctionDecl*& PossibleZeroParamPrototype) { 11398 // Don't warn about invalid declarations. 11399 if (FD->isInvalidDecl()) 11400 return false; 11401 11402 // Or declarations that aren't global. 11403 if (!FD->isGlobal()) 11404 return false; 11405 11406 // Don't warn about C++ member functions. 11407 if (isa<CXXMethodDecl>(FD)) 11408 return false; 11409 11410 // Don't warn about 'main'. 11411 if (FD->isMain()) 11412 return false; 11413 11414 // Don't warn about inline functions. 11415 if (FD->isInlined()) 11416 return false; 11417 11418 // Don't warn about function templates. 11419 if (FD->getDescribedFunctionTemplate()) 11420 return false; 11421 11422 // Don't warn about function template specializations. 11423 if (FD->isFunctionTemplateSpecialization()) 11424 return false; 11425 11426 // Don't warn for OpenCL kernels. 11427 if (FD->hasAttr<OpenCLKernelAttr>()) 11428 return false; 11429 11430 // Don't warn on explicitly deleted functions. 11431 if (FD->isDeleted()) 11432 return false; 11433 11434 bool MissingPrototype = true; 11435 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11436 Prev; Prev = Prev->getPreviousDecl()) { 11437 // Ignore any declarations that occur in function or method 11438 // scope, because they aren't visible from the header. 11439 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11440 continue; 11441 11442 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11443 if (FD->getNumParams() == 0) 11444 PossibleZeroParamPrototype = Prev; 11445 break; 11446 } 11447 11448 return MissingPrototype; 11449 } 11450 11451 void 11452 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11453 const FunctionDecl *EffectiveDefinition, 11454 SkipBodyInfo *SkipBody) { 11455 // Don't complain if we're in GNU89 mode and the previous definition 11456 // was an extern inline function. 11457 const FunctionDecl *Definition = EffectiveDefinition; 11458 if (!Definition) 11459 if (!FD->isDefined(Definition)) 11460 return; 11461 11462 if (canRedefineFunction(Definition, getLangOpts())) 11463 return; 11464 11465 // If we don't have a visible definition of the function, and it's inline or 11466 // a template, skip the new definition. 11467 if (SkipBody && !hasVisibleDefinition(Definition) && 11468 (Definition->getFormalLinkage() == InternalLinkage || 11469 Definition->isInlined() || 11470 Definition->getDescribedFunctionTemplate() || 11471 Definition->getNumTemplateParameterLists())) { 11472 SkipBody->ShouldSkip = true; 11473 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11474 makeMergedDefinitionVisible(TD, FD->getLocation()); 11475 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11476 FD->getLocation()); 11477 return; 11478 } 11479 11480 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11481 Definition->getStorageClass() == SC_Extern) 11482 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11483 << FD->getDeclName() << getLangOpts().CPlusPlus; 11484 else 11485 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11486 11487 Diag(Definition->getLocation(), diag::note_previous_definition); 11488 FD->setInvalidDecl(); 11489 } 11490 11491 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11492 Sema &S) { 11493 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11494 11495 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11496 LSI->CallOperator = CallOperator; 11497 LSI->Lambda = LambdaClass; 11498 LSI->ReturnType = CallOperator->getReturnType(); 11499 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11500 11501 if (LCD == LCD_None) 11502 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11503 else if (LCD == LCD_ByCopy) 11504 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11505 else if (LCD == LCD_ByRef) 11506 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11507 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11508 11509 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11510 LSI->Mutable = !CallOperator->isConst(); 11511 11512 // Add the captures to the LSI so they can be noted as already 11513 // captured within tryCaptureVar. 11514 auto I = LambdaClass->field_begin(); 11515 for (const auto &C : LambdaClass->captures()) { 11516 if (C.capturesVariable()) { 11517 VarDecl *VD = C.getCapturedVar(); 11518 if (VD->isInitCapture()) 11519 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11520 QualType CaptureType = VD->getType(); 11521 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11522 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11523 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11524 /*EllipsisLoc*/C.isPackExpansion() 11525 ? C.getEllipsisLoc() : SourceLocation(), 11526 CaptureType, /*Expr*/ nullptr); 11527 11528 } else if (C.capturesThis()) { 11529 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11530 /*Expr*/ nullptr, 11531 C.getCaptureKind() == LCK_StarThis); 11532 } else { 11533 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11534 } 11535 ++I; 11536 } 11537 } 11538 11539 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11540 SkipBodyInfo *SkipBody) { 11541 // Clear the last template instantiation error context. 11542 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11543 11544 if (!D) 11545 return D; 11546 FunctionDecl *FD = nullptr; 11547 11548 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11549 FD = FunTmpl->getTemplatedDecl(); 11550 else 11551 FD = cast<FunctionDecl>(D); 11552 11553 // See if this is a redefinition. 11554 if (!FD->isLateTemplateParsed()) { 11555 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11556 11557 // If we're skipping the body, we're done. Don't enter the scope. 11558 if (SkipBody && SkipBody->ShouldSkip) 11559 return D; 11560 } 11561 11562 // Mark this function as "will have a body eventually". This lets users to 11563 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11564 // this function. 11565 FD->setWillHaveBody(); 11566 11567 // If we are instantiating a generic lambda call operator, push 11568 // a LambdaScopeInfo onto the function stack. But use the information 11569 // that's already been calculated (ActOnLambdaExpr) to prime the current 11570 // LambdaScopeInfo. 11571 // When the template operator is being specialized, the LambdaScopeInfo, 11572 // has to be properly restored so that tryCaptureVariable doesn't try 11573 // and capture any new variables. In addition when calculating potential 11574 // captures during transformation of nested lambdas, it is necessary to 11575 // have the LSI properly restored. 11576 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11577 assert(ActiveTemplateInstantiations.size() && 11578 "There should be an active template instantiation on the stack " 11579 "when instantiating a generic lambda!"); 11580 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11581 } 11582 else 11583 // Enter a new function scope 11584 PushFunctionScope(); 11585 11586 // Builtin functions cannot be defined. 11587 if (unsigned BuiltinID = FD->getBuiltinID()) { 11588 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11589 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11590 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11591 FD->setInvalidDecl(); 11592 } 11593 } 11594 11595 // The return type of a function definition must be complete 11596 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11597 QualType ResultType = FD->getReturnType(); 11598 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11599 !FD->isInvalidDecl() && 11600 RequireCompleteType(FD->getLocation(), ResultType, 11601 diag::err_func_def_incomplete_result)) 11602 FD->setInvalidDecl(); 11603 11604 if (FnBodyScope) 11605 PushDeclContext(FnBodyScope, FD); 11606 11607 // Check the validity of our function parameters 11608 CheckParmsForFunctionDef(FD->parameters(), 11609 /*CheckParameterNames=*/true); 11610 11611 // Introduce our parameters into the function scope 11612 for (auto Param : FD->parameters()) { 11613 Param->setOwningFunction(FD); 11614 11615 // If this has an identifier, add it to the scope stack. 11616 if (Param->getIdentifier() && FnBodyScope) { 11617 CheckShadow(FnBodyScope, Param); 11618 11619 PushOnScopeChains(Param, FnBodyScope); 11620 } 11621 } 11622 11623 // If we had any tags defined in the function prototype, 11624 // introduce them into the function scope. 11625 if (FnBodyScope) { 11626 for (ArrayRef<NamedDecl *>::iterator 11627 I = FD->getDeclsInPrototypeScope().begin(), 11628 E = FD->getDeclsInPrototypeScope().end(); 11629 I != E; ++I) { 11630 NamedDecl *D = *I; 11631 11632 // Some of these decls (like enums) may have been pinned to the 11633 // translation unit for lack of a real context earlier. If so, remove 11634 // from the translation unit and reattach to the current context. 11635 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11636 // Is the decl actually in the context? 11637 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11638 Context.getTranslationUnitDecl()->removeDecl(D); 11639 // Either way, reassign the lexical decl context to our FunctionDecl. 11640 D->setLexicalDeclContext(CurContext); 11641 } 11642 11643 // If the decl has a non-null name, make accessible in the current scope. 11644 if (!D->getName().empty()) 11645 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11646 11647 // Similarly, dive into enums and fish their constants out, making them 11648 // accessible in this scope. 11649 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11650 for (auto *EI : ED->enumerators()) 11651 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11652 } 11653 } 11654 } 11655 11656 // Ensure that the function's exception specification is instantiated. 11657 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11658 ResolveExceptionSpec(D->getLocation(), FPT); 11659 11660 // dllimport cannot be applied to non-inline function definitions. 11661 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11662 !FD->isTemplateInstantiation()) { 11663 assert(!FD->hasAttr<DLLExportAttr>()); 11664 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11665 FD->setInvalidDecl(); 11666 return D; 11667 } 11668 // We want to attach documentation to original Decl (which might be 11669 // a function template). 11670 ActOnDocumentableDecl(D); 11671 if (getCurLexicalContext()->isObjCContainer() && 11672 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11673 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11674 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11675 11676 return D; 11677 } 11678 11679 /// \brief Given the set of return statements within a function body, 11680 /// compute the variables that are subject to the named return value 11681 /// optimization. 11682 /// 11683 /// Each of the variables that is subject to the named return value 11684 /// optimization will be marked as NRVO variables in the AST, and any 11685 /// return statement that has a marked NRVO variable as its NRVO candidate can 11686 /// use the named return value optimization. 11687 /// 11688 /// This function applies a very simplistic algorithm for NRVO: if every return 11689 /// statement in the scope of a variable has the same NRVO candidate, that 11690 /// candidate is an NRVO variable. 11691 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11692 ReturnStmt **Returns = Scope->Returns.data(); 11693 11694 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11695 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11696 if (!NRVOCandidate->isNRVOVariable()) 11697 Returns[I]->setNRVOCandidate(nullptr); 11698 } 11699 } 11700 } 11701 11702 bool Sema::canDelayFunctionBody(const Declarator &D) { 11703 // We can't delay parsing the body of a constexpr function template (yet). 11704 if (D.getDeclSpec().isConstexprSpecified()) 11705 return false; 11706 11707 // We can't delay parsing the body of a function template with a deduced 11708 // return type (yet). 11709 if (D.getDeclSpec().containsPlaceholderType()) { 11710 // If the placeholder introduces a non-deduced trailing return type, 11711 // we can still delay parsing it. 11712 if (D.getNumTypeObjects()) { 11713 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11714 if (Outer.Kind == DeclaratorChunk::Function && 11715 Outer.Fun.hasTrailingReturnType()) { 11716 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11717 return Ty.isNull() || !Ty->isUndeducedType(); 11718 } 11719 } 11720 return false; 11721 } 11722 11723 return true; 11724 } 11725 11726 bool Sema::canSkipFunctionBody(Decl *D) { 11727 // We cannot skip the body of a function (or function template) which is 11728 // constexpr, since we may need to evaluate its body in order to parse the 11729 // rest of the file. 11730 // We cannot skip the body of a function with an undeduced return type, 11731 // because any callers of that function need to know the type. 11732 if (const FunctionDecl *FD = D->getAsFunction()) 11733 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11734 return false; 11735 return Consumer.shouldSkipFunctionBody(D); 11736 } 11737 11738 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11739 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11740 FD->setHasSkippedBody(); 11741 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11742 MD->setHasSkippedBody(); 11743 return Decl; 11744 } 11745 11746 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11747 return ActOnFinishFunctionBody(D, BodyArg, false); 11748 } 11749 11750 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11751 bool IsInstantiation) { 11752 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11753 11754 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11755 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11756 11757 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11758 CheckCompletedCoroutineBody(FD, Body); 11759 11760 if (FD) { 11761 FD->setBody(Body); 11762 11763 if (getLangOpts().CPlusPlus14) { 11764 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11765 FD->getReturnType()->isUndeducedType()) { 11766 // If the function has a deduced result type but contains no 'return' 11767 // statements, the result type as written must be exactly 'auto', and 11768 // the deduced result type is 'void'. 11769 if (!FD->getReturnType()->getAs<AutoType>()) { 11770 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11771 << FD->getReturnType(); 11772 FD->setInvalidDecl(); 11773 } else { 11774 // Substitute 'void' for the 'auto' in the type. 11775 TypeLoc ResultType = getReturnTypeLoc(FD); 11776 Context.adjustDeducedFunctionResultType( 11777 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11778 } 11779 } 11780 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11781 // In C++11, we don't use 'auto' deduction rules for lambda call 11782 // operators because we don't support return type deduction. 11783 auto *LSI = getCurLambda(); 11784 if (LSI->HasImplicitReturnType) { 11785 deduceClosureReturnType(*LSI); 11786 11787 // C++11 [expr.prim.lambda]p4: 11788 // [...] if there are no return statements in the compound-statement 11789 // [the deduced type is] the type void 11790 QualType RetType = 11791 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11792 11793 // Update the return type to the deduced type. 11794 const FunctionProtoType *Proto = 11795 FD->getType()->getAs<FunctionProtoType>(); 11796 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11797 Proto->getExtProtoInfo())); 11798 } 11799 } 11800 11801 // The only way to be included in UndefinedButUsed is if there is an 11802 // ODR use before the definition. Avoid the expensive map lookup if this 11803 // is the first declaration. 11804 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11805 if (!FD->isExternallyVisible()) 11806 UndefinedButUsed.erase(FD); 11807 else if (FD->isInlined() && 11808 !LangOpts.GNUInline && 11809 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11810 UndefinedButUsed.erase(FD); 11811 } 11812 11813 // If the function implicitly returns zero (like 'main') or is naked, 11814 // don't complain about missing return statements. 11815 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11816 WP.disableCheckFallThrough(); 11817 11818 // MSVC permits the use of pure specifier (=0) on function definition, 11819 // defined at class scope, warn about this non-standard construct. 11820 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11821 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11822 11823 if (!FD->isInvalidDecl()) { 11824 // Don't diagnose unused parameters of defaulted or deleted functions. 11825 if (!FD->isDeleted() && !FD->isDefaulted()) 11826 DiagnoseUnusedParameters(FD->parameters()); 11827 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11828 FD->getReturnType(), FD); 11829 11830 // If this is a structor, we need a vtable. 11831 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11832 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11833 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11834 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11835 11836 // Try to apply the named return value optimization. We have to check 11837 // if we can do this here because lambdas keep return statements around 11838 // to deduce an implicit return type. 11839 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11840 !FD->isDependentContext()) 11841 computeNRVO(Body, getCurFunction()); 11842 } 11843 11844 // GNU warning -Wmissing-prototypes: 11845 // Warn if a global function is defined without a previous 11846 // prototype declaration. This warning is issued even if the 11847 // definition itself provides a prototype. The aim is to detect 11848 // global functions that fail to be declared in header files. 11849 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11850 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11851 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11852 11853 if (PossibleZeroParamPrototype) { 11854 // We found a declaration that is not a prototype, 11855 // but that could be a zero-parameter prototype 11856 if (TypeSourceInfo *TI = 11857 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11858 TypeLoc TL = TI->getTypeLoc(); 11859 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11860 Diag(PossibleZeroParamPrototype->getLocation(), 11861 diag::note_declaration_not_a_prototype) 11862 << PossibleZeroParamPrototype 11863 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11864 } 11865 } 11866 } 11867 11868 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11869 const CXXMethodDecl *KeyFunction; 11870 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11871 MD->isVirtual() && 11872 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11873 MD == KeyFunction->getCanonicalDecl()) { 11874 // Update the key-function state if necessary for this ABI. 11875 if (FD->isInlined() && 11876 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11877 Context.setNonKeyFunction(MD); 11878 11879 // If the newly-chosen key function is already defined, then we 11880 // need to mark the vtable as used retroactively. 11881 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11882 const FunctionDecl *Definition; 11883 if (KeyFunction && KeyFunction->isDefined(Definition)) 11884 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11885 } else { 11886 // We just defined they key function; mark the vtable as used. 11887 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11888 } 11889 } 11890 } 11891 11892 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11893 "Function parsing confused"); 11894 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11895 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11896 MD->setBody(Body); 11897 if (!MD->isInvalidDecl()) { 11898 DiagnoseUnusedParameters(MD->parameters()); 11899 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 11900 MD->getReturnType(), MD); 11901 11902 if (Body) 11903 computeNRVO(Body, getCurFunction()); 11904 } 11905 if (getCurFunction()->ObjCShouldCallSuper) { 11906 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11907 << MD->getSelector().getAsString(); 11908 getCurFunction()->ObjCShouldCallSuper = false; 11909 } 11910 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11911 const ObjCMethodDecl *InitMethod = nullptr; 11912 bool isDesignated = 11913 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11914 assert(isDesignated && InitMethod); 11915 (void)isDesignated; 11916 11917 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11918 auto IFace = MD->getClassInterface(); 11919 if (!IFace) 11920 return false; 11921 auto SuperD = IFace->getSuperClass(); 11922 if (!SuperD) 11923 return false; 11924 return SuperD->getIdentifier() == 11925 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11926 }; 11927 // Don't issue this warning for unavailable inits or direct subclasses 11928 // of NSObject. 11929 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11930 Diag(MD->getLocation(), 11931 diag::warn_objc_designated_init_missing_super_call); 11932 Diag(InitMethod->getLocation(), 11933 diag::note_objc_designated_init_marked_here); 11934 } 11935 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11936 } 11937 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11938 // Don't issue this warning for unavaialable inits. 11939 if (!MD->isUnavailable()) 11940 Diag(MD->getLocation(), 11941 diag::warn_objc_secondary_init_missing_init_call); 11942 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11943 } 11944 } else { 11945 return nullptr; 11946 } 11947 11948 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 11949 DiagnoseUnguardedAvailabilityViolations(dcl); 11950 11951 assert(!getCurFunction()->ObjCShouldCallSuper && 11952 "This should only be set for ObjC methods, which should have been " 11953 "handled in the block above."); 11954 11955 // Verify and clean out per-function state. 11956 if (Body && (!FD || !FD->isDefaulted())) { 11957 // C++ constructors that have function-try-blocks can't have return 11958 // statements in the handlers of that block. (C++ [except.handle]p14) 11959 // Verify this. 11960 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11961 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11962 11963 // Verify that gotos and switch cases don't jump into scopes illegally. 11964 if (getCurFunction()->NeedsScopeChecking() && 11965 !PP.isCodeCompletionEnabled()) 11966 DiagnoseInvalidJumps(Body); 11967 11968 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11969 if (!Destructor->getParent()->isDependentType()) 11970 CheckDestructor(Destructor); 11971 11972 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11973 Destructor->getParent()); 11974 } 11975 11976 // If any errors have occurred, clear out any temporaries that may have 11977 // been leftover. This ensures that these temporaries won't be picked up for 11978 // deletion in some later function. 11979 if (getDiagnostics().hasErrorOccurred() || 11980 getDiagnostics().getSuppressAllDiagnostics()) { 11981 DiscardCleanupsInEvaluationContext(); 11982 } 11983 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11984 !isa<FunctionTemplateDecl>(dcl)) { 11985 // Since the body is valid, issue any analysis-based warnings that are 11986 // enabled. 11987 ActivePolicy = &WP; 11988 } 11989 11990 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11991 (!CheckConstexprFunctionDecl(FD) || 11992 !CheckConstexprFunctionBody(FD, Body))) 11993 FD->setInvalidDecl(); 11994 11995 if (FD && FD->hasAttr<NakedAttr>()) { 11996 for (const Stmt *S : Body->children()) { 11997 // Allow local register variables without initializer as they don't 11998 // require prologue. 11999 bool RegisterVariables = false; 12000 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12001 for (const auto *Decl : DS->decls()) { 12002 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12003 RegisterVariables = 12004 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12005 if (!RegisterVariables) 12006 break; 12007 } 12008 } 12009 } 12010 if (RegisterVariables) 12011 continue; 12012 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12013 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12014 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12015 FD->setInvalidDecl(); 12016 break; 12017 } 12018 } 12019 } 12020 12021 assert(ExprCleanupObjects.size() == 12022 ExprEvalContexts.back().NumCleanupObjects && 12023 "Leftover temporaries in function"); 12024 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12025 assert(MaybeODRUseExprs.empty() && 12026 "Leftover expressions for odr-use checking"); 12027 } 12028 12029 if (!IsInstantiation) 12030 PopDeclContext(); 12031 12032 PopFunctionScopeInfo(ActivePolicy, dcl); 12033 // If any errors have occurred, clear out any temporaries that may have 12034 // been leftover. This ensures that these temporaries won't be picked up for 12035 // deletion in some later function. 12036 if (getDiagnostics().hasErrorOccurred()) { 12037 DiscardCleanupsInEvaluationContext(); 12038 } 12039 12040 return dcl; 12041 } 12042 12043 /// When we finish delayed parsing of an attribute, we must attach it to the 12044 /// relevant Decl. 12045 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12046 ParsedAttributes &Attrs) { 12047 // Always attach attributes to the underlying decl. 12048 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12049 D = TD->getTemplatedDecl(); 12050 ProcessDeclAttributeList(S, D, Attrs.getList()); 12051 12052 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12053 if (Method->isStatic()) 12054 checkThisInStaticMemberFunctionAttributes(Method); 12055 } 12056 12057 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12058 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12059 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12060 IdentifierInfo &II, Scope *S) { 12061 // Before we produce a declaration for an implicitly defined 12062 // function, see whether there was a locally-scoped declaration of 12063 // this name as a function or variable. If so, use that 12064 // (non-visible) declaration, and complain about it. 12065 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12066 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12067 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12068 return ExternCPrev; 12069 } 12070 12071 // Extension in C99. Legal in C90, but warn about it. 12072 unsigned diag_id; 12073 if (II.getName().startswith("__builtin_")) 12074 diag_id = diag::warn_builtin_unknown; 12075 else if (getLangOpts().C99) 12076 diag_id = diag::ext_implicit_function_decl; 12077 else 12078 diag_id = diag::warn_implicit_function_decl; 12079 Diag(Loc, diag_id) << &II; 12080 12081 // Because typo correction is expensive, only do it if the implicit 12082 // function declaration is going to be treated as an error. 12083 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12084 TypoCorrection Corrected; 12085 if (S && 12086 (Corrected = CorrectTypo( 12087 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12088 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12089 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12090 /*ErrorRecovery*/false); 12091 } 12092 12093 // Set a Declarator for the implicit definition: int foo(); 12094 const char *Dummy; 12095 AttributeFactory attrFactory; 12096 DeclSpec DS(attrFactory); 12097 unsigned DiagID; 12098 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12099 Context.getPrintingPolicy()); 12100 (void)Error; // Silence warning. 12101 assert(!Error && "Error setting up implicit decl!"); 12102 SourceLocation NoLoc; 12103 Declarator D(DS, Declarator::BlockContext); 12104 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12105 /*IsAmbiguous=*/false, 12106 /*LParenLoc=*/NoLoc, 12107 /*Params=*/nullptr, 12108 /*NumParams=*/0, 12109 /*EllipsisLoc=*/NoLoc, 12110 /*RParenLoc=*/NoLoc, 12111 /*TypeQuals=*/0, 12112 /*RefQualifierIsLvalueRef=*/true, 12113 /*RefQualifierLoc=*/NoLoc, 12114 /*ConstQualifierLoc=*/NoLoc, 12115 /*VolatileQualifierLoc=*/NoLoc, 12116 /*RestrictQualifierLoc=*/NoLoc, 12117 /*MutableLoc=*/NoLoc, 12118 EST_None, 12119 /*ESpecRange=*/SourceRange(), 12120 /*Exceptions=*/nullptr, 12121 /*ExceptionRanges=*/nullptr, 12122 /*NumExceptions=*/0, 12123 /*NoexceptExpr=*/nullptr, 12124 /*ExceptionSpecTokens=*/nullptr, 12125 Loc, Loc, D), 12126 DS.getAttributes(), 12127 SourceLocation()); 12128 D.SetIdentifier(&II, Loc); 12129 12130 // Insert this function into translation-unit scope. 12131 12132 DeclContext *PrevDC = CurContext; 12133 CurContext = Context.getTranslationUnitDecl(); 12134 12135 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12136 FD->setImplicit(); 12137 12138 CurContext = PrevDC; 12139 12140 AddKnownFunctionAttributes(FD); 12141 12142 return FD; 12143 } 12144 12145 /// \brief Adds any function attributes that we know a priori based on 12146 /// the declaration of this function. 12147 /// 12148 /// These attributes can apply both to implicitly-declared builtins 12149 /// (like __builtin___printf_chk) or to library-declared functions 12150 /// like NSLog or printf. 12151 /// 12152 /// We need to check for duplicate attributes both here and where user-written 12153 /// attributes are applied to declarations. 12154 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12155 if (FD->isInvalidDecl()) 12156 return; 12157 12158 // If this is a built-in function, map its builtin attributes to 12159 // actual attributes. 12160 if (unsigned BuiltinID = FD->getBuiltinID()) { 12161 // Handle printf-formatting attributes. 12162 unsigned FormatIdx; 12163 bool HasVAListArg; 12164 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12165 if (!FD->hasAttr<FormatAttr>()) { 12166 const char *fmt = "printf"; 12167 unsigned int NumParams = FD->getNumParams(); 12168 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12169 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12170 fmt = "NSString"; 12171 FD->addAttr(FormatAttr::CreateImplicit(Context, 12172 &Context.Idents.get(fmt), 12173 FormatIdx+1, 12174 HasVAListArg ? 0 : FormatIdx+2, 12175 FD->getLocation())); 12176 } 12177 } 12178 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12179 HasVAListArg)) { 12180 if (!FD->hasAttr<FormatAttr>()) 12181 FD->addAttr(FormatAttr::CreateImplicit(Context, 12182 &Context.Idents.get("scanf"), 12183 FormatIdx+1, 12184 HasVAListArg ? 0 : FormatIdx+2, 12185 FD->getLocation())); 12186 } 12187 12188 // Mark const if we don't care about errno and that is the only 12189 // thing preventing the function from being const. This allows 12190 // IRgen to use LLVM intrinsics for such functions. 12191 if (!getLangOpts().MathErrno && 12192 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12193 if (!FD->hasAttr<ConstAttr>()) 12194 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12195 } 12196 12197 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12198 !FD->hasAttr<ReturnsTwiceAttr>()) 12199 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12200 FD->getLocation())); 12201 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12202 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12203 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12204 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12205 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12206 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12207 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12208 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12209 // Add the appropriate attribute, depending on the CUDA compilation mode 12210 // and which target the builtin belongs to. For example, during host 12211 // compilation, aux builtins are __device__, while the rest are __host__. 12212 if (getLangOpts().CUDAIsDevice != 12213 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12214 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12215 else 12216 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12217 } 12218 } 12219 12220 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12221 // throw, add an implicit nothrow attribute to any extern "C" function we come 12222 // across. 12223 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12224 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12225 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12226 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12227 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12228 } 12229 12230 IdentifierInfo *Name = FD->getIdentifier(); 12231 if (!Name) 12232 return; 12233 if ((!getLangOpts().CPlusPlus && 12234 FD->getDeclContext()->isTranslationUnit()) || 12235 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12236 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12237 LinkageSpecDecl::lang_c)) { 12238 // Okay: this could be a libc/libm/Objective-C function we know 12239 // about. 12240 } else 12241 return; 12242 12243 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12244 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12245 // target-specific builtins, perhaps? 12246 if (!FD->hasAttr<FormatAttr>()) 12247 FD->addAttr(FormatAttr::CreateImplicit(Context, 12248 &Context.Idents.get("printf"), 2, 12249 Name->isStr("vasprintf") ? 0 : 3, 12250 FD->getLocation())); 12251 } 12252 12253 if (Name->isStr("__CFStringMakeConstantString")) { 12254 // We already have a __builtin___CFStringMakeConstantString, 12255 // but builds that use -fno-constant-cfstrings don't go through that. 12256 if (!FD->hasAttr<FormatArgAttr>()) 12257 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12258 FD->getLocation())); 12259 } 12260 } 12261 12262 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12263 TypeSourceInfo *TInfo) { 12264 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12265 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12266 12267 if (!TInfo) { 12268 assert(D.isInvalidType() && "no declarator info for valid type"); 12269 TInfo = Context.getTrivialTypeSourceInfo(T); 12270 } 12271 12272 // Scope manipulation handled by caller. 12273 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12274 D.getLocStart(), 12275 D.getIdentifierLoc(), 12276 D.getIdentifier(), 12277 TInfo); 12278 12279 // Bail out immediately if we have an invalid declaration. 12280 if (D.isInvalidType()) { 12281 NewTD->setInvalidDecl(); 12282 return NewTD; 12283 } 12284 12285 if (D.getDeclSpec().isModulePrivateSpecified()) { 12286 if (CurContext->isFunctionOrMethod()) 12287 Diag(NewTD->getLocation(), diag::err_module_private_local) 12288 << 2 << NewTD->getDeclName() 12289 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12290 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12291 else 12292 NewTD->setModulePrivate(); 12293 } 12294 12295 // C++ [dcl.typedef]p8: 12296 // If the typedef declaration defines an unnamed class (or 12297 // enum), the first typedef-name declared by the declaration 12298 // to be that class type (or enum type) is used to denote the 12299 // class type (or enum type) for linkage purposes only. 12300 // We need to check whether the type was declared in the declaration. 12301 switch (D.getDeclSpec().getTypeSpecType()) { 12302 case TST_enum: 12303 case TST_struct: 12304 case TST_interface: 12305 case TST_union: 12306 case TST_class: { 12307 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12308 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12309 break; 12310 } 12311 12312 default: 12313 break; 12314 } 12315 12316 return NewTD; 12317 } 12318 12319 /// \brief Check that this is a valid underlying type for an enum declaration. 12320 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12321 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12322 QualType T = TI->getType(); 12323 12324 if (T->isDependentType()) 12325 return false; 12326 12327 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12328 if (BT->isInteger()) 12329 return false; 12330 12331 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12332 return true; 12333 } 12334 12335 /// Check whether this is a valid redeclaration of a previous enumeration. 12336 /// \return true if the redeclaration was invalid. 12337 bool Sema::CheckEnumRedeclaration( 12338 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12339 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12340 bool IsFixed = !EnumUnderlyingTy.isNull(); 12341 12342 if (IsScoped != Prev->isScoped()) { 12343 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12344 << Prev->isScoped(); 12345 Diag(Prev->getLocation(), diag::note_previous_declaration); 12346 return true; 12347 } 12348 12349 if (IsFixed && Prev->isFixed()) { 12350 if (!EnumUnderlyingTy->isDependentType() && 12351 !Prev->getIntegerType()->isDependentType() && 12352 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12353 Prev->getIntegerType())) { 12354 // TODO: Highlight the underlying type of the redeclaration. 12355 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12356 << EnumUnderlyingTy << Prev->getIntegerType(); 12357 Diag(Prev->getLocation(), diag::note_previous_declaration) 12358 << Prev->getIntegerTypeRange(); 12359 return true; 12360 } 12361 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12362 ; 12363 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12364 ; 12365 } else if (IsFixed != Prev->isFixed()) { 12366 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12367 << Prev->isFixed(); 12368 Diag(Prev->getLocation(), diag::note_previous_declaration); 12369 return true; 12370 } 12371 12372 return false; 12373 } 12374 12375 /// \brief Get diagnostic %select index for tag kind for 12376 /// redeclaration diagnostic message. 12377 /// WARNING: Indexes apply to particular diagnostics only! 12378 /// 12379 /// \returns diagnostic %select index. 12380 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12381 switch (Tag) { 12382 case TTK_Struct: return 0; 12383 case TTK_Interface: return 1; 12384 case TTK_Class: return 2; 12385 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12386 } 12387 } 12388 12389 /// \brief Determine if tag kind is a class-key compatible with 12390 /// class for redeclaration (class, struct, or __interface). 12391 /// 12392 /// \returns true iff the tag kind is compatible. 12393 static bool isClassCompatTagKind(TagTypeKind Tag) 12394 { 12395 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12396 } 12397 12398 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) { 12399 if (isa<TypedefDecl>(PrevDecl)) 12400 return NTK_Typedef; 12401 else if (isa<TypeAliasDecl>(PrevDecl)) 12402 return NTK_TypeAlias; 12403 else if (isa<ClassTemplateDecl>(PrevDecl)) 12404 return NTK_Template; 12405 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12406 return NTK_TypeAliasTemplate; 12407 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12408 return NTK_TemplateTemplateArgument; 12409 return NTK_Unknown; 12410 } 12411 12412 /// \brief Determine whether a tag with a given kind is acceptable 12413 /// as a redeclaration of the given tag declaration. 12414 /// 12415 /// \returns true if the new tag kind is acceptable, false otherwise. 12416 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12417 TagTypeKind NewTag, bool isDefinition, 12418 SourceLocation NewTagLoc, 12419 const IdentifierInfo *Name) { 12420 // C++ [dcl.type.elab]p3: 12421 // The class-key or enum keyword present in the 12422 // elaborated-type-specifier shall agree in kind with the 12423 // declaration to which the name in the elaborated-type-specifier 12424 // refers. This rule also applies to the form of 12425 // elaborated-type-specifier that declares a class-name or 12426 // friend class since it can be construed as referring to the 12427 // definition of the class. Thus, in any 12428 // elaborated-type-specifier, the enum keyword shall be used to 12429 // refer to an enumeration (7.2), the union class-key shall be 12430 // used to refer to a union (clause 9), and either the class or 12431 // struct class-key shall be used to refer to a class (clause 9) 12432 // declared using the class or struct class-key. 12433 TagTypeKind OldTag = Previous->getTagKind(); 12434 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12435 if (OldTag == NewTag) 12436 return true; 12437 12438 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12439 // Warn about the struct/class tag mismatch. 12440 bool isTemplate = false; 12441 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12442 isTemplate = Record->getDescribedClassTemplate(); 12443 12444 if (!ActiveTemplateInstantiations.empty()) { 12445 // In a template instantiation, do not offer fix-its for tag mismatches 12446 // since they usually mess up the template instead of fixing the problem. 12447 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12448 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12449 << getRedeclDiagFromTagKind(OldTag); 12450 return true; 12451 } 12452 12453 if (isDefinition) { 12454 // On definitions, check previous tags and issue a fix-it for each 12455 // one that doesn't match the current tag. 12456 if (Previous->getDefinition()) { 12457 // Don't suggest fix-its for redefinitions. 12458 return true; 12459 } 12460 12461 bool previousMismatch = false; 12462 for (auto I : Previous->redecls()) { 12463 if (I->getTagKind() != NewTag) { 12464 if (!previousMismatch) { 12465 previousMismatch = true; 12466 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12467 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12468 << getRedeclDiagFromTagKind(I->getTagKind()); 12469 } 12470 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12471 << getRedeclDiagFromTagKind(NewTag) 12472 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12473 TypeWithKeyword::getTagTypeKindName(NewTag)); 12474 } 12475 } 12476 return true; 12477 } 12478 12479 // Check for a previous definition. If current tag and definition 12480 // are same type, do nothing. If no definition, but disagree with 12481 // with previous tag type, give a warning, but no fix-it. 12482 const TagDecl *Redecl = Previous->getDefinition() ? 12483 Previous->getDefinition() : Previous; 12484 if (Redecl->getTagKind() == NewTag) { 12485 return true; 12486 } 12487 12488 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12489 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12490 << getRedeclDiagFromTagKind(OldTag); 12491 Diag(Redecl->getLocation(), diag::note_previous_use); 12492 12493 // If there is a previous definition, suggest a fix-it. 12494 if (Previous->getDefinition()) { 12495 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12496 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12497 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12498 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12499 } 12500 12501 return true; 12502 } 12503 return false; 12504 } 12505 12506 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12507 /// from an outer enclosing namespace or file scope inside a friend declaration. 12508 /// This should provide the commented out code in the following snippet: 12509 /// namespace N { 12510 /// struct X; 12511 /// namespace M { 12512 /// struct Y { friend struct /*N::*/ X; }; 12513 /// } 12514 /// } 12515 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12516 SourceLocation NameLoc) { 12517 // While the decl is in a namespace, do repeated lookup of that name and see 12518 // if we get the same namespace back. If we do not, continue until 12519 // translation unit scope, at which point we have a fully qualified NNS. 12520 SmallVector<IdentifierInfo *, 4> Namespaces; 12521 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12522 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12523 // This tag should be declared in a namespace, which can only be enclosed by 12524 // other namespaces. Bail if there's an anonymous namespace in the chain. 12525 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12526 if (!Namespace || Namespace->isAnonymousNamespace()) 12527 return FixItHint(); 12528 IdentifierInfo *II = Namespace->getIdentifier(); 12529 Namespaces.push_back(II); 12530 NamedDecl *Lookup = SemaRef.LookupSingleName( 12531 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12532 if (Lookup == Namespace) 12533 break; 12534 } 12535 12536 // Once we have all the namespaces, reverse them to go outermost first, and 12537 // build an NNS. 12538 SmallString<64> Insertion; 12539 llvm::raw_svector_ostream OS(Insertion); 12540 if (DC->isTranslationUnit()) 12541 OS << "::"; 12542 std::reverse(Namespaces.begin(), Namespaces.end()); 12543 for (auto *II : Namespaces) 12544 OS << II->getName() << "::"; 12545 return FixItHint::CreateInsertion(NameLoc, Insertion); 12546 } 12547 12548 /// \brief Determine whether a tag originally declared in context \p OldDC can 12549 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12550 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12551 /// using-declaration). 12552 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12553 DeclContext *NewDC) { 12554 OldDC = OldDC->getRedeclContext(); 12555 NewDC = NewDC->getRedeclContext(); 12556 12557 if (OldDC->Equals(NewDC)) 12558 return true; 12559 12560 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12561 // encloses the other). 12562 if (S.getLangOpts().MSVCCompat && 12563 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12564 return true; 12565 12566 return false; 12567 } 12568 12569 /// Find the DeclContext in which a tag is implicitly declared if we see an 12570 /// elaborated type specifier in the specified context, and lookup finds 12571 /// nothing. 12572 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12573 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12574 DC = DC->getParent(); 12575 return DC; 12576 } 12577 12578 /// Find the Scope in which a tag is implicitly declared if we see an 12579 /// elaborated type specifier in the specified context, and lookup finds 12580 /// nothing. 12581 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12582 while (S->isClassScope() || 12583 (LangOpts.CPlusPlus && 12584 S->isFunctionPrototypeScope()) || 12585 ((S->getFlags() & Scope::DeclScope) == 0) || 12586 (S->getEntity() && S->getEntity()->isTransparentContext())) 12587 S = S->getParent(); 12588 return S; 12589 } 12590 12591 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12592 /// former case, Name will be non-null. In the later case, Name will be null. 12593 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12594 /// reference/declaration/definition of a tag. 12595 /// 12596 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12597 /// trailing-type-specifier) other than one in an alias-declaration. 12598 /// 12599 /// \param SkipBody If non-null, will be set to indicate if the caller should 12600 /// skip the definition of this tag and treat it as if it were a declaration. 12601 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12602 SourceLocation KWLoc, CXXScopeSpec &SS, 12603 IdentifierInfo *Name, SourceLocation NameLoc, 12604 AttributeList *Attr, AccessSpecifier AS, 12605 SourceLocation ModulePrivateLoc, 12606 MultiTemplateParamsArg TemplateParameterLists, 12607 bool &OwnedDecl, bool &IsDependent, 12608 SourceLocation ScopedEnumKWLoc, 12609 bool ScopedEnumUsesClassTag, 12610 TypeResult UnderlyingType, 12611 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12612 // If this is not a definition, it must have a name. 12613 IdentifierInfo *OrigName = Name; 12614 assert((Name != nullptr || TUK == TUK_Definition) && 12615 "Nameless record must be a definition!"); 12616 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12617 12618 OwnedDecl = false; 12619 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12620 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12621 12622 // FIXME: Check explicit specializations more carefully. 12623 bool isExplicitSpecialization = false; 12624 bool Invalid = false; 12625 12626 // We only need to do this matching if we have template parameters 12627 // or a scope specifier, which also conveniently avoids this work 12628 // for non-C++ cases. 12629 if (TemplateParameterLists.size() > 0 || 12630 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12631 if (TemplateParameterList *TemplateParams = 12632 MatchTemplateParametersToScopeSpecifier( 12633 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12634 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12635 if (Kind == TTK_Enum) { 12636 Diag(KWLoc, diag::err_enum_template); 12637 return nullptr; 12638 } 12639 12640 if (TemplateParams->size() > 0) { 12641 // This is a declaration or definition of a class template (which may 12642 // be a member of another template). 12643 12644 if (Invalid) 12645 return nullptr; 12646 12647 OwnedDecl = false; 12648 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12649 SS, Name, NameLoc, Attr, 12650 TemplateParams, AS, 12651 ModulePrivateLoc, 12652 /*FriendLoc*/SourceLocation(), 12653 TemplateParameterLists.size()-1, 12654 TemplateParameterLists.data(), 12655 SkipBody); 12656 return Result.get(); 12657 } else { 12658 // The "template<>" header is extraneous. 12659 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12660 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12661 isExplicitSpecialization = true; 12662 } 12663 } 12664 } 12665 12666 // Figure out the underlying type if this a enum declaration. We need to do 12667 // this early, because it's needed to detect if this is an incompatible 12668 // redeclaration. 12669 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12670 bool EnumUnderlyingIsImplicit = false; 12671 12672 if (Kind == TTK_Enum) { 12673 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12674 // No underlying type explicitly specified, or we failed to parse the 12675 // type, default to int. 12676 EnumUnderlying = Context.IntTy.getTypePtr(); 12677 else if (UnderlyingType.get()) { 12678 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12679 // integral type; any cv-qualification is ignored. 12680 TypeSourceInfo *TI = nullptr; 12681 GetTypeFromParser(UnderlyingType.get(), &TI); 12682 EnumUnderlying = TI; 12683 12684 if (CheckEnumUnderlyingType(TI)) 12685 // Recover by falling back to int. 12686 EnumUnderlying = Context.IntTy.getTypePtr(); 12687 12688 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12689 UPPC_FixedUnderlyingType)) 12690 EnumUnderlying = Context.IntTy.getTypePtr(); 12691 12692 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12693 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12694 // Microsoft enums are always of int type. 12695 EnumUnderlying = Context.IntTy.getTypePtr(); 12696 EnumUnderlyingIsImplicit = true; 12697 } 12698 } 12699 } 12700 12701 DeclContext *SearchDC = CurContext; 12702 DeclContext *DC = CurContext; 12703 bool isStdBadAlloc = false; 12704 bool isStdAlignValT = false; 12705 12706 RedeclarationKind Redecl = ForRedeclaration; 12707 if (TUK == TUK_Friend || TUK == TUK_Reference) 12708 Redecl = NotForRedeclaration; 12709 12710 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12711 if (Name && SS.isNotEmpty()) { 12712 // We have a nested-name tag ('struct foo::bar'). 12713 12714 // Check for invalid 'foo::'. 12715 if (SS.isInvalid()) { 12716 Name = nullptr; 12717 goto CreateNewDecl; 12718 } 12719 12720 // If this is a friend or a reference to a class in a dependent 12721 // context, don't try to make a decl for it. 12722 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12723 DC = computeDeclContext(SS, false); 12724 if (!DC) { 12725 IsDependent = true; 12726 return nullptr; 12727 } 12728 } else { 12729 DC = computeDeclContext(SS, true); 12730 if (!DC) { 12731 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12732 << SS.getRange(); 12733 return nullptr; 12734 } 12735 } 12736 12737 if (RequireCompleteDeclContext(SS, DC)) 12738 return nullptr; 12739 12740 SearchDC = DC; 12741 // Look-up name inside 'foo::'. 12742 LookupQualifiedName(Previous, DC); 12743 12744 if (Previous.isAmbiguous()) 12745 return nullptr; 12746 12747 if (Previous.empty()) { 12748 // Name lookup did not find anything. However, if the 12749 // nested-name-specifier refers to the current instantiation, 12750 // and that current instantiation has any dependent base 12751 // classes, we might find something at instantiation time: treat 12752 // this as a dependent elaborated-type-specifier. 12753 // But this only makes any sense for reference-like lookups. 12754 if (Previous.wasNotFoundInCurrentInstantiation() && 12755 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12756 IsDependent = true; 12757 return nullptr; 12758 } 12759 12760 // A tag 'foo::bar' must already exist. 12761 Diag(NameLoc, diag::err_not_tag_in_scope) 12762 << Kind << Name << DC << SS.getRange(); 12763 Name = nullptr; 12764 Invalid = true; 12765 goto CreateNewDecl; 12766 } 12767 } else if (Name) { 12768 // C++14 [class.mem]p14: 12769 // If T is the name of a class, then each of the following shall have a 12770 // name different from T: 12771 // -- every member of class T that is itself a type 12772 if (TUK != TUK_Reference && TUK != TUK_Friend && 12773 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12774 return nullptr; 12775 12776 // If this is a named struct, check to see if there was a previous forward 12777 // declaration or definition. 12778 // FIXME: We're looking into outer scopes here, even when we 12779 // shouldn't be. Doing so can result in ambiguities that we 12780 // shouldn't be diagnosing. 12781 LookupName(Previous, S); 12782 12783 // When declaring or defining a tag, ignore ambiguities introduced 12784 // by types using'ed into this scope. 12785 if (Previous.isAmbiguous() && 12786 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12787 LookupResult::Filter F = Previous.makeFilter(); 12788 while (F.hasNext()) { 12789 NamedDecl *ND = F.next(); 12790 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12791 SearchDC->getRedeclContext())) 12792 F.erase(); 12793 } 12794 F.done(); 12795 } 12796 12797 // C++11 [namespace.memdef]p3: 12798 // If the name in a friend declaration is neither qualified nor 12799 // a template-id and the declaration is a function or an 12800 // elaborated-type-specifier, the lookup to determine whether 12801 // the entity has been previously declared shall not consider 12802 // any scopes outside the innermost enclosing namespace. 12803 // 12804 // MSVC doesn't implement the above rule for types, so a friend tag 12805 // declaration may be a redeclaration of a type declared in an enclosing 12806 // scope. They do implement this rule for friend functions. 12807 // 12808 // Does it matter that this should be by scope instead of by 12809 // semantic context? 12810 if (!Previous.empty() && TUK == TUK_Friend) { 12811 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12812 LookupResult::Filter F = Previous.makeFilter(); 12813 bool FriendSawTagOutsideEnclosingNamespace = false; 12814 while (F.hasNext()) { 12815 NamedDecl *ND = F.next(); 12816 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12817 if (DC->isFileContext() && 12818 !EnclosingNS->Encloses(ND->getDeclContext())) { 12819 if (getLangOpts().MSVCCompat) 12820 FriendSawTagOutsideEnclosingNamespace = true; 12821 else 12822 F.erase(); 12823 } 12824 } 12825 F.done(); 12826 12827 // Diagnose this MSVC extension in the easy case where lookup would have 12828 // unambiguously found something outside the enclosing namespace. 12829 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12830 NamedDecl *ND = Previous.getFoundDecl(); 12831 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12832 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12833 } 12834 } 12835 12836 // Note: there used to be some attempt at recovery here. 12837 if (Previous.isAmbiguous()) 12838 return nullptr; 12839 12840 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12841 // FIXME: This makes sure that we ignore the contexts associated 12842 // with C structs, unions, and enums when looking for a matching 12843 // tag declaration or definition. See the similar lookup tweak 12844 // in Sema::LookupName; is there a better way to deal with this? 12845 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12846 SearchDC = SearchDC->getParent(); 12847 } 12848 } 12849 12850 if (Previous.isSingleResult() && 12851 Previous.getFoundDecl()->isTemplateParameter()) { 12852 // Maybe we will complain about the shadowed template parameter. 12853 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12854 // Just pretend that we didn't see the previous declaration. 12855 Previous.clear(); 12856 } 12857 12858 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12859 DC->Equals(getStdNamespace())) { 12860 if (Name->isStr("bad_alloc")) { 12861 // This is a declaration of or a reference to "std::bad_alloc". 12862 isStdBadAlloc = true; 12863 12864 // If std::bad_alloc has been implicitly declared (but made invisible to 12865 // name lookup), fill in this implicit declaration as the previous 12866 // declaration, so that the declarations get chained appropriately. 12867 if (Previous.empty() && StdBadAlloc) 12868 Previous.addDecl(getStdBadAlloc()); 12869 } else if (Name->isStr("align_val_t")) { 12870 isStdAlignValT = true; 12871 if (Previous.empty() && StdAlignValT) 12872 Previous.addDecl(getStdAlignValT()); 12873 } 12874 } 12875 12876 // If we didn't find a previous declaration, and this is a reference 12877 // (or friend reference), move to the correct scope. In C++, we 12878 // also need to do a redeclaration lookup there, just in case 12879 // there's a shadow friend decl. 12880 if (Name && Previous.empty() && 12881 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12882 if (Invalid) goto CreateNewDecl; 12883 assert(SS.isEmpty()); 12884 12885 if (TUK == TUK_Reference) { 12886 // C++ [basic.scope.pdecl]p5: 12887 // -- for an elaborated-type-specifier of the form 12888 // 12889 // class-key identifier 12890 // 12891 // if the elaborated-type-specifier is used in the 12892 // decl-specifier-seq or parameter-declaration-clause of a 12893 // function defined in namespace scope, the identifier is 12894 // declared as a class-name in the namespace that contains 12895 // the declaration; otherwise, except as a friend 12896 // declaration, the identifier is declared in the smallest 12897 // non-class, non-function-prototype scope that contains the 12898 // declaration. 12899 // 12900 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12901 // C structs and unions. 12902 // 12903 // It is an error in C++ to declare (rather than define) an enum 12904 // type, including via an elaborated type specifier. We'll 12905 // diagnose that later; for now, declare the enum in the same 12906 // scope as we would have picked for any other tag type. 12907 // 12908 // GNU C also supports this behavior as part of its incomplete 12909 // enum types extension, while GNU C++ does not. 12910 // 12911 // Find the context where we'll be declaring the tag. 12912 // FIXME: We would like to maintain the current DeclContext as the 12913 // lexical context, 12914 SearchDC = getTagInjectionContext(SearchDC); 12915 12916 // Find the scope where we'll be declaring the tag. 12917 S = getTagInjectionScope(S, getLangOpts()); 12918 } else { 12919 assert(TUK == TUK_Friend); 12920 // C++ [namespace.memdef]p3: 12921 // If a friend declaration in a non-local class first declares a 12922 // class or function, the friend class or function is a member of 12923 // the innermost enclosing namespace. 12924 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12925 } 12926 12927 // In C++, we need to do a redeclaration lookup to properly 12928 // diagnose some problems. 12929 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12930 // hidden declaration so that we don't get ambiguity errors when using a 12931 // type declared by an elaborated-type-specifier. In C that is not correct 12932 // and we should instead merge compatible types found by lookup. 12933 if (getLangOpts().CPlusPlus) { 12934 Previous.setRedeclarationKind(ForRedeclaration); 12935 LookupQualifiedName(Previous, SearchDC); 12936 } else { 12937 Previous.setRedeclarationKind(ForRedeclaration); 12938 LookupName(Previous, S); 12939 } 12940 } 12941 12942 // If we have a known previous declaration to use, then use it. 12943 if (Previous.empty() && SkipBody && SkipBody->Previous) 12944 Previous.addDecl(SkipBody->Previous); 12945 12946 if (!Previous.empty()) { 12947 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12948 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12949 12950 // It's okay to have a tag decl in the same scope as a typedef 12951 // which hides a tag decl in the same scope. Finding this 12952 // insanity with a redeclaration lookup can only actually happen 12953 // in C++. 12954 // 12955 // This is also okay for elaborated-type-specifiers, which is 12956 // technically forbidden by the current standard but which is 12957 // okay according to the likely resolution of an open issue; 12958 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12959 if (getLangOpts().CPlusPlus) { 12960 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12961 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12962 TagDecl *Tag = TT->getDecl(); 12963 if (Tag->getDeclName() == Name && 12964 Tag->getDeclContext()->getRedeclContext() 12965 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12966 PrevDecl = Tag; 12967 Previous.clear(); 12968 Previous.addDecl(Tag); 12969 Previous.resolveKind(); 12970 } 12971 } 12972 } 12973 } 12974 12975 // If this is a redeclaration of a using shadow declaration, it must 12976 // declare a tag in the same context. In MSVC mode, we allow a 12977 // redefinition if either context is within the other. 12978 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12979 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12980 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12981 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12982 !(OldTag && isAcceptableTagRedeclContext( 12983 *this, OldTag->getDeclContext(), SearchDC))) { 12984 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12985 Diag(Shadow->getTargetDecl()->getLocation(), 12986 diag::note_using_decl_target); 12987 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12988 << 0; 12989 // Recover by ignoring the old declaration. 12990 Previous.clear(); 12991 goto CreateNewDecl; 12992 } 12993 } 12994 12995 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12996 // If this is a use of a previous tag, or if the tag is already declared 12997 // in the same scope (so that the definition/declaration completes or 12998 // rementions the tag), reuse the decl. 12999 if (TUK == TUK_Reference || TUK == TUK_Friend || 13000 isDeclInScope(DirectPrevDecl, SearchDC, S, 13001 SS.isNotEmpty() || isExplicitSpecialization)) { 13002 // Make sure that this wasn't declared as an enum and now used as a 13003 // struct or something similar. 13004 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13005 TUK == TUK_Definition, KWLoc, 13006 Name)) { 13007 bool SafeToContinue 13008 = (PrevTagDecl->getTagKind() != TTK_Enum && 13009 Kind != TTK_Enum); 13010 if (SafeToContinue) 13011 Diag(KWLoc, diag::err_use_with_wrong_tag) 13012 << Name 13013 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13014 PrevTagDecl->getKindName()); 13015 else 13016 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13017 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13018 13019 if (SafeToContinue) 13020 Kind = PrevTagDecl->getTagKind(); 13021 else { 13022 // Recover by making this an anonymous redefinition. 13023 Name = nullptr; 13024 Previous.clear(); 13025 Invalid = true; 13026 } 13027 } 13028 13029 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13030 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13031 13032 // If this is an elaborated-type-specifier for a scoped enumeration, 13033 // the 'class' keyword is not necessary and not permitted. 13034 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13035 if (ScopedEnum) 13036 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13037 << PrevEnum->isScoped() 13038 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13039 return PrevTagDecl; 13040 } 13041 13042 QualType EnumUnderlyingTy; 13043 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13044 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13045 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13046 EnumUnderlyingTy = QualType(T, 0); 13047 13048 // All conflicts with previous declarations are recovered by 13049 // returning the previous declaration, unless this is a definition, 13050 // in which case we want the caller to bail out. 13051 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13052 ScopedEnum, EnumUnderlyingTy, 13053 EnumUnderlyingIsImplicit, PrevEnum)) 13054 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13055 } 13056 13057 // C++11 [class.mem]p1: 13058 // A member shall not be declared twice in the member-specification, 13059 // except that a nested class or member class template can be declared 13060 // and then later defined. 13061 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13062 S->isDeclScope(PrevDecl)) { 13063 Diag(NameLoc, diag::ext_member_redeclared); 13064 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13065 } 13066 13067 if (!Invalid) { 13068 // If this is a use, just return the declaration we found, unless 13069 // we have attributes. 13070 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13071 if (Attr) { 13072 // FIXME: Diagnose these attributes. For now, we create a new 13073 // declaration to hold them. 13074 } else if (TUK == TUK_Reference && 13075 (PrevTagDecl->getFriendObjectKind() == 13076 Decl::FOK_Undeclared || 13077 PP.getModuleContainingLocation( 13078 PrevDecl->getLocation()) != 13079 PP.getModuleContainingLocation(KWLoc)) && 13080 SS.isEmpty()) { 13081 // This declaration is a reference to an existing entity, but 13082 // has different visibility from that entity: it either makes 13083 // a friend visible or it makes a type visible in a new module. 13084 // In either case, create a new declaration. We only do this if 13085 // the declaration would have meant the same thing if no prior 13086 // declaration were found, that is, if it was found in the same 13087 // scope where we would have injected a declaration. 13088 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13089 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13090 return PrevTagDecl; 13091 // This is in the injected scope, create a new declaration in 13092 // that scope. 13093 S = getTagInjectionScope(S, getLangOpts()); 13094 } else { 13095 return PrevTagDecl; 13096 } 13097 } 13098 13099 // Diagnose attempts to redefine a tag. 13100 if (TUK == TUK_Definition) { 13101 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13102 // If we're defining a specialization and the previous definition 13103 // is from an implicit instantiation, don't emit an error 13104 // here; we'll catch this in the general case below. 13105 bool IsExplicitSpecializationAfterInstantiation = false; 13106 if (isExplicitSpecialization) { 13107 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13108 IsExplicitSpecializationAfterInstantiation = 13109 RD->getTemplateSpecializationKind() != 13110 TSK_ExplicitSpecialization; 13111 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13112 IsExplicitSpecializationAfterInstantiation = 13113 ED->getTemplateSpecializationKind() != 13114 TSK_ExplicitSpecialization; 13115 } 13116 13117 NamedDecl *Hidden = nullptr; 13118 if (SkipBody && getLangOpts().CPlusPlus && 13119 !hasVisibleDefinition(Def, &Hidden)) { 13120 // There is a definition of this tag, but it is not visible. We 13121 // explicitly make use of C++'s one definition rule here, and 13122 // assume that this definition is identical to the hidden one 13123 // we already have. Make the existing definition visible and 13124 // use it in place of this one. 13125 SkipBody->ShouldSkip = true; 13126 makeMergedDefinitionVisible(Hidden, KWLoc); 13127 return Def; 13128 } else if (!IsExplicitSpecializationAfterInstantiation) { 13129 // A redeclaration in function prototype scope in C isn't 13130 // visible elsewhere, so merely issue a warning. 13131 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13132 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13133 else 13134 Diag(NameLoc, diag::err_redefinition) << Name; 13135 Diag(Def->getLocation(), diag::note_previous_definition); 13136 // If this is a redefinition, recover by making this 13137 // struct be anonymous, which will make any later 13138 // references get the previous definition. 13139 Name = nullptr; 13140 Previous.clear(); 13141 Invalid = true; 13142 } 13143 } else { 13144 // If the type is currently being defined, complain 13145 // about a nested redefinition. 13146 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13147 if (TD->isBeingDefined()) { 13148 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13149 Diag(PrevTagDecl->getLocation(), 13150 diag::note_previous_definition); 13151 Name = nullptr; 13152 Previous.clear(); 13153 Invalid = true; 13154 } 13155 } 13156 13157 // Okay, this is definition of a previously declared or referenced 13158 // tag. We're going to create a new Decl for it. 13159 } 13160 13161 // Okay, we're going to make a redeclaration. If this is some kind 13162 // of reference, make sure we build the redeclaration in the same DC 13163 // as the original, and ignore the current access specifier. 13164 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13165 SearchDC = PrevTagDecl->getDeclContext(); 13166 AS = AS_none; 13167 } 13168 } 13169 // If we get here we have (another) forward declaration or we 13170 // have a definition. Just create a new decl. 13171 13172 } else { 13173 // If we get here, this is a definition of a new tag type in a nested 13174 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13175 // new decl/type. We set PrevDecl to NULL so that the entities 13176 // have distinct types. 13177 Previous.clear(); 13178 } 13179 // If we get here, we're going to create a new Decl. If PrevDecl 13180 // is non-NULL, it's a definition of the tag declared by 13181 // PrevDecl. If it's NULL, we have a new definition. 13182 13183 // Otherwise, PrevDecl is not a tag, but was found with tag 13184 // lookup. This is only actually possible in C++, where a few 13185 // things like templates still live in the tag namespace. 13186 } else { 13187 // Use a better diagnostic if an elaborated-type-specifier 13188 // found the wrong kind of type on the first 13189 // (non-redeclaration) lookup. 13190 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13191 !Previous.isForRedeclaration()) { 13192 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13193 Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK; 13194 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13195 Invalid = true; 13196 13197 // Otherwise, only diagnose if the declaration is in scope. 13198 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13199 SS.isNotEmpty() || isExplicitSpecialization)) { 13200 // do nothing 13201 13202 // Diagnose implicit declarations introduced by elaborated types. 13203 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13204 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13205 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13206 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13207 Invalid = true; 13208 13209 // Otherwise it's a declaration. Call out a particularly common 13210 // case here. 13211 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13212 unsigned Kind = 0; 13213 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13214 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13215 << Name << Kind << TND->getUnderlyingType(); 13216 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13217 Invalid = true; 13218 13219 // Otherwise, diagnose. 13220 } else { 13221 // The tag name clashes with something else in the target scope, 13222 // issue an error and recover by making this tag be anonymous. 13223 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13224 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13225 Name = nullptr; 13226 Invalid = true; 13227 } 13228 13229 // The existing declaration isn't relevant to us; we're in a 13230 // new scope, so clear out the previous declaration. 13231 Previous.clear(); 13232 } 13233 } 13234 13235 CreateNewDecl: 13236 13237 TagDecl *PrevDecl = nullptr; 13238 if (Previous.isSingleResult()) 13239 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13240 13241 // If there is an identifier, use the location of the identifier as the 13242 // location of the decl, otherwise use the location of the struct/union 13243 // keyword. 13244 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13245 13246 // Otherwise, create a new declaration. If there is a previous 13247 // declaration of the same entity, the two will be linked via 13248 // PrevDecl. 13249 TagDecl *New; 13250 13251 bool IsForwardReference = false; 13252 if (Kind == TTK_Enum) { 13253 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13254 // enum X { A, B, C } D; D should chain to X. 13255 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13256 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13257 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13258 13259 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13260 StdAlignValT = cast<EnumDecl>(New); 13261 13262 // If this is an undefined enum, warn. 13263 if (TUK != TUK_Definition && !Invalid) { 13264 TagDecl *Def; 13265 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13266 cast<EnumDecl>(New)->isFixed()) { 13267 // C++0x: 7.2p2: opaque-enum-declaration. 13268 // Conflicts are diagnosed above. Do nothing. 13269 } 13270 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13271 Diag(Loc, diag::ext_forward_ref_enum_def) 13272 << New; 13273 Diag(Def->getLocation(), diag::note_previous_definition); 13274 } else { 13275 unsigned DiagID = diag::ext_forward_ref_enum; 13276 if (getLangOpts().MSVCCompat) 13277 DiagID = diag::ext_ms_forward_ref_enum; 13278 else if (getLangOpts().CPlusPlus) 13279 DiagID = diag::err_forward_ref_enum; 13280 Diag(Loc, DiagID); 13281 13282 // If this is a forward-declared reference to an enumeration, make a 13283 // note of it; we won't actually be introducing the declaration into 13284 // the declaration context. 13285 if (TUK == TUK_Reference) 13286 IsForwardReference = true; 13287 } 13288 } 13289 13290 if (EnumUnderlying) { 13291 EnumDecl *ED = cast<EnumDecl>(New); 13292 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13293 ED->setIntegerTypeSourceInfo(TI); 13294 else 13295 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13296 ED->setPromotionType(ED->getIntegerType()); 13297 } 13298 } else { 13299 // struct/union/class 13300 13301 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13302 // struct X { int A; } D; D should chain to X. 13303 if (getLangOpts().CPlusPlus) { 13304 // FIXME: Look for a way to use RecordDecl for simple structs. 13305 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13306 cast_or_null<CXXRecordDecl>(PrevDecl)); 13307 13308 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13309 StdBadAlloc = cast<CXXRecordDecl>(New); 13310 } else 13311 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13312 cast_or_null<RecordDecl>(PrevDecl)); 13313 } 13314 13315 // C++11 [dcl.type]p3: 13316 // A type-specifier-seq shall not define a class or enumeration [...]. 13317 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13318 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13319 << Context.getTagDeclType(New); 13320 Invalid = true; 13321 } 13322 13323 // Maybe add qualifier info. 13324 if (SS.isNotEmpty()) { 13325 if (SS.isSet()) { 13326 // If this is either a declaration or a definition, check the 13327 // nested-name-specifier against the current context. We don't do this 13328 // for explicit specializations, because they have similar checking 13329 // (with more specific diagnostics) in the call to 13330 // CheckMemberSpecialization, below. 13331 if (!isExplicitSpecialization && 13332 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13333 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13334 Invalid = true; 13335 13336 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13337 if (TemplateParameterLists.size() > 0) { 13338 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13339 } 13340 } 13341 else 13342 Invalid = true; 13343 } 13344 13345 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13346 // Add alignment attributes if necessary; these attributes are checked when 13347 // the ASTContext lays out the structure. 13348 // 13349 // It is important for implementing the correct semantics that this 13350 // happen here (in act on tag decl). The #pragma pack stack is 13351 // maintained as a result of parser callbacks which can occur at 13352 // many points during the parsing of a struct declaration (because 13353 // the #pragma tokens are effectively skipped over during the 13354 // parsing of the struct). 13355 if (TUK == TUK_Definition) { 13356 AddAlignmentAttributesForRecord(RD); 13357 AddMsStructLayoutForRecord(RD); 13358 } 13359 } 13360 13361 if (ModulePrivateLoc.isValid()) { 13362 if (isExplicitSpecialization) 13363 Diag(New->getLocation(), diag::err_module_private_specialization) 13364 << 2 13365 << FixItHint::CreateRemoval(ModulePrivateLoc); 13366 // __module_private__ does not apply to local classes. However, we only 13367 // diagnose this as an error when the declaration specifiers are 13368 // freestanding. Here, we just ignore the __module_private__. 13369 else if (!SearchDC->isFunctionOrMethod()) 13370 New->setModulePrivate(); 13371 } 13372 13373 // If this is a specialization of a member class (of a class template), 13374 // check the specialization. 13375 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13376 Invalid = true; 13377 13378 // If we're declaring or defining a tag in function prototype scope in C, 13379 // note that this type can only be used within the function and add it to 13380 // the list of decls to inject into the function definition scope. 13381 if ((Name || Kind == TTK_Enum) && 13382 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13383 if (getLangOpts().CPlusPlus) { 13384 // C++ [dcl.fct]p6: 13385 // Types shall not be defined in return or parameter types. 13386 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13387 Diag(Loc, diag::err_type_defined_in_param_type) 13388 << Name; 13389 Invalid = true; 13390 } 13391 } else if (!PrevDecl) { 13392 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13393 } 13394 DeclsInPrototypeScope.push_back(New); 13395 } 13396 13397 if (Invalid) 13398 New->setInvalidDecl(); 13399 13400 if (Attr) 13401 ProcessDeclAttributeList(S, New, Attr); 13402 13403 // Set the lexical context. If the tag has a C++ scope specifier, the 13404 // lexical context will be different from the semantic context. 13405 New->setLexicalDeclContext(CurContext); 13406 13407 // Mark this as a friend decl if applicable. 13408 // In Microsoft mode, a friend declaration also acts as a forward 13409 // declaration so we always pass true to setObjectOfFriendDecl to make 13410 // the tag name visible. 13411 if (TUK == TUK_Friend) 13412 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13413 13414 // Set the access specifier. 13415 if (!Invalid && SearchDC->isRecord()) 13416 SetMemberAccessSpecifier(New, PrevDecl, AS); 13417 13418 if (TUK == TUK_Definition) 13419 New->startDefinition(); 13420 13421 // If this has an identifier, add it to the scope stack. 13422 if (TUK == TUK_Friend) { 13423 // We might be replacing an existing declaration in the lookup tables; 13424 // if so, borrow its access specifier. 13425 if (PrevDecl) 13426 New->setAccess(PrevDecl->getAccess()); 13427 13428 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13429 DC->makeDeclVisibleInContext(New); 13430 if (Name) // can be null along some error paths 13431 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13432 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13433 } else if (Name) { 13434 S = getNonFieldDeclScope(S); 13435 PushOnScopeChains(New, S, !IsForwardReference); 13436 if (IsForwardReference) 13437 SearchDC->makeDeclVisibleInContext(New); 13438 } else { 13439 CurContext->addDecl(New); 13440 } 13441 13442 // If this is the C FILE type, notify the AST context. 13443 if (IdentifierInfo *II = New->getIdentifier()) 13444 if (!New->isInvalidDecl() && 13445 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13446 II->isStr("FILE")) 13447 Context.setFILEDecl(New); 13448 13449 if (PrevDecl) 13450 mergeDeclAttributes(New, PrevDecl); 13451 13452 // If there's a #pragma GCC visibility in scope, set the visibility of this 13453 // record. 13454 AddPushedVisibilityAttribute(New); 13455 13456 OwnedDecl = true; 13457 // In C++, don't return an invalid declaration. We can't recover well from 13458 // the cases where we make the type anonymous. 13459 if (Invalid && getLangOpts().CPlusPlus) { 13460 if (New->isBeingDefined()) 13461 if (auto RD = dyn_cast<RecordDecl>(New)) 13462 RD->completeDefinition(); 13463 return nullptr; 13464 } else { 13465 return New; 13466 } 13467 } 13468 13469 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13470 AdjustDeclIfTemplate(TagD); 13471 TagDecl *Tag = cast<TagDecl>(TagD); 13472 13473 // Enter the tag context. 13474 PushDeclContext(S, Tag); 13475 13476 ActOnDocumentableDecl(TagD); 13477 13478 // If there's a #pragma GCC visibility in scope, set the visibility of this 13479 // record. 13480 AddPushedVisibilityAttribute(Tag); 13481 } 13482 13483 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13484 assert(isa<ObjCContainerDecl>(IDecl) && 13485 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13486 DeclContext *OCD = cast<DeclContext>(IDecl); 13487 assert(getContainingDC(OCD) == CurContext && 13488 "The next DeclContext should be lexically contained in the current one."); 13489 CurContext = OCD; 13490 return IDecl; 13491 } 13492 13493 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13494 SourceLocation FinalLoc, 13495 bool IsFinalSpelledSealed, 13496 SourceLocation LBraceLoc) { 13497 AdjustDeclIfTemplate(TagD); 13498 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13499 13500 FieldCollector->StartClass(); 13501 13502 if (!Record->getIdentifier()) 13503 return; 13504 13505 if (FinalLoc.isValid()) 13506 Record->addAttr(new (Context) 13507 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13508 13509 // C++ [class]p2: 13510 // [...] The class-name is also inserted into the scope of the 13511 // class itself; this is known as the injected-class-name. For 13512 // purposes of access checking, the injected-class-name is treated 13513 // as if it were a public member name. 13514 CXXRecordDecl *InjectedClassName 13515 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13516 Record->getLocStart(), Record->getLocation(), 13517 Record->getIdentifier(), 13518 /*PrevDecl=*/nullptr, 13519 /*DelayTypeCreation=*/true); 13520 Context.getTypeDeclType(InjectedClassName, Record); 13521 InjectedClassName->setImplicit(); 13522 InjectedClassName->setAccess(AS_public); 13523 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13524 InjectedClassName->setDescribedClassTemplate(Template); 13525 PushOnScopeChains(InjectedClassName, S); 13526 assert(InjectedClassName->isInjectedClassName() && 13527 "Broken injected-class-name"); 13528 } 13529 13530 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13531 SourceRange BraceRange) { 13532 AdjustDeclIfTemplate(TagD); 13533 TagDecl *Tag = cast<TagDecl>(TagD); 13534 Tag->setBraceRange(BraceRange); 13535 13536 // Make sure we "complete" the definition even it is invalid. 13537 if (Tag->isBeingDefined()) { 13538 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13539 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13540 RD->completeDefinition(); 13541 } 13542 13543 if (isa<CXXRecordDecl>(Tag)) 13544 FieldCollector->FinishClass(); 13545 13546 // Exit this scope of this tag's definition. 13547 PopDeclContext(); 13548 13549 if (getCurLexicalContext()->isObjCContainer() && 13550 Tag->getDeclContext()->isFileContext()) 13551 Tag->setTopLevelDeclInObjCContainer(); 13552 13553 // Notify the consumer that we've defined a tag. 13554 if (!Tag->isInvalidDecl()) 13555 Consumer.HandleTagDeclDefinition(Tag); 13556 } 13557 13558 void Sema::ActOnObjCContainerFinishDefinition() { 13559 // Exit this scope of this interface definition. 13560 PopDeclContext(); 13561 } 13562 13563 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13564 assert(DC == CurContext && "Mismatch of container contexts"); 13565 OriginalLexicalContext = DC; 13566 ActOnObjCContainerFinishDefinition(); 13567 } 13568 13569 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13570 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13571 OriginalLexicalContext = nullptr; 13572 } 13573 13574 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13575 AdjustDeclIfTemplate(TagD); 13576 TagDecl *Tag = cast<TagDecl>(TagD); 13577 Tag->setInvalidDecl(); 13578 13579 // Make sure we "complete" the definition even it is invalid. 13580 if (Tag->isBeingDefined()) { 13581 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13582 RD->completeDefinition(); 13583 } 13584 13585 // We're undoing ActOnTagStartDefinition here, not 13586 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13587 // the FieldCollector. 13588 13589 PopDeclContext(); 13590 } 13591 13592 // Note that FieldName may be null for anonymous bitfields. 13593 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13594 IdentifierInfo *FieldName, 13595 QualType FieldTy, bool IsMsStruct, 13596 Expr *BitWidth, bool *ZeroWidth) { 13597 // Default to true; that shouldn't confuse checks for emptiness 13598 if (ZeroWidth) 13599 *ZeroWidth = true; 13600 13601 // C99 6.7.2.1p4 - verify the field type. 13602 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13603 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13604 // Handle incomplete types with specific error. 13605 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13606 return ExprError(); 13607 if (FieldName) 13608 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13609 << FieldName << FieldTy << BitWidth->getSourceRange(); 13610 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13611 << FieldTy << BitWidth->getSourceRange(); 13612 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13613 UPPC_BitFieldWidth)) 13614 return ExprError(); 13615 13616 // If the bit-width is type- or value-dependent, don't try to check 13617 // it now. 13618 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13619 return BitWidth; 13620 13621 llvm::APSInt Value; 13622 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13623 if (ICE.isInvalid()) 13624 return ICE; 13625 BitWidth = ICE.get(); 13626 13627 if (Value != 0 && ZeroWidth) 13628 *ZeroWidth = false; 13629 13630 // Zero-width bitfield is ok for anonymous field. 13631 if (Value == 0 && FieldName) 13632 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13633 13634 if (Value.isSigned() && Value.isNegative()) { 13635 if (FieldName) 13636 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13637 << FieldName << Value.toString(10); 13638 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13639 << Value.toString(10); 13640 } 13641 13642 if (!FieldTy->isDependentType()) { 13643 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13644 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13645 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13646 13647 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13648 // ABI. 13649 bool CStdConstraintViolation = 13650 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13651 bool MSBitfieldViolation = 13652 Value.ugt(TypeStorageSize) && 13653 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13654 if (CStdConstraintViolation || MSBitfieldViolation) { 13655 unsigned DiagWidth = 13656 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13657 if (FieldName) 13658 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13659 << FieldName << (unsigned)Value.getZExtValue() 13660 << !CStdConstraintViolation << DiagWidth; 13661 13662 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13663 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13664 << DiagWidth; 13665 } 13666 13667 // Warn on types where the user might conceivably expect to get all 13668 // specified bits as value bits: that's all integral types other than 13669 // 'bool'. 13670 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13671 if (FieldName) 13672 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13673 << FieldName << (unsigned)Value.getZExtValue() 13674 << (unsigned)TypeWidth; 13675 else 13676 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13677 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13678 } 13679 } 13680 13681 return BitWidth; 13682 } 13683 13684 /// ActOnField - Each field of a C struct/union is passed into this in order 13685 /// to create a FieldDecl object for it. 13686 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13687 Declarator &D, Expr *BitfieldWidth) { 13688 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13689 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13690 /*InitStyle=*/ICIS_NoInit, AS_public); 13691 return Res; 13692 } 13693 13694 /// HandleField - Analyze a field of a C struct or a C++ data member. 13695 /// 13696 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13697 SourceLocation DeclStart, 13698 Declarator &D, Expr *BitWidth, 13699 InClassInitStyle InitStyle, 13700 AccessSpecifier AS) { 13701 if (D.isDecompositionDeclarator()) { 13702 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13703 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13704 << Decomp.getSourceRange(); 13705 return nullptr; 13706 } 13707 13708 IdentifierInfo *II = D.getIdentifier(); 13709 SourceLocation Loc = DeclStart; 13710 if (II) Loc = D.getIdentifierLoc(); 13711 13712 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13713 QualType T = TInfo->getType(); 13714 if (getLangOpts().CPlusPlus) { 13715 CheckExtraCXXDefaultArguments(D); 13716 13717 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13718 UPPC_DataMemberType)) { 13719 D.setInvalidType(); 13720 T = Context.IntTy; 13721 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13722 } 13723 } 13724 13725 // TR 18037 does not allow fields to be declared with address spaces. 13726 if (T.getQualifiers().hasAddressSpace()) { 13727 Diag(Loc, diag::err_field_with_address_space); 13728 D.setInvalidType(); 13729 } 13730 13731 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13732 // used as structure or union field: image, sampler, event or block types. 13733 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13734 T->isSamplerT() || T->isBlockPointerType())) { 13735 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13736 D.setInvalidType(); 13737 } 13738 13739 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13740 13741 if (D.getDeclSpec().isInlineSpecified()) 13742 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13743 << getLangOpts().CPlusPlus1z; 13744 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13745 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13746 diag::err_invalid_thread) 13747 << DeclSpec::getSpecifierName(TSCS); 13748 13749 // Check to see if this name was declared as a member previously 13750 NamedDecl *PrevDecl = nullptr; 13751 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13752 LookupName(Previous, S); 13753 switch (Previous.getResultKind()) { 13754 case LookupResult::Found: 13755 case LookupResult::FoundUnresolvedValue: 13756 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13757 break; 13758 13759 case LookupResult::FoundOverloaded: 13760 PrevDecl = Previous.getRepresentativeDecl(); 13761 break; 13762 13763 case LookupResult::NotFound: 13764 case LookupResult::NotFoundInCurrentInstantiation: 13765 case LookupResult::Ambiguous: 13766 break; 13767 } 13768 Previous.suppressDiagnostics(); 13769 13770 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13771 // Maybe we will complain about the shadowed template parameter. 13772 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13773 // Just pretend that we didn't see the previous declaration. 13774 PrevDecl = nullptr; 13775 } 13776 13777 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13778 PrevDecl = nullptr; 13779 13780 bool Mutable 13781 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13782 SourceLocation TSSL = D.getLocStart(); 13783 FieldDecl *NewFD 13784 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13785 TSSL, AS, PrevDecl, &D); 13786 13787 if (NewFD->isInvalidDecl()) 13788 Record->setInvalidDecl(); 13789 13790 if (D.getDeclSpec().isModulePrivateSpecified()) 13791 NewFD->setModulePrivate(); 13792 13793 if (NewFD->isInvalidDecl() && PrevDecl) { 13794 // Don't introduce NewFD into scope; there's already something 13795 // with the same name in the same scope. 13796 } else if (II) { 13797 PushOnScopeChains(NewFD, S); 13798 } else 13799 Record->addDecl(NewFD); 13800 13801 return NewFD; 13802 } 13803 13804 /// \brief Build a new FieldDecl and check its well-formedness. 13805 /// 13806 /// This routine builds a new FieldDecl given the fields name, type, 13807 /// record, etc. \p PrevDecl should refer to any previous declaration 13808 /// with the same name and in the same scope as the field to be 13809 /// created. 13810 /// 13811 /// \returns a new FieldDecl. 13812 /// 13813 /// \todo The Declarator argument is a hack. It will be removed once 13814 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13815 TypeSourceInfo *TInfo, 13816 RecordDecl *Record, SourceLocation Loc, 13817 bool Mutable, Expr *BitWidth, 13818 InClassInitStyle InitStyle, 13819 SourceLocation TSSL, 13820 AccessSpecifier AS, NamedDecl *PrevDecl, 13821 Declarator *D) { 13822 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13823 bool InvalidDecl = false; 13824 if (D) InvalidDecl = D->isInvalidType(); 13825 13826 // If we receive a broken type, recover by assuming 'int' and 13827 // marking this declaration as invalid. 13828 if (T.isNull()) { 13829 InvalidDecl = true; 13830 T = Context.IntTy; 13831 } 13832 13833 QualType EltTy = Context.getBaseElementType(T); 13834 if (!EltTy->isDependentType()) { 13835 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13836 // Fields of incomplete type force their record to be invalid. 13837 Record->setInvalidDecl(); 13838 InvalidDecl = true; 13839 } else { 13840 NamedDecl *Def; 13841 EltTy->isIncompleteType(&Def); 13842 if (Def && Def->isInvalidDecl()) { 13843 Record->setInvalidDecl(); 13844 InvalidDecl = true; 13845 } 13846 } 13847 } 13848 13849 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13850 if (BitWidth && getLangOpts().OpenCL) { 13851 Diag(Loc, diag::err_opencl_bitfields); 13852 InvalidDecl = true; 13853 } 13854 13855 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13856 // than a variably modified type. 13857 if (!InvalidDecl && T->isVariablyModifiedType()) { 13858 bool SizeIsNegative; 13859 llvm::APSInt Oversized; 13860 13861 TypeSourceInfo *FixedTInfo = 13862 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13863 SizeIsNegative, 13864 Oversized); 13865 if (FixedTInfo) { 13866 Diag(Loc, diag::warn_illegal_constant_array_size); 13867 TInfo = FixedTInfo; 13868 T = FixedTInfo->getType(); 13869 } else { 13870 if (SizeIsNegative) 13871 Diag(Loc, diag::err_typecheck_negative_array_size); 13872 else if (Oversized.getBoolValue()) 13873 Diag(Loc, diag::err_array_too_large) 13874 << Oversized.toString(10); 13875 else 13876 Diag(Loc, diag::err_typecheck_field_variable_size); 13877 InvalidDecl = true; 13878 } 13879 } 13880 13881 // Fields can not have abstract class types 13882 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13883 diag::err_abstract_type_in_decl, 13884 AbstractFieldType)) 13885 InvalidDecl = true; 13886 13887 bool ZeroWidth = false; 13888 if (InvalidDecl) 13889 BitWidth = nullptr; 13890 // If this is declared as a bit-field, check the bit-field. 13891 if (BitWidth) { 13892 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13893 &ZeroWidth).get(); 13894 if (!BitWidth) { 13895 InvalidDecl = true; 13896 BitWidth = nullptr; 13897 ZeroWidth = false; 13898 } 13899 } 13900 13901 // Check that 'mutable' is consistent with the type of the declaration. 13902 if (!InvalidDecl && Mutable) { 13903 unsigned DiagID = 0; 13904 if (T->isReferenceType()) 13905 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13906 : diag::err_mutable_reference; 13907 else if (T.isConstQualified()) 13908 DiagID = diag::err_mutable_const; 13909 13910 if (DiagID) { 13911 SourceLocation ErrLoc = Loc; 13912 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13913 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13914 Diag(ErrLoc, DiagID); 13915 if (DiagID != diag::ext_mutable_reference) { 13916 Mutable = false; 13917 InvalidDecl = true; 13918 } 13919 } 13920 } 13921 13922 // C++11 [class.union]p8 (DR1460): 13923 // At most one variant member of a union may have a 13924 // brace-or-equal-initializer. 13925 if (InitStyle != ICIS_NoInit) 13926 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13927 13928 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13929 BitWidth, Mutable, InitStyle); 13930 if (InvalidDecl) 13931 NewFD->setInvalidDecl(); 13932 13933 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13934 Diag(Loc, diag::err_duplicate_member) << II; 13935 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13936 NewFD->setInvalidDecl(); 13937 } 13938 13939 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13940 if (Record->isUnion()) { 13941 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13942 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13943 if (RDecl->getDefinition()) { 13944 // C++ [class.union]p1: An object of a class with a non-trivial 13945 // constructor, a non-trivial copy constructor, a non-trivial 13946 // destructor, or a non-trivial copy assignment operator 13947 // cannot be a member of a union, nor can an array of such 13948 // objects. 13949 if (CheckNontrivialField(NewFD)) 13950 NewFD->setInvalidDecl(); 13951 } 13952 } 13953 13954 // C++ [class.union]p1: If a union contains a member of reference type, 13955 // the program is ill-formed, except when compiling with MSVC extensions 13956 // enabled. 13957 if (EltTy->isReferenceType()) { 13958 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13959 diag::ext_union_member_of_reference_type : 13960 diag::err_union_member_of_reference_type) 13961 << NewFD->getDeclName() << EltTy; 13962 if (!getLangOpts().MicrosoftExt) 13963 NewFD->setInvalidDecl(); 13964 } 13965 } 13966 } 13967 13968 // FIXME: We need to pass in the attributes given an AST 13969 // representation, not a parser representation. 13970 if (D) { 13971 // FIXME: The current scope is almost... but not entirely... correct here. 13972 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13973 13974 if (NewFD->hasAttrs()) 13975 CheckAlignasUnderalignment(NewFD); 13976 } 13977 13978 // In auto-retain/release, infer strong retension for fields of 13979 // retainable type. 13980 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13981 NewFD->setInvalidDecl(); 13982 13983 if (T.isObjCGCWeak()) 13984 Diag(Loc, diag::warn_attribute_weak_on_field); 13985 13986 NewFD->setAccess(AS); 13987 return NewFD; 13988 } 13989 13990 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13991 assert(FD); 13992 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13993 13994 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13995 return false; 13996 13997 QualType EltTy = Context.getBaseElementType(FD->getType()); 13998 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13999 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14000 if (RDecl->getDefinition()) { 14001 // We check for copy constructors before constructors 14002 // because otherwise we'll never get complaints about 14003 // copy constructors. 14004 14005 CXXSpecialMember member = CXXInvalid; 14006 // We're required to check for any non-trivial constructors. Since the 14007 // implicit default constructor is suppressed if there are any 14008 // user-declared constructors, we just need to check that there is a 14009 // trivial default constructor and a trivial copy constructor. (We don't 14010 // worry about move constructors here, since this is a C++98 check.) 14011 if (RDecl->hasNonTrivialCopyConstructor()) 14012 member = CXXCopyConstructor; 14013 else if (!RDecl->hasTrivialDefaultConstructor()) 14014 member = CXXDefaultConstructor; 14015 else if (RDecl->hasNonTrivialCopyAssignment()) 14016 member = CXXCopyAssignment; 14017 else if (RDecl->hasNonTrivialDestructor()) 14018 member = CXXDestructor; 14019 14020 if (member != CXXInvalid) { 14021 if (!getLangOpts().CPlusPlus11 && 14022 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14023 // Objective-C++ ARC: it is an error to have a non-trivial field of 14024 // a union. However, system headers in Objective-C programs 14025 // occasionally have Objective-C lifetime objects within unions, 14026 // and rather than cause the program to fail, we make those 14027 // members unavailable. 14028 SourceLocation Loc = FD->getLocation(); 14029 if (getSourceManager().isInSystemHeader(Loc)) { 14030 if (!FD->hasAttr<UnavailableAttr>()) 14031 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14032 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14033 return false; 14034 } 14035 } 14036 14037 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14038 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14039 diag::err_illegal_union_or_anon_struct_member) 14040 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14041 DiagnoseNontrivial(RDecl, member); 14042 return !getLangOpts().CPlusPlus11; 14043 } 14044 } 14045 } 14046 14047 return false; 14048 } 14049 14050 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14051 /// AST enum value. 14052 static ObjCIvarDecl::AccessControl 14053 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14054 switch (ivarVisibility) { 14055 default: llvm_unreachable("Unknown visitibility kind"); 14056 case tok::objc_private: return ObjCIvarDecl::Private; 14057 case tok::objc_public: return ObjCIvarDecl::Public; 14058 case tok::objc_protected: return ObjCIvarDecl::Protected; 14059 case tok::objc_package: return ObjCIvarDecl::Package; 14060 } 14061 } 14062 14063 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14064 /// in order to create an IvarDecl object for it. 14065 Decl *Sema::ActOnIvar(Scope *S, 14066 SourceLocation DeclStart, 14067 Declarator &D, Expr *BitfieldWidth, 14068 tok::ObjCKeywordKind Visibility) { 14069 14070 IdentifierInfo *II = D.getIdentifier(); 14071 Expr *BitWidth = (Expr*)BitfieldWidth; 14072 SourceLocation Loc = DeclStart; 14073 if (II) Loc = D.getIdentifierLoc(); 14074 14075 // FIXME: Unnamed fields can be handled in various different ways, for 14076 // example, unnamed unions inject all members into the struct namespace! 14077 14078 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14079 QualType T = TInfo->getType(); 14080 14081 if (BitWidth) { 14082 // 6.7.2.1p3, 6.7.2.1p4 14083 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14084 if (!BitWidth) 14085 D.setInvalidType(); 14086 } else { 14087 // Not a bitfield. 14088 14089 // validate II. 14090 14091 } 14092 if (T->isReferenceType()) { 14093 Diag(Loc, diag::err_ivar_reference_type); 14094 D.setInvalidType(); 14095 } 14096 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14097 // than a variably modified type. 14098 else if (T->isVariablyModifiedType()) { 14099 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14100 D.setInvalidType(); 14101 } 14102 14103 // Get the visibility (access control) for this ivar. 14104 ObjCIvarDecl::AccessControl ac = 14105 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14106 : ObjCIvarDecl::None; 14107 // Must set ivar's DeclContext to its enclosing interface. 14108 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14109 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14110 return nullptr; 14111 ObjCContainerDecl *EnclosingContext; 14112 if (ObjCImplementationDecl *IMPDecl = 14113 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14114 if (LangOpts.ObjCRuntime.isFragile()) { 14115 // Case of ivar declared in an implementation. Context is that of its class. 14116 EnclosingContext = IMPDecl->getClassInterface(); 14117 assert(EnclosingContext && "Implementation has no class interface!"); 14118 } 14119 else 14120 EnclosingContext = EnclosingDecl; 14121 } else { 14122 if (ObjCCategoryDecl *CDecl = 14123 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14124 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14125 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14126 return nullptr; 14127 } 14128 } 14129 EnclosingContext = EnclosingDecl; 14130 } 14131 14132 // Construct the decl. 14133 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14134 DeclStart, Loc, II, T, 14135 TInfo, ac, (Expr *)BitfieldWidth); 14136 14137 if (II) { 14138 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14139 ForRedeclaration); 14140 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14141 && !isa<TagDecl>(PrevDecl)) { 14142 Diag(Loc, diag::err_duplicate_member) << II; 14143 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14144 NewID->setInvalidDecl(); 14145 } 14146 } 14147 14148 // Process attributes attached to the ivar. 14149 ProcessDeclAttributes(S, NewID, D); 14150 14151 if (D.isInvalidType()) 14152 NewID->setInvalidDecl(); 14153 14154 // In ARC, infer 'retaining' for ivars of retainable type. 14155 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14156 NewID->setInvalidDecl(); 14157 14158 if (D.getDeclSpec().isModulePrivateSpecified()) 14159 NewID->setModulePrivate(); 14160 14161 if (II) { 14162 // FIXME: When interfaces are DeclContexts, we'll need to add 14163 // these to the interface. 14164 S->AddDecl(NewID); 14165 IdResolver.AddDecl(NewID); 14166 } 14167 14168 if (LangOpts.ObjCRuntime.isNonFragile() && 14169 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14170 Diag(Loc, diag::warn_ivars_in_interface); 14171 14172 return NewID; 14173 } 14174 14175 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14176 /// class and class extensions. For every class \@interface and class 14177 /// extension \@interface, if the last ivar is a bitfield of any type, 14178 /// then add an implicit `char :0` ivar to the end of that interface. 14179 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14180 SmallVectorImpl<Decl *> &AllIvarDecls) { 14181 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14182 return; 14183 14184 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14185 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14186 14187 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14188 return; 14189 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14190 if (!ID) { 14191 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14192 if (!CD->IsClassExtension()) 14193 return; 14194 } 14195 // No need to add this to end of @implementation. 14196 else 14197 return; 14198 } 14199 // All conditions are met. Add a new bitfield to the tail end of ivars. 14200 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14201 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14202 14203 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14204 DeclLoc, DeclLoc, nullptr, 14205 Context.CharTy, 14206 Context.getTrivialTypeSourceInfo(Context.CharTy, 14207 DeclLoc), 14208 ObjCIvarDecl::Private, BW, 14209 true); 14210 AllIvarDecls.push_back(Ivar); 14211 } 14212 14213 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14214 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14215 SourceLocation RBrac, AttributeList *Attr) { 14216 assert(EnclosingDecl && "missing record or interface decl"); 14217 14218 // If this is an Objective-C @implementation or category and we have 14219 // new fields here we should reset the layout of the interface since 14220 // it will now change. 14221 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14222 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14223 switch (DC->getKind()) { 14224 default: break; 14225 case Decl::ObjCCategory: 14226 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14227 break; 14228 case Decl::ObjCImplementation: 14229 Context. 14230 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14231 break; 14232 } 14233 } 14234 14235 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14236 14237 // Start counting up the number of named members; make sure to include 14238 // members of anonymous structs and unions in the total. 14239 unsigned NumNamedMembers = 0; 14240 if (Record) { 14241 for (const auto *I : Record->decls()) { 14242 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14243 if (IFD->getDeclName()) 14244 ++NumNamedMembers; 14245 } 14246 } 14247 14248 // Verify that all the fields are okay. 14249 SmallVector<FieldDecl*, 32> RecFields; 14250 14251 bool ARCErrReported = false; 14252 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14253 i != end; ++i) { 14254 FieldDecl *FD = cast<FieldDecl>(*i); 14255 14256 // Get the type for the field. 14257 const Type *FDTy = FD->getType().getTypePtr(); 14258 14259 if (!FD->isAnonymousStructOrUnion()) { 14260 // Remember all fields written by the user. 14261 RecFields.push_back(FD); 14262 } 14263 14264 // If the field is already invalid for some reason, don't emit more 14265 // diagnostics about it. 14266 if (FD->isInvalidDecl()) { 14267 EnclosingDecl->setInvalidDecl(); 14268 continue; 14269 } 14270 14271 // C99 6.7.2.1p2: 14272 // A structure or union shall not contain a member with 14273 // incomplete or function type (hence, a structure shall not 14274 // contain an instance of itself, but may contain a pointer to 14275 // an instance of itself), except that the last member of a 14276 // structure with more than one named member may have incomplete 14277 // array type; such a structure (and any union containing, 14278 // possibly recursively, a member that is such a structure) 14279 // shall not be a member of a structure or an element of an 14280 // array. 14281 if (FDTy->isFunctionType()) { 14282 // Field declared as a function. 14283 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14284 << FD->getDeclName(); 14285 FD->setInvalidDecl(); 14286 EnclosingDecl->setInvalidDecl(); 14287 continue; 14288 } else if (FDTy->isIncompleteArrayType() && Record && 14289 ((i + 1 == Fields.end() && !Record->isUnion()) || 14290 ((getLangOpts().MicrosoftExt || 14291 getLangOpts().CPlusPlus) && 14292 (i + 1 == Fields.end() || Record->isUnion())))) { 14293 // Flexible array member. 14294 // Microsoft and g++ is more permissive regarding flexible array. 14295 // It will accept flexible array in union and also 14296 // as the sole element of a struct/class. 14297 unsigned DiagID = 0; 14298 if (Record->isUnion()) 14299 DiagID = getLangOpts().MicrosoftExt 14300 ? diag::ext_flexible_array_union_ms 14301 : getLangOpts().CPlusPlus 14302 ? diag::ext_flexible_array_union_gnu 14303 : diag::err_flexible_array_union; 14304 else if (NumNamedMembers < 1) 14305 DiagID = getLangOpts().MicrosoftExt 14306 ? diag::ext_flexible_array_empty_aggregate_ms 14307 : getLangOpts().CPlusPlus 14308 ? diag::ext_flexible_array_empty_aggregate_gnu 14309 : diag::err_flexible_array_empty_aggregate; 14310 14311 if (DiagID) 14312 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14313 << Record->getTagKind(); 14314 // While the layout of types that contain virtual bases is not specified 14315 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14316 // virtual bases after the derived members. This would make a flexible 14317 // array member declared at the end of an object not adjacent to the end 14318 // of the type. 14319 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14320 if (RD->getNumVBases() != 0) 14321 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14322 << FD->getDeclName() << Record->getTagKind(); 14323 if (!getLangOpts().C99) 14324 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14325 << FD->getDeclName() << Record->getTagKind(); 14326 14327 // If the element type has a non-trivial destructor, we would not 14328 // implicitly destroy the elements, so disallow it for now. 14329 // 14330 // FIXME: GCC allows this. We should probably either implicitly delete 14331 // the destructor of the containing class, or just allow this. 14332 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14333 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14334 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14335 << FD->getDeclName() << FD->getType(); 14336 FD->setInvalidDecl(); 14337 EnclosingDecl->setInvalidDecl(); 14338 continue; 14339 } 14340 // Okay, we have a legal flexible array member at the end of the struct. 14341 Record->setHasFlexibleArrayMember(true); 14342 } else if (!FDTy->isDependentType() && 14343 RequireCompleteType(FD->getLocation(), FD->getType(), 14344 diag::err_field_incomplete)) { 14345 // Incomplete type 14346 FD->setInvalidDecl(); 14347 EnclosingDecl->setInvalidDecl(); 14348 continue; 14349 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14350 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14351 // A type which contains a flexible array member is considered to be a 14352 // flexible array member. 14353 Record->setHasFlexibleArrayMember(true); 14354 if (!Record->isUnion()) { 14355 // If this is a struct/class and this is not the last element, reject 14356 // it. Note that GCC supports variable sized arrays in the middle of 14357 // structures. 14358 if (i + 1 != Fields.end()) 14359 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14360 << FD->getDeclName() << FD->getType(); 14361 else { 14362 // We support flexible arrays at the end of structs in 14363 // other structs as an extension. 14364 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14365 << FD->getDeclName(); 14366 } 14367 } 14368 } 14369 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14370 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14371 diag::err_abstract_type_in_decl, 14372 AbstractIvarType)) { 14373 // Ivars can not have abstract class types 14374 FD->setInvalidDecl(); 14375 } 14376 if (Record && FDTTy->getDecl()->hasObjectMember()) 14377 Record->setHasObjectMember(true); 14378 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14379 Record->setHasVolatileMember(true); 14380 } else if (FDTy->isObjCObjectType()) { 14381 /// A field cannot be an Objective-c object 14382 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14383 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14384 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14385 FD->setType(T); 14386 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14387 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14388 // It's an error in ARC if a field has lifetime. 14389 // We don't want to report this in a system header, though, 14390 // so we just make the field unavailable. 14391 // FIXME: that's really not sufficient; we need to make the type 14392 // itself invalid to, say, initialize or copy. 14393 QualType T = FD->getType(); 14394 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14395 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14396 SourceLocation loc = FD->getLocation(); 14397 if (getSourceManager().isInSystemHeader(loc)) { 14398 if (!FD->hasAttr<UnavailableAttr>()) { 14399 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14400 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14401 } 14402 } else { 14403 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14404 << T->isBlockPointerType() << Record->getTagKind(); 14405 } 14406 ARCErrReported = true; 14407 } 14408 } else if (getLangOpts().ObjC1 && 14409 getLangOpts().getGC() != LangOptions::NonGC && 14410 Record && !Record->hasObjectMember()) { 14411 if (FD->getType()->isObjCObjectPointerType() || 14412 FD->getType().isObjCGCStrong()) 14413 Record->setHasObjectMember(true); 14414 else if (Context.getAsArrayType(FD->getType())) { 14415 QualType BaseType = Context.getBaseElementType(FD->getType()); 14416 if (BaseType->isRecordType() && 14417 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14418 Record->setHasObjectMember(true); 14419 else if (BaseType->isObjCObjectPointerType() || 14420 BaseType.isObjCGCStrong()) 14421 Record->setHasObjectMember(true); 14422 } 14423 } 14424 if (Record && FD->getType().isVolatileQualified()) 14425 Record->setHasVolatileMember(true); 14426 // Keep track of the number of named members. 14427 if (FD->getIdentifier()) 14428 ++NumNamedMembers; 14429 } 14430 14431 // Okay, we successfully defined 'Record'. 14432 if (Record) { 14433 bool Completed = false; 14434 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14435 if (!CXXRecord->isInvalidDecl()) { 14436 // Set access bits correctly on the directly-declared conversions. 14437 for (CXXRecordDecl::conversion_iterator 14438 I = CXXRecord->conversion_begin(), 14439 E = CXXRecord->conversion_end(); I != E; ++I) 14440 I.setAccess((*I)->getAccess()); 14441 } 14442 14443 if (!CXXRecord->isDependentType()) { 14444 if (CXXRecord->hasUserDeclaredDestructor()) { 14445 // Adjust user-defined destructor exception spec. 14446 if (getLangOpts().CPlusPlus11) 14447 AdjustDestructorExceptionSpec(CXXRecord, 14448 CXXRecord->getDestructor()); 14449 } 14450 14451 if (!CXXRecord->isInvalidDecl()) { 14452 // Add any implicitly-declared members to this class. 14453 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14454 14455 // If we have virtual base classes, we may end up finding multiple 14456 // final overriders for a given virtual function. Check for this 14457 // problem now. 14458 if (CXXRecord->getNumVBases()) { 14459 CXXFinalOverriderMap FinalOverriders; 14460 CXXRecord->getFinalOverriders(FinalOverriders); 14461 14462 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14463 MEnd = FinalOverriders.end(); 14464 M != MEnd; ++M) { 14465 for (OverridingMethods::iterator SO = M->second.begin(), 14466 SOEnd = M->second.end(); 14467 SO != SOEnd; ++SO) { 14468 assert(SO->second.size() > 0 && 14469 "Virtual function without overridding functions?"); 14470 if (SO->second.size() == 1) 14471 continue; 14472 14473 // C++ [class.virtual]p2: 14474 // In a derived class, if a virtual member function of a base 14475 // class subobject has more than one final overrider the 14476 // program is ill-formed. 14477 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14478 << (const NamedDecl *)M->first << Record; 14479 Diag(M->first->getLocation(), 14480 diag::note_overridden_virtual_function); 14481 for (OverridingMethods::overriding_iterator 14482 OM = SO->second.begin(), 14483 OMEnd = SO->second.end(); 14484 OM != OMEnd; ++OM) 14485 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14486 << (const NamedDecl *)M->first << OM->Method->getParent(); 14487 14488 Record->setInvalidDecl(); 14489 } 14490 } 14491 CXXRecord->completeDefinition(&FinalOverriders); 14492 Completed = true; 14493 } 14494 } 14495 } 14496 } 14497 14498 if (!Completed) 14499 Record->completeDefinition(); 14500 14501 // We may have deferred checking for a deleted destructor. Check now. 14502 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14503 auto *Dtor = CXXRecord->getDestructor(); 14504 if (Dtor && Dtor->isImplicit() && 14505 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14506 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14507 } 14508 14509 if (Record->hasAttrs()) { 14510 CheckAlignasUnderalignment(Record); 14511 14512 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14513 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14514 IA->getRange(), IA->getBestCase(), 14515 IA->getSemanticSpelling()); 14516 } 14517 14518 // Check if the structure/union declaration is a type that can have zero 14519 // size in C. For C this is a language extension, for C++ it may cause 14520 // compatibility problems. 14521 bool CheckForZeroSize; 14522 if (!getLangOpts().CPlusPlus) { 14523 CheckForZeroSize = true; 14524 } else { 14525 // For C++ filter out types that cannot be referenced in C code. 14526 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14527 CheckForZeroSize = 14528 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14529 !CXXRecord->isDependentType() && 14530 CXXRecord->isCLike(); 14531 } 14532 if (CheckForZeroSize) { 14533 bool ZeroSize = true; 14534 bool IsEmpty = true; 14535 unsigned NonBitFields = 0; 14536 for (RecordDecl::field_iterator I = Record->field_begin(), 14537 E = Record->field_end(); 14538 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14539 IsEmpty = false; 14540 if (I->isUnnamedBitfield()) { 14541 if (I->getBitWidthValue(Context) > 0) 14542 ZeroSize = false; 14543 } else { 14544 ++NonBitFields; 14545 QualType FieldType = I->getType(); 14546 if (FieldType->isIncompleteType() || 14547 !Context.getTypeSizeInChars(FieldType).isZero()) 14548 ZeroSize = false; 14549 } 14550 } 14551 14552 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14553 // allowed in C++, but warn if its declaration is inside 14554 // extern "C" block. 14555 if (ZeroSize) { 14556 Diag(RecLoc, getLangOpts().CPlusPlus ? 14557 diag::warn_zero_size_struct_union_in_extern_c : 14558 diag::warn_zero_size_struct_union_compat) 14559 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14560 } 14561 14562 // Structs without named members are extension in C (C99 6.7.2.1p7), 14563 // but are accepted by GCC. 14564 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14565 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14566 diag::ext_no_named_members_in_struct_union) 14567 << Record->isUnion(); 14568 } 14569 } 14570 } else { 14571 ObjCIvarDecl **ClsFields = 14572 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14573 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14574 ID->setEndOfDefinitionLoc(RBrac); 14575 // Add ivar's to class's DeclContext. 14576 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14577 ClsFields[i]->setLexicalDeclContext(ID); 14578 ID->addDecl(ClsFields[i]); 14579 } 14580 // Must enforce the rule that ivars in the base classes may not be 14581 // duplicates. 14582 if (ID->getSuperClass()) 14583 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14584 } else if (ObjCImplementationDecl *IMPDecl = 14585 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14586 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14587 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14588 // Ivar declared in @implementation never belongs to the implementation. 14589 // Only it is in implementation's lexical context. 14590 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14591 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14592 IMPDecl->setIvarLBraceLoc(LBrac); 14593 IMPDecl->setIvarRBraceLoc(RBrac); 14594 } else if (ObjCCategoryDecl *CDecl = 14595 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14596 // case of ivars in class extension; all other cases have been 14597 // reported as errors elsewhere. 14598 // FIXME. Class extension does not have a LocEnd field. 14599 // CDecl->setLocEnd(RBrac); 14600 // Add ivar's to class extension's DeclContext. 14601 // Diagnose redeclaration of private ivars. 14602 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14603 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14604 if (IDecl) { 14605 if (const ObjCIvarDecl *ClsIvar = 14606 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14607 Diag(ClsFields[i]->getLocation(), 14608 diag::err_duplicate_ivar_declaration); 14609 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14610 continue; 14611 } 14612 for (const auto *Ext : IDecl->known_extensions()) { 14613 if (const ObjCIvarDecl *ClsExtIvar 14614 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14615 Diag(ClsFields[i]->getLocation(), 14616 diag::err_duplicate_ivar_declaration); 14617 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14618 continue; 14619 } 14620 } 14621 } 14622 ClsFields[i]->setLexicalDeclContext(CDecl); 14623 CDecl->addDecl(ClsFields[i]); 14624 } 14625 CDecl->setIvarLBraceLoc(LBrac); 14626 CDecl->setIvarRBraceLoc(RBrac); 14627 } 14628 } 14629 14630 if (Attr) 14631 ProcessDeclAttributeList(S, Record, Attr); 14632 } 14633 14634 /// \brief Determine whether the given integral value is representable within 14635 /// the given type T. 14636 static bool isRepresentableIntegerValue(ASTContext &Context, 14637 llvm::APSInt &Value, 14638 QualType T) { 14639 assert(T->isIntegralType(Context) && "Integral type required!"); 14640 unsigned BitWidth = Context.getIntWidth(T); 14641 14642 if (Value.isUnsigned() || Value.isNonNegative()) { 14643 if (T->isSignedIntegerOrEnumerationType()) 14644 --BitWidth; 14645 return Value.getActiveBits() <= BitWidth; 14646 } 14647 return Value.getMinSignedBits() <= BitWidth; 14648 } 14649 14650 // \brief Given an integral type, return the next larger integral type 14651 // (or a NULL type of no such type exists). 14652 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14653 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14654 // enum checking below. 14655 assert(T->isIntegralType(Context) && "Integral type required!"); 14656 const unsigned NumTypes = 4; 14657 QualType SignedIntegralTypes[NumTypes] = { 14658 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14659 }; 14660 QualType UnsignedIntegralTypes[NumTypes] = { 14661 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14662 Context.UnsignedLongLongTy 14663 }; 14664 14665 unsigned BitWidth = Context.getTypeSize(T); 14666 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14667 : UnsignedIntegralTypes; 14668 for (unsigned I = 0; I != NumTypes; ++I) 14669 if (Context.getTypeSize(Types[I]) > BitWidth) 14670 return Types[I]; 14671 14672 return QualType(); 14673 } 14674 14675 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14676 EnumConstantDecl *LastEnumConst, 14677 SourceLocation IdLoc, 14678 IdentifierInfo *Id, 14679 Expr *Val) { 14680 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14681 llvm::APSInt EnumVal(IntWidth); 14682 QualType EltTy; 14683 14684 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14685 Val = nullptr; 14686 14687 if (Val) 14688 Val = DefaultLvalueConversion(Val).get(); 14689 14690 if (Val) { 14691 if (Enum->isDependentType() || Val->isTypeDependent()) 14692 EltTy = Context.DependentTy; 14693 else { 14694 SourceLocation ExpLoc; 14695 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14696 !getLangOpts().MSVCCompat) { 14697 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14698 // constant-expression in the enumerator-definition shall be a converted 14699 // constant expression of the underlying type. 14700 EltTy = Enum->getIntegerType(); 14701 ExprResult Converted = 14702 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14703 CCEK_Enumerator); 14704 if (Converted.isInvalid()) 14705 Val = nullptr; 14706 else 14707 Val = Converted.get(); 14708 } else if (!Val->isValueDependent() && 14709 !(Val = VerifyIntegerConstantExpression(Val, 14710 &EnumVal).get())) { 14711 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14712 } else { 14713 if (Enum->isFixed()) { 14714 EltTy = Enum->getIntegerType(); 14715 14716 // In Obj-C and Microsoft mode, require the enumeration value to be 14717 // representable in the underlying type of the enumeration. In C++11, 14718 // we perform a non-narrowing conversion as part of converted constant 14719 // expression checking. 14720 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14721 if (getLangOpts().MSVCCompat) { 14722 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14723 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14724 } else 14725 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14726 } else 14727 Val = ImpCastExprToType(Val, EltTy, 14728 EltTy->isBooleanType() ? 14729 CK_IntegralToBoolean : CK_IntegralCast) 14730 .get(); 14731 } else if (getLangOpts().CPlusPlus) { 14732 // C++11 [dcl.enum]p5: 14733 // If the underlying type is not fixed, the type of each enumerator 14734 // is the type of its initializing value: 14735 // - If an initializer is specified for an enumerator, the 14736 // initializing value has the same type as the expression. 14737 EltTy = Val->getType(); 14738 } else { 14739 // C99 6.7.2.2p2: 14740 // The expression that defines the value of an enumeration constant 14741 // shall be an integer constant expression that has a value 14742 // representable as an int. 14743 14744 // Complain if the value is not representable in an int. 14745 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14746 Diag(IdLoc, diag::ext_enum_value_not_int) 14747 << EnumVal.toString(10) << Val->getSourceRange() 14748 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14749 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14750 // Force the type of the expression to 'int'. 14751 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14752 } 14753 EltTy = Val->getType(); 14754 } 14755 } 14756 } 14757 } 14758 14759 if (!Val) { 14760 if (Enum->isDependentType()) 14761 EltTy = Context.DependentTy; 14762 else if (!LastEnumConst) { 14763 // C++0x [dcl.enum]p5: 14764 // If the underlying type is not fixed, the type of each enumerator 14765 // is the type of its initializing value: 14766 // - If no initializer is specified for the first enumerator, the 14767 // initializing value has an unspecified integral type. 14768 // 14769 // GCC uses 'int' for its unspecified integral type, as does 14770 // C99 6.7.2.2p3. 14771 if (Enum->isFixed()) { 14772 EltTy = Enum->getIntegerType(); 14773 } 14774 else { 14775 EltTy = Context.IntTy; 14776 } 14777 } else { 14778 // Assign the last value + 1. 14779 EnumVal = LastEnumConst->getInitVal(); 14780 ++EnumVal; 14781 EltTy = LastEnumConst->getType(); 14782 14783 // Check for overflow on increment. 14784 if (EnumVal < LastEnumConst->getInitVal()) { 14785 // C++0x [dcl.enum]p5: 14786 // If the underlying type is not fixed, the type of each enumerator 14787 // is the type of its initializing value: 14788 // 14789 // - Otherwise the type of the initializing value is the same as 14790 // the type of the initializing value of the preceding enumerator 14791 // unless the incremented value is not representable in that type, 14792 // in which case the type is an unspecified integral type 14793 // sufficient to contain the incremented value. If no such type 14794 // exists, the program is ill-formed. 14795 QualType T = getNextLargerIntegralType(Context, EltTy); 14796 if (T.isNull() || Enum->isFixed()) { 14797 // There is no integral type larger enough to represent this 14798 // value. Complain, then allow the value to wrap around. 14799 EnumVal = LastEnumConst->getInitVal(); 14800 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14801 ++EnumVal; 14802 if (Enum->isFixed()) 14803 // When the underlying type is fixed, this is ill-formed. 14804 Diag(IdLoc, diag::err_enumerator_wrapped) 14805 << EnumVal.toString(10) 14806 << EltTy; 14807 else 14808 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14809 << EnumVal.toString(10); 14810 } else { 14811 EltTy = T; 14812 } 14813 14814 // Retrieve the last enumerator's value, extent that type to the 14815 // type that is supposed to be large enough to represent the incremented 14816 // value, then increment. 14817 EnumVal = LastEnumConst->getInitVal(); 14818 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14819 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14820 ++EnumVal; 14821 14822 // If we're not in C++, diagnose the overflow of enumerator values, 14823 // which in C99 means that the enumerator value is not representable in 14824 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14825 // permits enumerator values that are representable in some larger 14826 // integral type. 14827 if (!getLangOpts().CPlusPlus && !T.isNull()) 14828 Diag(IdLoc, diag::warn_enum_value_overflow); 14829 } else if (!getLangOpts().CPlusPlus && 14830 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14831 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14832 Diag(IdLoc, diag::ext_enum_value_not_int) 14833 << EnumVal.toString(10) << 1; 14834 } 14835 } 14836 } 14837 14838 if (!EltTy->isDependentType()) { 14839 // Make the enumerator value match the signedness and size of the 14840 // enumerator's type. 14841 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14842 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14843 } 14844 14845 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14846 Val, EnumVal); 14847 } 14848 14849 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14850 SourceLocation IILoc) { 14851 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14852 !getLangOpts().CPlusPlus) 14853 return SkipBodyInfo(); 14854 14855 // We have an anonymous enum definition. Look up the first enumerator to 14856 // determine if we should merge the definition with an existing one and 14857 // skip the body. 14858 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14859 ForRedeclaration); 14860 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14861 if (!PrevECD) 14862 return SkipBodyInfo(); 14863 14864 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14865 NamedDecl *Hidden; 14866 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14867 SkipBodyInfo Skip; 14868 Skip.Previous = Hidden; 14869 return Skip; 14870 } 14871 14872 return SkipBodyInfo(); 14873 } 14874 14875 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14876 SourceLocation IdLoc, IdentifierInfo *Id, 14877 AttributeList *Attr, 14878 SourceLocation EqualLoc, Expr *Val) { 14879 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14880 EnumConstantDecl *LastEnumConst = 14881 cast_or_null<EnumConstantDecl>(lastEnumConst); 14882 14883 // The scope passed in may not be a decl scope. Zip up the scope tree until 14884 // we find one that is. 14885 S = getNonFieldDeclScope(S); 14886 14887 // Verify that there isn't already something declared with this name in this 14888 // scope. 14889 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14890 ForRedeclaration); 14891 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14892 // Maybe we will complain about the shadowed template parameter. 14893 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14894 // Just pretend that we didn't see the previous declaration. 14895 PrevDecl = nullptr; 14896 } 14897 14898 // C++ [class.mem]p15: 14899 // If T is the name of a class, then each of the following shall have a name 14900 // different from T: 14901 // - every enumerator of every member of class T that is an unscoped 14902 // enumerated type 14903 if (!TheEnumDecl->isScoped()) 14904 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14905 DeclarationNameInfo(Id, IdLoc)); 14906 14907 EnumConstantDecl *New = 14908 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14909 if (!New) 14910 return nullptr; 14911 14912 if (PrevDecl) { 14913 // When in C++, we may get a TagDecl with the same name; in this case the 14914 // enum constant will 'hide' the tag. 14915 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14916 "Received TagDecl when not in C++!"); 14917 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14918 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14919 if (isa<EnumConstantDecl>(PrevDecl)) 14920 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14921 else 14922 Diag(IdLoc, diag::err_redefinition) << Id; 14923 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14924 return nullptr; 14925 } 14926 } 14927 14928 // Process attributes. 14929 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14930 14931 // Register this decl in the current scope stack. 14932 New->setAccess(TheEnumDecl->getAccess()); 14933 PushOnScopeChains(New, S); 14934 14935 ActOnDocumentableDecl(New); 14936 14937 return New; 14938 } 14939 14940 // Returns true when the enum initial expression does not trigger the 14941 // duplicate enum warning. A few common cases are exempted as follows: 14942 // Element2 = Element1 14943 // Element2 = Element1 + 1 14944 // Element2 = Element1 - 1 14945 // Where Element2 and Element1 are from the same enum. 14946 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14947 Expr *InitExpr = ECD->getInitExpr(); 14948 if (!InitExpr) 14949 return true; 14950 InitExpr = InitExpr->IgnoreImpCasts(); 14951 14952 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14953 if (!BO->isAdditiveOp()) 14954 return true; 14955 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14956 if (!IL) 14957 return true; 14958 if (IL->getValue() != 1) 14959 return true; 14960 14961 InitExpr = BO->getLHS(); 14962 } 14963 14964 // This checks if the elements are from the same enum. 14965 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14966 if (!DRE) 14967 return true; 14968 14969 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14970 if (!EnumConstant) 14971 return true; 14972 14973 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14974 Enum) 14975 return true; 14976 14977 return false; 14978 } 14979 14980 namespace { 14981 struct DupKey { 14982 int64_t val; 14983 bool isTombstoneOrEmptyKey; 14984 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14985 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14986 }; 14987 14988 static DupKey GetDupKey(const llvm::APSInt& Val) { 14989 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14990 false); 14991 } 14992 14993 struct DenseMapInfoDupKey { 14994 static DupKey getEmptyKey() { return DupKey(0, true); } 14995 static DupKey getTombstoneKey() { return DupKey(1, true); } 14996 static unsigned getHashValue(const DupKey Key) { 14997 return (unsigned)(Key.val * 37); 14998 } 14999 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15000 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15001 LHS.val == RHS.val; 15002 } 15003 }; 15004 } // end anonymous namespace 15005 15006 // Emits a warning when an element is implicitly set a value that 15007 // a previous element has already been set to. 15008 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15009 EnumDecl *Enum, 15010 QualType EnumType) { 15011 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15012 return; 15013 // Avoid anonymous enums 15014 if (!Enum->getIdentifier()) 15015 return; 15016 15017 // Only check for small enums. 15018 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15019 return; 15020 15021 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15022 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15023 15024 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15025 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15026 ValueToVectorMap; 15027 15028 DuplicatesVector DupVector; 15029 ValueToVectorMap EnumMap; 15030 15031 // Populate the EnumMap with all values represented by enum constants without 15032 // an initialier. 15033 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15034 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15035 15036 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15037 // this constant. Skip this enum since it may be ill-formed. 15038 if (!ECD) { 15039 return; 15040 } 15041 15042 if (ECD->getInitExpr()) 15043 continue; 15044 15045 DupKey Key = GetDupKey(ECD->getInitVal()); 15046 DeclOrVector &Entry = EnumMap[Key]; 15047 15048 // First time encountering this value. 15049 if (Entry.isNull()) 15050 Entry = ECD; 15051 } 15052 15053 // Create vectors for any values that has duplicates. 15054 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15055 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15056 if (!ValidDuplicateEnum(ECD, Enum)) 15057 continue; 15058 15059 DupKey Key = GetDupKey(ECD->getInitVal()); 15060 15061 DeclOrVector& Entry = EnumMap[Key]; 15062 if (Entry.isNull()) 15063 continue; 15064 15065 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15066 // Ensure constants are different. 15067 if (D == ECD) 15068 continue; 15069 15070 // Create new vector and push values onto it. 15071 ECDVector *Vec = new ECDVector(); 15072 Vec->push_back(D); 15073 Vec->push_back(ECD); 15074 15075 // Update entry to point to the duplicates vector. 15076 Entry = Vec; 15077 15078 // Store the vector somewhere we can consult later for quick emission of 15079 // diagnostics. 15080 DupVector.push_back(Vec); 15081 continue; 15082 } 15083 15084 ECDVector *Vec = Entry.get<ECDVector*>(); 15085 // Make sure constants are not added more than once. 15086 if (*Vec->begin() == ECD) 15087 continue; 15088 15089 Vec->push_back(ECD); 15090 } 15091 15092 // Emit diagnostics. 15093 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15094 DupVectorEnd = DupVector.end(); 15095 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15096 ECDVector *Vec = *DupVectorIter; 15097 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15098 15099 // Emit warning for one enum constant. 15100 ECDVector::iterator I = Vec->begin(); 15101 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15102 << (*I)->getName() << (*I)->getInitVal().toString(10) 15103 << (*I)->getSourceRange(); 15104 ++I; 15105 15106 // Emit one note for each of the remaining enum constants with 15107 // the same value. 15108 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15109 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15110 << (*I)->getName() << (*I)->getInitVal().toString(10) 15111 << (*I)->getSourceRange(); 15112 delete Vec; 15113 } 15114 } 15115 15116 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15117 bool AllowMask) const { 15118 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 15119 assert(ED->isCompleteDefinition() && "expected enum definition"); 15120 15121 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15122 llvm::APInt &FlagBits = R.first->second; 15123 15124 if (R.second) { 15125 for (auto *E : ED->enumerators()) { 15126 const auto &EVal = E->getInitVal(); 15127 // Only single-bit enumerators introduce new flag values. 15128 if (EVal.isPowerOf2()) 15129 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15130 } 15131 } 15132 15133 // A value is in a flag enum if either its bits are a subset of the enum's 15134 // flag bits (the first condition) or we are allowing masks and the same is 15135 // true of its complement (the second condition). When masks are allowed, we 15136 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15137 // 15138 // While it's true that any value could be used as a mask, the assumption is 15139 // that a mask will have all of the insignificant bits set. Anything else is 15140 // likely a logic error. 15141 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15142 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15143 } 15144 15145 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15146 Decl *EnumDeclX, 15147 ArrayRef<Decl *> Elements, 15148 Scope *S, AttributeList *Attr) { 15149 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15150 QualType EnumType = Context.getTypeDeclType(Enum); 15151 15152 if (Attr) 15153 ProcessDeclAttributeList(S, Enum, Attr); 15154 15155 if (Enum->isDependentType()) { 15156 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15157 EnumConstantDecl *ECD = 15158 cast_or_null<EnumConstantDecl>(Elements[i]); 15159 if (!ECD) continue; 15160 15161 ECD->setType(EnumType); 15162 } 15163 15164 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15165 return; 15166 } 15167 15168 // TODO: If the result value doesn't fit in an int, it must be a long or long 15169 // long value. ISO C does not support this, but GCC does as an extension, 15170 // emit a warning. 15171 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15172 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15173 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15174 15175 // Verify that all the values are okay, compute the size of the values, and 15176 // reverse the list. 15177 unsigned NumNegativeBits = 0; 15178 unsigned NumPositiveBits = 0; 15179 15180 // Keep track of whether all elements have type int. 15181 bool AllElementsInt = true; 15182 15183 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15184 EnumConstantDecl *ECD = 15185 cast_or_null<EnumConstantDecl>(Elements[i]); 15186 if (!ECD) continue; // Already issued a diagnostic. 15187 15188 const llvm::APSInt &InitVal = ECD->getInitVal(); 15189 15190 // Keep track of the size of positive and negative values. 15191 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15192 NumPositiveBits = std::max(NumPositiveBits, 15193 (unsigned)InitVal.getActiveBits()); 15194 else 15195 NumNegativeBits = std::max(NumNegativeBits, 15196 (unsigned)InitVal.getMinSignedBits()); 15197 15198 // Keep track of whether every enum element has type int (very commmon). 15199 if (AllElementsInt) 15200 AllElementsInt = ECD->getType() == Context.IntTy; 15201 } 15202 15203 // Figure out the type that should be used for this enum. 15204 QualType BestType; 15205 unsigned BestWidth; 15206 15207 // C++0x N3000 [conv.prom]p3: 15208 // An rvalue of an unscoped enumeration type whose underlying 15209 // type is not fixed can be converted to an rvalue of the first 15210 // of the following types that can represent all the values of 15211 // the enumeration: int, unsigned int, long int, unsigned long 15212 // int, long long int, or unsigned long long int. 15213 // C99 6.4.4.3p2: 15214 // An identifier declared as an enumeration constant has type int. 15215 // The C99 rule is modified by a gcc extension 15216 QualType BestPromotionType; 15217 15218 bool Packed = Enum->hasAttr<PackedAttr>(); 15219 // -fshort-enums is the equivalent to specifying the packed attribute on all 15220 // enum definitions. 15221 if (LangOpts.ShortEnums) 15222 Packed = true; 15223 15224 if (Enum->isFixed()) { 15225 BestType = Enum->getIntegerType(); 15226 if (BestType->isPromotableIntegerType()) 15227 BestPromotionType = Context.getPromotedIntegerType(BestType); 15228 else 15229 BestPromotionType = BestType; 15230 15231 BestWidth = Context.getIntWidth(BestType); 15232 } 15233 else if (NumNegativeBits) { 15234 // If there is a negative value, figure out the smallest integer type (of 15235 // int/long/longlong) that fits. 15236 // If it's packed, check also if it fits a char or a short. 15237 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15238 BestType = Context.SignedCharTy; 15239 BestWidth = CharWidth; 15240 } else if (Packed && NumNegativeBits <= ShortWidth && 15241 NumPositiveBits < ShortWidth) { 15242 BestType = Context.ShortTy; 15243 BestWidth = ShortWidth; 15244 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15245 BestType = Context.IntTy; 15246 BestWidth = IntWidth; 15247 } else { 15248 BestWidth = Context.getTargetInfo().getLongWidth(); 15249 15250 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15251 BestType = Context.LongTy; 15252 } else { 15253 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15254 15255 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15256 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15257 BestType = Context.LongLongTy; 15258 } 15259 } 15260 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15261 } else { 15262 // If there is no negative value, figure out the smallest type that fits 15263 // all of the enumerator values. 15264 // If it's packed, check also if it fits a char or a short. 15265 if (Packed && NumPositiveBits <= CharWidth) { 15266 BestType = Context.UnsignedCharTy; 15267 BestPromotionType = Context.IntTy; 15268 BestWidth = CharWidth; 15269 } else if (Packed && NumPositiveBits <= ShortWidth) { 15270 BestType = Context.UnsignedShortTy; 15271 BestPromotionType = Context.IntTy; 15272 BestWidth = ShortWidth; 15273 } else if (NumPositiveBits <= IntWidth) { 15274 BestType = Context.UnsignedIntTy; 15275 BestWidth = IntWidth; 15276 BestPromotionType 15277 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15278 ? Context.UnsignedIntTy : Context.IntTy; 15279 } else if (NumPositiveBits <= 15280 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15281 BestType = Context.UnsignedLongTy; 15282 BestPromotionType 15283 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15284 ? Context.UnsignedLongTy : Context.LongTy; 15285 } else { 15286 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15287 assert(NumPositiveBits <= BestWidth && 15288 "How could an initializer get larger than ULL?"); 15289 BestType = Context.UnsignedLongLongTy; 15290 BestPromotionType 15291 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15292 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15293 } 15294 } 15295 15296 // Loop over all of the enumerator constants, changing their types to match 15297 // the type of the enum if needed. 15298 for (auto *D : Elements) { 15299 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15300 if (!ECD) continue; // Already issued a diagnostic. 15301 15302 // Standard C says the enumerators have int type, but we allow, as an 15303 // extension, the enumerators to be larger than int size. If each 15304 // enumerator value fits in an int, type it as an int, otherwise type it the 15305 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15306 // that X has type 'int', not 'unsigned'. 15307 15308 // Determine whether the value fits into an int. 15309 llvm::APSInt InitVal = ECD->getInitVal(); 15310 15311 // If it fits into an integer type, force it. Otherwise force it to match 15312 // the enum decl type. 15313 QualType NewTy; 15314 unsigned NewWidth; 15315 bool NewSign; 15316 if (!getLangOpts().CPlusPlus && 15317 !Enum->isFixed() && 15318 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15319 NewTy = Context.IntTy; 15320 NewWidth = IntWidth; 15321 NewSign = true; 15322 } else if (ECD->getType() == BestType) { 15323 // Already the right type! 15324 if (getLangOpts().CPlusPlus) 15325 // C++ [dcl.enum]p4: Following the closing brace of an 15326 // enum-specifier, each enumerator has the type of its 15327 // enumeration. 15328 ECD->setType(EnumType); 15329 continue; 15330 } else { 15331 NewTy = BestType; 15332 NewWidth = BestWidth; 15333 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15334 } 15335 15336 // Adjust the APSInt value. 15337 InitVal = InitVal.extOrTrunc(NewWidth); 15338 InitVal.setIsSigned(NewSign); 15339 ECD->setInitVal(InitVal); 15340 15341 // Adjust the Expr initializer and type. 15342 if (ECD->getInitExpr() && 15343 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15344 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15345 CK_IntegralCast, 15346 ECD->getInitExpr(), 15347 /*base paths*/ nullptr, 15348 VK_RValue)); 15349 if (getLangOpts().CPlusPlus) 15350 // C++ [dcl.enum]p4: Following the closing brace of an 15351 // enum-specifier, each enumerator has the type of its 15352 // enumeration. 15353 ECD->setType(EnumType); 15354 else 15355 ECD->setType(NewTy); 15356 } 15357 15358 Enum->completeDefinition(BestType, BestPromotionType, 15359 NumPositiveBits, NumNegativeBits); 15360 15361 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15362 15363 if (Enum->hasAttr<FlagEnumAttr>()) { 15364 for (Decl *D : Elements) { 15365 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15366 if (!ECD) continue; // Already issued a diagnostic. 15367 15368 llvm::APSInt InitVal = ECD->getInitVal(); 15369 if (InitVal != 0 && !InitVal.isPowerOf2() && 15370 !IsValueInFlagEnum(Enum, InitVal, true)) 15371 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15372 << ECD << Enum; 15373 } 15374 } 15375 15376 // Now that the enum type is defined, ensure it's not been underaligned. 15377 if (Enum->hasAttrs()) 15378 CheckAlignasUnderalignment(Enum); 15379 } 15380 15381 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15382 SourceLocation StartLoc, 15383 SourceLocation EndLoc) { 15384 StringLiteral *AsmString = cast<StringLiteral>(expr); 15385 15386 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15387 AsmString, StartLoc, 15388 EndLoc); 15389 CurContext->addDecl(New); 15390 return New; 15391 } 15392 15393 static void checkModuleImportContext(Sema &S, Module *M, 15394 SourceLocation ImportLoc, DeclContext *DC, 15395 bool FromInclude = false) { 15396 SourceLocation ExternCLoc; 15397 15398 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15399 switch (LSD->getLanguage()) { 15400 case LinkageSpecDecl::lang_c: 15401 if (ExternCLoc.isInvalid()) 15402 ExternCLoc = LSD->getLocStart(); 15403 break; 15404 case LinkageSpecDecl::lang_cxx: 15405 break; 15406 } 15407 DC = LSD->getParent(); 15408 } 15409 15410 while (isa<LinkageSpecDecl>(DC)) 15411 DC = DC->getParent(); 15412 15413 if (!isa<TranslationUnitDecl>(DC)) { 15414 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15415 ? diag::ext_module_import_not_at_top_level_noop 15416 : diag::err_module_import_not_at_top_level_fatal) 15417 << M->getFullModuleName() << DC; 15418 S.Diag(cast<Decl>(DC)->getLocStart(), 15419 diag::note_module_import_not_at_top_level) << DC; 15420 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15421 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15422 << M->getFullModuleName(); 15423 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15424 } 15425 } 15426 15427 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 15428 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 15429 } 15430 15431 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15432 ModuleDeclKind MDK, 15433 ModuleIdPath Path) { 15434 // 'module implementation' requires that we are not compiling a module of any 15435 // kind. 'module' and 'module partition' require that we are compiling a 15436 // module inteface (not a module map). 15437 auto CMK = getLangOpts().getCompilingModule(); 15438 if (MDK == ModuleDeclKind::Implementation 15439 ? CMK != LangOptions::CMK_None 15440 : CMK != LangOptions::CMK_ModuleInterface) { 15441 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15442 << (unsigned)MDK; 15443 return nullptr; 15444 } 15445 15446 // FIXME: Create a ModuleDecl and return it. 15447 15448 // FIXME: Most of this work should be done by the preprocessor rather than 15449 // here, in case we look ahead across something where the current 15450 // module matters (eg a #include). 15451 15452 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15453 // hierarchical module map modules, the dots here are just another character 15454 // that can appear in a module name. Flatten down to the actual module name. 15455 std::string ModuleName; 15456 for (auto &Piece : Path) { 15457 if (!ModuleName.empty()) 15458 ModuleName += "."; 15459 ModuleName += Piece.first->getName(); 15460 } 15461 15462 // If a module name was explicitly specified on the command line, it must be 15463 // correct. 15464 if (!getLangOpts().CurrentModule.empty() && 15465 getLangOpts().CurrentModule != ModuleName) { 15466 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15467 << SourceRange(Path.front().second, Path.back().second) 15468 << getLangOpts().CurrentModule; 15469 return nullptr; 15470 } 15471 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15472 15473 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15474 15475 switch (MDK) { 15476 case ModuleDeclKind::Module: { 15477 // FIXME: Check we're not in a submodule. 15478 15479 // We can't have imported a definition of this module or parsed a module 15480 // map defining it already. 15481 if (auto *M = Map.findModule(ModuleName)) { 15482 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15483 if (M->DefinitionLoc.isValid()) 15484 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15485 else if (const auto *FE = M->getASTFile()) 15486 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15487 << FE->getName(); 15488 return nullptr; 15489 } 15490 15491 // Create a Module for the module that we're defining. 15492 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15493 assert(Mod && "module creation should not fail"); 15494 15495 // Enter the semantic scope of the module. 15496 ActOnModuleBegin(ModuleLoc, Mod); 15497 return nullptr; 15498 } 15499 15500 case ModuleDeclKind::Partition: 15501 // FIXME: Check we are in a submodule of the named module. 15502 return nullptr; 15503 15504 case ModuleDeclKind::Implementation: 15505 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15506 PP.getIdentifierInfo(ModuleName), Path[0].second); 15507 15508 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15509 if (Import.isInvalid()) 15510 return nullptr; 15511 return ConvertDeclToDeclGroup(Import.get()); 15512 } 15513 15514 llvm_unreachable("unexpected module decl kind"); 15515 } 15516 15517 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15518 SourceLocation ImportLoc, 15519 ModuleIdPath Path) { 15520 Module *Mod = 15521 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15522 /*IsIncludeDirective=*/false); 15523 if (!Mod) 15524 return true; 15525 15526 VisibleModules.setVisible(Mod, ImportLoc); 15527 15528 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15529 15530 // FIXME: we should support importing a submodule within a different submodule 15531 // of the same top-level module. Until we do, make it an error rather than 15532 // silently ignoring the import. 15533 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15534 // warn on a redundant import of the current module? 15535 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15536 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15537 Diag(ImportLoc, getLangOpts().isCompilingModule() 15538 ? diag::err_module_self_import 15539 : diag::err_module_import_in_implementation) 15540 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15541 15542 SmallVector<SourceLocation, 2> IdentifierLocs; 15543 Module *ModCheck = Mod; 15544 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15545 // If we've run out of module parents, just drop the remaining identifiers. 15546 // We need the length to be consistent. 15547 if (!ModCheck) 15548 break; 15549 ModCheck = ModCheck->Parent; 15550 15551 IdentifierLocs.push_back(Path[I].second); 15552 } 15553 15554 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15555 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15556 Mod, IdentifierLocs); 15557 if (!ModuleScopes.empty()) 15558 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15559 TU->addDecl(Import); 15560 return Import; 15561 } 15562 15563 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15564 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15565 BuildModuleInclude(DirectiveLoc, Mod); 15566 } 15567 15568 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15569 // Determine whether we're in the #include buffer for a module. The #includes 15570 // in that buffer do not qualify as module imports; they're just an 15571 // implementation detail of us building the module. 15572 // 15573 // FIXME: Should we even get ActOnModuleInclude calls for those? 15574 bool IsInModuleIncludes = 15575 TUKind == TU_Module && 15576 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15577 15578 bool ShouldAddImport = !IsInModuleIncludes; 15579 15580 // If this module import was due to an inclusion directive, create an 15581 // implicit import declaration to capture it in the AST. 15582 if (ShouldAddImport) { 15583 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15584 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15585 DirectiveLoc, Mod, 15586 DirectiveLoc); 15587 if (!ModuleScopes.empty()) 15588 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15589 TU->addDecl(ImportD); 15590 Consumer.HandleImplicitImportDecl(ImportD); 15591 } 15592 15593 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15594 VisibleModules.setVisible(Mod, DirectiveLoc); 15595 } 15596 15597 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15598 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15599 15600 ModuleScopes.push_back({}); 15601 ModuleScopes.back().Module = Mod; 15602 if (getLangOpts().ModulesLocalVisibility) 15603 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15604 15605 VisibleModules.setVisible(Mod, DirectiveLoc); 15606 } 15607 15608 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15609 checkModuleImportContext(*this, Mod, EofLoc, CurContext); 15610 15611 if (getLangOpts().ModulesLocalVisibility) { 15612 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15613 // Leaving a module hides namespace names, so our visible namespace cache 15614 // is now out of date. 15615 VisibleNamespaceCache.clear(); 15616 } 15617 15618 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15619 "left the wrong module scope"); 15620 ModuleScopes.pop_back(); 15621 15622 // We got to the end of processing a #include of a local module. Create an 15623 // ImportDecl as we would for an imported module. 15624 FileID File = getSourceManager().getFileID(EofLoc); 15625 assert(File != getSourceManager().getMainFileID() && 15626 "end of submodule in main source file"); 15627 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15628 BuildModuleInclude(DirectiveLoc, Mod); 15629 } 15630 15631 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15632 Module *Mod) { 15633 // Bail if we're not allowed to implicitly import a module here. 15634 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15635 return; 15636 15637 // Create the implicit import declaration. 15638 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15639 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15640 Loc, Mod, Loc); 15641 TU->addDecl(ImportD); 15642 Consumer.HandleImplicitImportDecl(ImportD); 15643 15644 // Make the module visible. 15645 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15646 VisibleModules.setVisible(Mod, Loc); 15647 } 15648 15649 /// We have parsed the start of an export declaration, including the '{' 15650 /// (if present). 15651 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15652 SourceLocation LBraceLoc) { 15653 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15654 15655 // C++ Modules TS draft: 15656 // An export-declaration [...] shall not contain more than one 15657 // export keyword. 15658 // 15659 // The intent here is that an export-declaration cannot appear within another 15660 // export-declaration. 15661 if (D->isExported()) 15662 Diag(ExportLoc, diag::err_export_within_export); 15663 15664 CurContext->addDecl(D); 15665 PushDeclContext(S, D); 15666 return D; 15667 } 15668 15669 /// Complete the definition of an export declaration. 15670 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15671 auto *ED = cast<ExportDecl>(D); 15672 if (RBraceLoc.isValid()) 15673 ED->setRBraceLoc(RBraceLoc); 15674 15675 // FIXME: Diagnose export of internal-linkage declaration (including 15676 // anonymous namespace). 15677 15678 PopDeclContext(); 15679 return D; 15680 } 15681 15682 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15683 IdentifierInfo* AliasName, 15684 SourceLocation PragmaLoc, 15685 SourceLocation NameLoc, 15686 SourceLocation AliasNameLoc) { 15687 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15688 LookupOrdinaryName); 15689 AsmLabelAttr *Attr = 15690 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15691 15692 // If a declaration that: 15693 // 1) declares a function or a variable 15694 // 2) has external linkage 15695 // already exists, add a label attribute to it. 15696 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15697 if (isDeclExternC(PrevDecl)) 15698 PrevDecl->addAttr(Attr); 15699 else 15700 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15701 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15702 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15703 } else 15704 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15705 } 15706 15707 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15708 SourceLocation PragmaLoc, 15709 SourceLocation NameLoc) { 15710 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15711 15712 if (PrevDecl) { 15713 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15714 } else { 15715 (void)WeakUndeclaredIdentifiers.insert( 15716 std::pair<IdentifierInfo*,WeakInfo> 15717 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15718 } 15719 } 15720 15721 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15722 IdentifierInfo* AliasName, 15723 SourceLocation PragmaLoc, 15724 SourceLocation NameLoc, 15725 SourceLocation AliasNameLoc) { 15726 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15727 LookupOrdinaryName); 15728 WeakInfo W = WeakInfo(Name, NameLoc); 15729 15730 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15731 if (!PrevDecl->hasAttr<AliasAttr>()) 15732 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15733 DeclApplyPragmaWeak(TUScope, ND, W); 15734 } else { 15735 (void)WeakUndeclaredIdentifiers.insert( 15736 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15737 } 15738 } 15739 15740 Decl *Sema::getObjCDeclContext() const { 15741 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15742 } 15743