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 QualType Ty = VD->getType(); 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 if (const TagType *TT = Ty->getAs<TagType>()) { 1539 const TagDecl *Tag = TT->getDecl(); 1540 if (Tag->hasAttr<UnusedAttr>()) 1541 return false; 1542 1543 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1544 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1545 return false; 1546 1547 if (const Expr *Init = VD->getInit()) { 1548 if (const ExprWithCleanups *Cleanups = 1549 dyn_cast<ExprWithCleanups>(Init)) 1550 Init = Cleanups->getSubExpr(); 1551 const CXXConstructExpr *Construct = 1552 dyn_cast<CXXConstructExpr>(Init); 1553 if (Construct && !Construct->isElidable()) { 1554 CXXConstructorDecl *CD = Construct->getConstructor(); 1555 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1556 return false; 1557 } 1558 } 1559 } 1560 } 1561 1562 // TODO: __attribute__((unused)) templates? 1563 } 1564 1565 return true; 1566 } 1567 1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1569 FixItHint &Hint) { 1570 if (isa<LabelDecl>(D)) { 1571 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1572 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1573 if (AfterColon.isInvalid()) 1574 return; 1575 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1576 getCharRange(D->getLocStart(), AfterColon)); 1577 } 1578 } 1579 1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1581 if (D->getTypeForDecl()->isDependentType()) 1582 return; 1583 1584 for (auto *TmpD : D->decls()) { 1585 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1586 DiagnoseUnusedDecl(T); 1587 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1588 DiagnoseUnusedNestedTypedefs(R); 1589 } 1590 } 1591 1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1593 /// unless they are marked attr(unused). 1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1595 if (!ShouldDiagnoseUnusedDecl(D)) 1596 return; 1597 1598 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1599 // typedefs can be referenced later on, so the diagnostics are emitted 1600 // at end-of-translation-unit. 1601 UnusedLocalTypedefNameCandidates.insert(TD); 1602 return; 1603 } 1604 1605 FixItHint Hint; 1606 GenerateFixForUnusedDecl(D, Context, Hint); 1607 1608 unsigned DiagID; 1609 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1610 DiagID = diag::warn_unused_exception_param; 1611 else if (isa<LabelDecl>(D)) 1612 DiagID = diag::warn_unused_label; 1613 else 1614 DiagID = diag::warn_unused_variable; 1615 1616 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1617 } 1618 1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1620 // Verify that we have no forward references left. If so, there was a goto 1621 // or address of a label taken, but no definition of it. Label fwd 1622 // definitions are indicated with a null substmt which is also not a resolved 1623 // MS inline assembly label name. 1624 bool Diagnose = false; 1625 if (L->isMSAsmLabel()) 1626 Diagnose = !L->isResolvedMSAsmLabel(); 1627 else 1628 Diagnose = L->getStmt() == nullptr; 1629 if (Diagnose) 1630 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1631 } 1632 1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1634 S->mergeNRVOIntoParent(); 1635 1636 if (S->decl_empty()) return; 1637 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1638 "Scope shouldn't contain decls!"); 1639 1640 for (auto *TmpD : S->decls()) { 1641 assert(TmpD && "This decl didn't get pushed??"); 1642 1643 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1644 NamedDecl *D = cast<NamedDecl>(TmpD); 1645 1646 if (!D->getDeclName()) continue; 1647 1648 // Diagnose unused variables in this scope. 1649 if (!S->hasUnrecoverableErrorOccurred()) { 1650 DiagnoseUnusedDecl(D); 1651 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1652 DiagnoseUnusedNestedTypedefs(RD); 1653 } 1654 1655 // If this was a forward reference to a label, verify it was defined. 1656 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1657 CheckPoppedLabel(LD, *this); 1658 1659 // Remove this name from our lexical scope, and warn on it if we haven't 1660 // already. 1661 IdResolver.RemoveDecl(D); 1662 auto ShadowI = ShadowingDecls.find(D); 1663 if (ShadowI != ShadowingDecls.end()) { 1664 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1665 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1666 << D << FD << FD->getParent(); 1667 Diag(FD->getLocation(), diag::note_previous_declaration); 1668 } 1669 ShadowingDecls.erase(ShadowI); 1670 } 1671 } 1672 } 1673 1674 /// \brief Look for an Objective-C class in the translation unit. 1675 /// 1676 /// \param Id The name of the Objective-C class we're looking for. If 1677 /// typo-correction fixes this name, the Id will be updated 1678 /// to the fixed name. 1679 /// 1680 /// \param IdLoc The location of the name in the translation unit. 1681 /// 1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1683 /// if there is no class with the given name. 1684 /// 1685 /// \returns The declaration of the named Objective-C class, or NULL if the 1686 /// class could not be found. 1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1688 SourceLocation IdLoc, 1689 bool DoTypoCorrection) { 1690 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1691 // creation from this context. 1692 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1693 1694 if (!IDecl && DoTypoCorrection) { 1695 // Perform typo correction at the given location, but only if we 1696 // find an Objective-C class name. 1697 if (TypoCorrection C = CorrectTypo( 1698 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1699 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1700 CTK_ErrorRecovery)) { 1701 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1702 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1703 Id = IDecl->getIdentifier(); 1704 } 1705 } 1706 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1707 // This routine must always return a class definition, if any. 1708 if (Def && Def->getDefinition()) 1709 Def = Def->getDefinition(); 1710 return Def; 1711 } 1712 1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1714 /// from S, where a non-field would be declared. This routine copes 1715 /// with the difference between C and C++ scoping rules in structs and 1716 /// unions. For example, the following code is well-formed in C but 1717 /// ill-formed in C++: 1718 /// @code 1719 /// struct S6 { 1720 /// enum { BAR } e; 1721 /// }; 1722 /// 1723 /// void test_S6() { 1724 /// struct S6 a; 1725 /// a.e = BAR; 1726 /// } 1727 /// @endcode 1728 /// For the declaration of BAR, this routine will return a different 1729 /// scope. The scope S will be the scope of the unnamed enumeration 1730 /// within S6. In C++, this routine will return the scope associated 1731 /// with S6, because the enumeration's scope is a transparent 1732 /// context but structures can contain non-field names. In C, this 1733 /// routine will return the translation unit scope, since the 1734 /// enumeration's scope is a transparent context and structures cannot 1735 /// contain non-field names. 1736 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1737 while (((S->getFlags() & Scope::DeclScope) == 0) || 1738 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1739 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1740 S = S->getParent(); 1741 return S; 1742 } 1743 1744 /// \brief Looks up the declaration of "struct objc_super" and 1745 /// saves it for later use in building builtin declaration of 1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1747 /// pre-existing declaration exists no action takes place. 1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1749 IdentifierInfo *II) { 1750 if (!II->isStr("objc_msgSendSuper")) 1751 return; 1752 ASTContext &Context = ThisSema.Context; 1753 1754 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1755 SourceLocation(), Sema::LookupTagName); 1756 ThisSema.LookupName(Result, S); 1757 if (Result.getResultKind() == LookupResult::Found) 1758 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1759 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1760 } 1761 1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1763 switch (Error) { 1764 case ASTContext::GE_None: 1765 return ""; 1766 case ASTContext::GE_Missing_stdio: 1767 return "stdio.h"; 1768 case ASTContext::GE_Missing_setjmp: 1769 return "setjmp.h"; 1770 case ASTContext::GE_Missing_ucontext: 1771 return "ucontext.h"; 1772 } 1773 llvm_unreachable("unhandled error kind"); 1774 } 1775 1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1777 /// file scope. lazily create a decl for it. ForRedeclaration is true 1778 /// if we're creating this built-in in anticipation of redeclaring the 1779 /// built-in. 1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1781 Scope *S, bool ForRedeclaration, 1782 SourceLocation Loc) { 1783 LookupPredefedObjCSuperType(*this, S, II); 1784 1785 ASTContext::GetBuiltinTypeError Error; 1786 QualType R = Context.GetBuiltinType(ID, Error); 1787 if (Error) { 1788 if (ForRedeclaration) 1789 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1790 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1791 return nullptr; 1792 } 1793 1794 if (!ForRedeclaration && 1795 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1796 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1797 Diag(Loc, diag::ext_implicit_lib_function_decl) 1798 << Context.BuiltinInfo.getName(ID) << R; 1799 if (Context.BuiltinInfo.getHeaderName(ID) && 1800 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1801 Diag(Loc, diag::note_include_header_or_declare) 1802 << Context.BuiltinInfo.getHeaderName(ID) 1803 << Context.BuiltinInfo.getName(ID); 1804 } 1805 1806 if (R.isNull()) 1807 return nullptr; 1808 1809 DeclContext *Parent = Context.getTranslationUnitDecl(); 1810 if (getLangOpts().CPlusPlus) { 1811 LinkageSpecDecl *CLinkageDecl = 1812 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1813 LinkageSpecDecl::lang_c, false); 1814 CLinkageDecl->setImplicit(); 1815 Parent->addDecl(CLinkageDecl); 1816 Parent = CLinkageDecl; 1817 } 1818 1819 FunctionDecl *New = FunctionDecl::Create(Context, 1820 Parent, 1821 Loc, Loc, II, R, /*TInfo=*/nullptr, 1822 SC_Extern, 1823 false, 1824 R->isFunctionProtoType()); 1825 New->setImplicit(); 1826 1827 // Create Decl objects for each parameter, adding them to the 1828 // FunctionDecl. 1829 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1830 SmallVector<ParmVarDecl*, 16> Params; 1831 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1832 ParmVarDecl *parm = 1833 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1834 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1835 SC_None, nullptr); 1836 parm->setScopeInfo(0, i); 1837 Params.push_back(parm); 1838 } 1839 New->setParams(Params); 1840 } 1841 1842 AddKnownFunctionAttributes(New); 1843 RegisterLocallyScopedExternCDecl(New, S); 1844 1845 // TUScope is the translation-unit scope to insert this function into. 1846 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1847 // relate Scopes to DeclContexts, and probably eliminate CurContext 1848 // entirely, but we're not there yet. 1849 DeclContext *SavedContext = CurContext; 1850 CurContext = Parent; 1851 PushOnScopeChains(New, TUScope); 1852 CurContext = SavedContext; 1853 return New; 1854 } 1855 1856 /// Typedef declarations don't have linkage, but they still denote the same 1857 /// entity if their types are the same. 1858 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1859 /// isSameEntity. 1860 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1861 TypedefNameDecl *Decl, 1862 LookupResult &Previous) { 1863 // This is only interesting when modules are enabled. 1864 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1865 return; 1866 1867 // Empty sets are uninteresting. 1868 if (Previous.empty()) 1869 return; 1870 1871 LookupResult::Filter Filter = Previous.makeFilter(); 1872 while (Filter.hasNext()) { 1873 NamedDecl *Old = Filter.next(); 1874 1875 // Non-hidden declarations are never ignored. 1876 if (S.isVisible(Old)) 1877 continue; 1878 1879 // Declarations of the same entity are not ignored, even if they have 1880 // different linkages. 1881 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1882 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1883 Decl->getUnderlyingType())) 1884 continue; 1885 1886 // If both declarations give a tag declaration a typedef name for linkage 1887 // purposes, then they declare the same entity. 1888 if (S.getLangOpts().CPlusPlus && 1889 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1890 Decl->getAnonDeclWithTypedefName()) 1891 continue; 1892 } 1893 1894 Filter.erase(); 1895 } 1896 1897 Filter.done(); 1898 } 1899 1900 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1901 QualType OldType; 1902 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1903 OldType = OldTypedef->getUnderlyingType(); 1904 else 1905 OldType = Context.getTypeDeclType(Old); 1906 QualType NewType = New->getUnderlyingType(); 1907 1908 if (NewType->isVariablyModifiedType()) { 1909 // Must not redefine a typedef with a variably-modified type. 1910 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1911 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1912 << Kind << NewType; 1913 if (Old->getLocation().isValid()) 1914 Diag(Old->getLocation(), diag::note_previous_definition); 1915 New->setInvalidDecl(); 1916 return true; 1917 } 1918 1919 if (OldType != NewType && 1920 !OldType->isDependentType() && 1921 !NewType->isDependentType() && 1922 !Context.hasSameType(OldType, NewType)) { 1923 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1924 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1925 << Kind << NewType << OldType; 1926 if (Old->getLocation().isValid()) 1927 Diag(Old->getLocation(), diag::note_previous_definition); 1928 New->setInvalidDecl(); 1929 return true; 1930 } 1931 return false; 1932 } 1933 1934 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1935 /// same name and scope as a previous declaration 'Old'. Figure out 1936 /// how to resolve this situation, merging decls or emitting 1937 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1938 /// 1939 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 1940 LookupResult &OldDecls) { 1941 // If the new decl is known invalid already, don't bother doing any 1942 // merging checks. 1943 if (New->isInvalidDecl()) return; 1944 1945 // Allow multiple definitions for ObjC built-in typedefs. 1946 // FIXME: Verify the underlying types are equivalent! 1947 if (getLangOpts().ObjC1) { 1948 const IdentifierInfo *TypeID = New->getIdentifier(); 1949 switch (TypeID->getLength()) { 1950 default: break; 1951 case 2: 1952 { 1953 if (!TypeID->isStr("id")) 1954 break; 1955 QualType T = New->getUnderlyingType(); 1956 if (!T->isPointerType()) 1957 break; 1958 if (!T->isVoidPointerType()) { 1959 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1960 if (!PT->isStructureType()) 1961 break; 1962 } 1963 Context.setObjCIdRedefinitionType(T); 1964 // Install the built-in type for 'id', ignoring the current definition. 1965 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1966 return; 1967 } 1968 case 5: 1969 if (!TypeID->isStr("Class")) 1970 break; 1971 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1972 // Install the built-in type for 'Class', ignoring the current definition. 1973 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1974 return; 1975 case 3: 1976 if (!TypeID->isStr("SEL")) 1977 break; 1978 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1979 // Install the built-in type for 'SEL', ignoring the current definition. 1980 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1981 return; 1982 } 1983 // Fall through - the typedef name was not a builtin type. 1984 } 1985 1986 // Verify the old decl was also a type. 1987 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1988 if (!Old) { 1989 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1990 << New->getDeclName(); 1991 1992 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1993 if (OldD->getLocation().isValid()) 1994 Diag(OldD->getLocation(), diag::note_previous_definition); 1995 1996 return New->setInvalidDecl(); 1997 } 1998 1999 // If the old declaration is invalid, just give up here. 2000 if (Old->isInvalidDecl()) 2001 return New->setInvalidDecl(); 2002 2003 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2004 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2005 auto *NewTag = New->getAnonDeclWithTypedefName(); 2006 NamedDecl *Hidden = nullptr; 2007 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2008 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2009 !hasVisibleDefinition(OldTag, &Hidden)) { 2010 // There is a definition of this tag, but it is not visible. Use it 2011 // instead of our tag. 2012 New->setTypeForDecl(OldTD->getTypeForDecl()); 2013 if (OldTD->isModed()) 2014 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2015 OldTD->getUnderlyingType()); 2016 else 2017 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2018 2019 // Make the old tag definition visible. 2020 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 2021 2022 // If this was an unscoped enumeration, yank all of its enumerators 2023 // out of the scope. 2024 if (isa<EnumDecl>(NewTag)) { 2025 Scope *EnumScope = getNonFieldDeclScope(S); 2026 for (auto *D : NewTag->decls()) { 2027 auto *ED = cast<EnumConstantDecl>(D); 2028 assert(EnumScope->isDeclScope(ED)); 2029 EnumScope->RemoveDecl(ED); 2030 IdResolver.RemoveDecl(ED); 2031 ED->getLexicalDeclContext()->removeDecl(ED); 2032 } 2033 } 2034 } 2035 } 2036 2037 // If the typedef types are not identical, reject them in all languages and 2038 // with any extensions enabled. 2039 if (isIncompatibleTypedef(Old, New)) 2040 return; 2041 2042 // The types match. Link up the redeclaration chain and merge attributes if 2043 // the old declaration was a typedef. 2044 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2045 New->setPreviousDecl(Typedef); 2046 mergeDeclAttributes(New, Old); 2047 } 2048 2049 if (getLangOpts().MicrosoftExt) 2050 return; 2051 2052 if (getLangOpts().CPlusPlus) { 2053 // C++ [dcl.typedef]p2: 2054 // In a given non-class scope, a typedef specifier can be used to 2055 // redefine the name of any type declared in that scope to refer 2056 // to the type to which it already refers. 2057 if (!isa<CXXRecordDecl>(CurContext)) 2058 return; 2059 2060 // C++0x [dcl.typedef]p4: 2061 // In a given class scope, a typedef specifier can be used to redefine 2062 // any class-name declared in that scope that is not also a typedef-name 2063 // to refer to the type to which it already refers. 2064 // 2065 // This wording came in via DR424, which was a correction to the 2066 // wording in DR56, which accidentally banned code like: 2067 // 2068 // struct S { 2069 // typedef struct A { } A; 2070 // }; 2071 // 2072 // in the C++03 standard. We implement the C++0x semantics, which 2073 // allow the above but disallow 2074 // 2075 // struct S { 2076 // typedef int I; 2077 // typedef int I; 2078 // }; 2079 // 2080 // since that was the intent of DR56. 2081 if (!isa<TypedefNameDecl>(Old)) 2082 return; 2083 2084 Diag(New->getLocation(), diag::err_redefinition) 2085 << New->getDeclName(); 2086 Diag(Old->getLocation(), diag::note_previous_definition); 2087 return New->setInvalidDecl(); 2088 } 2089 2090 // Modules always permit redefinition of typedefs, as does C11. 2091 if (getLangOpts().Modules || getLangOpts().C11) 2092 return; 2093 2094 // If we have a redefinition of a typedef in C, emit a warning. This warning 2095 // is normally mapped to an error, but can be controlled with 2096 // -Wtypedef-redefinition. If either the original or the redefinition is 2097 // in a system header, don't emit this for compatibility with GCC. 2098 if (getDiagnostics().getSuppressSystemWarnings() && 2099 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2100 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2101 return; 2102 2103 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2104 << New->getDeclName(); 2105 Diag(Old->getLocation(), diag::note_previous_definition); 2106 } 2107 2108 /// DeclhasAttr - returns true if decl Declaration already has the target 2109 /// attribute. 2110 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2111 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2112 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2113 for (const auto *i : D->attrs()) 2114 if (i->getKind() == A->getKind()) { 2115 if (Ann) { 2116 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2117 return true; 2118 continue; 2119 } 2120 // FIXME: Don't hardcode this check 2121 if (OA && isa<OwnershipAttr>(i)) 2122 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2123 return true; 2124 } 2125 2126 return false; 2127 } 2128 2129 static bool isAttributeTargetADefinition(Decl *D) { 2130 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2131 return VD->isThisDeclarationADefinition(); 2132 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2133 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2134 return true; 2135 } 2136 2137 /// Merge alignment attributes from \p Old to \p New, taking into account the 2138 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2139 /// 2140 /// \return \c true if any attributes were added to \p New. 2141 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2142 // Look for alignas attributes on Old, and pick out whichever attribute 2143 // specifies the strictest alignment requirement. 2144 AlignedAttr *OldAlignasAttr = nullptr; 2145 AlignedAttr *OldStrictestAlignAttr = nullptr; 2146 unsigned OldAlign = 0; 2147 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2148 // FIXME: We have no way of representing inherited dependent alignments 2149 // in a case like: 2150 // template<int A, int B> struct alignas(A) X; 2151 // template<int A, int B> struct alignas(B) X {}; 2152 // For now, we just ignore any alignas attributes which are not on the 2153 // definition in such a case. 2154 if (I->isAlignmentDependent()) 2155 return false; 2156 2157 if (I->isAlignas()) 2158 OldAlignasAttr = I; 2159 2160 unsigned Align = I->getAlignment(S.Context); 2161 if (Align > OldAlign) { 2162 OldAlign = Align; 2163 OldStrictestAlignAttr = I; 2164 } 2165 } 2166 2167 // Look for alignas attributes on New. 2168 AlignedAttr *NewAlignasAttr = nullptr; 2169 unsigned NewAlign = 0; 2170 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2171 if (I->isAlignmentDependent()) 2172 return false; 2173 2174 if (I->isAlignas()) 2175 NewAlignasAttr = I; 2176 2177 unsigned Align = I->getAlignment(S.Context); 2178 if (Align > NewAlign) 2179 NewAlign = Align; 2180 } 2181 2182 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2183 // Both declarations have 'alignas' attributes. We require them to match. 2184 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2185 // fall short. (If two declarations both have alignas, they must both match 2186 // every definition, and so must match each other if there is a definition.) 2187 2188 // If either declaration only contains 'alignas(0)' specifiers, then it 2189 // specifies the natural alignment for the type. 2190 if (OldAlign == 0 || NewAlign == 0) { 2191 QualType Ty; 2192 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2193 Ty = VD->getType(); 2194 else 2195 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2196 2197 if (OldAlign == 0) 2198 OldAlign = S.Context.getTypeAlign(Ty); 2199 if (NewAlign == 0) 2200 NewAlign = S.Context.getTypeAlign(Ty); 2201 } 2202 2203 if (OldAlign != NewAlign) { 2204 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2205 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2206 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2207 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2208 } 2209 } 2210 2211 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2212 // C++11 [dcl.align]p6: 2213 // if any declaration of an entity has an alignment-specifier, 2214 // every defining declaration of that entity shall specify an 2215 // equivalent alignment. 2216 // C11 6.7.5/7: 2217 // If the definition of an object does not have an alignment 2218 // specifier, any other declaration of that object shall also 2219 // have no alignment specifier. 2220 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2221 << OldAlignasAttr; 2222 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2223 << OldAlignasAttr; 2224 } 2225 2226 bool AnyAdded = false; 2227 2228 // Ensure we have an attribute representing the strictest alignment. 2229 if (OldAlign > NewAlign) { 2230 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2231 Clone->setInherited(true); 2232 New->addAttr(Clone); 2233 AnyAdded = true; 2234 } 2235 2236 // Ensure we have an alignas attribute if the old declaration had one. 2237 if (OldAlignasAttr && !NewAlignasAttr && 2238 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2239 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2240 Clone->setInherited(true); 2241 New->addAttr(Clone); 2242 AnyAdded = true; 2243 } 2244 2245 return AnyAdded; 2246 } 2247 2248 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2249 const InheritableAttr *Attr, 2250 Sema::AvailabilityMergeKind AMK) { 2251 // This function copies an attribute Attr from a previous declaration to the 2252 // new declaration D if the new declaration doesn't itself have that attribute 2253 // yet or if that attribute allows duplicates. 2254 // If you're adding a new attribute that requires logic different from 2255 // "use explicit attribute on decl if present, else use attribute from 2256 // previous decl", for example if the attribute needs to be consistent 2257 // between redeclarations, you need to call a custom merge function here. 2258 InheritableAttr *NewAttr = nullptr; 2259 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2260 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2261 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2262 AA->isImplicit(), AA->getIntroduced(), 2263 AA->getDeprecated(), 2264 AA->getObsoleted(), AA->getUnavailable(), 2265 AA->getMessage(), AA->getStrict(), 2266 AA->getReplacement(), AMK, 2267 AttrSpellingListIndex); 2268 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2269 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2270 AttrSpellingListIndex); 2271 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2272 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2273 AttrSpellingListIndex); 2274 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2275 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2276 AttrSpellingListIndex); 2277 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2278 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2279 AttrSpellingListIndex); 2280 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2281 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2282 FA->getFormatIdx(), FA->getFirstArg(), 2283 AttrSpellingListIndex); 2284 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2285 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2286 AttrSpellingListIndex); 2287 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2288 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2289 AttrSpellingListIndex, 2290 IA->getSemanticSpelling()); 2291 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2292 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2293 &S.Context.Idents.get(AA->getSpelling()), 2294 AttrSpellingListIndex); 2295 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2296 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2297 isa<CUDAGlobalAttr>(Attr))) { 2298 // CUDA target attributes are part of function signature for 2299 // overloading purposes and must not be merged. 2300 return false; 2301 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2302 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2303 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2304 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2305 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2306 NewAttr = S.mergeInternalLinkageAttr( 2307 D, InternalLinkageA->getRange(), 2308 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2309 AttrSpellingListIndex); 2310 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2311 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2312 &S.Context.Idents.get(CommonA->getSpelling()), 2313 AttrSpellingListIndex); 2314 else if (isa<AlignedAttr>(Attr)) 2315 // AlignedAttrs are handled separately, because we need to handle all 2316 // such attributes on a declaration at the same time. 2317 NewAttr = nullptr; 2318 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2319 (AMK == Sema::AMK_Override || 2320 AMK == Sema::AMK_ProtocolImplementation)) 2321 NewAttr = nullptr; 2322 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2323 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2324 UA->getGuid()); 2325 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2326 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2327 2328 if (NewAttr) { 2329 NewAttr->setInherited(true); 2330 D->addAttr(NewAttr); 2331 if (isa<MSInheritanceAttr>(NewAttr)) 2332 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2333 return true; 2334 } 2335 2336 return false; 2337 } 2338 2339 static const Decl *getDefinition(const Decl *D) { 2340 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2341 return TD->getDefinition(); 2342 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2343 const VarDecl *Def = VD->getDefinition(); 2344 if (Def) 2345 return Def; 2346 return VD->getActingDefinition(); 2347 } 2348 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2349 return FD->getDefinition(); 2350 return nullptr; 2351 } 2352 2353 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2354 for (const auto *Attribute : D->attrs()) 2355 if (Attribute->getKind() == Kind) 2356 return true; 2357 return false; 2358 } 2359 2360 /// checkNewAttributesAfterDef - If we already have a definition, check that 2361 /// there are no new attributes in this declaration. 2362 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2363 if (!New->hasAttrs()) 2364 return; 2365 2366 const Decl *Def = getDefinition(Old); 2367 if (!Def || Def == New) 2368 return; 2369 2370 AttrVec &NewAttributes = New->getAttrs(); 2371 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2372 const Attr *NewAttribute = NewAttributes[I]; 2373 2374 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2375 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2376 Sema::SkipBodyInfo SkipBody; 2377 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2378 2379 // If we're skipping this definition, drop the "alias" attribute. 2380 if (SkipBody.ShouldSkip) { 2381 NewAttributes.erase(NewAttributes.begin() + I); 2382 --E; 2383 continue; 2384 } 2385 } else { 2386 VarDecl *VD = cast<VarDecl>(New); 2387 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2388 VarDecl::TentativeDefinition 2389 ? diag::err_alias_after_tentative 2390 : diag::err_redefinition; 2391 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2392 S.Diag(Def->getLocation(), diag::note_previous_definition); 2393 VD->setInvalidDecl(); 2394 } 2395 ++I; 2396 continue; 2397 } 2398 2399 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2400 // Tentative definitions are only interesting for the alias check above. 2401 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2402 ++I; 2403 continue; 2404 } 2405 } 2406 2407 if (hasAttribute(Def, NewAttribute->getKind())) { 2408 ++I; 2409 continue; // regular attr merging will take care of validating this. 2410 } 2411 2412 if (isa<C11NoReturnAttr>(NewAttribute)) { 2413 // C's _Noreturn is allowed to be added to a function after it is defined. 2414 ++I; 2415 continue; 2416 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2417 if (AA->isAlignas()) { 2418 // C++11 [dcl.align]p6: 2419 // if any declaration of an entity has an alignment-specifier, 2420 // every defining declaration of that entity shall specify an 2421 // equivalent alignment. 2422 // C11 6.7.5/7: 2423 // If the definition of an object does not have an alignment 2424 // specifier, any other declaration of that object shall also 2425 // have no alignment specifier. 2426 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2427 << AA; 2428 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2429 << AA; 2430 NewAttributes.erase(NewAttributes.begin() + I); 2431 --E; 2432 continue; 2433 } 2434 } 2435 2436 S.Diag(NewAttribute->getLocation(), 2437 diag::warn_attribute_precede_definition); 2438 S.Diag(Def->getLocation(), diag::note_previous_definition); 2439 NewAttributes.erase(NewAttributes.begin() + I); 2440 --E; 2441 } 2442 } 2443 2444 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2445 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2446 AvailabilityMergeKind AMK) { 2447 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2448 UsedAttr *NewAttr = OldAttr->clone(Context); 2449 NewAttr->setInherited(true); 2450 New->addAttr(NewAttr); 2451 } 2452 2453 if (!Old->hasAttrs() && !New->hasAttrs()) 2454 return; 2455 2456 // Attributes declared post-definition are currently ignored. 2457 checkNewAttributesAfterDef(*this, New, Old); 2458 2459 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2460 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2461 if (OldA->getLabel() != NewA->getLabel()) { 2462 // This redeclaration changes __asm__ label. 2463 Diag(New->getLocation(), diag::err_different_asm_label); 2464 Diag(OldA->getLocation(), diag::note_previous_declaration); 2465 } 2466 } else if (Old->isUsed()) { 2467 // This redeclaration adds an __asm__ label to a declaration that has 2468 // already been ODR-used. 2469 Diag(New->getLocation(), diag::err_late_asm_label_name) 2470 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2471 } 2472 } 2473 2474 // Re-declaration cannot add abi_tag's. 2475 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2476 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2477 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2478 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2479 NewTag) == OldAbiTagAttr->tags_end()) { 2480 Diag(NewAbiTagAttr->getLocation(), 2481 diag::err_new_abi_tag_on_redeclaration) 2482 << NewTag; 2483 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2484 } 2485 } 2486 } else { 2487 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2488 Diag(Old->getLocation(), diag::note_previous_declaration); 2489 } 2490 } 2491 2492 if (!Old->hasAttrs()) 2493 return; 2494 2495 bool foundAny = New->hasAttrs(); 2496 2497 // Ensure that any moving of objects within the allocated map is done before 2498 // we process them. 2499 if (!foundAny) New->setAttrs(AttrVec()); 2500 2501 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2502 // Ignore deprecated/unavailable/availability attributes if requested. 2503 AvailabilityMergeKind LocalAMK = AMK_None; 2504 if (isa<DeprecatedAttr>(I) || 2505 isa<UnavailableAttr>(I) || 2506 isa<AvailabilityAttr>(I)) { 2507 switch (AMK) { 2508 case AMK_None: 2509 continue; 2510 2511 case AMK_Redeclaration: 2512 case AMK_Override: 2513 case AMK_ProtocolImplementation: 2514 LocalAMK = AMK; 2515 break; 2516 } 2517 } 2518 2519 // Already handled. 2520 if (isa<UsedAttr>(I)) 2521 continue; 2522 2523 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2524 foundAny = true; 2525 } 2526 2527 if (mergeAlignedAttrs(*this, New, Old)) 2528 foundAny = true; 2529 2530 if (!foundAny) New->dropAttrs(); 2531 } 2532 2533 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2534 /// to the new one. 2535 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2536 const ParmVarDecl *oldDecl, 2537 Sema &S) { 2538 // C++11 [dcl.attr.depend]p2: 2539 // The first declaration of a function shall specify the 2540 // carries_dependency attribute for its declarator-id if any declaration 2541 // of the function specifies the carries_dependency attribute. 2542 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2543 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2544 S.Diag(CDA->getLocation(), 2545 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2546 // Find the first declaration of the parameter. 2547 // FIXME: Should we build redeclaration chains for function parameters? 2548 const FunctionDecl *FirstFD = 2549 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2550 const ParmVarDecl *FirstVD = 2551 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2552 S.Diag(FirstVD->getLocation(), 2553 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2554 } 2555 2556 if (!oldDecl->hasAttrs()) 2557 return; 2558 2559 bool foundAny = newDecl->hasAttrs(); 2560 2561 // Ensure that any moving of objects within the allocated map is 2562 // done before we process them. 2563 if (!foundAny) newDecl->setAttrs(AttrVec()); 2564 2565 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2566 if (!DeclHasAttr(newDecl, I)) { 2567 InheritableAttr *newAttr = 2568 cast<InheritableParamAttr>(I->clone(S.Context)); 2569 newAttr->setInherited(true); 2570 newDecl->addAttr(newAttr); 2571 foundAny = true; 2572 } 2573 } 2574 2575 if (!foundAny) newDecl->dropAttrs(); 2576 } 2577 2578 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2579 const ParmVarDecl *OldParam, 2580 Sema &S) { 2581 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2582 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2583 if (*Oldnullability != *Newnullability) { 2584 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2585 << DiagNullabilityKind( 2586 *Newnullability, 2587 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2588 != 0)) 2589 << DiagNullabilityKind( 2590 *Oldnullability, 2591 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2592 != 0)); 2593 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2594 } 2595 } else { 2596 QualType NewT = NewParam->getType(); 2597 NewT = S.Context.getAttributedType( 2598 AttributedType::getNullabilityAttrKind(*Oldnullability), 2599 NewT, NewT); 2600 NewParam->setType(NewT); 2601 } 2602 } 2603 } 2604 2605 namespace { 2606 2607 /// Used in MergeFunctionDecl to keep track of function parameters in 2608 /// C. 2609 struct GNUCompatibleParamWarning { 2610 ParmVarDecl *OldParm; 2611 ParmVarDecl *NewParm; 2612 QualType PromotedType; 2613 }; 2614 2615 } // end anonymous namespace 2616 2617 /// getSpecialMember - get the special member enum for a method. 2618 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2619 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2620 if (Ctor->isDefaultConstructor()) 2621 return Sema::CXXDefaultConstructor; 2622 2623 if (Ctor->isCopyConstructor()) 2624 return Sema::CXXCopyConstructor; 2625 2626 if (Ctor->isMoveConstructor()) 2627 return Sema::CXXMoveConstructor; 2628 } else if (isa<CXXDestructorDecl>(MD)) { 2629 return Sema::CXXDestructor; 2630 } else if (MD->isCopyAssignmentOperator()) { 2631 return Sema::CXXCopyAssignment; 2632 } else if (MD->isMoveAssignmentOperator()) { 2633 return Sema::CXXMoveAssignment; 2634 } 2635 2636 return Sema::CXXInvalid; 2637 } 2638 2639 // Determine whether the previous declaration was a definition, implicit 2640 // declaration, or a declaration. 2641 template <typename T> 2642 static std::pair<diag::kind, SourceLocation> 2643 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2644 diag::kind PrevDiag; 2645 SourceLocation OldLocation = Old->getLocation(); 2646 if (Old->isThisDeclarationADefinition()) 2647 PrevDiag = diag::note_previous_definition; 2648 else if (Old->isImplicit()) { 2649 PrevDiag = diag::note_previous_implicit_declaration; 2650 if (OldLocation.isInvalid()) 2651 OldLocation = New->getLocation(); 2652 } else 2653 PrevDiag = diag::note_previous_declaration; 2654 return std::make_pair(PrevDiag, OldLocation); 2655 } 2656 2657 /// canRedefineFunction - checks if a function can be redefined. Currently, 2658 /// only extern inline functions can be redefined, and even then only in 2659 /// GNU89 mode. 2660 static bool canRedefineFunction(const FunctionDecl *FD, 2661 const LangOptions& LangOpts) { 2662 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2663 !LangOpts.CPlusPlus && 2664 FD->isInlineSpecified() && 2665 FD->getStorageClass() == SC_Extern); 2666 } 2667 2668 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2669 const AttributedType *AT = T->getAs<AttributedType>(); 2670 while (AT && !AT->isCallingConv()) 2671 AT = AT->getModifiedType()->getAs<AttributedType>(); 2672 return AT; 2673 } 2674 2675 template <typename T> 2676 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2677 const DeclContext *DC = Old->getDeclContext(); 2678 if (DC->isRecord()) 2679 return false; 2680 2681 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2682 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2683 return true; 2684 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2685 return true; 2686 return false; 2687 } 2688 2689 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2690 static bool isExternC(VarTemplateDecl *) { return false; } 2691 2692 /// \brief Check whether a redeclaration of an entity introduced by a 2693 /// using-declaration is valid, given that we know it's not an overload 2694 /// (nor a hidden tag declaration). 2695 template<typename ExpectedDecl> 2696 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2697 ExpectedDecl *New) { 2698 // C++11 [basic.scope.declarative]p4: 2699 // Given a set of declarations in a single declarative region, each of 2700 // which specifies the same unqualified name, 2701 // -- they shall all refer to the same entity, or all refer to functions 2702 // and function templates; or 2703 // -- exactly one declaration shall declare a class name or enumeration 2704 // name that is not a typedef name and the other declarations shall all 2705 // refer to the same variable or enumerator, or all refer to functions 2706 // and function templates; in this case the class name or enumeration 2707 // name is hidden (3.3.10). 2708 2709 // C++11 [namespace.udecl]p14: 2710 // If a function declaration in namespace scope or block scope has the 2711 // same name and the same parameter-type-list as a function introduced 2712 // by a using-declaration, and the declarations do not declare the same 2713 // function, the program is ill-formed. 2714 2715 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2716 if (Old && 2717 !Old->getDeclContext()->getRedeclContext()->Equals( 2718 New->getDeclContext()->getRedeclContext()) && 2719 !(isExternC(Old) && isExternC(New))) 2720 Old = nullptr; 2721 2722 if (!Old) { 2723 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2724 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2725 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2726 return true; 2727 } 2728 return false; 2729 } 2730 2731 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2732 const FunctionDecl *B) { 2733 assert(A->getNumParams() == B->getNumParams()); 2734 2735 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2736 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2737 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2738 if (AttrA == AttrB) 2739 return true; 2740 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2741 }; 2742 2743 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2744 } 2745 2746 /// MergeFunctionDecl - We just parsed a function 'New' from 2747 /// declarator D which has the same name and scope as a previous 2748 /// declaration 'Old'. Figure out how to resolve this situation, 2749 /// merging decls or emitting diagnostics as appropriate. 2750 /// 2751 /// In C++, New and Old must be declarations that are not 2752 /// overloaded. Use IsOverload to determine whether New and Old are 2753 /// overloaded, and to select the Old declaration that New should be 2754 /// merged with. 2755 /// 2756 /// Returns true if there was an error, false otherwise. 2757 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2758 Scope *S, bool MergeTypeWithOld) { 2759 // Verify the old decl was also a function. 2760 FunctionDecl *Old = OldD->getAsFunction(); 2761 if (!Old) { 2762 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2763 if (New->getFriendObjectKind()) { 2764 Diag(New->getLocation(), diag::err_using_decl_friend); 2765 Diag(Shadow->getTargetDecl()->getLocation(), 2766 diag::note_using_decl_target); 2767 Diag(Shadow->getUsingDecl()->getLocation(), 2768 diag::note_using_decl) << 0; 2769 return true; 2770 } 2771 2772 // Check whether the two declarations might declare the same function. 2773 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2774 return true; 2775 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2776 } else { 2777 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2778 << New->getDeclName(); 2779 Diag(OldD->getLocation(), diag::note_previous_definition); 2780 return true; 2781 } 2782 } 2783 2784 // If the old declaration is invalid, just give up here. 2785 if (Old->isInvalidDecl()) 2786 return true; 2787 2788 diag::kind PrevDiag; 2789 SourceLocation OldLocation; 2790 std::tie(PrevDiag, OldLocation) = 2791 getNoteDiagForInvalidRedeclaration(Old, New); 2792 2793 // Don't complain about this if we're in GNU89 mode and the old function 2794 // is an extern inline function. 2795 // Don't complain about specializations. They are not supposed to have 2796 // storage classes. 2797 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2798 New->getStorageClass() == SC_Static && 2799 Old->hasExternalFormalLinkage() && 2800 !New->getTemplateSpecializationInfo() && 2801 !canRedefineFunction(Old, getLangOpts())) { 2802 if (getLangOpts().MicrosoftExt) { 2803 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2804 Diag(OldLocation, PrevDiag); 2805 } else { 2806 Diag(New->getLocation(), diag::err_static_non_static) << New; 2807 Diag(OldLocation, PrevDiag); 2808 return true; 2809 } 2810 } 2811 2812 if (New->hasAttr<InternalLinkageAttr>() && 2813 !Old->hasAttr<InternalLinkageAttr>()) { 2814 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2815 << New->getDeclName(); 2816 Diag(Old->getLocation(), diag::note_previous_definition); 2817 New->dropAttr<InternalLinkageAttr>(); 2818 } 2819 2820 // If a function is first declared with a calling convention, but is later 2821 // declared or defined without one, all following decls assume the calling 2822 // convention of the first. 2823 // 2824 // It's OK if a function is first declared without a calling convention, 2825 // but is later declared or defined with the default calling convention. 2826 // 2827 // To test if either decl has an explicit calling convention, we look for 2828 // AttributedType sugar nodes on the type as written. If they are missing or 2829 // were canonicalized away, we assume the calling convention was implicit. 2830 // 2831 // Note also that we DO NOT return at this point, because we still have 2832 // other tests to run. 2833 QualType OldQType = Context.getCanonicalType(Old->getType()); 2834 QualType NewQType = Context.getCanonicalType(New->getType()); 2835 const FunctionType *OldType = cast<FunctionType>(OldQType); 2836 const FunctionType *NewType = cast<FunctionType>(NewQType); 2837 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2838 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2839 bool RequiresAdjustment = false; 2840 2841 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2842 FunctionDecl *First = Old->getFirstDecl(); 2843 const FunctionType *FT = 2844 First->getType().getCanonicalType()->castAs<FunctionType>(); 2845 FunctionType::ExtInfo FI = FT->getExtInfo(); 2846 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2847 if (!NewCCExplicit) { 2848 // Inherit the CC from the previous declaration if it was specified 2849 // there but not here. 2850 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2851 RequiresAdjustment = true; 2852 } else { 2853 // Calling conventions aren't compatible, so complain. 2854 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2855 Diag(New->getLocation(), diag::err_cconv_change) 2856 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2857 << !FirstCCExplicit 2858 << (!FirstCCExplicit ? "" : 2859 FunctionType::getNameForCallConv(FI.getCC())); 2860 2861 // Put the note on the first decl, since it is the one that matters. 2862 Diag(First->getLocation(), diag::note_previous_declaration); 2863 return true; 2864 } 2865 } 2866 2867 // FIXME: diagnose the other way around? 2868 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2869 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2870 RequiresAdjustment = true; 2871 } 2872 2873 // Merge regparm attribute. 2874 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2875 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2876 if (NewTypeInfo.getHasRegParm()) { 2877 Diag(New->getLocation(), diag::err_regparm_mismatch) 2878 << NewType->getRegParmType() 2879 << OldType->getRegParmType(); 2880 Diag(OldLocation, diag::note_previous_declaration); 2881 return true; 2882 } 2883 2884 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2885 RequiresAdjustment = true; 2886 } 2887 2888 // Merge ns_returns_retained attribute. 2889 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2890 if (NewTypeInfo.getProducesResult()) { 2891 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2892 Diag(OldLocation, diag::note_previous_declaration); 2893 return true; 2894 } 2895 2896 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2897 RequiresAdjustment = true; 2898 } 2899 2900 if (RequiresAdjustment) { 2901 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2902 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2903 New->setType(QualType(AdjustedType, 0)); 2904 NewQType = Context.getCanonicalType(New->getType()); 2905 NewType = cast<FunctionType>(NewQType); 2906 } 2907 2908 // If this redeclaration makes the function inline, we may need to add it to 2909 // UndefinedButUsed. 2910 if (!Old->isInlined() && New->isInlined() && 2911 !New->hasAttr<GNUInlineAttr>() && 2912 !getLangOpts().GNUInline && 2913 Old->isUsed(false) && 2914 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2915 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2916 SourceLocation())); 2917 2918 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2919 // about it. 2920 if (New->hasAttr<GNUInlineAttr>() && 2921 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2922 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2923 } 2924 2925 // If pass_object_size params don't match up perfectly, this isn't a valid 2926 // redeclaration. 2927 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 2928 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 2929 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 2930 << New->getDeclName(); 2931 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2932 return true; 2933 } 2934 2935 if (getLangOpts().CPlusPlus) { 2936 // (C++98 13.1p2): 2937 // Certain function declarations cannot be overloaded: 2938 // -- Function declarations that differ only in the return type 2939 // cannot be overloaded. 2940 2941 // Go back to the type source info to compare the declared return types, 2942 // per C++1y [dcl.type.auto]p13: 2943 // Redeclarations or specializations of a function or function template 2944 // with a declared return type that uses a placeholder type shall also 2945 // use that placeholder, not a deduced type. 2946 QualType OldDeclaredReturnType = 2947 (Old->getTypeSourceInfo() 2948 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2949 : OldType)->getReturnType(); 2950 QualType NewDeclaredReturnType = 2951 (New->getTypeSourceInfo() 2952 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2953 : NewType)->getReturnType(); 2954 QualType ResQT; 2955 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2956 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2957 New->isLocalExternDecl())) { 2958 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2959 OldDeclaredReturnType->isObjCObjectPointerType()) 2960 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2961 if (ResQT.isNull()) { 2962 if (New->isCXXClassMember() && New->isOutOfLine()) 2963 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2964 << New << New->getReturnTypeSourceRange(); 2965 else 2966 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2967 << New->getReturnTypeSourceRange(); 2968 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2969 << Old->getReturnTypeSourceRange(); 2970 return true; 2971 } 2972 else 2973 NewQType = ResQT; 2974 } 2975 2976 QualType OldReturnType = OldType->getReturnType(); 2977 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2978 if (OldReturnType != NewReturnType) { 2979 // If this function has a deduced return type and has already been 2980 // defined, copy the deduced value from the old declaration. 2981 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2982 if (OldAT && OldAT->isDeduced()) { 2983 New->setType( 2984 SubstAutoType(New->getType(), 2985 OldAT->isDependentType() ? Context.DependentTy 2986 : OldAT->getDeducedType())); 2987 NewQType = Context.getCanonicalType( 2988 SubstAutoType(NewQType, 2989 OldAT->isDependentType() ? Context.DependentTy 2990 : OldAT->getDeducedType())); 2991 } 2992 } 2993 2994 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2995 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2996 if (OldMethod && NewMethod) { 2997 // Preserve triviality. 2998 NewMethod->setTrivial(OldMethod->isTrivial()); 2999 3000 // MSVC allows explicit template specialization at class scope: 3001 // 2 CXXMethodDecls referring to the same function will be injected. 3002 // We don't want a redeclaration error. 3003 bool IsClassScopeExplicitSpecialization = 3004 OldMethod->isFunctionTemplateSpecialization() && 3005 NewMethod->isFunctionTemplateSpecialization(); 3006 bool isFriend = NewMethod->getFriendObjectKind(); 3007 3008 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3009 !IsClassScopeExplicitSpecialization) { 3010 // -- Member function declarations with the same name and the 3011 // same parameter types cannot be overloaded if any of them 3012 // is a static member function declaration. 3013 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3014 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3015 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3016 return true; 3017 } 3018 3019 // C++ [class.mem]p1: 3020 // [...] A member shall not be declared twice in the 3021 // member-specification, except that a nested class or member 3022 // class template can be declared and then later defined. 3023 if (ActiveTemplateInstantiations.empty()) { 3024 unsigned NewDiag; 3025 if (isa<CXXConstructorDecl>(OldMethod)) 3026 NewDiag = diag::err_constructor_redeclared; 3027 else if (isa<CXXDestructorDecl>(NewMethod)) 3028 NewDiag = diag::err_destructor_redeclared; 3029 else if (isa<CXXConversionDecl>(NewMethod)) 3030 NewDiag = diag::err_conv_function_redeclared; 3031 else 3032 NewDiag = diag::err_member_redeclared; 3033 3034 Diag(New->getLocation(), NewDiag); 3035 } else { 3036 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3037 << New << New->getType(); 3038 } 3039 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3040 return true; 3041 3042 // Complain if this is an explicit declaration of a special 3043 // member that was initially declared implicitly. 3044 // 3045 // As an exception, it's okay to befriend such methods in order 3046 // to permit the implicit constructor/destructor/operator calls. 3047 } else if (OldMethod->isImplicit()) { 3048 if (isFriend) { 3049 NewMethod->setImplicit(); 3050 } else { 3051 Diag(NewMethod->getLocation(), 3052 diag::err_definition_of_implicitly_declared_member) 3053 << New << getSpecialMember(OldMethod); 3054 return true; 3055 } 3056 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3057 Diag(NewMethod->getLocation(), 3058 diag::err_definition_of_explicitly_defaulted_member) 3059 << getSpecialMember(OldMethod); 3060 return true; 3061 } 3062 } 3063 3064 // C++11 [dcl.attr.noreturn]p1: 3065 // The first declaration of a function shall specify the noreturn 3066 // attribute if any declaration of that function specifies the noreturn 3067 // attribute. 3068 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3069 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3070 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3071 Diag(Old->getFirstDecl()->getLocation(), 3072 diag::note_noreturn_missing_first_decl); 3073 } 3074 3075 // C++11 [dcl.attr.depend]p2: 3076 // The first declaration of a function shall specify the 3077 // carries_dependency attribute for its declarator-id if any declaration 3078 // of the function specifies the carries_dependency attribute. 3079 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3080 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3081 Diag(CDA->getLocation(), 3082 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3083 Diag(Old->getFirstDecl()->getLocation(), 3084 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3085 } 3086 3087 // (C++98 8.3.5p3): 3088 // All declarations for a function shall agree exactly in both the 3089 // return type and the parameter-type-list. 3090 // We also want to respect all the extended bits except noreturn. 3091 3092 // noreturn should now match unless the old type info didn't have it. 3093 QualType OldQTypeForComparison = OldQType; 3094 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3095 assert(OldQType == QualType(OldType, 0)); 3096 const FunctionType *OldTypeForComparison 3097 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3098 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3099 assert(OldQTypeForComparison.isCanonical()); 3100 } 3101 3102 if (haveIncompatibleLanguageLinkages(Old, New)) { 3103 // As a special case, retain the language linkage from previous 3104 // declarations of a friend function as an extension. 3105 // 3106 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3107 // and is useful because there's otherwise no way to specify language 3108 // linkage within class scope. 3109 // 3110 // Check cautiously as the friend object kind isn't yet complete. 3111 if (New->getFriendObjectKind() != Decl::FOK_None) { 3112 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3113 Diag(OldLocation, PrevDiag); 3114 } else { 3115 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3116 Diag(OldLocation, PrevDiag); 3117 return true; 3118 } 3119 } 3120 3121 if (OldQTypeForComparison == NewQType) 3122 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3123 3124 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3125 New->isLocalExternDecl()) { 3126 // It's OK if we couldn't merge types for a local function declaraton 3127 // if either the old or new type is dependent. We'll merge the types 3128 // when we instantiate the function. 3129 return false; 3130 } 3131 3132 // Fall through for conflicting redeclarations and redefinitions. 3133 } 3134 3135 // C: Function types need to be compatible, not identical. This handles 3136 // duplicate function decls like "void f(int); void f(enum X);" properly. 3137 if (!getLangOpts().CPlusPlus && 3138 Context.typesAreCompatible(OldQType, NewQType)) { 3139 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3140 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3141 const FunctionProtoType *OldProto = nullptr; 3142 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3143 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3144 // The old declaration provided a function prototype, but the 3145 // new declaration does not. Merge in the prototype. 3146 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3147 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3148 NewQType = 3149 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3150 OldProto->getExtProtoInfo()); 3151 New->setType(NewQType); 3152 New->setHasInheritedPrototype(); 3153 3154 // Synthesize parameters with the same types. 3155 SmallVector<ParmVarDecl*, 16> Params; 3156 for (const auto &ParamType : OldProto->param_types()) { 3157 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3158 SourceLocation(), nullptr, 3159 ParamType, /*TInfo=*/nullptr, 3160 SC_None, nullptr); 3161 Param->setScopeInfo(0, Params.size()); 3162 Param->setImplicit(); 3163 Params.push_back(Param); 3164 } 3165 3166 New->setParams(Params); 3167 } 3168 3169 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3170 } 3171 3172 // GNU C permits a K&R definition to follow a prototype declaration 3173 // if the declared types of the parameters in the K&R definition 3174 // match the types in the prototype declaration, even when the 3175 // promoted types of the parameters from the K&R definition differ 3176 // from the types in the prototype. GCC then keeps the types from 3177 // the prototype. 3178 // 3179 // If a variadic prototype is followed by a non-variadic K&R definition, 3180 // the K&R definition becomes variadic. This is sort of an edge case, but 3181 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3182 // C99 6.9.1p8. 3183 if (!getLangOpts().CPlusPlus && 3184 Old->hasPrototype() && !New->hasPrototype() && 3185 New->getType()->getAs<FunctionProtoType>() && 3186 Old->getNumParams() == New->getNumParams()) { 3187 SmallVector<QualType, 16> ArgTypes; 3188 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3189 const FunctionProtoType *OldProto 3190 = Old->getType()->getAs<FunctionProtoType>(); 3191 const FunctionProtoType *NewProto 3192 = New->getType()->getAs<FunctionProtoType>(); 3193 3194 // Determine whether this is the GNU C extension. 3195 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3196 NewProto->getReturnType()); 3197 bool LooseCompatible = !MergedReturn.isNull(); 3198 for (unsigned Idx = 0, End = Old->getNumParams(); 3199 LooseCompatible && Idx != End; ++Idx) { 3200 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3201 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3202 if (Context.typesAreCompatible(OldParm->getType(), 3203 NewProto->getParamType(Idx))) { 3204 ArgTypes.push_back(NewParm->getType()); 3205 } else if (Context.typesAreCompatible(OldParm->getType(), 3206 NewParm->getType(), 3207 /*CompareUnqualified=*/true)) { 3208 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3209 NewProto->getParamType(Idx) }; 3210 Warnings.push_back(Warn); 3211 ArgTypes.push_back(NewParm->getType()); 3212 } else 3213 LooseCompatible = false; 3214 } 3215 3216 if (LooseCompatible) { 3217 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3218 Diag(Warnings[Warn].NewParm->getLocation(), 3219 diag::ext_param_promoted_not_compatible_with_prototype) 3220 << Warnings[Warn].PromotedType 3221 << Warnings[Warn].OldParm->getType(); 3222 if (Warnings[Warn].OldParm->getLocation().isValid()) 3223 Diag(Warnings[Warn].OldParm->getLocation(), 3224 diag::note_previous_declaration); 3225 } 3226 3227 if (MergeTypeWithOld) 3228 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3229 OldProto->getExtProtoInfo())); 3230 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3231 } 3232 3233 // Fall through to diagnose conflicting types. 3234 } 3235 3236 // A function that has already been declared has been redeclared or 3237 // defined with a different type; show an appropriate diagnostic. 3238 3239 // If the previous declaration was an implicitly-generated builtin 3240 // declaration, then at the very least we should use a specialized note. 3241 unsigned BuiltinID; 3242 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3243 // If it's actually a library-defined builtin function like 'malloc' 3244 // or 'printf', just warn about the incompatible redeclaration. 3245 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3246 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3247 Diag(OldLocation, diag::note_previous_builtin_declaration) 3248 << Old << Old->getType(); 3249 3250 // If this is a global redeclaration, just forget hereafter 3251 // about the "builtin-ness" of the function. 3252 // 3253 // Doing this for local extern declarations is problematic. If 3254 // the builtin declaration remains visible, a second invalid 3255 // local declaration will produce a hard error; if it doesn't 3256 // remain visible, a single bogus local redeclaration (which is 3257 // actually only a warning) could break all the downstream code. 3258 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3259 New->getIdentifier()->revertBuiltin(); 3260 3261 return false; 3262 } 3263 3264 PrevDiag = diag::note_previous_builtin_declaration; 3265 } 3266 3267 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3268 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3269 return true; 3270 } 3271 3272 /// \brief Completes the merge of two function declarations that are 3273 /// known to be compatible. 3274 /// 3275 /// This routine handles the merging of attributes and other 3276 /// properties of function declarations from the old declaration to 3277 /// the new declaration, once we know that New is in fact a 3278 /// redeclaration of Old. 3279 /// 3280 /// \returns false 3281 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3282 Scope *S, bool MergeTypeWithOld) { 3283 // Merge the attributes 3284 mergeDeclAttributes(New, Old); 3285 3286 // Merge "pure" flag. 3287 if (Old->isPure()) 3288 New->setPure(); 3289 3290 // Merge "used" flag. 3291 if (Old->getMostRecentDecl()->isUsed(false)) 3292 New->setIsUsed(); 3293 3294 // Merge attributes from the parameters. These can mismatch with K&R 3295 // declarations. 3296 if (New->getNumParams() == Old->getNumParams()) 3297 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3298 ParmVarDecl *NewParam = New->getParamDecl(i); 3299 ParmVarDecl *OldParam = Old->getParamDecl(i); 3300 mergeParamDeclAttributes(NewParam, OldParam, *this); 3301 mergeParamDeclTypes(NewParam, OldParam, *this); 3302 } 3303 3304 if (getLangOpts().CPlusPlus) 3305 return MergeCXXFunctionDecl(New, Old, S); 3306 3307 // Merge the function types so the we get the composite types for the return 3308 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3309 // was visible. 3310 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3311 if (!Merged.isNull() && MergeTypeWithOld) 3312 New->setType(Merged); 3313 3314 return false; 3315 } 3316 3317 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3318 ObjCMethodDecl *oldMethod) { 3319 // Merge the attributes, including deprecated/unavailable 3320 AvailabilityMergeKind MergeKind = 3321 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3322 ? AMK_ProtocolImplementation 3323 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3324 : AMK_Override; 3325 3326 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3327 3328 // Merge attributes from the parameters. 3329 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3330 oe = oldMethod->param_end(); 3331 for (ObjCMethodDecl::param_iterator 3332 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3333 ni != ne && oi != oe; ++ni, ++oi) 3334 mergeParamDeclAttributes(*ni, *oi, *this); 3335 3336 CheckObjCMethodOverride(newMethod, oldMethod); 3337 } 3338 3339 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3340 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3341 3342 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3343 ? diag::err_redefinition_different_type 3344 : diag::err_redeclaration_different_type) 3345 << New->getDeclName() << New->getType() << Old->getType(); 3346 3347 diag::kind PrevDiag; 3348 SourceLocation OldLocation; 3349 std::tie(PrevDiag, OldLocation) 3350 = getNoteDiagForInvalidRedeclaration(Old, New); 3351 S.Diag(OldLocation, PrevDiag); 3352 New->setInvalidDecl(); 3353 } 3354 3355 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3356 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3357 /// emitting diagnostics as appropriate. 3358 /// 3359 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3360 /// to here in AddInitializerToDecl. We can't check them before the initializer 3361 /// is attached. 3362 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3363 bool MergeTypeWithOld) { 3364 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3365 return; 3366 3367 QualType MergedT; 3368 if (getLangOpts().CPlusPlus) { 3369 if (New->getType()->isUndeducedType()) { 3370 // We don't know what the new type is until the initializer is attached. 3371 return; 3372 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3373 // These could still be something that needs exception specs checked. 3374 return MergeVarDeclExceptionSpecs(New, Old); 3375 } 3376 // C++ [basic.link]p10: 3377 // [...] the types specified by all declarations referring to a given 3378 // object or function shall be identical, except that declarations for an 3379 // array object can specify array types that differ by the presence or 3380 // absence of a major array bound (8.3.4). 3381 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3382 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3383 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3384 3385 // We are merging a variable declaration New into Old. If it has an array 3386 // bound, and that bound differs from Old's bound, we should diagnose the 3387 // mismatch. 3388 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3389 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3390 PrevVD = PrevVD->getPreviousDecl()) { 3391 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3392 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3393 continue; 3394 3395 if (!Context.hasSameType(NewArray, PrevVDTy)) 3396 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3397 } 3398 } 3399 3400 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3401 if (Context.hasSameType(OldArray->getElementType(), 3402 NewArray->getElementType())) 3403 MergedT = New->getType(); 3404 } 3405 // FIXME: Check visibility. New is hidden but has a complete type. If New 3406 // has no array bound, it should not inherit one from Old, if Old is not 3407 // visible. 3408 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3409 if (Context.hasSameType(OldArray->getElementType(), 3410 NewArray->getElementType())) 3411 MergedT = Old->getType(); 3412 } 3413 } 3414 else if (New->getType()->isObjCObjectPointerType() && 3415 Old->getType()->isObjCObjectPointerType()) { 3416 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3417 Old->getType()); 3418 } 3419 } else { 3420 // C 6.2.7p2: 3421 // All declarations that refer to the same object or function shall have 3422 // compatible type. 3423 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3424 } 3425 if (MergedT.isNull()) { 3426 // It's OK if we couldn't merge types if either type is dependent, for a 3427 // block-scope variable. In other cases (static data members of class 3428 // templates, variable templates, ...), we require the types to be 3429 // equivalent. 3430 // FIXME: The C++ standard doesn't say anything about this. 3431 if ((New->getType()->isDependentType() || 3432 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3433 // If the old type was dependent, we can't merge with it, so the new type 3434 // becomes dependent for now. We'll reproduce the original type when we 3435 // instantiate the TypeSourceInfo for the variable. 3436 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3437 New->setType(Context.DependentTy); 3438 return; 3439 } 3440 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3441 } 3442 3443 // Don't actually update the type on the new declaration if the old 3444 // declaration was an extern declaration in a different scope. 3445 if (MergeTypeWithOld) 3446 New->setType(MergedT); 3447 } 3448 3449 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3450 LookupResult &Previous) { 3451 // C11 6.2.7p4: 3452 // For an identifier with internal or external linkage declared 3453 // in a scope in which a prior declaration of that identifier is 3454 // visible, if the prior declaration specifies internal or 3455 // external linkage, the type of the identifier at the later 3456 // declaration becomes the composite type. 3457 // 3458 // If the variable isn't visible, we do not merge with its type. 3459 if (Previous.isShadowed()) 3460 return false; 3461 3462 if (S.getLangOpts().CPlusPlus) { 3463 // C++11 [dcl.array]p3: 3464 // If there is a preceding declaration of the entity in the same 3465 // scope in which the bound was specified, an omitted array bound 3466 // is taken to be the same as in that earlier declaration. 3467 return NewVD->isPreviousDeclInSameBlockScope() || 3468 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3469 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3470 } else { 3471 // If the old declaration was function-local, don't merge with its 3472 // type unless we're in the same function. 3473 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3474 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3475 } 3476 } 3477 3478 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3479 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3480 /// situation, merging decls or emitting diagnostics as appropriate. 3481 /// 3482 /// Tentative definition rules (C99 6.9.2p2) are checked by 3483 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3484 /// definitions here, since the initializer hasn't been attached. 3485 /// 3486 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3487 // If the new decl is already invalid, don't do any other checking. 3488 if (New->isInvalidDecl()) 3489 return; 3490 3491 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3492 return; 3493 3494 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3495 3496 // Verify the old decl was also a variable or variable template. 3497 VarDecl *Old = nullptr; 3498 VarTemplateDecl *OldTemplate = nullptr; 3499 if (Previous.isSingleResult()) { 3500 if (NewTemplate) { 3501 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3502 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3503 3504 if (auto *Shadow = 3505 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3506 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3507 return New->setInvalidDecl(); 3508 } else { 3509 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3510 3511 if (auto *Shadow = 3512 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3513 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3514 return New->setInvalidDecl(); 3515 } 3516 } 3517 if (!Old) { 3518 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3519 << New->getDeclName(); 3520 Diag(Previous.getRepresentativeDecl()->getLocation(), 3521 diag::note_previous_definition); 3522 return New->setInvalidDecl(); 3523 } 3524 3525 // Ensure the template parameters are compatible. 3526 if (NewTemplate && 3527 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3528 OldTemplate->getTemplateParameters(), 3529 /*Complain=*/true, TPL_TemplateMatch)) 3530 return New->setInvalidDecl(); 3531 3532 // C++ [class.mem]p1: 3533 // A member shall not be declared twice in the member-specification [...] 3534 // 3535 // Here, we need only consider static data members. 3536 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3537 Diag(New->getLocation(), diag::err_duplicate_member) 3538 << New->getIdentifier(); 3539 Diag(Old->getLocation(), diag::note_previous_declaration); 3540 New->setInvalidDecl(); 3541 } 3542 3543 mergeDeclAttributes(New, Old); 3544 // Warn if an already-declared variable is made a weak_import in a subsequent 3545 // declaration 3546 if (New->hasAttr<WeakImportAttr>() && 3547 Old->getStorageClass() == SC_None && 3548 !Old->hasAttr<WeakImportAttr>()) { 3549 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3550 Diag(Old->getLocation(), diag::note_previous_definition); 3551 // Remove weak_import attribute on new declaration. 3552 New->dropAttr<WeakImportAttr>(); 3553 } 3554 3555 if (New->hasAttr<InternalLinkageAttr>() && 3556 !Old->hasAttr<InternalLinkageAttr>()) { 3557 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3558 << New->getDeclName(); 3559 Diag(Old->getLocation(), diag::note_previous_definition); 3560 New->dropAttr<InternalLinkageAttr>(); 3561 } 3562 3563 // Merge the types. 3564 VarDecl *MostRecent = Old->getMostRecentDecl(); 3565 if (MostRecent != Old) { 3566 MergeVarDeclTypes(New, MostRecent, 3567 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3568 if (New->isInvalidDecl()) 3569 return; 3570 } 3571 3572 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3573 if (New->isInvalidDecl()) 3574 return; 3575 3576 diag::kind PrevDiag; 3577 SourceLocation OldLocation; 3578 std::tie(PrevDiag, OldLocation) = 3579 getNoteDiagForInvalidRedeclaration(Old, New); 3580 3581 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3582 if (New->getStorageClass() == SC_Static && 3583 !New->isStaticDataMember() && 3584 Old->hasExternalFormalLinkage()) { 3585 if (getLangOpts().MicrosoftExt) { 3586 Diag(New->getLocation(), diag::ext_static_non_static) 3587 << New->getDeclName(); 3588 Diag(OldLocation, PrevDiag); 3589 } else { 3590 Diag(New->getLocation(), diag::err_static_non_static) 3591 << New->getDeclName(); 3592 Diag(OldLocation, PrevDiag); 3593 return New->setInvalidDecl(); 3594 } 3595 } 3596 // C99 6.2.2p4: 3597 // For an identifier declared with the storage-class specifier 3598 // extern in a scope in which a prior declaration of that 3599 // identifier is visible,23) if the prior declaration specifies 3600 // internal or external linkage, the linkage of the identifier at 3601 // the later declaration is the same as the linkage specified at 3602 // the prior declaration. If no prior declaration is visible, or 3603 // if the prior declaration specifies no linkage, then the 3604 // identifier has external linkage. 3605 if (New->hasExternalStorage() && Old->hasLinkage()) 3606 /* Okay */; 3607 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3608 !New->isStaticDataMember() && 3609 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3610 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3611 Diag(OldLocation, PrevDiag); 3612 return New->setInvalidDecl(); 3613 } 3614 3615 // Check if extern is followed by non-extern and vice-versa. 3616 if (New->hasExternalStorage() && 3617 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3618 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3619 Diag(OldLocation, PrevDiag); 3620 return New->setInvalidDecl(); 3621 } 3622 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3623 !New->hasExternalStorage()) { 3624 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3625 Diag(OldLocation, PrevDiag); 3626 return New->setInvalidDecl(); 3627 } 3628 3629 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3630 3631 // FIXME: The test for external storage here seems wrong? We still 3632 // need to check for mismatches. 3633 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3634 // Don't complain about out-of-line definitions of static members. 3635 !(Old->getLexicalDeclContext()->isRecord() && 3636 !New->getLexicalDeclContext()->isRecord())) { 3637 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3638 Diag(OldLocation, PrevDiag); 3639 return New->setInvalidDecl(); 3640 } 3641 3642 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3643 if (VarDecl *Def = Old->getDefinition()) { 3644 // C++1z [dcl.fcn.spec]p4: 3645 // If the definition of a variable appears in a translation unit before 3646 // its first declaration as inline, the program is ill-formed. 3647 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3648 Diag(Def->getLocation(), diag::note_previous_definition); 3649 } 3650 } 3651 3652 // If this redeclaration makes the function inline, we may need to add it to 3653 // UndefinedButUsed. 3654 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3655 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3656 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3657 SourceLocation())); 3658 3659 if (New->getTLSKind() != Old->getTLSKind()) { 3660 if (!Old->getTLSKind()) { 3661 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3662 Diag(OldLocation, PrevDiag); 3663 } else if (!New->getTLSKind()) { 3664 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3665 Diag(OldLocation, PrevDiag); 3666 } else { 3667 // Do not allow redeclaration to change the variable between requiring 3668 // static and dynamic initialization. 3669 // FIXME: GCC allows this, but uses the TLS keyword on the first 3670 // declaration to determine the kind. Do we need to be compatible here? 3671 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3672 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3673 Diag(OldLocation, PrevDiag); 3674 } 3675 } 3676 3677 // C++ doesn't have tentative definitions, so go right ahead and check here. 3678 if (getLangOpts().CPlusPlus && 3679 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3680 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3681 Old->getCanonicalDecl()->isConstexpr()) { 3682 // This definition won't be a definition any more once it's been merged. 3683 Diag(New->getLocation(), 3684 diag::warn_deprecated_redundant_constexpr_static_def); 3685 } else if (VarDecl *Def = Old->getDefinition()) { 3686 if (checkVarDeclRedefinition(Def, New)) 3687 return; 3688 } 3689 } 3690 3691 if (haveIncompatibleLanguageLinkages(Old, New)) { 3692 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3693 Diag(OldLocation, PrevDiag); 3694 New->setInvalidDecl(); 3695 return; 3696 } 3697 3698 // Merge "used" flag. 3699 if (Old->getMostRecentDecl()->isUsed(false)) 3700 New->setIsUsed(); 3701 3702 // Keep a chain of previous declarations. 3703 New->setPreviousDecl(Old); 3704 if (NewTemplate) 3705 NewTemplate->setPreviousDecl(OldTemplate); 3706 3707 // Inherit access appropriately. 3708 New->setAccess(Old->getAccess()); 3709 if (NewTemplate) 3710 NewTemplate->setAccess(New->getAccess()); 3711 3712 if (Old->isInline()) 3713 New->setImplicitlyInline(); 3714 } 3715 3716 /// We've just determined that \p Old and \p New both appear to be definitions 3717 /// of the same variable. Either diagnose or fix the problem. 3718 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3719 if (!hasVisibleDefinition(Old) && 3720 (New->getFormalLinkage() == InternalLinkage || 3721 New->isInline() || 3722 New->getDescribedVarTemplate() || 3723 New->getNumTemplateParameterLists() || 3724 New->getDeclContext()->isDependentContext())) { 3725 // The previous definition is hidden, and multiple definitions are 3726 // permitted (in separate TUs). Demote this to a declaration. 3727 New->demoteThisDefinitionToDeclaration(); 3728 3729 // Make the canonical definition visible. 3730 if (auto *OldTD = Old->getDescribedVarTemplate()) 3731 makeMergedDefinitionVisible(OldTD, New->getLocation()); 3732 makeMergedDefinitionVisible(Old, New->getLocation()); 3733 return false; 3734 } else { 3735 Diag(New->getLocation(), diag::err_redefinition) << New; 3736 Diag(Old->getLocation(), diag::note_previous_definition); 3737 New->setInvalidDecl(); 3738 return true; 3739 } 3740 } 3741 3742 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3743 /// no declarator (e.g. "struct foo;") is parsed. 3744 Decl * 3745 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3746 RecordDecl *&AnonRecord) { 3747 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3748 AnonRecord); 3749 } 3750 3751 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3752 // disambiguate entities defined in different scopes. 3753 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3754 // compatibility. 3755 // We will pick our mangling number depending on which version of MSVC is being 3756 // targeted. 3757 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3758 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3759 ? S->getMSCurManglingNumber() 3760 : S->getMSLastManglingNumber(); 3761 } 3762 3763 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3764 if (!Context.getLangOpts().CPlusPlus) 3765 return; 3766 3767 if (isa<CXXRecordDecl>(Tag->getParent())) { 3768 // If this tag is the direct child of a class, number it if 3769 // it is anonymous. 3770 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3771 return; 3772 MangleNumberingContext &MCtx = 3773 Context.getManglingNumberContext(Tag->getParent()); 3774 Context.setManglingNumber( 3775 Tag, MCtx.getManglingNumber( 3776 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3777 return; 3778 } 3779 3780 // If this tag isn't a direct child of a class, number it if it is local. 3781 Decl *ManglingContextDecl; 3782 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3783 Tag->getDeclContext(), ManglingContextDecl)) { 3784 Context.setManglingNumber( 3785 Tag, MCtx->getManglingNumber( 3786 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3787 } 3788 } 3789 3790 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3791 TypedefNameDecl *NewTD) { 3792 if (TagFromDeclSpec->isInvalidDecl()) 3793 return; 3794 3795 // Do nothing if the tag already has a name for linkage purposes. 3796 if (TagFromDeclSpec->hasNameForLinkage()) 3797 return; 3798 3799 // A well-formed anonymous tag must always be a TUK_Definition. 3800 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3801 3802 // The type must match the tag exactly; no qualifiers allowed. 3803 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3804 Context.getTagDeclType(TagFromDeclSpec))) { 3805 if (getLangOpts().CPlusPlus) 3806 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3807 return; 3808 } 3809 3810 // If we've already computed linkage for the anonymous tag, then 3811 // adding a typedef name for the anonymous decl can change that 3812 // linkage, which might be a serious problem. Diagnose this as 3813 // unsupported and ignore the typedef name. TODO: we should 3814 // pursue this as a language defect and establish a formal rule 3815 // for how to handle it. 3816 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3817 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3818 3819 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3820 tagLoc = getLocForEndOfToken(tagLoc); 3821 3822 llvm::SmallString<40> textToInsert; 3823 textToInsert += ' '; 3824 textToInsert += NewTD->getIdentifier()->getName(); 3825 Diag(tagLoc, diag::note_typedef_changes_linkage) 3826 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3827 return; 3828 } 3829 3830 // Otherwise, set this is the anon-decl typedef for the tag. 3831 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3832 } 3833 3834 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3835 switch (T) { 3836 case DeclSpec::TST_class: 3837 return 0; 3838 case DeclSpec::TST_struct: 3839 return 1; 3840 case DeclSpec::TST_interface: 3841 return 2; 3842 case DeclSpec::TST_union: 3843 return 3; 3844 case DeclSpec::TST_enum: 3845 return 4; 3846 default: 3847 llvm_unreachable("unexpected type specifier"); 3848 } 3849 } 3850 3851 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3852 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3853 /// parameters to cope with template friend declarations. 3854 Decl * 3855 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3856 MultiTemplateParamsArg TemplateParams, 3857 bool IsExplicitInstantiation, 3858 RecordDecl *&AnonRecord) { 3859 Decl *TagD = nullptr; 3860 TagDecl *Tag = nullptr; 3861 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3862 DS.getTypeSpecType() == DeclSpec::TST_struct || 3863 DS.getTypeSpecType() == DeclSpec::TST_interface || 3864 DS.getTypeSpecType() == DeclSpec::TST_union || 3865 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3866 TagD = DS.getRepAsDecl(); 3867 3868 if (!TagD) // We probably had an error 3869 return nullptr; 3870 3871 // Note that the above type specs guarantee that the 3872 // type rep is a Decl, whereas in many of the others 3873 // it's a Type. 3874 if (isa<TagDecl>(TagD)) 3875 Tag = cast<TagDecl>(TagD); 3876 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3877 Tag = CTD->getTemplatedDecl(); 3878 } 3879 3880 if (Tag) { 3881 handleTagNumbering(Tag, S); 3882 Tag->setFreeStanding(); 3883 if (Tag->isInvalidDecl()) 3884 return Tag; 3885 } 3886 3887 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3888 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3889 // or incomplete types shall not be restrict-qualified." 3890 if (TypeQuals & DeclSpec::TQ_restrict) 3891 Diag(DS.getRestrictSpecLoc(), 3892 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3893 << DS.getSourceRange(); 3894 } 3895 3896 if (DS.isInlineSpecified()) 3897 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 3898 << getLangOpts().CPlusPlus1z; 3899 3900 if (DS.isConstexprSpecified()) { 3901 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3902 // and definitions of functions and variables. 3903 if (Tag) 3904 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3905 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3906 else 3907 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3908 // Don't emit warnings after this error. 3909 return TagD; 3910 } 3911 3912 if (DS.isConceptSpecified()) { 3913 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3914 // either a function concept and its definition or a variable concept and 3915 // its initializer. 3916 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3917 return TagD; 3918 } 3919 3920 DiagnoseFunctionSpecifiers(DS); 3921 3922 if (DS.isFriendSpecified()) { 3923 // If we're dealing with a decl but not a TagDecl, assume that 3924 // whatever routines created it handled the friendship aspect. 3925 if (TagD && !Tag) 3926 return nullptr; 3927 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3928 } 3929 3930 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3931 bool IsExplicitSpecialization = 3932 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3933 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3934 !IsExplicitInstantiation && !IsExplicitSpecialization && 3935 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 3936 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3937 // nested-name-specifier unless it is an explicit instantiation 3938 // or an explicit specialization. 3939 // 3940 // FIXME: We allow class template partial specializations here too, per the 3941 // obvious intent of DR1819. 3942 // 3943 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3944 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3945 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3946 return nullptr; 3947 } 3948 3949 // Track whether this decl-specifier declares anything. 3950 bool DeclaresAnything = true; 3951 3952 // Handle anonymous struct definitions. 3953 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3954 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3955 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3956 if (getLangOpts().CPlusPlus || 3957 Record->getDeclContext()->isRecord()) { 3958 // If CurContext is a DeclContext that can contain statements, 3959 // RecursiveASTVisitor won't visit the decls that 3960 // BuildAnonymousStructOrUnion() will put into CurContext. 3961 // Also store them here so that they can be part of the 3962 // DeclStmt that gets created in this case. 3963 // FIXME: Also return the IndirectFieldDecls created by 3964 // BuildAnonymousStructOr union, for the same reason? 3965 if (CurContext->isFunctionOrMethod()) 3966 AnonRecord = Record; 3967 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3968 Context.getPrintingPolicy()); 3969 } 3970 3971 DeclaresAnything = false; 3972 } 3973 } 3974 3975 // C11 6.7.2.1p2: 3976 // A struct-declaration that does not declare an anonymous structure or 3977 // anonymous union shall contain a struct-declarator-list. 3978 // 3979 // This rule also existed in C89 and C99; the grammar for struct-declaration 3980 // did not permit a struct-declaration without a struct-declarator-list. 3981 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3982 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3983 // Check for Microsoft C extension: anonymous struct/union member. 3984 // Handle 2 kinds of anonymous struct/union: 3985 // struct STRUCT; 3986 // union UNION; 3987 // and 3988 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3989 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3990 if ((Tag && Tag->getDeclName()) || 3991 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3992 RecordDecl *Record = nullptr; 3993 if (Tag) 3994 Record = dyn_cast<RecordDecl>(Tag); 3995 else if (const RecordType *RT = 3996 DS.getRepAsType().get()->getAsStructureType()) 3997 Record = RT->getDecl(); 3998 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3999 Record = UT->getDecl(); 4000 4001 if (Record && getLangOpts().MicrosoftExt) { 4002 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4003 << Record->isUnion() << DS.getSourceRange(); 4004 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4005 } 4006 4007 DeclaresAnything = false; 4008 } 4009 } 4010 4011 // Skip all the checks below if we have a type error. 4012 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4013 (TagD && TagD->isInvalidDecl())) 4014 return TagD; 4015 4016 if (getLangOpts().CPlusPlus && 4017 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4018 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4019 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4020 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4021 DeclaresAnything = false; 4022 4023 if (!DS.isMissingDeclaratorOk()) { 4024 // Customize diagnostic for a typedef missing a name. 4025 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4026 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4027 << DS.getSourceRange(); 4028 else 4029 DeclaresAnything = false; 4030 } 4031 4032 if (DS.isModulePrivateSpecified() && 4033 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4034 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4035 << Tag->getTagKind() 4036 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4037 4038 ActOnDocumentableDecl(TagD); 4039 4040 // C 6.7/2: 4041 // A declaration [...] shall declare at least a declarator [...], a tag, 4042 // or the members of an enumeration. 4043 // C++ [dcl.dcl]p3: 4044 // [If there are no declarators], and except for the declaration of an 4045 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4046 // names into the program, or shall redeclare a name introduced by a 4047 // previous declaration. 4048 if (!DeclaresAnything) { 4049 // In C, we allow this as a (popular) extension / bug. Don't bother 4050 // producing further diagnostics for redundant qualifiers after this. 4051 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4052 return TagD; 4053 } 4054 4055 // C++ [dcl.stc]p1: 4056 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4057 // init-declarator-list of the declaration shall not be empty. 4058 // C++ [dcl.fct.spec]p1: 4059 // If a cv-qualifier appears in a decl-specifier-seq, the 4060 // init-declarator-list of the declaration shall not be empty. 4061 // 4062 // Spurious qualifiers here appear to be valid in C. 4063 unsigned DiagID = diag::warn_standalone_specifier; 4064 if (getLangOpts().CPlusPlus) 4065 DiagID = diag::ext_standalone_specifier; 4066 4067 // Note that a linkage-specification sets a storage class, but 4068 // 'extern "C" struct foo;' is actually valid and not theoretically 4069 // useless. 4070 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4071 if (SCS == DeclSpec::SCS_mutable) 4072 // Since mutable is not a viable storage class specifier in C, there is 4073 // no reason to treat it as an extension. Instead, diagnose as an error. 4074 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4075 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4076 Diag(DS.getStorageClassSpecLoc(), DiagID) 4077 << DeclSpec::getSpecifierName(SCS); 4078 } 4079 4080 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4081 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4082 << DeclSpec::getSpecifierName(TSCS); 4083 if (DS.getTypeQualifiers()) { 4084 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4085 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4086 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4087 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4088 // Restrict is covered above. 4089 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4090 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4091 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4092 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4093 } 4094 4095 // Warn about ignored type attributes, for example: 4096 // __attribute__((aligned)) struct A; 4097 // Attributes should be placed after tag to apply to type declaration. 4098 if (!DS.getAttributes().empty()) { 4099 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4100 if (TypeSpecType == DeclSpec::TST_class || 4101 TypeSpecType == DeclSpec::TST_struct || 4102 TypeSpecType == DeclSpec::TST_interface || 4103 TypeSpecType == DeclSpec::TST_union || 4104 TypeSpecType == DeclSpec::TST_enum) { 4105 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4106 attrs = attrs->getNext()) 4107 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4108 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4109 } 4110 } 4111 4112 return TagD; 4113 } 4114 4115 /// We are trying to inject an anonymous member into the given scope; 4116 /// check if there's an existing declaration that can't be overloaded. 4117 /// 4118 /// \return true if this is a forbidden redeclaration 4119 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4120 Scope *S, 4121 DeclContext *Owner, 4122 DeclarationName Name, 4123 SourceLocation NameLoc, 4124 bool IsUnion) { 4125 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4126 Sema::ForRedeclaration); 4127 if (!SemaRef.LookupName(R, S)) return false; 4128 4129 // Pick a representative declaration. 4130 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4131 assert(PrevDecl && "Expected a non-null Decl"); 4132 4133 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4134 return false; 4135 4136 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4137 << IsUnion << Name; 4138 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4139 4140 return true; 4141 } 4142 4143 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4144 /// anonymous struct or union AnonRecord into the owning context Owner 4145 /// and scope S. This routine will be invoked just after we realize 4146 /// that an unnamed union or struct is actually an anonymous union or 4147 /// struct, e.g., 4148 /// 4149 /// @code 4150 /// union { 4151 /// int i; 4152 /// float f; 4153 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4154 /// // f into the surrounding scope.x 4155 /// @endcode 4156 /// 4157 /// This routine is recursive, injecting the names of nested anonymous 4158 /// structs/unions into the owning context and scope as well. 4159 static bool 4160 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4161 RecordDecl *AnonRecord, AccessSpecifier AS, 4162 SmallVectorImpl<NamedDecl *> &Chaining) { 4163 bool Invalid = false; 4164 4165 // Look every FieldDecl and IndirectFieldDecl with a name. 4166 for (auto *D : AnonRecord->decls()) { 4167 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4168 cast<NamedDecl>(D)->getDeclName()) { 4169 ValueDecl *VD = cast<ValueDecl>(D); 4170 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4171 VD->getLocation(), 4172 AnonRecord->isUnion())) { 4173 // C++ [class.union]p2: 4174 // The names of the members of an anonymous union shall be 4175 // distinct from the names of any other entity in the 4176 // scope in which the anonymous union is declared. 4177 Invalid = true; 4178 } else { 4179 // C++ [class.union]p2: 4180 // For the purpose of name lookup, after the anonymous union 4181 // definition, the members of the anonymous union are 4182 // considered to have been defined in the scope in which the 4183 // anonymous union is declared. 4184 unsigned OldChainingSize = Chaining.size(); 4185 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4186 Chaining.append(IF->chain_begin(), IF->chain_end()); 4187 else 4188 Chaining.push_back(VD); 4189 4190 assert(Chaining.size() >= 2); 4191 NamedDecl **NamedChain = 4192 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4193 for (unsigned i = 0; i < Chaining.size(); i++) 4194 NamedChain[i] = Chaining[i]; 4195 4196 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4197 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4198 VD->getType(), {NamedChain, Chaining.size()}); 4199 4200 for (const auto *Attr : VD->attrs()) 4201 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4202 4203 IndirectField->setAccess(AS); 4204 IndirectField->setImplicit(); 4205 SemaRef.PushOnScopeChains(IndirectField, S); 4206 4207 // That includes picking up the appropriate access specifier. 4208 if (AS != AS_none) IndirectField->setAccess(AS); 4209 4210 Chaining.resize(OldChainingSize); 4211 } 4212 } 4213 } 4214 4215 return Invalid; 4216 } 4217 4218 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4219 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4220 /// illegal input values are mapped to SC_None. 4221 static StorageClass 4222 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4223 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4224 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4225 "Parser allowed 'typedef' as storage class VarDecl."); 4226 switch (StorageClassSpec) { 4227 case DeclSpec::SCS_unspecified: return SC_None; 4228 case DeclSpec::SCS_extern: 4229 if (DS.isExternInLinkageSpec()) 4230 return SC_None; 4231 return SC_Extern; 4232 case DeclSpec::SCS_static: return SC_Static; 4233 case DeclSpec::SCS_auto: return SC_Auto; 4234 case DeclSpec::SCS_register: return SC_Register; 4235 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4236 // Illegal SCSs map to None: error reporting is up to the caller. 4237 case DeclSpec::SCS_mutable: // Fall through. 4238 case DeclSpec::SCS_typedef: return SC_None; 4239 } 4240 llvm_unreachable("unknown storage class specifier"); 4241 } 4242 4243 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4244 assert(Record->hasInClassInitializer()); 4245 4246 for (const auto *I : Record->decls()) { 4247 const auto *FD = dyn_cast<FieldDecl>(I); 4248 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4249 FD = IFD->getAnonField(); 4250 if (FD && FD->hasInClassInitializer()) 4251 return FD->getLocation(); 4252 } 4253 4254 llvm_unreachable("couldn't find in-class initializer"); 4255 } 4256 4257 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4258 SourceLocation DefaultInitLoc) { 4259 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4260 return; 4261 4262 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4263 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4264 } 4265 4266 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4267 CXXRecordDecl *AnonUnion) { 4268 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4269 return; 4270 4271 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4272 } 4273 4274 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4275 /// anonymous structure or union. Anonymous unions are a C++ feature 4276 /// (C++ [class.union]) and a C11 feature; anonymous structures 4277 /// are a C11 feature and GNU C++ extension. 4278 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4279 AccessSpecifier AS, 4280 RecordDecl *Record, 4281 const PrintingPolicy &Policy) { 4282 DeclContext *Owner = Record->getDeclContext(); 4283 4284 // Diagnose whether this anonymous struct/union is an extension. 4285 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4286 Diag(Record->getLocation(), diag::ext_anonymous_union); 4287 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4288 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4289 else if (!Record->isUnion() && !getLangOpts().C11) 4290 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4291 4292 // C and C++ require different kinds of checks for anonymous 4293 // structs/unions. 4294 bool Invalid = false; 4295 if (getLangOpts().CPlusPlus) { 4296 const char *PrevSpec = nullptr; 4297 unsigned DiagID; 4298 if (Record->isUnion()) { 4299 // C++ [class.union]p6: 4300 // Anonymous unions declared in a named namespace or in the 4301 // global namespace shall be declared static. 4302 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4303 (isa<TranslationUnitDecl>(Owner) || 4304 (isa<NamespaceDecl>(Owner) && 4305 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4306 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4307 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4308 4309 // Recover by adding 'static'. 4310 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4311 PrevSpec, DiagID, Policy); 4312 } 4313 // C++ [class.union]p6: 4314 // A storage class is not allowed in a declaration of an 4315 // anonymous union in a class scope. 4316 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4317 isa<RecordDecl>(Owner)) { 4318 Diag(DS.getStorageClassSpecLoc(), 4319 diag::err_anonymous_union_with_storage_spec) 4320 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4321 4322 // Recover by removing the storage specifier. 4323 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4324 SourceLocation(), 4325 PrevSpec, DiagID, Context.getPrintingPolicy()); 4326 } 4327 } 4328 4329 // Ignore const/volatile/restrict qualifiers. 4330 if (DS.getTypeQualifiers()) { 4331 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4332 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4333 << Record->isUnion() << "const" 4334 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4335 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4336 Diag(DS.getVolatileSpecLoc(), 4337 diag::ext_anonymous_struct_union_qualified) 4338 << Record->isUnion() << "volatile" 4339 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4340 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4341 Diag(DS.getRestrictSpecLoc(), 4342 diag::ext_anonymous_struct_union_qualified) 4343 << Record->isUnion() << "restrict" 4344 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4345 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4346 Diag(DS.getAtomicSpecLoc(), 4347 diag::ext_anonymous_struct_union_qualified) 4348 << Record->isUnion() << "_Atomic" 4349 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4350 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4351 Diag(DS.getUnalignedSpecLoc(), 4352 diag::ext_anonymous_struct_union_qualified) 4353 << Record->isUnion() << "__unaligned" 4354 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4355 4356 DS.ClearTypeQualifiers(); 4357 } 4358 4359 // C++ [class.union]p2: 4360 // The member-specification of an anonymous union shall only 4361 // define non-static data members. [Note: nested types and 4362 // functions cannot be declared within an anonymous union. ] 4363 for (auto *Mem : Record->decls()) { 4364 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4365 // C++ [class.union]p3: 4366 // An anonymous union shall not have private or protected 4367 // members (clause 11). 4368 assert(FD->getAccess() != AS_none); 4369 if (FD->getAccess() != AS_public) { 4370 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4371 << Record->isUnion() << (FD->getAccess() == AS_protected); 4372 Invalid = true; 4373 } 4374 4375 // C++ [class.union]p1 4376 // An object of a class with a non-trivial constructor, a non-trivial 4377 // copy constructor, a non-trivial destructor, or a non-trivial copy 4378 // assignment operator cannot be a member of a union, nor can an 4379 // array of such objects. 4380 if (CheckNontrivialField(FD)) 4381 Invalid = true; 4382 } else if (Mem->isImplicit()) { 4383 // Any implicit members are fine. 4384 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4385 // This is a type that showed up in an 4386 // elaborated-type-specifier inside the anonymous struct or 4387 // union, but which actually declares a type outside of the 4388 // anonymous struct or union. It's okay. 4389 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4390 if (!MemRecord->isAnonymousStructOrUnion() && 4391 MemRecord->getDeclName()) { 4392 // Visual C++ allows type definition in anonymous struct or union. 4393 if (getLangOpts().MicrosoftExt) 4394 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4395 << Record->isUnion(); 4396 else { 4397 // This is a nested type declaration. 4398 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4399 << Record->isUnion(); 4400 Invalid = true; 4401 } 4402 } else { 4403 // This is an anonymous type definition within another anonymous type. 4404 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4405 // not part of standard C++. 4406 Diag(MemRecord->getLocation(), 4407 diag::ext_anonymous_record_with_anonymous_type) 4408 << Record->isUnion(); 4409 } 4410 } else if (isa<AccessSpecDecl>(Mem)) { 4411 // Any access specifier is fine. 4412 } else if (isa<StaticAssertDecl>(Mem)) { 4413 // In C++1z, static_assert declarations are also fine. 4414 } else { 4415 // We have something that isn't a non-static data 4416 // member. Complain about it. 4417 unsigned DK = diag::err_anonymous_record_bad_member; 4418 if (isa<TypeDecl>(Mem)) 4419 DK = diag::err_anonymous_record_with_type; 4420 else if (isa<FunctionDecl>(Mem)) 4421 DK = diag::err_anonymous_record_with_function; 4422 else if (isa<VarDecl>(Mem)) 4423 DK = diag::err_anonymous_record_with_static; 4424 4425 // Visual C++ allows type definition in anonymous struct or union. 4426 if (getLangOpts().MicrosoftExt && 4427 DK == diag::err_anonymous_record_with_type) 4428 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4429 << Record->isUnion(); 4430 else { 4431 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4432 Invalid = true; 4433 } 4434 } 4435 } 4436 4437 // C++11 [class.union]p8 (DR1460): 4438 // At most one variant member of a union may have a 4439 // brace-or-equal-initializer. 4440 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4441 Owner->isRecord()) 4442 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4443 cast<CXXRecordDecl>(Record)); 4444 } 4445 4446 if (!Record->isUnion() && !Owner->isRecord()) { 4447 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4448 << getLangOpts().CPlusPlus; 4449 Invalid = true; 4450 } 4451 4452 // Mock up a declarator. 4453 Declarator Dc(DS, Declarator::MemberContext); 4454 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4455 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4456 4457 // Create a declaration for this anonymous struct/union. 4458 NamedDecl *Anon = nullptr; 4459 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4460 Anon = FieldDecl::Create(Context, OwningClass, 4461 DS.getLocStart(), 4462 Record->getLocation(), 4463 /*IdentifierInfo=*/nullptr, 4464 Context.getTypeDeclType(Record), 4465 TInfo, 4466 /*BitWidth=*/nullptr, /*Mutable=*/false, 4467 /*InitStyle=*/ICIS_NoInit); 4468 Anon->setAccess(AS); 4469 if (getLangOpts().CPlusPlus) 4470 FieldCollector->Add(cast<FieldDecl>(Anon)); 4471 } else { 4472 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4473 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4474 if (SCSpec == DeclSpec::SCS_mutable) { 4475 // mutable can only appear on non-static class members, so it's always 4476 // an error here 4477 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4478 Invalid = true; 4479 SC = SC_None; 4480 } 4481 4482 Anon = VarDecl::Create(Context, Owner, 4483 DS.getLocStart(), 4484 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4485 Context.getTypeDeclType(Record), 4486 TInfo, SC); 4487 4488 // Default-initialize the implicit variable. This initialization will be 4489 // trivial in almost all cases, except if a union member has an in-class 4490 // initializer: 4491 // union { int n = 0; }; 4492 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4493 } 4494 Anon->setImplicit(); 4495 4496 // Mark this as an anonymous struct/union type. 4497 Record->setAnonymousStructOrUnion(true); 4498 4499 // Add the anonymous struct/union object to the current 4500 // context. We'll be referencing this object when we refer to one of 4501 // its members. 4502 Owner->addDecl(Anon); 4503 4504 // Inject the members of the anonymous struct/union into the owning 4505 // context and into the identifier resolver chain for name lookup 4506 // purposes. 4507 SmallVector<NamedDecl*, 2> Chain; 4508 Chain.push_back(Anon); 4509 4510 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4511 Invalid = true; 4512 4513 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4514 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4515 Decl *ManglingContextDecl; 4516 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4517 NewVD->getDeclContext(), ManglingContextDecl)) { 4518 Context.setManglingNumber( 4519 NewVD, MCtx->getManglingNumber( 4520 NewVD, getMSManglingNumber(getLangOpts(), S))); 4521 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4522 } 4523 } 4524 } 4525 4526 if (Invalid) 4527 Anon->setInvalidDecl(); 4528 4529 return Anon; 4530 } 4531 4532 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4533 /// Microsoft C anonymous structure. 4534 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4535 /// Example: 4536 /// 4537 /// struct A { int a; }; 4538 /// struct B { struct A; int b; }; 4539 /// 4540 /// void foo() { 4541 /// B var; 4542 /// var.a = 3; 4543 /// } 4544 /// 4545 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4546 RecordDecl *Record) { 4547 assert(Record && "expected a record!"); 4548 4549 // Mock up a declarator. 4550 Declarator Dc(DS, Declarator::TypeNameContext); 4551 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4552 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4553 4554 auto *ParentDecl = cast<RecordDecl>(CurContext); 4555 QualType RecTy = Context.getTypeDeclType(Record); 4556 4557 // Create a declaration for this anonymous struct. 4558 NamedDecl *Anon = FieldDecl::Create(Context, 4559 ParentDecl, 4560 DS.getLocStart(), 4561 DS.getLocStart(), 4562 /*IdentifierInfo=*/nullptr, 4563 RecTy, 4564 TInfo, 4565 /*BitWidth=*/nullptr, /*Mutable=*/false, 4566 /*InitStyle=*/ICIS_NoInit); 4567 Anon->setImplicit(); 4568 4569 // Add the anonymous struct object to the current context. 4570 CurContext->addDecl(Anon); 4571 4572 // Inject the members of the anonymous struct into the current 4573 // context and into the identifier resolver chain for name lookup 4574 // purposes. 4575 SmallVector<NamedDecl*, 2> Chain; 4576 Chain.push_back(Anon); 4577 4578 RecordDecl *RecordDef = Record->getDefinition(); 4579 if (RequireCompleteType(Anon->getLocation(), RecTy, 4580 diag::err_field_incomplete) || 4581 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4582 AS_none, Chain)) { 4583 Anon->setInvalidDecl(); 4584 ParentDecl->setInvalidDecl(); 4585 } 4586 4587 return Anon; 4588 } 4589 4590 /// GetNameForDeclarator - Determine the full declaration name for the 4591 /// given Declarator. 4592 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4593 return GetNameFromUnqualifiedId(D.getName()); 4594 } 4595 4596 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4597 DeclarationNameInfo 4598 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4599 DeclarationNameInfo NameInfo; 4600 NameInfo.setLoc(Name.StartLocation); 4601 4602 switch (Name.getKind()) { 4603 4604 case UnqualifiedId::IK_ImplicitSelfParam: 4605 case UnqualifiedId::IK_Identifier: 4606 NameInfo.setName(Name.Identifier); 4607 NameInfo.setLoc(Name.StartLocation); 4608 return NameInfo; 4609 4610 case UnqualifiedId::IK_OperatorFunctionId: 4611 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4612 Name.OperatorFunctionId.Operator)); 4613 NameInfo.setLoc(Name.StartLocation); 4614 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4615 = Name.OperatorFunctionId.SymbolLocations[0]; 4616 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4617 = Name.EndLocation.getRawEncoding(); 4618 return NameInfo; 4619 4620 case UnqualifiedId::IK_LiteralOperatorId: 4621 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4622 Name.Identifier)); 4623 NameInfo.setLoc(Name.StartLocation); 4624 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4625 return NameInfo; 4626 4627 case UnqualifiedId::IK_ConversionFunctionId: { 4628 TypeSourceInfo *TInfo; 4629 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4630 if (Ty.isNull()) 4631 return DeclarationNameInfo(); 4632 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4633 Context.getCanonicalType(Ty))); 4634 NameInfo.setLoc(Name.StartLocation); 4635 NameInfo.setNamedTypeInfo(TInfo); 4636 return NameInfo; 4637 } 4638 4639 case UnqualifiedId::IK_ConstructorName: { 4640 TypeSourceInfo *TInfo; 4641 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4642 if (Ty.isNull()) 4643 return DeclarationNameInfo(); 4644 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4645 Context.getCanonicalType(Ty))); 4646 NameInfo.setLoc(Name.StartLocation); 4647 NameInfo.setNamedTypeInfo(TInfo); 4648 return NameInfo; 4649 } 4650 4651 case UnqualifiedId::IK_ConstructorTemplateId: { 4652 // In well-formed code, we can only have a constructor 4653 // template-id that refers to the current context, so go there 4654 // to find the actual type being constructed. 4655 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4656 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4657 return DeclarationNameInfo(); 4658 4659 // Determine the type of the class being constructed. 4660 QualType CurClassType = Context.getTypeDeclType(CurClass); 4661 4662 // FIXME: Check two things: that the template-id names the same type as 4663 // CurClassType, and that the template-id does not occur when the name 4664 // was qualified. 4665 4666 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4667 Context.getCanonicalType(CurClassType))); 4668 NameInfo.setLoc(Name.StartLocation); 4669 // FIXME: should we retrieve TypeSourceInfo? 4670 NameInfo.setNamedTypeInfo(nullptr); 4671 return NameInfo; 4672 } 4673 4674 case UnqualifiedId::IK_DestructorName: { 4675 TypeSourceInfo *TInfo; 4676 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4677 if (Ty.isNull()) 4678 return DeclarationNameInfo(); 4679 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4680 Context.getCanonicalType(Ty))); 4681 NameInfo.setLoc(Name.StartLocation); 4682 NameInfo.setNamedTypeInfo(TInfo); 4683 return NameInfo; 4684 } 4685 4686 case UnqualifiedId::IK_TemplateId: { 4687 TemplateName TName = Name.TemplateId->Template.get(); 4688 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4689 return Context.getNameForTemplate(TName, TNameLoc); 4690 } 4691 4692 } // switch (Name.getKind()) 4693 4694 llvm_unreachable("Unknown name kind"); 4695 } 4696 4697 static QualType getCoreType(QualType Ty) { 4698 do { 4699 if (Ty->isPointerType() || Ty->isReferenceType()) 4700 Ty = Ty->getPointeeType(); 4701 else if (Ty->isArrayType()) 4702 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4703 else 4704 return Ty.withoutLocalFastQualifiers(); 4705 } while (true); 4706 } 4707 4708 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4709 /// and Definition have "nearly" matching parameters. This heuristic is 4710 /// used to improve diagnostics in the case where an out-of-line function 4711 /// definition doesn't match any declaration within the class or namespace. 4712 /// Also sets Params to the list of indices to the parameters that differ 4713 /// between the declaration and the definition. If hasSimilarParameters 4714 /// returns true and Params is empty, then all of the parameters match. 4715 static bool hasSimilarParameters(ASTContext &Context, 4716 FunctionDecl *Declaration, 4717 FunctionDecl *Definition, 4718 SmallVectorImpl<unsigned> &Params) { 4719 Params.clear(); 4720 if (Declaration->param_size() != Definition->param_size()) 4721 return false; 4722 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4723 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4724 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4725 4726 // The parameter types are identical 4727 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4728 continue; 4729 4730 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4731 QualType DefParamBaseTy = getCoreType(DefParamTy); 4732 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4733 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4734 4735 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4736 (DeclTyName && DeclTyName == DefTyName)) 4737 Params.push_back(Idx); 4738 else // The two parameters aren't even close 4739 return false; 4740 } 4741 4742 return true; 4743 } 4744 4745 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4746 /// declarator needs to be rebuilt in the current instantiation. 4747 /// Any bits of declarator which appear before the name are valid for 4748 /// consideration here. That's specifically the type in the decl spec 4749 /// and the base type in any member-pointer chunks. 4750 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4751 DeclarationName Name) { 4752 // The types we specifically need to rebuild are: 4753 // - typenames, typeofs, and decltypes 4754 // - types which will become injected class names 4755 // Of course, we also need to rebuild any type referencing such a 4756 // type. It's safest to just say "dependent", but we call out a 4757 // few cases here. 4758 4759 DeclSpec &DS = D.getMutableDeclSpec(); 4760 switch (DS.getTypeSpecType()) { 4761 case DeclSpec::TST_typename: 4762 case DeclSpec::TST_typeofType: 4763 case DeclSpec::TST_underlyingType: 4764 case DeclSpec::TST_atomic: { 4765 // Grab the type from the parser. 4766 TypeSourceInfo *TSI = nullptr; 4767 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4768 if (T.isNull() || !T->isDependentType()) break; 4769 4770 // Make sure there's a type source info. This isn't really much 4771 // of a waste; most dependent types should have type source info 4772 // attached already. 4773 if (!TSI) 4774 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4775 4776 // Rebuild the type in the current instantiation. 4777 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4778 if (!TSI) return true; 4779 4780 // Store the new type back in the decl spec. 4781 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4782 DS.UpdateTypeRep(LocType); 4783 break; 4784 } 4785 4786 case DeclSpec::TST_decltype: 4787 case DeclSpec::TST_typeofExpr: { 4788 Expr *E = DS.getRepAsExpr(); 4789 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4790 if (Result.isInvalid()) return true; 4791 DS.UpdateExprRep(Result.get()); 4792 break; 4793 } 4794 4795 default: 4796 // Nothing to do for these decl specs. 4797 break; 4798 } 4799 4800 // It doesn't matter what order we do this in. 4801 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4802 DeclaratorChunk &Chunk = D.getTypeObject(I); 4803 4804 // The only type information in the declarator which can come 4805 // before the declaration name is the base type of a member 4806 // pointer. 4807 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4808 continue; 4809 4810 // Rebuild the scope specifier in-place. 4811 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4812 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4813 return true; 4814 } 4815 4816 return false; 4817 } 4818 4819 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4820 D.setFunctionDefinitionKind(FDK_Declaration); 4821 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4822 4823 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4824 Dcl && Dcl->getDeclContext()->isFileContext()) 4825 Dcl->setTopLevelDeclInObjCContainer(); 4826 4827 return Dcl; 4828 } 4829 4830 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4831 /// If T is the name of a class, then each of the following shall have a 4832 /// name different from T: 4833 /// - every static data member of class T; 4834 /// - every member function of class T 4835 /// - every member of class T that is itself a type; 4836 /// \returns true if the declaration name violates these rules. 4837 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4838 DeclarationNameInfo NameInfo) { 4839 DeclarationName Name = NameInfo.getName(); 4840 4841 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 4842 while (Record && Record->isAnonymousStructOrUnion()) 4843 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 4844 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 4845 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4846 return true; 4847 } 4848 4849 return false; 4850 } 4851 4852 /// \brief Diagnose a declaration whose declarator-id has the given 4853 /// nested-name-specifier. 4854 /// 4855 /// \param SS The nested-name-specifier of the declarator-id. 4856 /// 4857 /// \param DC The declaration context to which the nested-name-specifier 4858 /// resolves. 4859 /// 4860 /// \param Name The name of the entity being declared. 4861 /// 4862 /// \param Loc The location of the name of the entity being declared. 4863 /// 4864 /// \returns true if we cannot safely recover from this error, false otherwise. 4865 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4866 DeclarationName Name, 4867 SourceLocation Loc) { 4868 DeclContext *Cur = CurContext; 4869 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4870 Cur = Cur->getParent(); 4871 4872 // If the user provided a superfluous scope specifier that refers back to the 4873 // class in which the entity is already declared, diagnose and ignore it. 4874 // 4875 // class X { 4876 // void X::f(); 4877 // }; 4878 // 4879 // Note, it was once ill-formed to give redundant qualification in all 4880 // contexts, but that rule was removed by DR482. 4881 if (Cur->Equals(DC)) { 4882 if (Cur->isRecord()) { 4883 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4884 : diag::err_member_extra_qualification) 4885 << Name << FixItHint::CreateRemoval(SS.getRange()); 4886 SS.clear(); 4887 } else { 4888 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4889 } 4890 return false; 4891 } 4892 4893 // Check whether the qualifying scope encloses the scope of the original 4894 // declaration. 4895 if (!Cur->Encloses(DC)) { 4896 if (Cur->isRecord()) 4897 Diag(Loc, diag::err_member_qualification) 4898 << Name << SS.getRange(); 4899 else if (isa<TranslationUnitDecl>(DC)) 4900 Diag(Loc, diag::err_invalid_declarator_global_scope) 4901 << Name << SS.getRange(); 4902 else if (isa<FunctionDecl>(Cur)) 4903 Diag(Loc, diag::err_invalid_declarator_in_function) 4904 << Name << SS.getRange(); 4905 else if (isa<BlockDecl>(Cur)) 4906 Diag(Loc, diag::err_invalid_declarator_in_block) 4907 << Name << SS.getRange(); 4908 else 4909 Diag(Loc, diag::err_invalid_declarator_scope) 4910 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4911 4912 return true; 4913 } 4914 4915 if (Cur->isRecord()) { 4916 // Cannot qualify members within a class. 4917 Diag(Loc, diag::err_member_qualification) 4918 << Name << SS.getRange(); 4919 SS.clear(); 4920 4921 // C++ constructors and destructors with incorrect scopes can break 4922 // our AST invariants by having the wrong underlying types. If 4923 // that's the case, then drop this declaration entirely. 4924 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4925 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4926 !Context.hasSameType(Name.getCXXNameType(), 4927 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4928 return true; 4929 4930 return false; 4931 } 4932 4933 // C++11 [dcl.meaning]p1: 4934 // [...] "The nested-name-specifier of the qualified declarator-id shall 4935 // not begin with a decltype-specifer" 4936 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4937 while (SpecLoc.getPrefix()) 4938 SpecLoc = SpecLoc.getPrefix(); 4939 if (dyn_cast_or_null<DecltypeType>( 4940 SpecLoc.getNestedNameSpecifier()->getAsType())) 4941 Diag(Loc, diag::err_decltype_in_declarator) 4942 << SpecLoc.getTypeLoc().getSourceRange(); 4943 4944 return false; 4945 } 4946 4947 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4948 MultiTemplateParamsArg TemplateParamLists) { 4949 // TODO: consider using NameInfo for diagnostic. 4950 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4951 DeclarationName Name = NameInfo.getName(); 4952 4953 // All of these full declarators require an identifier. If it doesn't have 4954 // one, the ParsedFreeStandingDeclSpec action should be used. 4955 if (D.isDecompositionDeclarator()) { 4956 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 4957 } else if (!Name) { 4958 if (!D.isInvalidType()) // Reject this if we think it is valid. 4959 Diag(D.getDeclSpec().getLocStart(), 4960 diag::err_declarator_need_ident) 4961 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4962 return nullptr; 4963 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4964 return nullptr; 4965 4966 // The scope passed in may not be a decl scope. Zip up the scope tree until 4967 // we find one that is. 4968 while ((S->getFlags() & Scope::DeclScope) == 0 || 4969 (S->getFlags() & Scope::TemplateParamScope) != 0) 4970 S = S->getParent(); 4971 4972 DeclContext *DC = CurContext; 4973 if (D.getCXXScopeSpec().isInvalid()) 4974 D.setInvalidType(); 4975 else if (D.getCXXScopeSpec().isSet()) { 4976 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4977 UPPC_DeclarationQualifier)) 4978 return nullptr; 4979 4980 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4981 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4982 if (!DC || isa<EnumDecl>(DC)) { 4983 // If we could not compute the declaration context, it's because the 4984 // declaration context is dependent but does not refer to a class, 4985 // class template, or class template partial specialization. Complain 4986 // and return early, to avoid the coming semantic disaster. 4987 Diag(D.getIdentifierLoc(), 4988 diag::err_template_qualified_declarator_no_match) 4989 << D.getCXXScopeSpec().getScopeRep() 4990 << D.getCXXScopeSpec().getRange(); 4991 return nullptr; 4992 } 4993 bool IsDependentContext = DC->isDependentContext(); 4994 4995 if (!IsDependentContext && 4996 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4997 return nullptr; 4998 4999 // If a class is incomplete, do not parse entities inside it. 5000 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5001 Diag(D.getIdentifierLoc(), 5002 diag::err_member_def_undefined_record) 5003 << Name << DC << D.getCXXScopeSpec().getRange(); 5004 return nullptr; 5005 } 5006 if (!D.getDeclSpec().isFriendSpecified()) { 5007 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5008 Name, D.getIdentifierLoc())) { 5009 if (DC->isRecord()) 5010 return nullptr; 5011 5012 D.setInvalidType(); 5013 } 5014 } 5015 5016 // Check whether we need to rebuild the type of the given 5017 // declaration in the current instantiation. 5018 if (EnteringContext && IsDependentContext && 5019 TemplateParamLists.size() != 0) { 5020 ContextRAII SavedContext(*this, DC); 5021 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5022 D.setInvalidType(); 5023 } 5024 } 5025 5026 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5027 QualType R = TInfo->getType(); 5028 5029 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5030 // If this is a typedef, we'll end up spewing multiple diagnostics. 5031 // Just return early; it's safer. If this is a function, let the 5032 // "constructor cannot have a return type" diagnostic handle it. 5033 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5034 return nullptr; 5035 5036 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5037 UPPC_DeclarationType)) 5038 D.setInvalidType(); 5039 5040 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5041 ForRedeclaration); 5042 5043 // See if this is a redefinition of a variable in the same scope. 5044 if (!D.getCXXScopeSpec().isSet()) { 5045 bool IsLinkageLookup = false; 5046 bool CreateBuiltins = false; 5047 5048 // If the declaration we're planning to build will be a function 5049 // or object with linkage, then look for another declaration with 5050 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5051 // 5052 // If the declaration we're planning to build will be declared with 5053 // external linkage in the translation unit, create any builtin with 5054 // the same name. 5055 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5056 /* Do nothing*/; 5057 else if (CurContext->isFunctionOrMethod() && 5058 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5059 R->isFunctionType())) { 5060 IsLinkageLookup = true; 5061 CreateBuiltins = 5062 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5063 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5064 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5065 CreateBuiltins = true; 5066 5067 if (IsLinkageLookup) 5068 Previous.clear(LookupRedeclarationWithLinkage); 5069 5070 LookupName(Previous, S, CreateBuiltins); 5071 } else { // Something like "int foo::x;" 5072 LookupQualifiedName(Previous, DC); 5073 5074 // C++ [dcl.meaning]p1: 5075 // When the declarator-id is qualified, the declaration shall refer to a 5076 // previously declared member of the class or namespace to which the 5077 // qualifier refers (or, in the case of a namespace, of an element of the 5078 // inline namespace set of that namespace (7.3.1)) or to a specialization 5079 // thereof; [...] 5080 // 5081 // Note that we already checked the context above, and that we do not have 5082 // enough information to make sure that Previous contains the declaration 5083 // we want to match. For example, given: 5084 // 5085 // class X { 5086 // void f(); 5087 // void f(float); 5088 // }; 5089 // 5090 // void X::f(int) { } // ill-formed 5091 // 5092 // In this case, Previous will point to the overload set 5093 // containing the two f's declared in X, but neither of them 5094 // matches. 5095 5096 // C++ [dcl.meaning]p1: 5097 // [...] the member shall not merely have been introduced by a 5098 // using-declaration in the scope of the class or namespace nominated by 5099 // the nested-name-specifier of the declarator-id. 5100 RemoveUsingDecls(Previous); 5101 } 5102 5103 if (Previous.isSingleResult() && 5104 Previous.getFoundDecl()->isTemplateParameter()) { 5105 // Maybe we will complain about the shadowed template parameter. 5106 if (!D.isInvalidType()) 5107 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5108 Previous.getFoundDecl()); 5109 5110 // Just pretend that we didn't see the previous declaration. 5111 Previous.clear(); 5112 } 5113 5114 // In C++, the previous declaration we find might be a tag type 5115 // (class or enum). In this case, the new declaration will hide the 5116 // tag type. Note that this does does not apply if we're declaring a 5117 // typedef (C++ [dcl.typedef]p4). 5118 if (Previous.isSingleTagDecl() && 5119 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5120 Previous.clear(); 5121 5122 // Check that there are no default arguments other than in the parameters 5123 // of a function declaration (C++ only). 5124 if (getLangOpts().CPlusPlus) 5125 CheckExtraCXXDefaultArguments(D); 5126 5127 if (D.getDeclSpec().isConceptSpecified()) { 5128 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5129 // applied only to the definition of a function template or variable 5130 // template, declared in namespace scope 5131 if (!TemplateParamLists.size()) { 5132 Diag(D.getDeclSpec().getConceptSpecLoc(), 5133 diag:: err_concept_wrong_decl_kind); 5134 return nullptr; 5135 } 5136 5137 if (!DC->getRedeclContext()->isFileContext()) { 5138 Diag(D.getIdentifierLoc(), 5139 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5140 return nullptr; 5141 } 5142 } 5143 5144 NamedDecl *New; 5145 5146 bool AddToScope = true; 5147 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5148 if (TemplateParamLists.size()) { 5149 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5150 return nullptr; 5151 } 5152 5153 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5154 } else if (R->isFunctionType()) { 5155 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5156 TemplateParamLists, 5157 AddToScope); 5158 } else { 5159 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5160 AddToScope); 5161 } 5162 5163 if (!New) 5164 return nullptr; 5165 5166 // If this has an identifier and is not a function template specialization, 5167 // add it to the scope stack. 5168 if (New->getDeclName() && AddToScope) { 5169 // Only make a locally-scoped extern declaration visible if it is the first 5170 // declaration of this entity. Qualified lookup for such an entity should 5171 // only find this declaration if there is no visible declaration of it. 5172 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5173 PushOnScopeChains(New, S, AddToContext); 5174 if (!AddToContext) 5175 CurContext->addHiddenDecl(New); 5176 } 5177 5178 if (isInOpenMPDeclareTargetContext()) 5179 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5180 5181 return New; 5182 } 5183 5184 /// Helper method to turn variable array types into constant array 5185 /// types in certain situations which would otherwise be errors (for 5186 /// GCC compatibility). 5187 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5188 ASTContext &Context, 5189 bool &SizeIsNegative, 5190 llvm::APSInt &Oversized) { 5191 // This method tries to turn a variable array into a constant 5192 // array even when the size isn't an ICE. This is necessary 5193 // for compatibility with code that depends on gcc's buggy 5194 // constant expression folding, like struct {char x[(int)(char*)2];} 5195 SizeIsNegative = false; 5196 Oversized = 0; 5197 5198 if (T->isDependentType()) 5199 return QualType(); 5200 5201 QualifierCollector Qs; 5202 const Type *Ty = Qs.strip(T); 5203 5204 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5205 QualType Pointee = PTy->getPointeeType(); 5206 QualType FixedType = 5207 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5208 Oversized); 5209 if (FixedType.isNull()) return FixedType; 5210 FixedType = Context.getPointerType(FixedType); 5211 return Qs.apply(Context, FixedType); 5212 } 5213 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5214 QualType Inner = PTy->getInnerType(); 5215 QualType FixedType = 5216 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5217 Oversized); 5218 if (FixedType.isNull()) return FixedType; 5219 FixedType = Context.getParenType(FixedType); 5220 return Qs.apply(Context, FixedType); 5221 } 5222 5223 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5224 if (!VLATy) 5225 return QualType(); 5226 // FIXME: We should probably handle this case 5227 if (VLATy->getElementType()->isVariablyModifiedType()) 5228 return QualType(); 5229 5230 llvm::APSInt Res; 5231 if (!VLATy->getSizeExpr() || 5232 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5233 return QualType(); 5234 5235 // Check whether the array size is negative. 5236 if (Res.isSigned() && Res.isNegative()) { 5237 SizeIsNegative = true; 5238 return QualType(); 5239 } 5240 5241 // Check whether the array is too large to be addressed. 5242 unsigned ActiveSizeBits 5243 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5244 Res); 5245 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5246 Oversized = Res; 5247 return QualType(); 5248 } 5249 5250 return Context.getConstantArrayType(VLATy->getElementType(), 5251 Res, ArrayType::Normal, 0); 5252 } 5253 5254 static void 5255 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5256 SrcTL = SrcTL.getUnqualifiedLoc(); 5257 DstTL = DstTL.getUnqualifiedLoc(); 5258 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5259 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5260 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5261 DstPTL.getPointeeLoc()); 5262 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5263 return; 5264 } 5265 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5266 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5267 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5268 DstPTL.getInnerLoc()); 5269 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5270 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5271 return; 5272 } 5273 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5274 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5275 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5276 TypeLoc DstElemTL = DstATL.getElementLoc(); 5277 DstElemTL.initializeFullCopy(SrcElemTL); 5278 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5279 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5280 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5281 } 5282 5283 /// Helper method to turn variable array types into constant array 5284 /// types in certain situations which would otherwise be errors (for 5285 /// GCC compatibility). 5286 static TypeSourceInfo* 5287 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5288 ASTContext &Context, 5289 bool &SizeIsNegative, 5290 llvm::APSInt &Oversized) { 5291 QualType FixedTy 5292 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5293 SizeIsNegative, Oversized); 5294 if (FixedTy.isNull()) 5295 return nullptr; 5296 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5297 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5298 FixedTInfo->getTypeLoc()); 5299 return FixedTInfo; 5300 } 5301 5302 /// \brief Register the given locally-scoped extern "C" declaration so 5303 /// that it can be found later for redeclarations. We include any extern "C" 5304 /// declaration that is not visible in the translation unit here, not just 5305 /// function-scope declarations. 5306 void 5307 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5308 if (!getLangOpts().CPlusPlus && 5309 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5310 // Don't need to track declarations in the TU in C. 5311 return; 5312 5313 // Note that we have a locally-scoped external with this name. 5314 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5315 } 5316 5317 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5318 // FIXME: We can have multiple results via __attribute__((overloadable)). 5319 auto Result = Context.getExternCContextDecl()->lookup(Name); 5320 return Result.empty() ? nullptr : *Result.begin(); 5321 } 5322 5323 /// \brief Diagnose function specifiers on a declaration of an identifier that 5324 /// does not identify a function. 5325 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5326 // FIXME: We should probably indicate the identifier in question to avoid 5327 // confusion for constructs like "virtual int a(), b;" 5328 if (DS.isVirtualSpecified()) 5329 Diag(DS.getVirtualSpecLoc(), 5330 diag::err_virtual_non_function); 5331 5332 if (DS.isExplicitSpecified()) 5333 Diag(DS.getExplicitSpecLoc(), 5334 diag::err_explicit_non_function); 5335 5336 if (DS.isNoreturnSpecified()) 5337 Diag(DS.getNoreturnSpecLoc(), 5338 diag::err_noreturn_non_function); 5339 } 5340 5341 NamedDecl* 5342 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5343 TypeSourceInfo *TInfo, LookupResult &Previous) { 5344 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5345 if (D.getCXXScopeSpec().isSet()) { 5346 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5347 << D.getCXXScopeSpec().getRange(); 5348 D.setInvalidType(); 5349 // Pretend we didn't see the scope specifier. 5350 DC = CurContext; 5351 Previous.clear(); 5352 } 5353 5354 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5355 5356 if (D.getDeclSpec().isInlineSpecified()) 5357 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5358 << getLangOpts().CPlusPlus1z; 5359 if (D.getDeclSpec().isConstexprSpecified()) 5360 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5361 << 1; 5362 if (D.getDeclSpec().isConceptSpecified()) 5363 Diag(D.getDeclSpec().getConceptSpecLoc(), 5364 diag::err_concept_wrong_decl_kind); 5365 5366 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5367 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5368 << D.getName().getSourceRange(); 5369 return nullptr; 5370 } 5371 5372 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5373 if (!NewTD) return nullptr; 5374 5375 // Handle attributes prior to checking for duplicates in MergeVarDecl 5376 ProcessDeclAttributes(S, NewTD, D); 5377 5378 CheckTypedefForVariablyModifiedType(S, NewTD); 5379 5380 bool Redeclaration = D.isRedeclaration(); 5381 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5382 D.setRedeclaration(Redeclaration); 5383 return ND; 5384 } 5385 5386 void 5387 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5388 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5389 // then it shall have block scope. 5390 // Note that variably modified types must be fixed before merging the decl so 5391 // that redeclarations will match. 5392 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5393 QualType T = TInfo->getType(); 5394 if (T->isVariablyModifiedType()) { 5395 getCurFunction()->setHasBranchProtectedScope(); 5396 5397 if (S->getFnParent() == nullptr) { 5398 bool SizeIsNegative; 5399 llvm::APSInt Oversized; 5400 TypeSourceInfo *FixedTInfo = 5401 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5402 SizeIsNegative, 5403 Oversized); 5404 if (FixedTInfo) { 5405 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5406 NewTD->setTypeSourceInfo(FixedTInfo); 5407 } else { 5408 if (SizeIsNegative) 5409 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5410 else if (T->isVariableArrayType()) 5411 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5412 else if (Oversized.getBoolValue()) 5413 Diag(NewTD->getLocation(), diag::err_array_too_large) 5414 << Oversized.toString(10); 5415 else 5416 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5417 NewTD->setInvalidDecl(); 5418 } 5419 } 5420 } 5421 } 5422 5423 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5424 /// declares a typedef-name, either using the 'typedef' type specifier or via 5425 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5426 NamedDecl* 5427 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5428 LookupResult &Previous, bool &Redeclaration) { 5429 // Merge the decl with the existing one if appropriate. If the decl is 5430 // in an outer scope, it isn't the same thing. 5431 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5432 /*AllowInlineNamespace*/false); 5433 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5434 if (!Previous.empty()) { 5435 Redeclaration = true; 5436 MergeTypedefNameDecl(S, NewTD, Previous); 5437 } 5438 5439 // If this is the C FILE type, notify the AST context. 5440 if (IdentifierInfo *II = NewTD->getIdentifier()) 5441 if (!NewTD->isInvalidDecl() && 5442 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5443 if (II->isStr("FILE")) 5444 Context.setFILEDecl(NewTD); 5445 else if (II->isStr("jmp_buf")) 5446 Context.setjmp_bufDecl(NewTD); 5447 else if (II->isStr("sigjmp_buf")) 5448 Context.setsigjmp_bufDecl(NewTD); 5449 else if (II->isStr("ucontext_t")) 5450 Context.setucontext_tDecl(NewTD); 5451 } 5452 5453 return NewTD; 5454 } 5455 5456 /// \brief Determines whether the given declaration is an out-of-scope 5457 /// previous declaration. 5458 /// 5459 /// This routine should be invoked when name lookup has found a 5460 /// previous declaration (PrevDecl) that is not in the scope where a 5461 /// new declaration by the same name is being introduced. If the new 5462 /// declaration occurs in a local scope, previous declarations with 5463 /// linkage may still be considered previous declarations (C99 5464 /// 6.2.2p4-5, C++ [basic.link]p6). 5465 /// 5466 /// \param PrevDecl the previous declaration found by name 5467 /// lookup 5468 /// 5469 /// \param DC the context in which the new declaration is being 5470 /// declared. 5471 /// 5472 /// \returns true if PrevDecl is an out-of-scope previous declaration 5473 /// for a new delcaration with the same name. 5474 static bool 5475 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5476 ASTContext &Context) { 5477 if (!PrevDecl) 5478 return false; 5479 5480 if (!PrevDecl->hasLinkage()) 5481 return false; 5482 5483 if (Context.getLangOpts().CPlusPlus) { 5484 // C++ [basic.link]p6: 5485 // If there is a visible declaration of an entity with linkage 5486 // having the same name and type, ignoring entities declared 5487 // outside the innermost enclosing namespace scope, the block 5488 // scope declaration declares that same entity and receives the 5489 // linkage of the previous declaration. 5490 DeclContext *OuterContext = DC->getRedeclContext(); 5491 if (!OuterContext->isFunctionOrMethod()) 5492 // This rule only applies to block-scope declarations. 5493 return false; 5494 5495 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5496 if (PrevOuterContext->isRecord()) 5497 // We found a member function: ignore it. 5498 return false; 5499 5500 // Find the innermost enclosing namespace for the new and 5501 // previous declarations. 5502 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5503 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5504 5505 // The previous declaration is in a different namespace, so it 5506 // isn't the same function. 5507 if (!OuterContext->Equals(PrevOuterContext)) 5508 return false; 5509 } 5510 5511 return true; 5512 } 5513 5514 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5515 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5516 if (!SS.isSet()) return; 5517 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5518 } 5519 5520 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5521 QualType type = decl->getType(); 5522 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5523 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5524 // Various kinds of declaration aren't allowed to be __autoreleasing. 5525 unsigned kind = -1U; 5526 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5527 if (var->hasAttr<BlocksAttr>()) 5528 kind = 0; // __block 5529 else if (!var->hasLocalStorage()) 5530 kind = 1; // global 5531 } else if (isa<ObjCIvarDecl>(decl)) { 5532 kind = 3; // ivar 5533 } else if (isa<FieldDecl>(decl)) { 5534 kind = 2; // field 5535 } 5536 5537 if (kind != -1U) { 5538 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5539 << kind; 5540 } 5541 } else if (lifetime == Qualifiers::OCL_None) { 5542 // Try to infer lifetime. 5543 if (!type->isObjCLifetimeType()) 5544 return false; 5545 5546 lifetime = type->getObjCARCImplicitLifetime(); 5547 type = Context.getLifetimeQualifiedType(type, lifetime); 5548 decl->setType(type); 5549 } 5550 5551 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5552 // Thread-local variables cannot have lifetime. 5553 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5554 var->getTLSKind()) { 5555 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5556 << var->getType(); 5557 return true; 5558 } 5559 } 5560 5561 return false; 5562 } 5563 5564 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5565 // Ensure that an auto decl is deduced otherwise the checks below might cache 5566 // the wrong linkage. 5567 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5568 5569 // 'weak' only applies to declarations with external linkage. 5570 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5571 if (!ND.isExternallyVisible()) { 5572 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5573 ND.dropAttr<WeakAttr>(); 5574 } 5575 } 5576 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5577 if (ND.isExternallyVisible()) { 5578 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5579 ND.dropAttr<WeakRefAttr>(); 5580 ND.dropAttr<AliasAttr>(); 5581 } 5582 } 5583 5584 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5585 if (VD->hasInit()) { 5586 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5587 assert(VD->isThisDeclarationADefinition() && 5588 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5589 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5590 VD->dropAttr<AliasAttr>(); 5591 } 5592 } 5593 } 5594 5595 // 'selectany' only applies to externally visible variable declarations. 5596 // It does not apply to functions. 5597 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5598 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5599 S.Diag(Attr->getLocation(), 5600 diag::err_attribute_selectany_non_extern_data); 5601 ND.dropAttr<SelectAnyAttr>(); 5602 } 5603 } 5604 5605 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5606 // dll attributes require external linkage. Static locals may have external 5607 // linkage but still cannot be explicitly imported or exported. 5608 auto *VD = dyn_cast<VarDecl>(&ND); 5609 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5610 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5611 << &ND << Attr; 5612 ND.setInvalidDecl(); 5613 } 5614 } 5615 5616 // Virtual functions cannot be marked as 'notail'. 5617 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5618 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5619 if (MD->isVirtual()) { 5620 S.Diag(ND.getLocation(), 5621 diag::err_invalid_attribute_on_virtual_function) 5622 << Attr; 5623 ND.dropAttr<NotTailCalledAttr>(); 5624 } 5625 } 5626 5627 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5628 NamedDecl *NewDecl, 5629 bool IsSpecialization, 5630 bool IsDefinition) { 5631 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5632 OldDecl = OldTD->getTemplatedDecl(); 5633 if (!IsSpecialization) 5634 IsDefinition = false; 5635 } 5636 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5637 NewDecl = NewTD->getTemplatedDecl(); 5638 5639 if (!OldDecl || !NewDecl) 5640 return; 5641 5642 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5643 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5644 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5645 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5646 5647 // dllimport and dllexport are inheritable attributes so we have to exclude 5648 // inherited attribute instances. 5649 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5650 (NewExportAttr && !NewExportAttr->isInherited()); 5651 5652 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5653 // the only exception being explicit specializations. 5654 // Implicitly generated declarations are also excluded for now because there 5655 // is no other way to switch these to use dllimport or dllexport. 5656 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5657 5658 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5659 // Allow with a warning for free functions and global variables. 5660 bool JustWarn = false; 5661 if (!OldDecl->isCXXClassMember()) { 5662 auto *VD = dyn_cast<VarDecl>(OldDecl); 5663 if (VD && !VD->getDescribedVarTemplate()) 5664 JustWarn = true; 5665 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5666 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5667 JustWarn = true; 5668 } 5669 5670 // We cannot change a declaration that's been used because IR has already 5671 // been emitted. Dllimported functions will still work though (modulo 5672 // address equality) as they can use the thunk. 5673 if (OldDecl->isUsed()) 5674 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5675 JustWarn = false; 5676 5677 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5678 : diag::err_attribute_dll_redeclaration; 5679 S.Diag(NewDecl->getLocation(), DiagID) 5680 << NewDecl 5681 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5682 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5683 if (!JustWarn) { 5684 NewDecl->setInvalidDecl(); 5685 return; 5686 } 5687 } 5688 5689 // A redeclaration is not allowed to drop a dllimport attribute, the only 5690 // exceptions being inline function definitions, local extern declarations, 5691 // qualified friend declarations or special MSVC extension: in the last case, 5692 // the declaration is treated as if it were marked dllexport. 5693 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5694 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5695 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5696 // Ignore static data because out-of-line definitions are diagnosed 5697 // separately. 5698 IsStaticDataMember = VD->isStaticDataMember(); 5699 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5700 VarDecl::DeclarationOnly; 5701 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5702 IsInline = FD->isInlined(); 5703 IsQualifiedFriend = FD->getQualifier() && 5704 FD->getFriendObjectKind() == Decl::FOK_Declared; 5705 } 5706 5707 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5708 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5709 if (IsMicrosoft && IsDefinition) { 5710 S.Diag(NewDecl->getLocation(), 5711 diag::warn_redeclaration_without_import_attribute) 5712 << NewDecl; 5713 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5714 NewDecl->dropAttr<DLLImportAttr>(); 5715 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5716 NewImportAttr->getRange(), S.Context, 5717 NewImportAttr->getSpellingListIndex())); 5718 } else { 5719 S.Diag(NewDecl->getLocation(), 5720 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5721 << NewDecl << OldImportAttr; 5722 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5723 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5724 OldDecl->dropAttr<DLLImportAttr>(); 5725 NewDecl->dropAttr<DLLImportAttr>(); 5726 } 5727 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5728 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5729 OldDecl->dropAttr<DLLImportAttr>(); 5730 NewDecl->dropAttr<DLLImportAttr>(); 5731 S.Diag(NewDecl->getLocation(), 5732 diag::warn_dllimport_dropped_from_inline_function) 5733 << NewDecl << OldImportAttr; 5734 } 5735 } 5736 5737 /// Given that we are within the definition of the given function, 5738 /// will that definition behave like C99's 'inline', where the 5739 /// definition is discarded except for optimization purposes? 5740 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5741 // Try to avoid calling GetGVALinkageForFunction. 5742 5743 // All cases of this require the 'inline' keyword. 5744 if (!FD->isInlined()) return false; 5745 5746 // This is only possible in C++ with the gnu_inline attribute. 5747 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5748 return false; 5749 5750 // Okay, go ahead and call the relatively-more-expensive function. 5751 5752 #ifndef NDEBUG 5753 // AST quite reasonably asserts that it's working on a function 5754 // definition. We don't really have a way to tell it that we're 5755 // currently defining the function, so just lie to it in +Asserts 5756 // builds. This is an awful hack. 5757 FD->setLazyBody(1); 5758 #endif 5759 5760 bool isC99Inline = 5761 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5762 5763 #ifndef NDEBUG 5764 FD->setLazyBody(0); 5765 #endif 5766 5767 return isC99Inline; 5768 } 5769 5770 /// Determine whether a variable is extern "C" prior to attaching 5771 /// an initializer. We can't just call isExternC() here, because that 5772 /// will also compute and cache whether the declaration is externally 5773 /// visible, which might change when we attach the initializer. 5774 /// 5775 /// This can only be used if the declaration is known to not be a 5776 /// redeclaration of an internal linkage declaration. 5777 /// 5778 /// For instance: 5779 /// 5780 /// auto x = []{}; 5781 /// 5782 /// Attaching the initializer here makes this declaration not externally 5783 /// visible, because its type has internal linkage. 5784 /// 5785 /// FIXME: This is a hack. 5786 template<typename T> 5787 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5788 if (S.getLangOpts().CPlusPlus) { 5789 // In C++, the overloadable attribute negates the effects of extern "C". 5790 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5791 return false; 5792 5793 // So do CUDA's host/device attributes. 5794 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 5795 D->template hasAttr<CUDAHostAttr>())) 5796 return false; 5797 } 5798 return D->isExternC(); 5799 } 5800 5801 static bool shouldConsiderLinkage(const VarDecl *VD) { 5802 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5803 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 5804 return VD->hasExternalStorage(); 5805 if (DC->isFileContext()) 5806 return true; 5807 if (DC->isRecord()) 5808 return false; 5809 llvm_unreachable("Unexpected context"); 5810 } 5811 5812 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5813 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5814 if (DC->isFileContext() || DC->isFunctionOrMethod() || 5815 isa<OMPDeclareReductionDecl>(DC)) 5816 return true; 5817 if (DC->isRecord()) 5818 return false; 5819 llvm_unreachable("Unexpected context"); 5820 } 5821 5822 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5823 AttributeList::Kind Kind) { 5824 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5825 if (L->getKind() == Kind) 5826 return true; 5827 return false; 5828 } 5829 5830 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5831 AttributeList::Kind Kind) { 5832 // Check decl attributes on the DeclSpec. 5833 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5834 return true; 5835 5836 // Walk the declarator structure, checking decl attributes that were in a type 5837 // position to the decl itself. 5838 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5839 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5840 return true; 5841 } 5842 5843 // Finally, check attributes on the decl itself. 5844 return hasParsedAttr(S, PD.getAttributes(), Kind); 5845 } 5846 5847 /// Adjust the \c DeclContext for a function or variable that might be a 5848 /// function-local external declaration. 5849 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5850 if (!DC->isFunctionOrMethod()) 5851 return false; 5852 5853 // If this is a local extern function or variable declared within a function 5854 // template, don't add it into the enclosing namespace scope until it is 5855 // instantiated; it might have a dependent type right now. 5856 if (DC->isDependentContext()) 5857 return true; 5858 5859 // C++11 [basic.link]p7: 5860 // When a block scope declaration of an entity with linkage is not found to 5861 // refer to some other declaration, then that entity is a member of the 5862 // innermost enclosing namespace. 5863 // 5864 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5865 // semantically-enclosing namespace, not a lexically-enclosing one. 5866 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5867 DC = DC->getParent(); 5868 return true; 5869 } 5870 5871 /// \brief Returns true if given declaration has external C language linkage. 5872 static bool isDeclExternC(const Decl *D) { 5873 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5874 return FD->isExternC(); 5875 if (const auto *VD = dyn_cast<VarDecl>(D)) 5876 return VD->isExternC(); 5877 5878 llvm_unreachable("Unknown type of decl!"); 5879 } 5880 5881 NamedDecl *Sema::ActOnVariableDeclarator( 5882 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 5883 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 5884 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 5885 QualType R = TInfo->getType(); 5886 DeclarationName Name = GetNameForDeclarator(D).getName(); 5887 5888 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5889 5890 if (D.isDecompositionDeclarator()) { 5891 AddToScope = false; 5892 // Take the name of the first declarator as our name for diagnostic 5893 // purposes. 5894 auto &Decomp = D.getDecompositionDeclarator(); 5895 if (!Decomp.bindings().empty()) { 5896 II = Decomp.bindings()[0].Name; 5897 Name = II; 5898 } 5899 } else if (!II) { 5900 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5901 << Name; 5902 return nullptr; 5903 } 5904 5905 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 5906 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 5907 // argument. 5908 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) { 5909 Diag(D.getIdentifierLoc(), 5910 diag::err_opencl_type_can_only_be_used_as_function_parameter) 5911 << R; 5912 D.setInvalidType(); 5913 return nullptr; 5914 } 5915 5916 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5917 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5918 5919 // dllimport globals without explicit storage class are treated as extern. We 5920 // have to change the storage class this early to get the right DeclContext. 5921 if (SC == SC_None && !DC->isRecord() && 5922 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5923 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5924 SC = SC_Extern; 5925 5926 DeclContext *OriginalDC = DC; 5927 bool IsLocalExternDecl = SC == SC_Extern && 5928 adjustContextForLocalExternDecl(DC); 5929 5930 if (getLangOpts().OpenCL) { 5931 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5932 QualType NR = R; 5933 while (NR->isPointerType()) { 5934 if (NR->isFunctionPointerType()) { 5935 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5936 D.setInvalidType(); 5937 break; 5938 } 5939 NR = NR->getPointeeType(); 5940 } 5941 5942 if (!getOpenCLOptions().cl_khr_fp16) { 5943 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5944 // half array type (unless the cl_khr_fp16 extension is enabled). 5945 if (Context.getBaseElementType(R)->isHalfType()) { 5946 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5947 D.setInvalidType(); 5948 } 5949 } 5950 } 5951 5952 if (SCSpec == DeclSpec::SCS_mutable) { 5953 // mutable can only appear on non-static class members, so it's always 5954 // an error here 5955 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5956 D.setInvalidType(); 5957 SC = SC_None; 5958 } 5959 5960 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5961 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5962 D.getDeclSpec().getStorageClassSpecLoc())) { 5963 // In C++11, the 'register' storage class specifier is deprecated. 5964 // Suppress the warning in system macros, it's used in macros in some 5965 // popular C system headers, such as in glibc's htonl() macro. 5966 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5967 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 5968 : diag::warn_deprecated_register) 5969 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5970 } 5971 5972 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5973 5974 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5975 // C99 6.9p2: The storage-class specifiers auto and register shall not 5976 // appear in the declaration specifiers in an external declaration. 5977 // Global Register+Asm is a GNU extension we support. 5978 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5979 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5980 D.setInvalidType(); 5981 } 5982 } 5983 5984 if (getLangOpts().OpenCL) { 5985 // OpenCL v1.2 s6.9.b p4: 5986 // The sampler type cannot be used with the __local and __global address 5987 // space qualifiers. 5988 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5989 R.getAddressSpace() == LangAS::opencl_global)) { 5990 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5991 } 5992 5993 // OpenCL 1.2 spec, p6.9 r: 5994 // The event type cannot be used to declare a program scope variable. 5995 // The event type cannot be used with the __local, __constant and __global 5996 // address space qualifiers. 5997 if (R->isEventT()) { 5998 if (S->getParent() == nullptr) { 5999 Diag(D.getLocStart(), diag::err_event_t_global_var); 6000 D.setInvalidType(); 6001 } 6002 6003 if (R.getAddressSpace()) { 6004 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6005 D.setInvalidType(); 6006 } 6007 } 6008 } 6009 6010 bool IsExplicitSpecialization = false; 6011 bool IsVariableTemplateSpecialization = false; 6012 bool IsPartialSpecialization = false; 6013 bool IsVariableTemplate = false; 6014 VarDecl *NewVD = nullptr; 6015 VarTemplateDecl *NewTemplate = nullptr; 6016 TemplateParameterList *TemplateParams = nullptr; 6017 if (!getLangOpts().CPlusPlus) { 6018 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6019 D.getIdentifierLoc(), II, 6020 R, TInfo, SC); 6021 6022 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6023 ParsingInitForAutoVars.insert(NewVD); 6024 6025 if (D.isInvalidType()) 6026 NewVD->setInvalidDecl(); 6027 } else { 6028 bool Invalid = false; 6029 6030 if (DC->isRecord() && !CurContext->isRecord()) { 6031 // This is an out-of-line definition of a static data member. 6032 switch (SC) { 6033 case SC_None: 6034 break; 6035 case SC_Static: 6036 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6037 diag::err_static_out_of_line) 6038 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6039 break; 6040 case SC_Auto: 6041 case SC_Register: 6042 case SC_Extern: 6043 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6044 // to names of variables declared in a block or to function parameters. 6045 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6046 // of class members 6047 6048 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6049 diag::err_storage_class_for_static_member) 6050 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6051 break; 6052 case SC_PrivateExtern: 6053 llvm_unreachable("C storage class in c++!"); 6054 } 6055 } 6056 6057 if (SC == SC_Static && CurContext->isRecord()) { 6058 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6059 if (RD->isLocalClass()) 6060 Diag(D.getIdentifierLoc(), 6061 diag::err_static_data_member_not_allowed_in_local_class) 6062 << Name << RD->getDeclName(); 6063 6064 // C++98 [class.union]p1: If a union contains a static data member, 6065 // the program is ill-formed. C++11 drops this restriction. 6066 if (RD->isUnion()) 6067 Diag(D.getIdentifierLoc(), 6068 getLangOpts().CPlusPlus11 6069 ? diag::warn_cxx98_compat_static_data_member_in_union 6070 : diag::ext_static_data_member_in_union) << Name; 6071 // We conservatively disallow static data members in anonymous structs. 6072 else if (!RD->getDeclName()) 6073 Diag(D.getIdentifierLoc(), 6074 diag::err_static_data_member_not_allowed_in_anon_struct) 6075 << Name << RD->isUnion(); 6076 } 6077 } 6078 6079 // Match up the template parameter lists with the scope specifier, then 6080 // determine whether we have a template or a template specialization. 6081 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6082 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6083 D.getCXXScopeSpec(), 6084 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6085 ? D.getName().TemplateId 6086 : nullptr, 6087 TemplateParamLists, 6088 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 6089 6090 if (TemplateParams) { 6091 if (!TemplateParams->size() && 6092 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6093 // There is an extraneous 'template<>' for this variable. Complain 6094 // about it, but allow the declaration of the variable. 6095 Diag(TemplateParams->getTemplateLoc(), 6096 diag::err_template_variable_noparams) 6097 << II 6098 << SourceRange(TemplateParams->getTemplateLoc(), 6099 TemplateParams->getRAngleLoc()); 6100 TemplateParams = nullptr; 6101 } else { 6102 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6103 // This is an explicit specialization or a partial specialization. 6104 // FIXME: Check that we can declare a specialization here. 6105 IsVariableTemplateSpecialization = true; 6106 IsPartialSpecialization = TemplateParams->size() > 0; 6107 } else { // if (TemplateParams->size() > 0) 6108 // This is a template declaration. 6109 IsVariableTemplate = true; 6110 6111 // Check that we can declare a template here. 6112 if (CheckTemplateDeclScope(S, TemplateParams)) 6113 return nullptr; 6114 6115 // Only C++1y supports variable templates (N3651). 6116 Diag(D.getIdentifierLoc(), 6117 getLangOpts().CPlusPlus14 6118 ? diag::warn_cxx11_compat_variable_template 6119 : diag::ext_variable_template); 6120 } 6121 } 6122 } else { 6123 assert( 6124 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6125 "should have a 'template<>' for this decl"); 6126 } 6127 6128 if (IsVariableTemplateSpecialization) { 6129 SourceLocation TemplateKWLoc = 6130 TemplateParamLists.size() > 0 6131 ? TemplateParamLists[0]->getTemplateLoc() 6132 : SourceLocation(); 6133 DeclResult Res = ActOnVarTemplateSpecialization( 6134 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6135 IsPartialSpecialization); 6136 if (Res.isInvalid()) 6137 return nullptr; 6138 NewVD = cast<VarDecl>(Res.get()); 6139 AddToScope = false; 6140 } else if (D.isDecompositionDeclarator()) { 6141 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6142 D.getIdentifierLoc(), R, TInfo, SC, 6143 Bindings); 6144 } else 6145 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6146 D.getIdentifierLoc(), II, R, TInfo, SC); 6147 6148 // If this is supposed to be a variable template, create it as such. 6149 if (IsVariableTemplate) { 6150 NewTemplate = 6151 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6152 TemplateParams, NewVD); 6153 NewVD->setDescribedVarTemplate(NewTemplate); 6154 } 6155 6156 // If this decl has an auto type in need of deduction, make a note of the 6157 // Decl so we can diagnose uses of it in its own initializer. 6158 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 6159 ParsingInitForAutoVars.insert(NewVD); 6160 6161 if (D.isInvalidType() || Invalid) { 6162 NewVD->setInvalidDecl(); 6163 if (NewTemplate) 6164 NewTemplate->setInvalidDecl(); 6165 } 6166 6167 SetNestedNameSpecifier(NewVD, D); 6168 6169 // If we have any template parameter lists that don't directly belong to 6170 // the variable (matching the scope specifier), store them. 6171 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6172 if (TemplateParamLists.size() > VDTemplateParamLists) 6173 NewVD->setTemplateParameterListsInfo( 6174 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6175 6176 if (D.getDeclSpec().isConstexprSpecified()) { 6177 NewVD->setConstexpr(true); 6178 // C++1z [dcl.spec.constexpr]p1: 6179 // A static data member declared with the constexpr specifier is 6180 // implicitly an inline variable. 6181 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6182 NewVD->setImplicitlyInline(); 6183 } 6184 6185 if (D.getDeclSpec().isConceptSpecified()) { 6186 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6187 VTD->setConcept(); 6188 6189 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6190 // be declared with the thread_local, inline, friend, or constexpr 6191 // specifiers, [...] 6192 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6193 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6194 diag::err_concept_decl_invalid_specifiers) 6195 << 0 << 0; 6196 NewVD->setInvalidDecl(true); 6197 } 6198 6199 if (D.getDeclSpec().isConstexprSpecified()) { 6200 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6201 diag::err_concept_decl_invalid_specifiers) 6202 << 0 << 3; 6203 NewVD->setInvalidDecl(true); 6204 } 6205 6206 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6207 // applied only to the definition of a function template or variable 6208 // template, declared in namespace scope. 6209 if (IsVariableTemplateSpecialization) { 6210 Diag(D.getDeclSpec().getConceptSpecLoc(), 6211 diag::err_concept_specified_specialization) 6212 << (IsPartialSpecialization ? 2 : 1); 6213 } 6214 6215 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6216 // following restrictions: 6217 // - The declared type shall have the type bool. 6218 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6219 !NewVD->isInvalidDecl()) { 6220 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6221 NewVD->setInvalidDecl(true); 6222 } 6223 } 6224 } 6225 6226 if (D.getDeclSpec().isInlineSpecified()) { 6227 if (!getLangOpts().CPlusPlus) { 6228 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6229 << 0; 6230 } else if (CurContext->isFunctionOrMethod()) { 6231 // 'inline' is not allowed on block scope variable declaration. 6232 Diag(D.getDeclSpec().getInlineSpecLoc(), 6233 diag::err_inline_declaration_block_scope) << Name 6234 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6235 } else { 6236 Diag(D.getDeclSpec().getInlineSpecLoc(), 6237 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6238 : diag::ext_inline_variable); 6239 NewVD->setInlineSpecified(); 6240 } 6241 } 6242 6243 // Set the lexical context. If the declarator has a C++ scope specifier, the 6244 // lexical context will be different from the semantic context. 6245 NewVD->setLexicalDeclContext(CurContext); 6246 if (NewTemplate) 6247 NewTemplate->setLexicalDeclContext(CurContext); 6248 6249 if (IsLocalExternDecl) { 6250 if (D.isDecompositionDeclarator()) 6251 for (auto *B : Bindings) 6252 B->setLocalExternDecl(); 6253 else 6254 NewVD->setLocalExternDecl(); 6255 } 6256 6257 bool EmitTLSUnsupportedError = false; 6258 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6259 // C++11 [dcl.stc]p4: 6260 // When thread_local is applied to a variable of block scope the 6261 // storage-class-specifier static is implied if it does not appear 6262 // explicitly. 6263 // Core issue: 'static' is not implied if the variable is declared 6264 // 'extern'. 6265 if (NewVD->hasLocalStorage() && 6266 (SCSpec != DeclSpec::SCS_unspecified || 6267 TSCS != DeclSpec::TSCS_thread_local || 6268 !DC->isFunctionOrMethod())) 6269 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6270 diag::err_thread_non_global) 6271 << DeclSpec::getSpecifierName(TSCS); 6272 else if (!Context.getTargetInfo().isTLSSupported()) { 6273 if (getLangOpts().CUDA) { 6274 // Postpone error emission until we've collected attributes required to 6275 // figure out whether it's a host or device variable and whether the 6276 // error should be ignored. 6277 EmitTLSUnsupportedError = true; 6278 // We still need to mark the variable as TLS so it shows up in AST with 6279 // proper storage class for other tools to use even if we're not going 6280 // to emit any code for it. 6281 NewVD->setTSCSpec(TSCS); 6282 } else 6283 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6284 diag::err_thread_unsupported); 6285 } else 6286 NewVD->setTSCSpec(TSCS); 6287 } 6288 6289 // C99 6.7.4p3 6290 // An inline definition of a function with external linkage shall 6291 // not contain a definition of a modifiable object with static or 6292 // thread storage duration... 6293 // We only apply this when the function is required to be defined 6294 // elsewhere, i.e. when the function is not 'extern inline'. Note 6295 // that a local variable with thread storage duration still has to 6296 // be marked 'static'. Also note that it's possible to get these 6297 // semantics in C++ using __attribute__((gnu_inline)). 6298 if (SC == SC_Static && S->getFnParent() != nullptr && 6299 !NewVD->getType().isConstQualified()) { 6300 FunctionDecl *CurFD = getCurFunctionDecl(); 6301 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6302 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6303 diag::warn_static_local_in_extern_inline); 6304 MaybeSuggestAddingStaticToDecl(CurFD); 6305 } 6306 } 6307 6308 if (D.getDeclSpec().isModulePrivateSpecified()) { 6309 if (IsVariableTemplateSpecialization) 6310 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6311 << (IsPartialSpecialization ? 1 : 0) 6312 << FixItHint::CreateRemoval( 6313 D.getDeclSpec().getModulePrivateSpecLoc()); 6314 else if (IsExplicitSpecialization) 6315 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6316 << 2 6317 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6318 else if (NewVD->hasLocalStorage()) 6319 Diag(NewVD->getLocation(), diag::err_module_private_local) 6320 << 0 << NewVD->getDeclName() 6321 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6322 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6323 else { 6324 NewVD->setModulePrivate(); 6325 if (NewTemplate) 6326 NewTemplate->setModulePrivate(); 6327 for (auto *B : Bindings) 6328 B->setModulePrivate(); 6329 } 6330 } 6331 6332 // Handle attributes prior to checking for duplicates in MergeVarDecl 6333 ProcessDeclAttributes(S, NewVD, D); 6334 6335 if (getLangOpts().CUDA) { 6336 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6337 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6338 diag::err_thread_unsupported); 6339 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6340 // storage [duration]." 6341 if (SC == SC_None && S->getFnParent() != nullptr && 6342 (NewVD->hasAttr<CUDASharedAttr>() || 6343 NewVD->hasAttr<CUDAConstantAttr>())) { 6344 NewVD->setStorageClass(SC_Static); 6345 } 6346 } 6347 6348 // Ensure that dllimport globals without explicit storage class are treated as 6349 // extern. The storage class is set above using parsed attributes. Now we can 6350 // check the VarDecl itself. 6351 assert(!NewVD->hasAttr<DLLImportAttr>() || 6352 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6353 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6354 6355 // In auto-retain/release, infer strong retension for variables of 6356 // retainable type. 6357 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6358 NewVD->setInvalidDecl(); 6359 6360 // Handle GNU asm-label extension (encoded as an attribute). 6361 if (Expr *E = (Expr*)D.getAsmLabel()) { 6362 // The parser guarantees this is a string. 6363 StringLiteral *SE = cast<StringLiteral>(E); 6364 StringRef Label = SE->getString(); 6365 if (S->getFnParent() != nullptr) { 6366 switch (SC) { 6367 case SC_None: 6368 case SC_Auto: 6369 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6370 break; 6371 case SC_Register: 6372 // Local Named register 6373 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6374 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6375 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6376 break; 6377 case SC_Static: 6378 case SC_Extern: 6379 case SC_PrivateExtern: 6380 break; 6381 } 6382 } else if (SC == SC_Register) { 6383 // Global Named register 6384 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6385 const auto &TI = Context.getTargetInfo(); 6386 bool HasSizeMismatch; 6387 6388 if (!TI.isValidGCCRegisterName(Label)) 6389 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6390 else if (!TI.validateGlobalRegisterVariable(Label, 6391 Context.getTypeSize(R), 6392 HasSizeMismatch)) 6393 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6394 else if (HasSizeMismatch) 6395 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6396 } 6397 6398 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6399 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6400 NewVD->setInvalidDecl(true); 6401 } 6402 } 6403 6404 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6405 Context, Label, 0)); 6406 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6407 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6408 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6409 if (I != ExtnameUndeclaredIdentifiers.end()) { 6410 if (isDeclExternC(NewVD)) { 6411 NewVD->addAttr(I->second); 6412 ExtnameUndeclaredIdentifiers.erase(I); 6413 } else 6414 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6415 << /*Variable*/1 << NewVD; 6416 } 6417 } 6418 6419 // Diagnose shadowed variables before filtering for scope. 6420 if (D.getCXXScopeSpec().isEmpty()) 6421 CheckShadow(S, NewVD, Previous); 6422 6423 // Don't consider existing declarations that are in a different 6424 // scope and are out-of-semantic-context declarations (if the new 6425 // declaration has linkage). 6426 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6427 D.getCXXScopeSpec().isNotEmpty() || 6428 IsExplicitSpecialization || 6429 IsVariableTemplateSpecialization); 6430 6431 // Check whether the previous declaration is in the same block scope. This 6432 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6433 if (getLangOpts().CPlusPlus && 6434 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6435 NewVD->setPreviousDeclInSameBlockScope( 6436 Previous.isSingleResult() && !Previous.isShadowed() && 6437 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6438 6439 if (!getLangOpts().CPlusPlus) { 6440 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6441 } else { 6442 // If this is an explicit specialization of a static data member, check it. 6443 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6444 CheckMemberSpecialization(NewVD, Previous)) 6445 NewVD->setInvalidDecl(); 6446 6447 // Merge the decl with the existing one if appropriate. 6448 if (!Previous.empty()) { 6449 if (Previous.isSingleResult() && 6450 isa<FieldDecl>(Previous.getFoundDecl()) && 6451 D.getCXXScopeSpec().isSet()) { 6452 // The user tried to define a non-static data member 6453 // out-of-line (C++ [dcl.meaning]p1). 6454 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6455 << D.getCXXScopeSpec().getRange(); 6456 Previous.clear(); 6457 NewVD->setInvalidDecl(); 6458 } 6459 } else if (D.getCXXScopeSpec().isSet()) { 6460 // No previous declaration in the qualifying scope. 6461 Diag(D.getIdentifierLoc(), diag::err_no_member) 6462 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6463 << D.getCXXScopeSpec().getRange(); 6464 NewVD->setInvalidDecl(); 6465 } 6466 6467 if (!IsVariableTemplateSpecialization) 6468 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6469 6470 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6471 // an explicit specialization (14.8.3) or a partial specialization of a 6472 // concept definition. 6473 if (IsVariableTemplateSpecialization && 6474 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6475 Previous.isSingleResult()) { 6476 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6477 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6478 if (VarTmpl->isConcept()) { 6479 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6480 << 1 /*variable*/ 6481 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6482 : 1 /*explicitly specialized*/); 6483 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6484 NewVD->setInvalidDecl(); 6485 } 6486 } 6487 } 6488 6489 if (NewTemplate) { 6490 VarTemplateDecl *PrevVarTemplate = 6491 NewVD->getPreviousDecl() 6492 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6493 : nullptr; 6494 6495 // Check the template parameter list of this declaration, possibly 6496 // merging in the template parameter list from the previous variable 6497 // template declaration. 6498 if (CheckTemplateParameterList( 6499 TemplateParams, 6500 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6501 : nullptr, 6502 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6503 DC->isDependentContext()) 6504 ? TPC_ClassTemplateMember 6505 : TPC_VarTemplate)) 6506 NewVD->setInvalidDecl(); 6507 6508 // If we are providing an explicit specialization of a static variable 6509 // template, make a note of that. 6510 if (PrevVarTemplate && 6511 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6512 PrevVarTemplate->setMemberSpecialization(); 6513 } 6514 } 6515 6516 ProcessPragmaWeak(S, NewVD); 6517 6518 // If this is the first declaration of an extern C variable, update 6519 // the map of such variables. 6520 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6521 isIncompleteDeclExternC(*this, NewVD)) 6522 RegisterLocallyScopedExternCDecl(NewVD, S); 6523 6524 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6525 Decl *ManglingContextDecl; 6526 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6527 NewVD->getDeclContext(), ManglingContextDecl)) { 6528 Context.setManglingNumber( 6529 NewVD, MCtx->getManglingNumber( 6530 NewVD, getMSManglingNumber(getLangOpts(), S))); 6531 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6532 } 6533 } 6534 6535 // Special handling of variable named 'main'. 6536 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6537 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6538 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6539 6540 // C++ [basic.start.main]p3 6541 // A program that declares a variable main at global scope is ill-formed. 6542 if (getLangOpts().CPlusPlus) 6543 Diag(D.getLocStart(), diag::err_main_global_variable); 6544 6545 // In C, and external-linkage variable named main results in undefined 6546 // behavior. 6547 else if (NewVD->hasExternalFormalLinkage()) 6548 Diag(D.getLocStart(), diag::warn_main_redefined); 6549 } 6550 6551 if (D.isRedeclaration() && !Previous.empty()) { 6552 checkDLLAttributeRedeclaration( 6553 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6554 IsExplicitSpecialization, D.isFunctionDefinition()); 6555 } 6556 6557 if (NewTemplate) { 6558 if (NewVD->isInvalidDecl()) 6559 NewTemplate->setInvalidDecl(); 6560 ActOnDocumentableDecl(NewTemplate); 6561 return NewTemplate; 6562 } 6563 6564 return NewVD; 6565 } 6566 6567 /// Enum describing the %select options in diag::warn_decl_shadow. 6568 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field }; 6569 6570 /// Determine what kind of declaration we're shadowing. 6571 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6572 const DeclContext *OldDC) { 6573 if (isa<RecordDecl>(OldDC)) 6574 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6575 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6576 } 6577 6578 /// \brief Diagnose variable or built-in function shadowing. Implements 6579 /// -Wshadow. 6580 /// 6581 /// This method is called whenever a VarDecl is added to a "useful" 6582 /// scope. 6583 /// 6584 /// \param S the scope in which the shadowing name is being declared 6585 /// \param R the lookup of the name 6586 /// 6587 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6588 // Return if warning is ignored. 6589 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6590 return; 6591 6592 // Don't diagnose declarations at file scope. 6593 if (D->hasGlobalStorage()) 6594 return; 6595 6596 DeclContext *NewDC = D->getDeclContext(); 6597 6598 // Only diagnose if we're shadowing an unambiguous field or variable. 6599 if (R.getResultKind() != LookupResult::Found) 6600 return; 6601 6602 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6603 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6604 return; 6605 6606 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6607 // Fields are not shadowed by variables in C++ static methods. 6608 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6609 if (MD->isStatic()) 6610 return; 6611 6612 // Fields shadowed by constructor parameters are a special case. Usually 6613 // the constructor initializes the field with the parameter. 6614 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) { 6615 // Remember that this was shadowed so we can either warn about its 6616 // modification or its existence depending on warning settings. 6617 D = D->getCanonicalDecl(); 6618 ShadowingDecls.insert({D, FD}); 6619 return; 6620 } 6621 } 6622 6623 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6624 if (shadowedVar->isExternC()) { 6625 // For shadowing external vars, make sure that we point to the global 6626 // declaration, not a locally scoped extern declaration. 6627 for (auto I : shadowedVar->redecls()) 6628 if (I->isFileVarDecl()) { 6629 ShadowedDecl = I; 6630 break; 6631 } 6632 } 6633 6634 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6635 6636 // Only warn about certain kinds of shadowing for class members. 6637 if (NewDC && NewDC->isRecord()) { 6638 // In particular, don't warn about shadowing non-class members. 6639 if (!OldDC->isRecord()) 6640 return; 6641 6642 // TODO: should we warn about static data members shadowing 6643 // static data members from base classes? 6644 6645 // TODO: don't diagnose for inaccessible shadowed members. 6646 // This is hard to do perfectly because we might friend the 6647 // shadowing context, but that's just a false negative. 6648 } 6649 6650 6651 DeclarationName Name = R.getLookupName(); 6652 6653 // Emit warning and note. 6654 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6655 return; 6656 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6657 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6658 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6659 } 6660 6661 /// \brief Check -Wshadow without the advantage of a previous lookup. 6662 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6663 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6664 return; 6665 6666 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6667 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6668 LookupName(R, S); 6669 CheckShadow(S, D, R); 6670 } 6671 6672 /// Check if 'E', which is an expression that is about to be modified, refers 6673 /// to a constructor parameter that shadows a field. 6674 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 6675 // Quickly ignore expressions that can't be shadowing ctor parameters. 6676 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 6677 return; 6678 E = E->IgnoreParenImpCasts(); 6679 auto *DRE = dyn_cast<DeclRefExpr>(E); 6680 if (!DRE) 6681 return; 6682 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 6683 auto I = ShadowingDecls.find(D); 6684 if (I == ShadowingDecls.end()) 6685 return; 6686 const NamedDecl *ShadowedDecl = I->second; 6687 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6688 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 6689 Diag(D->getLocation(), diag::note_var_declared_here) << D; 6690 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6691 6692 // Avoid issuing multiple warnings about the same decl. 6693 ShadowingDecls.erase(I); 6694 } 6695 6696 /// Check for conflict between this global or extern "C" declaration and 6697 /// previous global or extern "C" declarations. This is only used in C++. 6698 template<typename T> 6699 static bool checkGlobalOrExternCConflict( 6700 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6701 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6702 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6703 6704 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6705 // The common case: this global doesn't conflict with any extern "C" 6706 // declaration. 6707 return false; 6708 } 6709 6710 if (Prev) { 6711 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6712 // Both the old and new declarations have C language linkage. This is a 6713 // redeclaration. 6714 Previous.clear(); 6715 Previous.addDecl(Prev); 6716 return true; 6717 } 6718 6719 // This is a global, non-extern "C" declaration, and there is a previous 6720 // non-global extern "C" declaration. Diagnose if this is a variable 6721 // declaration. 6722 if (!isa<VarDecl>(ND)) 6723 return false; 6724 } else { 6725 // The declaration is extern "C". Check for any declaration in the 6726 // translation unit which might conflict. 6727 if (IsGlobal) { 6728 // We have already performed the lookup into the translation unit. 6729 IsGlobal = false; 6730 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6731 I != E; ++I) { 6732 if (isa<VarDecl>(*I)) { 6733 Prev = *I; 6734 break; 6735 } 6736 } 6737 } else { 6738 DeclContext::lookup_result R = 6739 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6740 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6741 I != E; ++I) { 6742 if (isa<VarDecl>(*I)) { 6743 Prev = *I; 6744 break; 6745 } 6746 // FIXME: If we have any other entity with this name in global scope, 6747 // the declaration is ill-formed, but that is a defect: it breaks the 6748 // 'stat' hack, for instance. Only variables can have mangled name 6749 // clashes with extern "C" declarations, so only they deserve a 6750 // diagnostic. 6751 } 6752 } 6753 6754 if (!Prev) 6755 return false; 6756 } 6757 6758 // Use the first declaration's location to ensure we point at something which 6759 // is lexically inside an extern "C" linkage-spec. 6760 assert(Prev && "should have found a previous declaration to diagnose"); 6761 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6762 Prev = FD->getFirstDecl(); 6763 else 6764 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6765 6766 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6767 << IsGlobal << ND; 6768 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6769 << IsGlobal; 6770 return false; 6771 } 6772 6773 /// Apply special rules for handling extern "C" declarations. Returns \c true 6774 /// if we have found that this is a redeclaration of some prior entity. 6775 /// 6776 /// Per C++ [dcl.link]p6: 6777 /// Two declarations [for a function or variable] with C language linkage 6778 /// with the same name that appear in different scopes refer to the same 6779 /// [entity]. An entity with C language linkage shall not be declared with 6780 /// the same name as an entity in global scope. 6781 template<typename T> 6782 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6783 LookupResult &Previous) { 6784 if (!S.getLangOpts().CPlusPlus) { 6785 // In C, when declaring a global variable, look for a corresponding 'extern' 6786 // variable declared in function scope. We don't need this in C++, because 6787 // we find local extern decls in the surrounding file-scope DeclContext. 6788 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6789 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6790 Previous.clear(); 6791 Previous.addDecl(Prev); 6792 return true; 6793 } 6794 } 6795 return false; 6796 } 6797 6798 // A declaration in the translation unit can conflict with an extern "C" 6799 // declaration. 6800 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6801 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6802 6803 // An extern "C" declaration can conflict with a declaration in the 6804 // translation unit or can be a redeclaration of an extern "C" declaration 6805 // in another scope. 6806 if (isIncompleteDeclExternC(S,ND)) 6807 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6808 6809 // Neither global nor extern "C": nothing to do. 6810 return false; 6811 } 6812 6813 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6814 // If the decl is already known invalid, don't check it. 6815 if (NewVD->isInvalidDecl()) 6816 return; 6817 6818 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6819 QualType T = TInfo->getType(); 6820 6821 // Defer checking an 'auto' type until its initializer is attached. 6822 if (T->isUndeducedType()) 6823 return; 6824 6825 if (NewVD->hasAttrs()) 6826 CheckAlignasUnderalignment(NewVD); 6827 6828 if (T->isObjCObjectType()) { 6829 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6830 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6831 T = Context.getObjCObjectPointerType(T); 6832 NewVD->setType(T); 6833 } 6834 6835 // Emit an error if an address space was applied to decl with local storage. 6836 // This includes arrays of objects with address space qualifiers, but not 6837 // automatic variables that point to other address spaces. 6838 // ISO/IEC TR 18037 S5.1.2 6839 if (!getLangOpts().OpenCL 6840 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6841 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6842 NewVD->setInvalidDecl(); 6843 return; 6844 } 6845 6846 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 6847 // scope. 6848 if (getLangOpts().OpenCLVersion == 120 && 6849 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6850 NewVD->isStaticLocal()) { 6851 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6852 NewVD->setInvalidDecl(); 6853 return; 6854 } 6855 6856 if (getLangOpts().OpenCL) { 6857 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 6858 if (NewVD->hasAttr<BlocksAttr>()) { 6859 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 6860 return; 6861 } 6862 6863 if (T->isBlockPointerType()) { 6864 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 6865 // can't use 'extern' storage class. 6866 if (!T.isConstQualified()) { 6867 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 6868 << 0 /*const*/; 6869 NewVD->setInvalidDecl(); 6870 return; 6871 } 6872 if (NewVD->hasExternalStorage()) { 6873 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 6874 NewVD->setInvalidDecl(); 6875 return; 6876 } 6877 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported. 6878 // TODO: this check is not enough as it doesn't diagnose the typedef 6879 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>(); 6880 const FunctionProtoType *FTy = 6881 BlkTy->getPointeeType()->getAs<FunctionProtoType>(); 6882 if (FTy && FTy->isVariadic()) { 6883 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic) 6884 << T << NewVD->getSourceRange(); 6885 NewVD->setInvalidDecl(); 6886 return; 6887 } 6888 } 6889 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6890 // __constant address space. 6891 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6892 // variables inside a function can also be declared in the global 6893 // address space. 6894 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 6895 NewVD->hasExternalStorage()) { 6896 if (!T->isSamplerT() && 6897 !(T.getAddressSpace() == LangAS::opencl_constant || 6898 (T.getAddressSpace() == LangAS::opencl_global && 6899 getLangOpts().OpenCLVersion == 200))) { 6900 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 6901 if (getLangOpts().OpenCLVersion == 200) 6902 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6903 << Scope << "global or constant"; 6904 else 6905 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6906 << Scope << "constant"; 6907 NewVD->setInvalidDecl(); 6908 return; 6909 } 6910 } else { 6911 if (T.getAddressSpace() == LangAS::opencl_global) { 6912 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6913 << 1 /*is any function*/ << "global"; 6914 NewVD->setInvalidDecl(); 6915 return; 6916 } 6917 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6918 // in functions. 6919 if (T.getAddressSpace() == LangAS::opencl_constant || 6920 T.getAddressSpace() == LangAS::opencl_local) { 6921 FunctionDecl *FD = getCurFunctionDecl(); 6922 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6923 if (T.getAddressSpace() == LangAS::opencl_constant) 6924 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6925 << 0 /*non-kernel only*/ << "constant"; 6926 else 6927 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 6928 << 0 /*non-kernel only*/ << "local"; 6929 NewVD->setInvalidDecl(); 6930 return; 6931 } 6932 } 6933 } 6934 } 6935 6936 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6937 && !NewVD->hasAttr<BlocksAttr>()) { 6938 if (getLangOpts().getGC() != LangOptions::NonGC) 6939 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6940 else { 6941 assert(!getLangOpts().ObjCAutoRefCount); 6942 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6943 } 6944 } 6945 6946 bool isVM = T->isVariablyModifiedType(); 6947 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6948 NewVD->hasAttr<BlocksAttr>()) 6949 getCurFunction()->setHasBranchProtectedScope(); 6950 6951 if ((isVM && NewVD->hasLinkage()) || 6952 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6953 bool SizeIsNegative; 6954 llvm::APSInt Oversized; 6955 TypeSourceInfo *FixedTInfo = 6956 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6957 SizeIsNegative, Oversized); 6958 if (!FixedTInfo && T->isVariableArrayType()) { 6959 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6960 // FIXME: This won't give the correct result for 6961 // int a[10][n]; 6962 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6963 6964 if (NewVD->isFileVarDecl()) 6965 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6966 << SizeRange; 6967 else if (NewVD->isStaticLocal()) 6968 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6969 << SizeRange; 6970 else 6971 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6972 << SizeRange; 6973 NewVD->setInvalidDecl(); 6974 return; 6975 } 6976 6977 if (!FixedTInfo) { 6978 if (NewVD->isFileVarDecl()) 6979 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6980 else 6981 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6982 NewVD->setInvalidDecl(); 6983 return; 6984 } 6985 6986 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6987 NewVD->setType(FixedTInfo->getType()); 6988 NewVD->setTypeSourceInfo(FixedTInfo); 6989 } 6990 6991 if (T->isVoidType()) { 6992 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6993 // of objects and functions. 6994 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6995 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6996 << T; 6997 NewVD->setInvalidDecl(); 6998 return; 6999 } 7000 } 7001 7002 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7003 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7004 NewVD->setInvalidDecl(); 7005 return; 7006 } 7007 7008 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7009 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7010 NewVD->setInvalidDecl(); 7011 return; 7012 } 7013 7014 if (NewVD->isConstexpr() && !T->isDependentType() && 7015 RequireLiteralType(NewVD->getLocation(), T, 7016 diag::err_constexpr_var_non_literal)) { 7017 NewVD->setInvalidDecl(); 7018 return; 7019 } 7020 } 7021 7022 /// \brief Perform semantic checking on a newly-created variable 7023 /// declaration. 7024 /// 7025 /// This routine performs all of the type-checking required for a 7026 /// variable declaration once it has been built. It is used both to 7027 /// check variables after they have been parsed and their declarators 7028 /// have been translated into a declaration, and to check variables 7029 /// that have been instantiated from a template. 7030 /// 7031 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7032 /// 7033 /// Returns true if the variable declaration is a redeclaration. 7034 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7035 CheckVariableDeclarationType(NewVD); 7036 7037 // If the decl is already known invalid, don't check it. 7038 if (NewVD->isInvalidDecl()) 7039 return false; 7040 7041 // If we did not find anything by this name, look for a non-visible 7042 // extern "C" declaration with the same name. 7043 if (Previous.empty() && 7044 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7045 Previous.setShadowed(); 7046 7047 if (!Previous.empty()) { 7048 MergeVarDecl(NewVD, Previous); 7049 return true; 7050 } 7051 return false; 7052 } 7053 7054 namespace { 7055 struct FindOverriddenMethod { 7056 Sema *S; 7057 CXXMethodDecl *Method; 7058 7059 /// Member lookup function that determines whether a given C++ 7060 /// method overrides a method in a base class, to be used with 7061 /// CXXRecordDecl::lookupInBases(). 7062 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7063 RecordDecl *BaseRecord = 7064 Specifier->getType()->getAs<RecordType>()->getDecl(); 7065 7066 DeclarationName Name = Method->getDeclName(); 7067 7068 // FIXME: Do we care about other names here too? 7069 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7070 // We really want to find the base class destructor here. 7071 QualType T = S->Context.getTypeDeclType(BaseRecord); 7072 CanQualType CT = S->Context.getCanonicalType(T); 7073 7074 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7075 } 7076 7077 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7078 Path.Decls = Path.Decls.slice(1)) { 7079 NamedDecl *D = Path.Decls.front(); 7080 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7081 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7082 return true; 7083 } 7084 } 7085 7086 return false; 7087 } 7088 }; 7089 7090 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7091 } // end anonymous namespace 7092 7093 /// \brief Report an error regarding overriding, along with any relevant 7094 /// overriden methods. 7095 /// 7096 /// \param DiagID the primary error to report. 7097 /// \param MD the overriding method. 7098 /// \param OEK which overrides to include as notes. 7099 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7100 OverrideErrorKind OEK = OEK_All) { 7101 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7102 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7103 E = MD->end_overridden_methods(); 7104 I != E; ++I) { 7105 // This check (& the OEK parameter) could be replaced by a predicate, but 7106 // without lambdas that would be overkill. This is still nicer than writing 7107 // out the diag loop 3 times. 7108 if ((OEK == OEK_All) || 7109 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7110 (OEK == OEK_Deleted && (*I)->isDeleted())) 7111 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7112 } 7113 } 7114 7115 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7116 /// and if so, check that it's a valid override and remember it. 7117 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7118 // Look for methods in base classes that this method might override. 7119 CXXBasePaths Paths; 7120 FindOverriddenMethod FOM; 7121 FOM.Method = MD; 7122 FOM.S = this; 7123 bool hasDeletedOverridenMethods = false; 7124 bool hasNonDeletedOverridenMethods = false; 7125 bool AddedAny = false; 7126 if (DC->lookupInBases(FOM, Paths)) { 7127 for (auto *I : Paths.found_decls()) { 7128 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7129 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7130 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7131 !CheckOverridingFunctionAttributes(MD, OldMD) && 7132 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7133 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7134 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7135 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7136 AddedAny = true; 7137 } 7138 } 7139 } 7140 } 7141 7142 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7143 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7144 } 7145 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7146 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7147 } 7148 7149 return AddedAny; 7150 } 7151 7152 namespace { 7153 // Struct for holding all of the extra arguments needed by 7154 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7155 struct ActOnFDArgs { 7156 Scope *S; 7157 Declarator &D; 7158 MultiTemplateParamsArg TemplateParamLists; 7159 bool AddToScope; 7160 }; 7161 } // end anonymous namespace 7162 7163 namespace { 7164 7165 // Callback to only accept typo corrections that have a non-zero edit distance. 7166 // Also only accept corrections that have the same parent decl. 7167 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7168 public: 7169 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7170 CXXRecordDecl *Parent) 7171 : Context(Context), OriginalFD(TypoFD), 7172 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7173 7174 bool ValidateCandidate(const TypoCorrection &candidate) override { 7175 if (candidate.getEditDistance() == 0) 7176 return false; 7177 7178 SmallVector<unsigned, 1> MismatchedParams; 7179 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7180 CDeclEnd = candidate.end(); 7181 CDecl != CDeclEnd; ++CDecl) { 7182 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7183 7184 if (FD && !FD->hasBody() && 7185 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7186 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7187 CXXRecordDecl *Parent = MD->getParent(); 7188 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7189 return true; 7190 } else if (!ExpectedParent) { 7191 return true; 7192 } 7193 } 7194 } 7195 7196 return false; 7197 } 7198 7199 private: 7200 ASTContext &Context; 7201 FunctionDecl *OriginalFD; 7202 CXXRecordDecl *ExpectedParent; 7203 }; 7204 7205 } // end anonymous namespace 7206 7207 /// \brief Generate diagnostics for an invalid function redeclaration. 7208 /// 7209 /// This routine handles generating the diagnostic messages for an invalid 7210 /// function redeclaration, including finding possible similar declarations 7211 /// or performing typo correction if there are no previous declarations with 7212 /// the same name. 7213 /// 7214 /// Returns a NamedDecl iff typo correction was performed and substituting in 7215 /// the new declaration name does not cause new errors. 7216 static NamedDecl *DiagnoseInvalidRedeclaration( 7217 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7218 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7219 DeclarationName Name = NewFD->getDeclName(); 7220 DeclContext *NewDC = NewFD->getDeclContext(); 7221 SmallVector<unsigned, 1> MismatchedParams; 7222 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7223 TypoCorrection Correction; 7224 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7225 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7226 : diag::err_member_decl_does_not_match; 7227 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7228 IsLocalFriend ? Sema::LookupLocalFriendName 7229 : Sema::LookupOrdinaryName, 7230 Sema::ForRedeclaration); 7231 7232 NewFD->setInvalidDecl(); 7233 if (IsLocalFriend) 7234 SemaRef.LookupName(Prev, S); 7235 else 7236 SemaRef.LookupQualifiedName(Prev, NewDC); 7237 assert(!Prev.isAmbiguous() && 7238 "Cannot have an ambiguity in previous-declaration lookup"); 7239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7240 if (!Prev.empty()) { 7241 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7242 Func != FuncEnd; ++Func) { 7243 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7244 if (FD && 7245 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7246 // Add 1 to the index so that 0 can mean the mismatch didn't 7247 // involve a parameter 7248 unsigned ParamNum = 7249 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7250 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7251 } 7252 } 7253 // If the qualified name lookup yielded nothing, try typo correction 7254 } else if ((Correction = SemaRef.CorrectTypo( 7255 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7256 &ExtraArgs.D.getCXXScopeSpec(), 7257 llvm::make_unique<DifferentNameValidatorCCC>( 7258 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7259 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7260 // Set up everything for the call to ActOnFunctionDeclarator 7261 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7262 ExtraArgs.D.getIdentifierLoc()); 7263 Previous.clear(); 7264 Previous.setLookupName(Correction.getCorrection()); 7265 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7266 CDeclEnd = Correction.end(); 7267 CDecl != CDeclEnd; ++CDecl) { 7268 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7269 if (FD && !FD->hasBody() && 7270 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7271 Previous.addDecl(FD); 7272 } 7273 } 7274 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7275 7276 NamedDecl *Result; 7277 // Retry building the function declaration with the new previous 7278 // declarations, and with errors suppressed. 7279 { 7280 // Trap errors. 7281 Sema::SFINAETrap Trap(SemaRef); 7282 7283 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7284 // pieces need to verify the typo-corrected C++ declaration and hopefully 7285 // eliminate the need for the parameter pack ExtraArgs. 7286 Result = SemaRef.ActOnFunctionDeclarator( 7287 ExtraArgs.S, ExtraArgs.D, 7288 Correction.getCorrectionDecl()->getDeclContext(), 7289 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7290 ExtraArgs.AddToScope); 7291 7292 if (Trap.hasErrorOccurred()) 7293 Result = nullptr; 7294 } 7295 7296 if (Result) { 7297 // Determine which correction we picked. 7298 Decl *Canonical = Result->getCanonicalDecl(); 7299 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7300 I != E; ++I) 7301 if ((*I)->getCanonicalDecl() == Canonical) 7302 Correction.setCorrectionDecl(*I); 7303 7304 SemaRef.diagnoseTypo( 7305 Correction, 7306 SemaRef.PDiag(IsLocalFriend 7307 ? diag::err_no_matching_local_friend_suggest 7308 : diag::err_member_decl_does_not_match_suggest) 7309 << Name << NewDC << IsDefinition); 7310 return Result; 7311 } 7312 7313 // Pretend the typo correction never occurred 7314 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7315 ExtraArgs.D.getIdentifierLoc()); 7316 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7317 Previous.clear(); 7318 Previous.setLookupName(Name); 7319 } 7320 7321 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7322 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7323 7324 bool NewFDisConst = false; 7325 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7326 NewFDisConst = NewMD->isConst(); 7327 7328 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7329 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7330 NearMatch != NearMatchEnd; ++NearMatch) { 7331 FunctionDecl *FD = NearMatch->first; 7332 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7333 bool FDisConst = MD && MD->isConst(); 7334 bool IsMember = MD || !IsLocalFriend; 7335 7336 // FIXME: These notes are poorly worded for the local friend case. 7337 if (unsigned Idx = NearMatch->second) { 7338 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7339 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7340 if (Loc.isInvalid()) Loc = FD->getLocation(); 7341 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7342 : diag::note_local_decl_close_param_match) 7343 << Idx << FDParam->getType() 7344 << NewFD->getParamDecl(Idx - 1)->getType(); 7345 } else if (FDisConst != NewFDisConst) { 7346 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7347 << NewFDisConst << FD->getSourceRange().getEnd(); 7348 } else 7349 SemaRef.Diag(FD->getLocation(), 7350 IsMember ? diag::note_member_def_close_match 7351 : diag::note_local_decl_close_match); 7352 } 7353 return nullptr; 7354 } 7355 7356 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7357 switch (D.getDeclSpec().getStorageClassSpec()) { 7358 default: llvm_unreachable("Unknown storage class!"); 7359 case DeclSpec::SCS_auto: 7360 case DeclSpec::SCS_register: 7361 case DeclSpec::SCS_mutable: 7362 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7363 diag::err_typecheck_sclass_func); 7364 D.setInvalidType(); 7365 break; 7366 case DeclSpec::SCS_unspecified: break; 7367 case DeclSpec::SCS_extern: 7368 if (D.getDeclSpec().isExternInLinkageSpec()) 7369 return SC_None; 7370 return SC_Extern; 7371 case DeclSpec::SCS_static: { 7372 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7373 // C99 6.7.1p5: 7374 // The declaration of an identifier for a function that has 7375 // block scope shall have no explicit storage-class specifier 7376 // other than extern 7377 // See also (C++ [dcl.stc]p4). 7378 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7379 diag::err_static_block_func); 7380 break; 7381 } else 7382 return SC_Static; 7383 } 7384 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7385 } 7386 7387 // No explicit storage class has already been returned 7388 return SC_None; 7389 } 7390 7391 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7392 DeclContext *DC, QualType &R, 7393 TypeSourceInfo *TInfo, 7394 StorageClass SC, 7395 bool &IsVirtualOkay) { 7396 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7397 DeclarationName Name = NameInfo.getName(); 7398 7399 FunctionDecl *NewFD = nullptr; 7400 bool isInline = D.getDeclSpec().isInlineSpecified(); 7401 7402 if (!SemaRef.getLangOpts().CPlusPlus) { 7403 // Determine whether the function was written with a 7404 // prototype. This true when: 7405 // - there is a prototype in the declarator, or 7406 // - the type R of the function is some kind of typedef or other reference 7407 // to a type name (which eventually refers to a function type). 7408 bool HasPrototype = 7409 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7410 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7411 7412 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7413 D.getLocStart(), NameInfo, R, 7414 TInfo, SC, isInline, 7415 HasPrototype, false); 7416 if (D.isInvalidType()) 7417 NewFD->setInvalidDecl(); 7418 7419 return NewFD; 7420 } 7421 7422 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7423 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7424 7425 // Check that the return type is not an abstract class type. 7426 // For record types, this is done by the AbstractClassUsageDiagnoser once 7427 // the class has been completely parsed. 7428 if (!DC->isRecord() && 7429 SemaRef.RequireNonAbstractType( 7430 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7431 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7432 D.setInvalidType(); 7433 7434 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7435 // This is a C++ constructor declaration. 7436 assert(DC->isRecord() && 7437 "Constructors can only be declared in a member context"); 7438 7439 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7440 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7441 D.getLocStart(), NameInfo, 7442 R, TInfo, isExplicit, isInline, 7443 /*isImplicitlyDeclared=*/false, 7444 isConstexpr); 7445 7446 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7447 // This is a C++ destructor declaration. 7448 if (DC->isRecord()) { 7449 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7450 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7451 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7452 SemaRef.Context, Record, 7453 D.getLocStart(), 7454 NameInfo, R, TInfo, isInline, 7455 /*isImplicitlyDeclared=*/false); 7456 7457 // If the class is complete, then we now create the implicit exception 7458 // specification. If the class is incomplete or dependent, we can't do 7459 // it yet. 7460 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7461 Record->getDefinition() && !Record->isBeingDefined() && 7462 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7463 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7464 } 7465 7466 IsVirtualOkay = true; 7467 return NewDD; 7468 7469 } else { 7470 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7471 D.setInvalidType(); 7472 7473 // Create a FunctionDecl to satisfy the function definition parsing 7474 // code path. 7475 return FunctionDecl::Create(SemaRef.Context, DC, 7476 D.getLocStart(), 7477 D.getIdentifierLoc(), Name, R, TInfo, 7478 SC, isInline, 7479 /*hasPrototype=*/true, isConstexpr); 7480 } 7481 7482 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7483 if (!DC->isRecord()) { 7484 SemaRef.Diag(D.getIdentifierLoc(), 7485 diag::err_conv_function_not_member); 7486 return nullptr; 7487 } 7488 7489 SemaRef.CheckConversionDeclarator(D, R, SC); 7490 IsVirtualOkay = true; 7491 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7492 D.getLocStart(), NameInfo, 7493 R, TInfo, isInline, isExplicit, 7494 isConstexpr, SourceLocation()); 7495 7496 } else if (DC->isRecord()) { 7497 // If the name of the function is the same as the name of the record, 7498 // then this must be an invalid constructor that has a return type. 7499 // (The parser checks for a return type and makes the declarator a 7500 // constructor if it has no return type). 7501 if (Name.getAsIdentifierInfo() && 7502 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7503 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7504 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7505 << SourceRange(D.getIdentifierLoc()); 7506 return nullptr; 7507 } 7508 7509 // This is a C++ method declaration. 7510 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7511 cast<CXXRecordDecl>(DC), 7512 D.getLocStart(), NameInfo, R, 7513 TInfo, SC, isInline, 7514 isConstexpr, SourceLocation()); 7515 IsVirtualOkay = !Ret->isStatic(); 7516 return Ret; 7517 } else { 7518 bool isFriend = 7519 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7520 if (!isFriend && SemaRef.CurContext->isRecord()) 7521 return nullptr; 7522 7523 // Determine whether the function was written with a 7524 // prototype. This true when: 7525 // - we're in C++ (where every function has a prototype), 7526 return FunctionDecl::Create(SemaRef.Context, DC, 7527 D.getLocStart(), 7528 NameInfo, R, TInfo, SC, isInline, 7529 true/*HasPrototype*/, isConstexpr); 7530 } 7531 } 7532 7533 enum OpenCLParamType { 7534 ValidKernelParam, 7535 PtrPtrKernelParam, 7536 PtrKernelParam, 7537 PrivatePtrKernelParam, 7538 InvalidKernelParam, 7539 RecordKernelParam 7540 }; 7541 7542 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7543 if (PT->isPointerType()) { 7544 QualType PointeeType = PT->getPointeeType(); 7545 if (PointeeType->isPointerType()) 7546 return PtrPtrKernelParam; 7547 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7548 : PtrKernelParam; 7549 } 7550 7551 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7552 // be used as builtin types. 7553 7554 if (PT->isImageType()) 7555 return PtrKernelParam; 7556 7557 if (PT->isBooleanType()) 7558 return InvalidKernelParam; 7559 7560 if (PT->isEventT()) 7561 return InvalidKernelParam; 7562 7563 // OpenCL extension spec v1.2 s9.5: 7564 // This extension adds support for half scalar and vector types as built-in 7565 // types that can be used for arithmetic operations, conversions etc. 7566 if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType()) 7567 return InvalidKernelParam; 7568 7569 if (PT->isRecordType()) 7570 return RecordKernelParam; 7571 7572 return ValidKernelParam; 7573 } 7574 7575 static void checkIsValidOpenCLKernelParameter( 7576 Sema &S, 7577 Declarator &D, 7578 ParmVarDecl *Param, 7579 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7580 QualType PT = Param->getType(); 7581 7582 // Cache the valid types we encounter to avoid rechecking structs that are 7583 // used again 7584 if (ValidTypes.count(PT.getTypePtr())) 7585 return; 7586 7587 switch (getOpenCLKernelParameterType(S, PT)) { 7588 case PtrPtrKernelParam: 7589 // OpenCL v1.2 s6.9.a: 7590 // A kernel function argument cannot be declared as a 7591 // pointer to a pointer type. 7592 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7593 D.setInvalidType(); 7594 return; 7595 7596 case PrivatePtrKernelParam: 7597 // OpenCL v1.2 s6.9.a: 7598 // A kernel function argument cannot be declared as a 7599 // pointer to the private address space. 7600 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7601 D.setInvalidType(); 7602 return; 7603 7604 // OpenCL v1.2 s6.9.k: 7605 // Arguments to kernel functions in a program cannot be declared with the 7606 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7607 // uintptr_t or a struct and/or union that contain fields declared to be 7608 // one of these built-in scalar types. 7609 7610 case InvalidKernelParam: 7611 // OpenCL v1.2 s6.8 n: 7612 // A kernel function argument cannot be declared 7613 // of event_t type. 7614 // Do not diagnose half type since it is diagnosed as invalid argument 7615 // type for any function elsewhere. 7616 if (!PT->isHalfType()) 7617 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7618 D.setInvalidType(); 7619 return; 7620 7621 case PtrKernelParam: 7622 case ValidKernelParam: 7623 ValidTypes.insert(PT.getTypePtr()); 7624 return; 7625 7626 case RecordKernelParam: 7627 break; 7628 } 7629 7630 // Track nested structs we will inspect 7631 SmallVector<const Decl *, 4> VisitStack; 7632 7633 // Track where we are in the nested structs. Items will migrate from 7634 // VisitStack to HistoryStack as we do the DFS for bad field. 7635 SmallVector<const FieldDecl *, 4> HistoryStack; 7636 HistoryStack.push_back(nullptr); 7637 7638 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7639 VisitStack.push_back(PD); 7640 7641 assert(VisitStack.back() && "First decl null?"); 7642 7643 do { 7644 const Decl *Next = VisitStack.pop_back_val(); 7645 if (!Next) { 7646 assert(!HistoryStack.empty()); 7647 // Found a marker, we have gone up a level 7648 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7649 ValidTypes.insert(Hist->getType().getTypePtr()); 7650 7651 continue; 7652 } 7653 7654 // Adds everything except the original parameter declaration (which is not a 7655 // field itself) to the history stack. 7656 const RecordDecl *RD; 7657 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7658 HistoryStack.push_back(Field); 7659 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7660 } else { 7661 RD = cast<RecordDecl>(Next); 7662 } 7663 7664 // Add a null marker so we know when we've gone back up a level 7665 VisitStack.push_back(nullptr); 7666 7667 for (const auto *FD : RD->fields()) { 7668 QualType QT = FD->getType(); 7669 7670 if (ValidTypes.count(QT.getTypePtr())) 7671 continue; 7672 7673 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 7674 if (ParamType == ValidKernelParam) 7675 continue; 7676 7677 if (ParamType == RecordKernelParam) { 7678 VisitStack.push_back(FD); 7679 continue; 7680 } 7681 7682 // OpenCL v1.2 s6.9.p: 7683 // Arguments to kernel functions that are declared to be a struct or union 7684 // do not allow OpenCL objects to be passed as elements of the struct or 7685 // union. 7686 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7687 ParamType == PrivatePtrKernelParam) { 7688 S.Diag(Param->getLocation(), 7689 diag::err_record_with_pointers_kernel_param) 7690 << PT->isUnionType() 7691 << PT; 7692 } else { 7693 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7694 } 7695 7696 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7697 << PD->getDeclName(); 7698 7699 // We have an error, now let's go back up through history and show where 7700 // the offending field came from 7701 for (ArrayRef<const FieldDecl *>::const_iterator 7702 I = HistoryStack.begin() + 1, 7703 E = HistoryStack.end(); 7704 I != E; ++I) { 7705 const FieldDecl *OuterField = *I; 7706 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7707 << OuterField->getType(); 7708 } 7709 7710 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7711 << QT->isPointerType() 7712 << QT; 7713 D.setInvalidType(); 7714 return; 7715 } 7716 } while (!VisitStack.empty()); 7717 } 7718 7719 NamedDecl* 7720 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7721 TypeSourceInfo *TInfo, LookupResult &Previous, 7722 MultiTemplateParamsArg TemplateParamLists, 7723 bool &AddToScope) { 7724 QualType R = TInfo->getType(); 7725 7726 assert(R.getTypePtr()->isFunctionType()); 7727 7728 // TODO: consider using NameInfo for diagnostic. 7729 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7730 DeclarationName Name = NameInfo.getName(); 7731 StorageClass SC = getFunctionStorageClass(*this, D); 7732 7733 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7734 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7735 diag::err_invalid_thread) 7736 << DeclSpec::getSpecifierName(TSCS); 7737 7738 if (D.isFirstDeclarationOfMember()) 7739 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7740 D.getIdentifierLoc()); 7741 7742 bool isFriend = false; 7743 FunctionTemplateDecl *FunctionTemplate = nullptr; 7744 bool isExplicitSpecialization = false; 7745 bool isFunctionTemplateSpecialization = false; 7746 7747 bool isDependentClassScopeExplicitSpecialization = false; 7748 bool HasExplicitTemplateArgs = false; 7749 TemplateArgumentListInfo TemplateArgs; 7750 7751 bool isVirtualOkay = false; 7752 7753 DeclContext *OriginalDC = DC; 7754 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7755 7756 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7757 isVirtualOkay); 7758 if (!NewFD) return nullptr; 7759 7760 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7761 NewFD->setTopLevelDeclInObjCContainer(); 7762 7763 // Set the lexical context. If this is a function-scope declaration, or has a 7764 // C++ scope specifier, or is the object of a friend declaration, the lexical 7765 // context will be different from the semantic context. 7766 NewFD->setLexicalDeclContext(CurContext); 7767 7768 if (IsLocalExternDecl) 7769 NewFD->setLocalExternDecl(); 7770 7771 if (getLangOpts().CPlusPlus) { 7772 bool isInline = D.getDeclSpec().isInlineSpecified(); 7773 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7774 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7775 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7776 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7777 isFriend = D.getDeclSpec().isFriendSpecified(); 7778 if (isFriend && !isInline && D.isFunctionDefinition()) { 7779 // C++ [class.friend]p5 7780 // A function can be defined in a friend declaration of a 7781 // class . . . . Such a function is implicitly inline. 7782 NewFD->setImplicitlyInline(); 7783 } 7784 7785 // If this is a method defined in an __interface, and is not a constructor 7786 // or an overloaded operator, then set the pure flag (isVirtual will already 7787 // return true). 7788 if (const CXXRecordDecl *Parent = 7789 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7790 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7791 NewFD->setPure(true); 7792 7793 // C++ [class.union]p2 7794 // A union can have member functions, but not virtual functions. 7795 if (isVirtual && Parent->isUnion()) 7796 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7797 } 7798 7799 SetNestedNameSpecifier(NewFD, D); 7800 isExplicitSpecialization = false; 7801 isFunctionTemplateSpecialization = false; 7802 if (D.isInvalidType()) 7803 NewFD->setInvalidDecl(); 7804 7805 // Match up the template parameter lists with the scope specifier, then 7806 // determine whether we have a template or a template specialization. 7807 bool Invalid = false; 7808 if (TemplateParameterList *TemplateParams = 7809 MatchTemplateParametersToScopeSpecifier( 7810 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7811 D.getCXXScopeSpec(), 7812 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7813 ? D.getName().TemplateId 7814 : nullptr, 7815 TemplateParamLists, isFriend, isExplicitSpecialization, 7816 Invalid)) { 7817 if (TemplateParams->size() > 0) { 7818 // This is a function template 7819 7820 // Check that we can declare a template here. 7821 if (CheckTemplateDeclScope(S, TemplateParams)) 7822 NewFD->setInvalidDecl(); 7823 7824 // A destructor cannot be a template. 7825 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7826 Diag(NewFD->getLocation(), diag::err_destructor_template); 7827 NewFD->setInvalidDecl(); 7828 } 7829 7830 // If we're adding a template to a dependent context, we may need to 7831 // rebuilding some of the types used within the template parameter list, 7832 // now that we know what the current instantiation is. 7833 if (DC->isDependentContext()) { 7834 ContextRAII SavedContext(*this, DC); 7835 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7836 Invalid = true; 7837 } 7838 7839 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7840 NewFD->getLocation(), 7841 Name, TemplateParams, 7842 NewFD); 7843 FunctionTemplate->setLexicalDeclContext(CurContext); 7844 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7845 7846 // For source fidelity, store the other template param lists. 7847 if (TemplateParamLists.size() > 1) { 7848 NewFD->setTemplateParameterListsInfo(Context, 7849 TemplateParamLists.drop_back(1)); 7850 } 7851 } else { 7852 // This is a function template specialization. 7853 isFunctionTemplateSpecialization = true; 7854 // For source fidelity, store all the template param lists. 7855 if (TemplateParamLists.size() > 0) 7856 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7857 7858 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7859 if (isFriend) { 7860 // We want to remove the "template<>", found here. 7861 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7862 7863 // If we remove the template<> and the name is not a 7864 // template-id, we're actually silently creating a problem: 7865 // the friend declaration will refer to an untemplated decl, 7866 // and clearly the user wants a template specialization. So 7867 // we need to insert '<>' after the name. 7868 SourceLocation InsertLoc; 7869 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7870 InsertLoc = D.getName().getSourceRange().getEnd(); 7871 InsertLoc = getLocForEndOfToken(InsertLoc); 7872 } 7873 7874 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7875 << Name << RemoveRange 7876 << FixItHint::CreateRemoval(RemoveRange) 7877 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7878 } 7879 } 7880 } 7881 else { 7882 // All template param lists were matched against the scope specifier: 7883 // this is NOT (an explicit specialization of) a template. 7884 if (TemplateParamLists.size() > 0) 7885 // For source fidelity, store all the template param lists. 7886 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7887 } 7888 7889 if (Invalid) { 7890 NewFD->setInvalidDecl(); 7891 if (FunctionTemplate) 7892 FunctionTemplate->setInvalidDecl(); 7893 } 7894 7895 // C++ [dcl.fct.spec]p5: 7896 // The virtual specifier shall only be used in declarations of 7897 // nonstatic class member functions that appear within a 7898 // member-specification of a class declaration; see 10.3. 7899 // 7900 if (isVirtual && !NewFD->isInvalidDecl()) { 7901 if (!isVirtualOkay) { 7902 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7903 diag::err_virtual_non_function); 7904 } else if (!CurContext->isRecord()) { 7905 // 'virtual' was specified outside of the class. 7906 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7907 diag::err_virtual_out_of_class) 7908 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7909 } else if (NewFD->getDescribedFunctionTemplate()) { 7910 // C++ [temp.mem]p3: 7911 // A member function template shall not be virtual. 7912 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7913 diag::err_virtual_member_function_template) 7914 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7915 } else { 7916 // Okay: Add virtual to the method. 7917 NewFD->setVirtualAsWritten(true); 7918 } 7919 7920 if (getLangOpts().CPlusPlus14 && 7921 NewFD->getReturnType()->isUndeducedType()) 7922 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7923 } 7924 7925 if (getLangOpts().CPlusPlus14 && 7926 (NewFD->isDependentContext() || 7927 (isFriend && CurContext->isDependentContext())) && 7928 NewFD->getReturnType()->isUndeducedType()) { 7929 // If the function template is referenced directly (for instance, as a 7930 // member of the current instantiation), pretend it has a dependent type. 7931 // This is not really justified by the standard, but is the only sane 7932 // thing to do. 7933 // FIXME: For a friend function, we have not marked the function as being 7934 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7935 const FunctionProtoType *FPT = 7936 NewFD->getType()->castAs<FunctionProtoType>(); 7937 QualType Result = 7938 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7939 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7940 FPT->getExtProtoInfo())); 7941 } 7942 7943 // C++ [dcl.fct.spec]p3: 7944 // The inline specifier shall not appear on a block scope function 7945 // declaration. 7946 if (isInline && !NewFD->isInvalidDecl()) { 7947 if (CurContext->isFunctionOrMethod()) { 7948 // 'inline' is not allowed on block scope function declaration. 7949 Diag(D.getDeclSpec().getInlineSpecLoc(), 7950 diag::err_inline_declaration_block_scope) << Name 7951 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7952 } 7953 } 7954 7955 // C++ [dcl.fct.spec]p6: 7956 // The explicit specifier shall be used only in the declaration of a 7957 // constructor or conversion function within its class definition; 7958 // see 12.3.1 and 12.3.2. 7959 if (isExplicit && !NewFD->isInvalidDecl()) { 7960 if (!CurContext->isRecord()) { 7961 // 'explicit' was specified outside of the class. 7962 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7963 diag::err_explicit_out_of_class) 7964 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7965 } else if (!isa<CXXConstructorDecl>(NewFD) && 7966 !isa<CXXConversionDecl>(NewFD)) { 7967 // 'explicit' was specified on a function that wasn't a constructor 7968 // or conversion function. 7969 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7970 diag::err_explicit_non_ctor_or_conv_function) 7971 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7972 } 7973 } 7974 7975 if (isConstexpr) { 7976 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7977 // are implicitly inline. 7978 NewFD->setImplicitlyInline(); 7979 7980 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7981 // be either constructors or to return a literal type. Therefore, 7982 // destructors cannot be declared constexpr. 7983 if (isa<CXXDestructorDecl>(NewFD)) 7984 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7985 } 7986 7987 if (isConcept) { 7988 // This is a function concept. 7989 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 7990 FTD->setConcept(); 7991 7992 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7993 // applied only to the definition of a function template [...] 7994 if (!D.isFunctionDefinition()) { 7995 Diag(D.getDeclSpec().getConceptSpecLoc(), 7996 diag::err_function_concept_not_defined); 7997 NewFD->setInvalidDecl(); 7998 } 7999 8000 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8001 // have no exception-specification and is treated as if it were specified 8002 // with noexcept(true) (15.4). [...] 8003 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8004 if (FPT->hasExceptionSpec()) { 8005 SourceRange Range; 8006 if (D.isFunctionDeclarator()) 8007 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8008 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8009 << FixItHint::CreateRemoval(Range); 8010 NewFD->setInvalidDecl(); 8011 } else { 8012 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8013 } 8014 8015 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8016 // following restrictions: 8017 // - The declared return type shall have the type bool. 8018 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8019 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8020 NewFD->setInvalidDecl(); 8021 } 8022 8023 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8024 // following restrictions: 8025 // - The declaration's parameter list shall be equivalent to an empty 8026 // parameter list. 8027 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8028 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8029 } 8030 8031 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8032 // implicity defined to be a constexpr declaration (implicitly inline) 8033 NewFD->setImplicitlyInline(); 8034 8035 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8036 // be declared with the thread_local, inline, friend, or constexpr 8037 // specifiers, [...] 8038 if (isInline) { 8039 Diag(D.getDeclSpec().getInlineSpecLoc(), 8040 diag::err_concept_decl_invalid_specifiers) 8041 << 1 << 1; 8042 NewFD->setInvalidDecl(true); 8043 } 8044 8045 if (isFriend) { 8046 Diag(D.getDeclSpec().getFriendSpecLoc(), 8047 diag::err_concept_decl_invalid_specifiers) 8048 << 1 << 2; 8049 NewFD->setInvalidDecl(true); 8050 } 8051 8052 if (isConstexpr) { 8053 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8054 diag::err_concept_decl_invalid_specifiers) 8055 << 1 << 3; 8056 NewFD->setInvalidDecl(true); 8057 } 8058 8059 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8060 // applied only to the definition of a function template or variable 8061 // template, declared in namespace scope. 8062 if (isFunctionTemplateSpecialization) { 8063 Diag(D.getDeclSpec().getConceptSpecLoc(), 8064 diag::err_concept_specified_specialization) << 1; 8065 NewFD->setInvalidDecl(true); 8066 return NewFD; 8067 } 8068 } 8069 8070 // If __module_private__ was specified, mark the function accordingly. 8071 if (D.getDeclSpec().isModulePrivateSpecified()) { 8072 if (isFunctionTemplateSpecialization) { 8073 SourceLocation ModulePrivateLoc 8074 = D.getDeclSpec().getModulePrivateSpecLoc(); 8075 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8076 << 0 8077 << FixItHint::CreateRemoval(ModulePrivateLoc); 8078 } else { 8079 NewFD->setModulePrivate(); 8080 if (FunctionTemplate) 8081 FunctionTemplate->setModulePrivate(); 8082 } 8083 } 8084 8085 if (isFriend) { 8086 if (FunctionTemplate) { 8087 FunctionTemplate->setObjectOfFriendDecl(); 8088 FunctionTemplate->setAccess(AS_public); 8089 } 8090 NewFD->setObjectOfFriendDecl(); 8091 NewFD->setAccess(AS_public); 8092 } 8093 8094 // If a function is defined as defaulted or deleted, mark it as such now. 8095 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8096 // definition kind to FDK_Definition. 8097 switch (D.getFunctionDefinitionKind()) { 8098 case FDK_Declaration: 8099 case FDK_Definition: 8100 break; 8101 8102 case FDK_Defaulted: 8103 NewFD->setDefaulted(); 8104 break; 8105 8106 case FDK_Deleted: 8107 NewFD->setDeletedAsWritten(); 8108 break; 8109 } 8110 8111 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8112 D.isFunctionDefinition()) { 8113 // C++ [class.mfct]p2: 8114 // A member function may be defined (8.4) in its class definition, in 8115 // which case it is an inline member function (7.1.2) 8116 NewFD->setImplicitlyInline(); 8117 } 8118 8119 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8120 !CurContext->isRecord()) { 8121 // C++ [class.static]p1: 8122 // A data or function member of a class may be declared static 8123 // in a class definition, in which case it is a static member of 8124 // the class. 8125 8126 // Complain about the 'static' specifier if it's on an out-of-line 8127 // member function definition. 8128 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8129 diag::err_static_out_of_line) 8130 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8131 } 8132 8133 // C++11 [except.spec]p15: 8134 // A deallocation function with no exception-specification is treated 8135 // as if it were specified with noexcept(true). 8136 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8137 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8138 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8139 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8140 NewFD->setType(Context.getFunctionType( 8141 FPT->getReturnType(), FPT->getParamTypes(), 8142 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8143 } 8144 8145 // Filter out previous declarations that don't match the scope. 8146 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8147 D.getCXXScopeSpec().isNotEmpty() || 8148 isExplicitSpecialization || 8149 isFunctionTemplateSpecialization); 8150 8151 // Handle GNU asm-label extension (encoded as an attribute). 8152 if (Expr *E = (Expr*) D.getAsmLabel()) { 8153 // The parser guarantees this is a string. 8154 StringLiteral *SE = cast<StringLiteral>(E); 8155 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8156 SE->getString(), 0)); 8157 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8158 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8159 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8160 if (I != ExtnameUndeclaredIdentifiers.end()) { 8161 if (isDeclExternC(NewFD)) { 8162 NewFD->addAttr(I->second); 8163 ExtnameUndeclaredIdentifiers.erase(I); 8164 } else 8165 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8166 << /*Variable*/0 << NewFD; 8167 } 8168 } 8169 8170 // Copy the parameter declarations from the declarator D to the function 8171 // declaration NewFD, if they are available. First scavenge them into Params. 8172 SmallVector<ParmVarDecl*, 16> Params; 8173 if (D.isFunctionDeclarator()) { 8174 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8175 8176 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8177 // function that takes no arguments, not a function that takes a 8178 // single void argument. 8179 // We let through "const void" here because Sema::GetTypeForDeclarator 8180 // already checks for that case. 8181 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8182 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8183 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8184 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8185 Param->setDeclContext(NewFD); 8186 Params.push_back(Param); 8187 8188 if (Param->isInvalidDecl()) 8189 NewFD->setInvalidDecl(); 8190 } 8191 } 8192 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8193 // When we're declaring a function with a typedef, typeof, etc as in the 8194 // following example, we'll need to synthesize (unnamed) 8195 // parameters for use in the declaration. 8196 // 8197 // @code 8198 // typedef void fn(int); 8199 // fn f; 8200 // @endcode 8201 8202 // Synthesize a parameter for each argument type. 8203 for (const auto &AI : FT->param_types()) { 8204 ParmVarDecl *Param = 8205 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8206 Param->setScopeInfo(0, Params.size()); 8207 Params.push_back(Param); 8208 } 8209 } else { 8210 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8211 "Should not need args for typedef of non-prototype fn"); 8212 } 8213 8214 // Finally, we know we have the right number of parameters, install them. 8215 NewFD->setParams(Params); 8216 8217 // Find all anonymous symbols defined during the declaration of this function 8218 // and add to NewFD. This lets us track decls such 'enum Y' in: 8219 // 8220 // void f(enum Y {AA} x) {} 8221 // 8222 // which would otherwise incorrectly end up in the translation unit scope. 8223 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 8224 DeclsInPrototypeScope.clear(); 8225 8226 if (D.getDeclSpec().isNoreturnSpecified()) 8227 NewFD->addAttr( 8228 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8229 Context, 0)); 8230 8231 // Functions returning a variably modified type violate C99 6.7.5.2p2 8232 // because all functions have linkage. 8233 if (!NewFD->isInvalidDecl() && 8234 NewFD->getReturnType()->isVariablyModifiedType()) { 8235 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8236 NewFD->setInvalidDecl(); 8237 } 8238 8239 // Apply an implicit SectionAttr if #pragma code_seg is active. 8240 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8241 !NewFD->hasAttr<SectionAttr>()) { 8242 NewFD->addAttr( 8243 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8244 CodeSegStack.CurrentValue->getString(), 8245 CodeSegStack.CurrentPragmaLocation)); 8246 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8247 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8248 ASTContext::PSF_Read, 8249 NewFD)) 8250 NewFD->dropAttr<SectionAttr>(); 8251 } 8252 8253 // Handle attributes. 8254 ProcessDeclAttributes(S, NewFD, D); 8255 8256 if (getLangOpts().CUDA) 8257 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous); 8258 8259 if (getLangOpts().OpenCL) { 8260 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8261 // type declaration will generate a compilation error. 8262 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8263 if (AddressSpace == LangAS::opencl_local || 8264 AddressSpace == LangAS::opencl_global || 8265 AddressSpace == LangAS::opencl_constant) { 8266 Diag(NewFD->getLocation(), 8267 diag::err_opencl_return_value_with_address_space); 8268 NewFD->setInvalidDecl(); 8269 } 8270 } 8271 8272 if (!getLangOpts().CPlusPlus) { 8273 // Perform semantic checking on the function declaration. 8274 bool isExplicitSpecialization=false; 8275 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8276 CheckMain(NewFD, D.getDeclSpec()); 8277 8278 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8279 CheckMSVCRTEntryPoint(NewFD); 8280 8281 if (!NewFD->isInvalidDecl()) 8282 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8283 isExplicitSpecialization)); 8284 else if (!Previous.empty()) 8285 // Recover gracefully from an invalid redeclaration. 8286 D.setRedeclaration(true); 8287 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8288 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8289 "previous declaration set still overloaded"); 8290 8291 // Diagnose no-prototype function declarations with calling conventions that 8292 // don't support variadic calls. Only do this in C and do it after merging 8293 // possibly prototyped redeclarations. 8294 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8295 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8296 CallingConv CC = FT->getExtInfo().getCC(); 8297 if (!supportsVariadicCall(CC)) { 8298 // Windows system headers sometimes accidentally use stdcall without 8299 // (void) parameters, so we relax this to a warning. 8300 int DiagID = 8301 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8302 Diag(NewFD->getLocation(), DiagID) 8303 << FunctionType::getNameForCallConv(CC); 8304 } 8305 } 8306 } else { 8307 // C++11 [replacement.functions]p3: 8308 // The program's definitions shall not be specified as inline. 8309 // 8310 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8311 // 8312 // Suppress the diagnostic if the function is __attribute__((used)), since 8313 // that forces an external definition to be emitted. 8314 if (D.getDeclSpec().isInlineSpecified() && 8315 NewFD->isReplaceableGlobalAllocationFunction() && 8316 !NewFD->hasAttr<UsedAttr>()) 8317 Diag(D.getDeclSpec().getInlineSpecLoc(), 8318 diag::ext_operator_new_delete_declared_inline) 8319 << NewFD->getDeclName(); 8320 8321 // If the declarator is a template-id, translate the parser's template 8322 // argument list into our AST format. 8323 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8324 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8325 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8326 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8327 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8328 TemplateId->NumArgs); 8329 translateTemplateArguments(TemplateArgsPtr, 8330 TemplateArgs); 8331 8332 HasExplicitTemplateArgs = true; 8333 8334 if (NewFD->isInvalidDecl()) { 8335 HasExplicitTemplateArgs = false; 8336 } else if (FunctionTemplate) { 8337 // Function template with explicit template arguments. 8338 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8339 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8340 8341 HasExplicitTemplateArgs = false; 8342 } else { 8343 assert((isFunctionTemplateSpecialization || 8344 D.getDeclSpec().isFriendSpecified()) && 8345 "should have a 'template<>' for this decl"); 8346 // "friend void foo<>(int);" is an implicit specialization decl. 8347 isFunctionTemplateSpecialization = true; 8348 } 8349 } else if (isFriend && isFunctionTemplateSpecialization) { 8350 // This combination is only possible in a recovery case; the user 8351 // wrote something like: 8352 // template <> friend void foo(int); 8353 // which we're recovering from as if the user had written: 8354 // friend void foo<>(int); 8355 // Go ahead and fake up a template id. 8356 HasExplicitTemplateArgs = true; 8357 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8358 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8359 } 8360 8361 // If it's a friend (and only if it's a friend), it's possible 8362 // that either the specialized function type or the specialized 8363 // template is dependent, and therefore matching will fail. In 8364 // this case, don't check the specialization yet. 8365 bool InstantiationDependent = false; 8366 if (isFunctionTemplateSpecialization && isFriend && 8367 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8368 TemplateSpecializationType::anyDependentTemplateArguments( 8369 TemplateArgs, 8370 InstantiationDependent))) { 8371 assert(HasExplicitTemplateArgs && 8372 "friend function specialization without template args"); 8373 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8374 Previous)) 8375 NewFD->setInvalidDecl(); 8376 } else if (isFunctionTemplateSpecialization) { 8377 if (CurContext->isDependentContext() && CurContext->isRecord() 8378 && !isFriend) { 8379 isDependentClassScopeExplicitSpecialization = true; 8380 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8381 diag::ext_function_specialization_in_class : 8382 diag::err_function_specialization_in_class) 8383 << NewFD->getDeclName(); 8384 } else if (CheckFunctionTemplateSpecialization(NewFD, 8385 (HasExplicitTemplateArgs ? &TemplateArgs 8386 : nullptr), 8387 Previous)) 8388 NewFD->setInvalidDecl(); 8389 8390 // C++ [dcl.stc]p1: 8391 // A storage-class-specifier shall not be specified in an explicit 8392 // specialization (14.7.3) 8393 FunctionTemplateSpecializationInfo *Info = 8394 NewFD->getTemplateSpecializationInfo(); 8395 if (Info && SC != SC_None) { 8396 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8397 Diag(NewFD->getLocation(), 8398 diag::err_explicit_specialization_inconsistent_storage_class) 8399 << SC 8400 << FixItHint::CreateRemoval( 8401 D.getDeclSpec().getStorageClassSpecLoc()); 8402 8403 else 8404 Diag(NewFD->getLocation(), 8405 diag::ext_explicit_specialization_storage_class) 8406 << FixItHint::CreateRemoval( 8407 D.getDeclSpec().getStorageClassSpecLoc()); 8408 } 8409 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 8410 if (CheckMemberSpecialization(NewFD, Previous)) 8411 NewFD->setInvalidDecl(); 8412 } 8413 8414 // Perform semantic checking on the function declaration. 8415 if (!isDependentClassScopeExplicitSpecialization) { 8416 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8417 CheckMain(NewFD, D.getDeclSpec()); 8418 8419 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8420 CheckMSVCRTEntryPoint(NewFD); 8421 8422 if (!NewFD->isInvalidDecl()) 8423 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8424 isExplicitSpecialization)); 8425 else if (!Previous.empty()) 8426 // Recover gracefully from an invalid redeclaration. 8427 D.setRedeclaration(true); 8428 } 8429 8430 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8431 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8432 "previous declaration set still overloaded"); 8433 8434 NamedDecl *PrincipalDecl = (FunctionTemplate 8435 ? cast<NamedDecl>(FunctionTemplate) 8436 : NewFD); 8437 8438 if (isFriend && D.isRedeclaration()) { 8439 AccessSpecifier Access = AS_public; 8440 if (!NewFD->isInvalidDecl()) 8441 Access = NewFD->getPreviousDecl()->getAccess(); 8442 8443 NewFD->setAccess(Access); 8444 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8445 } 8446 8447 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8448 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8449 PrincipalDecl->setNonMemberOperator(); 8450 8451 // If we have a function template, check the template parameter 8452 // list. This will check and merge default template arguments. 8453 if (FunctionTemplate) { 8454 FunctionTemplateDecl *PrevTemplate = 8455 FunctionTemplate->getPreviousDecl(); 8456 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8457 PrevTemplate ? PrevTemplate->getTemplateParameters() 8458 : nullptr, 8459 D.getDeclSpec().isFriendSpecified() 8460 ? (D.isFunctionDefinition() 8461 ? TPC_FriendFunctionTemplateDefinition 8462 : TPC_FriendFunctionTemplate) 8463 : (D.getCXXScopeSpec().isSet() && 8464 DC && DC->isRecord() && 8465 DC->isDependentContext()) 8466 ? TPC_ClassTemplateMember 8467 : TPC_FunctionTemplate); 8468 } 8469 8470 if (NewFD->isInvalidDecl()) { 8471 // Ignore all the rest of this. 8472 } else if (!D.isRedeclaration()) { 8473 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8474 AddToScope }; 8475 // Fake up an access specifier if it's supposed to be a class member. 8476 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8477 NewFD->setAccess(AS_public); 8478 8479 // Qualified decls generally require a previous declaration. 8480 if (D.getCXXScopeSpec().isSet()) { 8481 // ...with the major exception of templated-scope or 8482 // dependent-scope friend declarations. 8483 8484 // TODO: we currently also suppress this check in dependent 8485 // contexts because (1) the parameter depth will be off when 8486 // matching friend templates and (2) we might actually be 8487 // selecting a friend based on a dependent factor. But there 8488 // are situations where these conditions don't apply and we 8489 // can actually do this check immediately. 8490 if (isFriend && 8491 (TemplateParamLists.size() || 8492 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8493 CurContext->isDependentContext())) { 8494 // ignore these 8495 } else { 8496 // The user tried to provide an out-of-line definition for a 8497 // function that is a member of a class or namespace, but there 8498 // was no such member function declared (C++ [class.mfct]p2, 8499 // C++ [namespace.memdef]p2). For example: 8500 // 8501 // class X { 8502 // void f() const; 8503 // }; 8504 // 8505 // void X::f() { } // ill-formed 8506 // 8507 // Complain about this problem, and attempt to suggest close 8508 // matches (e.g., those that differ only in cv-qualifiers and 8509 // whether the parameter types are references). 8510 8511 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8512 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8513 AddToScope = ExtraArgs.AddToScope; 8514 return Result; 8515 } 8516 } 8517 8518 // Unqualified local friend declarations are required to resolve 8519 // to something. 8520 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8521 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8522 *this, Previous, NewFD, ExtraArgs, true, S)) { 8523 AddToScope = ExtraArgs.AddToScope; 8524 return Result; 8525 } 8526 } 8527 } else if (!D.isFunctionDefinition() && 8528 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8529 !isFriend && !isFunctionTemplateSpecialization && 8530 !isExplicitSpecialization) { 8531 // An out-of-line member function declaration must also be a 8532 // definition (C++ [class.mfct]p2). 8533 // Note that this is not the case for explicit specializations of 8534 // function templates or member functions of class templates, per 8535 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8536 // extension for compatibility with old SWIG code which likes to 8537 // generate them. 8538 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8539 << D.getCXXScopeSpec().getRange(); 8540 } 8541 } 8542 8543 ProcessPragmaWeak(S, NewFD); 8544 checkAttributesAfterMerging(*this, *NewFD); 8545 8546 AddKnownFunctionAttributes(NewFD); 8547 8548 if (NewFD->hasAttr<OverloadableAttr>() && 8549 !NewFD->getType()->getAs<FunctionProtoType>()) { 8550 Diag(NewFD->getLocation(), 8551 diag::err_attribute_overloadable_no_prototype) 8552 << NewFD; 8553 8554 // Turn this into a variadic function with no parameters. 8555 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8556 FunctionProtoType::ExtProtoInfo EPI( 8557 Context.getDefaultCallingConvention(true, false)); 8558 EPI.Variadic = true; 8559 EPI.ExtInfo = FT->getExtInfo(); 8560 8561 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8562 NewFD->setType(R); 8563 } 8564 8565 // If there's a #pragma GCC visibility in scope, and this isn't a class 8566 // member, set the visibility of this function. 8567 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8568 AddPushedVisibilityAttribute(NewFD); 8569 8570 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8571 // marking the function. 8572 AddCFAuditedAttribute(NewFD); 8573 8574 // If this is a function definition, check if we have to apply optnone due to 8575 // a pragma. 8576 if(D.isFunctionDefinition()) 8577 AddRangeBasedOptnone(NewFD); 8578 8579 // If this is the first declaration of an extern C variable, update 8580 // the map of such variables. 8581 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8582 isIncompleteDeclExternC(*this, NewFD)) 8583 RegisterLocallyScopedExternCDecl(NewFD, S); 8584 8585 // Set this FunctionDecl's range up to the right paren. 8586 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8587 8588 if (D.isRedeclaration() && !Previous.empty()) { 8589 checkDLLAttributeRedeclaration( 8590 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8591 isExplicitSpecialization || isFunctionTemplateSpecialization, 8592 D.isFunctionDefinition()); 8593 } 8594 8595 if (getLangOpts().CUDA) { 8596 IdentifierInfo *II = NewFD->getIdentifier(); 8597 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 8598 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8599 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8600 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8601 8602 Context.setcudaConfigureCallDecl(NewFD); 8603 } 8604 8605 // Variadic functions, other than a *declaration* of printf, are not allowed 8606 // in device-side CUDA code, unless someone passed 8607 // -fcuda-allow-variadic-functions. 8608 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 8609 (NewFD->hasAttr<CUDADeviceAttr>() || 8610 NewFD->hasAttr<CUDAGlobalAttr>()) && 8611 !(II && II->isStr("printf") && NewFD->isExternC() && 8612 !D.isFunctionDefinition())) { 8613 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 8614 } 8615 } 8616 8617 if (getLangOpts().CPlusPlus) { 8618 if (FunctionTemplate) { 8619 if (NewFD->isInvalidDecl()) 8620 FunctionTemplate->setInvalidDecl(); 8621 return FunctionTemplate; 8622 } 8623 } 8624 8625 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8626 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8627 if ((getLangOpts().OpenCLVersion >= 120) 8628 && (SC == SC_Static)) { 8629 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8630 D.setInvalidType(); 8631 } 8632 8633 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8634 if (!NewFD->getReturnType()->isVoidType()) { 8635 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8636 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8637 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8638 : FixItHint()); 8639 D.setInvalidType(); 8640 } 8641 8642 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8643 for (auto Param : NewFD->parameters()) 8644 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8645 } 8646 for (const ParmVarDecl *Param : NewFD->parameters()) { 8647 QualType PT = Param->getType(); 8648 8649 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 8650 // types. 8651 if (getLangOpts().OpenCLVersion >= 200) { 8652 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 8653 QualType ElemTy = PipeTy->getElementType(); 8654 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 8655 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 8656 D.setInvalidType(); 8657 } 8658 } 8659 } 8660 } 8661 8662 MarkUnusedFileScopedDecl(NewFD); 8663 8664 // Here we have an function template explicit specialization at class scope. 8665 // The actually specialization will be postponed to template instatiation 8666 // time via the ClassScopeFunctionSpecializationDecl node. 8667 if (isDependentClassScopeExplicitSpecialization) { 8668 ClassScopeFunctionSpecializationDecl *NewSpec = 8669 ClassScopeFunctionSpecializationDecl::Create( 8670 Context, CurContext, SourceLocation(), 8671 cast<CXXMethodDecl>(NewFD), 8672 HasExplicitTemplateArgs, TemplateArgs); 8673 CurContext->addDecl(NewSpec); 8674 AddToScope = false; 8675 } 8676 8677 return NewFD; 8678 } 8679 8680 /// \brief Checks if the new declaration declared in dependent context must be 8681 /// put in the same redeclaration chain as the specified declaration. 8682 /// 8683 /// \param D Declaration that is checked. 8684 /// \param PrevDecl Previous declaration found with proper lookup method for the 8685 /// same declaration name. 8686 /// \returns True if D must be added to the redeclaration chain which PrevDecl 8687 /// belongs to. 8688 /// 8689 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 8690 // Any declarations should be put into redeclaration chains except for 8691 // friend declaration in a dependent context that names a function in 8692 // namespace scope. 8693 // 8694 // This allows to compile code like: 8695 // 8696 // void func(); 8697 // template<typename T> class C1 { friend void func() { } }; 8698 // template<typename T> class C2 { friend void func() { } }; 8699 // 8700 // This code snippet is a valid code unless both templates are instantiated. 8701 return !(D->getLexicalDeclContext()->isDependentContext() && 8702 D->getDeclContext()->isFileContext() && 8703 D->getFriendObjectKind() != Decl::FOK_None); 8704 } 8705 8706 /// \brief Perform semantic checking of a new function declaration. 8707 /// 8708 /// Performs semantic analysis of the new function declaration 8709 /// NewFD. This routine performs all semantic checking that does not 8710 /// require the actual declarator involved in the declaration, and is 8711 /// used both for the declaration of functions as they are parsed 8712 /// (called via ActOnDeclarator) and for the declaration of functions 8713 /// that have been instantiated via C++ template instantiation (called 8714 /// via InstantiateDecl). 8715 /// 8716 /// \param IsExplicitSpecialization whether this new function declaration is 8717 /// an explicit specialization of the previous declaration. 8718 /// 8719 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8720 /// 8721 /// \returns true if the function declaration is a redeclaration. 8722 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8723 LookupResult &Previous, 8724 bool IsExplicitSpecialization) { 8725 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8726 "Variably modified return types are not handled here"); 8727 8728 // Determine whether the type of this function should be merged with 8729 // a previous visible declaration. This never happens for functions in C++, 8730 // and always happens in C if the previous declaration was visible. 8731 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8732 !Previous.isShadowed(); 8733 8734 bool Redeclaration = false; 8735 NamedDecl *OldDecl = nullptr; 8736 8737 // Merge or overload the declaration with an existing declaration of 8738 // the same name, if appropriate. 8739 if (!Previous.empty()) { 8740 // Determine whether NewFD is an overload of PrevDecl or 8741 // a declaration that requires merging. If it's an overload, 8742 // there's no more work to do here; we'll just add the new 8743 // function to the scope. 8744 if (!AllowOverloadingOfFunction(Previous, Context)) { 8745 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8746 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8747 Redeclaration = true; 8748 OldDecl = Candidate; 8749 } 8750 } else { 8751 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8752 /*NewIsUsingDecl*/ false)) { 8753 case Ovl_Match: 8754 Redeclaration = true; 8755 break; 8756 8757 case Ovl_NonFunction: 8758 Redeclaration = true; 8759 break; 8760 8761 case Ovl_Overload: 8762 Redeclaration = false; 8763 break; 8764 } 8765 8766 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8767 // If a function name is overloadable in C, then every function 8768 // with that name must be marked "overloadable". 8769 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8770 << Redeclaration << NewFD; 8771 NamedDecl *OverloadedDecl = nullptr; 8772 if (Redeclaration) 8773 OverloadedDecl = OldDecl; 8774 else if (!Previous.empty()) 8775 OverloadedDecl = Previous.getRepresentativeDecl(); 8776 if (OverloadedDecl) 8777 Diag(OverloadedDecl->getLocation(), 8778 diag::note_attribute_overloadable_prev_overload); 8779 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8780 } 8781 } 8782 } 8783 8784 // Check for a previous extern "C" declaration with this name. 8785 if (!Redeclaration && 8786 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8787 if (!Previous.empty()) { 8788 // This is an extern "C" declaration with the same name as a previous 8789 // declaration, and thus redeclares that entity... 8790 Redeclaration = true; 8791 OldDecl = Previous.getFoundDecl(); 8792 MergeTypeWithPrevious = false; 8793 8794 // ... except in the presence of __attribute__((overloadable)). 8795 if (OldDecl->hasAttr<OverloadableAttr>()) { 8796 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8797 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8798 << Redeclaration << NewFD; 8799 Diag(Previous.getFoundDecl()->getLocation(), 8800 diag::note_attribute_overloadable_prev_overload); 8801 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8802 } 8803 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8804 Redeclaration = false; 8805 OldDecl = nullptr; 8806 } 8807 } 8808 } 8809 } 8810 8811 // C++11 [dcl.constexpr]p8: 8812 // A constexpr specifier for a non-static member function that is not 8813 // a constructor declares that member function to be const. 8814 // 8815 // This needs to be delayed until we know whether this is an out-of-line 8816 // definition of a static member function. 8817 // 8818 // This rule is not present in C++1y, so we produce a backwards 8819 // compatibility warning whenever it happens in C++11. 8820 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8821 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8822 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8823 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8824 CXXMethodDecl *OldMD = nullptr; 8825 if (OldDecl) 8826 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8827 if (!OldMD || !OldMD->isStatic()) { 8828 const FunctionProtoType *FPT = 8829 MD->getType()->castAs<FunctionProtoType>(); 8830 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8831 EPI.TypeQuals |= Qualifiers::Const; 8832 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8833 FPT->getParamTypes(), EPI)); 8834 8835 // Warn that we did this, if we're not performing template instantiation. 8836 // In that case, we'll have warned already when the template was defined. 8837 if (ActiveTemplateInstantiations.empty()) { 8838 SourceLocation AddConstLoc; 8839 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8840 .IgnoreParens().getAs<FunctionTypeLoc>()) 8841 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8842 8843 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8844 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8845 } 8846 } 8847 } 8848 8849 if (Redeclaration) { 8850 // NewFD and OldDecl represent declarations that need to be 8851 // merged. 8852 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8853 NewFD->setInvalidDecl(); 8854 return Redeclaration; 8855 } 8856 8857 Previous.clear(); 8858 Previous.addDecl(OldDecl); 8859 8860 if (FunctionTemplateDecl *OldTemplateDecl 8861 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8862 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8863 FunctionTemplateDecl *NewTemplateDecl 8864 = NewFD->getDescribedFunctionTemplate(); 8865 assert(NewTemplateDecl && "Template/non-template mismatch"); 8866 if (CXXMethodDecl *Method 8867 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8868 Method->setAccess(OldTemplateDecl->getAccess()); 8869 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8870 } 8871 8872 // If this is an explicit specialization of a member that is a function 8873 // template, mark it as a member specialization. 8874 if (IsExplicitSpecialization && 8875 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8876 NewTemplateDecl->setMemberSpecialization(); 8877 assert(OldTemplateDecl->isMemberSpecialization()); 8878 // Explicit specializations of a member template do not inherit deleted 8879 // status from the parent member template that they are specializing. 8880 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 8881 FunctionDecl *const OldTemplatedDecl = 8882 OldTemplateDecl->getTemplatedDecl(); 8883 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 8884 OldTemplatedDecl->setDeletedAsWritten(false); 8885 } 8886 } 8887 8888 } else { 8889 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 8890 // This needs to happen first so that 'inline' propagates. 8891 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8892 if (isa<CXXMethodDecl>(NewFD)) 8893 NewFD->setAccess(OldDecl->getAccess()); 8894 } else { 8895 Redeclaration = false; 8896 } 8897 } 8898 } 8899 8900 // Semantic checking for this function declaration (in isolation). 8901 8902 if (getLangOpts().CPlusPlus) { 8903 // C++-specific checks. 8904 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8905 CheckConstructor(Constructor); 8906 } else if (CXXDestructorDecl *Destructor = 8907 dyn_cast<CXXDestructorDecl>(NewFD)) { 8908 CXXRecordDecl *Record = Destructor->getParent(); 8909 QualType ClassType = Context.getTypeDeclType(Record); 8910 8911 // FIXME: Shouldn't we be able to perform this check even when the class 8912 // type is dependent? Both gcc and edg can handle that. 8913 if (!ClassType->isDependentType()) { 8914 DeclarationName Name 8915 = Context.DeclarationNames.getCXXDestructorName( 8916 Context.getCanonicalType(ClassType)); 8917 if (NewFD->getDeclName() != Name) { 8918 Diag(NewFD->getLocation(), diag::err_destructor_name); 8919 NewFD->setInvalidDecl(); 8920 return Redeclaration; 8921 } 8922 } 8923 } else if (CXXConversionDecl *Conversion 8924 = dyn_cast<CXXConversionDecl>(NewFD)) { 8925 ActOnConversionDeclarator(Conversion); 8926 } 8927 8928 // Find any virtual functions that this function overrides. 8929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8930 if (!Method->isFunctionTemplateSpecialization() && 8931 !Method->getDescribedFunctionTemplate() && 8932 Method->isCanonicalDecl()) { 8933 if (AddOverriddenMethods(Method->getParent(), Method)) { 8934 // If the function was marked as "static", we have a problem. 8935 if (NewFD->getStorageClass() == SC_Static) { 8936 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8937 } 8938 } 8939 } 8940 8941 if (Method->isStatic()) 8942 checkThisInStaticMemberFunctionType(Method); 8943 } 8944 8945 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8946 if (NewFD->isOverloadedOperator() && 8947 CheckOverloadedOperatorDeclaration(NewFD)) { 8948 NewFD->setInvalidDecl(); 8949 return Redeclaration; 8950 } 8951 8952 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8953 if (NewFD->getLiteralIdentifier() && 8954 CheckLiteralOperatorDeclaration(NewFD)) { 8955 NewFD->setInvalidDecl(); 8956 return Redeclaration; 8957 } 8958 8959 // In C++, check default arguments now that we have merged decls. Unless 8960 // the lexical context is the class, because in this case this is done 8961 // during delayed parsing anyway. 8962 if (!CurContext->isRecord()) 8963 CheckCXXDefaultArguments(NewFD); 8964 8965 // If this function declares a builtin function, check the type of this 8966 // declaration against the expected type for the builtin. 8967 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8968 ASTContext::GetBuiltinTypeError Error; 8969 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8970 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8971 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8972 // The type of this function differs from the type of the builtin, 8973 // so forget about the builtin entirely. 8974 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8975 } 8976 } 8977 8978 // If this function is declared as being extern "C", then check to see if 8979 // the function returns a UDT (class, struct, or union type) that is not C 8980 // compatible, and if it does, warn the user. 8981 // But, issue any diagnostic on the first declaration only. 8982 if (Previous.empty() && NewFD->isExternC()) { 8983 QualType R = NewFD->getReturnType(); 8984 if (R->isIncompleteType() && !R->isVoidType()) 8985 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8986 << NewFD << R; 8987 else if (!R.isPODType(Context) && !R->isVoidType() && 8988 !R->isObjCObjectPointerType()) 8989 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8990 } 8991 } 8992 return Redeclaration; 8993 } 8994 8995 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8996 // C++11 [basic.start.main]p3: 8997 // A program that [...] declares main to be inline, static or 8998 // constexpr is ill-formed. 8999 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9000 // appear in a declaration of main. 9001 // static main is not an error under C99, but we should warn about it. 9002 // We accept _Noreturn main as an extension. 9003 if (FD->getStorageClass() == SC_Static) 9004 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9005 ? diag::err_static_main : diag::warn_static_main) 9006 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9007 if (FD->isInlineSpecified()) 9008 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9009 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9010 if (DS.isNoreturnSpecified()) { 9011 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9012 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9013 Diag(NoreturnLoc, diag::ext_noreturn_main); 9014 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9015 << FixItHint::CreateRemoval(NoreturnRange); 9016 } 9017 if (FD->isConstexpr()) { 9018 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9019 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9020 FD->setConstexpr(false); 9021 } 9022 9023 if (getLangOpts().OpenCL) { 9024 Diag(FD->getLocation(), diag::err_opencl_no_main) 9025 << FD->hasAttr<OpenCLKernelAttr>(); 9026 FD->setInvalidDecl(); 9027 return; 9028 } 9029 9030 QualType T = FD->getType(); 9031 assert(T->isFunctionType() && "function decl is not of function type"); 9032 const FunctionType* FT = T->castAs<FunctionType>(); 9033 9034 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9035 // In C with GNU extensions we allow main() to have non-integer return 9036 // type, but we should warn about the extension, and we disable the 9037 // implicit-return-zero rule. 9038 9039 // GCC in C mode accepts qualified 'int'. 9040 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9041 FD->setHasImplicitReturnZero(true); 9042 else { 9043 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9044 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9045 if (RTRange.isValid()) 9046 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9047 << FixItHint::CreateReplacement(RTRange, "int"); 9048 } 9049 } else { 9050 // In C and C++, main magically returns 0 if you fall off the end; 9051 // set the flag which tells us that. 9052 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9053 9054 // All the standards say that main() should return 'int'. 9055 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9056 FD->setHasImplicitReturnZero(true); 9057 else { 9058 // Otherwise, this is just a flat-out error. 9059 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9060 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9061 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9062 : FixItHint()); 9063 FD->setInvalidDecl(true); 9064 } 9065 } 9066 9067 // Treat protoless main() as nullary. 9068 if (isa<FunctionNoProtoType>(FT)) return; 9069 9070 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9071 unsigned nparams = FTP->getNumParams(); 9072 assert(FD->getNumParams() == nparams); 9073 9074 bool HasExtraParameters = (nparams > 3); 9075 9076 if (FTP->isVariadic()) { 9077 Diag(FD->getLocation(), diag::ext_variadic_main); 9078 // FIXME: if we had information about the location of the ellipsis, we 9079 // could add a FixIt hint to remove it as a parameter. 9080 } 9081 9082 // Darwin passes an undocumented fourth argument of type char**. If 9083 // other platforms start sprouting these, the logic below will start 9084 // getting shifty. 9085 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9086 HasExtraParameters = false; 9087 9088 if (HasExtraParameters) { 9089 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9090 FD->setInvalidDecl(true); 9091 nparams = 3; 9092 } 9093 9094 // FIXME: a lot of the following diagnostics would be improved 9095 // if we had some location information about types. 9096 9097 QualType CharPP = 9098 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9099 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9100 9101 for (unsigned i = 0; i < nparams; ++i) { 9102 QualType AT = FTP->getParamType(i); 9103 9104 bool mismatch = true; 9105 9106 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9107 mismatch = false; 9108 else if (Expected[i] == CharPP) { 9109 // As an extension, the following forms are okay: 9110 // char const ** 9111 // char const * const * 9112 // char * const * 9113 9114 QualifierCollector qs; 9115 const PointerType* PT; 9116 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9117 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9118 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9119 Context.CharTy)) { 9120 qs.removeConst(); 9121 mismatch = !qs.empty(); 9122 } 9123 } 9124 9125 if (mismatch) { 9126 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9127 // TODO: suggest replacing given type with expected type 9128 FD->setInvalidDecl(true); 9129 } 9130 } 9131 9132 if (nparams == 1 && !FD->isInvalidDecl()) { 9133 Diag(FD->getLocation(), diag::warn_main_one_arg); 9134 } 9135 9136 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9137 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9138 FD->setInvalidDecl(); 9139 } 9140 } 9141 9142 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9143 QualType T = FD->getType(); 9144 assert(T->isFunctionType() && "function decl is not of function type"); 9145 const FunctionType *FT = T->castAs<FunctionType>(); 9146 9147 // Set an implicit return of 'zero' if the function can return some integral, 9148 // enumeration, pointer or nullptr type. 9149 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9150 FT->getReturnType()->isAnyPointerType() || 9151 FT->getReturnType()->isNullPtrType()) 9152 // DllMain is exempt because a return value of zero means it failed. 9153 if (FD->getName() != "DllMain") 9154 FD->setHasImplicitReturnZero(true); 9155 9156 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9157 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9158 FD->setInvalidDecl(); 9159 } 9160 } 9161 9162 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9163 // FIXME: Need strict checking. In C89, we need to check for 9164 // any assignment, increment, decrement, function-calls, or 9165 // commas outside of a sizeof. In C99, it's the same list, 9166 // except that the aforementioned are allowed in unevaluated 9167 // expressions. Everything else falls under the 9168 // "may accept other forms of constant expressions" exception. 9169 // (We never end up here for C++, so the constant expression 9170 // rules there don't matter.) 9171 const Expr *Culprit; 9172 if (Init->isConstantInitializer(Context, false, &Culprit)) 9173 return false; 9174 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9175 << Culprit->getSourceRange(); 9176 return true; 9177 } 9178 9179 namespace { 9180 // Visits an initialization expression to see if OrigDecl is evaluated in 9181 // its own initialization and throws a warning if it does. 9182 class SelfReferenceChecker 9183 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9184 Sema &S; 9185 Decl *OrigDecl; 9186 bool isRecordType; 9187 bool isPODType; 9188 bool isReferenceType; 9189 9190 bool isInitList; 9191 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9192 9193 public: 9194 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9195 9196 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9197 S(S), OrigDecl(OrigDecl) { 9198 isPODType = false; 9199 isRecordType = false; 9200 isReferenceType = false; 9201 isInitList = false; 9202 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9203 isPODType = VD->getType().isPODType(S.Context); 9204 isRecordType = VD->getType()->isRecordType(); 9205 isReferenceType = VD->getType()->isReferenceType(); 9206 } 9207 } 9208 9209 // For most expressions, just call the visitor. For initializer lists, 9210 // track the index of the field being initialized since fields are 9211 // initialized in order allowing use of previously initialized fields. 9212 void CheckExpr(Expr *E) { 9213 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9214 if (!InitList) { 9215 Visit(E); 9216 return; 9217 } 9218 9219 // Track and increment the index here. 9220 isInitList = true; 9221 InitFieldIndex.push_back(0); 9222 for (auto Child : InitList->children()) { 9223 CheckExpr(cast<Expr>(Child)); 9224 ++InitFieldIndex.back(); 9225 } 9226 InitFieldIndex.pop_back(); 9227 } 9228 9229 // Returns true if MemberExpr is checked and no futher checking is needed. 9230 // Returns false if additional checking is required. 9231 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9232 llvm::SmallVector<FieldDecl*, 4> Fields; 9233 Expr *Base = E; 9234 bool ReferenceField = false; 9235 9236 // Get the field memebers used. 9237 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9238 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9239 if (!FD) 9240 return false; 9241 Fields.push_back(FD); 9242 if (FD->getType()->isReferenceType()) 9243 ReferenceField = true; 9244 Base = ME->getBase()->IgnoreParenImpCasts(); 9245 } 9246 9247 // Keep checking only if the base Decl is the same. 9248 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9249 if (!DRE || DRE->getDecl() != OrigDecl) 9250 return false; 9251 9252 // A reference field can be bound to an unininitialized field. 9253 if (CheckReference && !ReferenceField) 9254 return true; 9255 9256 // Convert FieldDecls to their index number. 9257 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9258 for (const FieldDecl *I : llvm::reverse(Fields)) 9259 UsedFieldIndex.push_back(I->getFieldIndex()); 9260 9261 // See if a warning is needed by checking the first difference in index 9262 // numbers. If field being used has index less than the field being 9263 // initialized, then the use is safe. 9264 for (auto UsedIter = UsedFieldIndex.begin(), 9265 UsedEnd = UsedFieldIndex.end(), 9266 OrigIter = InitFieldIndex.begin(), 9267 OrigEnd = InitFieldIndex.end(); 9268 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9269 if (*UsedIter < *OrigIter) 9270 return true; 9271 if (*UsedIter > *OrigIter) 9272 break; 9273 } 9274 9275 // TODO: Add a different warning which will print the field names. 9276 HandleDeclRefExpr(DRE); 9277 return true; 9278 } 9279 9280 // For most expressions, the cast is directly above the DeclRefExpr. 9281 // For conditional operators, the cast can be outside the conditional 9282 // operator if both expressions are DeclRefExpr's. 9283 void HandleValue(Expr *E) { 9284 E = E->IgnoreParens(); 9285 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9286 HandleDeclRefExpr(DRE); 9287 return; 9288 } 9289 9290 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9291 Visit(CO->getCond()); 9292 HandleValue(CO->getTrueExpr()); 9293 HandleValue(CO->getFalseExpr()); 9294 return; 9295 } 9296 9297 if (BinaryConditionalOperator *BCO = 9298 dyn_cast<BinaryConditionalOperator>(E)) { 9299 Visit(BCO->getCond()); 9300 HandleValue(BCO->getFalseExpr()); 9301 return; 9302 } 9303 9304 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9305 HandleValue(OVE->getSourceExpr()); 9306 return; 9307 } 9308 9309 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9310 if (BO->getOpcode() == BO_Comma) { 9311 Visit(BO->getLHS()); 9312 HandleValue(BO->getRHS()); 9313 return; 9314 } 9315 } 9316 9317 if (isa<MemberExpr>(E)) { 9318 if (isInitList) { 9319 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9320 false /*CheckReference*/)) 9321 return; 9322 } 9323 9324 Expr *Base = E->IgnoreParenImpCasts(); 9325 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9326 // Check for static member variables and don't warn on them. 9327 if (!isa<FieldDecl>(ME->getMemberDecl())) 9328 return; 9329 Base = ME->getBase()->IgnoreParenImpCasts(); 9330 } 9331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9332 HandleDeclRefExpr(DRE); 9333 return; 9334 } 9335 9336 Visit(E); 9337 } 9338 9339 // Reference types not handled in HandleValue are handled here since all 9340 // uses of references are bad, not just r-value uses. 9341 void VisitDeclRefExpr(DeclRefExpr *E) { 9342 if (isReferenceType) 9343 HandleDeclRefExpr(E); 9344 } 9345 9346 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9347 if (E->getCastKind() == CK_LValueToRValue) { 9348 HandleValue(E->getSubExpr()); 9349 return; 9350 } 9351 9352 Inherited::VisitImplicitCastExpr(E); 9353 } 9354 9355 void VisitMemberExpr(MemberExpr *E) { 9356 if (isInitList) { 9357 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9358 return; 9359 } 9360 9361 // Don't warn on arrays since they can be treated as pointers. 9362 if (E->getType()->canDecayToPointerType()) return; 9363 9364 // Warn when a non-static method call is followed by non-static member 9365 // field accesses, which is followed by a DeclRefExpr. 9366 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9367 bool Warn = (MD && !MD->isStatic()); 9368 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9369 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9370 if (!isa<FieldDecl>(ME->getMemberDecl())) 9371 Warn = false; 9372 Base = ME->getBase()->IgnoreParenImpCasts(); 9373 } 9374 9375 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9376 if (Warn) 9377 HandleDeclRefExpr(DRE); 9378 return; 9379 } 9380 9381 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9382 // Visit that expression. 9383 Visit(Base); 9384 } 9385 9386 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9387 Expr *Callee = E->getCallee(); 9388 9389 if (isa<UnresolvedLookupExpr>(Callee)) 9390 return Inherited::VisitCXXOperatorCallExpr(E); 9391 9392 Visit(Callee); 9393 for (auto Arg: E->arguments()) 9394 HandleValue(Arg->IgnoreParenImpCasts()); 9395 } 9396 9397 void VisitUnaryOperator(UnaryOperator *E) { 9398 // For POD record types, addresses of its own members are well-defined. 9399 if (E->getOpcode() == UO_AddrOf && isRecordType && 9400 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9401 if (!isPODType) 9402 HandleValue(E->getSubExpr()); 9403 return; 9404 } 9405 9406 if (E->isIncrementDecrementOp()) { 9407 HandleValue(E->getSubExpr()); 9408 return; 9409 } 9410 9411 Inherited::VisitUnaryOperator(E); 9412 } 9413 9414 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9415 9416 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9417 if (E->getConstructor()->isCopyConstructor()) { 9418 Expr *ArgExpr = E->getArg(0); 9419 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9420 if (ILE->getNumInits() == 1) 9421 ArgExpr = ILE->getInit(0); 9422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9423 if (ICE->getCastKind() == CK_NoOp) 9424 ArgExpr = ICE->getSubExpr(); 9425 HandleValue(ArgExpr); 9426 return; 9427 } 9428 Inherited::VisitCXXConstructExpr(E); 9429 } 9430 9431 void VisitCallExpr(CallExpr *E) { 9432 // Treat std::move as a use. 9433 if (E->getNumArgs() == 1) { 9434 if (FunctionDecl *FD = E->getDirectCallee()) { 9435 if (FD->isInStdNamespace() && FD->getIdentifier() && 9436 FD->getIdentifier()->isStr("move")) { 9437 HandleValue(E->getArg(0)); 9438 return; 9439 } 9440 } 9441 } 9442 9443 Inherited::VisitCallExpr(E); 9444 } 9445 9446 void VisitBinaryOperator(BinaryOperator *E) { 9447 if (E->isCompoundAssignmentOp()) { 9448 HandleValue(E->getLHS()); 9449 Visit(E->getRHS()); 9450 return; 9451 } 9452 9453 Inherited::VisitBinaryOperator(E); 9454 } 9455 9456 // A custom visitor for BinaryConditionalOperator is needed because the 9457 // regular visitor would check the condition and true expression separately 9458 // but both point to the same place giving duplicate diagnostics. 9459 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9460 Visit(E->getCond()); 9461 Visit(E->getFalseExpr()); 9462 } 9463 9464 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9465 Decl* ReferenceDecl = DRE->getDecl(); 9466 if (OrigDecl != ReferenceDecl) return; 9467 unsigned diag; 9468 if (isReferenceType) { 9469 diag = diag::warn_uninit_self_reference_in_reference_init; 9470 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9471 diag = diag::warn_static_self_reference_in_init; 9472 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9473 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9474 DRE->getDecl()->getType()->isRecordType()) { 9475 diag = diag::warn_uninit_self_reference_in_init; 9476 } else { 9477 // Local variables will be handled by the CFG analysis. 9478 return; 9479 } 9480 9481 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9482 S.PDiag(diag) 9483 << DRE->getNameInfo().getName() 9484 << OrigDecl->getLocation() 9485 << DRE->getSourceRange()); 9486 } 9487 }; 9488 9489 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9490 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9491 bool DirectInit) { 9492 // Parameters arguments are occassionially constructed with itself, 9493 // for instance, in recursive functions. Skip them. 9494 if (isa<ParmVarDecl>(OrigDecl)) 9495 return; 9496 9497 E = E->IgnoreParens(); 9498 9499 // Skip checking T a = a where T is not a record or reference type. 9500 // Doing so is a way to silence uninitialized warnings. 9501 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9502 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9503 if (ICE->getCastKind() == CK_LValueToRValue) 9504 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9505 if (DRE->getDecl() == OrigDecl) 9506 return; 9507 9508 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9509 } 9510 } // end anonymous namespace 9511 9512 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9513 DeclarationName Name, QualType Type, 9514 TypeSourceInfo *TSI, 9515 SourceRange Range, bool DirectInit, 9516 Expr *Init) { 9517 bool IsInitCapture = !VDecl; 9518 assert((!VDecl || !VDecl->isInitCapture()) && 9519 "init captures are expected to be deduced prior to initialization"); 9520 9521 // FIXME: Deduction for a decomposition declaration does weird things if the 9522 // initializer is an array. 9523 9524 ArrayRef<Expr *> DeduceInits = Init; 9525 if (DirectInit) { 9526 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9527 DeduceInits = PL->exprs(); 9528 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9529 DeduceInits = IL->inits(); 9530 } 9531 9532 // Deduction only works if we have exactly one source expression. 9533 if (DeduceInits.empty()) { 9534 // It isn't possible to write this directly, but it is possible to 9535 // end up in this situation with "auto x(some_pack...);" 9536 Diag(Init->getLocStart(), IsInitCapture 9537 ? diag::err_init_capture_no_expression 9538 : diag::err_auto_var_init_no_expression) 9539 << Name << Type << Range; 9540 return QualType(); 9541 } 9542 9543 if (DeduceInits.size() > 1) { 9544 Diag(DeduceInits[1]->getLocStart(), 9545 IsInitCapture ? diag::err_init_capture_multiple_expressions 9546 : diag::err_auto_var_init_multiple_expressions) 9547 << Name << Type << Range; 9548 return QualType(); 9549 } 9550 9551 Expr *DeduceInit = DeduceInits[0]; 9552 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9553 Diag(Init->getLocStart(), IsInitCapture 9554 ? diag::err_init_capture_paren_braces 9555 : diag::err_auto_var_init_paren_braces) 9556 << isa<InitListExpr>(Init) << Name << Type << Range; 9557 return QualType(); 9558 } 9559 9560 // Expressions default to 'id' when we're in a debugger. 9561 bool DefaultedAnyToId = false; 9562 if (getLangOpts().DebuggerCastResultToId && 9563 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9564 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9565 if (Result.isInvalid()) { 9566 return QualType(); 9567 } 9568 Init = Result.get(); 9569 DefaultedAnyToId = true; 9570 } 9571 9572 QualType DeducedType; 9573 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9574 if (!IsInitCapture) 9575 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9576 else if (isa<InitListExpr>(Init)) 9577 Diag(Range.getBegin(), 9578 diag::err_init_capture_deduction_failure_from_init_list) 9579 << Name 9580 << (DeduceInit->getType().isNull() ? TSI->getType() 9581 : DeduceInit->getType()) 9582 << DeduceInit->getSourceRange(); 9583 else 9584 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9585 << Name << TSI->getType() 9586 << (DeduceInit->getType().isNull() ? TSI->getType() 9587 : DeduceInit->getType()) 9588 << DeduceInit->getSourceRange(); 9589 } 9590 9591 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9592 // 'id' instead of a specific object type prevents most of our usual 9593 // checks. 9594 // We only want to warn outside of template instantiations, though: 9595 // inside a template, the 'id' could have come from a parameter. 9596 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9597 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9598 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9599 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9600 } 9601 9602 return DeducedType; 9603 } 9604 9605 /// AddInitializerToDecl - Adds the initializer Init to the 9606 /// declaration dcl. If DirectInit is true, this is C++ direct 9607 /// initialization rather than copy initialization. 9608 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9609 bool DirectInit, bool TypeMayContainAuto) { 9610 // If there is no declaration, there was an error parsing it. Just ignore 9611 // the initializer. 9612 if (!RealDecl || RealDecl->isInvalidDecl()) { 9613 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9614 return; 9615 } 9616 9617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9618 // Pure-specifiers are handled in ActOnPureSpecifier. 9619 Diag(Method->getLocation(), diag::err_member_function_initialization) 9620 << Method->getDeclName() << Init->getSourceRange(); 9621 Method->setInvalidDecl(); 9622 return; 9623 } 9624 9625 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9626 if (!VDecl) { 9627 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9628 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9629 RealDecl->setInvalidDecl(); 9630 return; 9631 } 9632 9633 // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not 9634 // permitted. 9635 if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init)) 9636 Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl; 9637 9638 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9639 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9640 // Attempt typo correction early so that the type of the init expression can 9641 // be deduced based on the chosen correction if the original init contains a 9642 // TypoExpr. 9643 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9644 if (!Res.isUsable()) { 9645 RealDecl->setInvalidDecl(); 9646 return; 9647 } 9648 Init = Res.get(); 9649 9650 QualType DeducedType = deduceVarTypeFromInitializer( 9651 VDecl, VDecl->getDeclName(), VDecl->getType(), 9652 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9653 if (DeducedType.isNull()) { 9654 RealDecl->setInvalidDecl(); 9655 return; 9656 } 9657 9658 VDecl->setType(DeducedType); 9659 assert(VDecl->isLinkageValid()); 9660 9661 // In ARC, infer lifetime. 9662 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9663 VDecl->setInvalidDecl(); 9664 9665 // If this is a redeclaration, check that the type we just deduced matches 9666 // the previously declared type. 9667 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9668 // We never need to merge the type, because we cannot form an incomplete 9669 // array of auto, nor deduce such a type. 9670 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9671 } 9672 9673 // Check the deduced type is valid for a variable declaration. 9674 CheckVariableDeclarationType(VDecl); 9675 if (VDecl->isInvalidDecl()) 9676 return; 9677 } 9678 9679 // dllimport cannot be used on variable definitions. 9680 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9681 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9682 VDecl->setInvalidDecl(); 9683 return; 9684 } 9685 9686 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9687 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9688 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9689 VDecl->setInvalidDecl(); 9690 return; 9691 } 9692 9693 if (!VDecl->getType()->isDependentType()) { 9694 // A definition must end up with a complete type, which means it must be 9695 // complete with the restriction that an array type might be completed by 9696 // the initializer; note that later code assumes this restriction. 9697 QualType BaseDeclType = VDecl->getType(); 9698 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9699 BaseDeclType = Array->getElementType(); 9700 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9701 diag::err_typecheck_decl_incomplete_type)) { 9702 RealDecl->setInvalidDecl(); 9703 return; 9704 } 9705 9706 // The variable can not have an abstract class type. 9707 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9708 diag::err_abstract_type_in_decl, 9709 AbstractVariableType)) 9710 VDecl->setInvalidDecl(); 9711 } 9712 9713 // If adding the initializer will turn this declaration into a definition, 9714 // and we already have a definition for this variable, diagnose or otherwise 9715 // handle the situation. 9716 VarDecl *Def; 9717 if ((Def = VDecl->getDefinition()) && Def != VDecl && 9718 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 9719 !VDecl->isThisDeclarationADemotedDefinition() && 9720 checkVarDeclRedefinition(Def, VDecl)) 9721 return; 9722 9723 if (getLangOpts().CPlusPlus) { 9724 // C++ [class.static.data]p4 9725 // If a static data member is of const integral or const 9726 // enumeration type, its declaration in the class definition can 9727 // specify a constant-initializer which shall be an integral 9728 // constant expression (5.19). In that case, the member can appear 9729 // in integral constant expressions. The member shall still be 9730 // defined in a namespace scope if it is used in the program and the 9731 // namespace scope definition shall not contain an initializer. 9732 // 9733 // We already performed a redefinition check above, but for static 9734 // data members we also need to check whether there was an in-class 9735 // declaration with an initializer. 9736 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9737 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9738 << VDecl->getDeclName(); 9739 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9740 diag::note_previous_initializer) 9741 << 0; 9742 return; 9743 } 9744 9745 if (VDecl->hasLocalStorage()) 9746 getCurFunction()->setHasBranchProtectedScope(); 9747 9748 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9749 VDecl->setInvalidDecl(); 9750 return; 9751 } 9752 } 9753 9754 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9755 // a kernel function cannot be initialized." 9756 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9757 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9758 VDecl->setInvalidDecl(); 9759 return; 9760 } 9761 9762 // Get the decls type and save a reference for later, since 9763 // CheckInitializerTypes may change it. 9764 QualType DclT = VDecl->getType(), SavT = DclT; 9765 9766 // Expressions default to 'id' when we're in a debugger 9767 // and we are assigning it to a variable of Objective-C pointer type. 9768 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9769 Init->getType() == Context.UnknownAnyTy) { 9770 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9771 if (Result.isInvalid()) { 9772 VDecl->setInvalidDecl(); 9773 return; 9774 } 9775 Init = Result.get(); 9776 } 9777 9778 // Perform the initialization. 9779 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9780 if (!VDecl->isInvalidDecl()) { 9781 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9782 InitializationKind Kind = 9783 DirectInit 9784 ? CXXDirectInit 9785 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9786 Init->getLocStart(), 9787 Init->getLocEnd()) 9788 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9789 : InitializationKind::CreateCopy(VDecl->getLocation(), 9790 Init->getLocStart()); 9791 9792 MultiExprArg Args = Init; 9793 if (CXXDirectInit) 9794 Args = MultiExprArg(CXXDirectInit->getExprs(), 9795 CXXDirectInit->getNumExprs()); 9796 9797 // Try to correct any TypoExprs in the initialization arguments. 9798 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9799 ExprResult Res = CorrectDelayedTyposInExpr( 9800 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9801 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9802 return Init.Failed() ? ExprError() : E; 9803 }); 9804 if (Res.isInvalid()) { 9805 VDecl->setInvalidDecl(); 9806 } else if (Res.get() != Args[Idx]) { 9807 Args[Idx] = Res.get(); 9808 } 9809 } 9810 if (VDecl->isInvalidDecl()) 9811 return; 9812 9813 InitializationSequence InitSeq(*this, Entity, Kind, Args, 9814 /*TopLevelOfInitList=*/false, 9815 /*TreatUnavailableAsInvalid=*/false); 9816 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9817 if (Result.isInvalid()) { 9818 VDecl->setInvalidDecl(); 9819 return; 9820 } 9821 9822 Init = Result.getAs<Expr>(); 9823 } 9824 9825 // Check for self-references within variable initializers. 9826 // Variables declared within a function/method body (except for references) 9827 // are handled by a dataflow analysis. 9828 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9829 VDecl->getType()->isReferenceType()) { 9830 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9831 } 9832 9833 // If the type changed, it means we had an incomplete type that was 9834 // completed by the initializer. For example: 9835 // int ary[] = { 1, 3, 5 }; 9836 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9837 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9838 VDecl->setType(DclT); 9839 9840 if (!VDecl->isInvalidDecl()) { 9841 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9842 9843 if (VDecl->hasAttr<BlocksAttr>()) 9844 checkRetainCycles(VDecl, Init); 9845 9846 // It is safe to assign a weak reference into a strong variable. 9847 // Although this code can still have problems: 9848 // id x = self.weakProp; 9849 // id y = self.weakProp; 9850 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9851 // paths through the function. This should be revisited if 9852 // -Wrepeated-use-of-weak is made flow-sensitive. 9853 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9854 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9855 Init->getLocStart())) 9856 getCurFunction()->markSafeWeakUse(Init); 9857 } 9858 9859 // The initialization is usually a full-expression. 9860 // 9861 // FIXME: If this is a braced initialization of an aggregate, it is not 9862 // an expression, and each individual field initializer is a separate 9863 // full-expression. For instance, in: 9864 // 9865 // struct Temp { ~Temp(); }; 9866 // struct S { S(Temp); }; 9867 // struct T { S a, b; } t = { Temp(), Temp() } 9868 // 9869 // we should destroy the first Temp before constructing the second. 9870 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9871 false, 9872 VDecl->isConstexpr()); 9873 if (Result.isInvalid()) { 9874 VDecl->setInvalidDecl(); 9875 return; 9876 } 9877 Init = Result.get(); 9878 9879 // Attach the initializer to the decl. 9880 VDecl->setInit(Init); 9881 9882 if (VDecl->isLocalVarDecl()) { 9883 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9884 // static storage duration shall be constant expressions or string literals. 9885 // C++ does not have this restriction. 9886 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9887 const Expr *Culprit; 9888 if (VDecl->getStorageClass() == SC_Static) 9889 CheckForConstantInitializer(Init, DclT); 9890 // C89 is stricter than C99 for non-static aggregate types. 9891 // C89 6.5.7p3: All the expressions [...] in an initializer list 9892 // for an object that has aggregate or union type shall be 9893 // constant expressions. 9894 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9895 isa<InitListExpr>(Init) && 9896 !Init->isConstantInitializer(Context, false, &Culprit)) 9897 Diag(Culprit->getExprLoc(), 9898 diag::ext_aggregate_init_not_constant) 9899 << Culprit->getSourceRange(); 9900 } 9901 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 9902 VDecl->getLexicalDeclContext()->isRecord()) { 9903 // This is an in-class initialization for a static data member, e.g., 9904 // 9905 // struct S { 9906 // static const int value = 17; 9907 // }; 9908 9909 // C++ [class.mem]p4: 9910 // A member-declarator can contain a constant-initializer only 9911 // if it declares a static member (9.4) of const integral or 9912 // const enumeration type, see 9.4.2. 9913 // 9914 // C++11 [class.static.data]p3: 9915 // If a non-volatile non-inline const static data member is of integral 9916 // or enumeration type, its declaration in the class definition can 9917 // specify a brace-or-equal-initializer in which every initalizer-clause 9918 // that is an assignment-expression is a constant expression. A static 9919 // data member of literal type can be declared in the class definition 9920 // with the constexpr specifier; if so, its declaration shall specify a 9921 // brace-or-equal-initializer in which every initializer-clause that is 9922 // an assignment-expression is a constant expression. 9923 9924 // Do nothing on dependent types. 9925 if (DclT->isDependentType()) { 9926 9927 // Allow any 'static constexpr' members, whether or not they are of literal 9928 // type. We separately check that every constexpr variable is of literal 9929 // type. 9930 } else if (VDecl->isConstexpr()) { 9931 9932 // Require constness. 9933 } else if (!DclT.isConstQualified()) { 9934 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9935 << Init->getSourceRange(); 9936 VDecl->setInvalidDecl(); 9937 9938 // We allow integer constant expressions in all cases. 9939 } else if (DclT->isIntegralOrEnumerationType()) { 9940 // Check whether the expression is a constant expression. 9941 SourceLocation Loc; 9942 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9943 // In C++11, a non-constexpr const static data member with an 9944 // in-class initializer cannot be volatile. 9945 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9946 else if (Init->isValueDependent()) 9947 ; // Nothing to check. 9948 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9949 ; // Ok, it's an ICE! 9950 else if (Init->isEvaluatable(Context)) { 9951 // If we can constant fold the initializer through heroics, accept it, 9952 // but report this as a use of an extension for -pedantic. 9953 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9954 << Init->getSourceRange(); 9955 } else { 9956 // Otherwise, this is some crazy unknown case. Report the issue at the 9957 // location provided by the isIntegerConstantExpr failed check. 9958 Diag(Loc, diag::err_in_class_initializer_non_constant) 9959 << Init->getSourceRange(); 9960 VDecl->setInvalidDecl(); 9961 } 9962 9963 // We allow foldable floating-point constants as an extension. 9964 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9965 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9966 // it anyway and provide a fixit to add the 'constexpr'. 9967 if (getLangOpts().CPlusPlus11) { 9968 Diag(VDecl->getLocation(), 9969 diag::ext_in_class_initializer_float_type_cxx11) 9970 << DclT << Init->getSourceRange(); 9971 Diag(VDecl->getLocStart(), 9972 diag::note_in_class_initializer_float_type_cxx11) 9973 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9974 } else { 9975 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9976 << DclT << Init->getSourceRange(); 9977 9978 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9979 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9980 << Init->getSourceRange(); 9981 VDecl->setInvalidDecl(); 9982 } 9983 } 9984 9985 // Suggest adding 'constexpr' in C++11 for literal types. 9986 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9987 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9988 << DclT << Init->getSourceRange() 9989 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9990 VDecl->setConstexpr(true); 9991 9992 } else { 9993 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9994 << DclT << Init->getSourceRange(); 9995 VDecl->setInvalidDecl(); 9996 } 9997 } else if (VDecl->isFileVarDecl()) { 9998 // In C, extern is typically used to avoid tentative definitions when 9999 // declaring variables in headers, but adding an intializer makes it a 10000 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10001 // In C++, extern is often used to give implictly static const variables 10002 // external linkage, so don't warn in that case. If selectany is present, 10003 // this might be header code intended for C and C++ inclusion, so apply the 10004 // C++ rules. 10005 if (VDecl->getStorageClass() == SC_Extern && 10006 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10007 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10008 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10009 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10010 Diag(VDecl->getLocation(), diag::warn_extern_init); 10011 10012 // C99 6.7.8p4. All file scoped initializers need to be constant. 10013 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10014 CheckForConstantInitializer(Init, DclT); 10015 } 10016 10017 // We will represent direct-initialization similarly to copy-initialization: 10018 // int x(1); -as-> int x = 1; 10019 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10020 // 10021 // Clients that want to distinguish between the two forms, can check for 10022 // direct initializer using VarDecl::getInitStyle(). 10023 // A major benefit is that clients that don't particularly care about which 10024 // exactly form was it (like the CodeGen) can handle both cases without 10025 // special case code. 10026 10027 // C++ 8.5p11: 10028 // The form of initialization (using parentheses or '=') is generally 10029 // insignificant, but does matter when the entity being initialized has a 10030 // class type. 10031 if (CXXDirectInit) { 10032 assert(DirectInit && "Call-style initializer must be direct init."); 10033 VDecl->setInitStyle(VarDecl::CallInit); 10034 } else if (DirectInit) { 10035 // This must be list-initialization. No other way is direct-initialization. 10036 VDecl->setInitStyle(VarDecl::ListInit); 10037 } 10038 10039 CheckCompleteVariableDeclaration(VDecl); 10040 } 10041 10042 /// ActOnInitializerError - Given that there was an error parsing an 10043 /// initializer for the given declaration, try to return to some form 10044 /// of sanity. 10045 void Sema::ActOnInitializerError(Decl *D) { 10046 // Our main concern here is re-establishing invariants like "a 10047 // variable's type is either dependent or complete". 10048 if (!D || D->isInvalidDecl()) return; 10049 10050 VarDecl *VD = dyn_cast<VarDecl>(D); 10051 if (!VD) return; 10052 10053 // Bindings are not usable if we can't make sense of the initializer. 10054 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10055 for (auto *BD : DD->bindings()) 10056 BD->setInvalidDecl(); 10057 10058 // Auto types are meaningless if we can't make sense of the initializer. 10059 if (ParsingInitForAutoVars.count(D)) { 10060 D->setInvalidDecl(); 10061 return; 10062 } 10063 10064 QualType Ty = VD->getType(); 10065 if (Ty->isDependentType()) return; 10066 10067 // Require a complete type. 10068 if (RequireCompleteType(VD->getLocation(), 10069 Context.getBaseElementType(Ty), 10070 diag::err_typecheck_decl_incomplete_type)) { 10071 VD->setInvalidDecl(); 10072 return; 10073 } 10074 10075 // Require a non-abstract type. 10076 if (RequireNonAbstractType(VD->getLocation(), Ty, 10077 diag::err_abstract_type_in_decl, 10078 AbstractVariableType)) { 10079 VD->setInvalidDecl(); 10080 return; 10081 } 10082 10083 // Don't bother complaining about constructors or destructors, 10084 // though. 10085 } 10086 10087 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 10088 bool TypeMayContainAuto) { 10089 // If there is no declaration, there was an error parsing it. Just ignore it. 10090 if (!RealDecl) 10091 return; 10092 10093 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10094 QualType Type = Var->getType(); 10095 10096 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10097 if (isa<DecompositionDecl>(RealDecl)) { 10098 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10099 Var->setInvalidDecl(); 10100 return; 10101 } 10102 10103 // C++11 [dcl.spec.auto]p3 10104 if (TypeMayContainAuto && Type->getContainedAutoType()) { 10105 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 10106 << Var->getDeclName() << Type; 10107 Var->setInvalidDecl(); 10108 return; 10109 } 10110 10111 // C++11 [class.static.data]p3: A static data member can be declared with 10112 // the constexpr specifier; if so, its declaration shall specify 10113 // a brace-or-equal-initializer. 10114 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10115 // the definition of a variable [...] or the declaration of a static data 10116 // member. 10117 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 10118 if (Var->isStaticDataMember()) { 10119 // C++1z removes the relevant rule; the in-class declaration is always 10120 // a definition there. 10121 if (!getLangOpts().CPlusPlus1z) { 10122 Diag(Var->getLocation(), 10123 diag::err_constexpr_static_mem_var_requires_init) 10124 << Var->getDeclName(); 10125 Var->setInvalidDecl(); 10126 return; 10127 } 10128 } else { 10129 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10130 Var->setInvalidDecl(); 10131 return; 10132 } 10133 } 10134 10135 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10136 // definition having the concept specifier is called a variable concept. A 10137 // concept definition refers to [...] a variable concept and its initializer. 10138 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10139 if (VTD->isConcept()) { 10140 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10141 Var->setInvalidDecl(); 10142 return; 10143 } 10144 } 10145 10146 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10147 // be initialized. 10148 if (!Var->isInvalidDecl() && 10149 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10150 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10151 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10152 Var->setInvalidDecl(); 10153 return; 10154 } 10155 10156 switch (Var->isThisDeclarationADefinition()) { 10157 case VarDecl::Definition: 10158 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10159 break; 10160 10161 // We have an out-of-line definition of a static data member 10162 // that has an in-class initializer, so we type-check this like 10163 // a declaration. 10164 // 10165 // Fall through 10166 10167 case VarDecl::DeclarationOnly: 10168 // It's only a declaration. 10169 10170 // Block scope. C99 6.7p7: If an identifier for an object is 10171 // declared with no linkage (C99 6.2.2p6), the type for the 10172 // object shall be complete. 10173 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10174 !Var->hasLinkage() && !Var->isInvalidDecl() && 10175 RequireCompleteType(Var->getLocation(), Type, 10176 diag::err_typecheck_decl_incomplete_type)) 10177 Var->setInvalidDecl(); 10178 10179 // Make sure that the type is not abstract. 10180 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10181 RequireNonAbstractType(Var->getLocation(), Type, 10182 diag::err_abstract_type_in_decl, 10183 AbstractVariableType)) 10184 Var->setInvalidDecl(); 10185 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10186 Var->getStorageClass() == SC_PrivateExtern) { 10187 Diag(Var->getLocation(), diag::warn_private_extern); 10188 Diag(Var->getLocation(), diag::note_private_extern); 10189 } 10190 10191 return; 10192 10193 case VarDecl::TentativeDefinition: 10194 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10195 // object that has file scope without an initializer, and without a 10196 // storage-class specifier or with the storage-class specifier "static", 10197 // constitutes a tentative definition. Note: A tentative definition with 10198 // external linkage is valid (C99 6.2.2p5). 10199 if (!Var->isInvalidDecl()) { 10200 if (const IncompleteArrayType *ArrayT 10201 = Context.getAsIncompleteArrayType(Type)) { 10202 if (RequireCompleteType(Var->getLocation(), 10203 ArrayT->getElementType(), 10204 diag::err_illegal_decl_array_incomplete_type)) 10205 Var->setInvalidDecl(); 10206 } else if (Var->getStorageClass() == SC_Static) { 10207 // C99 6.9.2p3: If the declaration of an identifier for an object is 10208 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10209 // declared type shall not be an incomplete type. 10210 // NOTE: code such as the following 10211 // static struct s; 10212 // struct s { int a; }; 10213 // is accepted by gcc. Hence here we issue a warning instead of 10214 // an error and we do not invalidate the static declaration. 10215 // NOTE: to avoid multiple warnings, only check the first declaration. 10216 if (Var->isFirstDecl()) 10217 RequireCompleteType(Var->getLocation(), Type, 10218 diag::ext_typecheck_decl_incomplete_type); 10219 } 10220 } 10221 10222 // Record the tentative definition; we're done. 10223 if (!Var->isInvalidDecl()) 10224 TentativeDefinitions.push_back(Var); 10225 return; 10226 } 10227 10228 // Provide a specific diagnostic for uninitialized variable 10229 // definitions with incomplete array type. 10230 if (Type->isIncompleteArrayType()) { 10231 Diag(Var->getLocation(), 10232 diag::err_typecheck_incomplete_array_needs_initializer); 10233 Var->setInvalidDecl(); 10234 return; 10235 } 10236 10237 // Provide a specific diagnostic for uninitialized variable 10238 // definitions with reference type. 10239 if (Type->isReferenceType()) { 10240 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10241 << Var->getDeclName() 10242 << SourceRange(Var->getLocation(), Var->getLocation()); 10243 Var->setInvalidDecl(); 10244 return; 10245 } 10246 10247 // Do not attempt to type-check the default initializer for a 10248 // variable with dependent type. 10249 if (Type->isDependentType()) 10250 return; 10251 10252 if (Var->isInvalidDecl()) 10253 return; 10254 10255 if (!Var->hasAttr<AliasAttr>()) { 10256 if (RequireCompleteType(Var->getLocation(), 10257 Context.getBaseElementType(Type), 10258 diag::err_typecheck_decl_incomplete_type)) { 10259 Var->setInvalidDecl(); 10260 return; 10261 } 10262 } else { 10263 return; 10264 } 10265 10266 // The variable can not have an abstract class type. 10267 if (RequireNonAbstractType(Var->getLocation(), Type, 10268 diag::err_abstract_type_in_decl, 10269 AbstractVariableType)) { 10270 Var->setInvalidDecl(); 10271 return; 10272 } 10273 10274 // Check for jumps past the implicit initializer. C++0x 10275 // clarifies that this applies to a "variable with automatic 10276 // storage duration", not a "local variable". 10277 // C++11 [stmt.dcl]p3 10278 // A program that jumps from a point where a variable with automatic 10279 // storage duration is not in scope to a point where it is in scope is 10280 // ill-formed unless the variable has scalar type, class type with a 10281 // trivial default constructor and a trivial destructor, a cv-qualified 10282 // version of one of these types, or an array of one of the preceding 10283 // types and is declared without an initializer. 10284 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10285 if (const RecordType *Record 10286 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10287 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10288 // Mark the function for further checking even if the looser rules of 10289 // C++11 do not require such checks, so that we can diagnose 10290 // incompatibilities with C++98. 10291 if (!CXXRecord->isPOD()) 10292 getCurFunction()->setHasBranchProtectedScope(); 10293 } 10294 } 10295 10296 // C++03 [dcl.init]p9: 10297 // If no initializer is specified for an object, and the 10298 // object is of (possibly cv-qualified) non-POD class type (or 10299 // array thereof), the object shall be default-initialized; if 10300 // the object is of const-qualified type, the underlying class 10301 // type shall have a user-declared default 10302 // constructor. Otherwise, if no initializer is specified for 10303 // a non- static object, the object and its subobjects, if 10304 // any, have an indeterminate initial value); if the object 10305 // or any of its subobjects are of const-qualified type, the 10306 // program is ill-formed. 10307 // C++0x [dcl.init]p11: 10308 // If no initializer is specified for an object, the object is 10309 // default-initialized; [...]. 10310 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10311 InitializationKind Kind 10312 = InitializationKind::CreateDefault(Var->getLocation()); 10313 10314 InitializationSequence InitSeq(*this, Entity, Kind, None); 10315 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10316 if (Init.isInvalid()) 10317 Var->setInvalidDecl(); 10318 else if (Init.get()) { 10319 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10320 // This is important for template substitution. 10321 Var->setInitStyle(VarDecl::CallInit); 10322 } 10323 10324 CheckCompleteVariableDeclaration(Var); 10325 } 10326 } 10327 10328 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10329 // If there is no declaration, there was an error parsing it. Ignore it. 10330 if (!D) 10331 return; 10332 10333 VarDecl *VD = dyn_cast<VarDecl>(D); 10334 if (!VD) { 10335 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10336 D->setInvalidDecl(); 10337 return; 10338 } 10339 10340 VD->setCXXForRangeDecl(true); 10341 10342 // for-range-declaration cannot be given a storage class specifier. 10343 int Error = -1; 10344 switch (VD->getStorageClass()) { 10345 case SC_None: 10346 break; 10347 case SC_Extern: 10348 Error = 0; 10349 break; 10350 case SC_Static: 10351 Error = 1; 10352 break; 10353 case SC_PrivateExtern: 10354 Error = 2; 10355 break; 10356 case SC_Auto: 10357 Error = 3; 10358 break; 10359 case SC_Register: 10360 Error = 4; 10361 break; 10362 } 10363 if (Error != -1) { 10364 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10365 << VD->getDeclName() << Error; 10366 D->setInvalidDecl(); 10367 } 10368 } 10369 10370 StmtResult 10371 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10372 IdentifierInfo *Ident, 10373 ParsedAttributes &Attrs, 10374 SourceLocation AttrEnd) { 10375 // C++1y [stmt.iter]p1: 10376 // A range-based for statement of the form 10377 // for ( for-range-identifier : for-range-initializer ) statement 10378 // is equivalent to 10379 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10380 DeclSpec DS(Attrs.getPool().getFactory()); 10381 10382 const char *PrevSpec; 10383 unsigned DiagID; 10384 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10385 getPrintingPolicy()); 10386 10387 Declarator D(DS, Declarator::ForContext); 10388 D.SetIdentifier(Ident, IdentLoc); 10389 D.takeAttributes(Attrs, AttrEnd); 10390 10391 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10392 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10393 EmptyAttrs, IdentLoc); 10394 Decl *Var = ActOnDeclarator(S, D); 10395 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10396 FinalizeDeclaration(Var); 10397 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10398 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10399 } 10400 10401 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10402 if (var->isInvalidDecl()) return; 10403 10404 if (getLangOpts().OpenCL) { 10405 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10406 // initialiser 10407 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10408 !var->hasInit()) { 10409 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10410 << 1 /*Init*/; 10411 var->setInvalidDecl(); 10412 return; 10413 } 10414 } 10415 10416 // In Objective-C, don't allow jumps past the implicit initialization of a 10417 // local retaining variable. 10418 if (getLangOpts().ObjC1 && 10419 var->hasLocalStorage()) { 10420 switch (var->getType().getObjCLifetime()) { 10421 case Qualifiers::OCL_None: 10422 case Qualifiers::OCL_ExplicitNone: 10423 case Qualifiers::OCL_Autoreleasing: 10424 break; 10425 10426 case Qualifiers::OCL_Weak: 10427 case Qualifiers::OCL_Strong: 10428 getCurFunction()->setHasBranchProtectedScope(); 10429 break; 10430 } 10431 } 10432 10433 // Warn about externally-visible variables being defined without a 10434 // prior declaration. We only want to do this for global 10435 // declarations, but we also specifically need to avoid doing it for 10436 // class members because the linkage of an anonymous class can 10437 // change if it's later given a typedef name. 10438 if (var->isThisDeclarationADefinition() && 10439 var->getDeclContext()->getRedeclContext()->isFileContext() && 10440 var->isExternallyVisible() && var->hasLinkage() && 10441 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10442 var->getLocation())) { 10443 // Find a previous declaration that's not a definition. 10444 VarDecl *prev = var->getPreviousDecl(); 10445 while (prev && prev->isThisDeclarationADefinition()) 10446 prev = prev->getPreviousDecl(); 10447 10448 if (!prev) 10449 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10450 } 10451 10452 // Cache the result of checking for constant initialization. 10453 Optional<bool> CacheHasConstInit; 10454 const Expr *CacheCulprit; 10455 auto checkConstInit = [&]() mutable { 10456 if (!CacheHasConstInit) 10457 CacheHasConstInit = var->getInit()->isConstantInitializer( 10458 Context, var->getType()->isReferenceType(), &CacheCulprit); 10459 return *CacheHasConstInit; 10460 }; 10461 10462 if (var->getTLSKind() == VarDecl::TLS_Static) { 10463 if (var->getType().isDestructedType()) { 10464 // GNU C++98 edits for __thread, [basic.start.term]p3: 10465 // The type of an object with thread storage duration shall not 10466 // have a non-trivial destructor. 10467 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10468 if (getLangOpts().CPlusPlus11) 10469 Diag(var->getLocation(), diag::note_use_thread_local); 10470 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10471 if (!checkConstInit()) { 10472 // GNU C++98 edits for __thread, [basic.start.init]p4: 10473 // An object of thread storage duration shall not require dynamic 10474 // initialization. 10475 // FIXME: Need strict checking here. 10476 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10477 << CacheCulprit->getSourceRange(); 10478 if (getLangOpts().CPlusPlus11) 10479 Diag(var->getLocation(), diag::note_use_thread_local); 10480 } 10481 } 10482 } 10483 10484 // Apply section attributes and pragmas to global variables. 10485 bool GlobalStorage = var->hasGlobalStorage(); 10486 if (GlobalStorage && var->isThisDeclarationADefinition() && 10487 ActiveTemplateInstantiations.empty()) { 10488 PragmaStack<StringLiteral *> *Stack = nullptr; 10489 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 10490 if (var->getType().isConstQualified()) 10491 Stack = &ConstSegStack; 10492 else if (!var->getInit()) { 10493 Stack = &BSSSegStack; 10494 SectionFlags |= ASTContext::PSF_Write; 10495 } else { 10496 Stack = &DataSegStack; 10497 SectionFlags |= ASTContext::PSF_Write; 10498 } 10499 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 10500 var->addAttr(SectionAttr::CreateImplicit( 10501 Context, SectionAttr::Declspec_allocate, 10502 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 10503 } 10504 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 10505 if (UnifySection(SA->getName(), SectionFlags, var)) 10506 var->dropAttr<SectionAttr>(); 10507 10508 // Apply the init_seg attribute if this has an initializer. If the 10509 // initializer turns out to not be dynamic, we'll end up ignoring this 10510 // attribute. 10511 if (CurInitSeg && var->getInit()) 10512 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 10513 CurInitSegLoc)); 10514 } 10515 10516 // All the following checks are C++ only. 10517 if (!getLangOpts().CPlusPlus) { 10518 // If this variable must be emitted, add it as an initializer for the 10519 // current module. 10520 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10521 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10522 return; 10523 } 10524 10525 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 10526 CheckCompleteDecompositionDeclaration(DD); 10527 10528 QualType type = var->getType(); 10529 if (type->isDependentType()) return; 10530 10531 // __block variables might require us to capture a copy-initializer. 10532 if (var->hasAttr<BlocksAttr>()) { 10533 // It's currently invalid to ever have a __block variable with an 10534 // array type; should we diagnose that here? 10535 10536 // Regardless, we don't want to ignore array nesting when 10537 // constructing this copy. 10538 if (type->isStructureOrClassType()) { 10539 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10540 SourceLocation poi = var->getLocation(); 10541 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 10542 ExprResult result 10543 = PerformMoveOrCopyInitialization( 10544 InitializedEntity::InitializeBlock(poi, type, false), 10545 var, var->getType(), varRef, /*AllowNRVO=*/true); 10546 if (!result.isInvalid()) { 10547 result = MaybeCreateExprWithCleanups(result); 10548 Expr *init = result.getAs<Expr>(); 10549 Context.setBlockVarCopyInits(var, init); 10550 } 10551 } 10552 } 10553 10554 Expr *Init = var->getInit(); 10555 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10556 QualType baseType = Context.getBaseElementType(type); 10557 10558 if (!var->getDeclContext()->isDependentContext() && 10559 Init && !Init->isValueDependent()) { 10560 10561 if (var->isConstexpr()) { 10562 SmallVector<PartialDiagnosticAt, 8> Notes; 10563 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10564 SourceLocation DiagLoc = var->getLocation(); 10565 // If the note doesn't add any useful information other than a source 10566 // location, fold it into the primary diagnostic. 10567 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10568 diag::note_invalid_subexpr_in_const_expr) { 10569 DiagLoc = Notes[0].first; 10570 Notes.clear(); 10571 } 10572 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10573 << var << Init->getSourceRange(); 10574 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10575 Diag(Notes[I].first, Notes[I].second); 10576 } 10577 } else if (var->isUsableInConstantExpressions(Context)) { 10578 // Check whether the initializer of a const variable of integral or 10579 // enumeration type is an ICE now, since we can't tell whether it was 10580 // initialized by a constant expression if we check later. 10581 var->checkInitIsICE(); 10582 } 10583 10584 // Don't emit further diagnostics about constexpr globals since they 10585 // were just diagnosed. 10586 if (!var->isConstexpr() && GlobalStorage && 10587 var->hasAttr<RequireConstantInitAttr>()) { 10588 // FIXME: Need strict checking in C++03 here. 10589 bool DiagErr = getLangOpts().CPlusPlus11 10590 ? !var->checkInitIsICE() : !checkConstInit(); 10591 if (DiagErr) { 10592 auto attr = var->getAttr<RequireConstantInitAttr>(); 10593 Diag(var->getLocation(), diag::err_require_constant_init_failed) 10594 << Init->getSourceRange(); 10595 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 10596 << attr->getRange(); 10597 } 10598 } 10599 else if (!var->isConstexpr() && IsGlobal && 10600 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10601 var->getLocation())) { 10602 // Warn about globals which don't have a constant initializer. Don't 10603 // warn about globals with a non-trivial destructor because we already 10604 // warned about them. 10605 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10606 if (!(RD && !RD->hasTrivialDestructor())) { 10607 if (!checkConstInit()) 10608 Diag(var->getLocation(), diag::warn_global_constructor) 10609 << Init->getSourceRange(); 10610 } 10611 } 10612 } 10613 10614 // Require the destructor. 10615 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10616 FinalizeVarWithDestructor(var, recordType); 10617 10618 // If this variable must be emitted, add it as an initializer for the current 10619 // module. 10620 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 10621 Context.addModuleInitializer(ModuleScopes.back().Module, var); 10622 } 10623 10624 /// \brief Determines if a variable's alignment is dependent. 10625 static bool hasDependentAlignment(VarDecl *VD) { 10626 if (VD->getType()->isDependentType()) 10627 return true; 10628 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10629 if (I->isAlignmentDependent()) 10630 return true; 10631 return false; 10632 } 10633 10634 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10635 /// any semantic actions necessary after any initializer has been attached. 10636 void 10637 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10638 // Note that we are no longer parsing the initializer for this declaration. 10639 ParsingInitForAutoVars.erase(ThisDecl); 10640 10641 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10642 if (!VD) 10643 return; 10644 10645 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 10646 for (auto *BD : DD->bindings()) { 10647 if (ThisDecl->isInvalidDecl()) 10648 BD->setInvalidDecl(); 10649 FinalizeDeclaration(BD); 10650 } 10651 } 10652 10653 checkAttributesAfterMerging(*this, *VD); 10654 10655 // Perform TLS alignment check here after attributes attached to the variable 10656 // which may affect the alignment have been processed. Only perform the check 10657 // if the target has a maximum TLS alignment (zero means no constraints). 10658 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10659 // Protect the check so that it's not performed on dependent types and 10660 // dependent alignments (we can't determine the alignment in that case). 10661 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10662 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10663 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10664 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10665 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10666 << (unsigned)MaxAlignChars.getQuantity(); 10667 } 10668 } 10669 } 10670 10671 if (VD->isStaticLocal()) { 10672 if (FunctionDecl *FD = 10673 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10674 // Static locals inherit dll attributes from their function. 10675 if (Attr *A = getDLLAttr(FD)) { 10676 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10677 NewAttr->setInherited(true); 10678 VD->addAttr(NewAttr); 10679 } 10680 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 10681 // function, only __shared__ variables may be declared with 10682 // static storage class. 10683 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 10684 CUDADiagIfDeviceCode(VD->getLocation(), 10685 diag::err_device_static_local_var) 10686 << CurrentCUDATarget()) 10687 VD->setInvalidDecl(); 10688 } 10689 } 10690 10691 // Perform check for initializers of device-side global variables. 10692 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 10693 // 7.5). We must also apply the same checks to all __shared__ 10694 // variables whether they are local or not. CUDA also allows 10695 // constant initializers for __constant__ and __device__ variables. 10696 if (getLangOpts().CUDA) { 10697 const Expr *Init = VD->getInit(); 10698 if (Init && VD->hasGlobalStorage()) { 10699 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 10700 VD->hasAttr<CUDASharedAttr>()) { 10701 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 10702 bool AllowedInit = false; 10703 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 10704 AllowedInit = 10705 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 10706 // We'll allow constant initializers even if it's a non-empty 10707 // constructor according to CUDA rules. This deviates from NVCC, 10708 // but allows us to handle things like constexpr constructors. 10709 if (!AllowedInit && 10710 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 10711 AllowedInit = VD->getInit()->isConstantInitializer( 10712 Context, VD->getType()->isReferenceType()); 10713 10714 // Also make sure that destructor, if there is one, is empty. 10715 if (AllowedInit) 10716 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 10717 AllowedInit = 10718 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 10719 10720 if (!AllowedInit) { 10721 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 10722 ? diag::err_shared_var_init 10723 : diag::err_dynamic_var_init) 10724 << Init->getSourceRange(); 10725 VD->setInvalidDecl(); 10726 } 10727 } else { 10728 // This is a host-side global variable. Check that the initializer is 10729 // callable from the host side. 10730 const FunctionDecl *InitFn = nullptr; 10731 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 10732 InitFn = CE->getConstructor(); 10733 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 10734 InitFn = CE->getDirectCallee(); 10735 } 10736 if (InitFn) { 10737 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 10738 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 10739 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 10740 << InitFnTarget << InitFn; 10741 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 10742 VD->setInvalidDecl(); 10743 } 10744 } 10745 } 10746 } 10747 } 10748 10749 // Grab the dllimport or dllexport attribute off of the VarDecl. 10750 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10751 10752 // Imported static data members cannot be defined out-of-line. 10753 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10754 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10755 VD->isThisDeclarationADefinition()) { 10756 // We allow definitions of dllimport class template static data members 10757 // with a warning. 10758 CXXRecordDecl *Context = 10759 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10760 bool IsClassTemplateMember = 10761 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10762 Context->getDescribedClassTemplate(); 10763 10764 Diag(VD->getLocation(), 10765 IsClassTemplateMember 10766 ? diag::warn_attribute_dllimport_static_field_definition 10767 : diag::err_attribute_dllimport_static_field_definition); 10768 Diag(IA->getLocation(), diag::note_attribute); 10769 if (!IsClassTemplateMember) 10770 VD->setInvalidDecl(); 10771 } 10772 } 10773 10774 // dllimport/dllexport variables cannot be thread local, their TLS index 10775 // isn't exported with the variable. 10776 if (DLLAttr && VD->getTLSKind()) { 10777 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10778 if (F && getDLLAttr(F)) { 10779 assert(VD->isStaticLocal()); 10780 // But if this is a static local in a dlimport/dllexport function, the 10781 // function will never be inlined, which means the var would never be 10782 // imported, so having it marked import/export is safe. 10783 } else { 10784 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10785 << DLLAttr; 10786 VD->setInvalidDecl(); 10787 } 10788 } 10789 10790 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10791 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10792 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10793 VD->dropAttr<UsedAttr>(); 10794 } 10795 } 10796 10797 const DeclContext *DC = VD->getDeclContext(); 10798 // If there's a #pragma GCC visibility in scope, and this isn't a class 10799 // member, set the visibility of this variable. 10800 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10801 AddPushedVisibilityAttribute(VD); 10802 10803 // FIXME: Warn on unused templates. 10804 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10805 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10806 MarkUnusedFileScopedDecl(VD); 10807 10808 // Now we have parsed the initializer and can update the table of magic 10809 // tag values. 10810 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10811 !VD->getType()->isIntegralOrEnumerationType()) 10812 return; 10813 10814 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10815 const Expr *MagicValueExpr = VD->getInit(); 10816 if (!MagicValueExpr) { 10817 continue; 10818 } 10819 llvm::APSInt MagicValueInt; 10820 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10821 Diag(I->getRange().getBegin(), 10822 diag::err_type_tag_for_datatype_not_ice) 10823 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10824 continue; 10825 } 10826 if (MagicValueInt.getActiveBits() > 64) { 10827 Diag(I->getRange().getBegin(), 10828 diag::err_type_tag_for_datatype_too_large) 10829 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10830 continue; 10831 } 10832 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10833 RegisterTypeTagForDatatype(I->getArgumentKind(), 10834 MagicValue, 10835 I->getMatchingCType(), 10836 I->getLayoutCompatible(), 10837 I->getMustBeNull()); 10838 } 10839 } 10840 10841 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10842 ArrayRef<Decl *> Group) { 10843 SmallVector<Decl*, 8> Decls; 10844 10845 if (DS.isTypeSpecOwned()) 10846 Decls.push_back(DS.getRepAsDecl()); 10847 10848 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10849 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 10850 bool DiagnosedMultipleDecomps = false; 10851 10852 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10853 if (Decl *D = Group[i]) { 10854 auto *DD = dyn_cast<DeclaratorDecl>(D); 10855 if (DD && !FirstDeclaratorInGroup) 10856 FirstDeclaratorInGroup = DD; 10857 10858 auto *Decomp = dyn_cast<DecompositionDecl>(D); 10859 if (Decomp && !FirstDecompDeclaratorInGroup) 10860 FirstDecompDeclaratorInGroup = Decomp; 10861 10862 // A decomposition declaration cannot be combined with any other 10863 // declaration in the same group. 10864 auto *OtherDD = FirstDeclaratorInGroup; 10865 if (OtherDD == FirstDecompDeclaratorInGroup) 10866 OtherDD = DD; 10867 if (OtherDD && FirstDecompDeclaratorInGroup && 10868 OtherDD != FirstDecompDeclaratorInGroup && 10869 !DiagnosedMultipleDecomps) { 10870 Diag(FirstDecompDeclaratorInGroup->getLocation(), 10871 diag::err_decomp_decl_not_alone) 10872 << OtherDD->getSourceRange(); 10873 DiagnosedMultipleDecomps = true; 10874 } 10875 10876 Decls.push_back(D); 10877 } 10878 } 10879 10880 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10881 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10882 handleTagNumbering(Tag, S); 10883 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10884 getLangOpts().CPlusPlus) 10885 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10886 } 10887 } 10888 10889 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10890 } 10891 10892 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10893 /// group, performing any necessary semantic checking. 10894 Sema::DeclGroupPtrTy 10895 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10896 bool TypeMayContainAuto) { 10897 // C++0x [dcl.spec.auto]p7: 10898 // If the type deduced for the template parameter U is not the same in each 10899 // deduction, the program is ill-formed. 10900 // FIXME: When initializer-list support is added, a distinction is needed 10901 // between the deduced type U and the deduced type which 'auto' stands for. 10902 // auto a = 0, b = { 1, 2, 3 }; 10903 // is legal because the deduced type U is 'int' in both cases. 10904 if (TypeMayContainAuto && Group.size() > 1) { 10905 QualType Deduced; 10906 CanQualType DeducedCanon; 10907 VarDecl *DeducedDecl = nullptr; 10908 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10909 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10910 AutoType *AT = D->getType()->getContainedAutoType(); 10911 // Don't reissue diagnostics when instantiating a template. 10912 if (AT && D->isInvalidDecl()) 10913 break; 10914 QualType U = AT ? AT->getDeducedType() : QualType(); 10915 if (!U.isNull()) { 10916 CanQualType UCanon = Context.getCanonicalType(U); 10917 if (Deduced.isNull()) { 10918 Deduced = U; 10919 DeducedCanon = UCanon; 10920 DeducedDecl = D; 10921 } else if (DeducedCanon != UCanon) { 10922 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10923 diag::err_auto_different_deductions) 10924 << (unsigned)AT->getKeyword() 10925 << Deduced << DeducedDecl->getDeclName() 10926 << U << D->getDeclName() 10927 << DeducedDecl->getInit()->getSourceRange() 10928 << D->getInit()->getSourceRange(); 10929 D->setInvalidDecl(); 10930 break; 10931 } 10932 } 10933 } 10934 } 10935 } 10936 10937 ActOnDocumentableDecls(Group); 10938 10939 return DeclGroupPtrTy::make( 10940 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10941 } 10942 10943 void Sema::ActOnDocumentableDecl(Decl *D) { 10944 ActOnDocumentableDecls(D); 10945 } 10946 10947 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10948 // Don't parse the comment if Doxygen diagnostics are ignored. 10949 if (Group.empty() || !Group[0]) 10950 return; 10951 10952 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10953 Group[0]->getLocation()) && 10954 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10955 Group[0]->getLocation())) 10956 return; 10957 10958 if (Group.size() >= 2) { 10959 // This is a decl group. Normally it will contain only declarations 10960 // produced from declarator list. But in case we have any definitions or 10961 // additional declaration references: 10962 // 'typedef struct S {} S;' 10963 // 'typedef struct S *S;' 10964 // 'struct S *pS;' 10965 // FinalizeDeclaratorGroup adds these as separate declarations. 10966 Decl *MaybeTagDecl = Group[0]; 10967 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10968 Group = Group.slice(1); 10969 } 10970 } 10971 10972 // See if there are any new comments that are not attached to a decl. 10973 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10974 if (!Comments.empty() && 10975 !Comments.back()->isAttached()) { 10976 // There is at least one comment that not attached to a decl. 10977 // Maybe it should be attached to one of these decls? 10978 // 10979 // Note that this way we pick up not only comments that precede the 10980 // declaration, but also comments that *follow* the declaration -- thanks to 10981 // the lookahead in the lexer: we've consumed the semicolon and looked 10982 // ahead through comments. 10983 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10984 Context.getCommentForDecl(Group[i], &PP); 10985 } 10986 } 10987 10988 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10989 /// to introduce parameters into function prototype scope. 10990 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10991 const DeclSpec &DS = D.getDeclSpec(); 10992 10993 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10994 10995 // C++03 [dcl.stc]p2 also permits 'auto'. 10996 StorageClass SC = SC_None; 10997 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10998 SC = SC_Register; 10999 } else if (getLangOpts().CPlusPlus && 11000 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11001 SC = SC_Auto; 11002 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11003 Diag(DS.getStorageClassSpecLoc(), 11004 diag::err_invalid_storage_class_in_func_decl); 11005 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11006 } 11007 11008 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11009 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11010 << DeclSpec::getSpecifierName(TSCS); 11011 if (DS.isInlineSpecified()) 11012 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11013 << getLangOpts().CPlusPlus1z; 11014 if (DS.isConstexprSpecified()) 11015 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11016 << 0; 11017 if (DS.isConceptSpecified()) 11018 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11019 11020 DiagnoseFunctionSpecifiers(DS); 11021 11022 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11023 QualType parmDeclType = TInfo->getType(); 11024 11025 if (getLangOpts().CPlusPlus) { 11026 // Check that there are no default arguments inside the type of this 11027 // parameter. 11028 CheckExtraCXXDefaultArguments(D); 11029 11030 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11031 if (D.getCXXScopeSpec().isSet()) { 11032 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11033 << D.getCXXScopeSpec().getRange(); 11034 D.getCXXScopeSpec().clear(); 11035 } 11036 } 11037 11038 // Ensure we have a valid name 11039 IdentifierInfo *II = nullptr; 11040 if (D.hasName()) { 11041 II = D.getIdentifier(); 11042 if (!II) { 11043 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11044 << GetNameForDeclarator(D).getName(); 11045 D.setInvalidType(true); 11046 } 11047 } 11048 11049 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11050 if (II) { 11051 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11052 ForRedeclaration); 11053 LookupName(R, S); 11054 if (R.isSingleResult()) { 11055 NamedDecl *PrevDecl = R.getFoundDecl(); 11056 if (PrevDecl->isTemplateParameter()) { 11057 // Maybe we will complain about the shadowed template parameter. 11058 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11059 // Just pretend that we didn't see the previous declaration. 11060 PrevDecl = nullptr; 11061 } else if (S->isDeclScope(PrevDecl)) { 11062 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11063 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11064 11065 // Recover by removing the name 11066 II = nullptr; 11067 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11068 D.setInvalidType(true); 11069 } 11070 } 11071 } 11072 11073 // Temporarily put parameter variables in the translation unit, not 11074 // the enclosing context. This prevents them from accidentally 11075 // looking like class members in C++. 11076 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11077 D.getLocStart(), 11078 D.getIdentifierLoc(), II, 11079 parmDeclType, TInfo, 11080 SC); 11081 11082 if (D.isInvalidType()) 11083 New->setInvalidDecl(); 11084 11085 assert(S->isFunctionPrototypeScope()); 11086 assert(S->getFunctionPrototypeDepth() >= 1); 11087 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11088 S->getNextFunctionPrototypeIndex()); 11089 11090 // Add the parameter declaration into this scope. 11091 S->AddDecl(New); 11092 if (II) 11093 IdResolver.AddDecl(New); 11094 11095 ProcessDeclAttributes(S, New, D); 11096 11097 if (D.getDeclSpec().isModulePrivateSpecified()) 11098 Diag(New->getLocation(), diag::err_module_private_local) 11099 << 1 << New->getDeclName() 11100 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11101 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11102 11103 if (New->hasAttr<BlocksAttr>()) { 11104 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11105 } 11106 return New; 11107 } 11108 11109 /// \brief Synthesizes a variable for a parameter arising from a 11110 /// typedef. 11111 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11112 SourceLocation Loc, 11113 QualType T) { 11114 /* FIXME: setting StartLoc == Loc. 11115 Would it be worth to modify callers so as to provide proper source 11116 location for the unnamed parameters, embedding the parameter's type? */ 11117 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11118 T, Context.getTrivialTypeSourceInfo(T, Loc), 11119 SC_None, nullptr); 11120 Param->setImplicit(); 11121 return Param; 11122 } 11123 11124 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11125 // Don't diagnose unused-parameter errors in template instantiations; we 11126 // will already have done so in the template itself. 11127 if (!ActiveTemplateInstantiations.empty()) 11128 return; 11129 11130 for (const ParmVarDecl *Parameter : Parameters) { 11131 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11132 !Parameter->hasAttr<UnusedAttr>()) { 11133 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11134 << Parameter->getDeclName(); 11135 } 11136 } 11137 } 11138 11139 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11140 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11141 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11142 return; 11143 11144 // Warn if the return value is pass-by-value and larger than the specified 11145 // threshold. 11146 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11147 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11148 if (Size > LangOpts.NumLargeByValueCopy) 11149 Diag(D->getLocation(), diag::warn_return_value_size) 11150 << D->getDeclName() << Size; 11151 } 11152 11153 // Warn if any parameter is pass-by-value and larger than the specified 11154 // threshold. 11155 for (const ParmVarDecl *Parameter : Parameters) { 11156 QualType T = Parameter->getType(); 11157 if (T->isDependentType() || !T.isPODType(Context)) 11158 continue; 11159 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11160 if (Size > LangOpts.NumLargeByValueCopy) 11161 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11162 << Parameter->getDeclName() << Size; 11163 } 11164 } 11165 11166 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11167 SourceLocation NameLoc, IdentifierInfo *Name, 11168 QualType T, TypeSourceInfo *TSInfo, 11169 StorageClass SC) { 11170 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11171 if (getLangOpts().ObjCAutoRefCount && 11172 T.getObjCLifetime() == Qualifiers::OCL_None && 11173 T->isObjCLifetimeType()) { 11174 11175 Qualifiers::ObjCLifetime lifetime; 11176 11177 // Special cases for arrays: 11178 // - if it's const, use __unsafe_unretained 11179 // - otherwise, it's an error 11180 if (T->isArrayType()) { 11181 if (!T.isConstQualified()) { 11182 DelayedDiagnostics.add( 11183 sema::DelayedDiagnostic::makeForbiddenType( 11184 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11185 } 11186 lifetime = Qualifiers::OCL_ExplicitNone; 11187 } else { 11188 lifetime = T->getObjCARCImplicitLifetime(); 11189 } 11190 T = Context.getLifetimeQualifiedType(T, lifetime); 11191 } 11192 11193 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11194 Context.getAdjustedParameterType(T), 11195 TSInfo, SC, nullptr); 11196 11197 // Parameters can not be abstract class types. 11198 // For record types, this is done by the AbstractClassUsageDiagnoser once 11199 // the class has been completely parsed. 11200 if (!CurContext->isRecord() && 11201 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11202 AbstractParamType)) 11203 New->setInvalidDecl(); 11204 11205 // Parameter declarators cannot be interface types. All ObjC objects are 11206 // passed by reference. 11207 if (T->isObjCObjectType()) { 11208 SourceLocation TypeEndLoc = 11209 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11210 Diag(NameLoc, 11211 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11212 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11213 T = Context.getObjCObjectPointerType(T); 11214 New->setType(T); 11215 } 11216 11217 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11218 // duration shall not be qualified by an address-space qualifier." 11219 // Since all parameters have automatic store duration, they can not have 11220 // an address space. 11221 if (T.getAddressSpace() != 0) { 11222 // OpenCL allows function arguments declared to be an array of a type 11223 // to be qualified with an address space. 11224 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11225 Diag(NameLoc, diag::err_arg_with_address_space); 11226 New->setInvalidDecl(); 11227 } 11228 } 11229 11230 return New; 11231 } 11232 11233 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11234 SourceLocation LocAfterDecls) { 11235 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11236 11237 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11238 // for a K&R function. 11239 if (!FTI.hasPrototype) { 11240 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11241 --i; 11242 if (FTI.Params[i].Param == nullptr) { 11243 SmallString<256> Code; 11244 llvm::raw_svector_ostream(Code) 11245 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11246 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11247 << FTI.Params[i].Ident 11248 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11249 11250 // Implicitly declare the argument as type 'int' for lack of a better 11251 // type. 11252 AttributeFactory attrs; 11253 DeclSpec DS(attrs); 11254 const char* PrevSpec; // unused 11255 unsigned DiagID; // unused 11256 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11257 DiagID, Context.getPrintingPolicy()); 11258 // Use the identifier location for the type source range. 11259 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11260 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11261 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11262 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11263 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11264 } 11265 } 11266 } 11267 } 11268 11269 Decl * 11270 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11271 MultiTemplateParamsArg TemplateParameterLists, 11272 SkipBodyInfo *SkipBody) { 11273 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11274 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11275 Scope *ParentScope = FnBodyScope->getParent(); 11276 11277 D.setFunctionDefinitionKind(FDK_Definition); 11278 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11279 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11280 } 11281 11282 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11283 Consumer.HandleInlineFunctionDefinition(D); 11284 } 11285 11286 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11287 const FunctionDecl*& PossibleZeroParamPrototype) { 11288 // Don't warn about invalid declarations. 11289 if (FD->isInvalidDecl()) 11290 return false; 11291 11292 // Or declarations that aren't global. 11293 if (!FD->isGlobal()) 11294 return false; 11295 11296 // Don't warn about C++ member functions. 11297 if (isa<CXXMethodDecl>(FD)) 11298 return false; 11299 11300 // Don't warn about 'main'. 11301 if (FD->isMain()) 11302 return false; 11303 11304 // Don't warn about inline functions. 11305 if (FD->isInlined()) 11306 return false; 11307 11308 // Don't warn about function templates. 11309 if (FD->getDescribedFunctionTemplate()) 11310 return false; 11311 11312 // Don't warn about function template specializations. 11313 if (FD->isFunctionTemplateSpecialization()) 11314 return false; 11315 11316 // Don't warn for OpenCL kernels. 11317 if (FD->hasAttr<OpenCLKernelAttr>()) 11318 return false; 11319 11320 // Don't warn on explicitly deleted functions. 11321 if (FD->isDeleted()) 11322 return false; 11323 11324 bool MissingPrototype = true; 11325 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11326 Prev; Prev = Prev->getPreviousDecl()) { 11327 // Ignore any declarations that occur in function or method 11328 // scope, because they aren't visible from the header. 11329 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11330 continue; 11331 11332 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11333 if (FD->getNumParams() == 0) 11334 PossibleZeroParamPrototype = Prev; 11335 break; 11336 } 11337 11338 return MissingPrototype; 11339 } 11340 11341 void 11342 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11343 const FunctionDecl *EffectiveDefinition, 11344 SkipBodyInfo *SkipBody) { 11345 // Don't complain if we're in GNU89 mode and the previous definition 11346 // was an extern inline function. 11347 const FunctionDecl *Definition = EffectiveDefinition; 11348 if (!Definition) 11349 if (!FD->isDefined(Definition)) 11350 return; 11351 11352 if (canRedefineFunction(Definition, getLangOpts())) 11353 return; 11354 11355 // If we don't have a visible definition of the function, and it's inline or 11356 // a template, skip the new definition. 11357 if (SkipBody && !hasVisibleDefinition(Definition) && 11358 (Definition->getFormalLinkage() == InternalLinkage || 11359 Definition->isInlined() || 11360 Definition->getDescribedFunctionTemplate() || 11361 Definition->getNumTemplateParameterLists())) { 11362 SkipBody->ShouldSkip = true; 11363 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11364 makeMergedDefinitionVisible(TD, FD->getLocation()); 11365 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 11366 FD->getLocation()); 11367 return; 11368 } 11369 11370 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11371 Definition->getStorageClass() == SC_Extern) 11372 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11373 << FD->getDeclName() << getLangOpts().CPlusPlus; 11374 else 11375 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11376 11377 Diag(Definition->getLocation(), diag::note_previous_definition); 11378 FD->setInvalidDecl(); 11379 } 11380 11381 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11382 Sema &S) { 11383 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11384 11385 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11386 LSI->CallOperator = CallOperator; 11387 LSI->Lambda = LambdaClass; 11388 LSI->ReturnType = CallOperator->getReturnType(); 11389 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11390 11391 if (LCD == LCD_None) 11392 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11393 else if (LCD == LCD_ByCopy) 11394 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11395 else if (LCD == LCD_ByRef) 11396 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11397 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11398 11399 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11400 LSI->Mutable = !CallOperator->isConst(); 11401 11402 // Add the captures to the LSI so they can be noted as already 11403 // captured within tryCaptureVar. 11404 auto I = LambdaClass->field_begin(); 11405 for (const auto &C : LambdaClass->captures()) { 11406 if (C.capturesVariable()) { 11407 VarDecl *VD = C.getCapturedVar(); 11408 if (VD->isInitCapture()) 11409 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11410 QualType CaptureType = VD->getType(); 11411 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11412 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11413 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11414 /*EllipsisLoc*/C.isPackExpansion() 11415 ? C.getEllipsisLoc() : SourceLocation(), 11416 CaptureType, /*Expr*/ nullptr); 11417 11418 } else if (C.capturesThis()) { 11419 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11420 /*Expr*/ nullptr, 11421 C.getCaptureKind() == LCK_StarThis); 11422 } else { 11423 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11424 } 11425 ++I; 11426 } 11427 } 11428 11429 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11430 SkipBodyInfo *SkipBody) { 11431 // Clear the last template instantiation error context. 11432 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 11433 11434 if (!D) 11435 return D; 11436 FunctionDecl *FD = nullptr; 11437 11438 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11439 FD = FunTmpl->getTemplatedDecl(); 11440 else 11441 FD = cast<FunctionDecl>(D); 11442 11443 // See if this is a redefinition. 11444 if (!FD->isLateTemplateParsed()) { 11445 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11446 11447 // If we're skipping the body, we're done. Don't enter the scope. 11448 if (SkipBody && SkipBody->ShouldSkip) 11449 return D; 11450 } 11451 11452 // If we are instantiating a generic lambda call operator, push 11453 // a LambdaScopeInfo onto the function stack. But use the information 11454 // that's already been calculated (ActOnLambdaExpr) to prime the current 11455 // LambdaScopeInfo. 11456 // When the template operator is being specialized, the LambdaScopeInfo, 11457 // has to be properly restored so that tryCaptureVariable doesn't try 11458 // and capture any new variables. In addition when calculating potential 11459 // captures during transformation of nested lambdas, it is necessary to 11460 // have the LSI properly restored. 11461 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11462 assert(ActiveTemplateInstantiations.size() && 11463 "There should be an active template instantiation on the stack " 11464 "when instantiating a generic lambda!"); 11465 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 11466 } 11467 else 11468 // Enter a new function scope 11469 PushFunctionScope(); 11470 11471 // Builtin functions cannot be defined. 11472 if (unsigned BuiltinID = FD->getBuiltinID()) { 11473 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 11474 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 11475 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 11476 FD->setInvalidDecl(); 11477 } 11478 } 11479 11480 // The return type of a function definition must be complete 11481 // (C99 6.9.1p3, C++ [dcl.fct]p6). 11482 QualType ResultType = FD->getReturnType(); 11483 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 11484 !FD->isInvalidDecl() && 11485 RequireCompleteType(FD->getLocation(), ResultType, 11486 diag::err_func_def_incomplete_result)) 11487 FD->setInvalidDecl(); 11488 11489 if (FnBodyScope) 11490 PushDeclContext(FnBodyScope, FD); 11491 11492 // Check the validity of our function parameters 11493 CheckParmsForFunctionDef(FD->parameters(), 11494 /*CheckParameterNames=*/true); 11495 11496 // Introduce our parameters into the function scope 11497 for (auto Param : FD->parameters()) { 11498 Param->setOwningFunction(FD); 11499 11500 // If this has an identifier, add it to the scope stack. 11501 if (Param->getIdentifier() && FnBodyScope) { 11502 CheckShadow(FnBodyScope, Param); 11503 11504 PushOnScopeChains(Param, FnBodyScope); 11505 } 11506 } 11507 11508 // If we had any tags defined in the function prototype, 11509 // introduce them into the function scope. 11510 if (FnBodyScope) { 11511 for (ArrayRef<NamedDecl *>::iterator 11512 I = FD->getDeclsInPrototypeScope().begin(), 11513 E = FD->getDeclsInPrototypeScope().end(); 11514 I != E; ++I) { 11515 NamedDecl *D = *I; 11516 11517 // Some of these decls (like enums) may have been pinned to the 11518 // translation unit for lack of a real context earlier. If so, remove 11519 // from the translation unit and reattach to the current context. 11520 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 11521 // Is the decl actually in the context? 11522 if (Context.getTranslationUnitDecl()->containsDecl(D)) 11523 Context.getTranslationUnitDecl()->removeDecl(D); 11524 // Either way, reassign the lexical decl context to our FunctionDecl. 11525 D->setLexicalDeclContext(CurContext); 11526 } 11527 11528 // If the decl has a non-null name, make accessible in the current scope. 11529 if (!D->getName().empty()) 11530 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 11531 11532 // Similarly, dive into enums and fish their constants out, making them 11533 // accessible in this scope. 11534 if (auto *ED = dyn_cast<EnumDecl>(D)) { 11535 for (auto *EI : ED->enumerators()) 11536 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 11537 } 11538 } 11539 } 11540 11541 // Ensure that the function's exception specification is instantiated. 11542 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 11543 ResolveExceptionSpec(D->getLocation(), FPT); 11544 11545 // dllimport cannot be applied to non-inline function definitions. 11546 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 11547 !FD->isTemplateInstantiation()) { 11548 assert(!FD->hasAttr<DLLExportAttr>()); 11549 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 11550 FD->setInvalidDecl(); 11551 return D; 11552 } 11553 // We want to attach documentation to original Decl (which might be 11554 // a function template). 11555 ActOnDocumentableDecl(D); 11556 if (getCurLexicalContext()->isObjCContainer() && 11557 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 11558 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 11559 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 11560 11561 return D; 11562 } 11563 11564 /// \brief Given the set of return statements within a function body, 11565 /// compute the variables that are subject to the named return value 11566 /// optimization. 11567 /// 11568 /// Each of the variables that is subject to the named return value 11569 /// optimization will be marked as NRVO variables in the AST, and any 11570 /// return statement that has a marked NRVO variable as its NRVO candidate can 11571 /// use the named return value optimization. 11572 /// 11573 /// This function applies a very simplistic algorithm for NRVO: if every return 11574 /// statement in the scope of a variable has the same NRVO candidate, that 11575 /// candidate is an NRVO variable. 11576 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 11577 ReturnStmt **Returns = Scope->Returns.data(); 11578 11579 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 11580 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 11581 if (!NRVOCandidate->isNRVOVariable()) 11582 Returns[I]->setNRVOCandidate(nullptr); 11583 } 11584 } 11585 } 11586 11587 bool Sema::canDelayFunctionBody(const Declarator &D) { 11588 // We can't delay parsing the body of a constexpr function template (yet). 11589 if (D.getDeclSpec().isConstexprSpecified()) 11590 return false; 11591 11592 // We can't delay parsing the body of a function template with a deduced 11593 // return type (yet). 11594 if (D.getDeclSpec().containsPlaceholderType()) { 11595 // If the placeholder introduces a non-deduced trailing return type, 11596 // we can still delay parsing it. 11597 if (D.getNumTypeObjects()) { 11598 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 11599 if (Outer.Kind == DeclaratorChunk::Function && 11600 Outer.Fun.hasTrailingReturnType()) { 11601 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 11602 return Ty.isNull() || !Ty->isUndeducedType(); 11603 } 11604 } 11605 return false; 11606 } 11607 11608 return true; 11609 } 11610 11611 bool Sema::canSkipFunctionBody(Decl *D) { 11612 // We cannot skip the body of a function (or function template) which is 11613 // constexpr, since we may need to evaluate its body in order to parse the 11614 // rest of the file. 11615 // We cannot skip the body of a function with an undeduced return type, 11616 // because any callers of that function need to know the type. 11617 if (const FunctionDecl *FD = D->getAsFunction()) 11618 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 11619 return false; 11620 return Consumer.shouldSkipFunctionBody(D); 11621 } 11622 11623 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 11624 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 11625 FD->setHasSkippedBody(); 11626 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 11627 MD->setHasSkippedBody(); 11628 return Decl; 11629 } 11630 11631 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 11632 return ActOnFinishFunctionBody(D, BodyArg, false); 11633 } 11634 11635 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 11636 bool IsInstantiation) { 11637 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 11638 11639 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11640 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 11641 11642 if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty()) 11643 CheckCompletedCoroutineBody(FD, Body); 11644 11645 if (FD) { 11646 FD->setBody(Body); 11647 11648 if (getLangOpts().CPlusPlus14) { 11649 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 11650 FD->getReturnType()->isUndeducedType()) { 11651 // If the function has a deduced result type but contains no 'return' 11652 // statements, the result type as written must be exactly 'auto', and 11653 // the deduced result type is 'void'. 11654 if (!FD->getReturnType()->getAs<AutoType>()) { 11655 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 11656 << FD->getReturnType(); 11657 FD->setInvalidDecl(); 11658 } else { 11659 // Substitute 'void' for the 'auto' in the type. 11660 TypeLoc ResultType = getReturnTypeLoc(FD); 11661 Context.adjustDeducedFunctionResultType( 11662 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 11663 } 11664 } 11665 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11666 // In C++11, we don't use 'auto' deduction rules for lambda call 11667 // operators because we don't support return type deduction. 11668 auto *LSI = getCurLambda(); 11669 if (LSI->HasImplicitReturnType) { 11670 deduceClosureReturnType(*LSI); 11671 11672 // C++11 [expr.prim.lambda]p4: 11673 // [...] if there are no return statements in the compound-statement 11674 // [the deduced type is] the type void 11675 QualType RetType = 11676 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11677 11678 // Update the return type to the deduced type. 11679 const FunctionProtoType *Proto = 11680 FD->getType()->getAs<FunctionProtoType>(); 11681 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11682 Proto->getExtProtoInfo())); 11683 } 11684 } 11685 11686 // The only way to be included in UndefinedButUsed is if there is an 11687 // ODR use before the definition. Avoid the expensive map lookup if this 11688 // is the first declaration. 11689 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11690 if (!FD->isExternallyVisible()) 11691 UndefinedButUsed.erase(FD); 11692 else if (FD->isInlined() && 11693 !LangOpts.GNUInline && 11694 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11695 UndefinedButUsed.erase(FD); 11696 } 11697 11698 // If the function implicitly returns zero (like 'main') or is naked, 11699 // don't complain about missing return statements. 11700 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11701 WP.disableCheckFallThrough(); 11702 11703 // MSVC permits the use of pure specifier (=0) on function definition, 11704 // defined at class scope, warn about this non-standard construct. 11705 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11706 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11707 11708 if (!FD->isInvalidDecl()) { 11709 // Don't diagnose unused parameters of defaulted or deleted functions. 11710 if (!FD->isDeleted() && !FD->isDefaulted()) 11711 DiagnoseUnusedParameters(FD->parameters()); 11712 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 11713 FD->getReturnType(), FD); 11714 11715 // If this is a structor, we need a vtable. 11716 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11717 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11718 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11719 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11720 11721 // Try to apply the named return value optimization. We have to check 11722 // if we can do this here because lambdas keep return statements around 11723 // to deduce an implicit return type. 11724 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11725 !FD->isDependentContext()) 11726 computeNRVO(Body, getCurFunction()); 11727 } 11728 11729 // GNU warning -Wmissing-prototypes: 11730 // Warn if a global function is defined without a previous 11731 // prototype declaration. This warning is issued even if the 11732 // definition itself provides a prototype. The aim is to detect 11733 // global functions that fail to be declared in header files. 11734 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11735 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11736 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11737 11738 if (PossibleZeroParamPrototype) { 11739 // We found a declaration that is not a prototype, 11740 // but that could be a zero-parameter prototype 11741 if (TypeSourceInfo *TI = 11742 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11743 TypeLoc TL = TI->getTypeLoc(); 11744 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11745 Diag(PossibleZeroParamPrototype->getLocation(), 11746 diag::note_declaration_not_a_prototype) 11747 << PossibleZeroParamPrototype 11748 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11749 } 11750 } 11751 } 11752 11753 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11754 const CXXMethodDecl *KeyFunction; 11755 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11756 MD->isVirtual() && 11757 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11758 MD == KeyFunction->getCanonicalDecl()) { 11759 // Update the key-function state if necessary for this ABI. 11760 if (FD->isInlined() && 11761 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11762 Context.setNonKeyFunction(MD); 11763 11764 // If the newly-chosen key function is already defined, then we 11765 // need to mark the vtable as used retroactively. 11766 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11767 const FunctionDecl *Definition; 11768 if (KeyFunction && KeyFunction->isDefined(Definition)) 11769 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11770 } else { 11771 // We just defined they key function; mark the vtable as used. 11772 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11773 } 11774 } 11775 } 11776 11777 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11778 "Function parsing confused"); 11779 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11780 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11781 MD->setBody(Body); 11782 if (!MD->isInvalidDecl()) { 11783 DiagnoseUnusedParameters(MD->parameters()); 11784 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 11785 MD->getReturnType(), MD); 11786 11787 if (Body) 11788 computeNRVO(Body, getCurFunction()); 11789 } 11790 if (getCurFunction()->ObjCShouldCallSuper) { 11791 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11792 << MD->getSelector().getAsString(); 11793 getCurFunction()->ObjCShouldCallSuper = false; 11794 } 11795 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11796 const ObjCMethodDecl *InitMethod = nullptr; 11797 bool isDesignated = 11798 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11799 assert(isDesignated && InitMethod); 11800 (void)isDesignated; 11801 11802 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11803 auto IFace = MD->getClassInterface(); 11804 if (!IFace) 11805 return false; 11806 auto SuperD = IFace->getSuperClass(); 11807 if (!SuperD) 11808 return false; 11809 return SuperD->getIdentifier() == 11810 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11811 }; 11812 // Don't issue this warning for unavailable inits or direct subclasses 11813 // of NSObject. 11814 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11815 Diag(MD->getLocation(), 11816 diag::warn_objc_designated_init_missing_super_call); 11817 Diag(InitMethod->getLocation(), 11818 diag::note_objc_designated_init_marked_here); 11819 } 11820 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11821 } 11822 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11823 // Don't issue this warning for unavaialable inits. 11824 if (!MD->isUnavailable()) 11825 Diag(MD->getLocation(), 11826 diag::warn_objc_secondary_init_missing_init_call); 11827 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11828 } 11829 } else { 11830 return nullptr; 11831 } 11832 11833 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 11834 DiagnoseUnguardedAvailabilityViolations(dcl); 11835 11836 assert(!getCurFunction()->ObjCShouldCallSuper && 11837 "This should only be set for ObjC methods, which should have been " 11838 "handled in the block above."); 11839 11840 // Verify and clean out per-function state. 11841 if (Body && (!FD || !FD->isDefaulted())) { 11842 // C++ constructors that have function-try-blocks can't have return 11843 // statements in the handlers of that block. (C++ [except.handle]p14) 11844 // Verify this. 11845 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11846 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11847 11848 // Verify that gotos and switch cases don't jump into scopes illegally. 11849 if (getCurFunction()->NeedsScopeChecking() && 11850 !PP.isCodeCompletionEnabled()) 11851 DiagnoseInvalidJumps(Body); 11852 11853 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11854 if (!Destructor->getParent()->isDependentType()) 11855 CheckDestructor(Destructor); 11856 11857 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11858 Destructor->getParent()); 11859 } 11860 11861 // If any errors have occurred, clear out any temporaries that may have 11862 // been leftover. This ensures that these temporaries won't be picked up for 11863 // deletion in some later function. 11864 if (getDiagnostics().hasErrorOccurred() || 11865 getDiagnostics().getSuppressAllDiagnostics()) { 11866 DiscardCleanupsInEvaluationContext(); 11867 } 11868 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11869 !isa<FunctionTemplateDecl>(dcl)) { 11870 // Since the body is valid, issue any analysis-based warnings that are 11871 // enabled. 11872 ActivePolicy = &WP; 11873 } 11874 11875 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11876 (!CheckConstexprFunctionDecl(FD) || 11877 !CheckConstexprFunctionBody(FD, Body))) 11878 FD->setInvalidDecl(); 11879 11880 if (FD && FD->hasAttr<NakedAttr>()) { 11881 for (const Stmt *S : Body->children()) { 11882 // Allow local register variables without initializer as they don't 11883 // require prologue. 11884 bool RegisterVariables = false; 11885 if (auto *DS = dyn_cast<DeclStmt>(S)) { 11886 for (const auto *Decl : DS->decls()) { 11887 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 11888 RegisterVariables = 11889 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 11890 if (!RegisterVariables) 11891 break; 11892 } 11893 } 11894 } 11895 if (RegisterVariables) 11896 continue; 11897 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11898 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11899 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11900 FD->setInvalidDecl(); 11901 break; 11902 } 11903 } 11904 } 11905 11906 assert(ExprCleanupObjects.size() == 11907 ExprEvalContexts.back().NumCleanupObjects && 11908 "Leftover temporaries in function"); 11909 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 11910 assert(MaybeODRUseExprs.empty() && 11911 "Leftover expressions for odr-use checking"); 11912 } 11913 11914 if (!IsInstantiation) 11915 PopDeclContext(); 11916 11917 PopFunctionScopeInfo(ActivePolicy, dcl); 11918 // If any errors have occurred, clear out any temporaries that may have 11919 // been leftover. This ensures that these temporaries won't be picked up for 11920 // deletion in some later function. 11921 if (getDiagnostics().hasErrorOccurred()) { 11922 DiscardCleanupsInEvaluationContext(); 11923 } 11924 11925 return dcl; 11926 } 11927 11928 /// When we finish delayed parsing of an attribute, we must attach it to the 11929 /// relevant Decl. 11930 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11931 ParsedAttributes &Attrs) { 11932 // Always attach attributes to the underlying decl. 11933 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11934 D = TD->getTemplatedDecl(); 11935 ProcessDeclAttributeList(S, D, Attrs.getList()); 11936 11937 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11938 if (Method->isStatic()) 11939 checkThisInStaticMemberFunctionAttributes(Method); 11940 } 11941 11942 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11943 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11944 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11945 IdentifierInfo &II, Scope *S) { 11946 // Before we produce a declaration for an implicitly defined 11947 // function, see whether there was a locally-scoped declaration of 11948 // this name as a function or variable. If so, use that 11949 // (non-visible) declaration, and complain about it. 11950 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11951 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11952 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11953 return ExternCPrev; 11954 } 11955 11956 // Extension in C99. Legal in C90, but warn about it. 11957 unsigned diag_id; 11958 if (II.getName().startswith("__builtin_")) 11959 diag_id = diag::warn_builtin_unknown; 11960 else if (getLangOpts().C99) 11961 diag_id = diag::ext_implicit_function_decl; 11962 else 11963 diag_id = diag::warn_implicit_function_decl; 11964 Diag(Loc, diag_id) << &II; 11965 11966 // Because typo correction is expensive, only do it if the implicit 11967 // function declaration is going to be treated as an error. 11968 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11969 TypoCorrection Corrected; 11970 if (S && 11971 (Corrected = CorrectTypo( 11972 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11973 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11974 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11975 /*ErrorRecovery*/false); 11976 } 11977 11978 // Set a Declarator for the implicit definition: int foo(); 11979 const char *Dummy; 11980 AttributeFactory attrFactory; 11981 DeclSpec DS(attrFactory); 11982 unsigned DiagID; 11983 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11984 Context.getPrintingPolicy()); 11985 (void)Error; // Silence warning. 11986 assert(!Error && "Error setting up implicit decl!"); 11987 SourceLocation NoLoc; 11988 Declarator D(DS, Declarator::BlockContext); 11989 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11990 /*IsAmbiguous=*/false, 11991 /*LParenLoc=*/NoLoc, 11992 /*Params=*/nullptr, 11993 /*NumParams=*/0, 11994 /*EllipsisLoc=*/NoLoc, 11995 /*RParenLoc=*/NoLoc, 11996 /*TypeQuals=*/0, 11997 /*RefQualifierIsLvalueRef=*/true, 11998 /*RefQualifierLoc=*/NoLoc, 11999 /*ConstQualifierLoc=*/NoLoc, 12000 /*VolatileQualifierLoc=*/NoLoc, 12001 /*RestrictQualifierLoc=*/NoLoc, 12002 /*MutableLoc=*/NoLoc, 12003 EST_None, 12004 /*ESpecRange=*/SourceRange(), 12005 /*Exceptions=*/nullptr, 12006 /*ExceptionRanges=*/nullptr, 12007 /*NumExceptions=*/0, 12008 /*NoexceptExpr=*/nullptr, 12009 /*ExceptionSpecTokens=*/nullptr, 12010 Loc, Loc, D), 12011 DS.getAttributes(), 12012 SourceLocation()); 12013 D.SetIdentifier(&II, Loc); 12014 12015 // Insert this function into translation-unit scope. 12016 12017 DeclContext *PrevDC = CurContext; 12018 CurContext = Context.getTranslationUnitDecl(); 12019 12020 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12021 FD->setImplicit(); 12022 12023 CurContext = PrevDC; 12024 12025 AddKnownFunctionAttributes(FD); 12026 12027 return FD; 12028 } 12029 12030 /// \brief Adds any function attributes that we know a priori based on 12031 /// the declaration of this function. 12032 /// 12033 /// These attributes can apply both to implicitly-declared builtins 12034 /// (like __builtin___printf_chk) or to library-declared functions 12035 /// like NSLog or printf. 12036 /// 12037 /// We need to check for duplicate attributes both here and where user-written 12038 /// attributes are applied to declarations. 12039 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12040 if (FD->isInvalidDecl()) 12041 return; 12042 12043 // If this is a built-in function, map its builtin attributes to 12044 // actual attributes. 12045 if (unsigned BuiltinID = FD->getBuiltinID()) { 12046 // Handle printf-formatting attributes. 12047 unsigned FormatIdx; 12048 bool HasVAListArg; 12049 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12050 if (!FD->hasAttr<FormatAttr>()) { 12051 const char *fmt = "printf"; 12052 unsigned int NumParams = FD->getNumParams(); 12053 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12054 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12055 fmt = "NSString"; 12056 FD->addAttr(FormatAttr::CreateImplicit(Context, 12057 &Context.Idents.get(fmt), 12058 FormatIdx+1, 12059 HasVAListArg ? 0 : FormatIdx+2, 12060 FD->getLocation())); 12061 } 12062 } 12063 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12064 HasVAListArg)) { 12065 if (!FD->hasAttr<FormatAttr>()) 12066 FD->addAttr(FormatAttr::CreateImplicit(Context, 12067 &Context.Idents.get("scanf"), 12068 FormatIdx+1, 12069 HasVAListArg ? 0 : FormatIdx+2, 12070 FD->getLocation())); 12071 } 12072 12073 // Mark const if we don't care about errno and that is the only 12074 // thing preventing the function from being const. This allows 12075 // IRgen to use LLVM intrinsics for such functions. 12076 if (!getLangOpts().MathErrno && 12077 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12078 if (!FD->hasAttr<ConstAttr>()) 12079 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12080 } 12081 12082 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12083 !FD->hasAttr<ReturnsTwiceAttr>()) 12084 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12085 FD->getLocation())); 12086 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12087 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12088 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12089 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12090 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12091 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12092 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12093 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12094 // Add the appropriate attribute, depending on the CUDA compilation mode 12095 // and which target the builtin belongs to. For example, during host 12096 // compilation, aux builtins are __device__, while the rest are __host__. 12097 if (getLangOpts().CUDAIsDevice != 12098 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12099 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12100 else 12101 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12102 } 12103 } 12104 12105 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12106 // throw, add an implicit nothrow attribute to any extern "C" function we come 12107 // across. 12108 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12109 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12110 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12111 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12112 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12113 } 12114 12115 IdentifierInfo *Name = FD->getIdentifier(); 12116 if (!Name) 12117 return; 12118 if ((!getLangOpts().CPlusPlus && 12119 FD->getDeclContext()->isTranslationUnit()) || 12120 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12121 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12122 LinkageSpecDecl::lang_c)) { 12123 // Okay: this could be a libc/libm/Objective-C function we know 12124 // about. 12125 } else 12126 return; 12127 12128 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12129 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12130 // target-specific builtins, perhaps? 12131 if (!FD->hasAttr<FormatAttr>()) 12132 FD->addAttr(FormatAttr::CreateImplicit(Context, 12133 &Context.Idents.get("printf"), 2, 12134 Name->isStr("vasprintf") ? 0 : 3, 12135 FD->getLocation())); 12136 } 12137 12138 if (Name->isStr("__CFStringMakeConstantString")) { 12139 // We already have a __builtin___CFStringMakeConstantString, 12140 // but builds that use -fno-constant-cfstrings don't go through that. 12141 if (!FD->hasAttr<FormatArgAttr>()) 12142 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12143 FD->getLocation())); 12144 } 12145 } 12146 12147 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12148 TypeSourceInfo *TInfo) { 12149 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12150 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12151 12152 if (!TInfo) { 12153 assert(D.isInvalidType() && "no declarator info for valid type"); 12154 TInfo = Context.getTrivialTypeSourceInfo(T); 12155 } 12156 12157 // Scope manipulation handled by caller. 12158 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12159 D.getLocStart(), 12160 D.getIdentifierLoc(), 12161 D.getIdentifier(), 12162 TInfo); 12163 12164 // Bail out immediately if we have an invalid declaration. 12165 if (D.isInvalidType()) { 12166 NewTD->setInvalidDecl(); 12167 return NewTD; 12168 } 12169 12170 if (D.getDeclSpec().isModulePrivateSpecified()) { 12171 if (CurContext->isFunctionOrMethod()) 12172 Diag(NewTD->getLocation(), diag::err_module_private_local) 12173 << 2 << NewTD->getDeclName() 12174 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12175 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12176 else 12177 NewTD->setModulePrivate(); 12178 } 12179 12180 // C++ [dcl.typedef]p8: 12181 // If the typedef declaration defines an unnamed class (or 12182 // enum), the first typedef-name declared by the declaration 12183 // to be that class type (or enum type) is used to denote the 12184 // class type (or enum type) for linkage purposes only. 12185 // We need to check whether the type was declared in the declaration. 12186 switch (D.getDeclSpec().getTypeSpecType()) { 12187 case TST_enum: 12188 case TST_struct: 12189 case TST_interface: 12190 case TST_union: 12191 case TST_class: { 12192 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12193 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12194 break; 12195 } 12196 12197 default: 12198 break; 12199 } 12200 12201 return NewTD; 12202 } 12203 12204 /// \brief Check that this is a valid underlying type for an enum declaration. 12205 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12206 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12207 QualType T = TI->getType(); 12208 12209 if (T->isDependentType()) 12210 return false; 12211 12212 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12213 if (BT->isInteger()) 12214 return false; 12215 12216 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12217 return true; 12218 } 12219 12220 /// Check whether this is a valid redeclaration of a previous enumeration. 12221 /// \return true if the redeclaration was invalid. 12222 bool Sema::CheckEnumRedeclaration( 12223 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12224 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12225 bool IsFixed = !EnumUnderlyingTy.isNull(); 12226 12227 if (IsScoped != Prev->isScoped()) { 12228 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12229 << Prev->isScoped(); 12230 Diag(Prev->getLocation(), diag::note_previous_declaration); 12231 return true; 12232 } 12233 12234 if (IsFixed && Prev->isFixed()) { 12235 if (!EnumUnderlyingTy->isDependentType() && 12236 !Prev->getIntegerType()->isDependentType() && 12237 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12238 Prev->getIntegerType())) { 12239 // TODO: Highlight the underlying type of the redeclaration. 12240 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12241 << EnumUnderlyingTy << Prev->getIntegerType(); 12242 Diag(Prev->getLocation(), diag::note_previous_declaration) 12243 << Prev->getIntegerTypeRange(); 12244 return true; 12245 } 12246 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12247 ; 12248 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12249 ; 12250 } else if (IsFixed != Prev->isFixed()) { 12251 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12252 << Prev->isFixed(); 12253 Diag(Prev->getLocation(), diag::note_previous_declaration); 12254 return true; 12255 } 12256 12257 return false; 12258 } 12259 12260 /// \brief Get diagnostic %select index for tag kind for 12261 /// redeclaration diagnostic message. 12262 /// WARNING: Indexes apply to particular diagnostics only! 12263 /// 12264 /// \returns diagnostic %select index. 12265 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12266 switch (Tag) { 12267 case TTK_Struct: return 0; 12268 case TTK_Interface: return 1; 12269 case TTK_Class: return 2; 12270 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12271 } 12272 } 12273 12274 /// \brief Determine if tag kind is a class-key compatible with 12275 /// class for redeclaration (class, struct, or __interface). 12276 /// 12277 /// \returns true iff the tag kind is compatible. 12278 static bool isClassCompatTagKind(TagTypeKind Tag) 12279 { 12280 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12281 } 12282 12283 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) { 12284 if (isa<TypedefDecl>(PrevDecl)) 12285 return NTK_Typedef; 12286 else if (isa<TypeAliasDecl>(PrevDecl)) 12287 return NTK_TypeAlias; 12288 else if (isa<ClassTemplateDecl>(PrevDecl)) 12289 return NTK_Template; 12290 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12291 return NTK_TypeAliasTemplate; 12292 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12293 return NTK_TemplateTemplateArgument; 12294 return NTK_Unknown; 12295 } 12296 12297 /// \brief Determine whether a tag with a given kind is acceptable 12298 /// as a redeclaration of the given tag declaration. 12299 /// 12300 /// \returns true if the new tag kind is acceptable, false otherwise. 12301 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12302 TagTypeKind NewTag, bool isDefinition, 12303 SourceLocation NewTagLoc, 12304 const IdentifierInfo *Name) { 12305 // C++ [dcl.type.elab]p3: 12306 // The class-key or enum keyword present in the 12307 // elaborated-type-specifier shall agree in kind with the 12308 // declaration to which the name in the elaborated-type-specifier 12309 // refers. This rule also applies to the form of 12310 // elaborated-type-specifier that declares a class-name or 12311 // friend class since it can be construed as referring to the 12312 // definition of the class. Thus, in any 12313 // elaborated-type-specifier, the enum keyword shall be used to 12314 // refer to an enumeration (7.2), the union class-key shall be 12315 // used to refer to a union (clause 9), and either the class or 12316 // struct class-key shall be used to refer to a class (clause 9) 12317 // declared using the class or struct class-key. 12318 TagTypeKind OldTag = Previous->getTagKind(); 12319 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12320 if (OldTag == NewTag) 12321 return true; 12322 12323 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12324 // Warn about the struct/class tag mismatch. 12325 bool isTemplate = false; 12326 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12327 isTemplate = Record->getDescribedClassTemplate(); 12328 12329 if (!ActiveTemplateInstantiations.empty()) { 12330 // In a template instantiation, do not offer fix-its for tag mismatches 12331 // since they usually mess up the template instead of fixing the problem. 12332 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12333 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12334 << getRedeclDiagFromTagKind(OldTag); 12335 return true; 12336 } 12337 12338 if (isDefinition) { 12339 // On definitions, check previous tags and issue a fix-it for each 12340 // one that doesn't match the current tag. 12341 if (Previous->getDefinition()) { 12342 // Don't suggest fix-its for redefinitions. 12343 return true; 12344 } 12345 12346 bool previousMismatch = false; 12347 for (auto I : Previous->redecls()) { 12348 if (I->getTagKind() != NewTag) { 12349 if (!previousMismatch) { 12350 previousMismatch = true; 12351 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12352 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12353 << getRedeclDiagFromTagKind(I->getTagKind()); 12354 } 12355 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12356 << getRedeclDiagFromTagKind(NewTag) 12357 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12358 TypeWithKeyword::getTagTypeKindName(NewTag)); 12359 } 12360 } 12361 return true; 12362 } 12363 12364 // Check for a previous definition. If current tag and definition 12365 // are same type, do nothing. If no definition, but disagree with 12366 // with previous tag type, give a warning, but no fix-it. 12367 const TagDecl *Redecl = Previous->getDefinition() ? 12368 Previous->getDefinition() : Previous; 12369 if (Redecl->getTagKind() == NewTag) { 12370 return true; 12371 } 12372 12373 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12374 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12375 << getRedeclDiagFromTagKind(OldTag); 12376 Diag(Redecl->getLocation(), diag::note_previous_use); 12377 12378 // If there is a previous definition, suggest a fix-it. 12379 if (Previous->getDefinition()) { 12380 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12381 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12382 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12383 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12384 } 12385 12386 return true; 12387 } 12388 return false; 12389 } 12390 12391 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12392 /// from an outer enclosing namespace or file scope inside a friend declaration. 12393 /// This should provide the commented out code in the following snippet: 12394 /// namespace N { 12395 /// struct X; 12396 /// namespace M { 12397 /// struct Y { friend struct /*N::*/ X; }; 12398 /// } 12399 /// } 12400 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12401 SourceLocation NameLoc) { 12402 // While the decl is in a namespace, do repeated lookup of that name and see 12403 // if we get the same namespace back. If we do not, continue until 12404 // translation unit scope, at which point we have a fully qualified NNS. 12405 SmallVector<IdentifierInfo *, 4> Namespaces; 12406 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12407 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12408 // This tag should be declared in a namespace, which can only be enclosed by 12409 // other namespaces. Bail if there's an anonymous namespace in the chain. 12410 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12411 if (!Namespace || Namespace->isAnonymousNamespace()) 12412 return FixItHint(); 12413 IdentifierInfo *II = Namespace->getIdentifier(); 12414 Namespaces.push_back(II); 12415 NamedDecl *Lookup = SemaRef.LookupSingleName( 12416 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12417 if (Lookup == Namespace) 12418 break; 12419 } 12420 12421 // Once we have all the namespaces, reverse them to go outermost first, and 12422 // build an NNS. 12423 SmallString<64> Insertion; 12424 llvm::raw_svector_ostream OS(Insertion); 12425 if (DC->isTranslationUnit()) 12426 OS << "::"; 12427 std::reverse(Namespaces.begin(), Namespaces.end()); 12428 for (auto *II : Namespaces) 12429 OS << II->getName() << "::"; 12430 return FixItHint::CreateInsertion(NameLoc, Insertion); 12431 } 12432 12433 /// \brief Determine whether a tag originally declared in context \p OldDC can 12434 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12435 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12436 /// using-declaration). 12437 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12438 DeclContext *NewDC) { 12439 OldDC = OldDC->getRedeclContext(); 12440 NewDC = NewDC->getRedeclContext(); 12441 12442 if (OldDC->Equals(NewDC)) 12443 return true; 12444 12445 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12446 // encloses the other). 12447 if (S.getLangOpts().MSVCCompat && 12448 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 12449 return true; 12450 12451 return false; 12452 } 12453 12454 /// Find the DeclContext in which a tag is implicitly declared if we see an 12455 /// elaborated type specifier in the specified context, and lookup finds 12456 /// nothing. 12457 static DeclContext *getTagInjectionContext(DeclContext *DC) { 12458 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 12459 DC = DC->getParent(); 12460 return DC; 12461 } 12462 12463 /// Find the Scope in which a tag is implicitly declared if we see an 12464 /// elaborated type specifier in the specified context, and lookup finds 12465 /// nothing. 12466 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 12467 while (S->isClassScope() || 12468 (LangOpts.CPlusPlus && 12469 S->isFunctionPrototypeScope()) || 12470 ((S->getFlags() & Scope::DeclScope) == 0) || 12471 (S->getEntity() && S->getEntity()->isTransparentContext())) 12472 S = S->getParent(); 12473 return S; 12474 } 12475 12476 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 12477 /// former case, Name will be non-null. In the later case, Name will be null. 12478 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 12479 /// reference/declaration/definition of a tag. 12480 /// 12481 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 12482 /// trailing-type-specifier) other than one in an alias-declaration. 12483 /// 12484 /// \param SkipBody If non-null, will be set to indicate if the caller should 12485 /// skip the definition of this tag and treat it as if it were a declaration. 12486 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12487 SourceLocation KWLoc, CXXScopeSpec &SS, 12488 IdentifierInfo *Name, SourceLocation NameLoc, 12489 AttributeList *Attr, AccessSpecifier AS, 12490 SourceLocation ModulePrivateLoc, 12491 MultiTemplateParamsArg TemplateParameterLists, 12492 bool &OwnedDecl, bool &IsDependent, 12493 SourceLocation ScopedEnumKWLoc, 12494 bool ScopedEnumUsesClassTag, 12495 TypeResult UnderlyingType, 12496 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 12497 // If this is not a definition, it must have a name. 12498 IdentifierInfo *OrigName = Name; 12499 assert((Name != nullptr || TUK == TUK_Definition) && 12500 "Nameless record must be a definition!"); 12501 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 12502 12503 OwnedDecl = false; 12504 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12505 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 12506 12507 // FIXME: Check explicit specializations more carefully. 12508 bool isExplicitSpecialization = false; 12509 bool Invalid = false; 12510 12511 // We only need to do this matching if we have template parameters 12512 // or a scope specifier, which also conveniently avoids this work 12513 // for non-C++ cases. 12514 if (TemplateParameterLists.size() > 0 || 12515 (SS.isNotEmpty() && TUK != TUK_Reference)) { 12516 if (TemplateParameterList *TemplateParams = 12517 MatchTemplateParametersToScopeSpecifier( 12518 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 12519 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 12520 if (Kind == TTK_Enum) { 12521 Diag(KWLoc, diag::err_enum_template); 12522 return nullptr; 12523 } 12524 12525 if (TemplateParams->size() > 0) { 12526 // This is a declaration or definition of a class template (which may 12527 // be a member of another template). 12528 12529 if (Invalid) 12530 return nullptr; 12531 12532 OwnedDecl = false; 12533 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 12534 SS, Name, NameLoc, Attr, 12535 TemplateParams, AS, 12536 ModulePrivateLoc, 12537 /*FriendLoc*/SourceLocation(), 12538 TemplateParameterLists.size()-1, 12539 TemplateParameterLists.data(), 12540 SkipBody); 12541 return Result.get(); 12542 } else { 12543 // The "template<>" header is extraneous. 12544 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12545 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12546 isExplicitSpecialization = true; 12547 } 12548 } 12549 } 12550 12551 // Figure out the underlying type if this a enum declaration. We need to do 12552 // this early, because it's needed to detect if this is an incompatible 12553 // redeclaration. 12554 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 12555 bool EnumUnderlyingIsImplicit = false; 12556 12557 if (Kind == TTK_Enum) { 12558 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 12559 // No underlying type explicitly specified, or we failed to parse the 12560 // type, default to int. 12561 EnumUnderlying = Context.IntTy.getTypePtr(); 12562 else if (UnderlyingType.get()) { 12563 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 12564 // integral type; any cv-qualification is ignored. 12565 TypeSourceInfo *TI = nullptr; 12566 GetTypeFromParser(UnderlyingType.get(), &TI); 12567 EnumUnderlying = TI; 12568 12569 if (CheckEnumUnderlyingType(TI)) 12570 // Recover by falling back to int. 12571 EnumUnderlying = Context.IntTy.getTypePtr(); 12572 12573 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 12574 UPPC_FixedUnderlyingType)) 12575 EnumUnderlying = Context.IntTy.getTypePtr(); 12576 12577 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12578 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 12579 // Microsoft enums are always of int type. 12580 EnumUnderlying = Context.IntTy.getTypePtr(); 12581 EnumUnderlyingIsImplicit = true; 12582 } 12583 } 12584 } 12585 12586 DeclContext *SearchDC = CurContext; 12587 DeclContext *DC = CurContext; 12588 bool isStdBadAlloc = false; 12589 bool isStdAlignValT = false; 12590 12591 RedeclarationKind Redecl = ForRedeclaration; 12592 if (TUK == TUK_Friend || TUK == TUK_Reference) 12593 Redecl = NotForRedeclaration; 12594 12595 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 12596 if (Name && SS.isNotEmpty()) { 12597 // We have a nested-name tag ('struct foo::bar'). 12598 12599 // Check for invalid 'foo::'. 12600 if (SS.isInvalid()) { 12601 Name = nullptr; 12602 goto CreateNewDecl; 12603 } 12604 12605 // If this is a friend or a reference to a class in a dependent 12606 // context, don't try to make a decl for it. 12607 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12608 DC = computeDeclContext(SS, false); 12609 if (!DC) { 12610 IsDependent = true; 12611 return nullptr; 12612 } 12613 } else { 12614 DC = computeDeclContext(SS, true); 12615 if (!DC) { 12616 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 12617 << SS.getRange(); 12618 return nullptr; 12619 } 12620 } 12621 12622 if (RequireCompleteDeclContext(SS, DC)) 12623 return nullptr; 12624 12625 SearchDC = DC; 12626 // Look-up name inside 'foo::'. 12627 LookupQualifiedName(Previous, DC); 12628 12629 if (Previous.isAmbiguous()) 12630 return nullptr; 12631 12632 if (Previous.empty()) { 12633 // Name lookup did not find anything. However, if the 12634 // nested-name-specifier refers to the current instantiation, 12635 // and that current instantiation has any dependent base 12636 // classes, we might find something at instantiation time: treat 12637 // this as a dependent elaborated-type-specifier. 12638 // But this only makes any sense for reference-like lookups. 12639 if (Previous.wasNotFoundInCurrentInstantiation() && 12640 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12641 IsDependent = true; 12642 return nullptr; 12643 } 12644 12645 // A tag 'foo::bar' must already exist. 12646 Diag(NameLoc, diag::err_not_tag_in_scope) 12647 << Kind << Name << DC << SS.getRange(); 12648 Name = nullptr; 12649 Invalid = true; 12650 goto CreateNewDecl; 12651 } 12652 } else if (Name) { 12653 // C++14 [class.mem]p14: 12654 // If T is the name of a class, then each of the following shall have a 12655 // name different from T: 12656 // -- every member of class T that is itself a type 12657 if (TUK != TUK_Reference && TUK != TUK_Friend && 12658 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 12659 return nullptr; 12660 12661 // If this is a named struct, check to see if there was a previous forward 12662 // declaration or definition. 12663 // FIXME: We're looking into outer scopes here, even when we 12664 // shouldn't be. Doing so can result in ambiguities that we 12665 // shouldn't be diagnosing. 12666 LookupName(Previous, S); 12667 12668 // When declaring or defining a tag, ignore ambiguities introduced 12669 // by types using'ed into this scope. 12670 if (Previous.isAmbiguous() && 12671 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 12672 LookupResult::Filter F = Previous.makeFilter(); 12673 while (F.hasNext()) { 12674 NamedDecl *ND = F.next(); 12675 if (!ND->getDeclContext()->getRedeclContext()->Equals( 12676 SearchDC->getRedeclContext())) 12677 F.erase(); 12678 } 12679 F.done(); 12680 } 12681 12682 // C++11 [namespace.memdef]p3: 12683 // If the name in a friend declaration is neither qualified nor 12684 // a template-id and the declaration is a function or an 12685 // elaborated-type-specifier, the lookup to determine whether 12686 // the entity has been previously declared shall not consider 12687 // any scopes outside the innermost enclosing namespace. 12688 // 12689 // MSVC doesn't implement the above rule for types, so a friend tag 12690 // declaration may be a redeclaration of a type declared in an enclosing 12691 // scope. They do implement this rule for friend functions. 12692 // 12693 // Does it matter that this should be by scope instead of by 12694 // semantic context? 12695 if (!Previous.empty() && TUK == TUK_Friend) { 12696 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 12697 LookupResult::Filter F = Previous.makeFilter(); 12698 bool FriendSawTagOutsideEnclosingNamespace = false; 12699 while (F.hasNext()) { 12700 NamedDecl *ND = F.next(); 12701 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12702 if (DC->isFileContext() && 12703 !EnclosingNS->Encloses(ND->getDeclContext())) { 12704 if (getLangOpts().MSVCCompat) 12705 FriendSawTagOutsideEnclosingNamespace = true; 12706 else 12707 F.erase(); 12708 } 12709 } 12710 F.done(); 12711 12712 // Diagnose this MSVC extension in the easy case where lookup would have 12713 // unambiguously found something outside the enclosing namespace. 12714 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 12715 NamedDecl *ND = Previous.getFoundDecl(); 12716 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 12717 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 12718 } 12719 } 12720 12721 // Note: there used to be some attempt at recovery here. 12722 if (Previous.isAmbiguous()) 12723 return nullptr; 12724 12725 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 12726 // FIXME: This makes sure that we ignore the contexts associated 12727 // with C structs, unions, and enums when looking for a matching 12728 // tag declaration or definition. See the similar lookup tweak 12729 // in Sema::LookupName; is there a better way to deal with this? 12730 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12731 SearchDC = SearchDC->getParent(); 12732 } 12733 } 12734 12735 if (Previous.isSingleResult() && 12736 Previous.getFoundDecl()->isTemplateParameter()) { 12737 // Maybe we will complain about the shadowed template parameter. 12738 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12739 // Just pretend that we didn't see the previous declaration. 12740 Previous.clear(); 12741 } 12742 12743 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12744 DC->Equals(getStdNamespace())) { 12745 if (Name->isStr("bad_alloc")) { 12746 // This is a declaration of or a reference to "std::bad_alloc". 12747 isStdBadAlloc = true; 12748 12749 // If std::bad_alloc has been implicitly declared (but made invisible to 12750 // name lookup), fill in this implicit declaration as the previous 12751 // declaration, so that the declarations get chained appropriately. 12752 if (Previous.empty() && StdBadAlloc) 12753 Previous.addDecl(getStdBadAlloc()); 12754 } else if (Name->isStr("align_val_t")) { 12755 isStdAlignValT = true; 12756 if (Previous.empty() && StdAlignValT) 12757 Previous.addDecl(getStdAlignValT()); 12758 } 12759 } 12760 12761 // If we didn't find a previous declaration, and this is a reference 12762 // (or friend reference), move to the correct scope. In C++, we 12763 // also need to do a redeclaration lookup there, just in case 12764 // there's a shadow friend decl. 12765 if (Name && Previous.empty() && 12766 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12767 if (Invalid) goto CreateNewDecl; 12768 assert(SS.isEmpty()); 12769 12770 if (TUK == TUK_Reference) { 12771 // C++ [basic.scope.pdecl]p5: 12772 // -- for an elaborated-type-specifier of the form 12773 // 12774 // class-key identifier 12775 // 12776 // if the elaborated-type-specifier is used in the 12777 // decl-specifier-seq or parameter-declaration-clause of a 12778 // function defined in namespace scope, the identifier is 12779 // declared as a class-name in the namespace that contains 12780 // the declaration; otherwise, except as a friend 12781 // declaration, the identifier is declared in the smallest 12782 // non-class, non-function-prototype scope that contains the 12783 // declaration. 12784 // 12785 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12786 // C structs and unions. 12787 // 12788 // It is an error in C++ to declare (rather than define) an enum 12789 // type, including via an elaborated type specifier. We'll 12790 // diagnose that later; for now, declare the enum in the same 12791 // scope as we would have picked for any other tag type. 12792 // 12793 // GNU C also supports this behavior as part of its incomplete 12794 // enum types extension, while GNU C++ does not. 12795 // 12796 // Find the context where we'll be declaring the tag. 12797 // FIXME: We would like to maintain the current DeclContext as the 12798 // lexical context, 12799 SearchDC = getTagInjectionContext(SearchDC); 12800 12801 // Find the scope where we'll be declaring the tag. 12802 S = getTagInjectionScope(S, getLangOpts()); 12803 } else { 12804 assert(TUK == TUK_Friend); 12805 // C++ [namespace.memdef]p3: 12806 // If a friend declaration in a non-local class first declares a 12807 // class or function, the friend class or function is a member of 12808 // the innermost enclosing namespace. 12809 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12810 } 12811 12812 // In C++, we need to do a redeclaration lookup to properly 12813 // diagnose some problems. 12814 // FIXME: redeclaration lookup is also used (with and without C++) to find a 12815 // hidden declaration so that we don't get ambiguity errors when using a 12816 // type declared by an elaborated-type-specifier. In C that is not correct 12817 // and we should instead merge compatible types found by lookup. 12818 if (getLangOpts().CPlusPlus) { 12819 Previous.setRedeclarationKind(ForRedeclaration); 12820 LookupQualifiedName(Previous, SearchDC); 12821 } else { 12822 Previous.setRedeclarationKind(ForRedeclaration); 12823 LookupName(Previous, S); 12824 } 12825 } 12826 12827 // If we have a known previous declaration to use, then use it. 12828 if (Previous.empty() && SkipBody && SkipBody->Previous) 12829 Previous.addDecl(SkipBody->Previous); 12830 12831 if (!Previous.empty()) { 12832 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12833 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12834 12835 // It's okay to have a tag decl in the same scope as a typedef 12836 // which hides a tag decl in the same scope. Finding this 12837 // insanity with a redeclaration lookup can only actually happen 12838 // in C++. 12839 // 12840 // This is also okay for elaborated-type-specifiers, which is 12841 // technically forbidden by the current standard but which is 12842 // okay according to the likely resolution of an open issue; 12843 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12844 if (getLangOpts().CPlusPlus) { 12845 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12846 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12847 TagDecl *Tag = TT->getDecl(); 12848 if (Tag->getDeclName() == Name && 12849 Tag->getDeclContext()->getRedeclContext() 12850 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12851 PrevDecl = Tag; 12852 Previous.clear(); 12853 Previous.addDecl(Tag); 12854 Previous.resolveKind(); 12855 } 12856 } 12857 } 12858 } 12859 12860 // If this is a redeclaration of a using shadow declaration, it must 12861 // declare a tag in the same context. In MSVC mode, we allow a 12862 // redefinition if either context is within the other. 12863 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12864 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12865 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12866 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12867 !(OldTag && isAcceptableTagRedeclContext( 12868 *this, OldTag->getDeclContext(), SearchDC))) { 12869 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12870 Diag(Shadow->getTargetDecl()->getLocation(), 12871 diag::note_using_decl_target); 12872 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12873 << 0; 12874 // Recover by ignoring the old declaration. 12875 Previous.clear(); 12876 goto CreateNewDecl; 12877 } 12878 } 12879 12880 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12881 // If this is a use of a previous tag, or if the tag is already declared 12882 // in the same scope (so that the definition/declaration completes or 12883 // rementions the tag), reuse the decl. 12884 if (TUK == TUK_Reference || TUK == TUK_Friend || 12885 isDeclInScope(DirectPrevDecl, SearchDC, S, 12886 SS.isNotEmpty() || isExplicitSpecialization)) { 12887 // Make sure that this wasn't declared as an enum and now used as a 12888 // struct or something similar. 12889 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12890 TUK == TUK_Definition, KWLoc, 12891 Name)) { 12892 bool SafeToContinue 12893 = (PrevTagDecl->getTagKind() != TTK_Enum && 12894 Kind != TTK_Enum); 12895 if (SafeToContinue) 12896 Diag(KWLoc, diag::err_use_with_wrong_tag) 12897 << Name 12898 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12899 PrevTagDecl->getKindName()); 12900 else 12901 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12902 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12903 12904 if (SafeToContinue) 12905 Kind = PrevTagDecl->getTagKind(); 12906 else { 12907 // Recover by making this an anonymous redefinition. 12908 Name = nullptr; 12909 Previous.clear(); 12910 Invalid = true; 12911 } 12912 } 12913 12914 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12915 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12916 12917 // If this is an elaborated-type-specifier for a scoped enumeration, 12918 // the 'class' keyword is not necessary and not permitted. 12919 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12920 if (ScopedEnum) 12921 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12922 << PrevEnum->isScoped() 12923 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12924 return PrevTagDecl; 12925 } 12926 12927 QualType EnumUnderlyingTy; 12928 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12929 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12930 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12931 EnumUnderlyingTy = QualType(T, 0); 12932 12933 // All conflicts with previous declarations are recovered by 12934 // returning the previous declaration, unless this is a definition, 12935 // in which case we want the caller to bail out. 12936 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12937 ScopedEnum, EnumUnderlyingTy, 12938 EnumUnderlyingIsImplicit, PrevEnum)) 12939 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12940 } 12941 12942 // C++11 [class.mem]p1: 12943 // A member shall not be declared twice in the member-specification, 12944 // except that a nested class or member class template can be declared 12945 // and then later defined. 12946 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12947 S->isDeclScope(PrevDecl)) { 12948 Diag(NameLoc, diag::ext_member_redeclared); 12949 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12950 } 12951 12952 if (!Invalid) { 12953 // If this is a use, just return the declaration we found, unless 12954 // we have attributes. 12955 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12956 if (Attr) { 12957 // FIXME: Diagnose these attributes. For now, we create a new 12958 // declaration to hold them. 12959 } else if (TUK == TUK_Reference && 12960 (PrevTagDecl->getFriendObjectKind() == 12961 Decl::FOK_Undeclared || 12962 PP.getModuleContainingLocation( 12963 PrevDecl->getLocation()) != 12964 PP.getModuleContainingLocation(KWLoc)) && 12965 SS.isEmpty()) { 12966 // This declaration is a reference to an existing entity, but 12967 // has different visibility from that entity: it either makes 12968 // a friend visible or it makes a type visible in a new module. 12969 // In either case, create a new declaration. We only do this if 12970 // the declaration would have meant the same thing if no prior 12971 // declaration were found, that is, if it was found in the same 12972 // scope where we would have injected a declaration. 12973 if (!getTagInjectionContext(CurContext)->getRedeclContext() 12974 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 12975 return PrevTagDecl; 12976 // This is in the injected scope, create a new declaration in 12977 // that scope. 12978 S = getTagInjectionScope(S, getLangOpts()); 12979 } else { 12980 return PrevTagDecl; 12981 } 12982 } 12983 12984 // Diagnose attempts to redefine a tag. 12985 if (TUK == TUK_Definition) { 12986 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12987 // If we're defining a specialization and the previous definition 12988 // is from an implicit instantiation, don't emit an error 12989 // here; we'll catch this in the general case below. 12990 bool IsExplicitSpecializationAfterInstantiation = false; 12991 if (isExplicitSpecialization) { 12992 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12993 IsExplicitSpecializationAfterInstantiation = 12994 RD->getTemplateSpecializationKind() != 12995 TSK_ExplicitSpecialization; 12996 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12997 IsExplicitSpecializationAfterInstantiation = 12998 ED->getTemplateSpecializationKind() != 12999 TSK_ExplicitSpecialization; 13000 } 13001 13002 NamedDecl *Hidden = nullptr; 13003 if (SkipBody && getLangOpts().CPlusPlus && 13004 !hasVisibleDefinition(Def, &Hidden)) { 13005 // There is a definition of this tag, but it is not visible. We 13006 // explicitly make use of C++'s one definition rule here, and 13007 // assume that this definition is identical to the hidden one 13008 // we already have. Make the existing definition visible and 13009 // use it in place of this one. 13010 SkipBody->ShouldSkip = true; 13011 makeMergedDefinitionVisible(Hidden, KWLoc); 13012 return Def; 13013 } else if (!IsExplicitSpecializationAfterInstantiation) { 13014 // A redeclaration in function prototype scope in C isn't 13015 // visible elsewhere, so merely issue a warning. 13016 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13017 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13018 else 13019 Diag(NameLoc, diag::err_redefinition) << Name; 13020 Diag(Def->getLocation(), diag::note_previous_definition); 13021 // If this is a redefinition, recover by making this 13022 // struct be anonymous, which will make any later 13023 // references get the previous definition. 13024 Name = nullptr; 13025 Previous.clear(); 13026 Invalid = true; 13027 } 13028 } else { 13029 // If the type is currently being defined, complain 13030 // about a nested redefinition. 13031 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13032 if (TD->isBeingDefined()) { 13033 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13034 Diag(PrevTagDecl->getLocation(), 13035 diag::note_previous_definition); 13036 Name = nullptr; 13037 Previous.clear(); 13038 Invalid = true; 13039 } 13040 } 13041 13042 // Okay, this is definition of a previously declared or referenced 13043 // tag. We're going to create a new Decl for it. 13044 } 13045 13046 // Okay, we're going to make a redeclaration. If this is some kind 13047 // of reference, make sure we build the redeclaration in the same DC 13048 // as the original, and ignore the current access specifier. 13049 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13050 SearchDC = PrevTagDecl->getDeclContext(); 13051 AS = AS_none; 13052 } 13053 } 13054 // If we get here we have (another) forward declaration or we 13055 // have a definition. Just create a new decl. 13056 13057 } else { 13058 // If we get here, this is a definition of a new tag type in a nested 13059 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13060 // new decl/type. We set PrevDecl to NULL so that the entities 13061 // have distinct types. 13062 Previous.clear(); 13063 } 13064 // If we get here, we're going to create a new Decl. If PrevDecl 13065 // is non-NULL, it's a definition of the tag declared by 13066 // PrevDecl. If it's NULL, we have a new definition. 13067 13068 // Otherwise, PrevDecl is not a tag, but was found with tag 13069 // lookup. This is only actually possible in C++, where a few 13070 // things like templates still live in the tag namespace. 13071 } else { 13072 // Use a better diagnostic if an elaborated-type-specifier 13073 // found the wrong kind of type on the first 13074 // (non-redeclaration) lookup. 13075 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13076 !Previous.isForRedeclaration()) { 13077 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13078 Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK; 13079 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13080 Invalid = true; 13081 13082 // Otherwise, only diagnose if the declaration is in scope. 13083 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13084 SS.isNotEmpty() || isExplicitSpecialization)) { 13085 // do nothing 13086 13087 // Diagnose implicit declarations introduced by elaborated types. 13088 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13089 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl); 13090 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13091 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13092 Invalid = true; 13093 13094 // Otherwise it's a declaration. Call out a particularly common 13095 // case here. 13096 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13097 unsigned Kind = 0; 13098 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13099 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13100 << Name << Kind << TND->getUnderlyingType(); 13101 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13102 Invalid = true; 13103 13104 // Otherwise, diagnose. 13105 } else { 13106 // The tag name clashes with something else in the target scope, 13107 // issue an error and recover by making this tag be anonymous. 13108 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13109 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13110 Name = nullptr; 13111 Invalid = true; 13112 } 13113 13114 // The existing declaration isn't relevant to us; we're in a 13115 // new scope, so clear out the previous declaration. 13116 Previous.clear(); 13117 } 13118 } 13119 13120 CreateNewDecl: 13121 13122 TagDecl *PrevDecl = nullptr; 13123 if (Previous.isSingleResult()) 13124 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13125 13126 // If there is an identifier, use the location of the identifier as the 13127 // location of the decl, otherwise use the location of the struct/union 13128 // keyword. 13129 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13130 13131 // Otherwise, create a new declaration. If there is a previous 13132 // declaration of the same entity, the two will be linked via 13133 // PrevDecl. 13134 TagDecl *New; 13135 13136 bool IsForwardReference = false; 13137 if (Kind == TTK_Enum) { 13138 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13139 // enum X { A, B, C } D; D should chain to X. 13140 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13141 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13142 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13143 13144 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13145 StdAlignValT = cast<EnumDecl>(New); 13146 13147 // If this is an undefined enum, warn. 13148 if (TUK != TUK_Definition && !Invalid) { 13149 TagDecl *Def; 13150 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13151 cast<EnumDecl>(New)->isFixed()) { 13152 // C++0x: 7.2p2: opaque-enum-declaration. 13153 // Conflicts are diagnosed above. Do nothing. 13154 } 13155 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13156 Diag(Loc, diag::ext_forward_ref_enum_def) 13157 << New; 13158 Diag(Def->getLocation(), diag::note_previous_definition); 13159 } else { 13160 unsigned DiagID = diag::ext_forward_ref_enum; 13161 if (getLangOpts().MSVCCompat) 13162 DiagID = diag::ext_ms_forward_ref_enum; 13163 else if (getLangOpts().CPlusPlus) 13164 DiagID = diag::err_forward_ref_enum; 13165 Diag(Loc, DiagID); 13166 13167 // If this is a forward-declared reference to an enumeration, make a 13168 // note of it; we won't actually be introducing the declaration into 13169 // the declaration context. 13170 if (TUK == TUK_Reference) 13171 IsForwardReference = true; 13172 } 13173 } 13174 13175 if (EnumUnderlying) { 13176 EnumDecl *ED = cast<EnumDecl>(New); 13177 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13178 ED->setIntegerTypeSourceInfo(TI); 13179 else 13180 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13181 ED->setPromotionType(ED->getIntegerType()); 13182 } 13183 } else { 13184 // struct/union/class 13185 13186 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13187 // struct X { int A; } D; D should chain to X. 13188 if (getLangOpts().CPlusPlus) { 13189 // FIXME: Look for a way to use RecordDecl for simple structs. 13190 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13191 cast_or_null<CXXRecordDecl>(PrevDecl)); 13192 13193 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13194 StdBadAlloc = cast<CXXRecordDecl>(New); 13195 } else 13196 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13197 cast_or_null<RecordDecl>(PrevDecl)); 13198 } 13199 13200 // C++11 [dcl.type]p3: 13201 // A type-specifier-seq shall not define a class or enumeration [...]. 13202 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13203 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13204 << Context.getTagDeclType(New); 13205 Invalid = true; 13206 } 13207 13208 // Maybe add qualifier info. 13209 if (SS.isNotEmpty()) { 13210 if (SS.isSet()) { 13211 // If this is either a declaration or a definition, check the 13212 // nested-name-specifier against the current context. We don't do this 13213 // for explicit specializations, because they have similar checking 13214 // (with more specific diagnostics) in the call to 13215 // CheckMemberSpecialization, below. 13216 if (!isExplicitSpecialization && 13217 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13218 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13219 Invalid = true; 13220 13221 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13222 if (TemplateParameterLists.size() > 0) { 13223 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13224 } 13225 } 13226 else 13227 Invalid = true; 13228 } 13229 13230 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13231 // Add alignment attributes if necessary; these attributes are checked when 13232 // the ASTContext lays out the structure. 13233 // 13234 // It is important for implementing the correct semantics that this 13235 // happen here (in act on tag decl). The #pragma pack stack is 13236 // maintained as a result of parser callbacks which can occur at 13237 // many points during the parsing of a struct declaration (because 13238 // the #pragma tokens are effectively skipped over during the 13239 // parsing of the struct). 13240 if (TUK == TUK_Definition) { 13241 AddAlignmentAttributesForRecord(RD); 13242 AddMsStructLayoutForRecord(RD); 13243 } 13244 } 13245 13246 if (ModulePrivateLoc.isValid()) { 13247 if (isExplicitSpecialization) 13248 Diag(New->getLocation(), diag::err_module_private_specialization) 13249 << 2 13250 << FixItHint::CreateRemoval(ModulePrivateLoc); 13251 // __module_private__ does not apply to local classes. However, we only 13252 // diagnose this as an error when the declaration specifiers are 13253 // freestanding. Here, we just ignore the __module_private__. 13254 else if (!SearchDC->isFunctionOrMethod()) 13255 New->setModulePrivate(); 13256 } 13257 13258 // If this is a specialization of a member class (of a class template), 13259 // check the specialization. 13260 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 13261 Invalid = true; 13262 13263 // If we're declaring or defining a tag in function prototype scope in C, 13264 // note that this type can only be used within the function and add it to 13265 // the list of decls to inject into the function definition scope. 13266 if ((Name || Kind == TTK_Enum) && 13267 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13268 if (getLangOpts().CPlusPlus) { 13269 // C++ [dcl.fct]p6: 13270 // Types shall not be defined in return or parameter types. 13271 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13272 Diag(Loc, diag::err_type_defined_in_param_type) 13273 << Name; 13274 Invalid = true; 13275 } 13276 } else if (!PrevDecl) { 13277 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13278 } 13279 DeclsInPrototypeScope.push_back(New); 13280 } 13281 13282 if (Invalid) 13283 New->setInvalidDecl(); 13284 13285 if (Attr) 13286 ProcessDeclAttributeList(S, New, Attr); 13287 13288 // Set the lexical context. If the tag has a C++ scope specifier, the 13289 // lexical context will be different from the semantic context. 13290 New->setLexicalDeclContext(CurContext); 13291 13292 // Mark this as a friend decl if applicable. 13293 // In Microsoft mode, a friend declaration also acts as a forward 13294 // declaration so we always pass true to setObjectOfFriendDecl to make 13295 // the tag name visible. 13296 if (TUK == TUK_Friend) 13297 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13298 13299 // Set the access specifier. 13300 if (!Invalid && SearchDC->isRecord()) 13301 SetMemberAccessSpecifier(New, PrevDecl, AS); 13302 13303 if (TUK == TUK_Definition) 13304 New->startDefinition(); 13305 13306 // If this has an identifier, add it to the scope stack. 13307 if (TUK == TUK_Friend) { 13308 // We might be replacing an existing declaration in the lookup tables; 13309 // if so, borrow its access specifier. 13310 if (PrevDecl) 13311 New->setAccess(PrevDecl->getAccess()); 13312 13313 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13314 DC->makeDeclVisibleInContext(New); 13315 if (Name) // can be null along some error paths 13316 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13317 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13318 } else if (Name) { 13319 S = getNonFieldDeclScope(S); 13320 PushOnScopeChains(New, S, !IsForwardReference); 13321 if (IsForwardReference) 13322 SearchDC->makeDeclVisibleInContext(New); 13323 } else { 13324 CurContext->addDecl(New); 13325 } 13326 13327 // If this is the C FILE type, notify the AST context. 13328 if (IdentifierInfo *II = New->getIdentifier()) 13329 if (!New->isInvalidDecl() && 13330 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13331 II->isStr("FILE")) 13332 Context.setFILEDecl(New); 13333 13334 if (PrevDecl) 13335 mergeDeclAttributes(New, PrevDecl); 13336 13337 // If there's a #pragma GCC visibility in scope, set the visibility of this 13338 // record. 13339 AddPushedVisibilityAttribute(New); 13340 13341 OwnedDecl = true; 13342 // In C++, don't return an invalid declaration. We can't recover well from 13343 // the cases where we make the type anonymous. 13344 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 13345 } 13346 13347 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13348 AdjustDeclIfTemplate(TagD); 13349 TagDecl *Tag = cast<TagDecl>(TagD); 13350 13351 // Enter the tag context. 13352 PushDeclContext(S, Tag); 13353 13354 ActOnDocumentableDecl(TagD); 13355 13356 // If there's a #pragma GCC visibility in scope, set the visibility of this 13357 // record. 13358 AddPushedVisibilityAttribute(Tag); 13359 } 13360 13361 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13362 assert(isa<ObjCContainerDecl>(IDecl) && 13363 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13364 DeclContext *OCD = cast<DeclContext>(IDecl); 13365 assert(getContainingDC(OCD) == CurContext && 13366 "The next DeclContext should be lexically contained in the current one."); 13367 CurContext = OCD; 13368 return IDecl; 13369 } 13370 13371 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13372 SourceLocation FinalLoc, 13373 bool IsFinalSpelledSealed, 13374 SourceLocation LBraceLoc) { 13375 AdjustDeclIfTemplate(TagD); 13376 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13377 13378 FieldCollector->StartClass(); 13379 13380 if (!Record->getIdentifier()) 13381 return; 13382 13383 if (FinalLoc.isValid()) 13384 Record->addAttr(new (Context) 13385 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13386 13387 // C++ [class]p2: 13388 // [...] The class-name is also inserted into the scope of the 13389 // class itself; this is known as the injected-class-name. For 13390 // purposes of access checking, the injected-class-name is treated 13391 // as if it were a public member name. 13392 CXXRecordDecl *InjectedClassName 13393 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13394 Record->getLocStart(), Record->getLocation(), 13395 Record->getIdentifier(), 13396 /*PrevDecl=*/nullptr, 13397 /*DelayTypeCreation=*/true); 13398 Context.getTypeDeclType(InjectedClassName, Record); 13399 InjectedClassName->setImplicit(); 13400 InjectedClassName->setAccess(AS_public); 13401 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13402 InjectedClassName->setDescribedClassTemplate(Template); 13403 PushOnScopeChains(InjectedClassName, S); 13404 assert(InjectedClassName->isInjectedClassName() && 13405 "Broken injected-class-name"); 13406 } 13407 13408 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13409 SourceRange BraceRange) { 13410 AdjustDeclIfTemplate(TagD); 13411 TagDecl *Tag = cast<TagDecl>(TagD); 13412 Tag->setBraceRange(BraceRange); 13413 13414 // Make sure we "complete" the definition even it is invalid. 13415 if (Tag->isBeingDefined()) { 13416 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13417 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13418 RD->completeDefinition(); 13419 } 13420 13421 if (isa<CXXRecordDecl>(Tag)) 13422 FieldCollector->FinishClass(); 13423 13424 // Exit this scope of this tag's definition. 13425 PopDeclContext(); 13426 13427 if (getCurLexicalContext()->isObjCContainer() && 13428 Tag->getDeclContext()->isFileContext()) 13429 Tag->setTopLevelDeclInObjCContainer(); 13430 13431 // Notify the consumer that we've defined a tag. 13432 if (!Tag->isInvalidDecl()) 13433 Consumer.HandleTagDeclDefinition(Tag); 13434 } 13435 13436 void Sema::ActOnObjCContainerFinishDefinition() { 13437 // Exit this scope of this interface definition. 13438 PopDeclContext(); 13439 } 13440 13441 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13442 assert(DC == CurContext && "Mismatch of container contexts"); 13443 OriginalLexicalContext = DC; 13444 ActOnObjCContainerFinishDefinition(); 13445 } 13446 13447 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13448 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13449 OriginalLexicalContext = nullptr; 13450 } 13451 13452 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13453 AdjustDeclIfTemplate(TagD); 13454 TagDecl *Tag = cast<TagDecl>(TagD); 13455 Tag->setInvalidDecl(); 13456 13457 // Make sure we "complete" the definition even it is invalid. 13458 if (Tag->isBeingDefined()) { 13459 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13460 RD->completeDefinition(); 13461 } 13462 13463 // We're undoing ActOnTagStartDefinition here, not 13464 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 13465 // the FieldCollector. 13466 13467 PopDeclContext(); 13468 } 13469 13470 // Note that FieldName may be null for anonymous bitfields. 13471 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 13472 IdentifierInfo *FieldName, 13473 QualType FieldTy, bool IsMsStruct, 13474 Expr *BitWidth, bool *ZeroWidth) { 13475 // Default to true; that shouldn't confuse checks for emptiness 13476 if (ZeroWidth) 13477 *ZeroWidth = true; 13478 13479 // C99 6.7.2.1p4 - verify the field type. 13480 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 13481 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 13482 // Handle incomplete types with specific error. 13483 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 13484 return ExprError(); 13485 if (FieldName) 13486 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 13487 << FieldName << FieldTy << BitWidth->getSourceRange(); 13488 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 13489 << FieldTy << BitWidth->getSourceRange(); 13490 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 13491 UPPC_BitFieldWidth)) 13492 return ExprError(); 13493 13494 // If the bit-width is type- or value-dependent, don't try to check 13495 // it now. 13496 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 13497 return BitWidth; 13498 13499 llvm::APSInt Value; 13500 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 13501 if (ICE.isInvalid()) 13502 return ICE; 13503 BitWidth = ICE.get(); 13504 13505 if (Value != 0 && ZeroWidth) 13506 *ZeroWidth = false; 13507 13508 // Zero-width bitfield is ok for anonymous field. 13509 if (Value == 0 && FieldName) 13510 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 13511 13512 if (Value.isSigned() && Value.isNegative()) { 13513 if (FieldName) 13514 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 13515 << FieldName << Value.toString(10); 13516 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 13517 << Value.toString(10); 13518 } 13519 13520 if (!FieldTy->isDependentType()) { 13521 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 13522 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 13523 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 13524 13525 // Over-wide bitfields are an error in C or when using the MSVC bitfield 13526 // ABI. 13527 bool CStdConstraintViolation = 13528 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 13529 bool MSBitfieldViolation = 13530 Value.ugt(TypeStorageSize) && 13531 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 13532 if (CStdConstraintViolation || MSBitfieldViolation) { 13533 unsigned DiagWidth = 13534 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 13535 if (FieldName) 13536 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 13537 << FieldName << (unsigned)Value.getZExtValue() 13538 << !CStdConstraintViolation << DiagWidth; 13539 13540 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 13541 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 13542 << DiagWidth; 13543 } 13544 13545 // Warn on types where the user might conceivably expect to get all 13546 // specified bits as value bits: that's all integral types other than 13547 // 'bool'. 13548 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 13549 if (FieldName) 13550 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 13551 << FieldName << (unsigned)Value.getZExtValue() 13552 << (unsigned)TypeWidth; 13553 else 13554 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 13555 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 13556 } 13557 } 13558 13559 return BitWidth; 13560 } 13561 13562 /// ActOnField - Each field of a C struct/union is passed into this in order 13563 /// to create a FieldDecl object for it. 13564 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 13565 Declarator &D, Expr *BitfieldWidth) { 13566 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 13567 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 13568 /*InitStyle=*/ICIS_NoInit, AS_public); 13569 return Res; 13570 } 13571 13572 /// HandleField - Analyze a field of a C struct or a C++ data member. 13573 /// 13574 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 13575 SourceLocation DeclStart, 13576 Declarator &D, Expr *BitWidth, 13577 InClassInitStyle InitStyle, 13578 AccessSpecifier AS) { 13579 if (D.isDecompositionDeclarator()) { 13580 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 13581 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 13582 << Decomp.getSourceRange(); 13583 return nullptr; 13584 } 13585 13586 IdentifierInfo *II = D.getIdentifier(); 13587 SourceLocation Loc = DeclStart; 13588 if (II) Loc = D.getIdentifierLoc(); 13589 13590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13591 QualType T = TInfo->getType(); 13592 if (getLangOpts().CPlusPlus) { 13593 CheckExtraCXXDefaultArguments(D); 13594 13595 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13596 UPPC_DataMemberType)) { 13597 D.setInvalidType(); 13598 T = Context.IntTy; 13599 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13600 } 13601 } 13602 13603 // TR 18037 does not allow fields to be declared with address spaces. 13604 if (T.getQualifiers().hasAddressSpace()) { 13605 Diag(Loc, diag::err_field_with_address_space); 13606 D.setInvalidType(); 13607 } 13608 13609 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 13610 // used as structure or union field: image, sampler, event or block types. 13611 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 13612 T->isSamplerT() || T->isBlockPointerType())) { 13613 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 13614 D.setInvalidType(); 13615 } 13616 13617 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13618 13619 if (D.getDeclSpec().isInlineSpecified()) 13620 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 13621 << getLangOpts().CPlusPlus1z; 13622 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13623 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13624 diag::err_invalid_thread) 13625 << DeclSpec::getSpecifierName(TSCS); 13626 13627 // Check to see if this name was declared as a member previously 13628 NamedDecl *PrevDecl = nullptr; 13629 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13630 LookupName(Previous, S); 13631 switch (Previous.getResultKind()) { 13632 case LookupResult::Found: 13633 case LookupResult::FoundUnresolvedValue: 13634 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13635 break; 13636 13637 case LookupResult::FoundOverloaded: 13638 PrevDecl = Previous.getRepresentativeDecl(); 13639 break; 13640 13641 case LookupResult::NotFound: 13642 case LookupResult::NotFoundInCurrentInstantiation: 13643 case LookupResult::Ambiguous: 13644 break; 13645 } 13646 Previous.suppressDiagnostics(); 13647 13648 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13649 // Maybe we will complain about the shadowed template parameter. 13650 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13651 // Just pretend that we didn't see the previous declaration. 13652 PrevDecl = nullptr; 13653 } 13654 13655 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13656 PrevDecl = nullptr; 13657 13658 bool Mutable 13659 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 13660 SourceLocation TSSL = D.getLocStart(); 13661 FieldDecl *NewFD 13662 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 13663 TSSL, AS, PrevDecl, &D); 13664 13665 if (NewFD->isInvalidDecl()) 13666 Record->setInvalidDecl(); 13667 13668 if (D.getDeclSpec().isModulePrivateSpecified()) 13669 NewFD->setModulePrivate(); 13670 13671 if (NewFD->isInvalidDecl() && PrevDecl) { 13672 // Don't introduce NewFD into scope; there's already something 13673 // with the same name in the same scope. 13674 } else if (II) { 13675 PushOnScopeChains(NewFD, S); 13676 } else 13677 Record->addDecl(NewFD); 13678 13679 return NewFD; 13680 } 13681 13682 /// \brief Build a new FieldDecl and check its well-formedness. 13683 /// 13684 /// This routine builds a new FieldDecl given the fields name, type, 13685 /// record, etc. \p PrevDecl should refer to any previous declaration 13686 /// with the same name and in the same scope as the field to be 13687 /// created. 13688 /// 13689 /// \returns a new FieldDecl. 13690 /// 13691 /// \todo The Declarator argument is a hack. It will be removed once 13692 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 13693 TypeSourceInfo *TInfo, 13694 RecordDecl *Record, SourceLocation Loc, 13695 bool Mutable, Expr *BitWidth, 13696 InClassInitStyle InitStyle, 13697 SourceLocation TSSL, 13698 AccessSpecifier AS, NamedDecl *PrevDecl, 13699 Declarator *D) { 13700 IdentifierInfo *II = Name.getAsIdentifierInfo(); 13701 bool InvalidDecl = false; 13702 if (D) InvalidDecl = D->isInvalidType(); 13703 13704 // If we receive a broken type, recover by assuming 'int' and 13705 // marking this declaration as invalid. 13706 if (T.isNull()) { 13707 InvalidDecl = true; 13708 T = Context.IntTy; 13709 } 13710 13711 QualType EltTy = Context.getBaseElementType(T); 13712 if (!EltTy->isDependentType()) { 13713 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 13714 // Fields of incomplete type force their record to be invalid. 13715 Record->setInvalidDecl(); 13716 InvalidDecl = true; 13717 } else { 13718 NamedDecl *Def; 13719 EltTy->isIncompleteType(&Def); 13720 if (Def && Def->isInvalidDecl()) { 13721 Record->setInvalidDecl(); 13722 InvalidDecl = true; 13723 } 13724 } 13725 } 13726 13727 // OpenCL v1.2 s6.9.c: bitfields are not supported. 13728 if (BitWidth && getLangOpts().OpenCL) { 13729 Diag(Loc, diag::err_opencl_bitfields); 13730 InvalidDecl = true; 13731 } 13732 13733 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13734 // than a variably modified type. 13735 if (!InvalidDecl && T->isVariablyModifiedType()) { 13736 bool SizeIsNegative; 13737 llvm::APSInt Oversized; 13738 13739 TypeSourceInfo *FixedTInfo = 13740 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 13741 SizeIsNegative, 13742 Oversized); 13743 if (FixedTInfo) { 13744 Diag(Loc, diag::warn_illegal_constant_array_size); 13745 TInfo = FixedTInfo; 13746 T = FixedTInfo->getType(); 13747 } else { 13748 if (SizeIsNegative) 13749 Diag(Loc, diag::err_typecheck_negative_array_size); 13750 else if (Oversized.getBoolValue()) 13751 Diag(Loc, diag::err_array_too_large) 13752 << Oversized.toString(10); 13753 else 13754 Diag(Loc, diag::err_typecheck_field_variable_size); 13755 InvalidDecl = true; 13756 } 13757 } 13758 13759 // Fields can not have abstract class types 13760 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13761 diag::err_abstract_type_in_decl, 13762 AbstractFieldType)) 13763 InvalidDecl = true; 13764 13765 bool ZeroWidth = false; 13766 if (InvalidDecl) 13767 BitWidth = nullptr; 13768 // If this is declared as a bit-field, check the bit-field. 13769 if (BitWidth) { 13770 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13771 &ZeroWidth).get(); 13772 if (!BitWidth) { 13773 InvalidDecl = true; 13774 BitWidth = nullptr; 13775 ZeroWidth = false; 13776 } 13777 } 13778 13779 // Check that 'mutable' is consistent with the type of the declaration. 13780 if (!InvalidDecl && Mutable) { 13781 unsigned DiagID = 0; 13782 if (T->isReferenceType()) 13783 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13784 : diag::err_mutable_reference; 13785 else if (T.isConstQualified()) 13786 DiagID = diag::err_mutable_const; 13787 13788 if (DiagID) { 13789 SourceLocation ErrLoc = Loc; 13790 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13791 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13792 Diag(ErrLoc, DiagID); 13793 if (DiagID != diag::ext_mutable_reference) { 13794 Mutable = false; 13795 InvalidDecl = true; 13796 } 13797 } 13798 } 13799 13800 // C++11 [class.union]p8 (DR1460): 13801 // At most one variant member of a union may have a 13802 // brace-or-equal-initializer. 13803 if (InitStyle != ICIS_NoInit) 13804 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13805 13806 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13807 BitWidth, Mutable, InitStyle); 13808 if (InvalidDecl) 13809 NewFD->setInvalidDecl(); 13810 13811 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13812 Diag(Loc, diag::err_duplicate_member) << II; 13813 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13814 NewFD->setInvalidDecl(); 13815 } 13816 13817 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13818 if (Record->isUnion()) { 13819 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13820 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13821 if (RDecl->getDefinition()) { 13822 // C++ [class.union]p1: An object of a class with a non-trivial 13823 // constructor, a non-trivial copy constructor, a non-trivial 13824 // destructor, or a non-trivial copy assignment operator 13825 // cannot be a member of a union, nor can an array of such 13826 // objects. 13827 if (CheckNontrivialField(NewFD)) 13828 NewFD->setInvalidDecl(); 13829 } 13830 } 13831 13832 // C++ [class.union]p1: If a union contains a member of reference type, 13833 // the program is ill-formed, except when compiling with MSVC extensions 13834 // enabled. 13835 if (EltTy->isReferenceType()) { 13836 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13837 diag::ext_union_member_of_reference_type : 13838 diag::err_union_member_of_reference_type) 13839 << NewFD->getDeclName() << EltTy; 13840 if (!getLangOpts().MicrosoftExt) 13841 NewFD->setInvalidDecl(); 13842 } 13843 } 13844 } 13845 13846 // FIXME: We need to pass in the attributes given an AST 13847 // representation, not a parser representation. 13848 if (D) { 13849 // FIXME: The current scope is almost... but not entirely... correct here. 13850 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13851 13852 if (NewFD->hasAttrs()) 13853 CheckAlignasUnderalignment(NewFD); 13854 } 13855 13856 // In auto-retain/release, infer strong retension for fields of 13857 // retainable type. 13858 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13859 NewFD->setInvalidDecl(); 13860 13861 if (T.isObjCGCWeak()) 13862 Diag(Loc, diag::warn_attribute_weak_on_field); 13863 13864 NewFD->setAccess(AS); 13865 return NewFD; 13866 } 13867 13868 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13869 assert(FD); 13870 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13871 13872 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13873 return false; 13874 13875 QualType EltTy = Context.getBaseElementType(FD->getType()); 13876 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13877 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13878 if (RDecl->getDefinition()) { 13879 // We check for copy constructors before constructors 13880 // because otherwise we'll never get complaints about 13881 // copy constructors. 13882 13883 CXXSpecialMember member = CXXInvalid; 13884 // We're required to check for any non-trivial constructors. Since the 13885 // implicit default constructor is suppressed if there are any 13886 // user-declared constructors, we just need to check that there is a 13887 // trivial default constructor and a trivial copy constructor. (We don't 13888 // worry about move constructors here, since this is a C++98 check.) 13889 if (RDecl->hasNonTrivialCopyConstructor()) 13890 member = CXXCopyConstructor; 13891 else if (!RDecl->hasTrivialDefaultConstructor()) 13892 member = CXXDefaultConstructor; 13893 else if (RDecl->hasNonTrivialCopyAssignment()) 13894 member = CXXCopyAssignment; 13895 else if (RDecl->hasNonTrivialDestructor()) 13896 member = CXXDestructor; 13897 13898 if (member != CXXInvalid) { 13899 if (!getLangOpts().CPlusPlus11 && 13900 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13901 // Objective-C++ ARC: it is an error to have a non-trivial field of 13902 // a union. However, system headers in Objective-C programs 13903 // occasionally have Objective-C lifetime objects within unions, 13904 // and rather than cause the program to fail, we make those 13905 // members unavailable. 13906 SourceLocation Loc = FD->getLocation(); 13907 if (getSourceManager().isInSystemHeader(Loc)) { 13908 if (!FD->hasAttr<UnavailableAttr>()) 13909 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13910 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13911 return false; 13912 } 13913 } 13914 13915 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13916 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13917 diag::err_illegal_union_or_anon_struct_member) 13918 << FD->getParent()->isUnion() << FD->getDeclName() << member; 13919 DiagnoseNontrivial(RDecl, member); 13920 return !getLangOpts().CPlusPlus11; 13921 } 13922 } 13923 } 13924 13925 return false; 13926 } 13927 13928 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13929 /// AST enum value. 13930 static ObjCIvarDecl::AccessControl 13931 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13932 switch (ivarVisibility) { 13933 default: llvm_unreachable("Unknown visitibility kind"); 13934 case tok::objc_private: return ObjCIvarDecl::Private; 13935 case tok::objc_public: return ObjCIvarDecl::Public; 13936 case tok::objc_protected: return ObjCIvarDecl::Protected; 13937 case tok::objc_package: return ObjCIvarDecl::Package; 13938 } 13939 } 13940 13941 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13942 /// in order to create an IvarDecl object for it. 13943 Decl *Sema::ActOnIvar(Scope *S, 13944 SourceLocation DeclStart, 13945 Declarator &D, Expr *BitfieldWidth, 13946 tok::ObjCKeywordKind Visibility) { 13947 13948 IdentifierInfo *II = D.getIdentifier(); 13949 Expr *BitWidth = (Expr*)BitfieldWidth; 13950 SourceLocation Loc = DeclStart; 13951 if (II) Loc = D.getIdentifierLoc(); 13952 13953 // FIXME: Unnamed fields can be handled in various different ways, for 13954 // example, unnamed unions inject all members into the struct namespace! 13955 13956 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13957 QualType T = TInfo->getType(); 13958 13959 if (BitWidth) { 13960 // 6.7.2.1p3, 6.7.2.1p4 13961 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13962 if (!BitWidth) 13963 D.setInvalidType(); 13964 } else { 13965 // Not a bitfield. 13966 13967 // validate II. 13968 13969 } 13970 if (T->isReferenceType()) { 13971 Diag(Loc, diag::err_ivar_reference_type); 13972 D.setInvalidType(); 13973 } 13974 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13975 // than a variably modified type. 13976 else if (T->isVariablyModifiedType()) { 13977 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13978 D.setInvalidType(); 13979 } 13980 13981 // Get the visibility (access control) for this ivar. 13982 ObjCIvarDecl::AccessControl ac = 13983 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13984 : ObjCIvarDecl::None; 13985 // Must set ivar's DeclContext to its enclosing interface. 13986 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13987 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13988 return nullptr; 13989 ObjCContainerDecl *EnclosingContext; 13990 if (ObjCImplementationDecl *IMPDecl = 13991 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13992 if (LangOpts.ObjCRuntime.isFragile()) { 13993 // Case of ivar declared in an implementation. Context is that of its class. 13994 EnclosingContext = IMPDecl->getClassInterface(); 13995 assert(EnclosingContext && "Implementation has no class interface!"); 13996 } 13997 else 13998 EnclosingContext = EnclosingDecl; 13999 } else { 14000 if (ObjCCategoryDecl *CDecl = 14001 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14002 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14003 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14004 return nullptr; 14005 } 14006 } 14007 EnclosingContext = EnclosingDecl; 14008 } 14009 14010 // Construct the decl. 14011 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14012 DeclStart, Loc, II, T, 14013 TInfo, ac, (Expr *)BitfieldWidth); 14014 14015 if (II) { 14016 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14017 ForRedeclaration); 14018 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14019 && !isa<TagDecl>(PrevDecl)) { 14020 Diag(Loc, diag::err_duplicate_member) << II; 14021 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14022 NewID->setInvalidDecl(); 14023 } 14024 } 14025 14026 // Process attributes attached to the ivar. 14027 ProcessDeclAttributes(S, NewID, D); 14028 14029 if (D.isInvalidType()) 14030 NewID->setInvalidDecl(); 14031 14032 // In ARC, infer 'retaining' for ivars of retainable type. 14033 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14034 NewID->setInvalidDecl(); 14035 14036 if (D.getDeclSpec().isModulePrivateSpecified()) 14037 NewID->setModulePrivate(); 14038 14039 if (II) { 14040 // FIXME: When interfaces are DeclContexts, we'll need to add 14041 // these to the interface. 14042 S->AddDecl(NewID); 14043 IdResolver.AddDecl(NewID); 14044 } 14045 14046 if (LangOpts.ObjCRuntime.isNonFragile() && 14047 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14048 Diag(Loc, diag::warn_ivars_in_interface); 14049 14050 return NewID; 14051 } 14052 14053 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14054 /// class and class extensions. For every class \@interface and class 14055 /// extension \@interface, if the last ivar is a bitfield of any type, 14056 /// then add an implicit `char :0` ivar to the end of that interface. 14057 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14058 SmallVectorImpl<Decl *> &AllIvarDecls) { 14059 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14060 return; 14061 14062 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14063 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14064 14065 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14066 return; 14067 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14068 if (!ID) { 14069 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14070 if (!CD->IsClassExtension()) 14071 return; 14072 } 14073 // No need to add this to end of @implementation. 14074 else 14075 return; 14076 } 14077 // All conditions are met. Add a new bitfield to the tail end of ivars. 14078 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14079 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14080 14081 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14082 DeclLoc, DeclLoc, nullptr, 14083 Context.CharTy, 14084 Context.getTrivialTypeSourceInfo(Context.CharTy, 14085 DeclLoc), 14086 ObjCIvarDecl::Private, BW, 14087 true); 14088 AllIvarDecls.push_back(Ivar); 14089 } 14090 14091 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14092 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14093 SourceLocation RBrac, AttributeList *Attr) { 14094 assert(EnclosingDecl && "missing record or interface decl"); 14095 14096 // If this is an Objective-C @implementation or category and we have 14097 // new fields here we should reset the layout of the interface since 14098 // it will now change. 14099 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14100 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14101 switch (DC->getKind()) { 14102 default: break; 14103 case Decl::ObjCCategory: 14104 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14105 break; 14106 case Decl::ObjCImplementation: 14107 Context. 14108 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14109 break; 14110 } 14111 } 14112 14113 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14114 14115 // Start counting up the number of named members; make sure to include 14116 // members of anonymous structs and unions in the total. 14117 unsigned NumNamedMembers = 0; 14118 if (Record) { 14119 for (const auto *I : Record->decls()) { 14120 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14121 if (IFD->getDeclName()) 14122 ++NumNamedMembers; 14123 } 14124 } 14125 14126 // Verify that all the fields are okay. 14127 SmallVector<FieldDecl*, 32> RecFields; 14128 14129 bool ARCErrReported = false; 14130 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14131 i != end; ++i) { 14132 FieldDecl *FD = cast<FieldDecl>(*i); 14133 14134 // Get the type for the field. 14135 const Type *FDTy = FD->getType().getTypePtr(); 14136 14137 if (!FD->isAnonymousStructOrUnion()) { 14138 // Remember all fields written by the user. 14139 RecFields.push_back(FD); 14140 } 14141 14142 // If the field is already invalid for some reason, don't emit more 14143 // diagnostics about it. 14144 if (FD->isInvalidDecl()) { 14145 EnclosingDecl->setInvalidDecl(); 14146 continue; 14147 } 14148 14149 // C99 6.7.2.1p2: 14150 // A structure or union shall not contain a member with 14151 // incomplete or function type (hence, a structure shall not 14152 // contain an instance of itself, but may contain a pointer to 14153 // an instance of itself), except that the last member of a 14154 // structure with more than one named member may have incomplete 14155 // array type; such a structure (and any union containing, 14156 // possibly recursively, a member that is such a structure) 14157 // shall not be a member of a structure or an element of an 14158 // array. 14159 if (FDTy->isFunctionType()) { 14160 // Field declared as a function. 14161 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14162 << FD->getDeclName(); 14163 FD->setInvalidDecl(); 14164 EnclosingDecl->setInvalidDecl(); 14165 continue; 14166 } else if (FDTy->isIncompleteArrayType() && Record && 14167 ((i + 1 == Fields.end() && !Record->isUnion()) || 14168 ((getLangOpts().MicrosoftExt || 14169 getLangOpts().CPlusPlus) && 14170 (i + 1 == Fields.end() || Record->isUnion())))) { 14171 // Flexible array member. 14172 // Microsoft and g++ is more permissive regarding flexible array. 14173 // It will accept flexible array in union and also 14174 // as the sole element of a struct/class. 14175 unsigned DiagID = 0; 14176 if (Record->isUnion()) 14177 DiagID = getLangOpts().MicrosoftExt 14178 ? diag::ext_flexible_array_union_ms 14179 : getLangOpts().CPlusPlus 14180 ? diag::ext_flexible_array_union_gnu 14181 : diag::err_flexible_array_union; 14182 else if (NumNamedMembers < 1) 14183 DiagID = getLangOpts().MicrosoftExt 14184 ? diag::ext_flexible_array_empty_aggregate_ms 14185 : getLangOpts().CPlusPlus 14186 ? diag::ext_flexible_array_empty_aggregate_gnu 14187 : diag::err_flexible_array_empty_aggregate; 14188 14189 if (DiagID) 14190 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14191 << Record->getTagKind(); 14192 // While the layout of types that contain virtual bases is not specified 14193 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14194 // virtual bases after the derived members. This would make a flexible 14195 // array member declared at the end of an object not adjacent to the end 14196 // of the type. 14197 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14198 if (RD->getNumVBases() != 0) 14199 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14200 << FD->getDeclName() << Record->getTagKind(); 14201 if (!getLangOpts().C99) 14202 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14203 << FD->getDeclName() << Record->getTagKind(); 14204 14205 // If the element type has a non-trivial destructor, we would not 14206 // implicitly destroy the elements, so disallow it for now. 14207 // 14208 // FIXME: GCC allows this. We should probably either implicitly delete 14209 // the destructor of the containing class, or just allow this. 14210 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14211 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14212 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14213 << FD->getDeclName() << FD->getType(); 14214 FD->setInvalidDecl(); 14215 EnclosingDecl->setInvalidDecl(); 14216 continue; 14217 } 14218 // Okay, we have a legal flexible array member at the end of the struct. 14219 Record->setHasFlexibleArrayMember(true); 14220 } else if (!FDTy->isDependentType() && 14221 RequireCompleteType(FD->getLocation(), FD->getType(), 14222 diag::err_field_incomplete)) { 14223 // Incomplete type 14224 FD->setInvalidDecl(); 14225 EnclosingDecl->setInvalidDecl(); 14226 continue; 14227 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14228 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14229 // A type which contains a flexible array member is considered to be a 14230 // flexible array member. 14231 Record->setHasFlexibleArrayMember(true); 14232 if (!Record->isUnion()) { 14233 // If this is a struct/class and this is not the last element, reject 14234 // it. Note that GCC supports variable sized arrays in the middle of 14235 // structures. 14236 if (i + 1 != Fields.end()) 14237 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14238 << FD->getDeclName() << FD->getType(); 14239 else { 14240 // We support flexible arrays at the end of structs in 14241 // other structs as an extension. 14242 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14243 << FD->getDeclName(); 14244 } 14245 } 14246 } 14247 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14248 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14249 diag::err_abstract_type_in_decl, 14250 AbstractIvarType)) { 14251 // Ivars can not have abstract class types 14252 FD->setInvalidDecl(); 14253 } 14254 if (Record && FDTTy->getDecl()->hasObjectMember()) 14255 Record->setHasObjectMember(true); 14256 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14257 Record->setHasVolatileMember(true); 14258 } else if (FDTy->isObjCObjectType()) { 14259 /// A field cannot be an Objective-c object 14260 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14261 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14262 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14263 FD->setType(T); 14264 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 14265 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14266 // It's an error in ARC if a field has lifetime. 14267 // We don't want to report this in a system header, though, 14268 // so we just make the field unavailable. 14269 // FIXME: that's really not sufficient; we need to make the type 14270 // itself invalid to, say, initialize or copy. 14271 QualType T = FD->getType(); 14272 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 14273 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 14274 SourceLocation loc = FD->getLocation(); 14275 if (getSourceManager().isInSystemHeader(loc)) { 14276 if (!FD->hasAttr<UnavailableAttr>()) { 14277 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14278 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14279 } 14280 } else { 14281 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14282 << T->isBlockPointerType() << Record->getTagKind(); 14283 } 14284 ARCErrReported = true; 14285 } 14286 } else if (getLangOpts().ObjC1 && 14287 getLangOpts().getGC() != LangOptions::NonGC && 14288 Record && !Record->hasObjectMember()) { 14289 if (FD->getType()->isObjCObjectPointerType() || 14290 FD->getType().isObjCGCStrong()) 14291 Record->setHasObjectMember(true); 14292 else if (Context.getAsArrayType(FD->getType())) { 14293 QualType BaseType = Context.getBaseElementType(FD->getType()); 14294 if (BaseType->isRecordType() && 14295 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14296 Record->setHasObjectMember(true); 14297 else if (BaseType->isObjCObjectPointerType() || 14298 BaseType.isObjCGCStrong()) 14299 Record->setHasObjectMember(true); 14300 } 14301 } 14302 if (Record && FD->getType().isVolatileQualified()) 14303 Record->setHasVolatileMember(true); 14304 // Keep track of the number of named members. 14305 if (FD->getIdentifier()) 14306 ++NumNamedMembers; 14307 } 14308 14309 // Okay, we successfully defined 'Record'. 14310 if (Record) { 14311 bool Completed = false; 14312 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14313 if (!CXXRecord->isInvalidDecl()) { 14314 // Set access bits correctly on the directly-declared conversions. 14315 for (CXXRecordDecl::conversion_iterator 14316 I = CXXRecord->conversion_begin(), 14317 E = CXXRecord->conversion_end(); I != E; ++I) 14318 I.setAccess((*I)->getAccess()); 14319 } 14320 14321 if (!CXXRecord->isDependentType()) { 14322 if (CXXRecord->hasUserDeclaredDestructor()) { 14323 // Adjust user-defined destructor exception spec. 14324 if (getLangOpts().CPlusPlus11) 14325 AdjustDestructorExceptionSpec(CXXRecord, 14326 CXXRecord->getDestructor()); 14327 } 14328 14329 if (!CXXRecord->isInvalidDecl()) { 14330 // Add any implicitly-declared members to this class. 14331 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14332 14333 // If we have virtual base classes, we may end up finding multiple 14334 // final overriders for a given virtual function. Check for this 14335 // problem now. 14336 if (CXXRecord->getNumVBases()) { 14337 CXXFinalOverriderMap FinalOverriders; 14338 CXXRecord->getFinalOverriders(FinalOverriders); 14339 14340 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14341 MEnd = FinalOverriders.end(); 14342 M != MEnd; ++M) { 14343 for (OverridingMethods::iterator SO = M->second.begin(), 14344 SOEnd = M->second.end(); 14345 SO != SOEnd; ++SO) { 14346 assert(SO->second.size() > 0 && 14347 "Virtual function without overridding functions?"); 14348 if (SO->second.size() == 1) 14349 continue; 14350 14351 // C++ [class.virtual]p2: 14352 // In a derived class, if a virtual member function of a base 14353 // class subobject has more than one final overrider the 14354 // program is ill-formed. 14355 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14356 << (const NamedDecl *)M->first << Record; 14357 Diag(M->first->getLocation(), 14358 diag::note_overridden_virtual_function); 14359 for (OverridingMethods::overriding_iterator 14360 OM = SO->second.begin(), 14361 OMEnd = SO->second.end(); 14362 OM != OMEnd; ++OM) 14363 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14364 << (const NamedDecl *)M->first << OM->Method->getParent(); 14365 14366 Record->setInvalidDecl(); 14367 } 14368 } 14369 CXXRecord->completeDefinition(&FinalOverriders); 14370 Completed = true; 14371 } 14372 } 14373 } 14374 } 14375 14376 if (!Completed) 14377 Record->completeDefinition(); 14378 14379 // We may have deferred checking for a deleted destructor. Check now. 14380 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14381 auto *Dtor = CXXRecord->getDestructor(); 14382 if (Dtor && Dtor->isImplicit() && 14383 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14384 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14385 } 14386 14387 if (Record->hasAttrs()) { 14388 CheckAlignasUnderalignment(Record); 14389 14390 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14391 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14392 IA->getRange(), IA->getBestCase(), 14393 IA->getSemanticSpelling()); 14394 } 14395 14396 // Check if the structure/union declaration is a type that can have zero 14397 // size in C. For C this is a language extension, for C++ it may cause 14398 // compatibility problems. 14399 bool CheckForZeroSize; 14400 if (!getLangOpts().CPlusPlus) { 14401 CheckForZeroSize = true; 14402 } else { 14403 // For C++ filter out types that cannot be referenced in C code. 14404 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14405 CheckForZeroSize = 14406 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14407 !CXXRecord->isDependentType() && 14408 CXXRecord->isCLike(); 14409 } 14410 if (CheckForZeroSize) { 14411 bool ZeroSize = true; 14412 bool IsEmpty = true; 14413 unsigned NonBitFields = 0; 14414 for (RecordDecl::field_iterator I = Record->field_begin(), 14415 E = Record->field_end(); 14416 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14417 IsEmpty = false; 14418 if (I->isUnnamedBitfield()) { 14419 if (I->getBitWidthValue(Context) > 0) 14420 ZeroSize = false; 14421 } else { 14422 ++NonBitFields; 14423 QualType FieldType = I->getType(); 14424 if (FieldType->isIncompleteType() || 14425 !Context.getTypeSizeInChars(FieldType).isZero()) 14426 ZeroSize = false; 14427 } 14428 } 14429 14430 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14431 // allowed in C++, but warn if its declaration is inside 14432 // extern "C" block. 14433 if (ZeroSize) { 14434 Diag(RecLoc, getLangOpts().CPlusPlus ? 14435 diag::warn_zero_size_struct_union_in_extern_c : 14436 diag::warn_zero_size_struct_union_compat) 14437 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14438 } 14439 14440 // Structs without named members are extension in C (C99 6.7.2.1p7), 14441 // but are accepted by GCC. 14442 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14443 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14444 diag::ext_no_named_members_in_struct_union) 14445 << Record->isUnion(); 14446 } 14447 } 14448 } else { 14449 ObjCIvarDecl **ClsFields = 14450 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14451 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14452 ID->setEndOfDefinitionLoc(RBrac); 14453 // Add ivar's to class's DeclContext. 14454 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14455 ClsFields[i]->setLexicalDeclContext(ID); 14456 ID->addDecl(ClsFields[i]); 14457 } 14458 // Must enforce the rule that ivars in the base classes may not be 14459 // duplicates. 14460 if (ID->getSuperClass()) 14461 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 14462 } else if (ObjCImplementationDecl *IMPDecl = 14463 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14464 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 14465 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 14466 // Ivar declared in @implementation never belongs to the implementation. 14467 // Only it is in implementation's lexical context. 14468 ClsFields[I]->setLexicalDeclContext(IMPDecl); 14469 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 14470 IMPDecl->setIvarLBraceLoc(LBrac); 14471 IMPDecl->setIvarRBraceLoc(RBrac); 14472 } else if (ObjCCategoryDecl *CDecl = 14473 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14474 // case of ivars in class extension; all other cases have been 14475 // reported as errors elsewhere. 14476 // FIXME. Class extension does not have a LocEnd field. 14477 // CDecl->setLocEnd(RBrac); 14478 // Add ivar's to class extension's DeclContext. 14479 // Diagnose redeclaration of private ivars. 14480 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 14481 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 14482 if (IDecl) { 14483 if (const ObjCIvarDecl *ClsIvar = 14484 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 14485 Diag(ClsFields[i]->getLocation(), 14486 diag::err_duplicate_ivar_declaration); 14487 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 14488 continue; 14489 } 14490 for (const auto *Ext : IDecl->known_extensions()) { 14491 if (const ObjCIvarDecl *ClsExtIvar 14492 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 14493 Diag(ClsFields[i]->getLocation(), 14494 diag::err_duplicate_ivar_declaration); 14495 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 14496 continue; 14497 } 14498 } 14499 } 14500 ClsFields[i]->setLexicalDeclContext(CDecl); 14501 CDecl->addDecl(ClsFields[i]); 14502 } 14503 CDecl->setIvarLBraceLoc(LBrac); 14504 CDecl->setIvarRBraceLoc(RBrac); 14505 } 14506 } 14507 14508 if (Attr) 14509 ProcessDeclAttributeList(S, Record, Attr); 14510 } 14511 14512 /// \brief Determine whether the given integral value is representable within 14513 /// the given type T. 14514 static bool isRepresentableIntegerValue(ASTContext &Context, 14515 llvm::APSInt &Value, 14516 QualType T) { 14517 assert(T->isIntegralType(Context) && "Integral type required!"); 14518 unsigned BitWidth = Context.getIntWidth(T); 14519 14520 if (Value.isUnsigned() || Value.isNonNegative()) { 14521 if (T->isSignedIntegerOrEnumerationType()) 14522 --BitWidth; 14523 return Value.getActiveBits() <= BitWidth; 14524 } 14525 return Value.getMinSignedBits() <= BitWidth; 14526 } 14527 14528 // \brief Given an integral type, return the next larger integral type 14529 // (or a NULL type of no such type exists). 14530 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 14531 // FIXME: Int128/UInt128 support, which also needs to be introduced into 14532 // enum checking below. 14533 assert(T->isIntegralType(Context) && "Integral type required!"); 14534 const unsigned NumTypes = 4; 14535 QualType SignedIntegralTypes[NumTypes] = { 14536 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 14537 }; 14538 QualType UnsignedIntegralTypes[NumTypes] = { 14539 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 14540 Context.UnsignedLongLongTy 14541 }; 14542 14543 unsigned BitWidth = Context.getTypeSize(T); 14544 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 14545 : UnsignedIntegralTypes; 14546 for (unsigned I = 0; I != NumTypes; ++I) 14547 if (Context.getTypeSize(Types[I]) > BitWidth) 14548 return Types[I]; 14549 14550 return QualType(); 14551 } 14552 14553 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 14554 EnumConstantDecl *LastEnumConst, 14555 SourceLocation IdLoc, 14556 IdentifierInfo *Id, 14557 Expr *Val) { 14558 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14559 llvm::APSInt EnumVal(IntWidth); 14560 QualType EltTy; 14561 14562 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 14563 Val = nullptr; 14564 14565 if (Val) 14566 Val = DefaultLvalueConversion(Val).get(); 14567 14568 if (Val) { 14569 if (Enum->isDependentType() || Val->isTypeDependent()) 14570 EltTy = Context.DependentTy; 14571 else { 14572 SourceLocation ExpLoc; 14573 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 14574 !getLangOpts().MSVCCompat) { 14575 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 14576 // constant-expression in the enumerator-definition shall be a converted 14577 // constant expression of the underlying type. 14578 EltTy = Enum->getIntegerType(); 14579 ExprResult Converted = 14580 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 14581 CCEK_Enumerator); 14582 if (Converted.isInvalid()) 14583 Val = nullptr; 14584 else 14585 Val = Converted.get(); 14586 } else if (!Val->isValueDependent() && 14587 !(Val = VerifyIntegerConstantExpression(Val, 14588 &EnumVal).get())) { 14589 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 14590 } else { 14591 if (Enum->isFixed()) { 14592 EltTy = Enum->getIntegerType(); 14593 14594 // In Obj-C and Microsoft mode, require the enumeration value to be 14595 // representable in the underlying type of the enumeration. In C++11, 14596 // we perform a non-narrowing conversion as part of converted constant 14597 // expression checking. 14598 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14599 if (getLangOpts().MSVCCompat) { 14600 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 14601 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 14602 } else 14603 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 14604 } else 14605 Val = ImpCastExprToType(Val, EltTy, 14606 EltTy->isBooleanType() ? 14607 CK_IntegralToBoolean : CK_IntegralCast) 14608 .get(); 14609 } else if (getLangOpts().CPlusPlus) { 14610 // C++11 [dcl.enum]p5: 14611 // If the underlying type is not fixed, the type of each enumerator 14612 // is the type of its initializing value: 14613 // - If an initializer is specified for an enumerator, the 14614 // initializing value has the same type as the expression. 14615 EltTy = Val->getType(); 14616 } else { 14617 // C99 6.7.2.2p2: 14618 // The expression that defines the value of an enumeration constant 14619 // shall be an integer constant expression that has a value 14620 // representable as an int. 14621 14622 // Complain if the value is not representable in an int. 14623 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 14624 Diag(IdLoc, diag::ext_enum_value_not_int) 14625 << EnumVal.toString(10) << Val->getSourceRange() 14626 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 14627 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 14628 // Force the type of the expression to 'int'. 14629 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 14630 } 14631 EltTy = Val->getType(); 14632 } 14633 } 14634 } 14635 } 14636 14637 if (!Val) { 14638 if (Enum->isDependentType()) 14639 EltTy = Context.DependentTy; 14640 else if (!LastEnumConst) { 14641 // C++0x [dcl.enum]p5: 14642 // If the underlying type is not fixed, the type of each enumerator 14643 // is the type of its initializing value: 14644 // - If no initializer is specified for the first enumerator, the 14645 // initializing value has an unspecified integral type. 14646 // 14647 // GCC uses 'int' for its unspecified integral type, as does 14648 // C99 6.7.2.2p3. 14649 if (Enum->isFixed()) { 14650 EltTy = Enum->getIntegerType(); 14651 } 14652 else { 14653 EltTy = Context.IntTy; 14654 } 14655 } else { 14656 // Assign the last value + 1. 14657 EnumVal = LastEnumConst->getInitVal(); 14658 ++EnumVal; 14659 EltTy = LastEnumConst->getType(); 14660 14661 // Check for overflow on increment. 14662 if (EnumVal < LastEnumConst->getInitVal()) { 14663 // C++0x [dcl.enum]p5: 14664 // If the underlying type is not fixed, the type of each enumerator 14665 // is the type of its initializing value: 14666 // 14667 // - Otherwise the type of the initializing value is the same as 14668 // the type of the initializing value of the preceding enumerator 14669 // unless the incremented value is not representable in that type, 14670 // in which case the type is an unspecified integral type 14671 // sufficient to contain the incremented value. If no such type 14672 // exists, the program is ill-formed. 14673 QualType T = getNextLargerIntegralType(Context, EltTy); 14674 if (T.isNull() || Enum->isFixed()) { 14675 // There is no integral type larger enough to represent this 14676 // value. Complain, then allow the value to wrap around. 14677 EnumVal = LastEnumConst->getInitVal(); 14678 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 14679 ++EnumVal; 14680 if (Enum->isFixed()) 14681 // When the underlying type is fixed, this is ill-formed. 14682 Diag(IdLoc, diag::err_enumerator_wrapped) 14683 << EnumVal.toString(10) 14684 << EltTy; 14685 else 14686 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 14687 << EnumVal.toString(10); 14688 } else { 14689 EltTy = T; 14690 } 14691 14692 // Retrieve the last enumerator's value, extent that type to the 14693 // type that is supposed to be large enough to represent the incremented 14694 // value, then increment. 14695 EnumVal = LastEnumConst->getInitVal(); 14696 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14697 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 14698 ++EnumVal; 14699 14700 // If we're not in C++, diagnose the overflow of enumerator values, 14701 // which in C99 means that the enumerator value is not representable in 14702 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 14703 // permits enumerator values that are representable in some larger 14704 // integral type. 14705 if (!getLangOpts().CPlusPlus && !T.isNull()) 14706 Diag(IdLoc, diag::warn_enum_value_overflow); 14707 } else if (!getLangOpts().CPlusPlus && 14708 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 14709 // Enforce C99 6.7.2.2p2 even when we compute the next value. 14710 Diag(IdLoc, diag::ext_enum_value_not_int) 14711 << EnumVal.toString(10) << 1; 14712 } 14713 } 14714 } 14715 14716 if (!EltTy->isDependentType()) { 14717 // Make the enumerator value match the signedness and size of the 14718 // enumerator's type. 14719 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 14720 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 14721 } 14722 14723 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 14724 Val, EnumVal); 14725 } 14726 14727 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 14728 SourceLocation IILoc) { 14729 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 14730 !getLangOpts().CPlusPlus) 14731 return SkipBodyInfo(); 14732 14733 // We have an anonymous enum definition. Look up the first enumerator to 14734 // determine if we should merge the definition with an existing one and 14735 // skip the body. 14736 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 14737 ForRedeclaration); 14738 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 14739 if (!PrevECD) 14740 return SkipBodyInfo(); 14741 14742 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 14743 NamedDecl *Hidden; 14744 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 14745 SkipBodyInfo Skip; 14746 Skip.Previous = Hidden; 14747 return Skip; 14748 } 14749 14750 return SkipBodyInfo(); 14751 } 14752 14753 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 14754 SourceLocation IdLoc, IdentifierInfo *Id, 14755 AttributeList *Attr, 14756 SourceLocation EqualLoc, Expr *Val) { 14757 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 14758 EnumConstantDecl *LastEnumConst = 14759 cast_or_null<EnumConstantDecl>(lastEnumConst); 14760 14761 // The scope passed in may not be a decl scope. Zip up the scope tree until 14762 // we find one that is. 14763 S = getNonFieldDeclScope(S); 14764 14765 // Verify that there isn't already something declared with this name in this 14766 // scope. 14767 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 14768 ForRedeclaration); 14769 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14770 // Maybe we will complain about the shadowed template parameter. 14771 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14772 // Just pretend that we didn't see the previous declaration. 14773 PrevDecl = nullptr; 14774 } 14775 14776 // C++ [class.mem]p15: 14777 // If T is the name of a class, then each of the following shall have a name 14778 // different from T: 14779 // - every enumerator of every member of class T that is an unscoped 14780 // enumerated type 14781 if (!TheEnumDecl->isScoped()) 14782 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14783 DeclarationNameInfo(Id, IdLoc)); 14784 14785 EnumConstantDecl *New = 14786 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14787 if (!New) 14788 return nullptr; 14789 14790 if (PrevDecl) { 14791 // When in C++, we may get a TagDecl with the same name; in this case the 14792 // enum constant will 'hide' the tag. 14793 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14794 "Received TagDecl when not in C++!"); 14795 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 14796 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 14797 if (isa<EnumConstantDecl>(PrevDecl)) 14798 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14799 else 14800 Diag(IdLoc, diag::err_redefinition) << Id; 14801 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14802 return nullptr; 14803 } 14804 } 14805 14806 // Process attributes. 14807 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14808 14809 // Register this decl in the current scope stack. 14810 New->setAccess(TheEnumDecl->getAccess()); 14811 PushOnScopeChains(New, S); 14812 14813 ActOnDocumentableDecl(New); 14814 14815 return New; 14816 } 14817 14818 // Returns true when the enum initial expression does not trigger the 14819 // duplicate enum warning. A few common cases are exempted as follows: 14820 // Element2 = Element1 14821 // Element2 = Element1 + 1 14822 // Element2 = Element1 - 1 14823 // Where Element2 and Element1 are from the same enum. 14824 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14825 Expr *InitExpr = ECD->getInitExpr(); 14826 if (!InitExpr) 14827 return true; 14828 InitExpr = InitExpr->IgnoreImpCasts(); 14829 14830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14831 if (!BO->isAdditiveOp()) 14832 return true; 14833 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14834 if (!IL) 14835 return true; 14836 if (IL->getValue() != 1) 14837 return true; 14838 14839 InitExpr = BO->getLHS(); 14840 } 14841 14842 // This checks if the elements are from the same enum. 14843 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14844 if (!DRE) 14845 return true; 14846 14847 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14848 if (!EnumConstant) 14849 return true; 14850 14851 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14852 Enum) 14853 return true; 14854 14855 return false; 14856 } 14857 14858 namespace { 14859 struct DupKey { 14860 int64_t val; 14861 bool isTombstoneOrEmptyKey; 14862 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14863 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14864 }; 14865 14866 static DupKey GetDupKey(const llvm::APSInt& Val) { 14867 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14868 false); 14869 } 14870 14871 struct DenseMapInfoDupKey { 14872 static DupKey getEmptyKey() { return DupKey(0, true); } 14873 static DupKey getTombstoneKey() { return DupKey(1, true); } 14874 static unsigned getHashValue(const DupKey Key) { 14875 return (unsigned)(Key.val * 37); 14876 } 14877 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14878 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14879 LHS.val == RHS.val; 14880 } 14881 }; 14882 } // end anonymous namespace 14883 14884 // Emits a warning when an element is implicitly set a value that 14885 // a previous element has already been set to. 14886 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14887 EnumDecl *Enum, 14888 QualType EnumType) { 14889 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14890 return; 14891 // Avoid anonymous enums 14892 if (!Enum->getIdentifier()) 14893 return; 14894 14895 // Only check for small enums. 14896 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14897 return; 14898 14899 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14900 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14901 14902 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14903 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14904 ValueToVectorMap; 14905 14906 DuplicatesVector DupVector; 14907 ValueToVectorMap EnumMap; 14908 14909 // Populate the EnumMap with all values represented by enum constants without 14910 // an initialier. 14911 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14912 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14913 14914 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14915 // this constant. Skip this enum since it may be ill-formed. 14916 if (!ECD) { 14917 return; 14918 } 14919 14920 if (ECD->getInitExpr()) 14921 continue; 14922 14923 DupKey Key = GetDupKey(ECD->getInitVal()); 14924 DeclOrVector &Entry = EnumMap[Key]; 14925 14926 // First time encountering this value. 14927 if (Entry.isNull()) 14928 Entry = ECD; 14929 } 14930 14931 // Create vectors for any values that has duplicates. 14932 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14933 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14934 if (!ValidDuplicateEnum(ECD, Enum)) 14935 continue; 14936 14937 DupKey Key = GetDupKey(ECD->getInitVal()); 14938 14939 DeclOrVector& Entry = EnumMap[Key]; 14940 if (Entry.isNull()) 14941 continue; 14942 14943 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14944 // Ensure constants are different. 14945 if (D == ECD) 14946 continue; 14947 14948 // Create new vector and push values onto it. 14949 ECDVector *Vec = new ECDVector(); 14950 Vec->push_back(D); 14951 Vec->push_back(ECD); 14952 14953 // Update entry to point to the duplicates vector. 14954 Entry = Vec; 14955 14956 // Store the vector somewhere we can consult later for quick emission of 14957 // diagnostics. 14958 DupVector.push_back(Vec); 14959 continue; 14960 } 14961 14962 ECDVector *Vec = Entry.get<ECDVector*>(); 14963 // Make sure constants are not added more than once. 14964 if (*Vec->begin() == ECD) 14965 continue; 14966 14967 Vec->push_back(ECD); 14968 } 14969 14970 // Emit diagnostics. 14971 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14972 DupVectorEnd = DupVector.end(); 14973 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14974 ECDVector *Vec = *DupVectorIter; 14975 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14976 14977 // Emit warning for one enum constant. 14978 ECDVector::iterator I = Vec->begin(); 14979 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14980 << (*I)->getName() << (*I)->getInitVal().toString(10) 14981 << (*I)->getSourceRange(); 14982 ++I; 14983 14984 // Emit one note for each of the remaining enum constants with 14985 // the same value. 14986 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14987 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14988 << (*I)->getName() << (*I)->getInitVal().toString(10) 14989 << (*I)->getSourceRange(); 14990 delete Vec; 14991 } 14992 } 14993 14994 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14995 bool AllowMask) const { 14996 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14997 assert(ED->isCompleteDefinition() && "expected enum definition"); 14998 14999 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15000 llvm::APInt &FlagBits = R.first->second; 15001 15002 if (R.second) { 15003 for (auto *E : ED->enumerators()) { 15004 const auto &EVal = E->getInitVal(); 15005 // Only single-bit enumerators introduce new flag values. 15006 if (EVal.isPowerOf2()) 15007 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15008 } 15009 } 15010 15011 // A value is in a flag enum if either its bits are a subset of the enum's 15012 // flag bits (the first condition) or we are allowing masks and the same is 15013 // true of its complement (the second condition). When masks are allowed, we 15014 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15015 // 15016 // While it's true that any value could be used as a mask, the assumption is 15017 // that a mask will have all of the insignificant bits set. Anything else is 15018 // likely a logic error. 15019 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15020 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15021 } 15022 15023 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15024 Decl *EnumDeclX, 15025 ArrayRef<Decl *> Elements, 15026 Scope *S, AttributeList *Attr) { 15027 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15028 QualType EnumType = Context.getTypeDeclType(Enum); 15029 15030 if (Attr) 15031 ProcessDeclAttributeList(S, Enum, Attr); 15032 15033 if (Enum->isDependentType()) { 15034 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15035 EnumConstantDecl *ECD = 15036 cast_or_null<EnumConstantDecl>(Elements[i]); 15037 if (!ECD) continue; 15038 15039 ECD->setType(EnumType); 15040 } 15041 15042 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15043 return; 15044 } 15045 15046 // TODO: If the result value doesn't fit in an int, it must be a long or long 15047 // long value. ISO C does not support this, but GCC does as an extension, 15048 // emit a warning. 15049 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15050 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15051 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15052 15053 // Verify that all the values are okay, compute the size of the values, and 15054 // reverse the list. 15055 unsigned NumNegativeBits = 0; 15056 unsigned NumPositiveBits = 0; 15057 15058 // Keep track of whether all elements have type int. 15059 bool AllElementsInt = true; 15060 15061 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15062 EnumConstantDecl *ECD = 15063 cast_or_null<EnumConstantDecl>(Elements[i]); 15064 if (!ECD) continue; // Already issued a diagnostic. 15065 15066 const llvm::APSInt &InitVal = ECD->getInitVal(); 15067 15068 // Keep track of the size of positive and negative values. 15069 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15070 NumPositiveBits = std::max(NumPositiveBits, 15071 (unsigned)InitVal.getActiveBits()); 15072 else 15073 NumNegativeBits = std::max(NumNegativeBits, 15074 (unsigned)InitVal.getMinSignedBits()); 15075 15076 // Keep track of whether every enum element has type int (very commmon). 15077 if (AllElementsInt) 15078 AllElementsInt = ECD->getType() == Context.IntTy; 15079 } 15080 15081 // Figure out the type that should be used for this enum. 15082 QualType BestType; 15083 unsigned BestWidth; 15084 15085 // C++0x N3000 [conv.prom]p3: 15086 // An rvalue of an unscoped enumeration type whose underlying 15087 // type is not fixed can be converted to an rvalue of the first 15088 // of the following types that can represent all the values of 15089 // the enumeration: int, unsigned int, long int, unsigned long 15090 // int, long long int, or unsigned long long int. 15091 // C99 6.4.4.3p2: 15092 // An identifier declared as an enumeration constant has type int. 15093 // The C99 rule is modified by a gcc extension 15094 QualType BestPromotionType; 15095 15096 bool Packed = Enum->hasAttr<PackedAttr>(); 15097 // -fshort-enums is the equivalent to specifying the packed attribute on all 15098 // enum definitions. 15099 if (LangOpts.ShortEnums) 15100 Packed = true; 15101 15102 if (Enum->isFixed()) { 15103 BestType = Enum->getIntegerType(); 15104 if (BestType->isPromotableIntegerType()) 15105 BestPromotionType = Context.getPromotedIntegerType(BestType); 15106 else 15107 BestPromotionType = BestType; 15108 15109 BestWidth = Context.getIntWidth(BestType); 15110 } 15111 else if (NumNegativeBits) { 15112 // If there is a negative value, figure out the smallest integer type (of 15113 // int/long/longlong) that fits. 15114 // If it's packed, check also if it fits a char or a short. 15115 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15116 BestType = Context.SignedCharTy; 15117 BestWidth = CharWidth; 15118 } else if (Packed && NumNegativeBits <= ShortWidth && 15119 NumPositiveBits < ShortWidth) { 15120 BestType = Context.ShortTy; 15121 BestWidth = ShortWidth; 15122 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15123 BestType = Context.IntTy; 15124 BestWidth = IntWidth; 15125 } else { 15126 BestWidth = Context.getTargetInfo().getLongWidth(); 15127 15128 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15129 BestType = Context.LongTy; 15130 } else { 15131 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15132 15133 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15134 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15135 BestType = Context.LongLongTy; 15136 } 15137 } 15138 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15139 } else { 15140 // If there is no negative value, figure out the smallest type that fits 15141 // all of the enumerator values. 15142 // If it's packed, check also if it fits a char or a short. 15143 if (Packed && NumPositiveBits <= CharWidth) { 15144 BestType = Context.UnsignedCharTy; 15145 BestPromotionType = Context.IntTy; 15146 BestWidth = CharWidth; 15147 } else if (Packed && NumPositiveBits <= ShortWidth) { 15148 BestType = Context.UnsignedShortTy; 15149 BestPromotionType = Context.IntTy; 15150 BestWidth = ShortWidth; 15151 } else if (NumPositiveBits <= IntWidth) { 15152 BestType = Context.UnsignedIntTy; 15153 BestWidth = IntWidth; 15154 BestPromotionType 15155 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15156 ? Context.UnsignedIntTy : Context.IntTy; 15157 } else if (NumPositiveBits <= 15158 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15159 BestType = Context.UnsignedLongTy; 15160 BestPromotionType 15161 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15162 ? Context.UnsignedLongTy : Context.LongTy; 15163 } else { 15164 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15165 assert(NumPositiveBits <= BestWidth && 15166 "How could an initializer get larger than ULL?"); 15167 BestType = Context.UnsignedLongLongTy; 15168 BestPromotionType 15169 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15170 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15171 } 15172 } 15173 15174 // Loop over all of the enumerator constants, changing their types to match 15175 // the type of the enum if needed. 15176 for (auto *D : Elements) { 15177 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15178 if (!ECD) continue; // Already issued a diagnostic. 15179 15180 // Standard C says the enumerators have int type, but we allow, as an 15181 // extension, the enumerators to be larger than int size. If each 15182 // enumerator value fits in an int, type it as an int, otherwise type it the 15183 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15184 // that X has type 'int', not 'unsigned'. 15185 15186 // Determine whether the value fits into an int. 15187 llvm::APSInt InitVal = ECD->getInitVal(); 15188 15189 // If it fits into an integer type, force it. Otherwise force it to match 15190 // the enum decl type. 15191 QualType NewTy; 15192 unsigned NewWidth; 15193 bool NewSign; 15194 if (!getLangOpts().CPlusPlus && 15195 !Enum->isFixed() && 15196 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15197 NewTy = Context.IntTy; 15198 NewWidth = IntWidth; 15199 NewSign = true; 15200 } else if (ECD->getType() == BestType) { 15201 // Already the right type! 15202 if (getLangOpts().CPlusPlus) 15203 // C++ [dcl.enum]p4: Following the closing brace of an 15204 // enum-specifier, each enumerator has the type of its 15205 // enumeration. 15206 ECD->setType(EnumType); 15207 continue; 15208 } else { 15209 NewTy = BestType; 15210 NewWidth = BestWidth; 15211 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15212 } 15213 15214 // Adjust the APSInt value. 15215 InitVal = InitVal.extOrTrunc(NewWidth); 15216 InitVal.setIsSigned(NewSign); 15217 ECD->setInitVal(InitVal); 15218 15219 // Adjust the Expr initializer and type. 15220 if (ECD->getInitExpr() && 15221 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15222 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15223 CK_IntegralCast, 15224 ECD->getInitExpr(), 15225 /*base paths*/ nullptr, 15226 VK_RValue)); 15227 if (getLangOpts().CPlusPlus) 15228 // C++ [dcl.enum]p4: Following the closing brace of an 15229 // enum-specifier, each enumerator has the type of its 15230 // enumeration. 15231 ECD->setType(EnumType); 15232 else 15233 ECD->setType(NewTy); 15234 } 15235 15236 Enum->completeDefinition(BestType, BestPromotionType, 15237 NumPositiveBits, NumNegativeBits); 15238 15239 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15240 15241 if (Enum->hasAttr<FlagEnumAttr>()) { 15242 for (Decl *D : Elements) { 15243 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15244 if (!ECD) continue; // Already issued a diagnostic. 15245 15246 llvm::APSInt InitVal = ECD->getInitVal(); 15247 if (InitVal != 0 && !InitVal.isPowerOf2() && 15248 !IsValueInFlagEnum(Enum, InitVal, true)) 15249 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15250 << ECD << Enum; 15251 } 15252 } 15253 15254 // Now that the enum type is defined, ensure it's not been underaligned. 15255 if (Enum->hasAttrs()) 15256 CheckAlignasUnderalignment(Enum); 15257 } 15258 15259 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15260 SourceLocation StartLoc, 15261 SourceLocation EndLoc) { 15262 StringLiteral *AsmString = cast<StringLiteral>(expr); 15263 15264 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15265 AsmString, StartLoc, 15266 EndLoc); 15267 CurContext->addDecl(New); 15268 return New; 15269 } 15270 15271 static void checkModuleImportContext(Sema &S, Module *M, 15272 SourceLocation ImportLoc, DeclContext *DC, 15273 bool FromInclude = false) { 15274 SourceLocation ExternCLoc; 15275 15276 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15277 switch (LSD->getLanguage()) { 15278 case LinkageSpecDecl::lang_c: 15279 if (ExternCLoc.isInvalid()) 15280 ExternCLoc = LSD->getLocStart(); 15281 break; 15282 case LinkageSpecDecl::lang_cxx: 15283 break; 15284 } 15285 DC = LSD->getParent(); 15286 } 15287 15288 while (isa<LinkageSpecDecl>(DC)) 15289 DC = DC->getParent(); 15290 15291 if (!isa<TranslationUnitDecl>(DC)) { 15292 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15293 ? diag::ext_module_import_not_at_top_level_noop 15294 : diag::err_module_import_not_at_top_level_fatal) 15295 << M->getFullModuleName() << DC; 15296 S.Diag(cast<Decl>(DC)->getLocStart(), 15297 diag::note_module_import_not_at_top_level) << DC; 15298 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15299 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15300 << M->getFullModuleName(); 15301 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 15302 } 15303 } 15304 15305 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 15306 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 15307 } 15308 15309 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc, 15310 ModuleDeclKind MDK, 15311 ModuleIdPath Path) { 15312 // 'module implementation' requires that we are not compiling a module of any 15313 // kind. 'module' and 'module partition' require that we are compiling a 15314 // module inteface (not a module map). 15315 auto CMK = getLangOpts().getCompilingModule(); 15316 if (MDK == ModuleDeclKind::Implementation 15317 ? CMK != LangOptions::CMK_None 15318 : CMK != LangOptions::CMK_ModuleInterface) { 15319 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15320 << (unsigned)MDK; 15321 return nullptr; 15322 } 15323 15324 // FIXME: Create a ModuleDecl and return it. 15325 15326 // FIXME: Most of this work should be done by the preprocessor rather than 15327 // here, in case we look ahead across something where the current 15328 // module matters (eg a #include). 15329 15330 // The dots in a module name in the Modules TS are a lie. Unlike Clang's 15331 // hierarchical module map modules, the dots here are just another character 15332 // that can appear in a module name. Flatten down to the actual module name. 15333 std::string ModuleName; 15334 for (auto &Piece : Path) { 15335 if (!ModuleName.empty()) 15336 ModuleName += "."; 15337 ModuleName += Piece.first->getName(); 15338 } 15339 15340 // If a module name was explicitly specified on the command line, it must be 15341 // correct. 15342 if (!getLangOpts().CurrentModule.empty() && 15343 getLangOpts().CurrentModule != ModuleName) { 15344 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15345 << SourceRange(Path.front().second, Path.back().second) 15346 << getLangOpts().CurrentModule; 15347 return nullptr; 15348 } 15349 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15350 15351 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15352 15353 switch (MDK) { 15354 case ModuleDeclKind::Module: { 15355 // FIXME: Check we're not in a submodule. 15356 15357 // We can't have imported a definition of this module or parsed a module 15358 // map defining it already. 15359 if (auto *M = Map.findModule(ModuleName)) { 15360 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15361 if (M->DefinitionLoc.isValid()) 15362 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15363 else if (const auto *FE = M->getASTFile()) 15364 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15365 << FE->getName(); 15366 return nullptr; 15367 } 15368 15369 // Create a Module for the module that we're defining. 15370 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15371 assert(Mod && "module creation should not fail"); 15372 15373 // Enter the semantic scope of the module. 15374 ActOnModuleBegin(ModuleLoc, Mod); 15375 return nullptr; 15376 } 15377 15378 case ModuleDeclKind::Partition: 15379 // FIXME: Check we are in a submodule of the named module. 15380 return nullptr; 15381 15382 case ModuleDeclKind::Implementation: 15383 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15384 PP.getIdentifierInfo(ModuleName), Path[0].second); 15385 15386 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15387 if (Import.isInvalid()) 15388 return nullptr; 15389 return ConvertDeclToDeclGroup(Import.get()); 15390 } 15391 15392 llvm_unreachable("unexpected module decl kind"); 15393 } 15394 15395 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15396 SourceLocation ImportLoc, 15397 ModuleIdPath Path) { 15398 Module *Mod = 15399 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15400 /*IsIncludeDirective=*/false); 15401 if (!Mod) 15402 return true; 15403 15404 VisibleModules.setVisible(Mod, ImportLoc); 15405 15406 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15407 15408 // FIXME: we should support importing a submodule within a different submodule 15409 // of the same top-level module. Until we do, make it an error rather than 15410 // silently ignoring the import. 15411 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15412 // warn on a redundant import of the current module? 15413 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15414 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15415 Diag(ImportLoc, getLangOpts().isCompilingModule() 15416 ? diag::err_module_self_import 15417 : diag::err_module_import_in_implementation) 15418 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15419 15420 SmallVector<SourceLocation, 2> IdentifierLocs; 15421 Module *ModCheck = Mod; 15422 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15423 // If we've run out of module parents, just drop the remaining identifiers. 15424 // We need the length to be consistent. 15425 if (!ModCheck) 15426 break; 15427 ModCheck = ModCheck->Parent; 15428 15429 IdentifierLocs.push_back(Path[I].second); 15430 } 15431 15432 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15433 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15434 Mod, IdentifierLocs); 15435 if (!ModuleScopes.empty()) 15436 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15437 TU->addDecl(Import); 15438 return Import; 15439 } 15440 15441 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15442 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15443 BuildModuleInclude(DirectiveLoc, Mod); 15444 } 15445 15446 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15447 // Determine whether we're in the #include buffer for a module. The #includes 15448 // in that buffer do not qualify as module imports; they're just an 15449 // implementation detail of us building the module. 15450 // 15451 // FIXME: Should we even get ActOnModuleInclude calls for those? 15452 bool IsInModuleIncludes = 15453 TUKind == TU_Module && 15454 getSourceManager().isWrittenInMainFile(DirectiveLoc); 15455 15456 bool ShouldAddImport = !IsInModuleIncludes; 15457 15458 // If this module import was due to an inclusion directive, create an 15459 // implicit import declaration to capture it in the AST. 15460 if (ShouldAddImport) { 15461 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15462 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15463 DirectiveLoc, Mod, 15464 DirectiveLoc); 15465 if (!ModuleScopes.empty()) 15466 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 15467 TU->addDecl(ImportD); 15468 Consumer.HandleImplicitImportDecl(ImportD); 15469 } 15470 15471 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 15472 VisibleModules.setVisible(Mod, DirectiveLoc); 15473 } 15474 15475 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 15476 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 15477 15478 ModuleScopes.push_back({}); 15479 ModuleScopes.back().Module = Mod; 15480 if (getLangOpts().ModulesLocalVisibility) 15481 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 15482 15483 VisibleModules.setVisible(Mod, DirectiveLoc); 15484 } 15485 15486 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) { 15487 checkModuleImportContext(*this, Mod, EofLoc, CurContext); 15488 15489 if (getLangOpts().ModulesLocalVisibility) { 15490 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 15491 // Leaving a module hides namespace names, so our visible namespace cache 15492 // is now out of date. 15493 VisibleNamespaceCache.clear(); 15494 } 15495 15496 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 15497 "left the wrong module scope"); 15498 ModuleScopes.pop_back(); 15499 15500 // We got to the end of processing a #include of a local module. Create an 15501 // ImportDecl as we would for an imported module. 15502 FileID File = getSourceManager().getFileID(EofLoc); 15503 assert(File != getSourceManager().getMainFileID() && 15504 "end of submodule in main source file"); 15505 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File); 15506 BuildModuleInclude(DirectiveLoc, Mod); 15507 } 15508 15509 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 15510 Module *Mod) { 15511 // Bail if we're not allowed to implicitly import a module here. 15512 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 15513 return; 15514 15515 // Create the implicit import declaration. 15516 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15517 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 15518 Loc, Mod, Loc); 15519 TU->addDecl(ImportD); 15520 Consumer.HandleImplicitImportDecl(ImportD); 15521 15522 // Make the module visible. 15523 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 15524 VisibleModules.setVisible(Mod, Loc); 15525 } 15526 15527 /// We have parsed the start of an export declaration, including the '{' 15528 /// (if present). 15529 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 15530 SourceLocation LBraceLoc) { 15531 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 15532 15533 // C++ Modules TS draft: 15534 // An export-declaration [...] shall not contain more than one 15535 // export keyword. 15536 // 15537 // The intent here is that an export-declaration cannot appear within another 15538 // export-declaration. 15539 if (D->isExported()) 15540 Diag(ExportLoc, diag::err_export_within_export); 15541 15542 CurContext->addDecl(D); 15543 PushDeclContext(S, D); 15544 return D; 15545 } 15546 15547 /// Complete the definition of an export declaration. 15548 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 15549 auto *ED = cast<ExportDecl>(D); 15550 if (RBraceLoc.isValid()) 15551 ED->setRBraceLoc(RBraceLoc); 15552 15553 // FIXME: Diagnose export of internal-linkage declaration (including 15554 // anonymous namespace). 15555 15556 PopDeclContext(); 15557 return D; 15558 } 15559 15560 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 15561 IdentifierInfo* AliasName, 15562 SourceLocation PragmaLoc, 15563 SourceLocation NameLoc, 15564 SourceLocation AliasNameLoc) { 15565 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 15566 LookupOrdinaryName); 15567 AsmLabelAttr *Attr = 15568 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 15569 15570 // If a declaration that: 15571 // 1) declares a function or a variable 15572 // 2) has external linkage 15573 // already exists, add a label attribute to it. 15574 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15575 if (isDeclExternC(PrevDecl)) 15576 PrevDecl->addAttr(Attr); 15577 else 15578 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 15579 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 15580 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 15581 } else 15582 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 15583 } 15584 15585 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 15586 SourceLocation PragmaLoc, 15587 SourceLocation NameLoc) { 15588 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 15589 15590 if (PrevDecl) { 15591 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 15592 } else { 15593 (void)WeakUndeclaredIdentifiers.insert( 15594 std::pair<IdentifierInfo*,WeakInfo> 15595 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 15596 } 15597 } 15598 15599 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 15600 IdentifierInfo* AliasName, 15601 SourceLocation PragmaLoc, 15602 SourceLocation NameLoc, 15603 SourceLocation AliasNameLoc) { 15604 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 15605 LookupOrdinaryName); 15606 WeakInfo W = WeakInfo(Name, NameLoc); 15607 15608 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 15609 if (!PrevDecl->hasAttr<AliasAttr>()) 15610 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 15611 DeclApplyPragmaWeak(TUScope, ND, W); 15612 } else { 15613 (void)WeakUndeclaredIdentifiers.insert( 15614 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 15615 } 15616 } 15617 15618 Decl *Sema::getObjCDeclContext() const { 15619 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 15620 } 15621