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 "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Parse/ParseDiagnostic.h" 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 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 } 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_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 132 const IdentifierInfo &II, 133 SourceLocation NameLoc) { 134 // Find the first parent class template context, if any. 135 // FIXME: Perform the lookup in all enclosing class templates. 136 const CXXRecordDecl *RD = nullptr; 137 for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) { 138 RD = dyn_cast<CXXRecordDecl>(DC); 139 if (RD && RD->getDescribedClassTemplate()) 140 break; 141 } 142 if (!RD) 143 return ParsedType(); 144 145 // Look for type decls in dependent base classes that have known primary 146 // templates. 147 bool FoundTypeDecl = false; 148 for (const auto &Base : RD->bases()) { 149 auto *TST = Base.getType()->getAs<TemplateSpecializationType>(); 150 if (!TST || !TST->isDependentType()) 151 continue; 152 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 153 if (!TD) 154 continue; 155 auto *BasePrimaryTemplate = 156 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 157 if (!BasePrimaryTemplate) 158 continue; 159 // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly 160 // by calling or integrating with the main LookupQualifiedName mechanism. 161 for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) { 162 if (FoundTypeDecl) 163 return ParsedType(); 164 FoundTypeDecl = isa<TypeDecl>(ND); 165 if (!FoundTypeDecl) 166 return ParsedType(); 167 } 168 } 169 if (!FoundTypeDecl) 170 return ParsedType(); 171 172 // We found some types in dependent base classes. Recover as if the user 173 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 174 // lookup during template instantiation. 175 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 176 177 ASTContext &Context = S.Context; 178 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 179 cast<Type>(Context.getRecordType(RD))); 180 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 181 182 CXXScopeSpec SS; 183 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 184 185 TypeLocBuilder Builder; 186 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 187 DepTL.setNameLoc(NameLoc); 188 DepTL.setElaboratedKeywordLoc(SourceLocation()); 189 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 190 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 191 } 192 193 /// \brief If the identifier refers to a type name within this scope, 194 /// return the declaration of that type. 195 /// 196 /// This routine performs ordinary name lookup of the identifier II 197 /// within the given scope, with optional C++ scope specifier SS, to 198 /// determine whether the name refers to a type. If so, returns an 199 /// opaque pointer (actually a QualType) corresponding to that 200 /// type. Otherwise, returns NULL. 201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 202 Scope *S, CXXScopeSpec *SS, 203 bool isClassName, bool HasTrailingDot, 204 ParsedType ObjectTypePtr, 205 bool IsCtorOrDtorName, 206 bool WantNontrivialTypeSourceInfo, 207 IdentifierInfo **CorrectedII) { 208 // Determine where we will perform name lookup. 209 DeclContext *LookupCtx = nullptr; 210 if (ObjectTypePtr) { 211 QualType ObjectType = ObjectTypePtr.get(); 212 if (ObjectType->isRecordType()) 213 LookupCtx = computeDeclContext(ObjectType); 214 } else if (SS && SS->isNotEmpty()) { 215 LookupCtx = computeDeclContext(*SS, false); 216 217 if (!LookupCtx) { 218 if (isDependentScopeSpecifier(*SS)) { 219 // C++ [temp.res]p3: 220 // A qualified-id that refers to a type and in which the 221 // nested-name-specifier depends on a template-parameter (14.6.2) 222 // shall be prefixed by the keyword typename to indicate that the 223 // qualified-id denotes a type, forming an 224 // elaborated-type-specifier (7.1.5.3). 225 // 226 // We therefore do not perform any name lookup if the result would 227 // refer to a member of an unknown specialization. 228 if (!isClassName && !IsCtorOrDtorName) 229 return ParsedType(); 230 231 // We know from the grammar that this name refers to a type, 232 // so build a dependent node to describe the type. 233 if (WantNontrivialTypeSourceInfo) 234 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 235 236 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 237 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 238 II, NameLoc); 239 return ParsedType::make(T); 240 } 241 242 return ParsedType(); 243 } 244 245 if (!LookupCtx->isDependentContext() && 246 RequireCompleteDeclContext(*SS, LookupCtx)) 247 return ParsedType(); 248 } 249 250 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 251 // lookup for class-names. 252 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 253 LookupOrdinaryName; 254 LookupResult Result(*this, &II, NameLoc, Kind); 255 if (LookupCtx) { 256 // Perform "qualified" name lookup into the declaration context we 257 // computed, which is either the type of the base of a member access 258 // expression or the declaration context associated with a prior 259 // nested-name-specifier. 260 LookupQualifiedName(Result, LookupCtx); 261 262 if (ObjectTypePtr && Result.empty()) { 263 // C++ [basic.lookup.classref]p3: 264 // If the unqualified-id is ~type-name, the type-name is looked up 265 // in the context of the entire postfix-expression. If the type T of 266 // the object expression is of a class type C, the type-name is also 267 // looked up in the scope of class C. At least one of the lookups shall 268 // find a name that refers to (possibly cv-qualified) T. 269 LookupName(Result, S); 270 } 271 } else { 272 // Perform unqualified name lookup. 273 LookupName(Result, S); 274 275 // For unqualified lookup in a class template in MSVC mode, look into 276 // dependent base classes where the primary class template is known. 277 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 278 if (ParsedType TypeInBase = 279 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 280 return TypeInBase; 281 } 282 } 283 284 NamedDecl *IIDecl = nullptr; 285 switch (Result.getResultKind()) { 286 case LookupResult::NotFound: 287 case LookupResult::NotFoundInCurrentInstantiation: 288 if (CorrectedII) { 289 TypeNameValidatorCCC Validator(true, isClassName); 290 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 291 Kind, S, SS, Validator, 292 CTK_ErrorRecovery); 293 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 294 TemplateTy Template; 295 bool MemberOfUnknownSpecialization; 296 UnqualifiedId TemplateName; 297 TemplateName.setIdentifier(NewII, NameLoc); 298 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 299 CXXScopeSpec NewSS, *NewSSPtr = SS; 300 if (SS && NNS) { 301 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 302 NewSSPtr = &NewSS; 303 } 304 if (Correction && (NNS || NewII != &II) && 305 // Ignore a correction to a template type as the to-be-corrected 306 // identifier is not a template (typo correction for template names 307 // is handled elsewhere). 308 !(getLangOpts().CPlusPlus && NewSSPtr && 309 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 310 false, Template, MemberOfUnknownSpecialization))) { 311 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 312 isClassName, HasTrailingDot, ObjectTypePtr, 313 IsCtorOrDtorName, 314 WantNontrivialTypeSourceInfo); 315 if (Ty) { 316 diagnoseTypo(Correction, 317 PDiag(diag::err_unknown_type_or_class_name_suggest) 318 << Result.getLookupName() << isClassName); 319 if (SS && NNS) 320 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 321 *CorrectedII = NewII; 322 return Ty; 323 } 324 } 325 } 326 // If typo correction failed or was not performed, fall through 327 case LookupResult::FoundOverloaded: 328 case LookupResult::FoundUnresolvedValue: 329 Result.suppressDiagnostics(); 330 return ParsedType(); 331 332 case LookupResult::Ambiguous: 333 // Recover from type-hiding ambiguities by hiding the type. We'll 334 // do the lookup again when looking for an object, and we can 335 // diagnose the error then. If we don't do this, then the error 336 // about hiding the type will be immediately followed by an error 337 // that only makes sense if the identifier was treated like a type. 338 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 339 Result.suppressDiagnostics(); 340 return ParsedType(); 341 } 342 343 // Look to see if we have a type anywhere in the list of results. 344 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 345 Res != ResEnd; ++Res) { 346 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 347 if (!IIDecl || 348 (*Res)->getLocation().getRawEncoding() < 349 IIDecl->getLocation().getRawEncoding()) 350 IIDecl = *Res; 351 } 352 } 353 354 if (!IIDecl) { 355 // None of the entities we found is a type, so there is no way 356 // to even assume that the result is a type. In this case, don't 357 // complain about the ambiguity. The parser will either try to 358 // perform this lookup again (e.g., as an object name), which 359 // will produce the ambiguity, or will complain that it expected 360 // a type name. 361 Result.suppressDiagnostics(); 362 return ParsedType(); 363 } 364 365 // We found a type within the ambiguous lookup; diagnose the 366 // ambiguity and then return that type. This might be the right 367 // answer, or it might not be, but it suppresses any attempt to 368 // perform the name lookup again. 369 break; 370 371 case LookupResult::Found: 372 IIDecl = Result.getFoundDecl(); 373 break; 374 } 375 376 assert(IIDecl && "Didn't find decl"); 377 378 QualType T; 379 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 380 DiagnoseUseOfDecl(IIDecl, NameLoc); 381 382 T = Context.getTypeDeclType(TD); 383 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 384 385 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 386 // constructor or destructor name (in such a case, the scope specifier 387 // will be attached to the enclosing Expr or Decl node). 388 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 389 if (WantNontrivialTypeSourceInfo) { 390 // Construct a type with type-source information. 391 TypeLocBuilder Builder; 392 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 393 394 T = getElaboratedType(ETK_None, *SS, T); 395 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 396 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 397 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 398 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 399 } else { 400 T = getElaboratedType(ETK_None, *SS, T); 401 } 402 } 403 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 404 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 405 if (!HasTrailingDot) 406 T = Context.getObjCInterfaceType(IDecl); 407 } 408 409 if (T.isNull()) { 410 // If it's not plausibly a type, suppress diagnostics. 411 Result.suppressDiagnostics(); 412 return ParsedType(); 413 } 414 return ParsedType::make(T); 415 } 416 417 // Builds a fake NNS for the given decl context. 418 static NestedNameSpecifier * 419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 420 for (;; DC = DC->getLookupParent()) { 421 DC = DC->getPrimaryContext(); 422 auto *ND = dyn_cast<NamespaceDecl>(DC); 423 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 424 return NestedNameSpecifier::Create(Context, nullptr, ND); 425 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 426 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 427 RD->getTypeForDecl()); 428 else if (isa<TranslationUnitDecl>(DC)) 429 return NestedNameSpecifier::GlobalSpecifier(Context); 430 } 431 llvm_unreachable("something isn't in TU scope?"); 432 } 433 434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 435 SourceLocation NameLoc) { 436 // Accepting an undeclared identifier as a default argument for a template 437 // type parameter is a Microsoft extension. 438 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 439 440 // Build a fake DependentNameType that will perform lookup into CurContext at 441 // instantiation time. The name specifier isn't dependent, so template 442 // instantiation won't transform it. It will retry the lookup, however. 443 NestedNameSpecifier *NNS = 444 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 445 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 446 447 // Build type location information. We synthesized the qualifier, so we have 448 // to build a fake NestedNameSpecifierLoc. 449 NestedNameSpecifierLocBuilder NNSLocBuilder; 450 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 451 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 452 453 TypeLocBuilder Builder; 454 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 455 DepTL.setNameLoc(NameLoc); 456 DepTL.setElaboratedKeywordLoc(SourceLocation()); 457 DepTL.setQualifierLoc(QualifierLoc); 458 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 459 } 460 461 /// isTagName() - This method is called *for error recovery purposes only* 462 /// to determine if the specified name is a valid tag name ("struct foo"). If 463 /// so, this returns the TST for the tag corresponding to it (TST_enum, 464 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 465 /// cases in C where the user forgot to specify the tag. 466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 467 // Do a tag name lookup in this scope. 468 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 469 LookupName(R, S, false); 470 R.suppressDiagnostics(); 471 if (R.getResultKind() == LookupResult::Found) 472 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 473 switch (TD->getTagKind()) { 474 case TTK_Struct: return DeclSpec::TST_struct; 475 case TTK_Interface: return DeclSpec::TST_interface; 476 case TTK_Union: return DeclSpec::TST_union; 477 case TTK_Class: return DeclSpec::TST_class; 478 case TTK_Enum: return DeclSpec::TST_enum; 479 } 480 } 481 482 return DeclSpec::TST_unspecified; 483 } 484 485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 487 /// then downgrade the missing typename error to a warning. 488 /// This is needed for MSVC compatibility; Example: 489 /// @code 490 /// template<class T> class A { 491 /// public: 492 /// typedef int TYPE; 493 /// }; 494 /// template<class T> class B : public A<T> { 495 /// public: 496 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 497 /// }; 498 /// @endcode 499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 500 if (CurContext->isRecord()) { 501 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 502 return true; 503 504 const Type *Ty = SS->getScopeRep()->getAsType(); 505 506 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 507 for (const auto &Base : RD->bases()) 508 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 509 return true; 510 return S->isFunctionPrototypeScope(); 511 } 512 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 513 } 514 515 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 516 SourceLocation IILoc, 517 Scope *S, 518 CXXScopeSpec *SS, 519 ParsedType &SuggestedType, 520 bool AllowClassTemplates) { 521 // We don't have anything to suggest (yet). 522 SuggestedType = ParsedType(); 523 524 // There may have been a typo in the name of the type. Look up typo 525 // results, in case we have something that we can suggest. 526 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 527 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 528 LookupOrdinaryName, S, SS, 529 Validator, CTK_ErrorRecovery)) { 530 if (Corrected.isKeyword()) { 531 // We corrected to a keyword. 532 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 533 II = Corrected.getCorrectionAsIdentifierInfo(); 534 } else { 535 // We found a similarly-named type or interface; suggest that. 536 if (!SS || !SS->isSet()) { 537 diagnoseTypo(Corrected, 538 PDiag(diag::err_unknown_typename_suggest) << II); 539 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 540 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 541 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 542 II->getName().equals(CorrectedStr); 543 diagnoseTypo(Corrected, 544 PDiag(diag::err_unknown_nested_typename_suggest) 545 << II << DC << DroppedSpecifier << SS->getRange()); 546 } else { 547 llvm_unreachable("could not have corrected a typo here"); 548 } 549 550 CXXScopeSpec tmpSS; 551 if (Corrected.getCorrectionSpecifier()) 552 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 553 SourceRange(IILoc)); 554 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 555 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 556 false, ParsedType(), 557 /*IsCtorOrDtorName=*/false, 558 /*NonTrivialTypeSourceInfo=*/true); 559 } 560 return; 561 } 562 563 if (getLangOpts().CPlusPlus) { 564 // See if II is a class template that the user forgot to pass arguments to. 565 UnqualifiedId Name; 566 Name.setIdentifier(II, IILoc); 567 CXXScopeSpec EmptySS; 568 TemplateTy TemplateResult; 569 bool MemberOfUnknownSpecialization; 570 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 571 Name, ParsedType(), true, TemplateResult, 572 MemberOfUnknownSpecialization) == TNK_Type_template) { 573 TemplateName TplName = TemplateResult.get(); 574 Diag(IILoc, diag::err_template_missing_args) << TplName; 575 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 576 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 577 << TplDecl->getTemplateParameters()->getSourceRange(); 578 } 579 return; 580 } 581 } 582 583 // FIXME: Should we move the logic that tries to recover from a missing tag 584 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 585 586 if (!SS || (!SS->isSet() && !SS->isInvalid())) 587 Diag(IILoc, diag::err_unknown_typename) << II; 588 else if (DeclContext *DC = computeDeclContext(*SS, false)) 589 Diag(IILoc, diag::err_typename_nested_not_found) 590 << II << DC << SS->getRange(); 591 else if (isDependentScopeSpecifier(*SS)) { 592 unsigned DiagID = diag::err_typename_missing; 593 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 594 DiagID = diag::ext_typename_missing; 595 596 Diag(SS->getRange().getBegin(), DiagID) 597 << SS->getScopeRep() << II->getName() 598 << SourceRange(SS->getRange().getBegin(), IILoc) 599 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 600 SuggestedType = ActOnTypenameType(S, SourceLocation(), 601 *SS, *II, IILoc).get(); 602 } else { 603 assert(SS && SS->isInvalid() && 604 "Invalid scope specifier has already been diagnosed"); 605 } 606 } 607 608 /// \brief Determine whether the given result set contains either a type name 609 /// or 610 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 611 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 612 NextToken.is(tok::less); 613 614 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 615 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 616 return true; 617 618 if (CheckTemplate && isa<TemplateDecl>(*I)) 619 return true; 620 } 621 622 return false; 623 } 624 625 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 626 Scope *S, CXXScopeSpec &SS, 627 IdentifierInfo *&Name, 628 SourceLocation NameLoc) { 629 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 630 SemaRef.LookupParsedName(R, S, &SS); 631 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 632 StringRef FixItTagName; 633 switch (Tag->getTagKind()) { 634 case TTK_Class: 635 FixItTagName = "class "; 636 break; 637 638 case TTK_Enum: 639 FixItTagName = "enum "; 640 break; 641 642 case TTK_Struct: 643 FixItTagName = "struct "; 644 break; 645 646 case TTK_Interface: 647 FixItTagName = "__interface "; 648 break; 649 650 case TTK_Union: 651 FixItTagName = "union "; 652 break; 653 } 654 655 StringRef TagName = FixItTagName.drop_back(); 656 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 657 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 658 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 659 660 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 661 I != IEnd; ++I) 662 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 663 << Name << TagName; 664 665 // Replace lookup results with just the tag decl. 666 Result.clear(Sema::LookupTagName); 667 SemaRef.LookupParsedName(Result, S, &SS); 668 return true; 669 } 670 671 return false; 672 } 673 674 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 675 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 676 QualType T, SourceLocation NameLoc) { 677 ASTContext &Context = S.Context; 678 679 TypeLocBuilder Builder; 680 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 681 682 T = S.getElaboratedType(ETK_None, SS, T); 683 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 684 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 685 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 686 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 687 } 688 689 Sema::NameClassification Sema::ClassifyName(Scope *S, 690 CXXScopeSpec &SS, 691 IdentifierInfo *&Name, 692 SourceLocation NameLoc, 693 const Token &NextToken, 694 bool IsAddressOfOperand, 695 CorrectionCandidateCallback *CCC) { 696 DeclarationNameInfo NameInfo(Name, NameLoc); 697 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 698 699 if (NextToken.is(tok::coloncolon)) { 700 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 701 QualType(), false, SS, nullptr, false); 702 } 703 704 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 705 LookupParsedName(Result, S, &SS, !CurMethod); 706 707 // For unqualified lookup in a class template in MSVC mode, look into 708 // dependent base classes where the primary class template is known. 709 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 710 if (ParsedType TypeInBase = 711 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 712 return TypeInBase; 713 } 714 715 // Perform lookup for Objective-C instance variables (including automatically 716 // synthesized instance variables), if we're in an Objective-C method. 717 // FIXME: This lookup really, really needs to be folded in to the normal 718 // unqualified lookup mechanism. 719 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 720 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 721 if (E.get() || E.isInvalid()) 722 return E; 723 } 724 725 bool SecondTry = false; 726 bool IsFilteredTemplateName = false; 727 728 Corrected: 729 switch (Result.getResultKind()) { 730 case LookupResult::NotFound: 731 // If an unqualified-id is followed by a '(', then we have a function 732 // call. 733 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 734 // In C++, this is an ADL-only call. 735 // FIXME: Reference? 736 if (getLangOpts().CPlusPlus) 737 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 738 739 // C90 6.3.2.2: 740 // If the expression that precedes the parenthesized argument list in a 741 // function call consists solely of an identifier, and if no 742 // declaration is visible for this identifier, the identifier is 743 // implicitly declared exactly as if, in the innermost block containing 744 // the function call, the declaration 745 // 746 // extern int identifier (); 747 // 748 // appeared. 749 // 750 // We also allow this in C99 as an extension. 751 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 752 Result.addDecl(D); 753 Result.resolveKind(); 754 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 755 } 756 } 757 758 // In C, we first see whether there is a tag type by the same name, in 759 // which case it's likely that the user just forget to write "enum", 760 // "struct", or "union". 761 if (!getLangOpts().CPlusPlus && !SecondTry && 762 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 763 break; 764 } 765 766 // Perform typo correction to determine if there is another name that is 767 // close to this name. 768 if (!SecondTry && CCC) { 769 SecondTry = true; 770 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 771 Result.getLookupKind(), S, 772 &SS, *CCC, 773 CTK_ErrorRecovery)) { 774 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 775 unsigned QualifiedDiag = diag::err_no_member_suggest; 776 777 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 778 NamedDecl *UnderlyingFirstDecl 779 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 780 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 781 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 782 UnqualifiedDiag = diag::err_no_template_suggest; 783 QualifiedDiag = diag::err_no_member_template_suggest; 784 } else if (UnderlyingFirstDecl && 785 (isa<TypeDecl>(UnderlyingFirstDecl) || 786 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 787 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 788 UnqualifiedDiag = diag::err_unknown_typename_suggest; 789 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 790 } 791 792 if (SS.isEmpty()) { 793 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 794 } else {// FIXME: is this even reachable? Test it. 795 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 796 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 797 Name->getName().equals(CorrectedStr); 798 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 799 << Name << computeDeclContext(SS, false) 800 << DroppedSpecifier << SS.getRange()); 801 } 802 803 // Update the name, so that the caller has the new name. 804 Name = Corrected.getCorrectionAsIdentifierInfo(); 805 806 // Typo correction corrected to a keyword. 807 if (Corrected.isKeyword()) 808 return Name; 809 810 // Also update the LookupResult... 811 // FIXME: This should probably go away at some point 812 Result.clear(); 813 Result.setLookupName(Corrected.getCorrection()); 814 if (FirstDecl) 815 Result.addDecl(FirstDecl); 816 817 // If we found an Objective-C instance variable, let 818 // LookupInObjCMethod build the appropriate expression to 819 // reference the ivar. 820 // FIXME: This is a gross hack. 821 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 822 Result.clear(); 823 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 824 return E; 825 } 826 827 goto Corrected; 828 } 829 } 830 831 // We failed to correct; just fall through and let the parser deal with it. 832 Result.suppressDiagnostics(); 833 return NameClassification::Unknown(); 834 835 case LookupResult::NotFoundInCurrentInstantiation: { 836 // We performed name lookup into the current instantiation, and there were 837 // dependent bases, so we treat this result the same way as any other 838 // dependent nested-name-specifier. 839 840 // C++ [temp.res]p2: 841 // A name used in a template declaration or definition and that is 842 // dependent on a template-parameter is assumed not to name a type 843 // unless the applicable name lookup finds a type name or the name is 844 // qualified by the keyword typename. 845 // 846 // FIXME: If the next token is '<', we might want to ask the parser to 847 // perform some heroics to see if we actually have a 848 // template-argument-list, which would indicate a missing 'template' 849 // keyword here. 850 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 851 NameInfo, IsAddressOfOperand, 852 /*TemplateArgs=*/nullptr); 853 } 854 855 case LookupResult::Found: 856 case LookupResult::FoundOverloaded: 857 case LookupResult::FoundUnresolvedValue: 858 break; 859 860 case LookupResult::Ambiguous: 861 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 862 hasAnyAcceptableTemplateNames(Result)) { 863 // C++ [temp.local]p3: 864 // A lookup that finds an injected-class-name (10.2) can result in an 865 // ambiguity in certain cases (for example, if it is found in more than 866 // one base class). If all of the injected-class-names that are found 867 // refer to specializations of the same class template, and if the name 868 // is followed by a template-argument-list, the reference refers to the 869 // class template itself and not a specialization thereof, and is not 870 // ambiguous. 871 // 872 // This filtering can make an ambiguous result into an unambiguous one, 873 // so try again after filtering out template names. 874 FilterAcceptableTemplateNames(Result); 875 if (!Result.isAmbiguous()) { 876 IsFilteredTemplateName = true; 877 break; 878 } 879 } 880 881 // Diagnose the ambiguity and return an error. 882 return NameClassification::Error(); 883 } 884 885 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 886 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 887 // C++ [temp.names]p3: 888 // After name lookup (3.4) finds that a name is a template-name or that 889 // an operator-function-id or a literal- operator-id refers to a set of 890 // overloaded functions any member of which is a function template if 891 // this is followed by a <, the < is always taken as the delimiter of a 892 // template-argument-list and never as the less-than operator. 893 if (!IsFilteredTemplateName) 894 FilterAcceptableTemplateNames(Result); 895 896 if (!Result.empty()) { 897 bool IsFunctionTemplate; 898 bool IsVarTemplate; 899 TemplateName Template; 900 if (Result.end() - Result.begin() > 1) { 901 IsFunctionTemplate = true; 902 Template = Context.getOverloadedTemplateName(Result.begin(), 903 Result.end()); 904 } else { 905 TemplateDecl *TD 906 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 907 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 908 IsVarTemplate = isa<VarTemplateDecl>(TD); 909 910 if (SS.isSet() && !SS.isInvalid()) 911 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 912 /*TemplateKeyword=*/false, 913 TD); 914 else 915 Template = TemplateName(TD); 916 } 917 918 if (IsFunctionTemplate) { 919 // Function templates always go through overload resolution, at which 920 // point we'll perform the various checks (e.g., accessibility) we need 921 // to based on which function we selected. 922 Result.suppressDiagnostics(); 923 924 return NameClassification::FunctionTemplate(Template); 925 } 926 927 return IsVarTemplate ? NameClassification::VarTemplate(Template) 928 : NameClassification::TypeTemplate(Template); 929 } 930 } 931 932 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 933 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 934 DiagnoseUseOfDecl(Type, NameLoc); 935 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 936 QualType T = Context.getTypeDeclType(Type); 937 if (SS.isNotEmpty()) 938 return buildNestedType(*this, SS, T, NameLoc); 939 return ParsedType::make(T); 940 } 941 942 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 943 if (!Class) { 944 // FIXME: It's unfortunate that we don't have a Type node for handling this. 945 if (ObjCCompatibleAliasDecl *Alias = 946 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 947 Class = Alias->getClassInterface(); 948 } 949 950 if (Class) { 951 DiagnoseUseOfDecl(Class, NameLoc); 952 953 if (NextToken.is(tok::period)) { 954 // Interface. <something> is parsed as a property reference expression. 955 // Just return "unknown" as a fall-through for now. 956 Result.suppressDiagnostics(); 957 return NameClassification::Unknown(); 958 } 959 960 QualType T = Context.getObjCInterfaceType(Class); 961 return ParsedType::make(T); 962 } 963 964 // We can have a type template here if we're classifying a template argument. 965 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 966 return NameClassification::TypeTemplate( 967 TemplateName(cast<TemplateDecl>(FirstDecl))); 968 969 // Check for a tag type hidden by a non-type decl in a few cases where it 970 // seems likely a type is wanted instead of the non-type that was found. 971 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 972 if ((NextToken.is(tok::identifier) || 973 (NextIsOp && 974 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 975 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 976 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 977 DiagnoseUseOfDecl(Type, NameLoc); 978 QualType T = Context.getTypeDeclType(Type); 979 if (SS.isNotEmpty()) 980 return buildNestedType(*this, SS, T, NameLoc); 981 return ParsedType::make(T); 982 } 983 984 if (FirstDecl->isCXXClassMember()) 985 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 986 nullptr); 987 988 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 989 return BuildDeclarationNameExpr(SS, Result, ADL); 990 } 991 992 // Determines the context to return to after temporarily entering a 993 // context. This depends in an unnecessarily complicated way on the 994 // exact ordering of callbacks from the parser. 995 DeclContext *Sema::getContainingDC(DeclContext *DC) { 996 997 // Functions defined inline within classes aren't parsed until we've 998 // finished parsing the top-level class, so the top-level class is 999 // the context we'll need to return to. 1000 // A Lambda call operator whose parent is a class must not be treated 1001 // as an inline member function. A Lambda can be used legally 1002 // either as an in-class member initializer or a default argument. These 1003 // are parsed once the class has been marked complete and so the containing 1004 // context would be the nested class (when the lambda is defined in one); 1005 // If the class is not complete, then the lambda is being used in an 1006 // ill-formed fashion (such as to specify the width of a bit-field, or 1007 // in an array-bound) - in which case we still want to return the 1008 // lexically containing DC (which could be a nested class). 1009 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1010 DC = DC->getLexicalParent(); 1011 1012 // A function not defined within a class will always return to its 1013 // lexical context. 1014 if (!isa<CXXRecordDecl>(DC)) 1015 return DC; 1016 1017 // A C++ inline method/friend is parsed *after* the topmost class 1018 // it was declared in is fully parsed ("complete"); the topmost 1019 // class is the context we need to return to. 1020 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1021 DC = RD; 1022 1023 // Return the declaration context of the topmost class the inline method is 1024 // declared in. 1025 return DC; 1026 } 1027 1028 return DC->getLexicalParent(); 1029 } 1030 1031 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1032 assert(getContainingDC(DC) == CurContext && 1033 "The next DeclContext should be lexically contained in the current one."); 1034 CurContext = DC; 1035 S->setEntity(DC); 1036 } 1037 1038 void Sema::PopDeclContext() { 1039 assert(CurContext && "DeclContext imbalance!"); 1040 1041 CurContext = getContainingDC(CurContext); 1042 assert(CurContext && "Popped translation unit!"); 1043 } 1044 1045 /// EnterDeclaratorContext - Used when we must lookup names in the context 1046 /// of a declarator's nested name specifier. 1047 /// 1048 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1049 // C++0x [basic.lookup.unqual]p13: 1050 // A name used in the definition of a static data member of class 1051 // X (after the qualified-id of the static member) is looked up as 1052 // if the name was used in a member function of X. 1053 // C++0x [basic.lookup.unqual]p14: 1054 // If a variable member of a namespace is defined outside of the 1055 // scope of its namespace then any name used in the definition of 1056 // the variable member (after the declarator-id) is looked up as 1057 // if the definition of the variable member occurred in its 1058 // namespace. 1059 // Both of these imply that we should push a scope whose context 1060 // is the semantic context of the declaration. We can't use 1061 // PushDeclContext here because that context is not necessarily 1062 // lexically contained in the current context. Fortunately, 1063 // the containing scope should have the appropriate information. 1064 1065 assert(!S->getEntity() && "scope already has entity"); 1066 1067 #ifndef NDEBUG 1068 Scope *Ancestor = S->getParent(); 1069 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1070 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1071 #endif 1072 1073 CurContext = DC; 1074 S->setEntity(DC); 1075 } 1076 1077 void Sema::ExitDeclaratorContext(Scope *S) { 1078 assert(S->getEntity() == CurContext && "Context imbalance!"); 1079 1080 // Switch back to the lexical context. The safety of this is 1081 // enforced by an assert in EnterDeclaratorContext. 1082 Scope *Ancestor = S->getParent(); 1083 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1084 CurContext = Ancestor->getEntity(); 1085 1086 // We don't need to do anything with the scope, which is going to 1087 // disappear. 1088 } 1089 1090 1091 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1092 // We assume that the caller has already called 1093 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1094 FunctionDecl *FD = D->getAsFunction(); 1095 if (!FD) 1096 return; 1097 1098 // Same implementation as PushDeclContext, but enters the context 1099 // from the lexical parent, rather than the top-level class. 1100 assert(CurContext == FD->getLexicalParent() && 1101 "The next DeclContext should be lexically contained in the current one."); 1102 CurContext = FD; 1103 S->setEntity(CurContext); 1104 1105 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1106 ParmVarDecl *Param = FD->getParamDecl(P); 1107 // If the parameter has an identifier, then add it to the scope 1108 if (Param->getIdentifier()) { 1109 S->AddDecl(Param); 1110 IdResolver.AddDecl(Param); 1111 } 1112 } 1113 } 1114 1115 1116 void Sema::ActOnExitFunctionContext() { 1117 // Same implementation as PopDeclContext, but returns to the lexical parent, 1118 // rather than the top-level class. 1119 assert(CurContext && "DeclContext imbalance!"); 1120 CurContext = CurContext->getLexicalParent(); 1121 assert(CurContext && "Popped translation unit!"); 1122 } 1123 1124 1125 /// \brief Determine whether we allow overloading of the function 1126 /// PrevDecl with another declaration. 1127 /// 1128 /// This routine determines whether overloading is possible, not 1129 /// whether some new function is actually an overload. It will return 1130 /// true in C++ (where we can always provide overloads) or, as an 1131 /// extension, in C when the previous function is already an 1132 /// overloaded function declaration or has the "overloadable" 1133 /// attribute. 1134 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1135 ASTContext &Context) { 1136 if (Context.getLangOpts().CPlusPlus) 1137 return true; 1138 1139 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1140 return true; 1141 1142 return (Previous.getResultKind() == LookupResult::Found 1143 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1144 } 1145 1146 /// Add this decl to the scope shadowed decl chains. 1147 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1148 // Move up the scope chain until we find the nearest enclosing 1149 // non-transparent context. The declaration will be introduced into this 1150 // scope. 1151 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1152 S = S->getParent(); 1153 1154 // Add scoped declarations into their context, so that they can be 1155 // found later. Declarations without a context won't be inserted 1156 // into any context. 1157 if (AddToContext) 1158 CurContext->addDecl(D); 1159 1160 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1161 // are function-local declarations. 1162 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1163 !D->getDeclContext()->getRedeclContext()->Equals( 1164 D->getLexicalDeclContext()->getRedeclContext()) && 1165 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1166 return; 1167 1168 // Template instantiations should also not be pushed into scope. 1169 if (isa<FunctionDecl>(D) && 1170 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1171 return; 1172 1173 // If this replaces anything in the current scope, 1174 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1175 IEnd = IdResolver.end(); 1176 for (; I != IEnd; ++I) { 1177 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1178 S->RemoveDecl(*I); 1179 IdResolver.RemoveDecl(*I); 1180 1181 // Should only need to replace one decl. 1182 break; 1183 } 1184 } 1185 1186 S->AddDecl(D); 1187 1188 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1189 // Implicitly-generated labels may end up getting generated in an order that 1190 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1191 // the label at the appropriate place in the identifier chain. 1192 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1193 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1194 if (IDC == CurContext) { 1195 if (!S->isDeclScope(*I)) 1196 continue; 1197 } else if (IDC->Encloses(CurContext)) 1198 break; 1199 } 1200 1201 IdResolver.InsertDeclAfter(I, D); 1202 } else { 1203 IdResolver.AddDecl(D); 1204 } 1205 } 1206 1207 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1208 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1209 TUScope->AddDecl(D); 1210 } 1211 1212 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1213 bool AllowInlineNamespace) { 1214 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1215 } 1216 1217 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1218 DeclContext *TargetDC = DC->getPrimaryContext(); 1219 do { 1220 if (DeclContext *ScopeDC = S->getEntity()) 1221 if (ScopeDC->getPrimaryContext() == TargetDC) 1222 return S; 1223 } while ((S = S->getParent())); 1224 1225 return nullptr; 1226 } 1227 1228 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1229 DeclContext*, 1230 ASTContext&); 1231 1232 /// Filters out lookup results that don't fall within the given scope 1233 /// as determined by isDeclInScope. 1234 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1235 bool ConsiderLinkage, 1236 bool AllowInlineNamespace) { 1237 LookupResult::Filter F = R.makeFilter(); 1238 while (F.hasNext()) { 1239 NamedDecl *D = F.next(); 1240 1241 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1242 continue; 1243 1244 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1245 continue; 1246 1247 F.erase(); 1248 } 1249 1250 F.done(); 1251 } 1252 1253 static bool isUsingDecl(NamedDecl *D) { 1254 return isa<UsingShadowDecl>(D) || 1255 isa<UnresolvedUsingTypenameDecl>(D) || 1256 isa<UnresolvedUsingValueDecl>(D); 1257 } 1258 1259 /// Removes using shadow declarations from the lookup results. 1260 static void RemoveUsingDecls(LookupResult &R) { 1261 LookupResult::Filter F = R.makeFilter(); 1262 while (F.hasNext()) 1263 if (isUsingDecl(F.next())) 1264 F.erase(); 1265 1266 F.done(); 1267 } 1268 1269 /// \brief Check for this common pattern: 1270 /// @code 1271 /// class S { 1272 /// S(const S&); // DO NOT IMPLEMENT 1273 /// void operator=(const S&); // DO NOT IMPLEMENT 1274 /// }; 1275 /// @endcode 1276 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1277 // FIXME: Should check for private access too but access is set after we get 1278 // the decl here. 1279 if (D->doesThisDeclarationHaveABody()) 1280 return false; 1281 1282 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1283 return CD->isCopyConstructor(); 1284 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1285 return Method->isCopyAssignmentOperator(); 1286 return false; 1287 } 1288 1289 // We need this to handle 1290 // 1291 // typedef struct { 1292 // void *foo() { return 0; } 1293 // } A; 1294 // 1295 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1296 // for example. If 'A', foo will have external linkage. If we have '*A', 1297 // foo will have no linkage. Since we can't know until we get to the end 1298 // of the typedef, this function finds out if D might have non-external linkage. 1299 // Callers should verify at the end of the TU if it D has external linkage or 1300 // not. 1301 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1302 const DeclContext *DC = D->getDeclContext(); 1303 while (!DC->isTranslationUnit()) { 1304 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1305 if (!RD->hasNameForLinkage()) 1306 return true; 1307 } 1308 DC = DC->getParent(); 1309 } 1310 1311 return !D->isExternallyVisible(); 1312 } 1313 1314 // FIXME: This needs to be refactored; some other isInMainFile users want 1315 // these semantics. 1316 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1317 if (S.TUKind != TU_Complete) 1318 return false; 1319 return S.SourceMgr.isInMainFile(Loc); 1320 } 1321 1322 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1323 assert(D); 1324 1325 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1326 return false; 1327 1328 // Ignore all entities declared within templates, and out-of-line definitions 1329 // of members of class templates. 1330 if (D->getDeclContext()->isDependentContext() || 1331 D->getLexicalDeclContext()->isDependentContext()) 1332 return false; 1333 1334 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1335 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1336 return false; 1337 1338 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1339 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1340 return false; 1341 } else { 1342 // 'static inline' functions are defined in headers; don't warn. 1343 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1344 return false; 1345 } 1346 1347 if (FD->doesThisDeclarationHaveABody() && 1348 Context.DeclMustBeEmitted(FD)) 1349 return false; 1350 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1351 // Constants and utility variables are defined in headers with internal 1352 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1353 // like "inline".) 1354 if (!isMainFileLoc(*this, VD->getLocation())) 1355 return false; 1356 1357 if (Context.DeclMustBeEmitted(VD)) 1358 return false; 1359 1360 if (VD->isStaticDataMember() && 1361 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1362 return false; 1363 } else { 1364 return false; 1365 } 1366 1367 // Only warn for unused decls internal to the translation unit. 1368 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1369 // for inline functions defined in the main source file, for instance. 1370 return mightHaveNonExternalLinkage(D); 1371 } 1372 1373 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1374 if (!D) 1375 return; 1376 1377 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1378 const FunctionDecl *First = FD->getFirstDecl(); 1379 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1380 return; // First should already be in the vector. 1381 } 1382 1383 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1384 const VarDecl *First = VD->getFirstDecl(); 1385 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1386 return; // First should already be in the vector. 1387 } 1388 1389 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1390 UnusedFileScopedDecls.push_back(D); 1391 } 1392 1393 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1394 if (D->isInvalidDecl()) 1395 return false; 1396 1397 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1398 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1399 return false; 1400 1401 if (isa<LabelDecl>(D)) 1402 return true; 1403 1404 // Except for labels, we only care about unused decls that are local to 1405 // functions. 1406 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1407 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1408 // For dependent types, the diagnostic is deferred. 1409 WithinFunction = 1410 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1411 if (!WithinFunction) 1412 return false; 1413 1414 if (isa<TypedefNameDecl>(D)) 1415 return true; 1416 1417 // White-list anything that isn't a local variable. 1418 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1419 return false; 1420 1421 // Types of valid local variables should be complete, so this should succeed. 1422 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1423 1424 // White-list anything with an __attribute__((unused)) type. 1425 QualType Ty = VD->getType(); 1426 1427 // Only look at the outermost level of typedef. 1428 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1429 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1430 return false; 1431 } 1432 1433 // If we failed to complete the type for some reason, or if the type is 1434 // dependent, don't diagnose the variable. 1435 if (Ty->isIncompleteType() || Ty->isDependentType()) 1436 return false; 1437 1438 if (const TagType *TT = Ty->getAs<TagType>()) { 1439 const TagDecl *Tag = TT->getDecl(); 1440 if (Tag->hasAttr<UnusedAttr>()) 1441 return false; 1442 1443 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1444 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1445 return false; 1446 1447 if (const Expr *Init = VD->getInit()) { 1448 if (const ExprWithCleanups *Cleanups = 1449 dyn_cast<ExprWithCleanups>(Init)) 1450 Init = Cleanups->getSubExpr(); 1451 const CXXConstructExpr *Construct = 1452 dyn_cast<CXXConstructExpr>(Init); 1453 if (Construct && !Construct->isElidable()) { 1454 CXXConstructorDecl *CD = Construct->getConstructor(); 1455 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1456 return false; 1457 } 1458 } 1459 } 1460 } 1461 1462 // TODO: __attribute__((unused)) templates? 1463 } 1464 1465 return true; 1466 } 1467 1468 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1469 FixItHint &Hint) { 1470 if (isa<LabelDecl>(D)) { 1471 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1472 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1473 if (AfterColon.isInvalid()) 1474 return; 1475 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1476 getCharRange(D->getLocStart(), AfterColon)); 1477 } 1478 return; 1479 } 1480 1481 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1482 if (D->getTypeForDecl()->isDependentType()) 1483 return; 1484 1485 for (auto *TmpD : D->decls()) { 1486 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1487 DiagnoseUnusedDecl(T); 1488 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1489 DiagnoseUnusedNestedTypedefs(R); 1490 } 1491 } 1492 1493 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1494 /// unless they are marked attr(unused). 1495 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1496 if (!ShouldDiagnoseUnusedDecl(D)) 1497 return; 1498 1499 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1500 // typedefs can be referenced later on, so the diagnostics are emitted 1501 // at end-of-translation-unit. 1502 UnusedLocalTypedefNameCandidates.insert(TD); 1503 return; 1504 } 1505 1506 FixItHint Hint; 1507 GenerateFixForUnusedDecl(D, Context, Hint); 1508 1509 unsigned DiagID; 1510 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1511 DiagID = diag::warn_unused_exception_param; 1512 else if (isa<LabelDecl>(D)) 1513 DiagID = diag::warn_unused_label; 1514 else 1515 DiagID = diag::warn_unused_variable; 1516 1517 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1518 } 1519 1520 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1521 // Verify that we have no forward references left. If so, there was a goto 1522 // or address of a label taken, but no definition of it. Label fwd 1523 // definitions are indicated with a null substmt which is also not a resolved 1524 // MS inline assembly label name. 1525 bool Diagnose = false; 1526 if (L->isMSAsmLabel()) 1527 Diagnose = !L->isResolvedMSAsmLabel(); 1528 else 1529 Diagnose = L->getStmt() == nullptr; 1530 if (Diagnose) 1531 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1532 } 1533 1534 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1535 S->mergeNRVOIntoParent(); 1536 1537 if (S->decl_empty()) return; 1538 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1539 "Scope shouldn't contain decls!"); 1540 1541 for (auto *TmpD : S->decls()) { 1542 assert(TmpD && "This decl didn't get pushed??"); 1543 1544 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1545 NamedDecl *D = cast<NamedDecl>(TmpD); 1546 1547 if (!D->getDeclName()) continue; 1548 1549 // Diagnose unused variables in this scope. 1550 if (!S->hasUnrecoverableErrorOccurred()) { 1551 DiagnoseUnusedDecl(D); 1552 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1553 DiagnoseUnusedNestedTypedefs(RD); 1554 } 1555 1556 // If this was a forward reference to a label, verify it was defined. 1557 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1558 CheckPoppedLabel(LD, *this); 1559 1560 // Remove this name from our lexical scope. 1561 IdResolver.RemoveDecl(D); 1562 } 1563 } 1564 1565 /// \brief Look for an Objective-C class in the translation unit. 1566 /// 1567 /// \param Id The name of the Objective-C class we're looking for. If 1568 /// typo-correction fixes this name, the Id will be updated 1569 /// to the fixed name. 1570 /// 1571 /// \param IdLoc The location of the name in the translation unit. 1572 /// 1573 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1574 /// if there is no class with the given name. 1575 /// 1576 /// \returns The declaration of the named Objective-C class, or NULL if the 1577 /// class could not be found. 1578 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1579 SourceLocation IdLoc, 1580 bool DoTypoCorrection) { 1581 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1582 // creation from this context. 1583 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1584 1585 if (!IDecl && DoTypoCorrection) { 1586 // Perform typo correction at the given location, but only if we 1587 // find an Objective-C class name. 1588 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1589 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1590 LookupOrdinaryName, TUScope, nullptr, 1591 Validator, CTK_ErrorRecovery)) { 1592 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1593 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1594 Id = IDecl->getIdentifier(); 1595 } 1596 } 1597 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1598 // This routine must always return a class definition, if any. 1599 if (Def && Def->getDefinition()) 1600 Def = Def->getDefinition(); 1601 return Def; 1602 } 1603 1604 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1605 /// from S, where a non-field would be declared. This routine copes 1606 /// with the difference between C and C++ scoping rules in structs and 1607 /// unions. For example, the following code is well-formed in C but 1608 /// ill-formed in C++: 1609 /// @code 1610 /// struct S6 { 1611 /// enum { BAR } e; 1612 /// }; 1613 /// 1614 /// void test_S6() { 1615 /// struct S6 a; 1616 /// a.e = BAR; 1617 /// } 1618 /// @endcode 1619 /// For the declaration of BAR, this routine will return a different 1620 /// scope. The scope S will be the scope of the unnamed enumeration 1621 /// within S6. In C++, this routine will return the scope associated 1622 /// with S6, because the enumeration's scope is a transparent 1623 /// context but structures can contain non-field names. In C, this 1624 /// routine will return the translation unit scope, since the 1625 /// enumeration's scope is a transparent context and structures cannot 1626 /// contain non-field names. 1627 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1628 while (((S->getFlags() & Scope::DeclScope) == 0) || 1629 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1630 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1631 S = S->getParent(); 1632 return S; 1633 } 1634 1635 /// \brief Looks up the declaration of "struct objc_super" and 1636 /// saves it for later use in building builtin declaration of 1637 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1638 /// pre-existing declaration exists no action takes place. 1639 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1640 IdentifierInfo *II) { 1641 if (!II->isStr("objc_msgSendSuper")) 1642 return; 1643 ASTContext &Context = ThisSema.Context; 1644 1645 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1646 SourceLocation(), Sema::LookupTagName); 1647 ThisSema.LookupName(Result, S); 1648 if (Result.getResultKind() == LookupResult::Found) 1649 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1650 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1651 } 1652 1653 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1654 switch (Error) { 1655 case ASTContext::GE_None: 1656 return ""; 1657 case ASTContext::GE_Missing_stdio: 1658 return "stdio.h"; 1659 case ASTContext::GE_Missing_setjmp: 1660 return "setjmp.h"; 1661 case ASTContext::GE_Missing_ucontext: 1662 return "ucontext.h"; 1663 } 1664 llvm_unreachable("unhandled error kind"); 1665 } 1666 1667 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1668 /// file scope. lazily create a decl for it. ForRedeclaration is true 1669 /// if we're creating this built-in in anticipation of redeclaring the 1670 /// built-in. 1671 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1672 Scope *S, bool ForRedeclaration, 1673 SourceLocation Loc) { 1674 LookupPredefedObjCSuperType(*this, S, II); 1675 1676 ASTContext::GetBuiltinTypeError Error; 1677 QualType R = Context.GetBuiltinType(ID, Error); 1678 if (Error) { 1679 if (ForRedeclaration) 1680 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1681 << getHeaderName(Error) 1682 << Context.BuiltinInfo.GetName(ID); 1683 return nullptr; 1684 } 1685 1686 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1687 Diag(Loc, diag::ext_implicit_lib_function_decl) 1688 << Context.BuiltinInfo.GetName(ID) 1689 << R; 1690 if (Context.BuiltinInfo.getHeaderName(ID) && 1691 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1692 Diag(Loc, diag::note_include_header_or_declare) 1693 << Context.BuiltinInfo.getHeaderName(ID) 1694 << Context.BuiltinInfo.GetName(ID); 1695 } 1696 1697 DeclContext *Parent = Context.getTranslationUnitDecl(); 1698 if (getLangOpts().CPlusPlus) { 1699 LinkageSpecDecl *CLinkageDecl = 1700 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1701 LinkageSpecDecl::lang_c, false); 1702 CLinkageDecl->setImplicit(); 1703 Parent->addDecl(CLinkageDecl); 1704 Parent = CLinkageDecl; 1705 } 1706 1707 FunctionDecl *New = FunctionDecl::Create(Context, 1708 Parent, 1709 Loc, Loc, II, R, /*TInfo=*/nullptr, 1710 SC_Extern, 1711 false, 1712 /*hasPrototype=*/true); 1713 New->setImplicit(); 1714 1715 // Create Decl objects for each parameter, adding them to the 1716 // FunctionDecl. 1717 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1718 SmallVector<ParmVarDecl*, 16> Params; 1719 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1720 ParmVarDecl *parm = 1721 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1722 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1723 SC_None, nullptr); 1724 parm->setScopeInfo(0, i); 1725 Params.push_back(parm); 1726 } 1727 New->setParams(Params); 1728 } 1729 1730 AddKnownFunctionAttributes(New); 1731 RegisterLocallyScopedExternCDecl(New, S); 1732 1733 // TUScope is the translation-unit scope to insert this function into. 1734 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1735 // relate Scopes to DeclContexts, and probably eliminate CurContext 1736 // entirely, but we're not there yet. 1737 DeclContext *SavedContext = CurContext; 1738 CurContext = Parent; 1739 PushOnScopeChains(New, TUScope); 1740 CurContext = SavedContext; 1741 return New; 1742 } 1743 1744 /// \brief Filter out any previous declarations that the given declaration 1745 /// should not consider because they are not permitted to conflict, e.g., 1746 /// because they come from hidden sub-modules and do not refer to the same 1747 /// entity. 1748 static void filterNonConflictingPreviousDecls(ASTContext &context, 1749 NamedDecl *decl, 1750 LookupResult &previous){ 1751 // This is only interesting when modules are enabled. 1752 if (!context.getLangOpts().Modules) 1753 return; 1754 1755 // Empty sets are uninteresting. 1756 if (previous.empty()) 1757 return; 1758 1759 LookupResult::Filter filter = previous.makeFilter(); 1760 while (filter.hasNext()) { 1761 NamedDecl *old = filter.next(); 1762 1763 // Non-hidden declarations are never ignored. 1764 if (!old->isHidden()) 1765 continue; 1766 1767 if (!old->isExternallyVisible()) 1768 filter.erase(); 1769 } 1770 1771 filter.done(); 1772 } 1773 1774 /// Typedef declarations don't have linkage, but they still denote the same 1775 /// entity if their types are the same. 1776 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1777 /// isSameEntity. 1778 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context, 1779 TypedefNameDecl *Decl, 1780 LookupResult &Previous) { 1781 // This is only interesting when modules are enabled. 1782 if (!Context.getLangOpts().Modules) 1783 return; 1784 1785 // Empty sets are uninteresting. 1786 if (Previous.empty()) 1787 return; 1788 1789 LookupResult::Filter Filter = Previous.makeFilter(); 1790 while (Filter.hasNext()) { 1791 NamedDecl *Old = Filter.next(); 1792 1793 // Non-hidden declarations are never ignored. 1794 if (!Old->isHidden()) 1795 continue; 1796 1797 // Declarations of the same entity are not ignored, even if they have 1798 // different linkages. 1799 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) 1800 if (Context.hasSameType(OldTD->getUnderlyingType(), 1801 Decl->getUnderlyingType())) 1802 continue; 1803 1804 if (!Old->isExternallyVisible()) 1805 Filter.erase(); 1806 } 1807 1808 Filter.done(); 1809 } 1810 1811 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1812 QualType OldType; 1813 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1814 OldType = OldTypedef->getUnderlyingType(); 1815 else 1816 OldType = Context.getTypeDeclType(Old); 1817 QualType NewType = New->getUnderlyingType(); 1818 1819 if (NewType->isVariablyModifiedType()) { 1820 // Must not redefine a typedef with a variably-modified type. 1821 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1822 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1823 << Kind << NewType; 1824 if (Old->getLocation().isValid()) 1825 Diag(Old->getLocation(), diag::note_previous_definition); 1826 New->setInvalidDecl(); 1827 return true; 1828 } 1829 1830 if (OldType != NewType && 1831 !OldType->isDependentType() && 1832 !NewType->isDependentType() && 1833 !Context.hasSameType(OldType, NewType)) { 1834 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1835 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1836 << Kind << NewType << OldType; 1837 if (Old->getLocation().isValid()) 1838 Diag(Old->getLocation(), diag::note_previous_definition); 1839 New->setInvalidDecl(); 1840 return true; 1841 } 1842 return false; 1843 } 1844 1845 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1846 /// same name and scope as a previous declaration 'Old'. Figure out 1847 /// how to resolve this situation, merging decls or emitting 1848 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1849 /// 1850 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1851 // If the new decl is known invalid already, don't bother doing any 1852 // merging checks. 1853 if (New->isInvalidDecl()) return; 1854 1855 // Allow multiple definitions for ObjC built-in typedefs. 1856 // FIXME: Verify the underlying types are equivalent! 1857 if (getLangOpts().ObjC1) { 1858 const IdentifierInfo *TypeID = New->getIdentifier(); 1859 switch (TypeID->getLength()) { 1860 default: break; 1861 case 2: 1862 { 1863 if (!TypeID->isStr("id")) 1864 break; 1865 QualType T = New->getUnderlyingType(); 1866 if (!T->isPointerType()) 1867 break; 1868 if (!T->isVoidPointerType()) { 1869 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1870 if (!PT->isStructureType()) 1871 break; 1872 } 1873 Context.setObjCIdRedefinitionType(T); 1874 // Install the built-in type for 'id', ignoring the current definition. 1875 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1876 return; 1877 } 1878 case 5: 1879 if (!TypeID->isStr("Class")) 1880 break; 1881 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1882 // Install the built-in type for 'Class', ignoring the current definition. 1883 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1884 return; 1885 case 3: 1886 if (!TypeID->isStr("SEL")) 1887 break; 1888 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1889 // Install the built-in type for 'SEL', ignoring the current definition. 1890 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1891 return; 1892 } 1893 // Fall through - the typedef name was not a builtin type. 1894 } 1895 1896 // Verify the old decl was also a type. 1897 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1898 if (!Old) { 1899 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1900 << New->getDeclName(); 1901 1902 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1903 if (OldD->getLocation().isValid()) 1904 Diag(OldD->getLocation(), diag::note_previous_definition); 1905 1906 return New->setInvalidDecl(); 1907 } 1908 1909 // If the old declaration is invalid, just give up here. 1910 if (Old->isInvalidDecl()) 1911 return New->setInvalidDecl(); 1912 1913 // If the typedef types are not identical, reject them in all languages and 1914 // with any extensions enabled. 1915 if (isIncompatibleTypedef(Old, New)) 1916 return; 1917 1918 // The types match. Link up the redeclaration chain and merge attributes if 1919 // the old declaration was a typedef. 1920 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1921 New->setPreviousDecl(Typedef); 1922 mergeDeclAttributes(New, Old); 1923 } 1924 1925 if (getLangOpts().MicrosoftExt) 1926 return; 1927 1928 if (getLangOpts().CPlusPlus) { 1929 // C++ [dcl.typedef]p2: 1930 // In a given non-class scope, a typedef specifier can be used to 1931 // redefine the name of any type declared in that scope to refer 1932 // to the type to which it already refers. 1933 if (!isa<CXXRecordDecl>(CurContext)) 1934 return; 1935 1936 // C++0x [dcl.typedef]p4: 1937 // In a given class scope, a typedef specifier can be used to redefine 1938 // any class-name declared in that scope that is not also a typedef-name 1939 // to refer to the type to which it already refers. 1940 // 1941 // This wording came in via DR424, which was a correction to the 1942 // wording in DR56, which accidentally banned code like: 1943 // 1944 // struct S { 1945 // typedef struct A { } A; 1946 // }; 1947 // 1948 // in the C++03 standard. We implement the C++0x semantics, which 1949 // allow the above but disallow 1950 // 1951 // struct S { 1952 // typedef int I; 1953 // typedef int I; 1954 // }; 1955 // 1956 // since that was the intent of DR56. 1957 if (!isa<TypedefNameDecl>(Old)) 1958 return; 1959 1960 Diag(New->getLocation(), diag::err_redefinition) 1961 << New->getDeclName(); 1962 Diag(Old->getLocation(), diag::note_previous_definition); 1963 return New->setInvalidDecl(); 1964 } 1965 1966 // Modules always permit redefinition of typedefs, as does C11. 1967 if (getLangOpts().Modules || getLangOpts().C11) 1968 return; 1969 1970 // If we have a redefinition of a typedef in C, emit a warning. This warning 1971 // is normally mapped to an error, but can be controlled with 1972 // -Wtypedef-redefinition. If either the original or the redefinition is 1973 // in a system header, don't emit this for compatibility with GCC. 1974 if (getDiagnostics().getSuppressSystemWarnings() && 1975 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1976 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1977 return; 1978 1979 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 1980 << New->getDeclName(); 1981 Diag(Old->getLocation(), diag::note_previous_definition); 1982 return; 1983 } 1984 1985 /// DeclhasAttr - returns true if decl Declaration already has the target 1986 /// attribute. 1987 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1988 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1989 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1990 for (const auto *i : D->attrs()) 1991 if (i->getKind() == A->getKind()) { 1992 if (Ann) { 1993 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1994 return true; 1995 continue; 1996 } 1997 // FIXME: Don't hardcode this check 1998 if (OA && isa<OwnershipAttr>(i)) 1999 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2000 return true; 2001 } 2002 2003 return false; 2004 } 2005 2006 static bool isAttributeTargetADefinition(Decl *D) { 2007 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2008 return VD->isThisDeclarationADefinition(); 2009 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2010 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2011 return true; 2012 } 2013 2014 /// Merge alignment attributes from \p Old to \p New, taking into account the 2015 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2016 /// 2017 /// \return \c true if any attributes were added to \p New. 2018 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2019 // Look for alignas attributes on Old, and pick out whichever attribute 2020 // specifies the strictest alignment requirement. 2021 AlignedAttr *OldAlignasAttr = nullptr; 2022 AlignedAttr *OldStrictestAlignAttr = nullptr; 2023 unsigned OldAlign = 0; 2024 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2025 // FIXME: We have no way of representing inherited dependent alignments 2026 // in a case like: 2027 // template<int A, int B> struct alignas(A) X; 2028 // template<int A, int B> struct alignas(B) X {}; 2029 // For now, we just ignore any alignas attributes which are not on the 2030 // definition in such a case. 2031 if (I->isAlignmentDependent()) 2032 return false; 2033 2034 if (I->isAlignas()) 2035 OldAlignasAttr = I; 2036 2037 unsigned Align = I->getAlignment(S.Context); 2038 if (Align > OldAlign) { 2039 OldAlign = Align; 2040 OldStrictestAlignAttr = I; 2041 } 2042 } 2043 2044 // Look for alignas attributes on New. 2045 AlignedAttr *NewAlignasAttr = nullptr; 2046 unsigned NewAlign = 0; 2047 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2048 if (I->isAlignmentDependent()) 2049 return false; 2050 2051 if (I->isAlignas()) 2052 NewAlignasAttr = I; 2053 2054 unsigned Align = I->getAlignment(S.Context); 2055 if (Align > NewAlign) 2056 NewAlign = Align; 2057 } 2058 2059 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2060 // Both declarations have 'alignas' attributes. We require them to match. 2061 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2062 // fall short. (If two declarations both have alignas, they must both match 2063 // every definition, and so must match each other if there is a definition.) 2064 2065 // If either declaration only contains 'alignas(0)' specifiers, then it 2066 // specifies the natural alignment for the type. 2067 if (OldAlign == 0 || NewAlign == 0) { 2068 QualType Ty; 2069 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2070 Ty = VD->getType(); 2071 else 2072 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2073 2074 if (OldAlign == 0) 2075 OldAlign = S.Context.getTypeAlign(Ty); 2076 if (NewAlign == 0) 2077 NewAlign = S.Context.getTypeAlign(Ty); 2078 } 2079 2080 if (OldAlign != NewAlign) { 2081 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2082 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2083 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2084 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2085 } 2086 } 2087 2088 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2089 // C++11 [dcl.align]p6: 2090 // if any declaration of an entity has an alignment-specifier, 2091 // every defining declaration of that entity shall specify an 2092 // equivalent alignment. 2093 // C11 6.7.5/7: 2094 // If the definition of an object does not have an alignment 2095 // specifier, any other declaration of that object shall also 2096 // have no alignment specifier. 2097 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2098 << OldAlignasAttr; 2099 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2100 << OldAlignasAttr; 2101 } 2102 2103 bool AnyAdded = false; 2104 2105 // Ensure we have an attribute representing the strictest alignment. 2106 if (OldAlign > NewAlign) { 2107 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2108 Clone->setInherited(true); 2109 New->addAttr(Clone); 2110 AnyAdded = true; 2111 } 2112 2113 // Ensure we have an alignas attribute if the old declaration had one. 2114 if (OldAlignasAttr && !NewAlignasAttr && 2115 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2116 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2117 Clone->setInherited(true); 2118 New->addAttr(Clone); 2119 AnyAdded = true; 2120 } 2121 2122 return AnyAdded; 2123 } 2124 2125 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2126 const InheritableAttr *Attr, bool Override) { 2127 InheritableAttr *NewAttr = nullptr; 2128 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2129 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2130 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2131 AA->getIntroduced(), AA->getDeprecated(), 2132 AA->getObsoleted(), AA->getUnavailable(), 2133 AA->getMessage(), Override, 2134 AttrSpellingListIndex); 2135 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2136 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2137 AttrSpellingListIndex); 2138 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2139 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2140 AttrSpellingListIndex); 2141 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2142 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2143 AttrSpellingListIndex); 2144 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2145 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2146 AttrSpellingListIndex); 2147 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2148 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2149 FA->getFormatIdx(), FA->getFirstArg(), 2150 AttrSpellingListIndex); 2151 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2152 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2153 AttrSpellingListIndex); 2154 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2155 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2156 AttrSpellingListIndex, 2157 IA->getSemanticSpelling()); 2158 else if (isa<AlignedAttr>(Attr)) 2159 // AlignedAttrs are handled separately, because we need to handle all 2160 // such attributes on a declaration at the same time. 2161 NewAttr = nullptr; 2162 else if (isa<DeprecatedAttr>(Attr) && Override) 2163 NewAttr = nullptr; 2164 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2165 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2166 2167 if (NewAttr) { 2168 NewAttr->setInherited(true); 2169 D->addAttr(NewAttr); 2170 return true; 2171 } 2172 2173 return false; 2174 } 2175 2176 static const Decl *getDefinition(const Decl *D) { 2177 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2178 return TD->getDefinition(); 2179 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2180 const VarDecl *Def = VD->getDefinition(); 2181 if (Def) 2182 return Def; 2183 return VD->getActingDefinition(); 2184 } 2185 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2186 const FunctionDecl* Def; 2187 if (FD->isDefined(Def)) 2188 return Def; 2189 } 2190 return nullptr; 2191 } 2192 2193 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2194 for (const auto *Attribute : D->attrs()) 2195 if (Attribute->getKind() == Kind) 2196 return true; 2197 return false; 2198 } 2199 2200 /// checkNewAttributesAfterDef - If we already have a definition, check that 2201 /// there are no new attributes in this declaration. 2202 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2203 if (!New->hasAttrs()) 2204 return; 2205 2206 const Decl *Def = getDefinition(Old); 2207 if (!Def || Def == New) 2208 return; 2209 2210 AttrVec &NewAttributes = New->getAttrs(); 2211 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2212 const Attr *NewAttribute = NewAttributes[I]; 2213 2214 if (isa<AliasAttr>(NewAttribute)) { 2215 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2216 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2217 else { 2218 VarDecl *VD = cast<VarDecl>(New); 2219 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2220 VarDecl::TentativeDefinition 2221 ? diag::err_alias_after_tentative 2222 : diag::err_redefinition; 2223 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2224 S.Diag(Def->getLocation(), diag::note_previous_definition); 2225 VD->setInvalidDecl(); 2226 } 2227 ++I; 2228 continue; 2229 } 2230 2231 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2232 // Tentative definitions are only interesting for the alias check above. 2233 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2234 ++I; 2235 continue; 2236 } 2237 } 2238 2239 if (hasAttribute(Def, NewAttribute->getKind())) { 2240 ++I; 2241 continue; // regular attr merging will take care of validating this. 2242 } 2243 2244 if (isa<C11NoReturnAttr>(NewAttribute)) { 2245 // C's _Noreturn is allowed to be added to a function after it is defined. 2246 ++I; 2247 continue; 2248 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2249 if (AA->isAlignas()) { 2250 // C++11 [dcl.align]p6: 2251 // if any declaration of an entity has an alignment-specifier, 2252 // every defining declaration of that entity shall specify an 2253 // equivalent alignment. 2254 // C11 6.7.5/7: 2255 // If the definition of an object does not have an alignment 2256 // specifier, any other declaration of that object shall also 2257 // have no alignment specifier. 2258 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2259 << AA; 2260 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2261 << AA; 2262 NewAttributes.erase(NewAttributes.begin() + I); 2263 --E; 2264 continue; 2265 } 2266 } 2267 2268 S.Diag(NewAttribute->getLocation(), 2269 diag::warn_attribute_precede_definition); 2270 S.Diag(Def->getLocation(), diag::note_previous_definition); 2271 NewAttributes.erase(NewAttributes.begin() + I); 2272 --E; 2273 } 2274 } 2275 2276 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2277 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2278 AvailabilityMergeKind AMK) { 2279 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2280 UsedAttr *NewAttr = OldAttr->clone(Context); 2281 NewAttr->setInherited(true); 2282 New->addAttr(NewAttr); 2283 } 2284 2285 if (!Old->hasAttrs() && !New->hasAttrs()) 2286 return; 2287 2288 // attributes declared post-definition are currently ignored 2289 checkNewAttributesAfterDef(*this, New, Old); 2290 2291 if (!Old->hasAttrs()) 2292 return; 2293 2294 bool foundAny = New->hasAttrs(); 2295 2296 // Ensure that any moving of objects within the allocated map is done before 2297 // we process them. 2298 if (!foundAny) New->setAttrs(AttrVec()); 2299 2300 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2301 bool Override = false; 2302 // Ignore deprecated/unavailable/availability attributes if requested. 2303 if (isa<DeprecatedAttr>(I) || 2304 isa<UnavailableAttr>(I) || 2305 isa<AvailabilityAttr>(I)) { 2306 switch (AMK) { 2307 case AMK_None: 2308 continue; 2309 2310 case AMK_Redeclaration: 2311 break; 2312 2313 case AMK_Override: 2314 Override = true; 2315 break; 2316 } 2317 } 2318 2319 // Already handled. 2320 if (isa<UsedAttr>(I)) 2321 continue; 2322 2323 if (mergeDeclAttribute(*this, New, I, Override)) 2324 foundAny = true; 2325 } 2326 2327 if (mergeAlignedAttrs(*this, New, Old)) 2328 foundAny = true; 2329 2330 if (!foundAny) New->dropAttrs(); 2331 } 2332 2333 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2334 /// to the new one. 2335 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2336 const ParmVarDecl *oldDecl, 2337 Sema &S) { 2338 // C++11 [dcl.attr.depend]p2: 2339 // The first declaration of a function shall specify the 2340 // carries_dependency attribute for its declarator-id if any declaration 2341 // of the function specifies the carries_dependency attribute. 2342 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2343 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2344 S.Diag(CDA->getLocation(), 2345 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2346 // Find the first declaration of the parameter. 2347 // FIXME: Should we build redeclaration chains for function parameters? 2348 const FunctionDecl *FirstFD = 2349 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2350 const ParmVarDecl *FirstVD = 2351 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2352 S.Diag(FirstVD->getLocation(), 2353 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2354 } 2355 2356 if (!oldDecl->hasAttrs()) 2357 return; 2358 2359 bool foundAny = newDecl->hasAttrs(); 2360 2361 // Ensure that any moving of objects within the allocated map is 2362 // done before we process them. 2363 if (!foundAny) newDecl->setAttrs(AttrVec()); 2364 2365 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2366 if (!DeclHasAttr(newDecl, I)) { 2367 InheritableAttr *newAttr = 2368 cast<InheritableParamAttr>(I->clone(S.Context)); 2369 newAttr->setInherited(true); 2370 newDecl->addAttr(newAttr); 2371 foundAny = true; 2372 } 2373 } 2374 2375 if (!foundAny) newDecl->dropAttrs(); 2376 } 2377 2378 namespace { 2379 2380 /// Used in MergeFunctionDecl to keep track of function parameters in 2381 /// C. 2382 struct GNUCompatibleParamWarning { 2383 ParmVarDecl *OldParm; 2384 ParmVarDecl *NewParm; 2385 QualType PromotedType; 2386 }; 2387 2388 } 2389 2390 /// getSpecialMember - get the special member enum for a method. 2391 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2392 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2393 if (Ctor->isDefaultConstructor()) 2394 return Sema::CXXDefaultConstructor; 2395 2396 if (Ctor->isCopyConstructor()) 2397 return Sema::CXXCopyConstructor; 2398 2399 if (Ctor->isMoveConstructor()) 2400 return Sema::CXXMoveConstructor; 2401 } else if (isa<CXXDestructorDecl>(MD)) { 2402 return Sema::CXXDestructor; 2403 } else if (MD->isCopyAssignmentOperator()) { 2404 return Sema::CXXCopyAssignment; 2405 } else if (MD->isMoveAssignmentOperator()) { 2406 return Sema::CXXMoveAssignment; 2407 } 2408 2409 return Sema::CXXInvalid; 2410 } 2411 2412 // Determine whether the previous declaration was a definition, implicit 2413 // declaration, or a declaration. 2414 template <typename T> 2415 static std::pair<diag::kind, SourceLocation> 2416 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2417 diag::kind PrevDiag; 2418 SourceLocation OldLocation = Old->getLocation(); 2419 if (Old->isThisDeclarationADefinition()) 2420 PrevDiag = diag::note_previous_definition; 2421 else if (Old->isImplicit()) { 2422 PrevDiag = diag::note_previous_implicit_declaration; 2423 if (OldLocation.isInvalid()) 2424 OldLocation = New->getLocation(); 2425 } else 2426 PrevDiag = diag::note_previous_declaration; 2427 return std::make_pair(PrevDiag, OldLocation); 2428 } 2429 2430 /// canRedefineFunction - checks if a function can be redefined. Currently, 2431 /// only extern inline functions can be redefined, and even then only in 2432 /// GNU89 mode. 2433 static bool canRedefineFunction(const FunctionDecl *FD, 2434 const LangOptions& LangOpts) { 2435 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2436 !LangOpts.CPlusPlus && 2437 FD->isInlineSpecified() && 2438 FD->getStorageClass() == SC_Extern); 2439 } 2440 2441 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2442 const AttributedType *AT = T->getAs<AttributedType>(); 2443 while (AT && !AT->isCallingConv()) 2444 AT = AT->getModifiedType()->getAs<AttributedType>(); 2445 return AT; 2446 } 2447 2448 template <typename T> 2449 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2450 const DeclContext *DC = Old->getDeclContext(); 2451 if (DC->isRecord()) 2452 return false; 2453 2454 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2455 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2456 return true; 2457 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2458 return true; 2459 return false; 2460 } 2461 2462 /// MergeFunctionDecl - We just parsed a function 'New' from 2463 /// declarator D which has the same name and scope as a previous 2464 /// declaration 'Old'. Figure out how to resolve this situation, 2465 /// merging decls or emitting diagnostics as appropriate. 2466 /// 2467 /// In C++, New and Old must be declarations that are not 2468 /// overloaded. Use IsOverload to determine whether New and Old are 2469 /// overloaded, and to select the Old declaration that New should be 2470 /// merged with. 2471 /// 2472 /// Returns true if there was an error, false otherwise. 2473 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2474 Scope *S, bool MergeTypeWithOld) { 2475 // Verify the old decl was also a function. 2476 FunctionDecl *Old = OldD->getAsFunction(); 2477 if (!Old) { 2478 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2479 if (New->getFriendObjectKind()) { 2480 Diag(New->getLocation(), diag::err_using_decl_friend); 2481 Diag(Shadow->getTargetDecl()->getLocation(), 2482 diag::note_using_decl_target); 2483 Diag(Shadow->getUsingDecl()->getLocation(), 2484 diag::note_using_decl) << 0; 2485 return true; 2486 } 2487 2488 // C++11 [namespace.udecl]p14: 2489 // If a function declaration in namespace scope or block scope has the 2490 // same name and the same parameter-type-list as a function introduced 2491 // by a using-declaration, and the declarations do not declare the same 2492 // function, the program is ill-formed. 2493 2494 // Check whether the two declarations might declare the same function. 2495 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2496 if (Old && 2497 !Old->getDeclContext()->getRedeclContext()->Equals( 2498 New->getDeclContext()->getRedeclContext()) && 2499 !(Old->isExternC() && New->isExternC())) 2500 Old = nullptr; 2501 2502 if (!Old) { 2503 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2504 Diag(Shadow->getTargetDecl()->getLocation(), 2505 diag::note_using_decl_target); 2506 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2507 return true; 2508 } 2509 OldD = Old; 2510 } else { 2511 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2512 << New->getDeclName(); 2513 Diag(OldD->getLocation(), diag::note_previous_definition); 2514 return true; 2515 } 2516 } 2517 2518 // If the old declaration is invalid, just give up here. 2519 if (Old->isInvalidDecl()) 2520 return true; 2521 2522 diag::kind PrevDiag; 2523 SourceLocation OldLocation; 2524 std::tie(PrevDiag, OldLocation) = 2525 getNoteDiagForInvalidRedeclaration(Old, New); 2526 2527 // Don't complain about this if we're in GNU89 mode and the old function 2528 // is an extern inline function. 2529 // Don't complain about specializations. They are not supposed to have 2530 // storage classes. 2531 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2532 New->getStorageClass() == SC_Static && 2533 Old->hasExternalFormalLinkage() && 2534 !New->getTemplateSpecializationInfo() && 2535 !canRedefineFunction(Old, getLangOpts())) { 2536 if (getLangOpts().MicrosoftExt) { 2537 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2538 Diag(OldLocation, PrevDiag); 2539 } else { 2540 Diag(New->getLocation(), diag::err_static_non_static) << New; 2541 Diag(OldLocation, PrevDiag); 2542 return true; 2543 } 2544 } 2545 2546 2547 // If a function is first declared with a calling convention, but is later 2548 // declared or defined without one, all following decls assume the calling 2549 // convention of the first. 2550 // 2551 // It's OK if a function is first declared without a calling convention, 2552 // but is later declared or defined with the default calling convention. 2553 // 2554 // To test if either decl has an explicit calling convention, we look for 2555 // AttributedType sugar nodes on the type as written. If they are missing or 2556 // were canonicalized away, we assume the calling convention was implicit. 2557 // 2558 // Note also that we DO NOT return at this point, because we still have 2559 // other tests to run. 2560 QualType OldQType = Context.getCanonicalType(Old->getType()); 2561 QualType NewQType = Context.getCanonicalType(New->getType()); 2562 const FunctionType *OldType = cast<FunctionType>(OldQType); 2563 const FunctionType *NewType = cast<FunctionType>(NewQType); 2564 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2565 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2566 bool RequiresAdjustment = false; 2567 2568 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2569 FunctionDecl *First = Old->getFirstDecl(); 2570 const FunctionType *FT = 2571 First->getType().getCanonicalType()->castAs<FunctionType>(); 2572 FunctionType::ExtInfo FI = FT->getExtInfo(); 2573 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2574 if (!NewCCExplicit) { 2575 // Inherit the CC from the previous declaration if it was specified 2576 // there but not here. 2577 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2578 RequiresAdjustment = true; 2579 } else { 2580 // Calling conventions aren't compatible, so complain. 2581 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2582 Diag(New->getLocation(), diag::err_cconv_change) 2583 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2584 << !FirstCCExplicit 2585 << (!FirstCCExplicit ? "" : 2586 FunctionType::getNameForCallConv(FI.getCC())); 2587 2588 // Put the note on the first decl, since it is the one that matters. 2589 Diag(First->getLocation(), diag::note_previous_declaration); 2590 return true; 2591 } 2592 } 2593 2594 // FIXME: diagnose the other way around? 2595 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2596 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2597 RequiresAdjustment = true; 2598 } 2599 2600 // Merge regparm attribute. 2601 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2602 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2603 if (NewTypeInfo.getHasRegParm()) { 2604 Diag(New->getLocation(), diag::err_regparm_mismatch) 2605 << NewType->getRegParmType() 2606 << OldType->getRegParmType(); 2607 Diag(OldLocation, diag::note_previous_declaration); 2608 return true; 2609 } 2610 2611 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2612 RequiresAdjustment = true; 2613 } 2614 2615 // Merge ns_returns_retained attribute. 2616 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2617 if (NewTypeInfo.getProducesResult()) { 2618 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2619 Diag(OldLocation, diag::note_previous_declaration); 2620 return true; 2621 } 2622 2623 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2624 RequiresAdjustment = true; 2625 } 2626 2627 if (RequiresAdjustment) { 2628 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2629 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2630 New->setType(QualType(AdjustedType, 0)); 2631 NewQType = Context.getCanonicalType(New->getType()); 2632 NewType = cast<FunctionType>(NewQType); 2633 } 2634 2635 // If this redeclaration makes the function inline, we may need to add it to 2636 // UndefinedButUsed. 2637 if (!Old->isInlined() && New->isInlined() && 2638 !New->hasAttr<GNUInlineAttr>() && 2639 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2640 Old->isUsed(false) && 2641 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2642 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2643 SourceLocation())); 2644 2645 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2646 // about it. 2647 if (New->hasAttr<GNUInlineAttr>() && 2648 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2649 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2650 } 2651 2652 if (getLangOpts().CPlusPlus) { 2653 // (C++98 13.1p2): 2654 // Certain function declarations cannot be overloaded: 2655 // -- Function declarations that differ only in the return type 2656 // cannot be overloaded. 2657 2658 // Go back to the type source info to compare the declared return types, 2659 // per C++1y [dcl.type.auto]p13: 2660 // Redeclarations or specializations of a function or function template 2661 // with a declared return type that uses a placeholder type shall also 2662 // use that placeholder, not a deduced type. 2663 QualType OldDeclaredReturnType = 2664 (Old->getTypeSourceInfo() 2665 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2666 : OldType)->getReturnType(); 2667 QualType NewDeclaredReturnType = 2668 (New->getTypeSourceInfo() 2669 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2670 : NewType)->getReturnType(); 2671 QualType ResQT; 2672 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2673 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2674 New->isLocalExternDecl())) { 2675 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2676 OldDeclaredReturnType->isObjCObjectPointerType()) 2677 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2678 if (ResQT.isNull()) { 2679 if (New->isCXXClassMember() && New->isOutOfLine()) 2680 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2681 << New << New->getReturnTypeSourceRange(); 2682 else 2683 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2684 << New->getReturnTypeSourceRange(); 2685 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2686 << Old->getReturnTypeSourceRange(); 2687 return true; 2688 } 2689 else 2690 NewQType = ResQT; 2691 } 2692 2693 QualType OldReturnType = OldType->getReturnType(); 2694 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2695 if (OldReturnType != NewReturnType) { 2696 // If this function has a deduced return type and has already been 2697 // defined, copy the deduced value from the old declaration. 2698 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2699 if (OldAT && OldAT->isDeduced()) { 2700 New->setType( 2701 SubstAutoType(New->getType(), 2702 OldAT->isDependentType() ? Context.DependentTy 2703 : OldAT->getDeducedType())); 2704 NewQType = Context.getCanonicalType( 2705 SubstAutoType(NewQType, 2706 OldAT->isDependentType() ? Context.DependentTy 2707 : OldAT->getDeducedType())); 2708 } 2709 } 2710 2711 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2712 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2713 if (OldMethod && NewMethod) { 2714 // Preserve triviality. 2715 NewMethod->setTrivial(OldMethod->isTrivial()); 2716 2717 // MSVC allows explicit template specialization at class scope: 2718 // 2 CXXMethodDecls referring to the same function will be injected. 2719 // We don't want a redeclaration error. 2720 bool IsClassScopeExplicitSpecialization = 2721 OldMethod->isFunctionTemplateSpecialization() && 2722 NewMethod->isFunctionTemplateSpecialization(); 2723 bool isFriend = NewMethod->getFriendObjectKind(); 2724 2725 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2726 !IsClassScopeExplicitSpecialization) { 2727 // -- Member function declarations with the same name and the 2728 // same parameter types cannot be overloaded if any of them 2729 // is a static member function declaration. 2730 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2731 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2732 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2733 return true; 2734 } 2735 2736 // C++ [class.mem]p1: 2737 // [...] A member shall not be declared twice in the 2738 // member-specification, except that a nested class or member 2739 // class template can be declared and then later defined. 2740 if (ActiveTemplateInstantiations.empty()) { 2741 unsigned NewDiag; 2742 if (isa<CXXConstructorDecl>(OldMethod)) 2743 NewDiag = diag::err_constructor_redeclared; 2744 else if (isa<CXXDestructorDecl>(NewMethod)) 2745 NewDiag = diag::err_destructor_redeclared; 2746 else if (isa<CXXConversionDecl>(NewMethod)) 2747 NewDiag = diag::err_conv_function_redeclared; 2748 else 2749 NewDiag = diag::err_member_redeclared; 2750 2751 Diag(New->getLocation(), NewDiag); 2752 } else { 2753 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2754 << New << New->getType(); 2755 } 2756 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2757 2758 // Complain if this is an explicit declaration of a special 2759 // member that was initially declared implicitly. 2760 // 2761 // As an exception, it's okay to befriend such methods in order 2762 // to permit the implicit constructor/destructor/operator calls. 2763 } else if (OldMethod->isImplicit()) { 2764 if (isFriend) { 2765 NewMethod->setImplicit(); 2766 } else { 2767 Diag(NewMethod->getLocation(), 2768 diag::err_definition_of_implicitly_declared_member) 2769 << New << getSpecialMember(OldMethod); 2770 return true; 2771 } 2772 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2773 Diag(NewMethod->getLocation(), 2774 diag::err_definition_of_explicitly_defaulted_member) 2775 << getSpecialMember(OldMethod); 2776 return true; 2777 } 2778 } 2779 2780 // C++11 [dcl.attr.noreturn]p1: 2781 // The first declaration of a function shall specify the noreturn 2782 // attribute if any declaration of that function specifies the noreturn 2783 // attribute. 2784 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2785 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2786 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2787 Diag(Old->getFirstDecl()->getLocation(), 2788 diag::note_noreturn_missing_first_decl); 2789 } 2790 2791 // C++11 [dcl.attr.depend]p2: 2792 // The first declaration of a function shall specify the 2793 // carries_dependency attribute for its declarator-id if any declaration 2794 // of the function specifies the carries_dependency attribute. 2795 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2796 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2797 Diag(CDA->getLocation(), 2798 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2799 Diag(Old->getFirstDecl()->getLocation(), 2800 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2801 } 2802 2803 // (C++98 8.3.5p3): 2804 // All declarations for a function shall agree exactly in both the 2805 // return type and the parameter-type-list. 2806 // We also want to respect all the extended bits except noreturn. 2807 2808 // noreturn should now match unless the old type info didn't have it. 2809 QualType OldQTypeForComparison = OldQType; 2810 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2811 assert(OldQType == QualType(OldType, 0)); 2812 const FunctionType *OldTypeForComparison 2813 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2814 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2815 assert(OldQTypeForComparison.isCanonical()); 2816 } 2817 2818 if (haveIncompatibleLanguageLinkages(Old, New)) { 2819 // As a special case, retain the language linkage from previous 2820 // declarations of a friend function as an extension. 2821 // 2822 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2823 // and is useful because there's otherwise no way to specify language 2824 // linkage within class scope. 2825 // 2826 // Check cautiously as the friend object kind isn't yet complete. 2827 if (New->getFriendObjectKind() != Decl::FOK_None) { 2828 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2829 Diag(OldLocation, PrevDiag); 2830 } else { 2831 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2832 Diag(OldLocation, PrevDiag); 2833 return true; 2834 } 2835 } 2836 2837 if (OldQTypeForComparison == NewQType) 2838 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2839 2840 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2841 New->isLocalExternDecl()) { 2842 // It's OK if we couldn't merge types for a local function declaraton 2843 // if either the old or new type is dependent. We'll merge the types 2844 // when we instantiate the function. 2845 return false; 2846 } 2847 2848 // Fall through for conflicting redeclarations and redefinitions. 2849 } 2850 2851 // C: Function types need to be compatible, not identical. This handles 2852 // duplicate function decls like "void f(int); void f(enum X);" properly. 2853 if (!getLangOpts().CPlusPlus && 2854 Context.typesAreCompatible(OldQType, NewQType)) { 2855 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2856 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2857 const FunctionProtoType *OldProto = nullptr; 2858 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2859 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2860 // The old declaration provided a function prototype, but the 2861 // new declaration does not. Merge in the prototype. 2862 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2863 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2864 NewQType = 2865 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2866 OldProto->getExtProtoInfo()); 2867 New->setType(NewQType); 2868 New->setHasInheritedPrototype(); 2869 2870 // Synthesize parameters with the same types. 2871 SmallVector<ParmVarDecl*, 16> Params; 2872 for (const auto &ParamType : OldProto->param_types()) { 2873 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2874 SourceLocation(), nullptr, 2875 ParamType, /*TInfo=*/nullptr, 2876 SC_None, nullptr); 2877 Param->setScopeInfo(0, Params.size()); 2878 Param->setImplicit(); 2879 Params.push_back(Param); 2880 } 2881 2882 New->setParams(Params); 2883 } 2884 2885 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2886 } 2887 2888 // GNU C permits a K&R definition to follow a prototype declaration 2889 // if the declared types of the parameters in the K&R definition 2890 // match the types in the prototype declaration, even when the 2891 // promoted types of the parameters from the K&R definition differ 2892 // from the types in the prototype. GCC then keeps the types from 2893 // the prototype. 2894 // 2895 // If a variadic prototype is followed by a non-variadic K&R definition, 2896 // the K&R definition becomes variadic. This is sort of an edge case, but 2897 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2898 // C99 6.9.1p8. 2899 if (!getLangOpts().CPlusPlus && 2900 Old->hasPrototype() && !New->hasPrototype() && 2901 New->getType()->getAs<FunctionProtoType>() && 2902 Old->getNumParams() == New->getNumParams()) { 2903 SmallVector<QualType, 16> ArgTypes; 2904 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2905 const FunctionProtoType *OldProto 2906 = Old->getType()->getAs<FunctionProtoType>(); 2907 const FunctionProtoType *NewProto 2908 = New->getType()->getAs<FunctionProtoType>(); 2909 2910 // Determine whether this is the GNU C extension. 2911 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2912 NewProto->getReturnType()); 2913 bool LooseCompatible = !MergedReturn.isNull(); 2914 for (unsigned Idx = 0, End = Old->getNumParams(); 2915 LooseCompatible && Idx != End; ++Idx) { 2916 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2917 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2918 if (Context.typesAreCompatible(OldParm->getType(), 2919 NewProto->getParamType(Idx))) { 2920 ArgTypes.push_back(NewParm->getType()); 2921 } else if (Context.typesAreCompatible(OldParm->getType(), 2922 NewParm->getType(), 2923 /*CompareUnqualified=*/true)) { 2924 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2925 NewProto->getParamType(Idx) }; 2926 Warnings.push_back(Warn); 2927 ArgTypes.push_back(NewParm->getType()); 2928 } else 2929 LooseCompatible = false; 2930 } 2931 2932 if (LooseCompatible) { 2933 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2934 Diag(Warnings[Warn].NewParm->getLocation(), 2935 diag::ext_param_promoted_not_compatible_with_prototype) 2936 << Warnings[Warn].PromotedType 2937 << Warnings[Warn].OldParm->getType(); 2938 if (Warnings[Warn].OldParm->getLocation().isValid()) 2939 Diag(Warnings[Warn].OldParm->getLocation(), 2940 diag::note_previous_declaration); 2941 } 2942 2943 if (MergeTypeWithOld) 2944 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2945 OldProto->getExtProtoInfo())); 2946 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2947 } 2948 2949 // Fall through to diagnose conflicting types. 2950 } 2951 2952 // A function that has already been declared has been redeclared or 2953 // defined with a different type; show an appropriate diagnostic. 2954 2955 // If the previous declaration was an implicitly-generated builtin 2956 // declaration, then at the very least we should use a specialized note. 2957 unsigned BuiltinID; 2958 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2959 // If it's actually a library-defined builtin function like 'malloc' 2960 // or 'printf', just warn about the incompatible redeclaration. 2961 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2962 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2963 Diag(OldLocation, diag::note_previous_builtin_declaration) 2964 << Old << Old->getType(); 2965 2966 // If this is a global redeclaration, just forget hereafter 2967 // about the "builtin-ness" of the function. 2968 // 2969 // Doing this for local extern declarations is problematic. If 2970 // the builtin declaration remains visible, a second invalid 2971 // local declaration will produce a hard error; if it doesn't 2972 // remain visible, a single bogus local redeclaration (which is 2973 // actually only a warning) could break all the downstream code. 2974 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2975 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2976 2977 return false; 2978 } 2979 2980 PrevDiag = diag::note_previous_builtin_declaration; 2981 } 2982 2983 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2984 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2985 return true; 2986 } 2987 2988 /// \brief Completes the merge of two function declarations that are 2989 /// known to be compatible. 2990 /// 2991 /// This routine handles the merging of attributes and other 2992 /// properties of function declarations from the old declaration to 2993 /// the new declaration, once we know that New is in fact a 2994 /// redeclaration of Old. 2995 /// 2996 /// \returns false 2997 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2998 Scope *S, bool MergeTypeWithOld) { 2999 // Merge the attributes 3000 mergeDeclAttributes(New, Old); 3001 3002 // Merge "pure" flag. 3003 if (Old->isPure()) 3004 New->setPure(); 3005 3006 // Merge "used" flag. 3007 if (Old->getMostRecentDecl()->isUsed(false)) 3008 New->setIsUsed(); 3009 3010 // Merge attributes from the parameters. These can mismatch with K&R 3011 // declarations. 3012 if (New->getNumParams() == Old->getNumParams()) 3013 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3014 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3015 *this); 3016 3017 if (getLangOpts().CPlusPlus) 3018 return MergeCXXFunctionDecl(New, Old, S); 3019 3020 // Merge the function types so the we get the composite types for the return 3021 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3022 // was visible. 3023 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3024 if (!Merged.isNull() && MergeTypeWithOld) 3025 New->setType(Merged); 3026 3027 return false; 3028 } 3029 3030 3031 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3032 ObjCMethodDecl *oldMethod) { 3033 3034 // Merge the attributes, including deprecated/unavailable 3035 AvailabilityMergeKind MergeKind = 3036 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3037 : AMK_Override; 3038 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3039 3040 // Merge attributes from the parameters. 3041 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3042 oe = oldMethod->param_end(); 3043 for (ObjCMethodDecl::param_iterator 3044 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3045 ni != ne && oi != oe; ++ni, ++oi) 3046 mergeParamDeclAttributes(*ni, *oi, *this); 3047 3048 CheckObjCMethodOverride(newMethod, oldMethod); 3049 } 3050 3051 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3052 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3053 /// emitting diagnostics as appropriate. 3054 /// 3055 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3056 /// to here in AddInitializerToDecl. We can't check them before the initializer 3057 /// is attached. 3058 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3059 bool MergeTypeWithOld) { 3060 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3061 return; 3062 3063 QualType MergedT; 3064 if (getLangOpts().CPlusPlus) { 3065 if (New->getType()->isUndeducedType()) { 3066 // We don't know what the new type is until the initializer is attached. 3067 return; 3068 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3069 // These could still be something that needs exception specs checked. 3070 return MergeVarDeclExceptionSpecs(New, Old); 3071 } 3072 // C++ [basic.link]p10: 3073 // [...] the types specified by all declarations referring to a given 3074 // object or function shall be identical, except that declarations for an 3075 // array object can specify array types that differ by the presence or 3076 // absence of a major array bound (8.3.4). 3077 else if (Old->getType()->isIncompleteArrayType() && 3078 New->getType()->isArrayType()) { 3079 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3080 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3081 if (Context.hasSameType(OldArray->getElementType(), 3082 NewArray->getElementType())) 3083 MergedT = New->getType(); 3084 } else if (Old->getType()->isArrayType() && 3085 New->getType()->isIncompleteArrayType()) { 3086 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3087 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3088 if (Context.hasSameType(OldArray->getElementType(), 3089 NewArray->getElementType())) 3090 MergedT = Old->getType(); 3091 } else if (New->getType()->isObjCObjectPointerType() && 3092 Old->getType()->isObjCObjectPointerType()) { 3093 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3094 Old->getType()); 3095 } 3096 } else { 3097 // C 6.2.7p2: 3098 // All declarations that refer to the same object or function shall have 3099 // compatible type. 3100 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3101 } 3102 if (MergedT.isNull()) { 3103 // It's OK if we couldn't merge types if either type is dependent, for a 3104 // block-scope variable. In other cases (static data members of class 3105 // templates, variable templates, ...), we require the types to be 3106 // equivalent. 3107 // FIXME: The C++ standard doesn't say anything about this. 3108 if ((New->getType()->isDependentType() || 3109 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3110 // If the old type was dependent, we can't merge with it, so the new type 3111 // becomes dependent for now. We'll reproduce the original type when we 3112 // instantiate the TypeSourceInfo for the variable. 3113 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3114 New->setType(Context.DependentTy); 3115 return; 3116 } 3117 3118 // FIXME: Even if this merging succeeds, some other non-visible declaration 3119 // of this variable might have an incompatible type. For instance: 3120 // 3121 // extern int arr[]; 3122 // void f() { extern int arr[2]; } 3123 // void g() { extern int arr[3]; } 3124 // 3125 // Neither C nor C++ requires a diagnostic for this, but we should still try 3126 // to diagnose it. 3127 Diag(New->getLocation(), diag::err_redefinition_different_type) 3128 << New->getDeclName() << New->getType() << Old->getType(); 3129 Diag(Old->getLocation(), diag::note_previous_definition); 3130 return New->setInvalidDecl(); 3131 } 3132 3133 // Don't actually update the type on the new declaration if the old 3134 // declaration was an extern declaration in a different scope. 3135 if (MergeTypeWithOld) 3136 New->setType(MergedT); 3137 } 3138 3139 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3140 LookupResult &Previous) { 3141 // C11 6.2.7p4: 3142 // For an identifier with internal or external linkage declared 3143 // in a scope in which a prior declaration of that identifier is 3144 // visible, if the prior declaration specifies internal or 3145 // external linkage, the type of the identifier at the later 3146 // declaration becomes the composite type. 3147 // 3148 // If the variable isn't visible, we do not merge with its type. 3149 if (Previous.isShadowed()) 3150 return false; 3151 3152 if (S.getLangOpts().CPlusPlus) { 3153 // C++11 [dcl.array]p3: 3154 // If there is a preceding declaration of the entity in the same 3155 // scope in which the bound was specified, an omitted array bound 3156 // is taken to be the same as in that earlier declaration. 3157 return NewVD->isPreviousDeclInSameBlockScope() || 3158 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3159 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3160 } else { 3161 // If the old declaration was function-local, don't merge with its 3162 // type unless we're in the same function. 3163 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3164 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3165 } 3166 } 3167 3168 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3169 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3170 /// situation, merging decls or emitting diagnostics as appropriate. 3171 /// 3172 /// Tentative definition rules (C99 6.9.2p2) are checked by 3173 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3174 /// definitions here, since the initializer hasn't been attached. 3175 /// 3176 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3177 // If the new decl is already invalid, don't do any other checking. 3178 if (New->isInvalidDecl()) 3179 return; 3180 3181 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3182 3183 // Verify the old decl was also a variable or variable template. 3184 VarDecl *Old = nullptr; 3185 VarTemplateDecl *OldTemplate = nullptr; 3186 if (Previous.isSingleResult()) { 3187 if (NewTemplate) { 3188 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3189 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3190 } else 3191 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3192 } 3193 if (!Old) { 3194 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3195 << New->getDeclName(); 3196 Diag(Previous.getRepresentativeDecl()->getLocation(), 3197 diag::note_previous_definition); 3198 return New->setInvalidDecl(); 3199 } 3200 3201 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3202 return; 3203 3204 // Ensure the template parameters are compatible. 3205 if (NewTemplate && 3206 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3207 OldTemplate->getTemplateParameters(), 3208 /*Complain=*/true, TPL_TemplateMatch)) 3209 return; 3210 3211 // C++ [class.mem]p1: 3212 // A member shall not be declared twice in the member-specification [...] 3213 // 3214 // Here, we need only consider static data members. 3215 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3216 Diag(New->getLocation(), diag::err_duplicate_member) 3217 << New->getIdentifier(); 3218 Diag(Old->getLocation(), diag::note_previous_declaration); 3219 New->setInvalidDecl(); 3220 } 3221 3222 mergeDeclAttributes(New, Old); 3223 // Warn if an already-declared variable is made a weak_import in a subsequent 3224 // declaration 3225 if (New->hasAttr<WeakImportAttr>() && 3226 Old->getStorageClass() == SC_None && 3227 !Old->hasAttr<WeakImportAttr>()) { 3228 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3229 Diag(Old->getLocation(), diag::note_previous_definition); 3230 // Remove weak_import attribute on new declaration. 3231 New->dropAttr<WeakImportAttr>(); 3232 } 3233 3234 // Merge the types. 3235 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3236 3237 if (New->isInvalidDecl()) 3238 return; 3239 3240 diag::kind PrevDiag; 3241 SourceLocation OldLocation; 3242 std::tie(PrevDiag, OldLocation) = 3243 getNoteDiagForInvalidRedeclaration(Old, New); 3244 3245 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3246 if (New->getStorageClass() == SC_Static && 3247 !New->isStaticDataMember() && 3248 Old->hasExternalFormalLinkage()) { 3249 if (getLangOpts().MicrosoftExt) { 3250 Diag(New->getLocation(), diag::ext_static_non_static) 3251 << New->getDeclName(); 3252 Diag(OldLocation, PrevDiag); 3253 } else { 3254 Diag(New->getLocation(), diag::err_static_non_static) 3255 << New->getDeclName(); 3256 Diag(OldLocation, PrevDiag); 3257 return New->setInvalidDecl(); 3258 } 3259 } 3260 // C99 6.2.2p4: 3261 // For an identifier declared with the storage-class specifier 3262 // extern in a scope in which a prior declaration of that 3263 // identifier is visible,23) if the prior declaration specifies 3264 // internal or external linkage, the linkage of the identifier at 3265 // the later declaration is the same as the linkage specified at 3266 // the prior declaration. If no prior declaration is visible, or 3267 // if the prior declaration specifies no linkage, then the 3268 // identifier has external linkage. 3269 if (New->hasExternalStorage() && Old->hasLinkage()) 3270 /* Okay */; 3271 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3272 !New->isStaticDataMember() && 3273 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3274 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3275 Diag(OldLocation, PrevDiag); 3276 return New->setInvalidDecl(); 3277 } 3278 3279 // Check if extern is followed by non-extern and vice-versa. 3280 if (New->hasExternalStorage() && 3281 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3282 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3283 Diag(OldLocation, PrevDiag); 3284 return New->setInvalidDecl(); 3285 } 3286 if (Old->hasLinkage() && New->isLocalVarDecl() && 3287 !New->hasExternalStorage()) { 3288 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3289 Diag(OldLocation, PrevDiag); 3290 return New->setInvalidDecl(); 3291 } 3292 3293 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3294 3295 // FIXME: The test for external storage here seems wrong? We still 3296 // need to check for mismatches. 3297 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3298 // Don't complain about out-of-line definitions of static members. 3299 !(Old->getLexicalDeclContext()->isRecord() && 3300 !New->getLexicalDeclContext()->isRecord())) { 3301 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3302 Diag(OldLocation, PrevDiag); 3303 return New->setInvalidDecl(); 3304 } 3305 3306 if (New->getTLSKind() != Old->getTLSKind()) { 3307 if (!Old->getTLSKind()) { 3308 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3309 Diag(OldLocation, PrevDiag); 3310 } else if (!New->getTLSKind()) { 3311 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3312 Diag(OldLocation, PrevDiag); 3313 } else { 3314 // Do not allow redeclaration to change the variable between requiring 3315 // static and dynamic initialization. 3316 // FIXME: GCC allows this, but uses the TLS keyword on the first 3317 // declaration to determine the kind. Do we need to be compatible here? 3318 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3319 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3320 Diag(OldLocation, PrevDiag); 3321 } 3322 } 3323 3324 // C++ doesn't have tentative definitions, so go right ahead and check here. 3325 const VarDecl *Def; 3326 if (getLangOpts().CPlusPlus && 3327 New->isThisDeclarationADefinition() == VarDecl::Definition && 3328 (Def = Old->getDefinition())) { 3329 Diag(New->getLocation(), diag::err_redefinition) << New; 3330 Diag(Def->getLocation(), diag::note_previous_definition); 3331 New->setInvalidDecl(); 3332 return; 3333 } 3334 3335 if (haveIncompatibleLanguageLinkages(Old, New)) { 3336 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3337 Diag(OldLocation, PrevDiag); 3338 New->setInvalidDecl(); 3339 return; 3340 } 3341 3342 // Merge "used" flag. 3343 if (Old->getMostRecentDecl()->isUsed(false)) 3344 New->setIsUsed(); 3345 3346 // Keep a chain of previous declarations. 3347 New->setPreviousDecl(Old); 3348 if (NewTemplate) 3349 NewTemplate->setPreviousDecl(OldTemplate); 3350 3351 // Inherit access appropriately. 3352 New->setAccess(Old->getAccess()); 3353 if (NewTemplate) 3354 NewTemplate->setAccess(New->getAccess()); 3355 } 3356 3357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3358 /// no declarator (e.g. "struct foo;") is parsed. 3359 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3360 DeclSpec &DS) { 3361 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3362 } 3363 3364 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3365 if (!S.Context.getLangOpts().CPlusPlus) 3366 return; 3367 3368 if (isa<CXXRecordDecl>(Tag->getParent())) { 3369 // If this tag is the direct child of a class, number it if 3370 // it is anonymous. 3371 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3372 return; 3373 MangleNumberingContext &MCtx = 3374 S.Context.getManglingNumberContext(Tag->getParent()); 3375 S.Context.setManglingNumber( 3376 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3377 return; 3378 } 3379 3380 // If this tag isn't a direct child of a class, number it if it is local. 3381 Decl *ManglingContextDecl; 3382 if (MangleNumberingContext *MCtx = 3383 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3384 ManglingContextDecl)) { 3385 S.Context.setManglingNumber( 3386 Tag, 3387 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3388 } 3389 } 3390 3391 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3392 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3393 /// parameters to cope with template friend declarations. 3394 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3395 DeclSpec &DS, 3396 MultiTemplateParamsArg TemplateParams, 3397 bool IsExplicitInstantiation) { 3398 Decl *TagD = nullptr; 3399 TagDecl *Tag = nullptr; 3400 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3401 DS.getTypeSpecType() == DeclSpec::TST_struct || 3402 DS.getTypeSpecType() == DeclSpec::TST_interface || 3403 DS.getTypeSpecType() == DeclSpec::TST_union || 3404 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3405 TagD = DS.getRepAsDecl(); 3406 3407 if (!TagD) // We probably had an error 3408 return nullptr; 3409 3410 // Note that the above type specs guarantee that the 3411 // type rep is a Decl, whereas in many of the others 3412 // it's a Type. 3413 if (isa<TagDecl>(TagD)) 3414 Tag = cast<TagDecl>(TagD); 3415 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3416 Tag = CTD->getTemplatedDecl(); 3417 } 3418 3419 if (Tag) { 3420 HandleTagNumbering(*this, Tag, S); 3421 Tag->setFreeStanding(); 3422 if (Tag->isInvalidDecl()) 3423 return Tag; 3424 } 3425 3426 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3427 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3428 // or incomplete types shall not be restrict-qualified." 3429 if (TypeQuals & DeclSpec::TQ_restrict) 3430 Diag(DS.getRestrictSpecLoc(), 3431 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3432 << DS.getSourceRange(); 3433 } 3434 3435 if (DS.isConstexprSpecified()) { 3436 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3437 // and definitions of functions and variables. 3438 if (Tag) 3439 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3440 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3441 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3442 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3443 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3444 else 3445 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3446 // Don't emit warnings after this error. 3447 return TagD; 3448 } 3449 3450 DiagnoseFunctionSpecifiers(DS); 3451 3452 if (DS.isFriendSpecified()) { 3453 // If we're dealing with a decl but not a TagDecl, assume that 3454 // whatever routines created it handled the friendship aspect. 3455 if (TagD && !Tag) 3456 return nullptr; 3457 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3458 } 3459 3460 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3461 bool IsExplicitSpecialization = 3462 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3463 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3464 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3465 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3466 // nested-name-specifier unless it is an explicit instantiation 3467 // or an explicit specialization. 3468 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3469 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3470 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3471 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3472 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3473 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3474 << SS.getRange(); 3475 return nullptr; 3476 } 3477 3478 // Track whether this decl-specifier declares anything. 3479 bool DeclaresAnything = true; 3480 3481 // Handle anonymous struct definitions. 3482 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3483 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3484 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3485 if (getLangOpts().CPlusPlus || 3486 Record->getDeclContext()->isRecord()) 3487 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3488 3489 DeclaresAnything = false; 3490 } 3491 } 3492 3493 // C11 6.7.2.1p2: 3494 // A struct-declaration that does not declare an anonymous structure or 3495 // anonymous union shall contain a struct-declarator-list. 3496 // 3497 // This rule also existed in C89 and C99; the grammar for struct-declaration 3498 // did not permit a struct-declaration without a struct-declarator-list. 3499 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3500 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3501 // Check for Microsoft C extension: anonymous struct/union member. 3502 // Handle 2 kinds of anonymous struct/union: 3503 // struct STRUCT; 3504 // union UNION; 3505 // and 3506 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3507 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3508 if ((Tag && Tag->getDeclName()) || 3509 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3510 RecordDecl *Record = nullptr; 3511 if (Tag) 3512 Record = dyn_cast<RecordDecl>(Tag); 3513 else if (const RecordType *RT = 3514 DS.getRepAsType().get()->getAsStructureType()) 3515 Record = RT->getDecl(); 3516 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3517 Record = UT->getDecl(); 3518 3519 if (Record && getLangOpts().MicrosoftExt) { 3520 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3521 << Record->isUnion() << DS.getSourceRange(); 3522 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3523 } 3524 3525 DeclaresAnything = false; 3526 } 3527 } 3528 3529 // Skip all the checks below if we have a type error. 3530 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3531 (TagD && TagD->isInvalidDecl())) 3532 return TagD; 3533 3534 if (getLangOpts().CPlusPlus && 3535 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3536 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3537 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3538 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3539 DeclaresAnything = false; 3540 3541 if (!DS.isMissingDeclaratorOk()) { 3542 // Customize diagnostic for a typedef missing a name. 3543 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3544 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3545 << DS.getSourceRange(); 3546 else 3547 DeclaresAnything = false; 3548 } 3549 3550 if (DS.isModulePrivateSpecified() && 3551 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3552 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3553 << Tag->getTagKind() 3554 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3555 3556 ActOnDocumentableDecl(TagD); 3557 3558 // C 6.7/2: 3559 // A declaration [...] shall declare at least a declarator [...], a tag, 3560 // or the members of an enumeration. 3561 // C++ [dcl.dcl]p3: 3562 // [If there are no declarators], and except for the declaration of an 3563 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3564 // names into the program, or shall redeclare a name introduced by a 3565 // previous declaration. 3566 if (!DeclaresAnything) { 3567 // In C, we allow this as a (popular) extension / bug. Don't bother 3568 // producing further diagnostics for redundant qualifiers after this. 3569 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3570 return TagD; 3571 } 3572 3573 // C++ [dcl.stc]p1: 3574 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3575 // init-declarator-list of the declaration shall not be empty. 3576 // C++ [dcl.fct.spec]p1: 3577 // If a cv-qualifier appears in a decl-specifier-seq, the 3578 // init-declarator-list of the declaration shall not be empty. 3579 // 3580 // Spurious qualifiers here appear to be valid in C. 3581 unsigned DiagID = diag::warn_standalone_specifier; 3582 if (getLangOpts().CPlusPlus) 3583 DiagID = diag::ext_standalone_specifier; 3584 3585 // Note that a linkage-specification sets a storage class, but 3586 // 'extern "C" struct foo;' is actually valid and not theoretically 3587 // useless. 3588 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3589 if (SCS == DeclSpec::SCS_mutable) 3590 // Since mutable is not a viable storage class specifier in C, there is 3591 // no reason to treat it as an extension. Instead, diagnose as an error. 3592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3593 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3594 Diag(DS.getStorageClassSpecLoc(), DiagID) 3595 << DeclSpec::getSpecifierName(SCS); 3596 } 3597 3598 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3599 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3600 << DeclSpec::getSpecifierName(TSCS); 3601 if (DS.getTypeQualifiers()) { 3602 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3603 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3604 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3605 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3606 // Restrict is covered above. 3607 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3608 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3609 } 3610 3611 // Warn about ignored type attributes, for example: 3612 // __attribute__((aligned)) struct A; 3613 // Attributes should be placed after tag to apply to type declaration. 3614 if (!DS.getAttributes().empty()) { 3615 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3616 if (TypeSpecType == DeclSpec::TST_class || 3617 TypeSpecType == DeclSpec::TST_struct || 3618 TypeSpecType == DeclSpec::TST_interface || 3619 TypeSpecType == DeclSpec::TST_union || 3620 TypeSpecType == DeclSpec::TST_enum) { 3621 AttributeList* attrs = DS.getAttributes().getList(); 3622 while (attrs) { 3623 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3624 << attrs->getName() 3625 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3626 TypeSpecType == DeclSpec::TST_struct ? 1 : 3627 TypeSpecType == DeclSpec::TST_union ? 2 : 3628 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3629 attrs = attrs->getNext(); 3630 } 3631 } 3632 } 3633 3634 return TagD; 3635 } 3636 3637 /// We are trying to inject an anonymous member into the given scope; 3638 /// check if there's an existing declaration that can't be overloaded. 3639 /// 3640 /// \return true if this is a forbidden redeclaration 3641 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3642 Scope *S, 3643 DeclContext *Owner, 3644 DeclarationName Name, 3645 SourceLocation NameLoc, 3646 unsigned diagnostic) { 3647 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3648 Sema::ForRedeclaration); 3649 if (!SemaRef.LookupName(R, S)) return false; 3650 3651 if (R.getAsSingle<TagDecl>()) 3652 return false; 3653 3654 // Pick a representative declaration. 3655 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3656 assert(PrevDecl && "Expected a non-null Decl"); 3657 3658 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3659 return false; 3660 3661 SemaRef.Diag(NameLoc, diagnostic) << Name; 3662 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3663 3664 return true; 3665 } 3666 3667 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3668 /// anonymous struct or union AnonRecord into the owning context Owner 3669 /// and scope S. This routine will be invoked just after we realize 3670 /// that an unnamed union or struct is actually an anonymous union or 3671 /// struct, e.g., 3672 /// 3673 /// @code 3674 /// union { 3675 /// int i; 3676 /// float f; 3677 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3678 /// // f into the surrounding scope.x 3679 /// @endcode 3680 /// 3681 /// This routine is recursive, injecting the names of nested anonymous 3682 /// structs/unions into the owning context and scope as well. 3683 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3684 DeclContext *Owner, 3685 RecordDecl *AnonRecord, 3686 AccessSpecifier AS, 3687 SmallVectorImpl<NamedDecl *> &Chaining, 3688 bool MSAnonStruct) { 3689 unsigned diagKind 3690 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3691 : diag::err_anonymous_struct_member_redecl; 3692 3693 bool Invalid = false; 3694 3695 // Look every FieldDecl and IndirectFieldDecl with a name. 3696 for (auto *D : AnonRecord->decls()) { 3697 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3698 cast<NamedDecl>(D)->getDeclName()) { 3699 ValueDecl *VD = cast<ValueDecl>(D); 3700 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3701 VD->getLocation(), diagKind)) { 3702 // C++ [class.union]p2: 3703 // The names of the members of an anonymous union shall be 3704 // distinct from the names of any other entity in the 3705 // scope in which the anonymous union is declared. 3706 Invalid = true; 3707 } else { 3708 // C++ [class.union]p2: 3709 // For the purpose of name lookup, after the anonymous union 3710 // definition, the members of the anonymous union are 3711 // considered to have been defined in the scope in which the 3712 // anonymous union is declared. 3713 unsigned OldChainingSize = Chaining.size(); 3714 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3715 for (auto *PI : IF->chain()) 3716 Chaining.push_back(PI); 3717 else 3718 Chaining.push_back(VD); 3719 3720 assert(Chaining.size() >= 2); 3721 NamedDecl **NamedChain = 3722 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3723 for (unsigned i = 0; i < Chaining.size(); i++) 3724 NamedChain[i] = Chaining[i]; 3725 3726 IndirectFieldDecl* IndirectField = 3727 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3728 VD->getIdentifier(), VD->getType(), 3729 NamedChain, Chaining.size()); 3730 3731 IndirectField->setAccess(AS); 3732 IndirectField->setImplicit(); 3733 SemaRef.PushOnScopeChains(IndirectField, S); 3734 3735 // That includes picking up the appropriate access specifier. 3736 if (AS != AS_none) IndirectField->setAccess(AS); 3737 3738 Chaining.resize(OldChainingSize); 3739 } 3740 } 3741 } 3742 3743 return Invalid; 3744 } 3745 3746 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3747 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3748 /// illegal input values are mapped to SC_None. 3749 static StorageClass 3750 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3751 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3752 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3753 "Parser allowed 'typedef' as storage class VarDecl."); 3754 switch (StorageClassSpec) { 3755 case DeclSpec::SCS_unspecified: return SC_None; 3756 case DeclSpec::SCS_extern: 3757 if (DS.isExternInLinkageSpec()) 3758 return SC_None; 3759 return SC_Extern; 3760 case DeclSpec::SCS_static: return SC_Static; 3761 case DeclSpec::SCS_auto: return SC_Auto; 3762 case DeclSpec::SCS_register: return SC_Register; 3763 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3764 // Illegal SCSs map to None: error reporting is up to the caller. 3765 case DeclSpec::SCS_mutable: // Fall through. 3766 case DeclSpec::SCS_typedef: return SC_None; 3767 } 3768 llvm_unreachable("unknown storage class specifier"); 3769 } 3770 3771 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3772 assert(Record->hasInClassInitializer()); 3773 3774 for (const auto *I : Record->decls()) { 3775 const auto *FD = dyn_cast<FieldDecl>(I); 3776 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3777 FD = IFD->getAnonField(); 3778 if (FD && FD->hasInClassInitializer()) 3779 return FD->getLocation(); 3780 } 3781 3782 llvm_unreachable("couldn't find in-class initializer"); 3783 } 3784 3785 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3786 SourceLocation DefaultInitLoc) { 3787 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3788 return; 3789 3790 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3791 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3792 } 3793 3794 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3795 CXXRecordDecl *AnonUnion) { 3796 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3797 return; 3798 3799 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3800 } 3801 3802 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3803 /// anonymous structure or union. Anonymous unions are a C++ feature 3804 /// (C++ [class.union]) and a C11 feature; anonymous structures 3805 /// are a C11 feature and GNU C++ extension. 3806 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3807 AccessSpecifier AS, 3808 RecordDecl *Record, 3809 const PrintingPolicy &Policy) { 3810 DeclContext *Owner = Record->getDeclContext(); 3811 3812 // Diagnose whether this anonymous struct/union is an extension. 3813 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3814 Diag(Record->getLocation(), diag::ext_anonymous_union); 3815 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3816 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3817 else if (!Record->isUnion() && !getLangOpts().C11) 3818 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3819 3820 // C and C++ require different kinds of checks for anonymous 3821 // structs/unions. 3822 bool Invalid = false; 3823 if (getLangOpts().CPlusPlus) { 3824 const char *PrevSpec = nullptr; 3825 unsigned DiagID; 3826 if (Record->isUnion()) { 3827 // C++ [class.union]p6: 3828 // Anonymous unions declared in a named namespace or in the 3829 // global namespace shall be declared static. 3830 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3831 (isa<TranslationUnitDecl>(Owner) || 3832 (isa<NamespaceDecl>(Owner) && 3833 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3834 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3835 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3836 3837 // Recover by adding 'static'. 3838 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3839 PrevSpec, DiagID, Policy); 3840 } 3841 // C++ [class.union]p6: 3842 // A storage class is not allowed in a declaration of an 3843 // anonymous union in a class scope. 3844 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3845 isa<RecordDecl>(Owner)) { 3846 Diag(DS.getStorageClassSpecLoc(), 3847 diag::err_anonymous_union_with_storage_spec) 3848 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3849 3850 // Recover by removing the storage specifier. 3851 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3852 SourceLocation(), 3853 PrevSpec, DiagID, Context.getPrintingPolicy()); 3854 } 3855 } 3856 3857 // Ignore const/volatile/restrict qualifiers. 3858 if (DS.getTypeQualifiers()) { 3859 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3860 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3861 << Record->isUnion() << "const" 3862 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3863 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3864 Diag(DS.getVolatileSpecLoc(), 3865 diag::ext_anonymous_struct_union_qualified) 3866 << Record->isUnion() << "volatile" 3867 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3868 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3869 Diag(DS.getRestrictSpecLoc(), 3870 diag::ext_anonymous_struct_union_qualified) 3871 << Record->isUnion() << "restrict" 3872 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3873 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3874 Diag(DS.getAtomicSpecLoc(), 3875 diag::ext_anonymous_struct_union_qualified) 3876 << Record->isUnion() << "_Atomic" 3877 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3878 3879 DS.ClearTypeQualifiers(); 3880 } 3881 3882 // C++ [class.union]p2: 3883 // The member-specification of an anonymous union shall only 3884 // define non-static data members. [Note: nested types and 3885 // functions cannot be declared within an anonymous union. ] 3886 for (auto *Mem : Record->decls()) { 3887 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3888 // C++ [class.union]p3: 3889 // An anonymous union shall not have private or protected 3890 // members (clause 11). 3891 assert(FD->getAccess() != AS_none); 3892 if (FD->getAccess() != AS_public) { 3893 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3894 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3895 Invalid = true; 3896 } 3897 3898 // C++ [class.union]p1 3899 // An object of a class with a non-trivial constructor, a non-trivial 3900 // copy constructor, a non-trivial destructor, or a non-trivial copy 3901 // assignment operator cannot be a member of a union, nor can an 3902 // array of such objects. 3903 if (CheckNontrivialField(FD)) 3904 Invalid = true; 3905 } else if (Mem->isImplicit()) { 3906 // Any implicit members are fine. 3907 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3908 // This is a type that showed up in an 3909 // elaborated-type-specifier inside the anonymous struct or 3910 // union, but which actually declares a type outside of the 3911 // anonymous struct or union. It's okay. 3912 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3913 if (!MemRecord->isAnonymousStructOrUnion() && 3914 MemRecord->getDeclName()) { 3915 // Visual C++ allows type definition in anonymous struct or union. 3916 if (getLangOpts().MicrosoftExt) 3917 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3918 << (int)Record->isUnion(); 3919 else { 3920 // This is a nested type declaration. 3921 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3922 << (int)Record->isUnion(); 3923 Invalid = true; 3924 } 3925 } else { 3926 // This is an anonymous type definition within another anonymous type. 3927 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3928 // not part of standard C++. 3929 Diag(MemRecord->getLocation(), 3930 diag::ext_anonymous_record_with_anonymous_type) 3931 << (int)Record->isUnion(); 3932 } 3933 } else if (isa<AccessSpecDecl>(Mem)) { 3934 // Any access specifier is fine. 3935 } else if (isa<StaticAssertDecl>(Mem)) { 3936 // In C++1z, static_assert declarations are also fine. 3937 } else { 3938 // We have something that isn't a non-static data 3939 // member. Complain about it. 3940 unsigned DK = diag::err_anonymous_record_bad_member; 3941 if (isa<TypeDecl>(Mem)) 3942 DK = diag::err_anonymous_record_with_type; 3943 else if (isa<FunctionDecl>(Mem)) 3944 DK = diag::err_anonymous_record_with_function; 3945 else if (isa<VarDecl>(Mem)) 3946 DK = diag::err_anonymous_record_with_static; 3947 3948 // Visual C++ allows type definition in anonymous struct or union. 3949 if (getLangOpts().MicrosoftExt && 3950 DK == diag::err_anonymous_record_with_type) 3951 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3952 << (int)Record->isUnion(); 3953 else { 3954 Diag(Mem->getLocation(), DK) 3955 << (int)Record->isUnion(); 3956 Invalid = true; 3957 } 3958 } 3959 } 3960 3961 // C++11 [class.union]p8 (DR1460): 3962 // At most one variant member of a union may have a 3963 // brace-or-equal-initializer. 3964 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3965 Owner->isRecord()) 3966 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3967 cast<CXXRecordDecl>(Record)); 3968 } 3969 3970 if (!Record->isUnion() && !Owner->isRecord()) { 3971 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3972 << (int)getLangOpts().CPlusPlus; 3973 Invalid = true; 3974 } 3975 3976 // Mock up a declarator. 3977 Declarator Dc(DS, Declarator::MemberContext); 3978 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3979 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3980 3981 // Create a declaration for this anonymous struct/union. 3982 NamedDecl *Anon = nullptr; 3983 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3984 Anon = FieldDecl::Create(Context, OwningClass, 3985 DS.getLocStart(), 3986 Record->getLocation(), 3987 /*IdentifierInfo=*/nullptr, 3988 Context.getTypeDeclType(Record), 3989 TInfo, 3990 /*BitWidth=*/nullptr, /*Mutable=*/false, 3991 /*InitStyle=*/ICIS_NoInit); 3992 Anon->setAccess(AS); 3993 if (getLangOpts().CPlusPlus) 3994 FieldCollector->Add(cast<FieldDecl>(Anon)); 3995 } else { 3996 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3997 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3998 if (SCSpec == DeclSpec::SCS_mutable) { 3999 // mutable can only appear on non-static class members, so it's always 4000 // an error here 4001 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4002 Invalid = true; 4003 SC = SC_None; 4004 } 4005 4006 Anon = VarDecl::Create(Context, Owner, 4007 DS.getLocStart(), 4008 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4009 Context.getTypeDeclType(Record), 4010 TInfo, SC); 4011 4012 // Default-initialize the implicit variable. This initialization will be 4013 // trivial in almost all cases, except if a union member has an in-class 4014 // initializer: 4015 // union { int n = 0; }; 4016 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4017 } 4018 Anon->setImplicit(); 4019 4020 // Mark this as an anonymous struct/union type. 4021 Record->setAnonymousStructOrUnion(true); 4022 4023 // Add the anonymous struct/union object to the current 4024 // context. We'll be referencing this object when we refer to one of 4025 // its members. 4026 Owner->addDecl(Anon); 4027 4028 // Inject the members of the anonymous struct/union into the owning 4029 // context and into the identifier resolver chain for name lookup 4030 // purposes. 4031 SmallVector<NamedDecl*, 2> Chain; 4032 Chain.push_back(Anon); 4033 4034 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4035 Chain, false)) 4036 Invalid = true; 4037 4038 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4039 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4040 Decl *ManglingContextDecl; 4041 if (MangleNumberingContext *MCtx = 4042 getCurrentMangleNumberContext(NewVD->getDeclContext(), 4043 ManglingContextDecl)) { 4044 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 4045 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4046 } 4047 } 4048 } 4049 4050 if (Invalid) 4051 Anon->setInvalidDecl(); 4052 4053 return Anon; 4054 } 4055 4056 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4057 /// Microsoft C anonymous structure. 4058 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4059 /// Example: 4060 /// 4061 /// struct A { int a; }; 4062 /// struct B { struct A; int b; }; 4063 /// 4064 /// void foo() { 4065 /// B var; 4066 /// var.a = 3; 4067 /// } 4068 /// 4069 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4070 RecordDecl *Record) { 4071 assert(Record && "expected a record!"); 4072 4073 // Mock up a declarator. 4074 Declarator Dc(DS, Declarator::TypeNameContext); 4075 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4076 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4077 4078 auto *ParentDecl = cast<RecordDecl>(CurContext); 4079 QualType RecTy = Context.getTypeDeclType(Record); 4080 4081 // Create a declaration for this anonymous struct. 4082 NamedDecl *Anon = FieldDecl::Create(Context, 4083 ParentDecl, 4084 DS.getLocStart(), 4085 DS.getLocStart(), 4086 /*IdentifierInfo=*/nullptr, 4087 RecTy, 4088 TInfo, 4089 /*BitWidth=*/nullptr, /*Mutable=*/false, 4090 /*InitStyle=*/ICIS_NoInit); 4091 Anon->setImplicit(); 4092 4093 // Add the anonymous struct object to the current context. 4094 CurContext->addDecl(Anon); 4095 4096 // Inject the members of the anonymous struct into the current 4097 // context and into the identifier resolver chain for name lookup 4098 // purposes. 4099 SmallVector<NamedDecl*, 2> Chain; 4100 Chain.push_back(Anon); 4101 4102 RecordDecl *RecordDef = Record->getDefinition(); 4103 if (RequireCompleteType(Anon->getLocation(), RecTy, 4104 diag::err_field_incomplete) || 4105 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4106 AS_none, Chain, true)) { 4107 Anon->setInvalidDecl(); 4108 ParentDecl->setInvalidDecl(); 4109 } 4110 4111 return Anon; 4112 } 4113 4114 /// GetNameForDeclarator - Determine the full declaration name for the 4115 /// given Declarator. 4116 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4117 return GetNameFromUnqualifiedId(D.getName()); 4118 } 4119 4120 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4121 DeclarationNameInfo 4122 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4123 DeclarationNameInfo NameInfo; 4124 NameInfo.setLoc(Name.StartLocation); 4125 4126 switch (Name.getKind()) { 4127 4128 case UnqualifiedId::IK_ImplicitSelfParam: 4129 case UnqualifiedId::IK_Identifier: 4130 NameInfo.setName(Name.Identifier); 4131 NameInfo.setLoc(Name.StartLocation); 4132 return NameInfo; 4133 4134 case UnqualifiedId::IK_OperatorFunctionId: 4135 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4136 Name.OperatorFunctionId.Operator)); 4137 NameInfo.setLoc(Name.StartLocation); 4138 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4139 = Name.OperatorFunctionId.SymbolLocations[0]; 4140 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4141 = Name.EndLocation.getRawEncoding(); 4142 return NameInfo; 4143 4144 case UnqualifiedId::IK_LiteralOperatorId: 4145 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4146 Name.Identifier)); 4147 NameInfo.setLoc(Name.StartLocation); 4148 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4149 return NameInfo; 4150 4151 case UnqualifiedId::IK_ConversionFunctionId: { 4152 TypeSourceInfo *TInfo; 4153 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4154 if (Ty.isNull()) 4155 return DeclarationNameInfo(); 4156 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4157 Context.getCanonicalType(Ty))); 4158 NameInfo.setLoc(Name.StartLocation); 4159 NameInfo.setNamedTypeInfo(TInfo); 4160 return NameInfo; 4161 } 4162 4163 case UnqualifiedId::IK_ConstructorName: { 4164 TypeSourceInfo *TInfo; 4165 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4166 if (Ty.isNull()) 4167 return DeclarationNameInfo(); 4168 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4169 Context.getCanonicalType(Ty))); 4170 NameInfo.setLoc(Name.StartLocation); 4171 NameInfo.setNamedTypeInfo(TInfo); 4172 return NameInfo; 4173 } 4174 4175 case UnqualifiedId::IK_ConstructorTemplateId: { 4176 // In well-formed code, we can only have a constructor 4177 // template-id that refers to the current context, so go there 4178 // to find the actual type being constructed. 4179 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4180 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4181 return DeclarationNameInfo(); 4182 4183 // Determine the type of the class being constructed. 4184 QualType CurClassType = Context.getTypeDeclType(CurClass); 4185 4186 // FIXME: Check two things: that the template-id names the same type as 4187 // CurClassType, and that the template-id does not occur when the name 4188 // was qualified. 4189 4190 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4191 Context.getCanonicalType(CurClassType))); 4192 NameInfo.setLoc(Name.StartLocation); 4193 // FIXME: should we retrieve TypeSourceInfo? 4194 NameInfo.setNamedTypeInfo(nullptr); 4195 return NameInfo; 4196 } 4197 4198 case UnqualifiedId::IK_DestructorName: { 4199 TypeSourceInfo *TInfo; 4200 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4201 if (Ty.isNull()) 4202 return DeclarationNameInfo(); 4203 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4204 Context.getCanonicalType(Ty))); 4205 NameInfo.setLoc(Name.StartLocation); 4206 NameInfo.setNamedTypeInfo(TInfo); 4207 return NameInfo; 4208 } 4209 4210 case UnqualifiedId::IK_TemplateId: { 4211 TemplateName TName = Name.TemplateId->Template.get(); 4212 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4213 return Context.getNameForTemplate(TName, TNameLoc); 4214 } 4215 4216 } // switch (Name.getKind()) 4217 4218 llvm_unreachable("Unknown name kind"); 4219 } 4220 4221 static QualType getCoreType(QualType Ty) { 4222 do { 4223 if (Ty->isPointerType() || Ty->isReferenceType()) 4224 Ty = Ty->getPointeeType(); 4225 else if (Ty->isArrayType()) 4226 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4227 else 4228 return Ty.withoutLocalFastQualifiers(); 4229 } while (true); 4230 } 4231 4232 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4233 /// and Definition have "nearly" matching parameters. This heuristic is 4234 /// used to improve diagnostics in the case where an out-of-line function 4235 /// definition doesn't match any declaration within the class or namespace. 4236 /// Also sets Params to the list of indices to the parameters that differ 4237 /// between the declaration and the definition. If hasSimilarParameters 4238 /// returns true and Params is empty, then all of the parameters match. 4239 static bool hasSimilarParameters(ASTContext &Context, 4240 FunctionDecl *Declaration, 4241 FunctionDecl *Definition, 4242 SmallVectorImpl<unsigned> &Params) { 4243 Params.clear(); 4244 if (Declaration->param_size() != Definition->param_size()) 4245 return false; 4246 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4247 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4248 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4249 4250 // The parameter types are identical 4251 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4252 continue; 4253 4254 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4255 QualType DefParamBaseTy = getCoreType(DefParamTy); 4256 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4257 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4258 4259 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4260 (DeclTyName && DeclTyName == DefTyName)) 4261 Params.push_back(Idx); 4262 else // The two parameters aren't even close 4263 return false; 4264 } 4265 4266 return true; 4267 } 4268 4269 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4270 /// declarator needs to be rebuilt in the current instantiation. 4271 /// Any bits of declarator which appear before the name are valid for 4272 /// consideration here. That's specifically the type in the decl spec 4273 /// and the base type in any member-pointer chunks. 4274 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4275 DeclarationName Name) { 4276 // The types we specifically need to rebuild are: 4277 // - typenames, typeofs, and decltypes 4278 // - types which will become injected class names 4279 // Of course, we also need to rebuild any type referencing such a 4280 // type. It's safest to just say "dependent", but we call out a 4281 // few cases here. 4282 4283 DeclSpec &DS = D.getMutableDeclSpec(); 4284 switch (DS.getTypeSpecType()) { 4285 case DeclSpec::TST_typename: 4286 case DeclSpec::TST_typeofType: 4287 case DeclSpec::TST_underlyingType: 4288 case DeclSpec::TST_atomic: { 4289 // Grab the type from the parser. 4290 TypeSourceInfo *TSI = nullptr; 4291 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4292 if (T.isNull() || !T->isDependentType()) break; 4293 4294 // Make sure there's a type source info. This isn't really much 4295 // of a waste; most dependent types should have type source info 4296 // attached already. 4297 if (!TSI) 4298 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4299 4300 // Rebuild the type in the current instantiation. 4301 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4302 if (!TSI) return true; 4303 4304 // Store the new type back in the decl spec. 4305 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4306 DS.UpdateTypeRep(LocType); 4307 break; 4308 } 4309 4310 case DeclSpec::TST_decltype: 4311 case DeclSpec::TST_typeofExpr: { 4312 Expr *E = DS.getRepAsExpr(); 4313 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4314 if (Result.isInvalid()) return true; 4315 DS.UpdateExprRep(Result.get()); 4316 break; 4317 } 4318 4319 default: 4320 // Nothing to do for these decl specs. 4321 break; 4322 } 4323 4324 // It doesn't matter what order we do this in. 4325 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4326 DeclaratorChunk &Chunk = D.getTypeObject(I); 4327 4328 // The only type information in the declarator which can come 4329 // before the declaration name is the base type of a member 4330 // pointer. 4331 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4332 continue; 4333 4334 // Rebuild the scope specifier in-place. 4335 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4336 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4337 return true; 4338 } 4339 4340 return false; 4341 } 4342 4343 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4344 D.setFunctionDefinitionKind(FDK_Declaration); 4345 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4346 4347 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4348 Dcl && Dcl->getDeclContext()->isFileContext()) 4349 Dcl->setTopLevelDeclInObjCContainer(); 4350 4351 return Dcl; 4352 } 4353 4354 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4355 /// If T is the name of a class, then each of the following shall have a 4356 /// name different from T: 4357 /// - every static data member of class T; 4358 /// - every member function of class T 4359 /// - every member of class T that is itself a type; 4360 /// \returns true if the declaration name violates these rules. 4361 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4362 DeclarationNameInfo NameInfo) { 4363 DeclarationName Name = NameInfo.getName(); 4364 4365 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4366 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4367 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4368 return true; 4369 } 4370 4371 return false; 4372 } 4373 4374 /// \brief Diagnose a declaration whose declarator-id has the given 4375 /// nested-name-specifier. 4376 /// 4377 /// \param SS The nested-name-specifier of the declarator-id. 4378 /// 4379 /// \param DC The declaration context to which the nested-name-specifier 4380 /// resolves. 4381 /// 4382 /// \param Name The name of the entity being declared. 4383 /// 4384 /// \param Loc The location of the name of the entity being declared. 4385 /// 4386 /// \returns true if we cannot safely recover from this error, false otherwise. 4387 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4388 DeclarationName Name, 4389 SourceLocation Loc) { 4390 DeclContext *Cur = CurContext; 4391 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4392 Cur = Cur->getParent(); 4393 4394 // If the user provided a superfluous scope specifier that refers back to the 4395 // class in which the entity is already declared, diagnose and ignore it. 4396 // 4397 // class X { 4398 // void X::f(); 4399 // }; 4400 // 4401 // Note, it was once ill-formed to give redundant qualification in all 4402 // contexts, but that rule was removed by DR482. 4403 if (Cur->Equals(DC)) { 4404 if (Cur->isRecord()) { 4405 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4406 : diag::err_member_extra_qualification) 4407 << Name << FixItHint::CreateRemoval(SS.getRange()); 4408 SS.clear(); 4409 } else { 4410 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4411 } 4412 return false; 4413 } 4414 4415 // Check whether the qualifying scope encloses the scope of the original 4416 // declaration. 4417 if (!Cur->Encloses(DC)) { 4418 if (Cur->isRecord()) 4419 Diag(Loc, diag::err_member_qualification) 4420 << Name << SS.getRange(); 4421 else if (isa<TranslationUnitDecl>(DC)) 4422 Diag(Loc, diag::err_invalid_declarator_global_scope) 4423 << Name << SS.getRange(); 4424 else if (isa<FunctionDecl>(Cur)) 4425 Diag(Loc, diag::err_invalid_declarator_in_function) 4426 << Name << SS.getRange(); 4427 else if (isa<BlockDecl>(Cur)) 4428 Diag(Loc, diag::err_invalid_declarator_in_block) 4429 << Name << SS.getRange(); 4430 else 4431 Diag(Loc, diag::err_invalid_declarator_scope) 4432 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4433 4434 return true; 4435 } 4436 4437 if (Cur->isRecord()) { 4438 // Cannot qualify members within a class. 4439 Diag(Loc, diag::err_member_qualification) 4440 << Name << SS.getRange(); 4441 SS.clear(); 4442 4443 // C++ constructors and destructors with incorrect scopes can break 4444 // our AST invariants by having the wrong underlying types. If 4445 // that's the case, then drop this declaration entirely. 4446 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4447 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4448 !Context.hasSameType(Name.getCXXNameType(), 4449 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4450 return true; 4451 4452 return false; 4453 } 4454 4455 // C++11 [dcl.meaning]p1: 4456 // [...] "The nested-name-specifier of the qualified declarator-id shall 4457 // not begin with a decltype-specifer" 4458 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4459 while (SpecLoc.getPrefix()) 4460 SpecLoc = SpecLoc.getPrefix(); 4461 if (dyn_cast_or_null<DecltypeType>( 4462 SpecLoc.getNestedNameSpecifier()->getAsType())) 4463 Diag(Loc, diag::err_decltype_in_declarator) 4464 << SpecLoc.getTypeLoc().getSourceRange(); 4465 4466 return false; 4467 } 4468 4469 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4470 MultiTemplateParamsArg TemplateParamLists) { 4471 // TODO: consider using NameInfo for diagnostic. 4472 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4473 DeclarationName Name = NameInfo.getName(); 4474 4475 // All of these full declarators require an identifier. If it doesn't have 4476 // one, the ParsedFreeStandingDeclSpec action should be used. 4477 if (!Name) { 4478 if (!D.isInvalidType()) // Reject this if we think it is valid. 4479 Diag(D.getDeclSpec().getLocStart(), 4480 diag::err_declarator_need_ident) 4481 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4482 return nullptr; 4483 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4484 return nullptr; 4485 4486 // The scope passed in may not be a decl scope. Zip up the scope tree until 4487 // we find one that is. 4488 while ((S->getFlags() & Scope::DeclScope) == 0 || 4489 (S->getFlags() & Scope::TemplateParamScope) != 0) 4490 S = S->getParent(); 4491 4492 DeclContext *DC = CurContext; 4493 if (D.getCXXScopeSpec().isInvalid()) 4494 D.setInvalidType(); 4495 else if (D.getCXXScopeSpec().isSet()) { 4496 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4497 UPPC_DeclarationQualifier)) 4498 return nullptr; 4499 4500 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4501 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4502 if (!DC || isa<EnumDecl>(DC)) { 4503 // If we could not compute the declaration context, it's because the 4504 // declaration context is dependent but does not refer to a class, 4505 // class template, or class template partial specialization. Complain 4506 // and return early, to avoid the coming semantic disaster. 4507 Diag(D.getIdentifierLoc(), 4508 diag::err_template_qualified_declarator_no_match) 4509 << D.getCXXScopeSpec().getScopeRep() 4510 << D.getCXXScopeSpec().getRange(); 4511 return nullptr; 4512 } 4513 bool IsDependentContext = DC->isDependentContext(); 4514 4515 if (!IsDependentContext && 4516 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4517 return nullptr; 4518 4519 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4520 Diag(D.getIdentifierLoc(), 4521 diag::err_member_def_undefined_record) 4522 << Name << DC << D.getCXXScopeSpec().getRange(); 4523 D.setInvalidType(); 4524 } else if (!D.getDeclSpec().isFriendSpecified()) { 4525 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4526 Name, D.getIdentifierLoc())) { 4527 if (DC->isRecord()) 4528 return nullptr; 4529 4530 D.setInvalidType(); 4531 } 4532 } 4533 4534 // Check whether we need to rebuild the type of the given 4535 // declaration in the current instantiation. 4536 if (EnteringContext && IsDependentContext && 4537 TemplateParamLists.size() != 0) { 4538 ContextRAII SavedContext(*this, DC); 4539 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4540 D.setInvalidType(); 4541 } 4542 } 4543 4544 if (DiagnoseClassNameShadow(DC, NameInfo)) 4545 // If this is a typedef, we'll end up spewing multiple diagnostics. 4546 // Just return early; it's safer. 4547 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4548 return nullptr; 4549 4550 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4551 QualType R = TInfo->getType(); 4552 4553 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4554 UPPC_DeclarationType)) 4555 D.setInvalidType(); 4556 4557 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4558 ForRedeclaration); 4559 4560 // See if this is a redefinition of a variable in the same scope. 4561 if (!D.getCXXScopeSpec().isSet()) { 4562 bool IsLinkageLookup = false; 4563 bool CreateBuiltins = false; 4564 4565 // If the declaration we're planning to build will be a function 4566 // or object with linkage, then look for another declaration with 4567 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4568 // 4569 // If the declaration we're planning to build will be declared with 4570 // external linkage in the translation unit, create any builtin with 4571 // the same name. 4572 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4573 /* Do nothing*/; 4574 else if (CurContext->isFunctionOrMethod() && 4575 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4576 R->isFunctionType())) { 4577 IsLinkageLookup = true; 4578 CreateBuiltins = 4579 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4580 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4581 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4582 CreateBuiltins = true; 4583 4584 if (IsLinkageLookup) 4585 Previous.clear(LookupRedeclarationWithLinkage); 4586 4587 LookupName(Previous, S, CreateBuiltins); 4588 } else { // Something like "int foo::x;" 4589 LookupQualifiedName(Previous, DC); 4590 4591 // C++ [dcl.meaning]p1: 4592 // When the declarator-id is qualified, the declaration shall refer to a 4593 // previously declared member of the class or namespace to which the 4594 // qualifier refers (or, in the case of a namespace, of an element of the 4595 // inline namespace set of that namespace (7.3.1)) or to a specialization 4596 // thereof; [...] 4597 // 4598 // Note that we already checked the context above, and that we do not have 4599 // enough information to make sure that Previous contains the declaration 4600 // we want to match. For example, given: 4601 // 4602 // class X { 4603 // void f(); 4604 // void f(float); 4605 // }; 4606 // 4607 // void X::f(int) { } // ill-formed 4608 // 4609 // In this case, Previous will point to the overload set 4610 // containing the two f's declared in X, but neither of them 4611 // matches. 4612 4613 // C++ [dcl.meaning]p1: 4614 // [...] the member shall not merely have been introduced by a 4615 // using-declaration in the scope of the class or namespace nominated by 4616 // the nested-name-specifier of the declarator-id. 4617 RemoveUsingDecls(Previous); 4618 } 4619 4620 if (Previous.isSingleResult() && 4621 Previous.getFoundDecl()->isTemplateParameter()) { 4622 // Maybe we will complain about the shadowed template parameter. 4623 if (!D.isInvalidType()) 4624 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4625 Previous.getFoundDecl()); 4626 4627 // Just pretend that we didn't see the previous declaration. 4628 Previous.clear(); 4629 } 4630 4631 // In C++, the previous declaration we find might be a tag type 4632 // (class or enum). In this case, the new declaration will hide the 4633 // tag type. Note that this does does not apply if we're declaring a 4634 // typedef (C++ [dcl.typedef]p4). 4635 if (Previous.isSingleTagDecl() && 4636 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4637 Previous.clear(); 4638 4639 // Check that there are no default arguments other than in the parameters 4640 // of a function declaration (C++ only). 4641 if (getLangOpts().CPlusPlus) 4642 CheckExtraCXXDefaultArguments(D); 4643 4644 NamedDecl *New; 4645 4646 bool AddToScope = true; 4647 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4648 if (TemplateParamLists.size()) { 4649 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4650 return nullptr; 4651 } 4652 4653 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4654 } else if (R->isFunctionType()) { 4655 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4656 TemplateParamLists, 4657 AddToScope); 4658 } else { 4659 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4660 AddToScope); 4661 } 4662 4663 if (!New) 4664 return nullptr; 4665 4666 // If this has an identifier and is not an invalid redeclaration or 4667 // function template specialization, add it to the scope stack. 4668 if (New->getDeclName() && AddToScope && 4669 !(D.isRedeclaration() && New->isInvalidDecl())) { 4670 // Only make a locally-scoped extern declaration visible if it is the first 4671 // declaration of this entity. Qualified lookup for such an entity should 4672 // only find this declaration if there is no visible declaration of it. 4673 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4674 PushOnScopeChains(New, S, AddToContext); 4675 if (!AddToContext) 4676 CurContext->addHiddenDecl(New); 4677 } 4678 4679 return New; 4680 } 4681 4682 /// Helper method to turn variable array types into constant array 4683 /// types in certain situations which would otherwise be errors (for 4684 /// GCC compatibility). 4685 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4686 ASTContext &Context, 4687 bool &SizeIsNegative, 4688 llvm::APSInt &Oversized) { 4689 // This method tries to turn a variable array into a constant 4690 // array even when the size isn't an ICE. This is necessary 4691 // for compatibility with code that depends on gcc's buggy 4692 // constant expression folding, like struct {char x[(int)(char*)2];} 4693 SizeIsNegative = false; 4694 Oversized = 0; 4695 4696 if (T->isDependentType()) 4697 return QualType(); 4698 4699 QualifierCollector Qs; 4700 const Type *Ty = Qs.strip(T); 4701 4702 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4703 QualType Pointee = PTy->getPointeeType(); 4704 QualType FixedType = 4705 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4706 Oversized); 4707 if (FixedType.isNull()) return FixedType; 4708 FixedType = Context.getPointerType(FixedType); 4709 return Qs.apply(Context, FixedType); 4710 } 4711 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4712 QualType Inner = PTy->getInnerType(); 4713 QualType FixedType = 4714 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4715 Oversized); 4716 if (FixedType.isNull()) return FixedType; 4717 FixedType = Context.getParenType(FixedType); 4718 return Qs.apply(Context, FixedType); 4719 } 4720 4721 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4722 if (!VLATy) 4723 return QualType(); 4724 // FIXME: We should probably handle this case 4725 if (VLATy->getElementType()->isVariablyModifiedType()) 4726 return QualType(); 4727 4728 llvm::APSInt Res; 4729 if (!VLATy->getSizeExpr() || 4730 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4731 return QualType(); 4732 4733 // Check whether the array size is negative. 4734 if (Res.isSigned() && Res.isNegative()) { 4735 SizeIsNegative = true; 4736 return QualType(); 4737 } 4738 4739 // Check whether the array is too large to be addressed. 4740 unsigned ActiveSizeBits 4741 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4742 Res); 4743 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4744 Oversized = Res; 4745 return QualType(); 4746 } 4747 4748 return Context.getConstantArrayType(VLATy->getElementType(), 4749 Res, ArrayType::Normal, 0); 4750 } 4751 4752 static void 4753 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4754 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4755 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4756 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4757 DstPTL.getPointeeLoc()); 4758 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4759 return; 4760 } 4761 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4762 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4763 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4764 DstPTL.getInnerLoc()); 4765 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4766 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4767 return; 4768 } 4769 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4770 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4771 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4772 TypeLoc DstElemTL = DstATL.getElementLoc(); 4773 DstElemTL.initializeFullCopy(SrcElemTL); 4774 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4775 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4776 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4777 } 4778 4779 /// Helper method to turn variable array types into constant array 4780 /// types in certain situations which would otherwise be errors (for 4781 /// GCC compatibility). 4782 static TypeSourceInfo* 4783 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4784 ASTContext &Context, 4785 bool &SizeIsNegative, 4786 llvm::APSInt &Oversized) { 4787 QualType FixedTy 4788 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4789 SizeIsNegative, Oversized); 4790 if (FixedTy.isNull()) 4791 return nullptr; 4792 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4793 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4794 FixedTInfo->getTypeLoc()); 4795 return FixedTInfo; 4796 } 4797 4798 /// \brief Register the given locally-scoped extern "C" declaration so 4799 /// that it can be found later for redeclarations. We include any extern "C" 4800 /// declaration that is not visible in the translation unit here, not just 4801 /// function-scope declarations. 4802 void 4803 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4804 if (!getLangOpts().CPlusPlus && 4805 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4806 // Don't need to track declarations in the TU in C. 4807 return; 4808 4809 // Note that we have a locally-scoped external with this name. 4810 // FIXME: There can be multiple such declarations if they are functions marked 4811 // __attribute__((overloadable)) declared in function scope in C. 4812 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4813 } 4814 4815 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4816 if (ExternalSource) { 4817 // Load locally-scoped external decls from the external source. 4818 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4819 SmallVector<NamedDecl *, 4> Decls; 4820 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4821 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4822 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4823 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4824 if (Pos == LocallyScopedExternCDecls.end()) 4825 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4826 } 4827 } 4828 4829 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4830 return D ? D->getMostRecentDecl() : nullptr; 4831 } 4832 4833 /// \brief Diagnose function specifiers on a declaration of an identifier that 4834 /// does not identify a function. 4835 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4836 // FIXME: We should probably indicate the identifier in question to avoid 4837 // confusion for constructs like "inline int a(), b;" 4838 if (DS.isInlineSpecified()) 4839 Diag(DS.getInlineSpecLoc(), 4840 diag::err_inline_non_function); 4841 4842 if (DS.isVirtualSpecified()) 4843 Diag(DS.getVirtualSpecLoc(), 4844 diag::err_virtual_non_function); 4845 4846 if (DS.isExplicitSpecified()) 4847 Diag(DS.getExplicitSpecLoc(), 4848 diag::err_explicit_non_function); 4849 4850 if (DS.isNoreturnSpecified()) 4851 Diag(DS.getNoreturnSpecLoc(), 4852 diag::err_noreturn_non_function); 4853 } 4854 4855 NamedDecl* 4856 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4857 TypeSourceInfo *TInfo, LookupResult &Previous) { 4858 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4859 if (D.getCXXScopeSpec().isSet()) { 4860 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4861 << D.getCXXScopeSpec().getRange(); 4862 D.setInvalidType(); 4863 // Pretend we didn't see the scope specifier. 4864 DC = CurContext; 4865 Previous.clear(); 4866 } 4867 4868 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4869 4870 if (D.getDeclSpec().isConstexprSpecified()) 4871 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4872 << 1; 4873 4874 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4875 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4876 << D.getName().getSourceRange(); 4877 return nullptr; 4878 } 4879 4880 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4881 if (!NewTD) return nullptr; 4882 4883 // Handle attributes prior to checking for duplicates in MergeVarDecl 4884 ProcessDeclAttributes(S, NewTD, D); 4885 4886 CheckTypedefForVariablyModifiedType(S, NewTD); 4887 4888 bool Redeclaration = D.isRedeclaration(); 4889 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4890 D.setRedeclaration(Redeclaration); 4891 return ND; 4892 } 4893 4894 void 4895 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4896 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4897 // then it shall have block scope. 4898 // Note that variably modified types must be fixed before merging the decl so 4899 // that redeclarations will match. 4900 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4901 QualType T = TInfo->getType(); 4902 if (T->isVariablyModifiedType()) { 4903 getCurFunction()->setHasBranchProtectedScope(); 4904 4905 if (S->getFnParent() == nullptr) { 4906 bool SizeIsNegative; 4907 llvm::APSInt Oversized; 4908 TypeSourceInfo *FixedTInfo = 4909 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4910 SizeIsNegative, 4911 Oversized); 4912 if (FixedTInfo) { 4913 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4914 NewTD->setTypeSourceInfo(FixedTInfo); 4915 } else { 4916 if (SizeIsNegative) 4917 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4918 else if (T->isVariableArrayType()) 4919 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4920 else if (Oversized.getBoolValue()) 4921 Diag(NewTD->getLocation(), diag::err_array_too_large) 4922 << Oversized.toString(10); 4923 else 4924 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4925 NewTD->setInvalidDecl(); 4926 } 4927 } 4928 } 4929 } 4930 4931 4932 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4933 /// declares a typedef-name, either using the 'typedef' type specifier or via 4934 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4935 NamedDecl* 4936 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4937 LookupResult &Previous, bool &Redeclaration) { 4938 // Merge the decl with the existing one if appropriate. If the decl is 4939 // in an outer scope, it isn't the same thing. 4940 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4941 /*AllowInlineNamespace*/false); 4942 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 4943 if (!Previous.empty()) { 4944 Redeclaration = true; 4945 MergeTypedefNameDecl(NewTD, Previous); 4946 } 4947 4948 // If this is the C FILE type, notify the AST context. 4949 if (IdentifierInfo *II = NewTD->getIdentifier()) 4950 if (!NewTD->isInvalidDecl() && 4951 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4952 if (II->isStr("FILE")) 4953 Context.setFILEDecl(NewTD); 4954 else if (II->isStr("jmp_buf")) 4955 Context.setjmp_bufDecl(NewTD); 4956 else if (II->isStr("sigjmp_buf")) 4957 Context.setsigjmp_bufDecl(NewTD); 4958 else if (II->isStr("ucontext_t")) 4959 Context.setucontext_tDecl(NewTD); 4960 } 4961 4962 return NewTD; 4963 } 4964 4965 /// \brief Determines whether the given declaration is an out-of-scope 4966 /// previous declaration. 4967 /// 4968 /// This routine should be invoked when name lookup has found a 4969 /// previous declaration (PrevDecl) that is not in the scope where a 4970 /// new declaration by the same name is being introduced. If the new 4971 /// declaration occurs in a local scope, previous declarations with 4972 /// linkage may still be considered previous declarations (C99 4973 /// 6.2.2p4-5, C++ [basic.link]p6). 4974 /// 4975 /// \param PrevDecl the previous declaration found by name 4976 /// lookup 4977 /// 4978 /// \param DC the context in which the new declaration is being 4979 /// declared. 4980 /// 4981 /// \returns true if PrevDecl is an out-of-scope previous declaration 4982 /// for a new delcaration with the same name. 4983 static bool 4984 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4985 ASTContext &Context) { 4986 if (!PrevDecl) 4987 return false; 4988 4989 if (!PrevDecl->hasLinkage()) 4990 return false; 4991 4992 if (Context.getLangOpts().CPlusPlus) { 4993 // C++ [basic.link]p6: 4994 // If there is a visible declaration of an entity with linkage 4995 // having the same name and type, ignoring entities declared 4996 // outside the innermost enclosing namespace scope, the block 4997 // scope declaration declares that same entity and receives the 4998 // linkage of the previous declaration. 4999 DeclContext *OuterContext = DC->getRedeclContext(); 5000 if (!OuterContext->isFunctionOrMethod()) 5001 // This rule only applies to block-scope declarations. 5002 return false; 5003 5004 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5005 if (PrevOuterContext->isRecord()) 5006 // We found a member function: ignore it. 5007 return false; 5008 5009 // Find the innermost enclosing namespace for the new and 5010 // previous declarations. 5011 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5012 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5013 5014 // The previous declaration is in a different namespace, so it 5015 // isn't the same function. 5016 if (!OuterContext->Equals(PrevOuterContext)) 5017 return false; 5018 } 5019 5020 return true; 5021 } 5022 5023 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5024 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5025 if (!SS.isSet()) return; 5026 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5027 } 5028 5029 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5030 QualType type = decl->getType(); 5031 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5032 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5033 // Various kinds of declaration aren't allowed to be __autoreleasing. 5034 unsigned kind = -1U; 5035 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5036 if (var->hasAttr<BlocksAttr>()) 5037 kind = 0; // __block 5038 else if (!var->hasLocalStorage()) 5039 kind = 1; // global 5040 } else if (isa<ObjCIvarDecl>(decl)) { 5041 kind = 3; // ivar 5042 } else if (isa<FieldDecl>(decl)) { 5043 kind = 2; // field 5044 } 5045 5046 if (kind != -1U) { 5047 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5048 << kind; 5049 } 5050 } else if (lifetime == Qualifiers::OCL_None) { 5051 // Try to infer lifetime. 5052 if (!type->isObjCLifetimeType()) 5053 return false; 5054 5055 lifetime = type->getObjCARCImplicitLifetime(); 5056 type = Context.getLifetimeQualifiedType(type, lifetime); 5057 decl->setType(type); 5058 } 5059 5060 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5061 // Thread-local variables cannot have lifetime. 5062 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5063 var->getTLSKind()) { 5064 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5065 << var->getType(); 5066 return true; 5067 } 5068 } 5069 5070 return false; 5071 } 5072 5073 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5074 // Ensure that an auto decl is deduced otherwise the checks below might cache 5075 // the wrong linkage. 5076 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5077 5078 // 'weak' only applies to declarations with external linkage. 5079 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5080 if (!ND.isExternallyVisible()) { 5081 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5082 ND.dropAttr<WeakAttr>(); 5083 } 5084 } 5085 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5086 if (ND.isExternallyVisible()) { 5087 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5088 ND.dropAttr<WeakRefAttr>(); 5089 } 5090 } 5091 5092 // 'selectany' only applies to externally visible varable declarations. 5093 // It does not apply to functions. 5094 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5095 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5096 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5097 ND.dropAttr<SelectAnyAttr>(); 5098 } 5099 } 5100 5101 // dll attributes require external linkage. 5102 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5103 if (!ND.isExternallyVisible()) { 5104 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5105 << &ND << Attr; 5106 ND.setInvalidDecl(); 5107 } 5108 } 5109 } 5110 5111 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5112 NamedDecl *NewDecl, 5113 bool IsSpecialization) { 5114 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5115 OldDecl = OldTD->getTemplatedDecl(); 5116 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5117 NewDecl = NewTD->getTemplatedDecl(); 5118 5119 if (!OldDecl || !NewDecl) 5120 return; 5121 5122 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5123 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5124 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5125 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5126 5127 // dllimport and dllexport are inheritable attributes so we have to exclude 5128 // inherited attribute instances. 5129 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5130 (NewExportAttr && !NewExportAttr->isInherited()); 5131 5132 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5133 // the only exception being explicit specializations. 5134 // Implicitly generated declarations are also excluded for now because there 5135 // is no other way to switch these to use dllimport or dllexport. 5136 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5137 5138 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5139 // If the declaration hasn't been used yet, allow with a warning for 5140 // free functions and global variables. 5141 bool JustWarn = false; 5142 if (!OldDecl->isUsed() && OldDecl->getDeclContext()->isFileContext()) { 5143 auto *VD = dyn_cast<VarDecl>(OldDecl); 5144 if (VD && !VD->getDescribedVarTemplate()) 5145 JustWarn = true; 5146 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5147 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5148 JustWarn = true; 5149 } 5150 5151 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5152 : diag::err_attribute_dll_redeclaration; 5153 S.Diag(NewDecl->getLocation(), DiagID) 5154 << NewDecl 5155 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5156 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5157 if (!JustWarn) { 5158 NewDecl->setInvalidDecl(); 5159 return; 5160 } 5161 } 5162 5163 // A redeclaration is not allowed to drop a dllimport attribute, the only 5164 // exceptions being inline function definitions, local extern declarations, 5165 // and qualified friend declarations. 5166 // NB: MSVC converts such a declaration to dllexport. 5167 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5168 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5169 // Ignore static data because out-of-line definitions are diagnosed 5170 // separately. 5171 IsStaticDataMember = VD->isStaticDataMember(); 5172 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5173 IsInline = FD->isInlined(); 5174 IsQualifiedFriend = FD->getQualifier() && 5175 FD->getFriendObjectKind() == Decl::FOK_Declared; 5176 } 5177 5178 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5179 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5180 S.Diag(NewDecl->getLocation(), 5181 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5182 << NewDecl << OldImportAttr; 5183 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5184 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5185 OldDecl->dropAttr<DLLImportAttr>(); 5186 NewDecl->dropAttr<DLLImportAttr>(); 5187 } 5188 } 5189 5190 /// Given that we are within the definition of the given function, 5191 /// will that definition behave like C99's 'inline', where the 5192 /// definition is discarded except for optimization purposes? 5193 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5194 // Try to avoid calling GetGVALinkageForFunction. 5195 5196 // All cases of this require the 'inline' keyword. 5197 if (!FD->isInlined()) return false; 5198 5199 // This is only possible in C++ with the gnu_inline attribute. 5200 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5201 return false; 5202 5203 // Okay, go ahead and call the relatively-more-expensive function. 5204 5205 #ifndef NDEBUG 5206 // AST quite reasonably asserts that it's working on a function 5207 // definition. We don't really have a way to tell it that we're 5208 // currently defining the function, so just lie to it in +Asserts 5209 // builds. This is an awful hack. 5210 FD->setLazyBody(1); 5211 #endif 5212 5213 bool isC99Inline = 5214 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5215 5216 #ifndef NDEBUG 5217 FD->setLazyBody(0); 5218 #endif 5219 5220 return isC99Inline; 5221 } 5222 5223 /// Determine whether a variable is extern "C" prior to attaching 5224 /// an initializer. We can't just call isExternC() here, because that 5225 /// will also compute and cache whether the declaration is externally 5226 /// visible, which might change when we attach the initializer. 5227 /// 5228 /// This can only be used if the declaration is known to not be a 5229 /// redeclaration of an internal linkage declaration. 5230 /// 5231 /// For instance: 5232 /// 5233 /// auto x = []{}; 5234 /// 5235 /// Attaching the initializer here makes this declaration not externally 5236 /// visible, because its type has internal linkage. 5237 /// 5238 /// FIXME: This is a hack. 5239 template<typename T> 5240 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5241 if (S.getLangOpts().CPlusPlus) { 5242 // In C++, the overloadable attribute negates the effects of extern "C". 5243 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5244 return false; 5245 } 5246 return D->isExternC(); 5247 } 5248 5249 static bool shouldConsiderLinkage(const VarDecl *VD) { 5250 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5251 if (DC->isFunctionOrMethod()) 5252 return VD->hasExternalStorage(); 5253 if (DC->isFileContext()) 5254 return true; 5255 if (DC->isRecord()) 5256 return false; 5257 llvm_unreachable("Unexpected context"); 5258 } 5259 5260 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5261 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5262 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5263 return true; 5264 if (DC->isRecord()) 5265 return false; 5266 llvm_unreachable("Unexpected context"); 5267 } 5268 5269 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5270 AttributeList::Kind Kind) { 5271 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5272 if (L->getKind() == Kind) 5273 return true; 5274 return false; 5275 } 5276 5277 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5278 AttributeList::Kind Kind) { 5279 // Check decl attributes on the DeclSpec. 5280 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5281 return true; 5282 5283 // Walk the declarator structure, checking decl attributes that were in a type 5284 // position to the decl itself. 5285 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5286 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5287 return true; 5288 } 5289 5290 // Finally, check attributes on the decl itself. 5291 return hasParsedAttr(S, PD.getAttributes(), Kind); 5292 } 5293 5294 /// Adjust the \c DeclContext for a function or variable that might be a 5295 /// function-local external declaration. 5296 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5297 if (!DC->isFunctionOrMethod()) 5298 return false; 5299 5300 // If this is a local extern function or variable declared within a function 5301 // template, don't add it into the enclosing namespace scope until it is 5302 // instantiated; it might have a dependent type right now. 5303 if (DC->isDependentContext()) 5304 return true; 5305 5306 // C++11 [basic.link]p7: 5307 // When a block scope declaration of an entity with linkage is not found to 5308 // refer to some other declaration, then that entity is a member of the 5309 // innermost enclosing namespace. 5310 // 5311 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5312 // semantically-enclosing namespace, not a lexically-enclosing one. 5313 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5314 DC = DC->getParent(); 5315 return true; 5316 } 5317 5318 NamedDecl * 5319 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5320 TypeSourceInfo *TInfo, LookupResult &Previous, 5321 MultiTemplateParamsArg TemplateParamLists, 5322 bool &AddToScope) { 5323 QualType R = TInfo->getType(); 5324 DeclarationName Name = GetNameForDeclarator(D).getName(); 5325 5326 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5327 VarDecl::StorageClass SC = 5328 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5329 5330 // dllimport globals without explicit storage class are treated as extern. We 5331 // have to change the storage class this early to get the right DeclContext. 5332 if (SC == SC_None && !DC->isRecord() && 5333 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5334 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5335 SC = SC_Extern; 5336 5337 DeclContext *OriginalDC = DC; 5338 bool IsLocalExternDecl = SC == SC_Extern && 5339 adjustContextForLocalExternDecl(DC); 5340 5341 if (getLangOpts().OpenCL) { 5342 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5343 QualType NR = R; 5344 while (NR->isPointerType()) { 5345 if (NR->isFunctionPointerType()) { 5346 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5347 D.setInvalidType(); 5348 break; 5349 } 5350 NR = NR->getPointeeType(); 5351 } 5352 5353 if (!getOpenCLOptions().cl_khr_fp16) { 5354 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5355 // half array type (unless the cl_khr_fp16 extension is enabled). 5356 if (Context.getBaseElementType(R)->isHalfType()) { 5357 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5358 D.setInvalidType(); 5359 } 5360 } 5361 } 5362 5363 if (SCSpec == DeclSpec::SCS_mutable) { 5364 // mutable can only appear on non-static class members, so it's always 5365 // an error here 5366 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5367 D.setInvalidType(); 5368 SC = SC_None; 5369 } 5370 5371 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5372 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5373 D.getDeclSpec().getStorageClassSpecLoc())) { 5374 // In C++11, the 'register' storage class specifier is deprecated. 5375 // Suppress the warning in system macros, it's used in macros in some 5376 // popular C system headers, such as in glibc's htonl() macro. 5377 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5378 diag::warn_deprecated_register) 5379 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5380 } 5381 5382 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5383 if (!II) { 5384 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5385 << Name; 5386 return nullptr; 5387 } 5388 5389 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5390 5391 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5392 // C99 6.9p2: The storage-class specifiers auto and register shall not 5393 // appear in the declaration specifiers in an external declaration. 5394 // Global Register+Asm is a GNU extension we support. 5395 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5396 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5397 D.setInvalidType(); 5398 } 5399 } 5400 5401 if (getLangOpts().OpenCL) { 5402 // Set up the special work-group-local storage class for variables in the 5403 // OpenCL __local address space. 5404 if (R.getAddressSpace() == LangAS::opencl_local) { 5405 SC = SC_OpenCLWorkGroupLocal; 5406 } 5407 5408 // OpenCL v1.2 s6.9.b p4: 5409 // The sampler type cannot be used with the __local and __global address 5410 // space qualifiers. 5411 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5412 R.getAddressSpace() == LangAS::opencl_global)) { 5413 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5414 } 5415 5416 // OpenCL 1.2 spec, p6.9 r: 5417 // The event type cannot be used to declare a program scope variable. 5418 // The event type cannot be used with the __local, __constant and __global 5419 // address space qualifiers. 5420 if (R->isEventT()) { 5421 if (S->getParent() == nullptr) { 5422 Diag(D.getLocStart(), diag::err_event_t_global_var); 5423 D.setInvalidType(); 5424 } 5425 5426 if (R.getAddressSpace()) { 5427 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5428 D.setInvalidType(); 5429 } 5430 } 5431 } 5432 5433 bool IsExplicitSpecialization = false; 5434 bool IsVariableTemplateSpecialization = false; 5435 bool IsPartialSpecialization = false; 5436 bool IsVariableTemplate = false; 5437 VarDecl *NewVD = nullptr; 5438 VarTemplateDecl *NewTemplate = nullptr; 5439 TemplateParameterList *TemplateParams = nullptr; 5440 if (!getLangOpts().CPlusPlus) { 5441 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5442 D.getIdentifierLoc(), II, 5443 R, TInfo, SC); 5444 5445 if (D.isInvalidType()) 5446 NewVD->setInvalidDecl(); 5447 } else { 5448 bool Invalid = false; 5449 5450 if (DC->isRecord() && !CurContext->isRecord()) { 5451 // This is an out-of-line definition of a static data member. 5452 switch (SC) { 5453 case SC_None: 5454 break; 5455 case SC_Static: 5456 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5457 diag::err_static_out_of_line) 5458 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5459 break; 5460 case SC_Auto: 5461 case SC_Register: 5462 case SC_Extern: 5463 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5464 // to names of variables declared in a block or to function parameters. 5465 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5466 // of class members 5467 5468 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5469 diag::err_storage_class_for_static_member) 5470 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5471 break; 5472 case SC_PrivateExtern: 5473 llvm_unreachable("C storage class in c++!"); 5474 case SC_OpenCLWorkGroupLocal: 5475 llvm_unreachable("OpenCL storage class in c++!"); 5476 } 5477 } 5478 5479 if (SC == SC_Static && CurContext->isRecord()) { 5480 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5481 if (RD->isLocalClass()) 5482 Diag(D.getIdentifierLoc(), 5483 diag::err_static_data_member_not_allowed_in_local_class) 5484 << Name << RD->getDeclName(); 5485 5486 // C++98 [class.union]p1: If a union contains a static data member, 5487 // the program is ill-formed. C++11 drops this restriction. 5488 if (RD->isUnion()) 5489 Diag(D.getIdentifierLoc(), 5490 getLangOpts().CPlusPlus11 5491 ? diag::warn_cxx98_compat_static_data_member_in_union 5492 : diag::ext_static_data_member_in_union) << Name; 5493 // We conservatively disallow static data members in anonymous structs. 5494 else if (!RD->getDeclName()) 5495 Diag(D.getIdentifierLoc(), 5496 diag::err_static_data_member_not_allowed_in_anon_struct) 5497 << Name << RD->isUnion(); 5498 } 5499 } 5500 5501 // Match up the template parameter lists with the scope specifier, then 5502 // determine whether we have a template or a template specialization. 5503 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5504 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5505 D.getCXXScopeSpec(), 5506 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5507 ? D.getName().TemplateId 5508 : nullptr, 5509 TemplateParamLists, 5510 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5511 5512 if (TemplateParams) { 5513 if (!TemplateParams->size() && 5514 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5515 // There is an extraneous 'template<>' for this variable. Complain 5516 // about it, but allow the declaration of the variable. 5517 Diag(TemplateParams->getTemplateLoc(), 5518 diag::err_template_variable_noparams) 5519 << II 5520 << SourceRange(TemplateParams->getTemplateLoc(), 5521 TemplateParams->getRAngleLoc()); 5522 TemplateParams = nullptr; 5523 } else { 5524 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5525 // This is an explicit specialization or a partial specialization. 5526 // FIXME: Check that we can declare a specialization here. 5527 IsVariableTemplateSpecialization = true; 5528 IsPartialSpecialization = TemplateParams->size() > 0; 5529 } else { // if (TemplateParams->size() > 0) 5530 // This is a template declaration. 5531 IsVariableTemplate = true; 5532 5533 // Check that we can declare a template here. 5534 if (CheckTemplateDeclScope(S, TemplateParams)) 5535 return nullptr; 5536 5537 // Only C++1y supports variable templates (N3651). 5538 Diag(D.getIdentifierLoc(), 5539 getLangOpts().CPlusPlus14 5540 ? diag::warn_cxx11_compat_variable_template 5541 : diag::ext_variable_template); 5542 } 5543 } 5544 } else { 5545 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5546 "should have a 'template<>' for this decl"); 5547 } 5548 5549 if (IsVariableTemplateSpecialization) { 5550 SourceLocation TemplateKWLoc = 5551 TemplateParamLists.size() > 0 5552 ? TemplateParamLists[0]->getTemplateLoc() 5553 : SourceLocation(); 5554 DeclResult Res = ActOnVarTemplateSpecialization( 5555 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5556 IsPartialSpecialization); 5557 if (Res.isInvalid()) 5558 return nullptr; 5559 NewVD = cast<VarDecl>(Res.get()); 5560 AddToScope = false; 5561 } else 5562 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5563 D.getIdentifierLoc(), II, R, TInfo, SC); 5564 5565 // If this is supposed to be a variable template, create it as such. 5566 if (IsVariableTemplate) { 5567 NewTemplate = 5568 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5569 TemplateParams, NewVD); 5570 NewVD->setDescribedVarTemplate(NewTemplate); 5571 } 5572 5573 // If this decl has an auto type in need of deduction, make a note of the 5574 // Decl so we can diagnose uses of it in its own initializer. 5575 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5576 ParsingInitForAutoVars.insert(NewVD); 5577 5578 if (D.isInvalidType() || Invalid) { 5579 NewVD->setInvalidDecl(); 5580 if (NewTemplate) 5581 NewTemplate->setInvalidDecl(); 5582 } 5583 5584 SetNestedNameSpecifier(NewVD, D); 5585 5586 // If we have any template parameter lists that don't directly belong to 5587 // the variable (matching the scope specifier), store them. 5588 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5589 if (TemplateParamLists.size() > VDTemplateParamLists) 5590 NewVD->setTemplateParameterListsInfo( 5591 Context, TemplateParamLists.size() - VDTemplateParamLists, 5592 TemplateParamLists.data()); 5593 5594 if (D.getDeclSpec().isConstexprSpecified()) 5595 NewVD->setConstexpr(true); 5596 } 5597 5598 // Set the lexical context. If the declarator has a C++ scope specifier, the 5599 // lexical context will be different from the semantic context. 5600 NewVD->setLexicalDeclContext(CurContext); 5601 if (NewTemplate) 5602 NewTemplate->setLexicalDeclContext(CurContext); 5603 5604 if (IsLocalExternDecl) 5605 NewVD->setLocalExternDecl(); 5606 5607 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5608 if (NewVD->hasLocalStorage()) { 5609 // C++11 [dcl.stc]p4: 5610 // When thread_local is applied to a variable of block scope the 5611 // storage-class-specifier static is implied if it does not appear 5612 // explicitly. 5613 // Core issue: 'static' is not implied if the variable is declared 5614 // 'extern'. 5615 if (SCSpec == DeclSpec::SCS_unspecified && 5616 TSCS == DeclSpec::TSCS_thread_local && 5617 DC->isFunctionOrMethod()) 5618 NewVD->setTSCSpec(TSCS); 5619 else 5620 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5621 diag::err_thread_non_global) 5622 << DeclSpec::getSpecifierName(TSCS); 5623 } else if (!Context.getTargetInfo().isTLSSupported()) 5624 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5625 diag::err_thread_unsupported); 5626 else 5627 NewVD->setTSCSpec(TSCS); 5628 } 5629 5630 // C99 6.7.4p3 5631 // An inline definition of a function with external linkage shall 5632 // not contain a definition of a modifiable object with static or 5633 // thread storage duration... 5634 // We only apply this when the function is required to be defined 5635 // elsewhere, i.e. when the function is not 'extern inline'. Note 5636 // that a local variable with thread storage duration still has to 5637 // be marked 'static'. Also note that it's possible to get these 5638 // semantics in C++ using __attribute__((gnu_inline)). 5639 if (SC == SC_Static && S->getFnParent() != nullptr && 5640 !NewVD->getType().isConstQualified()) { 5641 FunctionDecl *CurFD = getCurFunctionDecl(); 5642 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5643 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5644 diag::warn_static_local_in_extern_inline); 5645 MaybeSuggestAddingStaticToDecl(CurFD); 5646 } 5647 } 5648 5649 if (D.getDeclSpec().isModulePrivateSpecified()) { 5650 if (IsVariableTemplateSpecialization) 5651 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5652 << (IsPartialSpecialization ? 1 : 0) 5653 << FixItHint::CreateRemoval( 5654 D.getDeclSpec().getModulePrivateSpecLoc()); 5655 else if (IsExplicitSpecialization) 5656 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5657 << 2 5658 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5659 else if (NewVD->hasLocalStorage()) 5660 Diag(NewVD->getLocation(), diag::err_module_private_local) 5661 << 0 << NewVD->getDeclName() 5662 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5663 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5664 else { 5665 NewVD->setModulePrivate(); 5666 if (NewTemplate) 5667 NewTemplate->setModulePrivate(); 5668 } 5669 } 5670 5671 // Handle attributes prior to checking for duplicates in MergeVarDecl 5672 ProcessDeclAttributes(S, NewVD, D); 5673 5674 if (getLangOpts().CUDA) { 5675 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5676 // storage [duration]." 5677 if (SC == SC_None && S->getFnParent() != nullptr && 5678 (NewVD->hasAttr<CUDASharedAttr>() || 5679 NewVD->hasAttr<CUDAConstantAttr>())) { 5680 NewVD->setStorageClass(SC_Static); 5681 } 5682 } 5683 5684 // Ensure that dllimport globals without explicit storage class are treated as 5685 // extern. The storage class is set above using parsed attributes. Now we can 5686 // check the VarDecl itself. 5687 assert(!NewVD->hasAttr<DLLImportAttr>() || 5688 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5689 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5690 5691 // In auto-retain/release, infer strong retension for variables of 5692 // retainable type. 5693 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5694 NewVD->setInvalidDecl(); 5695 5696 // Handle GNU asm-label extension (encoded as an attribute). 5697 if (Expr *E = (Expr*)D.getAsmLabel()) { 5698 // The parser guarantees this is a string. 5699 StringLiteral *SE = cast<StringLiteral>(E); 5700 StringRef Label = SE->getString(); 5701 if (S->getFnParent() != nullptr) { 5702 switch (SC) { 5703 case SC_None: 5704 case SC_Auto: 5705 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5706 break; 5707 case SC_Register: 5708 // Local Named register 5709 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5710 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5711 break; 5712 case SC_Static: 5713 case SC_Extern: 5714 case SC_PrivateExtern: 5715 case SC_OpenCLWorkGroupLocal: 5716 break; 5717 } 5718 } else if (SC == SC_Register) { 5719 // Global Named register 5720 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5721 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5722 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5723 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5724 NewVD->setInvalidDecl(true); 5725 } 5726 } 5727 5728 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5729 Context, Label, 0)); 5730 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5731 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5732 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5733 if (I != ExtnameUndeclaredIdentifiers.end()) { 5734 NewVD->addAttr(I->second); 5735 ExtnameUndeclaredIdentifiers.erase(I); 5736 } 5737 } 5738 5739 // Diagnose shadowed variables before filtering for scope. 5740 if (D.getCXXScopeSpec().isEmpty()) 5741 CheckShadow(S, NewVD, Previous); 5742 5743 // Don't consider existing declarations that are in a different 5744 // scope and are out-of-semantic-context declarations (if the new 5745 // declaration has linkage). 5746 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5747 D.getCXXScopeSpec().isNotEmpty() || 5748 IsExplicitSpecialization || 5749 IsVariableTemplateSpecialization); 5750 5751 // Check whether the previous declaration is in the same block scope. This 5752 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5753 if (getLangOpts().CPlusPlus && 5754 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5755 NewVD->setPreviousDeclInSameBlockScope( 5756 Previous.isSingleResult() && !Previous.isShadowed() && 5757 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5758 5759 if (!getLangOpts().CPlusPlus) { 5760 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5761 } else { 5762 // If this is an explicit specialization of a static data member, check it. 5763 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5764 CheckMemberSpecialization(NewVD, Previous)) 5765 NewVD->setInvalidDecl(); 5766 5767 // Merge the decl with the existing one if appropriate. 5768 if (!Previous.empty()) { 5769 if (Previous.isSingleResult() && 5770 isa<FieldDecl>(Previous.getFoundDecl()) && 5771 D.getCXXScopeSpec().isSet()) { 5772 // The user tried to define a non-static data member 5773 // out-of-line (C++ [dcl.meaning]p1). 5774 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5775 << D.getCXXScopeSpec().getRange(); 5776 Previous.clear(); 5777 NewVD->setInvalidDecl(); 5778 } 5779 } else if (D.getCXXScopeSpec().isSet()) { 5780 // No previous declaration in the qualifying scope. 5781 Diag(D.getIdentifierLoc(), diag::err_no_member) 5782 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5783 << D.getCXXScopeSpec().getRange(); 5784 NewVD->setInvalidDecl(); 5785 } 5786 5787 if (!IsVariableTemplateSpecialization) 5788 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5789 5790 if (NewTemplate) { 5791 VarTemplateDecl *PrevVarTemplate = 5792 NewVD->getPreviousDecl() 5793 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5794 : nullptr; 5795 5796 // Check the template parameter list of this declaration, possibly 5797 // merging in the template parameter list from the previous variable 5798 // template declaration. 5799 if (CheckTemplateParameterList( 5800 TemplateParams, 5801 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5802 : nullptr, 5803 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5804 DC->isDependentContext()) 5805 ? TPC_ClassTemplateMember 5806 : TPC_VarTemplate)) 5807 NewVD->setInvalidDecl(); 5808 5809 // If we are providing an explicit specialization of a static variable 5810 // template, make a note of that. 5811 if (PrevVarTemplate && 5812 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5813 PrevVarTemplate->setMemberSpecialization(); 5814 } 5815 } 5816 5817 ProcessPragmaWeak(S, NewVD); 5818 5819 // If this is the first declaration of an extern C variable, update 5820 // the map of such variables. 5821 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5822 isIncompleteDeclExternC(*this, NewVD)) 5823 RegisterLocallyScopedExternCDecl(NewVD, S); 5824 5825 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5826 Decl *ManglingContextDecl; 5827 if (MangleNumberingContext *MCtx = 5828 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5829 ManglingContextDecl)) { 5830 Context.setManglingNumber( 5831 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5832 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5833 } 5834 } 5835 5836 if (D.isRedeclaration() && !Previous.empty()) { 5837 checkDLLAttributeRedeclaration( 5838 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5839 IsExplicitSpecialization); 5840 } 5841 5842 if (NewTemplate) { 5843 if (NewVD->isInvalidDecl()) 5844 NewTemplate->setInvalidDecl(); 5845 ActOnDocumentableDecl(NewTemplate); 5846 return NewTemplate; 5847 } 5848 5849 return NewVD; 5850 } 5851 5852 /// \brief Diagnose variable or built-in function shadowing. Implements 5853 /// -Wshadow. 5854 /// 5855 /// This method is called whenever a VarDecl is added to a "useful" 5856 /// scope. 5857 /// 5858 /// \param S the scope in which the shadowing name is being declared 5859 /// \param R the lookup of the name 5860 /// 5861 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5862 // Return if warning is ignored. 5863 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5864 return; 5865 5866 // Don't diagnose declarations at file scope. 5867 if (D->hasGlobalStorage()) 5868 return; 5869 5870 DeclContext *NewDC = D->getDeclContext(); 5871 5872 // Only diagnose if we're shadowing an unambiguous field or variable. 5873 if (R.getResultKind() != LookupResult::Found) 5874 return; 5875 5876 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5877 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5878 return; 5879 5880 // Fields are not shadowed by variables in C++ static methods. 5881 if (isa<FieldDecl>(ShadowedDecl)) 5882 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5883 if (MD->isStatic()) 5884 return; 5885 5886 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5887 if (shadowedVar->isExternC()) { 5888 // For shadowing external vars, make sure that we point to the global 5889 // declaration, not a locally scoped extern declaration. 5890 for (auto I : shadowedVar->redecls()) 5891 if (I->isFileVarDecl()) { 5892 ShadowedDecl = I; 5893 break; 5894 } 5895 } 5896 5897 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5898 5899 // Only warn about certain kinds of shadowing for class members. 5900 if (NewDC && NewDC->isRecord()) { 5901 // In particular, don't warn about shadowing non-class members. 5902 if (!OldDC->isRecord()) 5903 return; 5904 5905 // TODO: should we warn about static data members shadowing 5906 // static data members from base classes? 5907 5908 // TODO: don't diagnose for inaccessible shadowed members. 5909 // This is hard to do perfectly because we might friend the 5910 // shadowing context, but that's just a false negative. 5911 } 5912 5913 // Determine what kind of declaration we're shadowing. 5914 unsigned Kind; 5915 if (isa<RecordDecl>(OldDC)) { 5916 if (isa<FieldDecl>(ShadowedDecl)) 5917 Kind = 3; // field 5918 else 5919 Kind = 2; // static data member 5920 } else if (OldDC->isFileContext()) 5921 Kind = 1; // global 5922 else 5923 Kind = 0; // local 5924 5925 DeclarationName Name = R.getLookupName(); 5926 5927 // Emit warning and note. 5928 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5929 return; 5930 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5931 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5932 } 5933 5934 /// \brief Check -Wshadow without the advantage of a previous lookup. 5935 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5936 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 5937 return; 5938 5939 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5940 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5941 LookupName(R, S); 5942 CheckShadow(S, D, R); 5943 } 5944 5945 /// Check for conflict between this global or extern "C" declaration and 5946 /// previous global or extern "C" declarations. This is only used in C++. 5947 template<typename T> 5948 static bool checkGlobalOrExternCConflict( 5949 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5950 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5951 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5952 5953 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5954 // The common case: this global doesn't conflict with any extern "C" 5955 // declaration. 5956 return false; 5957 } 5958 5959 if (Prev) { 5960 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5961 // Both the old and new declarations have C language linkage. This is a 5962 // redeclaration. 5963 Previous.clear(); 5964 Previous.addDecl(Prev); 5965 return true; 5966 } 5967 5968 // This is a global, non-extern "C" declaration, and there is a previous 5969 // non-global extern "C" declaration. Diagnose if this is a variable 5970 // declaration. 5971 if (!isa<VarDecl>(ND)) 5972 return false; 5973 } else { 5974 // The declaration is extern "C". Check for any declaration in the 5975 // translation unit which might conflict. 5976 if (IsGlobal) { 5977 // We have already performed the lookup into the translation unit. 5978 IsGlobal = false; 5979 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5980 I != E; ++I) { 5981 if (isa<VarDecl>(*I)) { 5982 Prev = *I; 5983 break; 5984 } 5985 } 5986 } else { 5987 DeclContext::lookup_result R = 5988 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5989 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5990 I != E; ++I) { 5991 if (isa<VarDecl>(*I)) { 5992 Prev = *I; 5993 break; 5994 } 5995 // FIXME: If we have any other entity with this name in global scope, 5996 // the declaration is ill-formed, but that is a defect: it breaks the 5997 // 'stat' hack, for instance. Only variables can have mangled name 5998 // clashes with extern "C" declarations, so only they deserve a 5999 // diagnostic. 6000 } 6001 } 6002 6003 if (!Prev) 6004 return false; 6005 } 6006 6007 // Use the first declaration's location to ensure we point at something which 6008 // is lexically inside an extern "C" linkage-spec. 6009 assert(Prev && "should have found a previous declaration to diagnose"); 6010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6011 Prev = FD->getFirstDecl(); 6012 else 6013 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6014 6015 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6016 << IsGlobal << ND; 6017 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6018 << IsGlobal; 6019 return false; 6020 } 6021 6022 /// Apply special rules for handling extern "C" declarations. Returns \c true 6023 /// if we have found that this is a redeclaration of some prior entity. 6024 /// 6025 /// Per C++ [dcl.link]p6: 6026 /// Two declarations [for a function or variable] with C language linkage 6027 /// with the same name that appear in different scopes refer to the same 6028 /// [entity]. An entity with C language linkage shall not be declared with 6029 /// the same name as an entity in global scope. 6030 template<typename T> 6031 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6032 LookupResult &Previous) { 6033 if (!S.getLangOpts().CPlusPlus) { 6034 // In C, when declaring a global variable, look for a corresponding 'extern' 6035 // variable declared in function scope. We don't need this in C++, because 6036 // we find local extern decls in the surrounding file-scope DeclContext. 6037 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6038 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6039 Previous.clear(); 6040 Previous.addDecl(Prev); 6041 return true; 6042 } 6043 } 6044 return false; 6045 } 6046 6047 // A declaration in the translation unit can conflict with an extern "C" 6048 // declaration. 6049 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6050 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6051 6052 // An extern "C" declaration can conflict with a declaration in the 6053 // translation unit or can be a redeclaration of an extern "C" declaration 6054 // in another scope. 6055 if (isIncompleteDeclExternC(S,ND)) 6056 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6057 6058 // Neither global nor extern "C": nothing to do. 6059 return false; 6060 } 6061 6062 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6063 // If the decl is already known invalid, don't check it. 6064 if (NewVD->isInvalidDecl()) 6065 return; 6066 6067 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6068 QualType T = TInfo->getType(); 6069 6070 // Defer checking an 'auto' type until its initializer is attached. 6071 if (T->isUndeducedType()) 6072 return; 6073 6074 if (NewVD->hasAttrs()) 6075 CheckAlignasUnderalignment(NewVD); 6076 6077 if (T->isObjCObjectType()) { 6078 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6079 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6080 T = Context.getObjCObjectPointerType(T); 6081 NewVD->setType(T); 6082 } 6083 6084 // Emit an error if an address space was applied to decl with local storage. 6085 // This includes arrays of objects with address space qualifiers, but not 6086 // automatic variables that point to other address spaces. 6087 // ISO/IEC TR 18037 S5.1.2 6088 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6089 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6090 NewVD->setInvalidDecl(); 6091 return; 6092 } 6093 6094 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6095 // __constant address space. 6096 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6097 && T.getAddressSpace() != LangAS::opencl_constant 6098 && !T->isSamplerT()){ 6099 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6100 NewVD->setInvalidDecl(); 6101 return; 6102 } 6103 6104 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6105 // scope. 6106 if ((getLangOpts().OpenCLVersion >= 120) 6107 && NewVD->isStaticLocal()) { 6108 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6109 NewVD->setInvalidDecl(); 6110 return; 6111 } 6112 6113 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6114 && !NewVD->hasAttr<BlocksAttr>()) { 6115 if (getLangOpts().getGC() != LangOptions::NonGC) 6116 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6117 else { 6118 assert(!getLangOpts().ObjCAutoRefCount); 6119 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6120 } 6121 } 6122 6123 bool isVM = T->isVariablyModifiedType(); 6124 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6125 NewVD->hasAttr<BlocksAttr>()) 6126 getCurFunction()->setHasBranchProtectedScope(); 6127 6128 if ((isVM && NewVD->hasLinkage()) || 6129 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6130 bool SizeIsNegative; 6131 llvm::APSInt Oversized; 6132 TypeSourceInfo *FixedTInfo = 6133 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6134 SizeIsNegative, Oversized); 6135 if (!FixedTInfo && T->isVariableArrayType()) { 6136 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6137 // FIXME: This won't give the correct result for 6138 // int a[10][n]; 6139 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6140 6141 if (NewVD->isFileVarDecl()) 6142 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6143 << SizeRange; 6144 else if (NewVD->isStaticLocal()) 6145 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6146 << SizeRange; 6147 else 6148 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6149 << SizeRange; 6150 NewVD->setInvalidDecl(); 6151 return; 6152 } 6153 6154 if (!FixedTInfo) { 6155 if (NewVD->isFileVarDecl()) 6156 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6157 else 6158 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6159 NewVD->setInvalidDecl(); 6160 return; 6161 } 6162 6163 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6164 NewVD->setType(FixedTInfo->getType()); 6165 NewVD->setTypeSourceInfo(FixedTInfo); 6166 } 6167 6168 if (T->isVoidType()) { 6169 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6170 // of objects and functions. 6171 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6172 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6173 << T; 6174 NewVD->setInvalidDecl(); 6175 return; 6176 } 6177 } 6178 6179 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6180 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6181 NewVD->setInvalidDecl(); 6182 return; 6183 } 6184 6185 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6186 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6187 NewVD->setInvalidDecl(); 6188 return; 6189 } 6190 6191 if (NewVD->isConstexpr() && !T->isDependentType() && 6192 RequireLiteralType(NewVD->getLocation(), T, 6193 diag::err_constexpr_var_non_literal)) { 6194 NewVD->setInvalidDecl(); 6195 return; 6196 } 6197 } 6198 6199 /// \brief Perform semantic checking on a newly-created variable 6200 /// declaration. 6201 /// 6202 /// This routine performs all of the type-checking required for a 6203 /// variable declaration once it has been built. It is used both to 6204 /// check variables after they have been parsed and their declarators 6205 /// have been translated into a declaration, and to check variables 6206 /// that have been instantiated from a template. 6207 /// 6208 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6209 /// 6210 /// Returns true if the variable declaration is a redeclaration. 6211 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6212 CheckVariableDeclarationType(NewVD); 6213 6214 // If the decl is already known invalid, don't check it. 6215 if (NewVD->isInvalidDecl()) 6216 return false; 6217 6218 // If we did not find anything by this name, look for a non-visible 6219 // extern "C" declaration with the same name. 6220 if (Previous.empty() && 6221 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6222 Previous.setShadowed(); 6223 6224 // Filter out any non-conflicting previous declarations. 6225 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6226 6227 if (!Previous.empty()) { 6228 MergeVarDecl(NewVD, Previous); 6229 return true; 6230 } 6231 return false; 6232 } 6233 6234 /// \brief Data used with FindOverriddenMethod 6235 struct FindOverriddenMethodData { 6236 Sema *S; 6237 CXXMethodDecl *Method; 6238 }; 6239 6240 /// \brief Member lookup function that determines whether a given C++ 6241 /// method overrides a method in a base class, to be used with 6242 /// CXXRecordDecl::lookupInBases(). 6243 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6244 CXXBasePath &Path, 6245 void *UserData) { 6246 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6247 6248 FindOverriddenMethodData *Data 6249 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6250 6251 DeclarationName Name = Data->Method->getDeclName(); 6252 6253 // FIXME: Do we care about other names here too? 6254 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6255 // We really want to find the base class destructor here. 6256 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6257 CanQualType CT = Data->S->Context.getCanonicalType(T); 6258 6259 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6260 } 6261 6262 for (Path.Decls = BaseRecord->lookup(Name); 6263 !Path.Decls.empty(); 6264 Path.Decls = Path.Decls.slice(1)) { 6265 NamedDecl *D = Path.Decls.front(); 6266 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6267 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6268 return true; 6269 } 6270 } 6271 6272 return false; 6273 } 6274 6275 namespace { 6276 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6277 } 6278 /// \brief Report an error regarding overriding, along with any relevant 6279 /// overriden methods. 6280 /// 6281 /// \param DiagID the primary error to report. 6282 /// \param MD the overriding method. 6283 /// \param OEK which overrides to include as notes. 6284 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6285 OverrideErrorKind OEK = OEK_All) { 6286 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6287 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6288 E = MD->end_overridden_methods(); 6289 I != E; ++I) { 6290 // This check (& the OEK parameter) could be replaced by a predicate, but 6291 // without lambdas that would be overkill. This is still nicer than writing 6292 // out the diag loop 3 times. 6293 if ((OEK == OEK_All) || 6294 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6295 (OEK == OEK_Deleted && (*I)->isDeleted())) 6296 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6297 } 6298 } 6299 6300 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6301 /// and if so, check that it's a valid override and remember it. 6302 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6303 // Look for virtual methods in base classes that this method might override. 6304 CXXBasePaths Paths; 6305 FindOverriddenMethodData Data; 6306 Data.Method = MD; 6307 Data.S = this; 6308 bool hasDeletedOverridenMethods = false; 6309 bool hasNonDeletedOverridenMethods = false; 6310 bool AddedAny = false; 6311 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6312 for (auto *I : Paths.found_decls()) { 6313 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6314 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6315 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6316 !CheckOverridingFunctionAttributes(MD, OldMD) && 6317 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6318 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6319 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6320 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6321 AddedAny = true; 6322 } 6323 } 6324 } 6325 } 6326 6327 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6328 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6329 } 6330 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6331 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6332 } 6333 6334 return AddedAny; 6335 } 6336 6337 namespace { 6338 // Struct for holding all of the extra arguments needed by 6339 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6340 struct ActOnFDArgs { 6341 Scope *S; 6342 Declarator &D; 6343 MultiTemplateParamsArg TemplateParamLists; 6344 bool AddToScope; 6345 }; 6346 } 6347 6348 namespace { 6349 6350 // Callback to only accept typo corrections that have a non-zero edit distance. 6351 // Also only accept corrections that have the same parent decl. 6352 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6353 public: 6354 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6355 CXXRecordDecl *Parent) 6356 : Context(Context), OriginalFD(TypoFD), 6357 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6358 6359 bool ValidateCandidate(const TypoCorrection &candidate) override { 6360 if (candidate.getEditDistance() == 0) 6361 return false; 6362 6363 SmallVector<unsigned, 1> MismatchedParams; 6364 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6365 CDeclEnd = candidate.end(); 6366 CDecl != CDeclEnd; ++CDecl) { 6367 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6368 6369 if (FD && !FD->hasBody() && 6370 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6371 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6372 CXXRecordDecl *Parent = MD->getParent(); 6373 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6374 return true; 6375 } else if (!ExpectedParent) { 6376 return true; 6377 } 6378 } 6379 } 6380 6381 return false; 6382 } 6383 6384 private: 6385 ASTContext &Context; 6386 FunctionDecl *OriginalFD; 6387 CXXRecordDecl *ExpectedParent; 6388 }; 6389 6390 } 6391 6392 /// \brief Generate diagnostics for an invalid function redeclaration. 6393 /// 6394 /// This routine handles generating the diagnostic messages for an invalid 6395 /// function redeclaration, including finding possible similar declarations 6396 /// or performing typo correction if there are no previous declarations with 6397 /// the same name. 6398 /// 6399 /// Returns a NamedDecl iff typo correction was performed and substituting in 6400 /// the new declaration name does not cause new errors. 6401 static NamedDecl *DiagnoseInvalidRedeclaration( 6402 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6403 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6404 DeclarationName Name = NewFD->getDeclName(); 6405 DeclContext *NewDC = NewFD->getDeclContext(); 6406 SmallVector<unsigned, 1> MismatchedParams; 6407 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6408 TypoCorrection Correction; 6409 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6410 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6411 : diag::err_member_decl_does_not_match; 6412 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6413 IsLocalFriend ? Sema::LookupLocalFriendName 6414 : Sema::LookupOrdinaryName, 6415 Sema::ForRedeclaration); 6416 6417 NewFD->setInvalidDecl(); 6418 if (IsLocalFriend) 6419 SemaRef.LookupName(Prev, S); 6420 else 6421 SemaRef.LookupQualifiedName(Prev, NewDC); 6422 assert(!Prev.isAmbiguous() && 6423 "Cannot have an ambiguity in previous-declaration lookup"); 6424 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6425 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6426 MD ? MD->getParent() : nullptr); 6427 if (!Prev.empty()) { 6428 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6429 Func != FuncEnd; ++Func) { 6430 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6431 if (FD && 6432 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6433 // Add 1 to the index so that 0 can mean the mismatch didn't 6434 // involve a parameter 6435 unsigned ParamNum = 6436 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6437 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6438 } 6439 } 6440 // If the qualified name lookup yielded nothing, try typo correction 6441 } else if ((Correction = SemaRef.CorrectTypo( 6442 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6443 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6444 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6445 // Set up everything for the call to ActOnFunctionDeclarator 6446 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6447 ExtraArgs.D.getIdentifierLoc()); 6448 Previous.clear(); 6449 Previous.setLookupName(Correction.getCorrection()); 6450 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6451 CDeclEnd = Correction.end(); 6452 CDecl != CDeclEnd; ++CDecl) { 6453 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6454 if (FD && !FD->hasBody() && 6455 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6456 Previous.addDecl(FD); 6457 } 6458 } 6459 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6460 6461 NamedDecl *Result; 6462 // Retry building the function declaration with the new previous 6463 // declarations, and with errors suppressed. 6464 { 6465 // Trap errors. 6466 Sema::SFINAETrap Trap(SemaRef); 6467 6468 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6469 // pieces need to verify the typo-corrected C++ declaration and hopefully 6470 // eliminate the need for the parameter pack ExtraArgs. 6471 Result = SemaRef.ActOnFunctionDeclarator( 6472 ExtraArgs.S, ExtraArgs.D, 6473 Correction.getCorrectionDecl()->getDeclContext(), 6474 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6475 ExtraArgs.AddToScope); 6476 6477 if (Trap.hasErrorOccurred()) 6478 Result = nullptr; 6479 } 6480 6481 if (Result) { 6482 // Determine which correction we picked. 6483 Decl *Canonical = Result->getCanonicalDecl(); 6484 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6485 I != E; ++I) 6486 if ((*I)->getCanonicalDecl() == Canonical) 6487 Correction.setCorrectionDecl(*I); 6488 6489 SemaRef.diagnoseTypo( 6490 Correction, 6491 SemaRef.PDiag(IsLocalFriend 6492 ? diag::err_no_matching_local_friend_suggest 6493 : diag::err_member_decl_does_not_match_suggest) 6494 << Name << NewDC << IsDefinition); 6495 return Result; 6496 } 6497 6498 // Pretend the typo correction never occurred 6499 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6500 ExtraArgs.D.getIdentifierLoc()); 6501 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6502 Previous.clear(); 6503 Previous.setLookupName(Name); 6504 } 6505 6506 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6507 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6508 6509 bool NewFDisConst = false; 6510 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6511 NewFDisConst = NewMD->isConst(); 6512 6513 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6514 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6515 NearMatch != NearMatchEnd; ++NearMatch) { 6516 FunctionDecl *FD = NearMatch->first; 6517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6518 bool FDisConst = MD && MD->isConst(); 6519 bool IsMember = MD || !IsLocalFriend; 6520 6521 // FIXME: These notes are poorly worded for the local friend case. 6522 if (unsigned Idx = NearMatch->second) { 6523 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6524 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6525 if (Loc.isInvalid()) Loc = FD->getLocation(); 6526 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6527 : diag::note_local_decl_close_param_match) 6528 << Idx << FDParam->getType() 6529 << NewFD->getParamDecl(Idx - 1)->getType(); 6530 } else if (FDisConst != NewFDisConst) { 6531 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6532 << NewFDisConst << FD->getSourceRange().getEnd(); 6533 } else 6534 SemaRef.Diag(FD->getLocation(), 6535 IsMember ? diag::note_member_def_close_match 6536 : diag::note_local_decl_close_match); 6537 } 6538 return nullptr; 6539 } 6540 6541 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6542 Declarator &D) { 6543 switch (D.getDeclSpec().getStorageClassSpec()) { 6544 default: llvm_unreachable("Unknown storage class!"); 6545 case DeclSpec::SCS_auto: 6546 case DeclSpec::SCS_register: 6547 case DeclSpec::SCS_mutable: 6548 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6549 diag::err_typecheck_sclass_func); 6550 D.setInvalidType(); 6551 break; 6552 case DeclSpec::SCS_unspecified: break; 6553 case DeclSpec::SCS_extern: 6554 if (D.getDeclSpec().isExternInLinkageSpec()) 6555 return SC_None; 6556 return SC_Extern; 6557 case DeclSpec::SCS_static: { 6558 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6559 // C99 6.7.1p5: 6560 // The declaration of an identifier for a function that has 6561 // block scope shall have no explicit storage-class specifier 6562 // other than extern 6563 // See also (C++ [dcl.stc]p4). 6564 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6565 diag::err_static_block_func); 6566 break; 6567 } else 6568 return SC_Static; 6569 } 6570 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6571 } 6572 6573 // No explicit storage class has already been returned 6574 return SC_None; 6575 } 6576 6577 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6578 DeclContext *DC, QualType &R, 6579 TypeSourceInfo *TInfo, 6580 FunctionDecl::StorageClass SC, 6581 bool &IsVirtualOkay) { 6582 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6583 DeclarationName Name = NameInfo.getName(); 6584 6585 FunctionDecl *NewFD = nullptr; 6586 bool isInline = D.getDeclSpec().isInlineSpecified(); 6587 6588 if (!SemaRef.getLangOpts().CPlusPlus) { 6589 // Determine whether the function was written with a 6590 // prototype. This true when: 6591 // - there is a prototype in the declarator, or 6592 // - the type R of the function is some kind of typedef or other reference 6593 // to a type name (which eventually refers to a function type). 6594 bool HasPrototype = 6595 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6596 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6597 6598 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6599 D.getLocStart(), NameInfo, R, 6600 TInfo, SC, isInline, 6601 HasPrototype, false); 6602 if (D.isInvalidType()) 6603 NewFD->setInvalidDecl(); 6604 6605 // Set the lexical context. 6606 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6607 6608 return NewFD; 6609 } 6610 6611 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6612 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6613 6614 // Check that the return type is not an abstract class type. 6615 // For record types, this is done by the AbstractClassUsageDiagnoser once 6616 // the class has been completely parsed. 6617 if (!DC->isRecord() && 6618 SemaRef.RequireNonAbstractType( 6619 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6620 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6621 D.setInvalidType(); 6622 6623 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6624 // This is a C++ constructor declaration. 6625 assert(DC->isRecord() && 6626 "Constructors can only be declared in a member context"); 6627 6628 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6629 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6630 D.getLocStart(), NameInfo, 6631 R, TInfo, isExplicit, isInline, 6632 /*isImplicitlyDeclared=*/false, 6633 isConstexpr); 6634 6635 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6636 // This is a C++ destructor declaration. 6637 if (DC->isRecord()) { 6638 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6639 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6640 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6641 SemaRef.Context, Record, 6642 D.getLocStart(), 6643 NameInfo, R, TInfo, isInline, 6644 /*isImplicitlyDeclared=*/false); 6645 6646 // If the class is complete, then we now create the implicit exception 6647 // specification. If the class is incomplete or dependent, we can't do 6648 // it yet. 6649 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6650 Record->getDefinition() && !Record->isBeingDefined() && 6651 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6652 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6653 } 6654 6655 IsVirtualOkay = true; 6656 return NewDD; 6657 6658 } else { 6659 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6660 D.setInvalidType(); 6661 6662 // Create a FunctionDecl to satisfy the function definition parsing 6663 // code path. 6664 return FunctionDecl::Create(SemaRef.Context, DC, 6665 D.getLocStart(), 6666 D.getIdentifierLoc(), Name, R, TInfo, 6667 SC, isInline, 6668 /*hasPrototype=*/true, isConstexpr); 6669 } 6670 6671 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6672 if (!DC->isRecord()) { 6673 SemaRef.Diag(D.getIdentifierLoc(), 6674 diag::err_conv_function_not_member); 6675 return nullptr; 6676 } 6677 6678 SemaRef.CheckConversionDeclarator(D, R, SC); 6679 IsVirtualOkay = true; 6680 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6681 D.getLocStart(), NameInfo, 6682 R, TInfo, isInline, isExplicit, 6683 isConstexpr, SourceLocation()); 6684 6685 } else if (DC->isRecord()) { 6686 // If the name of the function is the same as the name of the record, 6687 // then this must be an invalid constructor that has a return type. 6688 // (The parser checks for a return type and makes the declarator a 6689 // constructor if it has no return type). 6690 if (Name.getAsIdentifierInfo() && 6691 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6692 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6693 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6694 << SourceRange(D.getIdentifierLoc()); 6695 return nullptr; 6696 } 6697 6698 // This is a C++ method declaration. 6699 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6700 cast<CXXRecordDecl>(DC), 6701 D.getLocStart(), NameInfo, R, 6702 TInfo, SC, isInline, 6703 isConstexpr, SourceLocation()); 6704 IsVirtualOkay = !Ret->isStatic(); 6705 return Ret; 6706 } else { 6707 // Determine whether the function was written with a 6708 // prototype. This true when: 6709 // - we're in C++ (where every function has a prototype), 6710 return FunctionDecl::Create(SemaRef.Context, DC, 6711 D.getLocStart(), 6712 NameInfo, R, TInfo, SC, isInline, 6713 true/*HasPrototype*/, isConstexpr); 6714 } 6715 } 6716 6717 enum OpenCLParamType { 6718 ValidKernelParam, 6719 PtrPtrKernelParam, 6720 PtrKernelParam, 6721 PrivatePtrKernelParam, 6722 InvalidKernelParam, 6723 RecordKernelParam 6724 }; 6725 6726 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6727 if (PT->isPointerType()) { 6728 QualType PointeeType = PT->getPointeeType(); 6729 if (PointeeType->isPointerType()) 6730 return PtrPtrKernelParam; 6731 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6732 : PtrKernelParam; 6733 } 6734 6735 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6736 // be used as builtin types. 6737 6738 if (PT->isImageType()) 6739 return PtrKernelParam; 6740 6741 if (PT->isBooleanType()) 6742 return InvalidKernelParam; 6743 6744 if (PT->isEventT()) 6745 return InvalidKernelParam; 6746 6747 if (PT->isHalfType()) 6748 return InvalidKernelParam; 6749 6750 if (PT->isRecordType()) 6751 return RecordKernelParam; 6752 6753 return ValidKernelParam; 6754 } 6755 6756 static void checkIsValidOpenCLKernelParameter( 6757 Sema &S, 6758 Declarator &D, 6759 ParmVarDecl *Param, 6760 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6761 QualType PT = Param->getType(); 6762 6763 // Cache the valid types we encounter to avoid rechecking structs that are 6764 // used again 6765 if (ValidTypes.count(PT.getTypePtr())) 6766 return; 6767 6768 switch (getOpenCLKernelParameterType(PT)) { 6769 case PtrPtrKernelParam: 6770 // OpenCL v1.2 s6.9.a: 6771 // A kernel function argument cannot be declared as a 6772 // pointer to a pointer type. 6773 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6774 D.setInvalidType(); 6775 return; 6776 6777 case PrivatePtrKernelParam: 6778 // OpenCL v1.2 s6.9.a: 6779 // A kernel function argument cannot be declared as a 6780 // pointer to the private address space. 6781 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6782 D.setInvalidType(); 6783 return; 6784 6785 // OpenCL v1.2 s6.9.k: 6786 // Arguments to kernel functions in a program cannot be declared with the 6787 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6788 // uintptr_t or a struct and/or union that contain fields declared to be 6789 // one of these built-in scalar types. 6790 6791 case InvalidKernelParam: 6792 // OpenCL v1.2 s6.8 n: 6793 // A kernel function argument cannot be declared 6794 // of event_t type. 6795 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6796 D.setInvalidType(); 6797 return; 6798 6799 case PtrKernelParam: 6800 case ValidKernelParam: 6801 ValidTypes.insert(PT.getTypePtr()); 6802 return; 6803 6804 case RecordKernelParam: 6805 break; 6806 } 6807 6808 // Track nested structs we will inspect 6809 SmallVector<const Decl *, 4> VisitStack; 6810 6811 // Track where we are in the nested structs. Items will migrate from 6812 // VisitStack to HistoryStack as we do the DFS for bad field. 6813 SmallVector<const FieldDecl *, 4> HistoryStack; 6814 HistoryStack.push_back(nullptr); 6815 6816 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6817 VisitStack.push_back(PD); 6818 6819 assert(VisitStack.back() && "First decl null?"); 6820 6821 do { 6822 const Decl *Next = VisitStack.pop_back_val(); 6823 if (!Next) { 6824 assert(!HistoryStack.empty()); 6825 // Found a marker, we have gone up a level 6826 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6827 ValidTypes.insert(Hist->getType().getTypePtr()); 6828 6829 continue; 6830 } 6831 6832 // Adds everything except the original parameter declaration (which is not a 6833 // field itself) to the history stack. 6834 const RecordDecl *RD; 6835 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6836 HistoryStack.push_back(Field); 6837 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6838 } else { 6839 RD = cast<RecordDecl>(Next); 6840 } 6841 6842 // Add a null marker so we know when we've gone back up a level 6843 VisitStack.push_back(nullptr); 6844 6845 for (const auto *FD : RD->fields()) { 6846 QualType QT = FD->getType(); 6847 6848 if (ValidTypes.count(QT.getTypePtr())) 6849 continue; 6850 6851 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6852 if (ParamType == ValidKernelParam) 6853 continue; 6854 6855 if (ParamType == RecordKernelParam) { 6856 VisitStack.push_back(FD); 6857 continue; 6858 } 6859 6860 // OpenCL v1.2 s6.9.p: 6861 // Arguments to kernel functions that are declared to be a struct or union 6862 // do not allow OpenCL objects to be passed as elements of the struct or 6863 // union. 6864 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6865 ParamType == PrivatePtrKernelParam) { 6866 S.Diag(Param->getLocation(), 6867 diag::err_record_with_pointers_kernel_param) 6868 << PT->isUnionType() 6869 << PT; 6870 } else { 6871 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6872 } 6873 6874 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6875 << PD->getDeclName(); 6876 6877 // We have an error, now let's go back up through history and show where 6878 // the offending field came from 6879 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6880 E = HistoryStack.end(); I != E; ++I) { 6881 const FieldDecl *OuterField = *I; 6882 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6883 << OuterField->getType(); 6884 } 6885 6886 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6887 << QT->isPointerType() 6888 << QT; 6889 D.setInvalidType(); 6890 return; 6891 } 6892 } while (!VisitStack.empty()); 6893 } 6894 6895 NamedDecl* 6896 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6897 TypeSourceInfo *TInfo, LookupResult &Previous, 6898 MultiTemplateParamsArg TemplateParamLists, 6899 bool &AddToScope) { 6900 QualType R = TInfo->getType(); 6901 6902 assert(R.getTypePtr()->isFunctionType()); 6903 6904 // TODO: consider using NameInfo for diagnostic. 6905 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6906 DeclarationName Name = NameInfo.getName(); 6907 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6908 6909 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6910 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6911 diag::err_invalid_thread) 6912 << DeclSpec::getSpecifierName(TSCS); 6913 6914 if (D.isFirstDeclarationOfMember()) 6915 adjustMemberFunctionCC(R, D.isStaticMember()); 6916 6917 bool isFriend = false; 6918 FunctionTemplateDecl *FunctionTemplate = nullptr; 6919 bool isExplicitSpecialization = false; 6920 bool isFunctionTemplateSpecialization = false; 6921 6922 bool isDependentClassScopeExplicitSpecialization = false; 6923 bool HasExplicitTemplateArgs = false; 6924 TemplateArgumentListInfo TemplateArgs; 6925 6926 bool isVirtualOkay = false; 6927 6928 DeclContext *OriginalDC = DC; 6929 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6930 6931 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6932 isVirtualOkay); 6933 if (!NewFD) return nullptr; 6934 6935 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6936 NewFD->setTopLevelDeclInObjCContainer(); 6937 6938 // Set the lexical context. If this is a function-scope declaration, or has a 6939 // C++ scope specifier, or is the object of a friend declaration, the lexical 6940 // context will be different from the semantic context. 6941 NewFD->setLexicalDeclContext(CurContext); 6942 6943 if (IsLocalExternDecl) 6944 NewFD->setLocalExternDecl(); 6945 6946 if (getLangOpts().CPlusPlus) { 6947 bool isInline = D.getDeclSpec().isInlineSpecified(); 6948 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6949 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6950 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6951 isFriend = D.getDeclSpec().isFriendSpecified(); 6952 if (isFriend && !isInline && D.isFunctionDefinition()) { 6953 // C++ [class.friend]p5 6954 // A function can be defined in a friend declaration of a 6955 // class . . . . Such a function is implicitly inline. 6956 NewFD->setImplicitlyInline(); 6957 } 6958 6959 // If this is a method defined in an __interface, and is not a constructor 6960 // or an overloaded operator, then set the pure flag (isVirtual will already 6961 // return true). 6962 if (const CXXRecordDecl *Parent = 6963 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6964 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6965 NewFD->setPure(true); 6966 } 6967 6968 SetNestedNameSpecifier(NewFD, D); 6969 isExplicitSpecialization = false; 6970 isFunctionTemplateSpecialization = false; 6971 if (D.isInvalidType()) 6972 NewFD->setInvalidDecl(); 6973 6974 // Match up the template parameter lists with the scope specifier, then 6975 // determine whether we have a template or a template specialization. 6976 bool Invalid = false; 6977 if (TemplateParameterList *TemplateParams = 6978 MatchTemplateParametersToScopeSpecifier( 6979 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6980 D.getCXXScopeSpec(), 6981 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6982 ? D.getName().TemplateId 6983 : nullptr, 6984 TemplateParamLists, isFriend, isExplicitSpecialization, 6985 Invalid)) { 6986 if (TemplateParams->size() > 0) { 6987 // This is a function template 6988 6989 // Check that we can declare a template here. 6990 if (CheckTemplateDeclScope(S, TemplateParams)) 6991 return nullptr; 6992 6993 // A destructor cannot be a template. 6994 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6995 Diag(NewFD->getLocation(), diag::err_destructor_template); 6996 return nullptr; 6997 } 6998 6999 // If we're adding a template to a dependent context, we may need to 7000 // rebuilding some of the types used within the template parameter list, 7001 // now that we know what the current instantiation is. 7002 if (DC->isDependentContext()) { 7003 ContextRAII SavedContext(*this, DC); 7004 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7005 Invalid = true; 7006 } 7007 7008 7009 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7010 NewFD->getLocation(), 7011 Name, TemplateParams, 7012 NewFD); 7013 FunctionTemplate->setLexicalDeclContext(CurContext); 7014 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7015 7016 // For source fidelity, store the other template param lists. 7017 if (TemplateParamLists.size() > 1) { 7018 NewFD->setTemplateParameterListsInfo(Context, 7019 TemplateParamLists.size() - 1, 7020 TemplateParamLists.data()); 7021 } 7022 } else { 7023 // This is a function template specialization. 7024 isFunctionTemplateSpecialization = true; 7025 // For source fidelity, store all the template param lists. 7026 if (TemplateParamLists.size() > 0) 7027 NewFD->setTemplateParameterListsInfo(Context, 7028 TemplateParamLists.size(), 7029 TemplateParamLists.data()); 7030 7031 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7032 if (isFriend) { 7033 // We want to remove the "template<>", found here. 7034 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7035 7036 // If we remove the template<> and the name is not a 7037 // template-id, we're actually silently creating a problem: 7038 // the friend declaration will refer to an untemplated decl, 7039 // and clearly the user wants a template specialization. So 7040 // we need to insert '<>' after the name. 7041 SourceLocation InsertLoc; 7042 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7043 InsertLoc = D.getName().getSourceRange().getEnd(); 7044 InsertLoc = getLocForEndOfToken(InsertLoc); 7045 } 7046 7047 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7048 << Name << RemoveRange 7049 << FixItHint::CreateRemoval(RemoveRange) 7050 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7051 } 7052 } 7053 } 7054 else { 7055 // All template param lists were matched against the scope specifier: 7056 // this is NOT (an explicit specialization of) a template. 7057 if (TemplateParamLists.size() > 0) 7058 // For source fidelity, store all the template param lists. 7059 NewFD->setTemplateParameterListsInfo(Context, 7060 TemplateParamLists.size(), 7061 TemplateParamLists.data()); 7062 } 7063 7064 if (Invalid) { 7065 NewFD->setInvalidDecl(); 7066 if (FunctionTemplate) 7067 FunctionTemplate->setInvalidDecl(); 7068 } 7069 7070 // C++ [dcl.fct.spec]p5: 7071 // The virtual specifier shall only be used in declarations of 7072 // nonstatic class member functions that appear within a 7073 // member-specification of a class declaration; see 10.3. 7074 // 7075 if (isVirtual && !NewFD->isInvalidDecl()) { 7076 if (!isVirtualOkay) { 7077 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7078 diag::err_virtual_non_function); 7079 } else if (!CurContext->isRecord()) { 7080 // 'virtual' was specified outside of the class. 7081 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7082 diag::err_virtual_out_of_class) 7083 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7084 } else if (NewFD->getDescribedFunctionTemplate()) { 7085 // C++ [temp.mem]p3: 7086 // A member function template shall not be virtual. 7087 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7088 diag::err_virtual_member_function_template) 7089 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7090 } else { 7091 // Okay: Add virtual to the method. 7092 NewFD->setVirtualAsWritten(true); 7093 } 7094 7095 if (getLangOpts().CPlusPlus14 && 7096 NewFD->getReturnType()->isUndeducedType()) 7097 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7098 } 7099 7100 if (getLangOpts().CPlusPlus14 && 7101 (NewFD->isDependentContext() || 7102 (isFriend && CurContext->isDependentContext())) && 7103 NewFD->getReturnType()->isUndeducedType()) { 7104 // If the function template is referenced directly (for instance, as a 7105 // member of the current instantiation), pretend it has a dependent type. 7106 // This is not really justified by the standard, but is the only sane 7107 // thing to do. 7108 // FIXME: For a friend function, we have not marked the function as being 7109 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7110 const FunctionProtoType *FPT = 7111 NewFD->getType()->castAs<FunctionProtoType>(); 7112 QualType Result = 7113 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7114 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7115 FPT->getExtProtoInfo())); 7116 } 7117 7118 // C++ [dcl.fct.spec]p3: 7119 // The inline specifier shall not appear on a block scope function 7120 // declaration. 7121 if (isInline && !NewFD->isInvalidDecl()) { 7122 if (CurContext->isFunctionOrMethod()) { 7123 // 'inline' is not allowed on block scope function declaration. 7124 Diag(D.getDeclSpec().getInlineSpecLoc(), 7125 diag::err_inline_declaration_block_scope) << Name 7126 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7127 } 7128 } 7129 7130 // C++ [dcl.fct.spec]p6: 7131 // The explicit specifier shall be used only in the declaration of a 7132 // constructor or conversion function within its class definition; 7133 // see 12.3.1 and 12.3.2. 7134 if (isExplicit && !NewFD->isInvalidDecl()) { 7135 if (!CurContext->isRecord()) { 7136 // 'explicit' was specified outside of the class. 7137 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7138 diag::err_explicit_out_of_class) 7139 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7140 } else if (!isa<CXXConstructorDecl>(NewFD) && 7141 !isa<CXXConversionDecl>(NewFD)) { 7142 // 'explicit' was specified on a function that wasn't a constructor 7143 // or conversion function. 7144 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7145 diag::err_explicit_non_ctor_or_conv_function) 7146 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7147 } 7148 } 7149 7150 if (isConstexpr) { 7151 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7152 // are implicitly inline. 7153 NewFD->setImplicitlyInline(); 7154 7155 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7156 // be either constructors or to return a literal type. Therefore, 7157 // destructors cannot be declared constexpr. 7158 if (isa<CXXDestructorDecl>(NewFD)) 7159 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7160 } 7161 7162 // If __module_private__ was specified, mark the function accordingly. 7163 if (D.getDeclSpec().isModulePrivateSpecified()) { 7164 if (isFunctionTemplateSpecialization) { 7165 SourceLocation ModulePrivateLoc 7166 = D.getDeclSpec().getModulePrivateSpecLoc(); 7167 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7168 << 0 7169 << FixItHint::CreateRemoval(ModulePrivateLoc); 7170 } else { 7171 NewFD->setModulePrivate(); 7172 if (FunctionTemplate) 7173 FunctionTemplate->setModulePrivate(); 7174 } 7175 } 7176 7177 if (isFriend) { 7178 if (FunctionTemplate) { 7179 FunctionTemplate->setObjectOfFriendDecl(); 7180 FunctionTemplate->setAccess(AS_public); 7181 } 7182 NewFD->setObjectOfFriendDecl(); 7183 NewFD->setAccess(AS_public); 7184 } 7185 7186 // If a function is defined as defaulted or deleted, mark it as such now. 7187 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7188 // definition kind to FDK_Definition. 7189 switch (D.getFunctionDefinitionKind()) { 7190 case FDK_Declaration: 7191 case FDK_Definition: 7192 break; 7193 7194 case FDK_Defaulted: 7195 NewFD->setDefaulted(); 7196 break; 7197 7198 case FDK_Deleted: 7199 NewFD->setDeletedAsWritten(); 7200 break; 7201 } 7202 7203 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7204 D.isFunctionDefinition()) { 7205 // C++ [class.mfct]p2: 7206 // A member function may be defined (8.4) in its class definition, in 7207 // which case it is an inline member function (7.1.2) 7208 NewFD->setImplicitlyInline(); 7209 } 7210 7211 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7212 !CurContext->isRecord()) { 7213 // C++ [class.static]p1: 7214 // A data or function member of a class may be declared static 7215 // in a class definition, in which case it is a static member of 7216 // the class. 7217 7218 // Complain about the 'static' specifier if it's on an out-of-line 7219 // member function definition. 7220 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7221 diag::err_static_out_of_line) 7222 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7223 } 7224 7225 // C++11 [except.spec]p15: 7226 // A deallocation function with no exception-specification is treated 7227 // as if it were specified with noexcept(true). 7228 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7229 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7230 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7231 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7232 NewFD->setType(Context.getFunctionType( 7233 FPT->getReturnType(), FPT->getParamTypes(), 7234 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7235 } 7236 7237 // Filter out previous declarations that don't match the scope. 7238 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7239 D.getCXXScopeSpec().isNotEmpty() || 7240 isExplicitSpecialization || 7241 isFunctionTemplateSpecialization); 7242 7243 // Handle GNU asm-label extension (encoded as an attribute). 7244 if (Expr *E = (Expr*) D.getAsmLabel()) { 7245 // The parser guarantees this is a string. 7246 StringLiteral *SE = cast<StringLiteral>(E); 7247 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7248 SE->getString(), 0)); 7249 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7250 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7251 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7252 if (I != ExtnameUndeclaredIdentifiers.end()) { 7253 NewFD->addAttr(I->second); 7254 ExtnameUndeclaredIdentifiers.erase(I); 7255 } 7256 } 7257 7258 // Copy the parameter declarations from the declarator D to the function 7259 // declaration NewFD, if they are available. First scavenge them into Params. 7260 SmallVector<ParmVarDecl*, 16> Params; 7261 if (D.isFunctionDeclarator()) { 7262 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7263 7264 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7265 // function that takes no arguments, not a function that takes a 7266 // single void argument. 7267 // We let through "const void" here because Sema::GetTypeForDeclarator 7268 // already checks for that case. 7269 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7270 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7271 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7272 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7273 Param->setDeclContext(NewFD); 7274 Params.push_back(Param); 7275 7276 if (Param->isInvalidDecl()) 7277 NewFD->setInvalidDecl(); 7278 } 7279 } 7280 7281 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7282 // When we're declaring a function with a typedef, typeof, etc as in the 7283 // following example, we'll need to synthesize (unnamed) 7284 // parameters for use in the declaration. 7285 // 7286 // @code 7287 // typedef void fn(int); 7288 // fn f; 7289 // @endcode 7290 7291 // Synthesize a parameter for each argument type. 7292 for (const auto &AI : FT->param_types()) { 7293 ParmVarDecl *Param = 7294 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7295 Param->setScopeInfo(0, Params.size()); 7296 Params.push_back(Param); 7297 } 7298 } else { 7299 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7300 "Should not need args for typedef of non-prototype fn"); 7301 } 7302 7303 // Finally, we know we have the right number of parameters, install them. 7304 NewFD->setParams(Params); 7305 7306 // Find all anonymous symbols defined during the declaration of this function 7307 // and add to NewFD. This lets us track decls such 'enum Y' in: 7308 // 7309 // void f(enum Y {AA} x) {} 7310 // 7311 // which would otherwise incorrectly end up in the translation unit scope. 7312 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7313 DeclsInPrototypeScope.clear(); 7314 7315 if (D.getDeclSpec().isNoreturnSpecified()) 7316 NewFD->addAttr( 7317 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7318 Context, 0)); 7319 7320 // Functions returning a variably modified type violate C99 6.7.5.2p2 7321 // because all functions have linkage. 7322 if (!NewFD->isInvalidDecl() && 7323 NewFD->getReturnType()->isVariablyModifiedType()) { 7324 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7325 NewFD->setInvalidDecl(); 7326 } 7327 7328 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7329 !NewFD->hasAttr<SectionAttr>()) { 7330 NewFD->addAttr( 7331 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7332 CodeSegStack.CurrentValue->getString(), 7333 CodeSegStack.CurrentPragmaLocation)); 7334 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7335 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7336 NewFD->dropAttr<SectionAttr>(); 7337 } 7338 7339 // Handle attributes. 7340 ProcessDeclAttributes(S, NewFD, D); 7341 7342 QualType RetType = NewFD->getReturnType(); 7343 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7344 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7345 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7346 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7347 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7348 // Attach WarnUnusedResult to functions returning types with that attribute. 7349 // Don't apply the attribute to that type's own non-static member functions 7350 // (to avoid warning on things like assignment operators) 7351 if (!MD || MD->getParent() != Ret) 7352 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7353 } 7354 7355 if (getLangOpts().OpenCL) { 7356 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7357 // type declaration will generate a compilation error. 7358 unsigned AddressSpace = RetType.getAddressSpace(); 7359 if (AddressSpace == LangAS::opencl_local || 7360 AddressSpace == LangAS::opencl_global || 7361 AddressSpace == LangAS::opencl_constant) { 7362 Diag(NewFD->getLocation(), 7363 diag::err_opencl_return_value_with_address_space); 7364 NewFD->setInvalidDecl(); 7365 } 7366 } 7367 7368 if (!getLangOpts().CPlusPlus) { 7369 // Perform semantic checking on the function declaration. 7370 bool isExplicitSpecialization=false; 7371 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7372 CheckMain(NewFD, D.getDeclSpec()); 7373 7374 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7375 CheckMSVCRTEntryPoint(NewFD); 7376 7377 if (!NewFD->isInvalidDecl()) 7378 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7379 isExplicitSpecialization)); 7380 else if (!Previous.empty()) 7381 // Make graceful recovery from an invalid redeclaration. 7382 D.setRedeclaration(true); 7383 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7384 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7385 "previous declaration set still overloaded"); 7386 } else { 7387 // C++11 [replacement.functions]p3: 7388 // The program's definitions shall not be specified as inline. 7389 // 7390 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7391 // 7392 // Suppress the diagnostic if the function is __attribute__((used)), since 7393 // that forces an external definition to be emitted. 7394 if (D.getDeclSpec().isInlineSpecified() && 7395 NewFD->isReplaceableGlobalAllocationFunction() && 7396 !NewFD->hasAttr<UsedAttr>()) 7397 Diag(D.getDeclSpec().getInlineSpecLoc(), 7398 diag::ext_operator_new_delete_declared_inline) 7399 << NewFD->getDeclName(); 7400 7401 // If the declarator is a template-id, translate the parser's template 7402 // argument list into our AST format. 7403 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7404 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7405 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7406 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7407 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7408 TemplateId->NumArgs); 7409 translateTemplateArguments(TemplateArgsPtr, 7410 TemplateArgs); 7411 7412 HasExplicitTemplateArgs = true; 7413 7414 if (NewFD->isInvalidDecl()) { 7415 HasExplicitTemplateArgs = false; 7416 } else if (FunctionTemplate) { 7417 // Function template with explicit template arguments. 7418 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7419 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7420 7421 HasExplicitTemplateArgs = false; 7422 } else { 7423 assert((isFunctionTemplateSpecialization || 7424 D.getDeclSpec().isFriendSpecified()) && 7425 "should have a 'template<>' for this decl"); 7426 // "friend void foo<>(int);" is an implicit specialization decl. 7427 isFunctionTemplateSpecialization = true; 7428 } 7429 } else if (isFriend && isFunctionTemplateSpecialization) { 7430 // This combination is only possible in a recovery case; the user 7431 // wrote something like: 7432 // template <> friend void foo(int); 7433 // which we're recovering from as if the user had written: 7434 // friend void foo<>(int); 7435 // Go ahead and fake up a template id. 7436 HasExplicitTemplateArgs = true; 7437 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7438 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7439 } 7440 7441 // If it's a friend (and only if it's a friend), it's possible 7442 // that either the specialized function type or the specialized 7443 // template is dependent, and therefore matching will fail. In 7444 // this case, don't check the specialization yet. 7445 bool InstantiationDependent = false; 7446 if (isFunctionTemplateSpecialization && isFriend && 7447 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7448 TemplateSpecializationType::anyDependentTemplateArguments( 7449 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7450 InstantiationDependent))) { 7451 assert(HasExplicitTemplateArgs && 7452 "friend function specialization without template args"); 7453 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7454 Previous)) 7455 NewFD->setInvalidDecl(); 7456 } else if (isFunctionTemplateSpecialization) { 7457 if (CurContext->isDependentContext() && CurContext->isRecord() 7458 && !isFriend) { 7459 isDependentClassScopeExplicitSpecialization = true; 7460 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7461 diag::ext_function_specialization_in_class : 7462 diag::err_function_specialization_in_class) 7463 << NewFD->getDeclName(); 7464 } else if (CheckFunctionTemplateSpecialization(NewFD, 7465 (HasExplicitTemplateArgs ? &TemplateArgs 7466 : nullptr), 7467 Previous)) 7468 NewFD->setInvalidDecl(); 7469 7470 // C++ [dcl.stc]p1: 7471 // A storage-class-specifier shall not be specified in an explicit 7472 // specialization (14.7.3) 7473 FunctionTemplateSpecializationInfo *Info = 7474 NewFD->getTemplateSpecializationInfo(); 7475 if (Info && SC != SC_None) { 7476 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7477 Diag(NewFD->getLocation(), 7478 diag::err_explicit_specialization_inconsistent_storage_class) 7479 << SC 7480 << FixItHint::CreateRemoval( 7481 D.getDeclSpec().getStorageClassSpecLoc()); 7482 7483 else 7484 Diag(NewFD->getLocation(), 7485 diag::ext_explicit_specialization_storage_class) 7486 << FixItHint::CreateRemoval( 7487 D.getDeclSpec().getStorageClassSpecLoc()); 7488 } 7489 7490 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7491 if (CheckMemberSpecialization(NewFD, Previous)) 7492 NewFD->setInvalidDecl(); 7493 } 7494 7495 // Perform semantic checking on the function declaration. 7496 if (!isDependentClassScopeExplicitSpecialization) { 7497 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7498 CheckMain(NewFD, D.getDeclSpec()); 7499 7500 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7501 CheckMSVCRTEntryPoint(NewFD); 7502 7503 if (!NewFD->isInvalidDecl()) 7504 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7505 isExplicitSpecialization)); 7506 } 7507 7508 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7509 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7510 "previous declaration set still overloaded"); 7511 7512 NamedDecl *PrincipalDecl = (FunctionTemplate 7513 ? cast<NamedDecl>(FunctionTemplate) 7514 : NewFD); 7515 7516 if (isFriend && D.isRedeclaration()) { 7517 AccessSpecifier Access = AS_public; 7518 if (!NewFD->isInvalidDecl()) 7519 Access = NewFD->getPreviousDecl()->getAccess(); 7520 7521 NewFD->setAccess(Access); 7522 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7523 } 7524 7525 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7526 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7527 PrincipalDecl->setNonMemberOperator(); 7528 7529 // If we have a function template, check the template parameter 7530 // list. This will check and merge default template arguments. 7531 if (FunctionTemplate) { 7532 FunctionTemplateDecl *PrevTemplate = 7533 FunctionTemplate->getPreviousDecl(); 7534 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7535 PrevTemplate ? PrevTemplate->getTemplateParameters() 7536 : nullptr, 7537 D.getDeclSpec().isFriendSpecified() 7538 ? (D.isFunctionDefinition() 7539 ? TPC_FriendFunctionTemplateDefinition 7540 : TPC_FriendFunctionTemplate) 7541 : (D.getCXXScopeSpec().isSet() && 7542 DC && DC->isRecord() && 7543 DC->isDependentContext()) 7544 ? TPC_ClassTemplateMember 7545 : TPC_FunctionTemplate); 7546 } 7547 7548 if (NewFD->isInvalidDecl()) { 7549 // Ignore all the rest of this. 7550 } else if (!D.isRedeclaration()) { 7551 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7552 AddToScope }; 7553 // Fake up an access specifier if it's supposed to be a class member. 7554 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7555 NewFD->setAccess(AS_public); 7556 7557 // Qualified decls generally require a previous declaration. 7558 if (D.getCXXScopeSpec().isSet()) { 7559 // ...with the major exception of templated-scope or 7560 // dependent-scope friend declarations. 7561 7562 // TODO: we currently also suppress this check in dependent 7563 // contexts because (1) the parameter depth will be off when 7564 // matching friend templates and (2) we might actually be 7565 // selecting a friend based on a dependent factor. But there 7566 // are situations where these conditions don't apply and we 7567 // can actually do this check immediately. 7568 if (isFriend && 7569 (TemplateParamLists.size() || 7570 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7571 CurContext->isDependentContext())) { 7572 // ignore these 7573 } else { 7574 // The user tried to provide an out-of-line definition for a 7575 // function that is a member of a class or namespace, but there 7576 // was no such member function declared (C++ [class.mfct]p2, 7577 // C++ [namespace.memdef]p2). For example: 7578 // 7579 // class X { 7580 // void f() const; 7581 // }; 7582 // 7583 // void X::f() { } // ill-formed 7584 // 7585 // Complain about this problem, and attempt to suggest close 7586 // matches (e.g., those that differ only in cv-qualifiers and 7587 // whether the parameter types are references). 7588 7589 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7590 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7591 AddToScope = ExtraArgs.AddToScope; 7592 return Result; 7593 } 7594 } 7595 7596 // Unqualified local friend declarations are required to resolve 7597 // to something. 7598 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7599 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7600 *this, Previous, NewFD, ExtraArgs, true, S)) { 7601 AddToScope = ExtraArgs.AddToScope; 7602 return Result; 7603 } 7604 } 7605 7606 } else if (!D.isFunctionDefinition() && 7607 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7608 !isFriend && !isFunctionTemplateSpecialization && 7609 !isExplicitSpecialization) { 7610 // An out-of-line member function declaration must also be a 7611 // definition (C++ [class.mfct]p2). 7612 // Note that this is not the case for explicit specializations of 7613 // function templates or member functions of class templates, per 7614 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7615 // extension for compatibility with old SWIG code which likes to 7616 // generate them. 7617 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7618 << D.getCXXScopeSpec().getRange(); 7619 } 7620 } 7621 7622 ProcessPragmaWeak(S, NewFD); 7623 checkAttributesAfterMerging(*this, *NewFD); 7624 7625 AddKnownFunctionAttributes(NewFD); 7626 7627 if (NewFD->hasAttr<OverloadableAttr>() && 7628 !NewFD->getType()->getAs<FunctionProtoType>()) { 7629 Diag(NewFD->getLocation(), 7630 diag::err_attribute_overloadable_no_prototype) 7631 << NewFD; 7632 7633 // Turn this into a variadic function with no parameters. 7634 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7635 FunctionProtoType::ExtProtoInfo EPI( 7636 Context.getDefaultCallingConvention(true, false)); 7637 EPI.Variadic = true; 7638 EPI.ExtInfo = FT->getExtInfo(); 7639 7640 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7641 NewFD->setType(R); 7642 } 7643 7644 // If there's a #pragma GCC visibility in scope, and this isn't a class 7645 // member, set the visibility of this function. 7646 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7647 AddPushedVisibilityAttribute(NewFD); 7648 7649 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7650 // marking the function. 7651 AddCFAuditedAttribute(NewFD); 7652 7653 // If this is a function definition, check if we have to apply optnone due to 7654 // a pragma. 7655 if(D.isFunctionDefinition()) 7656 AddRangeBasedOptnone(NewFD); 7657 7658 // If this is the first declaration of an extern C variable, update 7659 // the map of such variables. 7660 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7661 isIncompleteDeclExternC(*this, NewFD)) 7662 RegisterLocallyScopedExternCDecl(NewFD, S); 7663 7664 // Set this FunctionDecl's range up to the right paren. 7665 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7666 7667 if (D.isRedeclaration() && !Previous.empty()) { 7668 checkDLLAttributeRedeclaration( 7669 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7670 isExplicitSpecialization || isFunctionTemplateSpecialization); 7671 } 7672 7673 if (getLangOpts().CPlusPlus) { 7674 if (FunctionTemplate) { 7675 if (NewFD->isInvalidDecl()) 7676 FunctionTemplate->setInvalidDecl(); 7677 return FunctionTemplate; 7678 } 7679 } 7680 7681 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7682 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7683 if ((getLangOpts().OpenCLVersion >= 120) 7684 && (SC == SC_Static)) { 7685 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7686 D.setInvalidType(); 7687 } 7688 7689 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7690 if (!NewFD->getReturnType()->isVoidType()) { 7691 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7692 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7693 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7694 : FixItHint()); 7695 D.setInvalidType(); 7696 } 7697 7698 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7699 for (auto Param : NewFD->params()) 7700 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7701 } 7702 7703 MarkUnusedFileScopedDecl(NewFD); 7704 7705 if (getLangOpts().CUDA) 7706 if (IdentifierInfo *II = NewFD->getIdentifier()) 7707 if (!NewFD->isInvalidDecl() && 7708 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7709 if (II->isStr("cudaConfigureCall")) { 7710 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7711 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7712 7713 Context.setcudaConfigureCallDecl(NewFD); 7714 } 7715 } 7716 7717 // Here we have an function template explicit specialization at class scope. 7718 // The actually specialization will be postponed to template instatiation 7719 // time via the ClassScopeFunctionSpecializationDecl node. 7720 if (isDependentClassScopeExplicitSpecialization) { 7721 ClassScopeFunctionSpecializationDecl *NewSpec = 7722 ClassScopeFunctionSpecializationDecl::Create( 7723 Context, CurContext, SourceLocation(), 7724 cast<CXXMethodDecl>(NewFD), 7725 HasExplicitTemplateArgs, TemplateArgs); 7726 CurContext->addDecl(NewSpec); 7727 AddToScope = false; 7728 } 7729 7730 return NewFD; 7731 } 7732 7733 /// \brief Perform semantic checking of a new function declaration. 7734 /// 7735 /// Performs semantic analysis of the new function declaration 7736 /// NewFD. This routine performs all semantic checking that does not 7737 /// require the actual declarator involved in the declaration, and is 7738 /// used both for the declaration of functions as they are parsed 7739 /// (called via ActOnDeclarator) and for the declaration of functions 7740 /// that have been instantiated via C++ template instantiation (called 7741 /// via InstantiateDecl). 7742 /// 7743 /// \param IsExplicitSpecialization whether this new function declaration is 7744 /// an explicit specialization of the previous declaration. 7745 /// 7746 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7747 /// 7748 /// \returns true if the function declaration is a redeclaration. 7749 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7750 LookupResult &Previous, 7751 bool IsExplicitSpecialization) { 7752 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7753 "Variably modified return types are not handled here"); 7754 7755 // Determine whether the type of this function should be merged with 7756 // a previous visible declaration. This never happens for functions in C++, 7757 // and always happens in C if the previous declaration was visible. 7758 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7759 !Previous.isShadowed(); 7760 7761 // Filter out any non-conflicting previous declarations. 7762 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7763 7764 bool Redeclaration = false; 7765 NamedDecl *OldDecl = nullptr; 7766 7767 // Merge or overload the declaration with an existing declaration of 7768 // the same name, if appropriate. 7769 if (!Previous.empty()) { 7770 // Determine whether NewFD is an overload of PrevDecl or 7771 // a declaration that requires merging. If it's an overload, 7772 // there's no more work to do here; we'll just add the new 7773 // function to the scope. 7774 if (!AllowOverloadingOfFunction(Previous, Context)) { 7775 NamedDecl *Candidate = Previous.getFoundDecl(); 7776 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7777 Redeclaration = true; 7778 OldDecl = Candidate; 7779 } 7780 } else { 7781 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7782 /*NewIsUsingDecl*/ false)) { 7783 case Ovl_Match: 7784 Redeclaration = true; 7785 break; 7786 7787 case Ovl_NonFunction: 7788 Redeclaration = true; 7789 break; 7790 7791 case Ovl_Overload: 7792 Redeclaration = false; 7793 break; 7794 } 7795 7796 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7797 // If a function name is overloadable in C, then every function 7798 // with that name must be marked "overloadable". 7799 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7800 << Redeclaration << NewFD; 7801 NamedDecl *OverloadedDecl = nullptr; 7802 if (Redeclaration) 7803 OverloadedDecl = OldDecl; 7804 else if (!Previous.empty()) 7805 OverloadedDecl = Previous.getRepresentativeDecl(); 7806 if (OverloadedDecl) 7807 Diag(OverloadedDecl->getLocation(), 7808 diag::note_attribute_overloadable_prev_overload); 7809 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7810 } 7811 } 7812 } 7813 7814 // Check for a previous extern "C" declaration with this name. 7815 if (!Redeclaration && 7816 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7817 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7818 if (!Previous.empty()) { 7819 // This is an extern "C" declaration with the same name as a previous 7820 // declaration, and thus redeclares that entity... 7821 Redeclaration = true; 7822 OldDecl = Previous.getFoundDecl(); 7823 MergeTypeWithPrevious = false; 7824 7825 // ... except in the presence of __attribute__((overloadable)). 7826 if (OldDecl->hasAttr<OverloadableAttr>()) { 7827 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7828 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7829 << Redeclaration << NewFD; 7830 Diag(Previous.getFoundDecl()->getLocation(), 7831 diag::note_attribute_overloadable_prev_overload); 7832 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7833 } 7834 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7835 Redeclaration = false; 7836 OldDecl = nullptr; 7837 } 7838 } 7839 } 7840 } 7841 7842 // C++11 [dcl.constexpr]p8: 7843 // A constexpr specifier for a non-static member function that is not 7844 // a constructor declares that member function to be const. 7845 // 7846 // This needs to be delayed until we know whether this is an out-of-line 7847 // definition of a static member function. 7848 // 7849 // This rule is not present in C++1y, so we produce a backwards 7850 // compatibility warning whenever it happens in C++11. 7851 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7852 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7853 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7854 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7855 CXXMethodDecl *OldMD = nullptr; 7856 if (OldDecl) 7857 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7858 if (!OldMD || !OldMD->isStatic()) { 7859 const FunctionProtoType *FPT = 7860 MD->getType()->castAs<FunctionProtoType>(); 7861 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7862 EPI.TypeQuals |= Qualifiers::Const; 7863 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7864 FPT->getParamTypes(), EPI)); 7865 7866 // Warn that we did this, if we're not performing template instantiation. 7867 // In that case, we'll have warned already when the template was defined. 7868 if (ActiveTemplateInstantiations.empty()) { 7869 SourceLocation AddConstLoc; 7870 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7871 .IgnoreParens().getAs<FunctionTypeLoc>()) 7872 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7873 7874 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 7875 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7876 } 7877 } 7878 } 7879 7880 if (Redeclaration) { 7881 // NewFD and OldDecl represent declarations that need to be 7882 // merged. 7883 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7884 NewFD->setInvalidDecl(); 7885 return Redeclaration; 7886 } 7887 7888 Previous.clear(); 7889 Previous.addDecl(OldDecl); 7890 7891 if (FunctionTemplateDecl *OldTemplateDecl 7892 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7893 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7894 FunctionTemplateDecl *NewTemplateDecl 7895 = NewFD->getDescribedFunctionTemplate(); 7896 assert(NewTemplateDecl && "Template/non-template mismatch"); 7897 if (CXXMethodDecl *Method 7898 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7899 Method->setAccess(OldTemplateDecl->getAccess()); 7900 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7901 } 7902 7903 // If this is an explicit specialization of a member that is a function 7904 // template, mark it as a member specialization. 7905 if (IsExplicitSpecialization && 7906 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7907 NewTemplateDecl->setMemberSpecialization(); 7908 assert(OldTemplateDecl->isMemberSpecialization()); 7909 } 7910 7911 } else { 7912 // This needs to happen first so that 'inline' propagates. 7913 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7914 7915 if (isa<CXXMethodDecl>(NewFD)) { 7916 // A valid redeclaration of a C++ method must be out-of-line, 7917 // but (unfortunately) it's not necessarily a definition 7918 // because of templates, which means that the previous 7919 // declaration is not necessarily from the class definition. 7920 7921 // For just setting the access, that doesn't matter. 7922 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7923 NewFD->setAccess(oldMethod->getAccess()); 7924 7925 // Update the key-function state if necessary for this ABI. 7926 if (NewFD->isInlined() && 7927 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7928 // setNonKeyFunction needs to work with the original 7929 // declaration from the class definition, and isVirtual() is 7930 // just faster in that case, so map back to that now. 7931 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7932 if (oldMethod->isVirtual()) { 7933 Context.setNonKeyFunction(oldMethod); 7934 } 7935 } 7936 } 7937 } 7938 } 7939 7940 // Semantic checking for this function declaration (in isolation). 7941 7942 // Diagnose the use of callee-cleanup calls on unprototyped functions. 7943 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 7944 const FunctionType *NewType = cast<FunctionType>(NewQType); 7945 if (isa<FunctionNoProtoType>(NewType)) { 7946 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 7947 if (isCalleeCleanup(NewTypeInfo.getCC())) { 7948 // Windows system headers sometimes accidentally use stdcall without 7949 // (void) parameters, so use a default-error warning in this case :-/ 7950 int DiagID = NewTypeInfo.getCC() == CC_X86StdCall 7951 ? diag::warn_cconv_knr : diag::err_cconv_knr; 7952 Diag(NewFD->getLocation(), DiagID) 7953 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()); 7954 } 7955 } 7956 7957 if (getLangOpts().CPlusPlus) { 7958 // C++-specific checks. 7959 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7960 CheckConstructor(Constructor); 7961 } else if (CXXDestructorDecl *Destructor = 7962 dyn_cast<CXXDestructorDecl>(NewFD)) { 7963 CXXRecordDecl *Record = Destructor->getParent(); 7964 QualType ClassType = Context.getTypeDeclType(Record); 7965 7966 // FIXME: Shouldn't we be able to perform this check even when the class 7967 // type is dependent? Both gcc and edg can handle that. 7968 if (!ClassType->isDependentType()) { 7969 DeclarationName Name 7970 = Context.DeclarationNames.getCXXDestructorName( 7971 Context.getCanonicalType(ClassType)); 7972 if (NewFD->getDeclName() != Name) { 7973 Diag(NewFD->getLocation(), diag::err_destructor_name); 7974 NewFD->setInvalidDecl(); 7975 return Redeclaration; 7976 } 7977 } 7978 } else if (CXXConversionDecl *Conversion 7979 = dyn_cast<CXXConversionDecl>(NewFD)) { 7980 ActOnConversionDeclarator(Conversion); 7981 } 7982 7983 // Find any virtual functions that this function overrides. 7984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7985 if (!Method->isFunctionTemplateSpecialization() && 7986 !Method->getDescribedFunctionTemplate() && 7987 Method->isCanonicalDecl()) { 7988 if (AddOverriddenMethods(Method->getParent(), Method)) { 7989 // If the function was marked as "static", we have a problem. 7990 if (NewFD->getStorageClass() == SC_Static) { 7991 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7992 } 7993 } 7994 } 7995 7996 if (Method->isStatic()) 7997 checkThisInStaticMemberFunctionType(Method); 7998 } 7999 8000 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8001 if (NewFD->isOverloadedOperator() && 8002 CheckOverloadedOperatorDeclaration(NewFD)) { 8003 NewFD->setInvalidDecl(); 8004 return Redeclaration; 8005 } 8006 8007 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8008 if (NewFD->getLiteralIdentifier() && 8009 CheckLiteralOperatorDeclaration(NewFD)) { 8010 NewFD->setInvalidDecl(); 8011 return Redeclaration; 8012 } 8013 8014 // In C++, check default arguments now that we have merged decls. Unless 8015 // the lexical context is the class, because in this case this is done 8016 // during delayed parsing anyway. 8017 if (!CurContext->isRecord()) 8018 CheckCXXDefaultArguments(NewFD); 8019 8020 // If this function declares a builtin function, check the type of this 8021 // declaration against the expected type for the builtin. 8022 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8023 ASTContext::GetBuiltinTypeError Error; 8024 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8025 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8026 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8027 // The type of this function differs from the type of the builtin, 8028 // so forget about the builtin entirely. 8029 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8030 } 8031 } 8032 8033 // If this function is declared as being extern "C", then check to see if 8034 // the function returns a UDT (class, struct, or union type) that is not C 8035 // compatible, and if it does, warn the user. 8036 // But, issue any diagnostic on the first declaration only. 8037 if (NewFD->isExternC() && Previous.empty()) { 8038 QualType R = NewFD->getReturnType(); 8039 if (R->isIncompleteType() && !R->isVoidType()) 8040 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8041 << NewFD << R; 8042 else if (!R.isPODType(Context) && !R->isVoidType() && 8043 !R->isObjCObjectPointerType()) 8044 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8045 } 8046 } 8047 return Redeclaration; 8048 } 8049 8050 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8051 // C++11 [basic.start.main]p3: 8052 // A program that [...] declares main to be inline, static or 8053 // constexpr is ill-formed. 8054 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8055 // appear in a declaration of main. 8056 // static main is not an error under C99, but we should warn about it. 8057 // We accept _Noreturn main as an extension. 8058 if (FD->getStorageClass() == SC_Static) 8059 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8060 ? diag::err_static_main : diag::warn_static_main) 8061 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8062 if (FD->isInlineSpecified()) 8063 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8064 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8065 if (DS.isNoreturnSpecified()) { 8066 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8067 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8068 Diag(NoreturnLoc, diag::ext_noreturn_main); 8069 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8070 << FixItHint::CreateRemoval(NoreturnRange); 8071 } 8072 if (FD->isConstexpr()) { 8073 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8074 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8075 FD->setConstexpr(false); 8076 } 8077 8078 if (getLangOpts().OpenCL) { 8079 Diag(FD->getLocation(), diag::err_opencl_no_main) 8080 << FD->hasAttr<OpenCLKernelAttr>(); 8081 FD->setInvalidDecl(); 8082 return; 8083 } 8084 8085 QualType T = FD->getType(); 8086 assert(T->isFunctionType() && "function decl is not of function type"); 8087 const FunctionType* FT = T->castAs<FunctionType>(); 8088 8089 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8090 // In C with GNU extensions we allow main() to have non-integer return 8091 // type, but we should warn about the extension, and we disable the 8092 // implicit-return-zero rule. 8093 8094 // GCC in C mode accepts qualified 'int'. 8095 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8096 FD->setHasImplicitReturnZero(true); 8097 else { 8098 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8099 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8100 if (RTRange.isValid()) 8101 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8102 << FixItHint::CreateReplacement(RTRange, "int"); 8103 } 8104 } else { 8105 // In C and C++, main magically returns 0 if you fall off the end; 8106 // set the flag which tells us that. 8107 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8108 8109 // All the standards say that main() should return 'int'. 8110 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8111 FD->setHasImplicitReturnZero(true); 8112 else { 8113 // Otherwise, this is just a flat-out error. 8114 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8115 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8116 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8117 : FixItHint()); 8118 FD->setInvalidDecl(true); 8119 } 8120 } 8121 8122 // Treat protoless main() as nullary. 8123 if (isa<FunctionNoProtoType>(FT)) return; 8124 8125 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8126 unsigned nparams = FTP->getNumParams(); 8127 assert(FD->getNumParams() == nparams); 8128 8129 bool HasExtraParameters = (nparams > 3); 8130 8131 // Darwin passes an undocumented fourth argument of type char**. If 8132 // other platforms start sprouting these, the logic below will start 8133 // getting shifty. 8134 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8135 HasExtraParameters = false; 8136 8137 if (HasExtraParameters) { 8138 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8139 FD->setInvalidDecl(true); 8140 nparams = 3; 8141 } 8142 8143 // FIXME: a lot of the following diagnostics would be improved 8144 // if we had some location information about types. 8145 8146 QualType CharPP = 8147 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8148 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8149 8150 for (unsigned i = 0; i < nparams; ++i) { 8151 QualType AT = FTP->getParamType(i); 8152 8153 bool mismatch = true; 8154 8155 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8156 mismatch = false; 8157 else if (Expected[i] == CharPP) { 8158 // As an extension, the following forms are okay: 8159 // char const ** 8160 // char const * const * 8161 // char * const * 8162 8163 QualifierCollector qs; 8164 const PointerType* PT; 8165 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8166 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8167 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8168 Context.CharTy)) { 8169 qs.removeConst(); 8170 mismatch = !qs.empty(); 8171 } 8172 } 8173 8174 if (mismatch) { 8175 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8176 // TODO: suggest replacing given type with expected type 8177 FD->setInvalidDecl(true); 8178 } 8179 } 8180 8181 if (nparams == 1 && !FD->isInvalidDecl()) { 8182 Diag(FD->getLocation(), diag::warn_main_one_arg); 8183 } 8184 8185 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8186 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8187 FD->setInvalidDecl(); 8188 } 8189 } 8190 8191 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8192 QualType T = FD->getType(); 8193 assert(T->isFunctionType() && "function decl is not of function type"); 8194 const FunctionType *FT = T->castAs<FunctionType>(); 8195 8196 // Set an implicit return of 'zero' if the function can return some integral, 8197 // enumeration, pointer or nullptr type. 8198 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8199 FT->getReturnType()->isAnyPointerType() || 8200 FT->getReturnType()->isNullPtrType()) 8201 // DllMain is exempt because a return value of zero means it failed. 8202 if (FD->getName() != "DllMain") 8203 FD->setHasImplicitReturnZero(true); 8204 8205 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8206 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8207 FD->setInvalidDecl(); 8208 } 8209 } 8210 8211 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8212 // FIXME: Need strict checking. In C89, we need to check for 8213 // any assignment, increment, decrement, function-calls, or 8214 // commas outside of a sizeof. In C99, it's the same list, 8215 // except that the aforementioned are allowed in unevaluated 8216 // expressions. Everything else falls under the 8217 // "may accept other forms of constant expressions" exception. 8218 // (We never end up here for C++, so the constant expression 8219 // rules there don't matter.) 8220 const Expr *Culprit; 8221 if (Init->isConstantInitializer(Context, false, &Culprit)) 8222 return false; 8223 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8224 << Culprit->getSourceRange(); 8225 return true; 8226 } 8227 8228 namespace { 8229 // Visits an initialization expression to see if OrigDecl is evaluated in 8230 // its own initialization and throws a warning if it does. 8231 class SelfReferenceChecker 8232 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8233 Sema &S; 8234 Decl *OrigDecl; 8235 bool isRecordType; 8236 bool isPODType; 8237 bool isReferenceType; 8238 8239 bool isInitList; 8240 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8241 public: 8242 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8243 8244 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8245 S(S), OrigDecl(OrigDecl) { 8246 isPODType = false; 8247 isRecordType = false; 8248 isReferenceType = false; 8249 isInitList = false; 8250 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8251 isPODType = VD->getType().isPODType(S.Context); 8252 isRecordType = VD->getType()->isRecordType(); 8253 isReferenceType = VD->getType()->isReferenceType(); 8254 } 8255 } 8256 8257 // For most expressions, just call the visitor. For initializer lists, 8258 // track the index of the field being initialized since fields are 8259 // initialized in order allowing use of previously initialized fields. 8260 void CheckExpr(Expr *E) { 8261 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8262 if (!InitList) { 8263 Visit(E); 8264 return; 8265 } 8266 8267 // Track and increment the index here. 8268 isInitList = true; 8269 InitFieldIndex.push_back(0); 8270 for (auto Child : InitList->children()) { 8271 CheckExpr(cast<Expr>(Child)); 8272 ++InitFieldIndex.back(); 8273 } 8274 InitFieldIndex.pop_back(); 8275 } 8276 8277 // Returns true if MemberExpr is checked and no futher checking is needed. 8278 // Returns false if additional checking is required. 8279 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8280 llvm::SmallVector<FieldDecl*, 4> Fields; 8281 Expr *Base = E; 8282 bool ReferenceField = false; 8283 8284 // Get the field memebers used. 8285 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8286 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8287 if (!FD) 8288 return false; 8289 Fields.push_back(FD); 8290 if (FD->getType()->isReferenceType()) 8291 ReferenceField = true; 8292 Base = ME->getBase()->IgnoreParenImpCasts(); 8293 } 8294 8295 // Keep checking only if the base Decl is the same. 8296 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8297 if (!DRE || DRE->getDecl() != OrigDecl) 8298 return false; 8299 8300 // A reference field can be bound to an unininitialized field. 8301 if (CheckReference && !ReferenceField) 8302 return true; 8303 8304 // Convert FieldDecls to their index number. 8305 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8306 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8307 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8308 } 8309 8310 // See if a warning is needed by checking the first difference in index 8311 // numbers. If field being used has index less than the field being 8312 // initialized, then the use is safe. 8313 for (auto UsedIter = UsedFieldIndex.begin(), 8314 UsedEnd = UsedFieldIndex.end(), 8315 OrigIter = InitFieldIndex.begin(), 8316 OrigEnd = InitFieldIndex.end(); 8317 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8318 if (*UsedIter < *OrigIter) 8319 return true; 8320 if (*UsedIter > *OrigIter) 8321 break; 8322 } 8323 8324 // TODO: Add a different warning which will print the field names. 8325 HandleDeclRefExpr(DRE); 8326 return true; 8327 } 8328 8329 // For most expressions, the cast is directly above the DeclRefExpr. 8330 // For conditional operators, the cast can be outside the conditional 8331 // operator if both expressions are DeclRefExpr's. 8332 void HandleValue(Expr *E) { 8333 E = E->IgnoreParens(); 8334 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8335 HandleDeclRefExpr(DRE); 8336 return; 8337 } 8338 8339 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8340 Visit(CO->getCond()); 8341 HandleValue(CO->getTrueExpr()); 8342 HandleValue(CO->getFalseExpr()); 8343 return; 8344 } 8345 8346 if (BinaryConditionalOperator *BCO = 8347 dyn_cast<BinaryConditionalOperator>(E)) { 8348 Visit(BCO->getCond()); 8349 HandleValue(BCO->getFalseExpr()); 8350 return; 8351 } 8352 8353 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8354 HandleValue(OVE->getSourceExpr()); 8355 return; 8356 } 8357 8358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8359 if (BO->getOpcode() == BO_Comma) { 8360 Visit(BO->getLHS()); 8361 HandleValue(BO->getRHS()); 8362 return; 8363 } 8364 } 8365 8366 if (isa<MemberExpr>(E)) { 8367 if (isInitList) { 8368 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8369 false /*CheckReference*/)) 8370 return; 8371 } 8372 8373 Expr *Base = E->IgnoreParenImpCasts(); 8374 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8375 // Check for static member variables and don't warn on them. 8376 if (!isa<FieldDecl>(ME->getMemberDecl())) 8377 return; 8378 Base = ME->getBase()->IgnoreParenImpCasts(); 8379 } 8380 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8381 HandleDeclRefExpr(DRE); 8382 return; 8383 } 8384 8385 Visit(E); 8386 } 8387 8388 // Reference types not handled in HandleValue are handled here since all 8389 // uses of references are bad, not just r-value uses. 8390 void VisitDeclRefExpr(DeclRefExpr *E) { 8391 if (isReferenceType) 8392 HandleDeclRefExpr(E); 8393 } 8394 8395 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8396 if (E->getCastKind() == CK_LValueToRValue) { 8397 HandleValue(E->getSubExpr()); 8398 return; 8399 } 8400 8401 Inherited::VisitImplicitCastExpr(E); 8402 } 8403 8404 void VisitMemberExpr(MemberExpr *E) { 8405 if (isInitList) { 8406 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8407 return; 8408 } 8409 8410 // Don't warn on arrays since they can be treated as pointers. 8411 if (E->getType()->canDecayToPointerType()) return; 8412 8413 // Warn when a non-static method call is followed by non-static member 8414 // field accesses, which is followed by a DeclRefExpr. 8415 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8416 bool Warn = (MD && !MD->isStatic()); 8417 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8418 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8419 if (!isa<FieldDecl>(ME->getMemberDecl())) 8420 Warn = false; 8421 Base = ME->getBase()->IgnoreParenImpCasts(); 8422 } 8423 8424 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8425 if (Warn) 8426 HandleDeclRefExpr(DRE); 8427 return; 8428 } 8429 8430 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8431 // Visit that expression. 8432 Visit(Base); 8433 } 8434 8435 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8436 if (E->getNumArgs() > 0) 8437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8438 HandleDeclRefExpr(DRE); 8439 8440 Inherited::VisitCXXOperatorCallExpr(E); 8441 } 8442 8443 void VisitUnaryOperator(UnaryOperator *E) { 8444 // For POD record types, addresses of its own members are well-defined. 8445 if (E->getOpcode() == UO_AddrOf && isRecordType && 8446 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8447 if (!isPODType) 8448 HandleValue(E->getSubExpr()); 8449 return; 8450 } 8451 8452 if (E->isIncrementDecrementOp()) { 8453 HandleValue(E->getSubExpr()); 8454 return; 8455 } 8456 8457 Inherited::VisitUnaryOperator(E); 8458 } 8459 8460 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8461 8462 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8463 if (E->getConstructor()->isCopyConstructor()) { 8464 Expr *ArgExpr = E->getArg(0); 8465 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8466 if (ILE->getNumInits() == 1) 8467 ArgExpr = ILE->getInit(0); 8468 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8469 if (ICE->getCastKind() == CK_NoOp) 8470 ArgExpr = ICE->getSubExpr(); 8471 HandleValue(ArgExpr); 8472 return; 8473 } 8474 Inherited::VisitCXXConstructExpr(E); 8475 } 8476 8477 void VisitCallExpr(CallExpr *E) { 8478 // Treat std::move as a use. 8479 if (E->getNumArgs() == 1) { 8480 if (FunctionDecl *FD = E->getDirectCallee()) { 8481 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 8482 HandleValue(E->getArg(0)); 8483 return; 8484 } 8485 } 8486 } 8487 8488 Inherited::VisitCallExpr(E); 8489 } 8490 8491 void VisitBinaryOperator(BinaryOperator *E) { 8492 if (E->isCompoundAssignmentOp()) { 8493 HandleValue(E->getLHS()); 8494 Visit(E->getRHS()); 8495 return; 8496 } 8497 8498 Inherited::VisitBinaryOperator(E); 8499 } 8500 8501 // A custom visitor for BinaryConditionalOperator is needed because the 8502 // regular visitor would check the condition and true expression separately 8503 // but both point to the same place giving duplicate diagnostics. 8504 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8505 Visit(E->getCond()); 8506 Visit(E->getFalseExpr()); 8507 } 8508 8509 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8510 Decl* ReferenceDecl = DRE->getDecl(); 8511 if (OrigDecl != ReferenceDecl) return; 8512 unsigned diag; 8513 if (isReferenceType) { 8514 diag = diag::warn_uninit_self_reference_in_reference_init; 8515 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8516 diag = diag::warn_static_self_reference_in_init; 8517 } else { 8518 diag = diag::warn_uninit_self_reference_in_init; 8519 } 8520 8521 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8522 S.PDiag(diag) 8523 << DRE->getNameInfo().getName() 8524 << OrigDecl->getLocation() 8525 << DRE->getSourceRange()); 8526 } 8527 }; 8528 8529 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8530 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8531 bool DirectInit) { 8532 // Parameters arguments are occassionially constructed with itself, 8533 // for instance, in recursive functions. Skip them. 8534 if (isa<ParmVarDecl>(OrigDecl)) 8535 return; 8536 8537 E = E->IgnoreParens(); 8538 8539 // Skip checking T a = a where T is not a record or reference type. 8540 // Doing so is a way to silence uninitialized warnings. 8541 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8542 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8543 if (ICE->getCastKind() == CK_LValueToRValue) 8544 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8545 if (DRE->getDecl() == OrigDecl) 8546 return; 8547 8548 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8549 } 8550 } 8551 8552 /// AddInitializerToDecl - Adds the initializer Init to the 8553 /// declaration dcl. If DirectInit is true, this is C++ direct 8554 /// initialization rather than copy initialization. 8555 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8556 bool DirectInit, bool TypeMayContainAuto) { 8557 // If there is no declaration, there was an error parsing it. Just ignore 8558 // the initializer. 8559 if (!RealDecl || RealDecl->isInvalidDecl()) 8560 return; 8561 8562 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8563 // With declarators parsed the way they are, the parser cannot 8564 // distinguish between a normal initializer and a pure-specifier. 8565 // Thus this grotesque test. 8566 IntegerLiteral *IL; 8567 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8568 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8569 CheckPureMethod(Method, Init->getSourceRange()); 8570 else { 8571 Diag(Method->getLocation(), diag::err_member_function_initialization) 8572 << Method->getDeclName() << Init->getSourceRange(); 8573 Method->setInvalidDecl(); 8574 } 8575 return; 8576 } 8577 8578 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8579 if (!VDecl) { 8580 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8581 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8582 RealDecl->setInvalidDecl(); 8583 return; 8584 } 8585 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8586 8587 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8588 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8589 Expr *DeduceInit = Init; 8590 // Initializer could be a C++ direct-initializer. Deduction only works if it 8591 // contains exactly one expression. 8592 if (CXXDirectInit) { 8593 if (CXXDirectInit->getNumExprs() == 0) { 8594 // It isn't possible to write this directly, but it is possible to 8595 // end up in this situation with "auto x(some_pack...);" 8596 Diag(CXXDirectInit->getLocStart(), 8597 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8598 : diag::err_auto_var_init_no_expression) 8599 << VDecl->getDeclName() << VDecl->getType() 8600 << VDecl->getSourceRange(); 8601 RealDecl->setInvalidDecl(); 8602 return; 8603 } else if (CXXDirectInit->getNumExprs() > 1) { 8604 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8605 VDecl->isInitCapture() 8606 ? diag::err_init_capture_multiple_expressions 8607 : diag::err_auto_var_init_multiple_expressions) 8608 << VDecl->getDeclName() << VDecl->getType() 8609 << VDecl->getSourceRange(); 8610 RealDecl->setInvalidDecl(); 8611 return; 8612 } else { 8613 DeduceInit = CXXDirectInit->getExpr(0); 8614 if (isa<InitListExpr>(DeduceInit)) 8615 Diag(CXXDirectInit->getLocStart(), 8616 diag::err_auto_var_init_paren_braces) 8617 << VDecl->getDeclName() << VDecl->getType() 8618 << VDecl->getSourceRange(); 8619 } 8620 } 8621 8622 // Expressions default to 'id' when we're in a debugger. 8623 bool DefaultedToAuto = false; 8624 if (getLangOpts().DebuggerCastResultToId && 8625 Init->getType() == Context.UnknownAnyTy) { 8626 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8627 if (Result.isInvalid()) { 8628 VDecl->setInvalidDecl(); 8629 return; 8630 } 8631 Init = Result.get(); 8632 DefaultedToAuto = true; 8633 } 8634 8635 QualType DeducedType; 8636 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8637 DAR_Failed) 8638 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8639 if (DeducedType.isNull()) { 8640 RealDecl->setInvalidDecl(); 8641 return; 8642 } 8643 VDecl->setType(DeducedType); 8644 assert(VDecl->isLinkageValid()); 8645 8646 // In ARC, infer lifetime. 8647 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8648 VDecl->setInvalidDecl(); 8649 8650 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8651 // 'id' instead of a specific object type prevents most of our usual checks. 8652 // We only want to warn outside of template instantiations, though: 8653 // inside a template, the 'id' could have come from a parameter. 8654 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8655 DeducedType->isObjCIdType()) { 8656 SourceLocation Loc = 8657 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8658 Diag(Loc, diag::warn_auto_var_is_id) 8659 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8660 } 8661 8662 // If this is a redeclaration, check that the type we just deduced matches 8663 // the previously declared type. 8664 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8665 // We never need to merge the type, because we cannot form an incomplete 8666 // array of auto, nor deduce such a type. 8667 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8668 } 8669 8670 // Check the deduced type is valid for a variable declaration. 8671 CheckVariableDeclarationType(VDecl); 8672 if (VDecl->isInvalidDecl()) 8673 return; 8674 } 8675 8676 // dllimport cannot be used on variable definitions. 8677 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8678 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8679 VDecl->setInvalidDecl(); 8680 return; 8681 } 8682 8683 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8684 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8685 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8686 VDecl->setInvalidDecl(); 8687 return; 8688 } 8689 8690 if (!VDecl->getType()->isDependentType()) { 8691 // A definition must end up with a complete type, which means it must be 8692 // complete with the restriction that an array type might be completed by 8693 // the initializer; note that later code assumes this restriction. 8694 QualType BaseDeclType = VDecl->getType(); 8695 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8696 BaseDeclType = Array->getElementType(); 8697 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8698 diag::err_typecheck_decl_incomplete_type)) { 8699 RealDecl->setInvalidDecl(); 8700 return; 8701 } 8702 8703 // The variable can not have an abstract class type. 8704 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8705 diag::err_abstract_type_in_decl, 8706 AbstractVariableType)) 8707 VDecl->setInvalidDecl(); 8708 } 8709 8710 const VarDecl *Def; 8711 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8712 Diag(VDecl->getLocation(), diag::err_redefinition) 8713 << VDecl->getDeclName(); 8714 Diag(Def->getLocation(), diag::note_previous_definition); 8715 VDecl->setInvalidDecl(); 8716 return; 8717 } 8718 8719 const VarDecl *PrevInit = nullptr; 8720 if (getLangOpts().CPlusPlus) { 8721 // C++ [class.static.data]p4 8722 // If a static data member is of const integral or const 8723 // enumeration type, its declaration in the class definition can 8724 // specify a constant-initializer which shall be an integral 8725 // constant expression (5.19). In that case, the member can appear 8726 // in integral constant expressions. The member shall still be 8727 // defined in a namespace scope if it is used in the program and the 8728 // namespace scope definition shall not contain an initializer. 8729 // 8730 // We already performed a redefinition check above, but for static 8731 // data members we also need to check whether there was an in-class 8732 // declaration with an initializer. 8733 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8734 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8735 << VDecl->getDeclName(); 8736 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8737 return; 8738 } 8739 8740 if (VDecl->hasLocalStorage()) 8741 getCurFunction()->setHasBranchProtectedScope(); 8742 8743 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8744 VDecl->setInvalidDecl(); 8745 return; 8746 } 8747 } 8748 8749 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8750 // a kernel function cannot be initialized." 8751 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8752 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8753 VDecl->setInvalidDecl(); 8754 return; 8755 } 8756 8757 // Get the decls type and save a reference for later, since 8758 // CheckInitializerTypes may change it. 8759 QualType DclT = VDecl->getType(), SavT = DclT; 8760 8761 // Expressions default to 'id' when we're in a debugger 8762 // and we are assigning it to a variable of Objective-C pointer type. 8763 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8764 Init->getType() == Context.UnknownAnyTy) { 8765 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8766 if (Result.isInvalid()) { 8767 VDecl->setInvalidDecl(); 8768 return; 8769 } 8770 Init = Result.get(); 8771 } 8772 8773 // Perform the initialization. 8774 if (!VDecl->isInvalidDecl()) { 8775 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8776 InitializationKind Kind 8777 = DirectInit ? 8778 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8779 Init->getLocStart(), 8780 Init->getLocEnd()) 8781 : InitializationKind::CreateDirectList( 8782 VDecl->getLocation()) 8783 : InitializationKind::CreateCopy(VDecl->getLocation(), 8784 Init->getLocStart()); 8785 8786 MultiExprArg Args = Init; 8787 if (CXXDirectInit) 8788 Args = MultiExprArg(CXXDirectInit->getExprs(), 8789 CXXDirectInit->getNumExprs()); 8790 8791 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8792 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8793 if (Result.isInvalid()) { 8794 VDecl->setInvalidDecl(); 8795 return; 8796 } 8797 8798 Init = Result.getAs<Expr>(); 8799 } 8800 8801 // Check for self-references within variable initializers. 8802 // Variables declared within a function/method body (except for references) 8803 // are handled by a dataflow analysis. 8804 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8805 VDecl->getType()->isReferenceType()) { 8806 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8807 } 8808 8809 // If the type changed, it means we had an incomplete type that was 8810 // completed by the initializer. For example: 8811 // int ary[] = { 1, 3, 5 }; 8812 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8813 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8814 VDecl->setType(DclT); 8815 8816 if (!VDecl->isInvalidDecl()) { 8817 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8818 8819 if (VDecl->hasAttr<BlocksAttr>()) 8820 checkRetainCycles(VDecl, Init); 8821 8822 // It is safe to assign a weak reference into a strong variable. 8823 // Although this code can still have problems: 8824 // id x = self.weakProp; 8825 // id y = self.weakProp; 8826 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8827 // paths through the function. This should be revisited if 8828 // -Wrepeated-use-of-weak is made flow-sensitive. 8829 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8830 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8831 Init->getLocStart())) 8832 getCurFunction()->markSafeWeakUse(Init); 8833 } 8834 8835 // The initialization is usually a full-expression. 8836 // 8837 // FIXME: If this is a braced initialization of an aggregate, it is not 8838 // an expression, and each individual field initializer is a separate 8839 // full-expression. For instance, in: 8840 // 8841 // struct Temp { ~Temp(); }; 8842 // struct S { S(Temp); }; 8843 // struct T { S a, b; } t = { Temp(), Temp() } 8844 // 8845 // we should destroy the first Temp before constructing the second. 8846 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8847 false, 8848 VDecl->isConstexpr()); 8849 if (Result.isInvalid()) { 8850 VDecl->setInvalidDecl(); 8851 return; 8852 } 8853 Init = Result.get(); 8854 8855 // Attach the initializer to the decl. 8856 VDecl->setInit(Init); 8857 8858 if (VDecl->isLocalVarDecl()) { 8859 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8860 // static storage duration shall be constant expressions or string literals. 8861 // C++ does not have this restriction. 8862 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8863 const Expr *Culprit; 8864 if (VDecl->getStorageClass() == SC_Static) 8865 CheckForConstantInitializer(Init, DclT); 8866 // C89 is stricter than C99 for non-static aggregate types. 8867 // C89 6.5.7p3: All the expressions [...] in an initializer list 8868 // for an object that has aggregate or union type shall be 8869 // constant expressions. 8870 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8871 isa<InitListExpr>(Init) && 8872 !Init->isConstantInitializer(Context, false, &Culprit)) 8873 Diag(Culprit->getExprLoc(), 8874 diag::ext_aggregate_init_not_constant) 8875 << Culprit->getSourceRange(); 8876 } 8877 } else if (VDecl->isStaticDataMember() && 8878 VDecl->getLexicalDeclContext()->isRecord()) { 8879 // This is an in-class initialization for a static data member, e.g., 8880 // 8881 // struct S { 8882 // static const int value = 17; 8883 // }; 8884 8885 // C++ [class.mem]p4: 8886 // A member-declarator can contain a constant-initializer only 8887 // if it declares a static member (9.4) of const integral or 8888 // const enumeration type, see 9.4.2. 8889 // 8890 // C++11 [class.static.data]p3: 8891 // If a non-volatile const static data member is of integral or 8892 // enumeration type, its declaration in the class definition can 8893 // specify a brace-or-equal-initializer in which every initalizer-clause 8894 // that is an assignment-expression is a constant expression. A static 8895 // data member of literal type can be declared in the class definition 8896 // with the constexpr specifier; if so, its declaration shall specify a 8897 // brace-or-equal-initializer in which every initializer-clause that is 8898 // an assignment-expression is a constant expression. 8899 8900 // Do nothing on dependent types. 8901 if (DclT->isDependentType()) { 8902 8903 // Allow any 'static constexpr' members, whether or not they are of literal 8904 // type. We separately check that every constexpr variable is of literal 8905 // type. 8906 } else if (VDecl->isConstexpr()) { 8907 8908 // Require constness. 8909 } else if (!DclT.isConstQualified()) { 8910 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8911 << Init->getSourceRange(); 8912 VDecl->setInvalidDecl(); 8913 8914 // We allow integer constant expressions in all cases. 8915 } else if (DclT->isIntegralOrEnumerationType()) { 8916 // Check whether the expression is a constant expression. 8917 SourceLocation Loc; 8918 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8919 // In C++11, a non-constexpr const static data member with an 8920 // in-class initializer cannot be volatile. 8921 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8922 else if (Init->isValueDependent()) 8923 ; // Nothing to check. 8924 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8925 ; // Ok, it's an ICE! 8926 else if (Init->isEvaluatable(Context)) { 8927 // If we can constant fold the initializer through heroics, accept it, 8928 // but report this as a use of an extension for -pedantic. 8929 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8930 << Init->getSourceRange(); 8931 } else { 8932 // Otherwise, this is some crazy unknown case. Report the issue at the 8933 // location provided by the isIntegerConstantExpr failed check. 8934 Diag(Loc, diag::err_in_class_initializer_non_constant) 8935 << Init->getSourceRange(); 8936 VDecl->setInvalidDecl(); 8937 } 8938 8939 // We allow foldable floating-point constants as an extension. 8940 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8941 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8942 // it anyway and provide a fixit to add the 'constexpr'. 8943 if (getLangOpts().CPlusPlus11) { 8944 Diag(VDecl->getLocation(), 8945 diag::ext_in_class_initializer_float_type_cxx11) 8946 << DclT << Init->getSourceRange(); 8947 Diag(VDecl->getLocStart(), 8948 diag::note_in_class_initializer_float_type_cxx11) 8949 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8950 } else { 8951 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8952 << DclT << Init->getSourceRange(); 8953 8954 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8955 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8956 << Init->getSourceRange(); 8957 VDecl->setInvalidDecl(); 8958 } 8959 } 8960 8961 // Suggest adding 'constexpr' in C++11 for literal types. 8962 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8963 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8964 << DclT << Init->getSourceRange() 8965 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8966 VDecl->setConstexpr(true); 8967 8968 } else { 8969 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8970 << DclT << Init->getSourceRange(); 8971 VDecl->setInvalidDecl(); 8972 } 8973 } else if (VDecl->isFileVarDecl()) { 8974 if (VDecl->getStorageClass() == SC_Extern && 8975 (!getLangOpts().CPlusPlus || 8976 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8977 VDecl->isExternC())) && 8978 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8979 Diag(VDecl->getLocation(), diag::warn_extern_init); 8980 8981 // C99 6.7.8p4. All file scoped initializers need to be constant. 8982 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8983 CheckForConstantInitializer(Init, DclT); 8984 } 8985 8986 // We will represent direct-initialization similarly to copy-initialization: 8987 // int x(1); -as-> int x = 1; 8988 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8989 // 8990 // Clients that want to distinguish between the two forms, can check for 8991 // direct initializer using VarDecl::getInitStyle(). 8992 // A major benefit is that clients that don't particularly care about which 8993 // exactly form was it (like the CodeGen) can handle both cases without 8994 // special case code. 8995 8996 // C++ 8.5p11: 8997 // The form of initialization (using parentheses or '=') is generally 8998 // insignificant, but does matter when the entity being initialized has a 8999 // class type. 9000 if (CXXDirectInit) { 9001 assert(DirectInit && "Call-style initializer must be direct init."); 9002 VDecl->setInitStyle(VarDecl::CallInit); 9003 } else if (DirectInit) { 9004 // This must be list-initialization. No other way is direct-initialization. 9005 VDecl->setInitStyle(VarDecl::ListInit); 9006 } 9007 9008 CheckCompleteVariableDeclaration(VDecl); 9009 } 9010 9011 /// ActOnInitializerError - Given that there was an error parsing an 9012 /// initializer for the given declaration, try to return to some form 9013 /// of sanity. 9014 void Sema::ActOnInitializerError(Decl *D) { 9015 // Our main concern here is re-establishing invariants like "a 9016 // variable's type is either dependent or complete". 9017 if (!D || D->isInvalidDecl()) return; 9018 9019 VarDecl *VD = dyn_cast<VarDecl>(D); 9020 if (!VD) return; 9021 9022 // Auto types are meaningless if we can't make sense of the initializer. 9023 if (ParsingInitForAutoVars.count(D)) { 9024 D->setInvalidDecl(); 9025 return; 9026 } 9027 9028 QualType Ty = VD->getType(); 9029 if (Ty->isDependentType()) return; 9030 9031 // Require a complete type. 9032 if (RequireCompleteType(VD->getLocation(), 9033 Context.getBaseElementType(Ty), 9034 diag::err_typecheck_decl_incomplete_type)) { 9035 VD->setInvalidDecl(); 9036 return; 9037 } 9038 9039 // Require a non-abstract type. 9040 if (RequireNonAbstractType(VD->getLocation(), Ty, 9041 diag::err_abstract_type_in_decl, 9042 AbstractVariableType)) { 9043 VD->setInvalidDecl(); 9044 return; 9045 } 9046 9047 // Don't bother complaining about constructors or destructors, 9048 // though. 9049 } 9050 9051 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9052 bool TypeMayContainAuto) { 9053 // If there is no declaration, there was an error parsing it. Just ignore it. 9054 if (!RealDecl) 9055 return; 9056 9057 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9058 QualType Type = Var->getType(); 9059 9060 // C++11 [dcl.spec.auto]p3 9061 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9062 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9063 << Var->getDeclName() << Type; 9064 Var->setInvalidDecl(); 9065 return; 9066 } 9067 9068 // C++11 [class.static.data]p3: A static data member can be declared with 9069 // the constexpr specifier; if so, its declaration shall specify 9070 // a brace-or-equal-initializer. 9071 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9072 // the definition of a variable [...] or the declaration of a static data 9073 // member. 9074 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9075 if (Var->isStaticDataMember()) 9076 Diag(Var->getLocation(), 9077 diag::err_constexpr_static_mem_var_requires_init) 9078 << Var->getDeclName(); 9079 else 9080 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9081 Var->setInvalidDecl(); 9082 return; 9083 } 9084 9085 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9086 // be initialized. 9087 if (!Var->isInvalidDecl() && 9088 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9089 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9090 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9091 Var->setInvalidDecl(); 9092 return; 9093 } 9094 9095 switch (Var->isThisDeclarationADefinition()) { 9096 case VarDecl::Definition: 9097 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9098 break; 9099 9100 // We have an out-of-line definition of a static data member 9101 // that has an in-class initializer, so we type-check this like 9102 // a declaration. 9103 // 9104 // Fall through 9105 9106 case VarDecl::DeclarationOnly: 9107 // It's only a declaration. 9108 9109 // Block scope. C99 6.7p7: If an identifier for an object is 9110 // declared with no linkage (C99 6.2.2p6), the type for the 9111 // object shall be complete. 9112 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9113 !Var->hasLinkage() && !Var->isInvalidDecl() && 9114 RequireCompleteType(Var->getLocation(), Type, 9115 diag::err_typecheck_decl_incomplete_type)) 9116 Var->setInvalidDecl(); 9117 9118 // Make sure that the type is not abstract. 9119 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9120 RequireNonAbstractType(Var->getLocation(), Type, 9121 diag::err_abstract_type_in_decl, 9122 AbstractVariableType)) 9123 Var->setInvalidDecl(); 9124 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9125 Var->getStorageClass() == SC_PrivateExtern) { 9126 Diag(Var->getLocation(), diag::warn_private_extern); 9127 Diag(Var->getLocation(), diag::note_private_extern); 9128 } 9129 9130 return; 9131 9132 case VarDecl::TentativeDefinition: 9133 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9134 // object that has file scope without an initializer, and without a 9135 // storage-class specifier or with the storage-class specifier "static", 9136 // constitutes a tentative definition. Note: A tentative definition with 9137 // external linkage is valid (C99 6.2.2p5). 9138 if (!Var->isInvalidDecl()) { 9139 if (const IncompleteArrayType *ArrayT 9140 = Context.getAsIncompleteArrayType(Type)) { 9141 if (RequireCompleteType(Var->getLocation(), 9142 ArrayT->getElementType(), 9143 diag::err_illegal_decl_array_incomplete_type)) 9144 Var->setInvalidDecl(); 9145 } else if (Var->getStorageClass() == SC_Static) { 9146 // C99 6.9.2p3: If the declaration of an identifier for an object is 9147 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9148 // declared type shall not be an incomplete type. 9149 // NOTE: code such as the following 9150 // static struct s; 9151 // struct s { int a; }; 9152 // is accepted by gcc. Hence here we issue a warning instead of 9153 // an error and we do not invalidate the static declaration. 9154 // NOTE: to avoid multiple warnings, only check the first declaration. 9155 if (Var->isFirstDecl()) 9156 RequireCompleteType(Var->getLocation(), Type, 9157 diag::ext_typecheck_decl_incomplete_type); 9158 } 9159 } 9160 9161 // Record the tentative definition; we're done. 9162 if (!Var->isInvalidDecl()) 9163 TentativeDefinitions.push_back(Var); 9164 return; 9165 } 9166 9167 // Provide a specific diagnostic for uninitialized variable 9168 // definitions with incomplete array type. 9169 if (Type->isIncompleteArrayType()) { 9170 Diag(Var->getLocation(), 9171 diag::err_typecheck_incomplete_array_needs_initializer); 9172 Var->setInvalidDecl(); 9173 return; 9174 } 9175 9176 // Provide a specific diagnostic for uninitialized variable 9177 // definitions with reference type. 9178 if (Type->isReferenceType()) { 9179 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9180 << Var->getDeclName() 9181 << SourceRange(Var->getLocation(), Var->getLocation()); 9182 Var->setInvalidDecl(); 9183 return; 9184 } 9185 9186 // Do not attempt to type-check the default initializer for a 9187 // variable with dependent type. 9188 if (Type->isDependentType()) 9189 return; 9190 9191 if (Var->isInvalidDecl()) 9192 return; 9193 9194 if (!Var->hasAttr<AliasAttr>()) { 9195 if (RequireCompleteType(Var->getLocation(), 9196 Context.getBaseElementType(Type), 9197 diag::err_typecheck_decl_incomplete_type)) { 9198 Var->setInvalidDecl(); 9199 return; 9200 } 9201 } 9202 9203 // The variable can not have an abstract class type. 9204 if (RequireNonAbstractType(Var->getLocation(), Type, 9205 diag::err_abstract_type_in_decl, 9206 AbstractVariableType)) { 9207 Var->setInvalidDecl(); 9208 return; 9209 } 9210 9211 // Check for jumps past the implicit initializer. C++0x 9212 // clarifies that this applies to a "variable with automatic 9213 // storage duration", not a "local variable". 9214 // C++11 [stmt.dcl]p3 9215 // A program that jumps from a point where a variable with automatic 9216 // storage duration is not in scope to a point where it is in scope is 9217 // ill-formed unless the variable has scalar type, class type with a 9218 // trivial default constructor and a trivial destructor, a cv-qualified 9219 // version of one of these types, or an array of one of the preceding 9220 // types and is declared without an initializer. 9221 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9222 if (const RecordType *Record 9223 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9224 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9225 // Mark the function for further checking even if the looser rules of 9226 // C++11 do not require such checks, so that we can diagnose 9227 // incompatibilities with C++98. 9228 if (!CXXRecord->isPOD()) 9229 getCurFunction()->setHasBranchProtectedScope(); 9230 } 9231 } 9232 9233 // C++03 [dcl.init]p9: 9234 // If no initializer is specified for an object, and the 9235 // object is of (possibly cv-qualified) non-POD class type (or 9236 // array thereof), the object shall be default-initialized; if 9237 // the object is of const-qualified type, the underlying class 9238 // type shall have a user-declared default 9239 // constructor. Otherwise, if no initializer is specified for 9240 // a non- static object, the object and its subobjects, if 9241 // any, have an indeterminate initial value); if the object 9242 // or any of its subobjects are of const-qualified type, the 9243 // program is ill-formed. 9244 // C++0x [dcl.init]p11: 9245 // If no initializer is specified for an object, the object is 9246 // default-initialized; [...]. 9247 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9248 InitializationKind Kind 9249 = InitializationKind::CreateDefault(Var->getLocation()); 9250 9251 InitializationSequence InitSeq(*this, Entity, Kind, None); 9252 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9253 if (Init.isInvalid()) 9254 Var->setInvalidDecl(); 9255 else if (Init.get()) { 9256 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9257 // This is important for template substitution. 9258 Var->setInitStyle(VarDecl::CallInit); 9259 } 9260 9261 CheckCompleteVariableDeclaration(Var); 9262 } 9263 } 9264 9265 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9266 VarDecl *VD = dyn_cast<VarDecl>(D); 9267 if (!VD) { 9268 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9269 D->setInvalidDecl(); 9270 return; 9271 } 9272 9273 VD->setCXXForRangeDecl(true); 9274 9275 // for-range-declaration cannot be given a storage class specifier. 9276 int Error = -1; 9277 switch (VD->getStorageClass()) { 9278 case SC_None: 9279 break; 9280 case SC_Extern: 9281 Error = 0; 9282 break; 9283 case SC_Static: 9284 Error = 1; 9285 break; 9286 case SC_PrivateExtern: 9287 Error = 2; 9288 break; 9289 case SC_Auto: 9290 Error = 3; 9291 break; 9292 case SC_Register: 9293 Error = 4; 9294 break; 9295 case SC_OpenCLWorkGroupLocal: 9296 llvm_unreachable("Unexpected storage class"); 9297 } 9298 if (VD->isConstexpr()) 9299 Error = 5; 9300 if (Error != -1) { 9301 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9302 << VD->getDeclName() << Error; 9303 D->setInvalidDecl(); 9304 } 9305 } 9306 9307 StmtResult 9308 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9309 IdentifierInfo *Ident, 9310 ParsedAttributes &Attrs, 9311 SourceLocation AttrEnd) { 9312 // C++1y [stmt.iter]p1: 9313 // A range-based for statement of the form 9314 // for ( for-range-identifier : for-range-initializer ) statement 9315 // is equivalent to 9316 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9317 DeclSpec DS(Attrs.getPool().getFactory()); 9318 9319 const char *PrevSpec; 9320 unsigned DiagID; 9321 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9322 getPrintingPolicy()); 9323 9324 Declarator D(DS, Declarator::ForContext); 9325 D.SetIdentifier(Ident, IdentLoc); 9326 D.takeAttributes(Attrs, AttrEnd); 9327 9328 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9329 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9330 EmptyAttrs, IdentLoc); 9331 Decl *Var = ActOnDeclarator(S, D); 9332 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9333 FinalizeDeclaration(Var); 9334 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9335 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9336 } 9337 9338 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9339 if (var->isInvalidDecl()) return; 9340 9341 // In ARC, don't allow jumps past the implicit initialization of a 9342 // local retaining variable. 9343 if (getLangOpts().ObjCAutoRefCount && 9344 var->hasLocalStorage()) { 9345 switch (var->getType().getObjCLifetime()) { 9346 case Qualifiers::OCL_None: 9347 case Qualifiers::OCL_ExplicitNone: 9348 case Qualifiers::OCL_Autoreleasing: 9349 break; 9350 9351 case Qualifiers::OCL_Weak: 9352 case Qualifiers::OCL_Strong: 9353 getCurFunction()->setHasBranchProtectedScope(); 9354 break; 9355 } 9356 } 9357 9358 // Warn about externally-visible variables being defined without a 9359 // prior declaration. We only want to do this for global 9360 // declarations, but we also specifically need to avoid doing it for 9361 // class members because the linkage of an anonymous class can 9362 // change if it's later given a typedef name. 9363 if (var->isThisDeclarationADefinition() && 9364 var->getDeclContext()->getRedeclContext()->isFileContext() && 9365 var->isExternallyVisible() && var->hasLinkage() && 9366 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9367 var->getLocation())) { 9368 // Find a previous declaration that's not a definition. 9369 VarDecl *prev = var->getPreviousDecl(); 9370 while (prev && prev->isThisDeclarationADefinition()) 9371 prev = prev->getPreviousDecl(); 9372 9373 if (!prev) 9374 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9375 } 9376 9377 if (var->getTLSKind() == VarDecl::TLS_Static) { 9378 const Expr *Culprit; 9379 if (var->getType().isDestructedType()) { 9380 // GNU C++98 edits for __thread, [basic.start.term]p3: 9381 // The type of an object with thread storage duration shall not 9382 // have a non-trivial destructor. 9383 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9384 if (getLangOpts().CPlusPlus11) 9385 Diag(var->getLocation(), diag::note_use_thread_local); 9386 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9387 !var->getInit()->isConstantInitializer( 9388 Context, var->getType()->isReferenceType(), &Culprit)) { 9389 // GNU C++98 edits for __thread, [basic.start.init]p4: 9390 // An object of thread storage duration shall not require dynamic 9391 // initialization. 9392 // FIXME: Need strict checking here. 9393 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9394 << Culprit->getSourceRange(); 9395 if (getLangOpts().CPlusPlus11) 9396 Diag(var->getLocation(), diag::note_use_thread_local); 9397 } 9398 9399 } 9400 9401 if (var->isThisDeclarationADefinition() && 9402 ActiveTemplateInstantiations.empty()) { 9403 PragmaStack<StringLiteral *> *Stack = nullptr; 9404 int SectionFlags = PSF_Implicit | PSF_Read; 9405 if (var->getType().isConstQualified()) 9406 Stack = &ConstSegStack; 9407 else if (!var->getInit()) { 9408 Stack = &BSSSegStack; 9409 SectionFlags |= PSF_Write; 9410 } else { 9411 Stack = &DataSegStack; 9412 SectionFlags |= PSF_Write; 9413 } 9414 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9415 var->addAttr( 9416 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9417 Stack->CurrentValue->getString(), 9418 Stack->CurrentPragmaLocation)); 9419 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9420 if (UnifySection(SA->getName(), SectionFlags, var)) 9421 var->dropAttr<SectionAttr>(); 9422 9423 // Apply the init_seg attribute if this has an initializer. If the 9424 // initializer turns out to not be dynamic, we'll end up ignoring this 9425 // attribute. 9426 if (CurInitSeg && var->getInit()) 9427 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9428 CurInitSegLoc)); 9429 } 9430 9431 // All the following checks are C++ only. 9432 if (!getLangOpts().CPlusPlus) return; 9433 9434 QualType type = var->getType(); 9435 if (type->isDependentType()) return; 9436 9437 // __block variables might require us to capture a copy-initializer. 9438 if (var->hasAttr<BlocksAttr>()) { 9439 // It's currently invalid to ever have a __block variable with an 9440 // array type; should we diagnose that here? 9441 9442 // Regardless, we don't want to ignore array nesting when 9443 // constructing this copy. 9444 if (type->isStructureOrClassType()) { 9445 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9446 SourceLocation poi = var->getLocation(); 9447 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9448 ExprResult result 9449 = PerformMoveOrCopyInitialization( 9450 InitializedEntity::InitializeBlock(poi, type, false), 9451 var, var->getType(), varRef, /*AllowNRVO=*/true); 9452 if (!result.isInvalid()) { 9453 result = MaybeCreateExprWithCleanups(result); 9454 Expr *init = result.getAs<Expr>(); 9455 Context.setBlockVarCopyInits(var, init); 9456 } 9457 } 9458 } 9459 9460 Expr *Init = var->getInit(); 9461 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9462 QualType baseType = Context.getBaseElementType(type); 9463 9464 if (!var->getDeclContext()->isDependentContext() && 9465 Init && !Init->isValueDependent()) { 9466 if (IsGlobal && !var->isConstexpr() && 9467 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9468 var->getLocation())) { 9469 // Warn about globals which don't have a constant initializer. Don't 9470 // warn about globals with a non-trivial destructor because we already 9471 // warned about them. 9472 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9473 if (!(RD && !RD->hasTrivialDestructor()) && 9474 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9475 Diag(var->getLocation(), diag::warn_global_constructor) 9476 << Init->getSourceRange(); 9477 } 9478 9479 if (var->isConstexpr()) { 9480 SmallVector<PartialDiagnosticAt, 8> Notes; 9481 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9482 SourceLocation DiagLoc = var->getLocation(); 9483 // If the note doesn't add any useful information other than a source 9484 // location, fold it into the primary diagnostic. 9485 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9486 diag::note_invalid_subexpr_in_const_expr) { 9487 DiagLoc = Notes[0].first; 9488 Notes.clear(); 9489 } 9490 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9491 << var << Init->getSourceRange(); 9492 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9493 Diag(Notes[I].first, Notes[I].second); 9494 } 9495 } else if (var->isUsableInConstantExpressions(Context)) { 9496 // Check whether the initializer of a const variable of integral or 9497 // enumeration type is an ICE now, since we can't tell whether it was 9498 // initialized by a constant expression if we check later. 9499 var->checkInitIsICE(); 9500 } 9501 } 9502 9503 // Require the destructor. 9504 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9505 FinalizeVarWithDestructor(var, recordType); 9506 } 9507 9508 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9509 /// any semantic actions necessary after any initializer has been attached. 9510 void 9511 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9512 // Note that we are no longer parsing the initializer for this declaration. 9513 ParsingInitForAutoVars.erase(ThisDecl); 9514 9515 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9516 if (!VD) 9517 return; 9518 9519 checkAttributesAfterMerging(*this, *VD); 9520 9521 // Static locals inherit dll attributes from their function. 9522 if (VD->isStaticLocal()) { 9523 if (FunctionDecl *FD = 9524 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9525 if (Attr *A = getDLLAttr(FD)) { 9526 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9527 NewAttr->setInherited(true); 9528 VD->addAttr(NewAttr); 9529 } 9530 } 9531 } 9532 9533 // Grab the dllimport or dllexport attribute off of the VarDecl. 9534 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9535 9536 // Imported static data members cannot be defined out-of-line. 9537 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9538 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9539 VD->isThisDeclarationADefinition()) { 9540 // We allow definitions of dllimport class template static data members 9541 // with a warning. 9542 CXXRecordDecl *Context = 9543 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9544 bool IsClassTemplateMember = 9545 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9546 Context->getDescribedClassTemplate(); 9547 9548 Diag(VD->getLocation(), 9549 IsClassTemplateMember 9550 ? diag::warn_attribute_dllimport_static_field_definition 9551 : diag::err_attribute_dllimport_static_field_definition); 9552 Diag(IA->getLocation(), diag::note_attribute); 9553 if (!IsClassTemplateMember) 9554 VD->setInvalidDecl(); 9555 } 9556 } 9557 9558 // dllimport/dllexport variables cannot be thread local, their TLS index 9559 // isn't exported with the variable. 9560 if (DLLAttr && VD->getTLSKind()) { 9561 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9562 << DLLAttr; 9563 VD->setInvalidDecl(); 9564 } 9565 9566 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9567 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9568 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9569 VD->dropAttr<UsedAttr>(); 9570 } 9571 } 9572 9573 if (!VD->isInvalidDecl() && 9574 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9575 if (const VarDecl *Def = VD->getDefinition()) { 9576 if (Def->hasAttr<AliasAttr>()) { 9577 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9578 << VD->getDeclName(); 9579 Diag(Def->getLocation(), diag::note_previous_definition); 9580 VD->setInvalidDecl(); 9581 } 9582 } 9583 } 9584 9585 const DeclContext *DC = VD->getDeclContext(); 9586 // If there's a #pragma GCC visibility in scope, and this isn't a class 9587 // member, set the visibility of this variable. 9588 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9589 AddPushedVisibilityAttribute(VD); 9590 9591 // FIXME: Warn on unused templates. 9592 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9593 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9594 MarkUnusedFileScopedDecl(VD); 9595 9596 // Now we have parsed the initializer and can update the table of magic 9597 // tag values. 9598 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9599 !VD->getType()->isIntegralOrEnumerationType()) 9600 return; 9601 9602 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9603 const Expr *MagicValueExpr = VD->getInit(); 9604 if (!MagicValueExpr) { 9605 continue; 9606 } 9607 llvm::APSInt MagicValueInt; 9608 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9609 Diag(I->getRange().getBegin(), 9610 diag::err_type_tag_for_datatype_not_ice) 9611 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9612 continue; 9613 } 9614 if (MagicValueInt.getActiveBits() > 64) { 9615 Diag(I->getRange().getBegin(), 9616 diag::err_type_tag_for_datatype_too_large) 9617 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9618 continue; 9619 } 9620 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9621 RegisterTypeTagForDatatype(I->getArgumentKind(), 9622 MagicValue, 9623 I->getMatchingCType(), 9624 I->getLayoutCompatible(), 9625 I->getMustBeNull()); 9626 } 9627 } 9628 9629 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9630 ArrayRef<Decl *> Group) { 9631 SmallVector<Decl*, 8> Decls; 9632 9633 if (DS.isTypeSpecOwned()) 9634 Decls.push_back(DS.getRepAsDecl()); 9635 9636 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9637 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9638 if (Decl *D = Group[i]) { 9639 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9640 if (!FirstDeclaratorInGroup) 9641 FirstDeclaratorInGroup = DD; 9642 Decls.push_back(D); 9643 } 9644 9645 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9646 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9647 HandleTagNumbering(*this, Tag, S); 9648 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9649 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9650 } 9651 } 9652 9653 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9654 } 9655 9656 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9657 /// group, performing any necessary semantic checking. 9658 Sema::DeclGroupPtrTy 9659 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9660 bool TypeMayContainAuto) { 9661 // C++0x [dcl.spec.auto]p7: 9662 // If the type deduced for the template parameter U is not the same in each 9663 // deduction, the program is ill-formed. 9664 // FIXME: When initializer-list support is added, a distinction is needed 9665 // between the deduced type U and the deduced type which 'auto' stands for. 9666 // auto a = 0, b = { 1, 2, 3 }; 9667 // is legal because the deduced type U is 'int' in both cases. 9668 if (TypeMayContainAuto && Group.size() > 1) { 9669 QualType Deduced; 9670 CanQualType DeducedCanon; 9671 VarDecl *DeducedDecl = nullptr; 9672 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9673 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9674 AutoType *AT = D->getType()->getContainedAutoType(); 9675 // Don't reissue diagnostics when instantiating a template. 9676 if (AT && D->isInvalidDecl()) 9677 break; 9678 QualType U = AT ? AT->getDeducedType() : QualType(); 9679 if (!U.isNull()) { 9680 CanQualType UCanon = Context.getCanonicalType(U); 9681 if (Deduced.isNull()) { 9682 Deduced = U; 9683 DeducedCanon = UCanon; 9684 DeducedDecl = D; 9685 } else if (DeducedCanon != UCanon) { 9686 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9687 diag::err_auto_different_deductions) 9688 << (AT->isDecltypeAuto() ? 1 : 0) 9689 << Deduced << DeducedDecl->getDeclName() 9690 << U << D->getDeclName() 9691 << DeducedDecl->getInit()->getSourceRange() 9692 << D->getInit()->getSourceRange(); 9693 D->setInvalidDecl(); 9694 break; 9695 } 9696 } 9697 } 9698 } 9699 } 9700 9701 ActOnDocumentableDecls(Group); 9702 9703 return DeclGroupPtrTy::make( 9704 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9705 } 9706 9707 void Sema::ActOnDocumentableDecl(Decl *D) { 9708 ActOnDocumentableDecls(D); 9709 } 9710 9711 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9712 // Don't parse the comment if Doxygen diagnostics are ignored. 9713 if (Group.empty() || !Group[0]) 9714 return; 9715 9716 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9717 return; 9718 9719 if (Group.size() >= 2) { 9720 // This is a decl group. Normally it will contain only declarations 9721 // produced from declarator list. But in case we have any definitions or 9722 // additional declaration references: 9723 // 'typedef struct S {} S;' 9724 // 'typedef struct S *S;' 9725 // 'struct S *pS;' 9726 // FinalizeDeclaratorGroup adds these as separate declarations. 9727 Decl *MaybeTagDecl = Group[0]; 9728 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9729 Group = Group.slice(1); 9730 } 9731 } 9732 9733 // See if there are any new comments that are not attached to a decl. 9734 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9735 if (!Comments.empty() && 9736 !Comments.back()->isAttached()) { 9737 // There is at least one comment that not attached to a decl. 9738 // Maybe it should be attached to one of these decls? 9739 // 9740 // Note that this way we pick up not only comments that precede the 9741 // declaration, but also comments that *follow* the declaration -- thanks to 9742 // the lookahead in the lexer: we've consumed the semicolon and looked 9743 // ahead through comments. 9744 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9745 Context.getCommentForDecl(Group[i], &PP); 9746 } 9747 } 9748 9749 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9750 /// to introduce parameters into function prototype scope. 9751 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9752 const DeclSpec &DS = D.getDeclSpec(); 9753 9754 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9755 9756 // C++03 [dcl.stc]p2 also permits 'auto'. 9757 VarDecl::StorageClass StorageClass = SC_None; 9758 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9759 StorageClass = SC_Register; 9760 } else if (getLangOpts().CPlusPlus && 9761 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9762 StorageClass = SC_Auto; 9763 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9764 Diag(DS.getStorageClassSpecLoc(), 9765 diag::err_invalid_storage_class_in_func_decl); 9766 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9767 } 9768 9769 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9770 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9771 << DeclSpec::getSpecifierName(TSCS); 9772 if (DS.isConstexprSpecified()) 9773 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9774 << 0; 9775 9776 DiagnoseFunctionSpecifiers(DS); 9777 9778 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9779 QualType parmDeclType = TInfo->getType(); 9780 9781 if (getLangOpts().CPlusPlus) { 9782 // Check that there are no default arguments inside the type of this 9783 // parameter. 9784 CheckExtraCXXDefaultArguments(D); 9785 9786 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9787 if (D.getCXXScopeSpec().isSet()) { 9788 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9789 << D.getCXXScopeSpec().getRange(); 9790 D.getCXXScopeSpec().clear(); 9791 } 9792 } 9793 9794 // Ensure we have a valid name 9795 IdentifierInfo *II = nullptr; 9796 if (D.hasName()) { 9797 II = D.getIdentifier(); 9798 if (!II) { 9799 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9800 << GetNameForDeclarator(D).getName(); 9801 D.setInvalidType(true); 9802 } 9803 } 9804 9805 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9806 if (II) { 9807 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9808 ForRedeclaration); 9809 LookupName(R, S); 9810 if (R.isSingleResult()) { 9811 NamedDecl *PrevDecl = R.getFoundDecl(); 9812 if (PrevDecl->isTemplateParameter()) { 9813 // Maybe we will complain about the shadowed template parameter. 9814 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9815 // Just pretend that we didn't see the previous declaration. 9816 PrevDecl = nullptr; 9817 } else if (S->isDeclScope(PrevDecl)) { 9818 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9819 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9820 9821 // Recover by removing the name 9822 II = nullptr; 9823 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9824 D.setInvalidType(true); 9825 } 9826 } 9827 } 9828 9829 // Temporarily put parameter variables in the translation unit, not 9830 // the enclosing context. This prevents them from accidentally 9831 // looking like class members in C++. 9832 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9833 D.getLocStart(), 9834 D.getIdentifierLoc(), II, 9835 parmDeclType, TInfo, 9836 StorageClass); 9837 9838 if (D.isInvalidType()) 9839 New->setInvalidDecl(); 9840 9841 assert(S->isFunctionPrototypeScope()); 9842 assert(S->getFunctionPrototypeDepth() >= 1); 9843 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9844 S->getNextFunctionPrototypeIndex()); 9845 9846 // Add the parameter declaration into this scope. 9847 S->AddDecl(New); 9848 if (II) 9849 IdResolver.AddDecl(New); 9850 9851 ProcessDeclAttributes(S, New, D); 9852 9853 if (D.getDeclSpec().isModulePrivateSpecified()) 9854 Diag(New->getLocation(), diag::err_module_private_local) 9855 << 1 << New->getDeclName() 9856 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9857 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9858 9859 if (New->hasAttr<BlocksAttr>()) { 9860 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9861 } 9862 return New; 9863 } 9864 9865 /// \brief Synthesizes a variable for a parameter arising from a 9866 /// typedef. 9867 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9868 SourceLocation Loc, 9869 QualType T) { 9870 /* FIXME: setting StartLoc == Loc. 9871 Would it be worth to modify callers so as to provide proper source 9872 location for the unnamed parameters, embedding the parameter's type? */ 9873 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9874 T, Context.getTrivialTypeSourceInfo(T, Loc), 9875 SC_None, nullptr); 9876 Param->setImplicit(); 9877 return Param; 9878 } 9879 9880 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9881 ParmVarDecl * const *ParamEnd) { 9882 // Don't diagnose unused-parameter errors in template instantiations; we 9883 // will already have done so in the template itself. 9884 if (!ActiveTemplateInstantiations.empty()) 9885 return; 9886 9887 for (; Param != ParamEnd; ++Param) { 9888 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9889 !(*Param)->hasAttr<UnusedAttr>()) { 9890 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9891 << (*Param)->getDeclName(); 9892 } 9893 } 9894 } 9895 9896 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9897 ParmVarDecl * const *ParamEnd, 9898 QualType ReturnTy, 9899 NamedDecl *D) { 9900 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9901 return; 9902 9903 // Warn if the return value is pass-by-value and larger than the specified 9904 // threshold. 9905 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9906 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9907 if (Size > LangOpts.NumLargeByValueCopy) 9908 Diag(D->getLocation(), diag::warn_return_value_size) 9909 << D->getDeclName() << Size; 9910 } 9911 9912 // Warn if any parameter is pass-by-value and larger than the specified 9913 // threshold. 9914 for (; Param != ParamEnd; ++Param) { 9915 QualType T = (*Param)->getType(); 9916 if (T->isDependentType() || !T.isPODType(Context)) 9917 continue; 9918 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9919 if (Size > LangOpts.NumLargeByValueCopy) 9920 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9921 << (*Param)->getDeclName() << Size; 9922 } 9923 } 9924 9925 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9926 SourceLocation NameLoc, IdentifierInfo *Name, 9927 QualType T, TypeSourceInfo *TSInfo, 9928 VarDecl::StorageClass StorageClass) { 9929 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9930 if (getLangOpts().ObjCAutoRefCount && 9931 T.getObjCLifetime() == Qualifiers::OCL_None && 9932 T->isObjCLifetimeType()) { 9933 9934 Qualifiers::ObjCLifetime lifetime; 9935 9936 // Special cases for arrays: 9937 // - if it's const, use __unsafe_unretained 9938 // - otherwise, it's an error 9939 if (T->isArrayType()) { 9940 if (!T.isConstQualified()) { 9941 DelayedDiagnostics.add( 9942 sema::DelayedDiagnostic::makeForbiddenType( 9943 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9944 } 9945 lifetime = Qualifiers::OCL_ExplicitNone; 9946 } else { 9947 lifetime = T->getObjCARCImplicitLifetime(); 9948 } 9949 T = Context.getLifetimeQualifiedType(T, lifetime); 9950 } 9951 9952 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9953 Context.getAdjustedParameterType(T), 9954 TSInfo, 9955 StorageClass, nullptr); 9956 9957 // Parameters can not be abstract class types. 9958 // For record types, this is done by the AbstractClassUsageDiagnoser once 9959 // the class has been completely parsed. 9960 if (!CurContext->isRecord() && 9961 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9962 AbstractParamType)) 9963 New->setInvalidDecl(); 9964 9965 // Parameter declarators cannot be interface types. All ObjC objects are 9966 // passed by reference. 9967 if (T->isObjCObjectType()) { 9968 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9969 Diag(NameLoc, 9970 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9971 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9972 T = Context.getObjCObjectPointerType(T); 9973 New->setType(T); 9974 } 9975 9976 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9977 // duration shall not be qualified by an address-space qualifier." 9978 // Since all parameters have automatic store duration, they can not have 9979 // an address space. 9980 if (T.getAddressSpace() != 0) { 9981 // OpenCL allows function arguments declared to be an array of a type 9982 // to be qualified with an address space. 9983 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9984 Diag(NameLoc, diag::err_arg_with_address_space); 9985 New->setInvalidDecl(); 9986 } 9987 } 9988 9989 return New; 9990 } 9991 9992 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9993 SourceLocation LocAfterDecls) { 9994 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9995 9996 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9997 // for a K&R function. 9998 if (!FTI.hasPrototype) { 9999 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10000 --i; 10001 if (FTI.Params[i].Param == nullptr) { 10002 SmallString<256> Code; 10003 llvm::raw_svector_ostream(Code) 10004 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10005 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10006 << FTI.Params[i].Ident 10007 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 10008 10009 // Implicitly declare the argument as type 'int' for lack of a better 10010 // type. 10011 AttributeFactory attrs; 10012 DeclSpec DS(attrs); 10013 const char* PrevSpec; // unused 10014 unsigned DiagID; // unused 10015 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10016 DiagID, Context.getPrintingPolicy()); 10017 // Use the identifier location for the type source range. 10018 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10019 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10020 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10021 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10022 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10023 } 10024 } 10025 } 10026 } 10027 10028 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10029 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10030 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10031 Scope *ParentScope = FnBodyScope->getParent(); 10032 10033 D.setFunctionDefinitionKind(FDK_Definition); 10034 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10035 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10036 } 10037 10038 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10039 Consumer.HandleInlineMethodDefinition(D); 10040 } 10041 10042 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10043 const FunctionDecl*& PossibleZeroParamPrototype) { 10044 // Don't warn about invalid declarations. 10045 if (FD->isInvalidDecl()) 10046 return false; 10047 10048 // Or declarations that aren't global. 10049 if (!FD->isGlobal()) 10050 return false; 10051 10052 // Don't warn about C++ member functions. 10053 if (isa<CXXMethodDecl>(FD)) 10054 return false; 10055 10056 // Don't warn about 'main'. 10057 if (FD->isMain()) 10058 return false; 10059 10060 // Don't warn about inline functions. 10061 if (FD->isInlined()) 10062 return false; 10063 10064 // Don't warn about function templates. 10065 if (FD->getDescribedFunctionTemplate()) 10066 return false; 10067 10068 // Don't warn about function template specializations. 10069 if (FD->isFunctionTemplateSpecialization()) 10070 return false; 10071 10072 // Don't warn for OpenCL kernels. 10073 if (FD->hasAttr<OpenCLKernelAttr>()) 10074 return false; 10075 10076 bool MissingPrototype = true; 10077 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10078 Prev; Prev = Prev->getPreviousDecl()) { 10079 // Ignore any declarations that occur in function or method 10080 // scope, because they aren't visible from the header. 10081 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10082 continue; 10083 10084 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10085 if (FD->getNumParams() == 0) 10086 PossibleZeroParamPrototype = Prev; 10087 break; 10088 } 10089 10090 return MissingPrototype; 10091 } 10092 10093 void 10094 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10095 const FunctionDecl *EffectiveDefinition) { 10096 // Don't complain if we're in GNU89 mode and the previous definition 10097 // was an extern inline function. 10098 const FunctionDecl *Definition = EffectiveDefinition; 10099 if (!Definition) 10100 if (!FD->isDefined(Definition)) 10101 return; 10102 10103 if (canRedefineFunction(Definition, getLangOpts())) 10104 return; 10105 10106 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10107 Definition->getStorageClass() == SC_Extern) 10108 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10109 << FD->getDeclName() << getLangOpts().CPlusPlus; 10110 else 10111 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10112 10113 Diag(Definition->getLocation(), diag::note_previous_definition); 10114 FD->setInvalidDecl(); 10115 } 10116 10117 10118 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10119 Sema &S) { 10120 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10121 10122 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10123 LSI->CallOperator = CallOperator; 10124 LSI->Lambda = LambdaClass; 10125 LSI->ReturnType = CallOperator->getReturnType(); 10126 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10127 10128 if (LCD == LCD_None) 10129 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10130 else if (LCD == LCD_ByCopy) 10131 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10132 else if (LCD == LCD_ByRef) 10133 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10134 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10135 10136 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10137 LSI->Mutable = !CallOperator->isConst(); 10138 10139 // Add the captures to the LSI so they can be noted as already 10140 // captured within tryCaptureVar. 10141 auto I = LambdaClass->field_begin(); 10142 for (const auto &C : LambdaClass->captures()) { 10143 if (C.capturesVariable()) { 10144 VarDecl *VD = C.getCapturedVar(); 10145 if (VD->isInitCapture()) 10146 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10147 QualType CaptureType = VD->getType(); 10148 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10149 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10150 /*RefersToEnclosingLocal*/true, C.getLocation(), 10151 /*EllipsisLoc*/C.isPackExpansion() 10152 ? C.getEllipsisLoc() : SourceLocation(), 10153 CaptureType, /*Expr*/ nullptr); 10154 10155 } else if (C.capturesThis()) { 10156 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10157 S.getCurrentThisType(), /*Expr*/ nullptr); 10158 } else { 10159 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10160 } 10161 ++I; 10162 } 10163 } 10164 10165 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10166 // Clear the last template instantiation error context. 10167 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10168 10169 if (!D) 10170 return D; 10171 FunctionDecl *FD = nullptr; 10172 10173 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10174 FD = FunTmpl->getTemplatedDecl(); 10175 else 10176 FD = cast<FunctionDecl>(D); 10177 // If we are instantiating a generic lambda call operator, push 10178 // a LambdaScopeInfo onto the function stack. But use the information 10179 // that's already been calculated (ActOnLambdaExpr) to prime the current 10180 // LambdaScopeInfo. 10181 // When the template operator is being specialized, the LambdaScopeInfo, 10182 // has to be properly restored so that tryCaptureVariable doesn't try 10183 // and capture any new variables. In addition when calculating potential 10184 // captures during transformation of nested lambdas, it is necessary to 10185 // have the LSI properly restored. 10186 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10187 assert(ActiveTemplateInstantiations.size() && 10188 "There should be an active template instantiation on the stack " 10189 "when instantiating a generic lambda!"); 10190 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10191 } 10192 else 10193 // Enter a new function scope 10194 PushFunctionScope(); 10195 10196 // See if this is a redefinition. 10197 if (!FD->isLateTemplateParsed()) 10198 CheckForFunctionRedefinition(FD); 10199 10200 // Builtin functions cannot be defined. 10201 if (unsigned BuiltinID = FD->getBuiltinID()) { 10202 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10203 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10204 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10205 FD->setInvalidDecl(); 10206 } 10207 } 10208 10209 // The return type of a function definition must be complete 10210 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10211 QualType ResultType = FD->getReturnType(); 10212 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10213 !FD->isInvalidDecl() && 10214 RequireCompleteType(FD->getLocation(), ResultType, 10215 diag::err_func_def_incomplete_result)) 10216 FD->setInvalidDecl(); 10217 10218 // GNU warning -Wmissing-prototypes: 10219 // Warn if a global function is defined without a previous 10220 // prototype declaration. This warning is issued even if the 10221 // definition itself provides a prototype. The aim is to detect 10222 // global functions that fail to be declared in header files. 10223 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10224 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10225 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10226 10227 if (PossibleZeroParamPrototype) { 10228 // We found a declaration that is not a prototype, 10229 // but that could be a zero-parameter prototype 10230 if (TypeSourceInfo *TI = 10231 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10232 TypeLoc TL = TI->getTypeLoc(); 10233 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10234 Diag(PossibleZeroParamPrototype->getLocation(), 10235 diag::note_declaration_not_a_prototype) 10236 << PossibleZeroParamPrototype 10237 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10238 } 10239 } 10240 } 10241 10242 if (FnBodyScope) 10243 PushDeclContext(FnBodyScope, FD); 10244 10245 // Check the validity of our function parameters 10246 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10247 /*CheckParameterNames=*/true); 10248 10249 // Introduce our parameters into the function scope 10250 for (auto Param : FD->params()) { 10251 Param->setOwningFunction(FD); 10252 10253 // If this has an identifier, add it to the scope stack. 10254 if (Param->getIdentifier() && FnBodyScope) { 10255 CheckShadow(FnBodyScope, Param); 10256 10257 PushOnScopeChains(Param, FnBodyScope); 10258 } 10259 } 10260 10261 // If we had any tags defined in the function prototype, 10262 // introduce them into the function scope. 10263 if (FnBodyScope) { 10264 for (ArrayRef<NamedDecl *>::iterator 10265 I = FD->getDeclsInPrototypeScope().begin(), 10266 E = FD->getDeclsInPrototypeScope().end(); 10267 I != E; ++I) { 10268 NamedDecl *D = *I; 10269 10270 // Some of these decls (like enums) may have been pinned to the translation unit 10271 // for lack of a real context earlier. If so, remove from the translation unit 10272 // and reattach to the current context. 10273 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10274 // Is the decl actually in the context? 10275 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10276 if (DI == D) { 10277 Context.getTranslationUnitDecl()->removeDecl(D); 10278 break; 10279 } 10280 } 10281 // Either way, reassign the lexical decl context to our FunctionDecl. 10282 D->setLexicalDeclContext(CurContext); 10283 } 10284 10285 // If the decl has a non-null name, make accessible in the current scope. 10286 if (!D->getName().empty()) 10287 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10288 10289 // Similarly, dive into enums and fish their constants out, making them 10290 // accessible in this scope. 10291 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10292 for (auto *EI : ED->enumerators()) 10293 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10294 } 10295 } 10296 } 10297 10298 // Ensure that the function's exception specification is instantiated. 10299 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10300 ResolveExceptionSpec(D->getLocation(), FPT); 10301 10302 // dllimport cannot be applied to non-inline function definitions. 10303 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10304 !FD->isTemplateInstantiation()) { 10305 assert(!FD->hasAttr<DLLExportAttr>()); 10306 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10307 FD->setInvalidDecl(); 10308 return D; 10309 } 10310 // We want to attach documentation to original Decl (which might be 10311 // a function template). 10312 ActOnDocumentableDecl(D); 10313 if (getCurLexicalContext()->isObjCContainer() && 10314 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10315 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10316 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10317 10318 return D; 10319 } 10320 10321 /// \brief Given the set of return statements within a function body, 10322 /// compute the variables that are subject to the named return value 10323 /// optimization. 10324 /// 10325 /// Each of the variables that is subject to the named return value 10326 /// optimization will be marked as NRVO variables in the AST, and any 10327 /// return statement that has a marked NRVO variable as its NRVO candidate can 10328 /// use the named return value optimization. 10329 /// 10330 /// This function applies a very simplistic algorithm for NRVO: if every return 10331 /// statement in the scope of a variable has the same NRVO candidate, that 10332 /// candidate is an NRVO variable. 10333 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10334 ReturnStmt **Returns = Scope->Returns.data(); 10335 10336 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10337 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10338 if (!NRVOCandidate->isNRVOVariable()) 10339 Returns[I]->setNRVOCandidate(nullptr); 10340 } 10341 } 10342 } 10343 10344 bool Sema::canDelayFunctionBody(const Declarator &D) { 10345 // We can't delay parsing the body of a constexpr function template (yet). 10346 if (D.getDeclSpec().isConstexprSpecified()) 10347 return false; 10348 10349 // We can't delay parsing the body of a function template with a deduced 10350 // return type (yet). 10351 if (D.getDeclSpec().containsPlaceholderType()) { 10352 // If the placeholder introduces a non-deduced trailing return type, 10353 // we can still delay parsing it. 10354 if (D.getNumTypeObjects()) { 10355 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10356 if (Outer.Kind == DeclaratorChunk::Function && 10357 Outer.Fun.hasTrailingReturnType()) { 10358 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10359 return Ty.isNull() || !Ty->isUndeducedType(); 10360 } 10361 } 10362 return false; 10363 } 10364 10365 return true; 10366 } 10367 10368 bool Sema::canSkipFunctionBody(Decl *D) { 10369 // We cannot skip the body of a function (or function template) which is 10370 // constexpr, since we may need to evaluate its body in order to parse the 10371 // rest of the file. 10372 // We cannot skip the body of a function with an undeduced return type, 10373 // because any callers of that function need to know the type. 10374 if (const FunctionDecl *FD = D->getAsFunction()) 10375 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10376 return false; 10377 return Consumer.shouldSkipFunctionBody(D); 10378 } 10379 10380 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10381 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10382 FD->setHasSkippedBody(); 10383 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10384 MD->setHasSkippedBody(); 10385 return ActOnFinishFunctionBody(Decl, nullptr); 10386 } 10387 10388 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10389 return ActOnFinishFunctionBody(D, BodyArg, false); 10390 } 10391 10392 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10393 bool IsInstantiation) { 10394 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10395 10396 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10397 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10398 10399 if (FD) { 10400 FD->setBody(Body); 10401 10402 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10403 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10404 // If the function has a deduced result type but contains no 'return' 10405 // statements, the result type as written must be exactly 'auto', and 10406 // the deduced result type is 'void'. 10407 if (!FD->getReturnType()->getAs<AutoType>()) { 10408 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10409 << FD->getReturnType(); 10410 FD->setInvalidDecl(); 10411 } else { 10412 // Substitute 'void' for the 'auto' in the type. 10413 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 10414 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 10415 Context.adjustDeducedFunctionResultType( 10416 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10417 } 10418 } 10419 10420 // The only way to be included in UndefinedButUsed is if there is an 10421 // ODR use before the definition. Avoid the expensive map lookup if this 10422 // is the first declaration. 10423 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10424 if (!FD->isExternallyVisible()) 10425 UndefinedButUsed.erase(FD); 10426 else if (FD->isInlined() && 10427 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10428 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10429 UndefinedButUsed.erase(FD); 10430 } 10431 10432 // If the function implicitly returns zero (like 'main') or is naked, 10433 // don't complain about missing return statements. 10434 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10435 WP.disableCheckFallThrough(); 10436 10437 // MSVC permits the use of pure specifier (=0) on function definition, 10438 // defined at class scope, warn about this non-standard construct. 10439 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10440 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10441 10442 if (!FD->isInvalidDecl()) { 10443 // Don't diagnose unused parameters of defaulted or deleted functions. 10444 if (Body) 10445 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10446 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10447 FD->getReturnType(), FD); 10448 10449 // If this is a constructor, we need a vtable. 10450 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10451 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10452 10453 // Try to apply the named return value optimization. We have to check 10454 // if we can do this here because lambdas keep return statements around 10455 // to deduce an implicit return type. 10456 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10457 !FD->isDependentContext()) 10458 computeNRVO(Body, getCurFunction()); 10459 } 10460 10461 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10462 "Function parsing confused"); 10463 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10464 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10465 MD->setBody(Body); 10466 if (!MD->isInvalidDecl()) { 10467 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10468 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10469 MD->getReturnType(), MD); 10470 10471 if (Body) 10472 computeNRVO(Body, getCurFunction()); 10473 } 10474 if (getCurFunction()->ObjCShouldCallSuper) { 10475 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10476 << MD->getSelector().getAsString(); 10477 getCurFunction()->ObjCShouldCallSuper = false; 10478 } 10479 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10480 const ObjCMethodDecl *InitMethod = nullptr; 10481 bool isDesignated = 10482 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10483 assert(isDesignated && InitMethod); 10484 (void)isDesignated; 10485 10486 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10487 auto IFace = MD->getClassInterface(); 10488 if (!IFace) 10489 return false; 10490 auto SuperD = IFace->getSuperClass(); 10491 if (!SuperD) 10492 return false; 10493 return SuperD->getIdentifier() == 10494 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10495 }; 10496 // Don't issue this warning for unavailable inits or direct subclasses 10497 // of NSObject. 10498 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10499 Diag(MD->getLocation(), 10500 diag::warn_objc_designated_init_missing_super_call); 10501 Diag(InitMethod->getLocation(), 10502 diag::note_objc_designated_init_marked_here); 10503 } 10504 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10505 } 10506 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10507 // Don't issue this warning for unavaialable inits. 10508 if (!MD->isUnavailable()) 10509 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10510 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10511 } 10512 } else { 10513 return nullptr; 10514 } 10515 10516 assert(!getCurFunction()->ObjCShouldCallSuper && 10517 "This should only be set for ObjC methods, which should have been " 10518 "handled in the block above."); 10519 10520 // Verify and clean out per-function state. 10521 if (Body) { 10522 // C++ constructors that have function-try-blocks can't have return 10523 // statements in the handlers of that block. (C++ [except.handle]p14) 10524 // Verify this. 10525 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10526 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10527 10528 // Verify that gotos and switch cases don't jump into scopes illegally. 10529 if (getCurFunction()->NeedsScopeChecking() && 10530 !PP.isCodeCompletionEnabled()) 10531 DiagnoseInvalidJumps(Body); 10532 10533 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10534 if (!Destructor->getParent()->isDependentType()) 10535 CheckDestructor(Destructor); 10536 10537 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10538 Destructor->getParent()); 10539 } 10540 10541 // If any errors have occurred, clear out any temporaries that may have 10542 // been leftover. This ensures that these temporaries won't be picked up for 10543 // deletion in some later function. 10544 if (getDiagnostics().hasErrorOccurred() || 10545 getDiagnostics().getSuppressAllDiagnostics()) { 10546 DiscardCleanupsInEvaluationContext(); 10547 } 10548 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10549 !isa<FunctionTemplateDecl>(dcl)) { 10550 // Since the body is valid, issue any analysis-based warnings that are 10551 // enabled. 10552 ActivePolicy = &WP; 10553 } 10554 10555 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10556 (!CheckConstexprFunctionDecl(FD) || 10557 !CheckConstexprFunctionBody(FD, Body))) 10558 FD->setInvalidDecl(); 10559 10560 if (FD && FD->hasAttr<NakedAttr>()) { 10561 for (const Stmt *S : Body->children()) { 10562 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10563 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10564 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10565 FD->setInvalidDecl(); 10566 break; 10567 } 10568 } 10569 } 10570 10571 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10572 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10573 assert(MaybeODRUseExprs.empty() && 10574 "Leftover expressions for odr-use checking"); 10575 } 10576 10577 if (!IsInstantiation) 10578 PopDeclContext(); 10579 10580 PopFunctionScopeInfo(ActivePolicy, dcl); 10581 // If any errors have occurred, clear out any temporaries that may have 10582 // been leftover. This ensures that these temporaries won't be picked up for 10583 // deletion in some later function. 10584 if (getDiagnostics().hasErrorOccurred()) { 10585 DiscardCleanupsInEvaluationContext(); 10586 } 10587 10588 return dcl; 10589 } 10590 10591 10592 /// When we finish delayed parsing of an attribute, we must attach it to the 10593 /// relevant Decl. 10594 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10595 ParsedAttributes &Attrs) { 10596 // Always attach attributes to the underlying decl. 10597 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10598 D = TD->getTemplatedDecl(); 10599 ProcessDeclAttributeList(S, D, Attrs.getList()); 10600 10601 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10602 if (Method->isStatic()) 10603 checkThisInStaticMemberFunctionAttributes(Method); 10604 } 10605 10606 10607 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10608 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10609 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10610 IdentifierInfo &II, Scope *S) { 10611 // Before we produce a declaration for an implicitly defined 10612 // function, see whether there was a locally-scoped declaration of 10613 // this name as a function or variable. If so, use that 10614 // (non-visible) declaration, and complain about it. 10615 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10616 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10617 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10618 return ExternCPrev; 10619 } 10620 10621 // Extension in C99. Legal in C90, but warn about it. 10622 unsigned diag_id; 10623 if (II.getName().startswith("__builtin_")) 10624 diag_id = diag::warn_builtin_unknown; 10625 else if (getLangOpts().C99) 10626 diag_id = diag::ext_implicit_function_decl; 10627 else 10628 diag_id = diag::warn_implicit_function_decl; 10629 Diag(Loc, diag_id) << &II; 10630 10631 // Because typo correction is expensive, only do it if the implicit 10632 // function declaration is going to be treated as an error. 10633 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10634 TypoCorrection Corrected; 10635 DeclFilterCCC<FunctionDecl> Validator; 10636 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10637 LookupOrdinaryName, S, nullptr, Validator, 10638 CTK_NonError))) 10639 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10640 /*ErrorRecovery*/false); 10641 } 10642 10643 // Set a Declarator for the implicit definition: int foo(); 10644 const char *Dummy; 10645 AttributeFactory attrFactory; 10646 DeclSpec DS(attrFactory); 10647 unsigned DiagID; 10648 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10649 Context.getPrintingPolicy()); 10650 (void)Error; // Silence warning. 10651 assert(!Error && "Error setting up implicit decl!"); 10652 SourceLocation NoLoc; 10653 Declarator D(DS, Declarator::BlockContext); 10654 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10655 /*IsAmbiguous=*/false, 10656 /*LParenLoc=*/NoLoc, 10657 /*Params=*/nullptr, 10658 /*NumParams=*/0, 10659 /*EllipsisLoc=*/NoLoc, 10660 /*RParenLoc=*/NoLoc, 10661 /*TypeQuals=*/0, 10662 /*RefQualifierIsLvalueRef=*/true, 10663 /*RefQualifierLoc=*/NoLoc, 10664 /*ConstQualifierLoc=*/NoLoc, 10665 /*VolatileQualifierLoc=*/NoLoc, 10666 /*MutableLoc=*/NoLoc, 10667 EST_None, 10668 /*ESpecLoc=*/NoLoc, 10669 /*Exceptions=*/nullptr, 10670 /*ExceptionRanges=*/nullptr, 10671 /*NumExceptions=*/0, 10672 /*NoexceptExpr=*/nullptr, 10673 Loc, Loc, D), 10674 DS.getAttributes(), 10675 SourceLocation()); 10676 D.SetIdentifier(&II, Loc); 10677 10678 // Insert this function into translation-unit scope. 10679 10680 DeclContext *PrevDC = CurContext; 10681 CurContext = Context.getTranslationUnitDecl(); 10682 10683 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10684 FD->setImplicit(); 10685 10686 CurContext = PrevDC; 10687 10688 AddKnownFunctionAttributes(FD); 10689 10690 return FD; 10691 } 10692 10693 /// \brief Adds any function attributes that we know a priori based on 10694 /// the declaration of this function. 10695 /// 10696 /// These attributes can apply both to implicitly-declared builtins 10697 /// (like __builtin___printf_chk) or to library-declared functions 10698 /// like NSLog or printf. 10699 /// 10700 /// We need to check for duplicate attributes both here and where user-written 10701 /// attributes are applied to declarations. 10702 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10703 if (FD->isInvalidDecl()) 10704 return; 10705 10706 // If this is a built-in function, map its builtin attributes to 10707 // actual attributes. 10708 if (unsigned BuiltinID = FD->getBuiltinID()) { 10709 // Handle printf-formatting attributes. 10710 unsigned FormatIdx; 10711 bool HasVAListArg; 10712 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10713 if (!FD->hasAttr<FormatAttr>()) { 10714 const char *fmt = "printf"; 10715 unsigned int NumParams = FD->getNumParams(); 10716 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10717 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10718 fmt = "NSString"; 10719 FD->addAttr(FormatAttr::CreateImplicit(Context, 10720 &Context.Idents.get(fmt), 10721 FormatIdx+1, 10722 HasVAListArg ? 0 : FormatIdx+2, 10723 FD->getLocation())); 10724 } 10725 } 10726 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10727 HasVAListArg)) { 10728 if (!FD->hasAttr<FormatAttr>()) 10729 FD->addAttr(FormatAttr::CreateImplicit(Context, 10730 &Context.Idents.get("scanf"), 10731 FormatIdx+1, 10732 HasVAListArg ? 0 : FormatIdx+2, 10733 FD->getLocation())); 10734 } 10735 10736 // Mark const if we don't care about errno and that is the only 10737 // thing preventing the function from being const. This allows 10738 // IRgen to use LLVM intrinsics for such functions. 10739 if (!getLangOpts().MathErrno && 10740 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10741 if (!FD->hasAttr<ConstAttr>()) 10742 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10743 } 10744 10745 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10746 !FD->hasAttr<ReturnsTwiceAttr>()) 10747 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10748 FD->getLocation())); 10749 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10750 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10751 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10752 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10753 } 10754 10755 IdentifierInfo *Name = FD->getIdentifier(); 10756 if (!Name) 10757 return; 10758 if ((!getLangOpts().CPlusPlus && 10759 FD->getDeclContext()->isTranslationUnit()) || 10760 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10761 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10762 LinkageSpecDecl::lang_c)) { 10763 // Okay: this could be a libc/libm/Objective-C function we know 10764 // about. 10765 } else 10766 return; 10767 10768 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10769 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10770 // target-specific builtins, perhaps? 10771 if (!FD->hasAttr<FormatAttr>()) 10772 FD->addAttr(FormatAttr::CreateImplicit(Context, 10773 &Context.Idents.get("printf"), 2, 10774 Name->isStr("vasprintf") ? 0 : 3, 10775 FD->getLocation())); 10776 } 10777 10778 if (Name->isStr("__CFStringMakeConstantString")) { 10779 // We already have a __builtin___CFStringMakeConstantString, 10780 // but builds that use -fno-constant-cfstrings don't go through that. 10781 if (!FD->hasAttr<FormatArgAttr>()) 10782 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10783 FD->getLocation())); 10784 } 10785 } 10786 10787 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10788 TypeSourceInfo *TInfo) { 10789 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10790 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10791 10792 if (!TInfo) { 10793 assert(D.isInvalidType() && "no declarator info for valid type"); 10794 TInfo = Context.getTrivialTypeSourceInfo(T); 10795 } 10796 10797 // Scope manipulation handled by caller. 10798 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10799 D.getLocStart(), 10800 D.getIdentifierLoc(), 10801 D.getIdentifier(), 10802 TInfo); 10803 10804 // Bail out immediately if we have an invalid declaration. 10805 if (D.isInvalidType()) { 10806 NewTD->setInvalidDecl(); 10807 return NewTD; 10808 } 10809 10810 if (D.getDeclSpec().isModulePrivateSpecified()) { 10811 if (CurContext->isFunctionOrMethod()) 10812 Diag(NewTD->getLocation(), diag::err_module_private_local) 10813 << 2 << NewTD->getDeclName() 10814 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10815 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10816 else 10817 NewTD->setModulePrivate(); 10818 } 10819 10820 // C++ [dcl.typedef]p8: 10821 // If the typedef declaration defines an unnamed class (or 10822 // enum), the first typedef-name declared by the declaration 10823 // to be that class type (or enum type) is used to denote the 10824 // class type (or enum type) for linkage purposes only. 10825 // We need to check whether the type was declared in the declaration. 10826 switch (D.getDeclSpec().getTypeSpecType()) { 10827 case TST_enum: 10828 case TST_struct: 10829 case TST_interface: 10830 case TST_union: 10831 case TST_class: { 10832 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10833 10834 // Do nothing if the tag is not anonymous or already has an 10835 // associated typedef (from an earlier typedef in this decl group). 10836 if (tagFromDeclSpec->getIdentifier()) break; 10837 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10838 10839 // A well-formed anonymous tag must always be a TUK_Definition. 10840 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10841 10842 // The type must match the tag exactly; no qualifiers allowed. 10843 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10844 break; 10845 10846 // If we've already computed linkage for the anonymous tag, then 10847 // adding a typedef name for the anonymous decl can change that 10848 // linkage, which might be a serious problem. Diagnose this as 10849 // unsupported and ignore the typedef name. TODO: we should 10850 // pursue this as a language defect and establish a formal rule 10851 // for how to handle it. 10852 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10853 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10854 10855 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10856 tagLoc = getLocForEndOfToken(tagLoc); 10857 10858 llvm::SmallString<40> textToInsert; 10859 textToInsert += ' '; 10860 textToInsert += D.getIdentifier()->getName(); 10861 Diag(tagLoc, diag::note_typedef_changes_linkage) 10862 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10863 break; 10864 } 10865 10866 // Otherwise, set this is the anon-decl typedef for the tag. 10867 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10868 break; 10869 } 10870 10871 default: 10872 break; 10873 } 10874 10875 return NewTD; 10876 } 10877 10878 10879 /// \brief Check that this is a valid underlying type for an enum declaration. 10880 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10881 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10882 QualType T = TI->getType(); 10883 10884 if (T->isDependentType()) 10885 return false; 10886 10887 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10888 if (BT->isInteger()) 10889 return false; 10890 10891 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10892 return true; 10893 } 10894 10895 /// Check whether this is a valid redeclaration of a previous enumeration. 10896 /// \return true if the redeclaration was invalid. 10897 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10898 QualType EnumUnderlyingTy, 10899 const EnumDecl *Prev) { 10900 bool IsFixed = !EnumUnderlyingTy.isNull(); 10901 10902 if (IsScoped != Prev->isScoped()) { 10903 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10904 << Prev->isScoped(); 10905 Diag(Prev->getLocation(), diag::note_previous_declaration); 10906 return true; 10907 } 10908 10909 if (IsFixed && Prev->isFixed()) { 10910 if (!EnumUnderlyingTy->isDependentType() && 10911 !Prev->getIntegerType()->isDependentType() && 10912 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10913 Prev->getIntegerType())) { 10914 // TODO: Highlight the underlying type of the redeclaration. 10915 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10916 << EnumUnderlyingTy << Prev->getIntegerType(); 10917 Diag(Prev->getLocation(), diag::note_previous_declaration) 10918 << Prev->getIntegerTypeRange(); 10919 return true; 10920 } 10921 } else if (IsFixed != Prev->isFixed()) { 10922 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10923 << Prev->isFixed(); 10924 Diag(Prev->getLocation(), diag::note_previous_declaration); 10925 return true; 10926 } 10927 10928 return false; 10929 } 10930 10931 /// \brief Get diagnostic %select index for tag kind for 10932 /// redeclaration diagnostic message. 10933 /// WARNING: Indexes apply to particular diagnostics only! 10934 /// 10935 /// \returns diagnostic %select index. 10936 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10937 switch (Tag) { 10938 case TTK_Struct: return 0; 10939 case TTK_Interface: return 1; 10940 case TTK_Class: return 2; 10941 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10942 } 10943 } 10944 10945 /// \brief Determine if tag kind is a class-key compatible with 10946 /// class for redeclaration (class, struct, or __interface). 10947 /// 10948 /// \returns true iff the tag kind is compatible. 10949 static bool isClassCompatTagKind(TagTypeKind Tag) 10950 { 10951 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10952 } 10953 10954 /// \brief Determine whether a tag with a given kind is acceptable 10955 /// as a redeclaration of the given tag declaration. 10956 /// 10957 /// \returns true if the new tag kind is acceptable, false otherwise. 10958 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10959 TagTypeKind NewTag, bool isDefinition, 10960 SourceLocation NewTagLoc, 10961 const IdentifierInfo &Name) { 10962 // C++ [dcl.type.elab]p3: 10963 // The class-key or enum keyword present in the 10964 // elaborated-type-specifier shall agree in kind with the 10965 // declaration to which the name in the elaborated-type-specifier 10966 // refers. This rule also applies to the form of 10967 // elaborated-type-specifier that declares a class-name or 10968 // friend class since it can be construed as referring to the 10969 // definition of the class. Thus, in any 10970 // elaborated-type-specifier, the enum keyword shall be used to 10971 // refer to an enumeration (7.2), the union class-key shall be 10972 // used to refer to a union (clause 9), and either the class or 10973 // struct class-key shall be used to refer to a class (clause 9) 10974 // declared using the class or struct class-key. 10975 TagTypeKind OldTag = Previous->getTagKind(); 10976 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10977 if (OldTag == NewTag) 10978 return true; 10979 10980 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10981 // Warn about the struct/class tag mismatch. 10982 bool isTemplate = false; 10983 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10984 isTemplate = Record->getDescribedClassTemplate(); 10985 10986 if (!ActiveTemplateInstantiations.empty()) { 10987 // In a template instantiation, do not offer fix-its for tag mismatches 10988 // since they usually mess up the template instead of fixing the problem. 10989 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10990 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10991 << getRedeclDiagFromTagKind(OldTag); 10992 return true; 10993 } 10994 10995 if (isDefinition) { 10996 // On definitions, check previous tags and issue a fix-it for each 10997 // one that doesn't match the current tag. 10998 if (Previous->getDefinition()) { 10999 // Don't suggest fix-its for redefinitions. 11000 return true; 11001 } 11002 11003 bool previousMismatch = false; 11004 for (auto I : Previous->redecls()) { 11005 if (I->getTagKind() != NewTag) { 11006 if (!previousMismatch) { 11007 previousMismatch = true; 11008 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11009 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11010 << getRedeclDiagFromTagKind(I->getTagKind()); 11011 } 11012 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11013 << getRedeclDiagFromTagKind(NewTag) 11014 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11015 TypeWithKeyword::getTagTypeKindName(NewTag)); 11016 } 11017 } 11018 return true; 11019 } 11020 11021 // Check for a previous definition. If current tag and definition 11022 // are same type, do nothing. If no definition, but disagree with 11023 // with previous tag type, give a warning, but no fix-it. 11024 const TagDecl *Redecl = Previous->getDefinition() ? 11025 Previous->getDefinition() : Previous; 11026 if (Redecl->getTagKind() == NewTag) { 11027 return true; 11028 } 11029 11030 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11031 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11032 << getRedeclDiagFromTagKind(OldTag); 11033 Diag(Redecl->getLocation(), diag::note_previous_use); 11034 11035 // If there is a previous definition, suggest a fix-it. 11036 if (Previous->getDefinition()) { 11037 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11038 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11039 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11040 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11041 } 11042 11043 return true; 11044 } 11045 return false; 11046 } 11047 11048 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11049 /// from an outer enclosing namespace or file scope inside a friend declaration. 11050 /// This should provide the commented out code in the following snippet: 11051 /// namespace N { 11052 /// struct X; 11053 /// namespace M { 11054 /// struct Y { friend struct /*N::*/ X; }; 11055 /// } 11056 /// } 11057 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11058 SourceLocation NameLoc) { 11059 // While the decl is in a namespace, do repeated lookup of that name and see 11060 // if we get the same namespace back. If we do not, continue until 11061 // translation unit scope, at which point we have a fully qualified NNS. 11062 SmallVector<IdentifierInfo *, 4> Namespaces; 11063 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11064 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11065 // This tag should be declared in a namespace, which can only be enclosed by 11066 // other namespaces. Bail if there's an anonymous namespace in the chain. 11067 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11068 if (!Namespace || Namespace->isAnonymousNamespace()) 11069 return FixItHint(); 11070 IdentifierInfo *II = Namespace->getIdentifier(); 11071 Namespaces.push_back(II); 11072 NamedDecl *Lookup = SemaRef.LookupSingleName( 11073 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11074 if (Lookup == Namespace) 11075 break; 11076 } 11077 11078 // Once we have all the namespaces, reverse them to go outermost first, and 11079 // build an NNS. 11080 SmallString<64> Insertion; 11081 llvm::raw_svector_ostream OS(Insertion); 11082 if (DC->isTranslationUnit()) 11083 OS << "::"; 11084 std::reverse(Namespaces.begin(), Namespaces.end()); 11085 for (auto *II : Namespaces) 11086 OS << II->getName() << "::"; 11087 OS.flush(); 11088 return FixItHint::CreateInsertion(NameLoc, Insertion); 11089 } 11090 11091 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11092 /// former case, Name will be non-null. In the later case, Name will be null. 11093 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11094 /// reference/declaration/definition of a tag. 11095 /// 11096 /// IsTypeSpecifier is true if this is a type-specifier (or 11097 /// trailing-type-specifier) other than one in an alias-declaration. 11098 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11099 SourceLocation KWLoc, CXXScopeSpec &SS, 11100 IdentifierInfo *Name, SourceLocation NameLoc, 11101 AttributeList *Attr, AccessSpecifier AS, 11102 SourceLocation ModulePrivateLoc, 11103 MultiTemplateParamsArg TemplateParameterLists, 11104 bool &OwnedDecl, bool &IsDependent, 11105 SourceLocation ScopedEnumKWLoc, 11106 bool ScopedEnumUsesClassTag, 11107 TypeResult UnderlyingType, 11108 bool IsTypeSpecifier) { 11109 // If this is not a definition, it must have a name. 11110 IdentifierInfo *OrigName = Name; 11111 assert((Name != nullptr || TUK == TUK_Definition) && 11112 "Nameless record must be a definition!"); 11113 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11114 11115 OwnedDecl = false; 11116 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11117 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11118 11119 // FIXME: Check explicit specializations more carefully. 11120 bool isExplicitSpecialization = false; 11121 bool Invalid = false; 11122 11123 // We only need to do this matching if we have template parameters 11124 // or a scope specifier, which also conveniently avoids this work 11125 // for non-C++ cases. 11126 if (TemplateParameterLists.size() > 0 || 11127 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11128 if (TemplateParameterList *TemplateParams = 11129 MatchTemplateParametersToScopeSpecifier( 11130 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11131 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11132 if (Kind == TTK_Enum) { 11133 Diag(KWLoc, diag::err_enum_template); 11134 return nullptr; 11135 } 11136 11137 if (TemplateParams->size() > 0) { 11138 // This is a declaration or definition of a class template (which may 11139 // be a member of another template). 11140 11141 if (Invalid) 11142 return nullptr; 11143 11144 OwnedDecl = false; 11145 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11146 SS, Name, NameLoc, Attr, 11147 TemplateParams, AS, 11148 ModulePrivateLoc, 11149 /*FriendLoc*/SourceLocation(), 11150 TemplateParameterLists.size()-1, 11151 TemplateParameterLists.data()); 11152 return Result.get(); 11153 } else { 11154 // The "template<>" header is extraneous. 11155 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11156 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11157 isExplicitSpecialization = true; 11158 } 11159 } 11160 } 11161 11162 // Figure out the underlying type if this a enum declaration. We need to do 11163 // this early, because it's needed to detect if this is an incompatible 11164 // redeclaration. 11165 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11166 11167 if (Kind == TTK_Enum) { 11168 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11169 // No underlying type explicitly specified, or we failed to parse the 11170 // type, default to int. 11171 EnumUnderlying = Context.IntTy.getTypePtr(); 11172 else if (UnderlyingType.get()) { 11173 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11174 // integral type; any cv-qualification is ignored. 11175 TypeSourceInfo *TI = nullptr; 11176 GetTypeFromParser(UnderlyingType.get(), &TI); 11177 EnumUnderlying = TI; 11178 11179 if (CheckEnumUnderlyingType(TI)) 11180 // Recover by falling back to int. 11181 EnumUnderlying = Context.IntTy.getTypePtr(); 11182 11183 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11184 UPPC_FixedUnderlyingType)) 11185 EnumUnderlying = Context.IntTy.getTypePtr(); 11186 11187 } else if (getLangOpts().MSVCCompat) 11188 // Microsoft enums are always of int type. 11189 EnumUnderlying = Context.IntTy.getTypePtr(); 11190 } 11191 11192 DeclContext *SearchDC = CurContext; 11193 DeclContext *DC = CurContext; 11194 bool isStdBadAlloc = false; 11195 11196 RedeclarationKind Redecl = ForRedeclaration; 11197 if (TUK == TUK_Friend || TUK == TUK_Reference) 11198 Redecl = NotForRedeclaration; 11199 11200 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11201 if (Name && SS.isNotEmpty()) { 11202 // We have a nested-name tag ('struct foo::bar'). 11203 11204 // Check for invalid 'foo::'. 11205 if (SS.isInvalid()) { 11206 Name = nullptr; 11207 goto CreateNewDecl; 11208 } 11209 11210 // If this is a friend or a reference to a class in a dependent 11211 // context, don't try to make a decl for it. 11212 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11213 DC = computeDeclContext(SS, false); 11214 if (!DC) { 11215 IsDependent = true; 11216 return nullptr; 11217 } 11218 } else { 11219 DC = computeDeclContext(SS, true); 11220 if (!DC) { 11221 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11222 << SS.getRange(); 11223 return nullptr; 11224 } 11225 } 11226 11227 if (RequireCompleteDeclContext(SS, DC)) 11228 return nullptr; 11229 11230 SearchDC = DC; 11231 // Look-up name inside 'foo::'. 11232 LookupQualifiedName(Previous, DC); 11233 11234 if (Previous.isAmbiguous()) 11235 return nullptr; 11236 11237 if (Previous.empty()) { 11238 // Name lookup did not find anything. However, if the 11239 // nested-name-specifier refers to the current instantiation, 11240 // and that current instantiation has any dependent base 11241 // classes, we might find something at instantiation time: treat 11242 // this as a dependent elaborated-type-specifier. 11243 // But this only makes any sense for reference-like lookups. 11244 if (Previous.wasNotFoundInCurrentInstantiation() && 11245 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11246 IsDependent = true; 11247 return nullptr; 11248 } 11249 11250 // A tag 'foo::bar' must already exist. 11251 Diag(NameLoc, diag::err_not_tag_in_scope) 11252 << Kind << Name << DC << SS.getRange(); 11253 Name = nullptr; 11254 Invalid = true; 11255 goto CreateNewDecl; 11256 } 11257 } else if (Name) { 11258 // If this is a named struct, check to see if there was a previous forward 11259 // declaration or definition. 11260 // FIXME: We're looking into outer scopes here, even when we 11261 // shouldn't be. Doing so can result in ambiguities that we 11262 // shouldn't be diagnosing. 11263 LookupName(Previous, S); 11264 11265 // When declaring or defining a tag, ignore ambiguities introduced 11266 // by types using'ed into this scope. 11267 if (Previous.isAmbiguous() && 11268 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11269 LookupResult::Filter F = Previous.makeFilter(); 11270 while (F.hasNext()) { 11271 NamedDecl *ND = F.next(); 11272 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11273 F.erase(); 11274 } 11275 F.done(); 11276 } 11277 11278 // C++11 [namespace.memdef]p3: 11279 // If the name in a friend declaration is neither qualified nor 11280 // a template-id and the declaration is a function or an 11281 // elaborated-type-specifier, the lookup to determine whether 11282 // the entity has been previously declared shall not consider 11283 // any scopes outside the innermost enclosing namespace. 11284 // 11285 // MSVC doesn't implement the above rule for types, so a friend tag 11286 // declaration may be a redeclaration of a type declared in an enclosing 11287 // scope. They do implement this rule for friend functions. 11288 // 11289 // Does it matter that this should be by scope instead of by 11290 // semantic context? 11291 if (!Previous.empty() && TUK == TUK_Friend) { 11292 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11293 LookupResult::Filter F = Previous.makeFilter(); 11294 bool FriendSawTagOutsideEnclosingNamespace = false; 11295 while (F.hasNext()) { 11296 NamedDecl *ND = F.next(); 11297 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11298 if (DC->isFileContext() && 11299 !EnclosingNS->Encloses(ND->getDeclContext())) { 11300 if (getLangOpts().MSVCCompat) 11301 FriendSawTagOutsideEnclosingNamespace = true; 11302 else 11303 F.erase(); 11304 } 11305 } 11306 F.done(); 11307 11308 // Diagnose this MSVC extension in the easy case where lookup would have 11309 // unambiguously found something outside the enclosing namespace. 11310 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11311 NamedDecl *ND = Previous.getFoundDecl(); 11312 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11313 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11314 } 11315 } 11316 11317 // Note: there used to be some attempt at recovery here. 11318 if (Previous.isAmbiguous()) 11319 return nullptr; 11320 11321 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11322 // FIXME: This makes sure that we ignore the contexts associated 11323 // with C structs, unions, and enums when looking for a matching 11324 // tag declaration or definition. See the similar lookup tweak 11325 // in Sema::LookupName; is there a better way to deal with this? 11326 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11327 SearchDC = SearchDC->getParent(); 11328 } 11329 } 11330 11331 if (Previous.isSingleResult() && 11332 Previous.getFoundDecl()->isTemplateParameter()) { 11333 // Maybe we will complain about the shadowed template parameter. 11334 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11335 // Just pretend that we didn't see the previous declaration. 11336 Previous.clear(); 11337 } 11338 11339 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11340 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11341 // This is a declaration of or a reference to "std::bad_alloc". 11342 isStdBadAlloc = true; 11343 11344 if (Previous.empty() && StdBadAlloc) { 11345 // std::bad_alloc has been implicitly declared (but made invisible to 11346 // name lookup). Fill in this implicit declaration as the previous 11347 // declaration, so that the declarations get chained appropriately. 11348 Previous.addDecl(getStdBadAlloc()); 11349 } 11350 } 11351 11352 // If we didn't find a previous declaration, and this is a reference 11353 // (or friend reference), move to the correct scope. In C++, we 11354 // also need to do a redeclaration lookup there, just in case 11355 // there's a shadow friend decl. 11356 if (Name && Previous.empty() && 11357 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11358 if (Invalid) goto CreateNewDecl; 11359 assert(SS.isEmpty()); 11360 11361 if (TUK == TUK_Reference) { 11362 // C++ [basic.scope.pdecl]p5: 11363 // -- for an elaborated-type-specifier of the form 11364 // 11365 // class-key identifier 11366 // 11367 // if the elaborated-type-specifier is used in the 11368 // decl-specifier-seq or parameter-declaration-clause of a 11369 // function defined in namespace scope, the identifier is 11370 // declared as a class-name in the namespace that contains 11371 // the declaration; otherwise, except as a friend 11372 // declaration, the identifier is declared in the smallest 11373 // non-class, non-function-prototype scope that contains the 11374 // declaration. 11375 // 11376 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11377 // C structs and unions. 11378 // 11379 // It is an error in C++ to declare (rather than define) an enum 11380 // type, including via an elaborated type specifier. We'll 11381 // diagnose that later; for now, declare the enum in the same 11382 // scope as we would have picked for any other tag type. 11383 // 11384 // GNU C also supports this behavior as part of its incomplete 11385 // enum types extension, while GNU C++ does not. 11386 // 11387 // Find the context where we'll be declaring the tag. 11388 // FIXME: We would like to maintain the current DeclContext as the 11389 // lexical context, 11390 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11391 SearchDC = SearchDC->getParent(); 11392 11393 // Find the scope where we'll be declaring the tag. 11394 while (S->isClassScope() || 11395 (getLangOpts().CPlusPlus && 11396 S->isFunctionPrototypeScope()) || 11397 ((S->getFlags() & Scope::DeclScope) == 0) || 11398 (S->getEntity() && S->getEntity()->isTransparentContext())) 11399 S = S->getParent(); 11400 } else { 11401 assert(TUK == TUK_Friend); 11402 // C++ [namespace.memdef]p3: 11403 // If a friend declaration in a non-local class first declares a 11404 // class or function, the friend class or function is a member of 11405 // the innermost enclosing namespace. 11406 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11407 } 11408 11409 // In C++, we need to do a redeclaration lookup to properly 11410 // diagnose some problems. 11411 if (getLangOpts().CPlusPlus) { 11412 Previous.setRedeclarationKind(ForRedeclaration); 11413 LookupQualifiedName(Previous, SearchDC); 11414 } 11415 } 11416 11417 if (!Previous.empty()) { 11418 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11419 NamedDecl *DirectPrevDecl = 11420 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11421 11422 // It's okay to have a tag decl in the same scope as a typedef 11423 // which hides a tag decl in the same scope. Finding this 11424 // insanity with a redeclaration lookup can only actually happen 11425 // in C++. 11426 // 11427 // This is also okay for elaborated-type-specifiers, which is 11428 // technically forbidden by the current standard but which is 11429 // okay according to the likely resolution of an open issue; 11430 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11431 if (getLangOpts().CPlusPlus) { 11432 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11433 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11434 TagDecl *Tag = TT->getDecl(); 11435 if (Tag->getDeclName() == Name && 11436 Tag->getDeclContext()->getRedeclContext() 11437 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11438 PrevDecl = Tag; 11439 Previous.clear(); 11440 Previous.addDecl(Tag); 11441 Previous.resolveKind(); 11442 } 11443 } 11444 } 11445 } 11446 11447 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11448 // If this is a use of a previous tag, or if the tag is already declared 11449 // in the same scope (so that the definition/declaration completes or 11450 // rementions the tag), reuse the decl. 11451 if (TUK == TUK_Reference || TUK == TUK_Friend || 11452 isDeclInScope(DirectPrevDecl, SearchDC, S, 11453 SS.isNotEmpty() || isExplicitSpecialization)) { 11454 // Make sure that this wasn't declared as an enum and now used as a 11455 // struct or something similar. 11456 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11457 TUK == TUK_Definition, KWLoc, 11458 *Name)) { 11459 bool SafeToContinue 11460 = (PrevTagDecl->getTagKind() != TTK_Enum && 11461 Kind != TTK_Enum); 11462 if (SafeToContinue) 11463 Diag(KWLoc, diag::err_use_with_wrong_tag) 11464 << Name 11465 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11466 PrevTagDecl->getKindName()); 11467 else 11468 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11469 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11470 11471 if (SafeToContinue) 11472 Kind = PrevTagDecl->getTagKind(); 11473 else { 11474 // Recover by making this an anonymous redefinition. 11475 Name = nullptr; 11476 Previous.clear(); 11477 Invalid = true; 11478 } 11479 } 11480 11481 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11482 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11483 11484 // If this is an elaborated-type-specifier for a scoped enumeration, 11485 // the 'class' keyword is not necessary and not permitted. 11486 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11487 if (ScopedEnum) 11488 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11489 << PrevEnum->isScoped() 11490 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11491 return PrevTagDecl; 11492 } 11493 11494 QualType EnumUnderlyingTy; 11495 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11496 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11497 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11498 EnumUnderlyingTy = QualType(T, 0); 11499 11500 // All conflicts with previous declarations are recovered by 11501 // returning the previous declaration, unless this is a definition, 11502 // in which case we want the caller to bail out. 11503 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11504 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11505 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11506 } 11507 11508 // C++11 [class.mem]p1: 11509 // A member shall not be declared twice in the member-specification, 11510 // except that a nested class or member class template can be declared 11511 // and then later defined. 11512 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11513 S->isDeclScope(PrevDecl)) { 11514 Diag(NameLoc, diag::ext_member_redeclared); 11515 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11516 } 11517 11518 if (!Invalid) { 11519 // If this is a use, just return the declaration we found, unless 11520 // we have attributes. 11521 11522 // FIXME: In the future, return a variant or some other clue 11523 // for the consumer of this Decl to know it doesn't own it. 11524 // For our current ASTs this shouldn't be a problem, but will 11525 // need to be changed with DeclGroups. 11526 if (!Attr && 11527 ((TUK == TUK_Reference && 11528 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11529 || TUK == TUK_Friend)) 11530 return PrevTagDecl; 11531 11532 // Diagnose attempts to redefine a tag. 11533 if (TUK == TUK_Definition) { 11534 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11535 // If we're defining a specialization and the previous definition 11536 // is from an implicit instantiation, don't emit an error 11537 // here; we'll catch this in the general case below. 11538 bool IsExplicitSpecializationAfterInstantiation = false; 11539 if (isExplicitSpecialization) { 11540 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11541 IsExplicitSpecializationAfterInstantiation = 11542 RD->getTemplateSpecializationKind() != 11543 TSK_ExplicitSpecialization; 11544 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11545 IsExplicitSpecializationAfterInstantiation = 11546 ED->getTemplateSpecializationKind() != 11547 TSK_ExplicitSpecialization; 11548 } 11549 11550 if (!IsExplicitSpecializationAfterInstantiation) { 11551 // A redeclaration in function prototype scope in C isn't 11552 // visible elsewhere, so merely issue a warning. 11553 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11554 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11555 else 11556 Diag(NameLoc, diag::err_redefinition) << Name; 11557 Diag(Def->getLocation(), diag::note_previous_definition); 11558 // If this is a redefinition, recover by making this 11559 // struct be anonymous, which will make any later 11560 // references get the previous definition. 11561 Name = nullptr; 11562 Previous.clear(); 11563 Invalid = true; 11564 } 11565 } else { 11566 // If the type is currently being defined, complain 11567 // about a nested redefinition. 11568 const TagType *Tag 11569 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 11570 if (Tag->isBeingDefined()) { 11571 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11572 Diag(PrevTagDecl->getLocation(), 11573 diag::note_previous_definition); 11574 Name = nullptr; 11575 Previous.clear(); 11576 Invalid = true; 11577 } 11578 } 11579 11580 // Okay, this is definition of a previously declared or referenced 11581 // tag. We're going to create a new Decl for it. 11582 } 11583 11584 // Okay, we're going to make a redeclaration. If this is some kind 11585 // of reference, make sure we build the redeclaration in the same DC 11586 // as the original, and ignore the current access specifier. 11587 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11588 SearchDC = PrevTagDecl->getDeclContext(); 11589 AS = AS_none; 11590 } 11591 } 11592 // If we get here we have (another) forward declaration or we 11593 // have a definition. Just create a new decl. 11594 11595 } else { 11596 // If we get here, this is a definition of a new tag type in a nested 11597 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11598 // new decl/type. We set PrevDecl to NULL so that the entities 11599 // have distinct types. 11600 Previous.clear(); 11601 } 11602 // If we get here, we're going to create a new Decl. If PrevDecl 11603 // is non-NULL, it's a definition of the tag declared by 11604 // PrevDecl. If it's NULL, we have a new definition. 11605 11606 11607 // Otherwise, PrevDecl is not a tag, but was found with tag 11608 // lookup. This is only actually possible in C++, where a few 11609 // things like templates still live in the tag namespace. 11610 } else { 11611 // Use a better diagnostic if an elaborated-type-specifier 11612 // found the wrong kind of type on the first 11613 // (non-redeclaration) lookup. 11614 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11615 !Previous.isForRedeclaration()) { 11616 unsigned Kind = 0; 11617 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11618 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11619 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11620 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11621 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11622 Invalid = true; 11623 11624 // Otherwise, only diagnose if the declaration is in scope. 11625 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11626 SS.isNotEmpty() || isExplicitSpecialization)) { 11627 // do nothing 11628 11629 // Diagnose implicit declarations introduced by elaborated types. 11630 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11631 unsigned Kind = 0; 11632 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11633 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11634 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11635 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11636 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11637 Invalid = true; 11638 11639 // Otherwise it's a declaration. Call out a particularly common 11640 // case here. 11641 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11642 unsigned Kind = 0; 11643 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11644 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11645 << Name << Kind << TND->getUnderlyingType(); 11646 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11647 Invalid = true; 11648 11649 // Otherwise, diagnose. 11650 } else { 11651 // The tag name clashes with something else in the target scope, 11652 // issue an error and recover by making this tag be anonymous. 11653 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11654 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11655 Name = nullptr; 11656 Invalid = true; 11657 } 11658 11659 // The existing declaration isn't relevant to us; we're in a 11660 // new scope, so clear out the previous declaration. 11661 Previous.clear(); 11662 } 11663 } 11664 11665 CreateNewDecl: 11666 11667 TagDecl *PrevDecl = nullptr; 11668 if (Previous.isSingleResult()) 11669 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11670 11671 // If there is an identifier, use the location of the identifier as the 11672 // location of the decl, otherwise use the location of the struct/union 11673 // keyword. 11674 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11675 11676 // Otherwise, create a new declaration. If there is a previous 11677 // declaration of the same entity, the two will be linked via 11678 // PrevDecl. 11679 TagDecl *New; 11680 11681 bool IsForwardReference = false; 11682 if (Kind == TTK_Enum) { 11683 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11684 // enum X { A, B, C } D; D should chain to X. 11685 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11686 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11687 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11688 // If this is an undefined enum, warn. 11689 if (TUK != TUK_Definition && !Invalid) { 11690 TagDecl *Def; 11691 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11692 cast<EnumDecl>(New)->isFixed()) { 11693 // C++0x: 7.2p2: opaque-enum-declaration. 11694 // Conflicts are diagnosed above. Do nothing. 11695 } 11696 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11697 Diag(Loc, diag::ext_forward_ref_enum_def) 11698 << New; 11699 Diag(Def->getLocation(), diag::note_previous_definition); 11700 } else { 11701 unsigned DiagID = diag::ext_forward_ref_enum; 11702 if (getLangOpts().MSVCCompat) 11703 DiagID = diag::ext_ms_forward_ref_enum; 11704 else if (getLangOpts().CPlusPlus) 11705 DiagID = diag::err_forward_ref_enum; 11706 Diag(Loc, DiagID); 11707 11708 // If this is a forward-declared reference to an enumeration, make a 11709 // note of it; we won't actually be introducing the declaration into 11710 // the declaration context. 11711 if (TUK == TUK_Reference) 11712 IsForwardReference = true; 11713 } 11714 } 11715 11716 if (EnumUnderlying) { 11717 EnumDecl *ED = cast<EnumDecl>(New); 11718 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11719 ED->setIntegerTypeSourceInfo(TI); 11720 else 11721 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11722 ED->setPromotionType(ED->getIntegerType()); 11723 } 11724 11725 } else { 11726 // struct/union/class 11727 11728 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11729 // struct X { int A; } D; D should chain to X. 11730 if (getLangOpts().CPlusPlus) { 11731 // FIXME: Look for a way to use RecordDecl for simple structs. 11732 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11733 cast_or_null<CXXRecordDecl>(PrevDecl)); 11734 11735 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11736 StdBadAlloc = cast<CXXRecordDecl>(New); 11737 } else 11738 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11739 cast_or_null<RecordDecl>(PrevDecl)); 11740 } 11741 11742 // C++11 [dcl.type]p3: 11743 // A type-specifier-seq shall not define a class or enumeration [...]. 11744 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11745 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11746 << Context.getTagDeclType(New); 11747 Invalid = true; 11748 } 11749 11750 // Maybe add qualifier info. 11751 if (SS.isNotEmpty()) { 11752 if (SS.isSet()) { 11753 // If this is either a declaration or a definition, check the 11754 // nested-name-specifier against the current context. We don't do this 11755 // for explicit specializations, because they have similar checking 11756 // (with more specific diagnostics) in the call to 11757 // CheckMemberSpecialization, below. 11758 if (!isExplicitSpecialization && 11759 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11760 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11761 Invalid = true; 11762 11763 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11764 if (TemplateParameterLists.size() > 0) { 11765 New->setTemplateParameterListsInfo(Context, 11766 TemplateParameterLists.size(), 11767 TemplateParameterLists.data()); 11768 } 11769 } 11770 else 11771 Invalid = true; 11772 } 11773 11774 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11775 // Add alignment attributes if necessary; these attributes are checked when 11776 // the ASTContext lays out the structure. 11777 // 11778 // It is important for implementing the correct semantics that this 11779 // happen here (in act on tag decl). The #pragma pack stack is 11780 // maintained as a result of parser callbacks which can occur at 11781 // many points during the parsing of a struct declaration (because 11782 // the #pragma tokens are effectively skipped over during the 11783 // parsing of the struct). 11784 if (TUK == TUK_Definition) { 11785 AddAlignmentAttributesForRecord(RD); 11786 AddMsStructLayoutForRecord(RD); 11787 } 11788 } 11789 11790 if (ModulePrivateLoc.isValid()) { 11791 if (isExplicitSpecialization) 11792 Diag(New->getLocation(), diag::err_module_private_specialization) 11793 << 2 11794 << FixItHint::CreateRemoval(ModulePrivateLoc); 11795 // __module_private__ does not apply to local classes. However, we only 11796 // diagnose this as an error when the declaration specifiers are 11797 // freestanding. Here, we just ignore the __module_private__. 11798 else if (!SearchDC->isFunctionOrMethod()) 11799 New->setModulePrivate(); 11800 } 11801 11802 // If this is a specialization of a member class (of a class template), 11803 // check the specialization. 11804 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11805 Invalid = true; 11806 11807 // If we're declaring or defining a tag in function prototype scope in C, 11808 // note that this type can only be used within the function and add it to 11809 // the list of decls to inject into the function definition scope. 11810 if ((Name || Kind == TTK_Enum) && 11811 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11812 if (getLangOpts().CPlusPlus) { 11813 // C++ [dcl.fct]p6: 11814 // Types shall not be defined in return or parameter types. 11815 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11816 Diag(Loc, diag::err_type_defined_in_param_type) 11817 << Name; 11818 Invalid = true; 11819 } 11820 } else { 11821 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11822 } 11823 DeclsInPrototypeScope.push_back(New); 11824 } 11825 11826 if (Invalid) 11827 New->setInvalidDecl(); 11828 11829 if (Attr) 11830 ProcessDeclAttributeList(S, New, Attr); 11831 11832 // Set the lexical context. If the tag has a C++ scope specifier, the 11833 // lexical context will be different from the semantic context. 11834 New->setLexicalDeclContext(CurContext); 11835 11836 // Mark this as a friend decl if applicable. 11837 // In Microsoft mode, a friend declaration also acts as a forward 11838 // declaration so we always pass true to setObjectOfFriendDecl to make 11839 // the tag name visible. 11840 if (TUK == TUK_Friend) 11841 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11842 11843 // Set the access specifier. 11844 if (!Invalid && SearchDC->isRecord()) 11845 SetMemberAccessSpecifier(New, PrevDecl, AS); 11846 11847 if (TUK == TUK_Definition) 11848 New->startDefinition(); 11849 11850 // If this has an identifier, add it to the scope stack. 11851 if (TUK == TUK_Friend) { 11852 // We might be replacing an existing declaration in the lookup tables; 11853 // if so, borrow its access specifier. 11854 if (PrevDecl) 11855 New->setAccess(PrevDecl->getAccess()); 11856 11857 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11858 DC->makeDeclVisibleInContext(New); 11859 if (Name) // can be null along some error paths 11860 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11861 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11862 } else if (Name) { 11863 S = getNonFieldDeclScope(S); 11864 PushOnScopeChains(New, S, !IsForwardReference); 11865 if (IsForwardReference) 11866 SearchDC->makeDeclVisibleInContext(New); 11867 11868 } else { 11869 CurContext->addDecl(New); 11870 } 11871 11872 // If this is the C FILE type, notify the AST context. 11873 if (IdentifierInfo *II = New->getIdentifier()) 11874 if (!New->isInvalidDecl() && 11875 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11876 II->isStr("FILE")) 11877 Context.setFILEDecl(New); 11878 11879 if (PrevDecl) 11880 mergeDeclAttributes(New, PrevDecl); 11881 11882 // If there's a #pragma GCC visibility in scope, set the visibility of this 11883 // record. 11884 AddPushedVisibilityAttribute(New); 11885 11886 OwnedDecl = true; 11887 // In C++, don't return an invalid declaration. We can't recover well from 11888 // the cases where we make the type anonymous. 11889 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11890 } 11891 11892 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11893 AdjustDeclIfTemplate(TagD); 11894 TagDecl *Tag = cast<TagDecl>(TagD); 11895 11896 // Enter the tag context. 11897 PushDeclContext(S, Tag); 11898 11899 ActOnDocumentableDecl(TagD); 11900 11901 // If there's a #pragma GCC visibility in scope, set the visibility of this 11902 // record. 11903 AddPushedVisibilityAttribute(Tag); 11904 } 11905 11906 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11907 assert(isa<ObjCContainerDecl>(IDecl) && 11908 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11909 DeclContext *OCD = cast<DeclContext>(IDecl); 11910 assert(getContainingDC(OCD) == CurContext && 11911 "The next DeclContext should be lexically contained in the current one."); 11912 CurContext = OCD; 11913 return IDecl; 11914 } 11915 11916 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11917 SourceLocation FinalLoc, 11918 bool IsFinalSpelledSealed, 11919 SourceLocation LBraceLoc) { 11920 AdjustDeclIfTemplate(TagD); 11921 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11922 11923 FieldCollector->StartClass(); 11924 11925 if (!Record->getIdentifier()) 11926 return; 11927 11928 if (FinalLoc.isValid()) 11929 Record->addAttr(new (Context) 11930 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11931 11932 // C++ [class]p2: 11933 // [...] The class-name is also inserted into the scope of the 11934 // class itself; this is known as the injected-class-name. For 11935 // purposes of access checking, the injected-class-name is treated 11936 // as if it were a public member name. 11937 CXXRecordDecl *InjectedClassName 11938 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11939 Record->getLocStart(), Record->getLocation(), 11940 Record->getIdentifier(), 11941 /*PrevDecl=*/nullptr, 11942 /*DelayTypeCreation=*/true); 11943 Context.getTypeDeclType(InjectedClassName, Record); 11944 InjectedClassName->setImplicit(); 11945 InjectedClassName->setAccess(AS_public); 11946 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11947 InjectedClassName->setDescribedClassTemplate(Template); 11948 PushOnScopeChains(InjectedClassName, S); 11949 assert(InjectedClassName->isInjectedClassName() && 11950 "Broken injected-class-name"); 11951 } 11952 11953 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11954 SourceLocation RBraceLoc) { 11955 AdjustDeclIfTemplate(TagD); 11956 TagDecl *Tag = cast<TagDecl>(TagD); 11957 Tag->setRBraceLoc(RBraceLoc); 11958 11959 // Make sure we "complete" the definition even it is invalid. 11960 if (Tag->isBeingDefined()) { 11961 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11962 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11963 RD->completeDefinition(); 11964 } 11965 11966 if (isa<CXXRecordDecl>(Tag)) 11967 FieldCollector->FinishClass(); 11968 11969 // Exit this scope of this tag's definition. 11970 PopDeclContext(); 11971 11972 if (getCurLexicalContext()->isObjCContainer() && 11973 Tag->getDeclContext()->isFileContext()) 11974 Tag->setTopLevelDeclInObjCContainer(); 11975 11976 // Notify the consumer that we've defined a tag. 11977 if (!Tag->isInvalidDecl()) 11978 Consumer.HandleTagDeclDefinition(Tag); 11979 } 11980 11981 void Sema::ActOnObjCContainerFinishDefinition() { 11982 // Exit this scope of this interface definition. 11983 PopDeclContext(); 11984 } 11985 11986 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11987 assert(DC == CurContext && "Mismatch of container contexts"); 11988 OriginalLexicalContext = DC; 11989 ActOnObjCContainerFinishDefinition(); 11990 } 11991 11992 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11993 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11994 OriginalLexicalContext = nullptr; 11995 } 11996 11997 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11998 AdjustDeclIfTemplate(TagD); 11999 TagDecl *Tag = cast<TagDecl>(TagD); 12000 Tag->setInvalidDecl(); 12001 12002 // Make sure we "complete" the definition even it is invalid. 12003 if (Tag->isBeingDefined()) { 12004 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12005 RD->completeDefinition(); 12006 } 12007 12008 // We're undoing ActOnTagStartDefinition here, not 12009 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12010 // the FieldCollector. 12011 12012 PopDeclContext(); 12013 } 12014 12015 // Note that FieldName may be null for anonymous bitfields. 12016 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12017 IdentifierInfo *FieldName, 12018 QualType FieldTy, bool IsMsStruct, 12019 Expr *BitWidth, bool *ZeroWidth) { 12020 // Default to true; that shouldn't confuse checks for emptiness 12021 if (ZeroWidth) 12022 *ZeroWidth = true; 12023 12024 // C99 6.7.2.1p4 - verify the field type. 12025 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12026 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12027 // Handle incomplete types with specific error. 12028 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12029 return ExprError(); 12030 if (FieldName) 12031 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12032 << FieldName << FieldTy << BitWidth->getSourceRange(); 12033 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12034 << FieldTy << BitWidth->getSourceRange(); 12035 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12036 UPPC_BitFieldWidth)) 12037 return ExprError(); 12038 12039 // If the bit-width is type- or value-dependent, don't try to check 12040 // it now. 12041 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12042 return BitWidth; 12043 12044 llvm::APSInt Value; 12045 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12046 if (ICE.isInvalid()) 12047 return ICE; 12048 BitWidth = ICE.get(); 12049 12050 if (Value != 0 && ZeroWidth) 12051 *ZeroWidth = false; 12052 12053 // Zero-width bitfield is ok for anonymous field. 12054 if (Value == 0 && FieldName) 12055 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12056 12057 if (Value.isSigned() && Value.isNegative()) { 12058 if (FieldName) 12059 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12060 << FieldName << Value.toString(10); 12061 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12062 << Value.toString(10); 12063 } 12064 12065 if (!FieldTy->isDependentType()) { 12066 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12067 if (Value.getZExtValue() > TypeSize) { 12068 if (!getLangOpts().CPlusPlus || IsMsStruct || 12069 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12070 if (FieldName) 12071 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12072 << FieldName << (unsigned)Value.getZExtValue() 12073 << (unsigned)TypeSize; 12074 12075 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12076 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12077 } 12078 12079 if (FieldName) 12080 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12081 << FieldName << (unsigned)Value.getZExtValue() 12082 << (unsigned)TypeSize; 12083 else 12084 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12085 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12086 } 12087 } 12088 12089 return BitWidth; 12090 } 12091 12092 /// ActOnField - Each field of a C struct/union is passed into this in order 12093 /// to create a FieldDecl object for it. 12094 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12095 Declarator &D, Expr *BitfieldWidth) { 12096 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12097 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12098 /*InitStyle=*/ICIS_NoInit, AS_public); 12099 return Res; 12100 } 12101 12102 /// HandleField - Analyze a field of a C struct or a C++ data member. 12103 /// 12104 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12105 SourceLocation DeclStart, 12106 Declarator &D, Expr *BitWidth, 12107 InClassInitStyle InitStyle, 12108 AccessSpecifier AS) { 12109 IdentifierInfo *II = D.getIdentifier(); 12110 SourceLocation Loc = DeclStart; 12111 if (II) Loc = D.getIdentifierLoc(); 12112 12113 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12114 QualType T = TInfo->getType(); 12115 if (getLangOpts().CPlusPlus) { 12116 CheckExtraCXXDefaultArguments(D); 12117 12118 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12119 UPPC_DataMemberType)) { 12120 D.setInvalidType(); 12121 T = Context.IntTy; 12122 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12123 } 12124 } 12125 12126 // TR 18037 does not allow fields to be declared with address spaces. 12127 if (T.getQualifiers().hasAddressSpace()) { 12128 Diag(Loc, diag::err_field_with_address_space); 12129 D.setInvalidType(); 12130 } 12131 12132 // OpenCL 1.2 spec, s6.9 r: 12133 // The event type cannot be used to declare a structure or union field. 12134 if (LangOpts.OpenCL && T->isEventT()) { 12135 Diag(Loc, diag::err_event_t_struct_field); 12136 D.setInvalidType(); 12137 } 12138 12139 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12140 12141 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12142 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12143 diag::err_invalid_thread) 12144 << DeclSpec::getSpecifierName(TSCS); 12145 12146 // Check to see if this name was declared as a member previously 12147 NamedDecl *PrevDecl = nullptr; 12148 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12149 LookupName(Previous, S); 12150 switch (Previous.getResultKind()) { 12151 case LookupResult::Found: 12152 case LookupResult::FoundUnresolvedValue: 12153 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12154 break; 12155 12156 case LookupResult::FoundOverloaded: 12157 PrevDecl = Previous.getRepresentativeDecl(); 12158 break; 12159 12160 case LookupResult::NotFound: 12161 case LookupResult::NotFoundInCurrentInstantiation: 12162 case LookupResult::Ambiguous: 12163 break; 12164 } 12165 Previous.suppressDiagnostics(); 12166 12167 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12168 // Maybe we will complain about the shadowed template parameter. 12169 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12170 // Just pretend that we didn't see the previous declaration. 12171 PrevDecl = nullptr; 12172 } 12173 12174 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12175 PrevDecl = nullptr; 12176 12177 bool Mutable 12178 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12179 SourceLocation TSSL = D.getLocStart(); 12180 FieldDecl *NewFD 12181 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12182 TSSL, AS, PrevDecl, &D); 12183 12184 if (NewFD->isInvalidDecl()) 12185 Record->setInvalidDecl(); 12186 12187 if (D.getDeclSpec().isModulePrivateSpecified()) 12188 NewFD->setModulePrivate(); 12189 12190 if (NewFD->isInvalidDecl() && PrevDecl) { 12191 // Don't introduce NewFD into scope; there's already something 12192 // with the same name in the same scope. 12193 } else if (II) { 12194 PushOnScopeChains(NewFD, S); 12195 } else 12196 Record->addDecl(NewFD); 12197 12198 return NewFD; 12199 } 12200 12201 /// \brief Build a new FieldDecl and check its well-formedness. 12202 /// 12203 /// This routine builds a new FieldDecl given the fields name, type, 12204 /// record, etc. \p PrevDecl should refer to any previous declaration 12205 /// with the same name and in the same scope as the field to be 12206 /// created. 12207 /// 12208 /// \returns a new FieldDecl. 12209 /// 12210 /// \todo The Declarator argument is a hack. It will be removed once 12211 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12212 TypeSourceInfo *TInfo, 12213 RecordDecl *Record, SourceLocation Loc, 12214 bool Mutable, Expr *BitWidth, 12215 InClassInitStyle InitStyle, 12216 SourceLocation TSSL, 12217 AccessSpecifier AS, NamedDecl *PrevDecl, 12218 Declarator *D) { 12219 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12220 bool InvalidDecl = false; 12221 if (D) InvalidDecl = D->isInvalidType(); 12222 12223 // If we receive a broken type, recover by assuming 'int' and 12224 // marking this declaration as invalid. 12225 if (T.isNull()) { 12226 InvalidDecl = true; 12227 T = Context.IntTy; 12228 } 12229 12230 QualType EltTy = Context.getBaseElementType(T); 12231 if (!EltTy->isDependentType()) { 12232 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12233 // Fields of incomplete type force their record to be invalid. 12234 Record->setInvalidDecl(); 12235 InvalidDecl = true; 12236 } else { 12237 NamedDecl *Def; 12238 EltTy->isIncompleteType(&Def); 12239 if (Def && Def->isInvalidDecl()) { 12240 Record->setInvalidDecl(); 12241 InvalidDecl = true; 12242 } 12243 } 12244 } 12245 12246 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12247 if (BitWidth && getLangOpts().OpenCL) { 12248 Diag(Loc, diag::err_opencl_bitfields); 12249 InvalidDecl = true; 12250 } 12251 12252 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12253 // than a variably modified type. 12254 if (!InvalidDecl && T->isVariablyModifiedType()) { 12255 bool SizeIsNegative; 12256 llvm::APSInt Oversized; 12257 12258 TypeSourceInfo *FixedTInfo = 12259 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12260 SizeIsNegative, 12261 Oversized); 12262 if (FixedTInfo) { 12263 Diag(Loc, diag::warn_illegal_constant_array_size); 12264 TInfo = FixedTInfo; 12265 T = FixedTInfo->getType(); 12266 } else { 12267 if (SizeIsNegative) 12268 Diag(Loc, diag::err_typecheck_negative_array_size); 12269 else if (Oversized.getBoolValue()) 12270 Diag(Loc, diag::err_array_too_large) 12271 << Oversized.toString(10); 12272 else 12273 Diag(Loc, diag::err_typecheck_field_variable_size); 12274 InvalidDecl = true; 12275 } 12276 } 12277 12278 // Fields can not have abstract class types 12279 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12280 diag::err_abstract_type_in_decl, 12281 AbstractFieldType)) 12282 InvalidDecl = true; 12283 12284 bool ZeroWidth = false; 12285 // If this is declared as a bit-field, check the bit-field. 12286 if (!InvalidDecl && BitWidth) { 12287 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12288 &ZeroWidth).get(); 12289 if (!BitWidth) { 12290 InvalidDecl = true; 12291 BitWidth = nullptr; 12292 ZeroWidth = false; 12293 } 12294 } 12295 12296 // Check that 'mutable' is consistent with the type of the declaration. 12297 if (!InvalidDecl && Mutable) { 12298 unsigned DiagID = 0; 12299 if (T->isReferenceType()) 12300 DiagID = diag::err_mutable_reference; 12301 else if (T.isConstQualified()) 12302 DiagID = diag::err_mutable_const; 12303 12304 if (DiagID) { 12305 SourceLocation ErrLoc = Loc; 12306 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12307 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12308 Diag(ErrLoc, DiagID); 12309 Mutable = false; 12310 InvalidDecl = true; 12311 } 12312 } 12313 12314 // C++11 [class.union]p8 (DR1460): 12315 // At most one variant member of a union may have a 12316 // brace-or-equal-initializer. 12317 if (InitStyle != ICIS_NoInit) 12318 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12319 12320 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12321 BitWidth, Mutable, InitStyle); 12322 if (InvalidDecl) 12323 NewFD->setInvalidDecl(); 12324 12325 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12326 Diag(Loc, diag::err_duplicate_member) << II; 12327 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12328 NewFD->setInvalidDecl(); 12329 } 12330 12331 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12332 if (Record->isUnion()) { 12333 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12334 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12335 if (RDecl->getDefinition()) { 12336 // C++ [class.union]p1: An object of a class with a non-trivial 12337 // constructor, a non-trivial copy constructor, a non-trivial 12338 // destructor, or a non-trivial copy assignment operator 12339 // cannot be a member of a union, nor can an array of such 12340 // objects. 12341 if (CheckNontrivialField(NewFD)) 12342 NewFD->setInvalidDecl(); 12343 } 12344 } 12345 12346 // C++ [class.union]p1: If a union contains a member of reference type, 12347 // the program is ill-formed, except when compiling with MSVC extensions 12348 // enabled. 12349 if (EltTy->isReferenceType()) { 12350 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12351 diag::ext_union_member_of_reference_type : 12352 diag::err_union_member_of_reference_type) 12353 << NewFD->getDeclName() << EltTy; 12354 if (!getLangOpts().MicrosoftExt) 12355 NewFD->setInvalidDecl(); 12356 } 12357 } 12358 } 12359 12360 // FIXME: We need to pass in the attributes given an AST 12361 // representation, not a parser representation. 12362 if (D) { 12363 // FIXME: The current scope is almost... but not entirely... correct here. 12364 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12365 12366 if (NewFD->hasAttrs()) 12367 CheckAlignasUnderalignment(NewFD); 12368 } 12369 12370 // In auto-retain/release, infer strong retension for fields of 12371 // retainable type. 12372 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12373 NewFD->setInvalidDecl(); 12374 12375 if (T.isObjCGCWeak()) 12376 Diag(Loc, diag::warn_attribute_weak_on_field); 12377 12378 NewFD->setAccess(AS); 12379 return NewFD; 12380 } 12381 12382 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12383 assert(FD); 12384 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12385 12386 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12387 return false; 12388 12389 QualType EltTy = Context.getBaseElementType(FD->getType()); 12390 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12391 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12392 if (RDecl->getDefinition()) { 12393 // We check for copy constructors before constructors 12394 // because otherwise we'll never get complaints about 12395 // copy constructors. 12396 12397 CXXSpecialMember member = CXXInvalid; 12398 // We're required to check for any non-trivial constructors. Since the 12399 // implicit default constructor is suppressed if there are any 12400 // user-declared constructors, we just need to check that there is a 12401 // trivial default constructor and a trivial copy constructor. (We don't 12402 // worry about move constructors here, since this is a C++98 check.) 12403 if (RDecl->hasNonTrivialCopyConstructor()) 12404 member = CXXCopyConstructor; 12405 else if (!RDecl->hasTrivialDefaultConstructor()) 12406 member = CXXDefaultConstructor; 12407 else if (RDecl->hasNonTrivialCopyAssignment()) 12408 member = CXXCopyAssignment; 12409 else if (RDecl->hasNonTrivialDestructor()) 12410 member = CXXDestructor; 12411 12412 if (member != CXXInvalid) { 12413 if (!getLangOpts().CPlusPlus11 && 12414 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12415 // Objective-C++ ARC: it is an error to have a non-trivial field of 12416 // a union. However, system headers in Objective-C programs 12417 // occasionally have Objective-C lifetime objects within unions, 12418 // and rather than cause the program to fail, we make those 12419 // members unavailable. 12420 SourceLocation Loc = FD->getLocation(); 12421 if (getSourceManager().isInSystemHeader(Loc)) { 12422 if (!FD->hasAttr<UnavailableAttr>()) 12423 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12424 "this system field has retaining ownership", 12425 Loc)); 12426 return false; 12427 } 12428 } 12429 12430 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12431 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12432 diag::err_illegal_union_or_anon_struct_member) 12433 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12434 DiagnoseNontrivial(RDecl, member); 12435 return !getLangOpts().CPlusPlus11; 12436 } 12437 } 12438 } 12439 12440 return false; 12441 } 12442 12443 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12444 /// AST enum value. 12445 static ObjCIvarDecl::AccessControl 12446 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12447 switch (ivarVisibility) { 12448 default: llvm_unreachable("Unknown visitibility kind"); 12449 case tok::objc_private: return ObjCIvarDecl::Private; 12450 case tok::objc_public: return ObjCIvarDecl::Public; 12451 case tok::objc_protected: return ObjCIvarDecl::Protected; 12452 case tok::objc_package: return ObjCIvarDecl::Package; 12453 } 12454 } 12455 12456 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12457 /// in order to create an IvarDecl object for it. 12458 Decl *Sema::ActOnIvar(Scope *S, 12459 SourceLocation DeclStart, 12460 Declarator &D, Expr *BitfieldWidth, 12461 tok::ObjCKeywordKind Visibility) { 12462 12463 IdentifierInfo *II = D.getIdentifier(); 12464 Expr *BitWidth = (Expr*)BitfieldWidth; 12465 SourceLocation Loc = DeclStart; 12466 if (II) Loc = D.getIdentifierLoc(); 12467 12468 // FIXME: Unnamed fields can be handled in various different ways, for 12469 // example, unnamed unions inject all members into the struct namespace! 12470 12471 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12472 QualType T = TInfo->getType(); 12473 12474 if (BitWidth) { 12475 // 6.7.2.1p3, 6.7.2.1p4 12476 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12477 if (!BitWidth) 12478 D.setInvalidType(); 12479 } else { 12480 // Not a bitfield. 12481 12482 // validate II. 12483 12484 } 12485 if (T->isReferenceType()) { 12486 Diag(Loc, diag::err_ivar_reference_type); 12487 D.setInvalidType(); 12488 } 12489 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12490 // than a variably modified type. 12491 else if (T->isVariablyModifiedType()) { 12492 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12493 D.setInvalidType(); 12494 } 12495 12496 // Get the visibility (access control) for this ivar. 12497 ObjCIvarDecl::AccessControl ac = 12498 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12499 : ObjCIvarDecl::None; 12500 // Must set ivar's DeclContext to its enclosing interface. 12501 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12502 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12503 return nullptr; 12504 ObjCContainerDecl *EnclosingContext; 12505 if (ObjCImplementationDecl *IMPDecl = 12506 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12507 if (LangOpts.ObjCRuntime.isFragile()) { 12508 // Case of ivar declared in an implementation. Context is that of its class. 12509 EnclosingContext = IMPDecl->getClassInterface(); 12510 assert(EnclosingContext && "Implementation has no class interface!"); 12511 } 12512 else 12513 EnclosingContext = EnclosingDecl; 12514 } else { 12515 if (ObjCCategoryDecl *CDecl = 12516 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12517 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12518 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12519 return nullptr; 12520 } 12521 } 12522 EnclosingContext = EnclosingDecl; 12523 } 12524 12525 // Construct the decl. 12526 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12527 DeclStart, Loc, II, T, 12528 TInfo, ac, (Expr *)BitfieldWidth); 12529 12530 if (II) { 12531 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12532 ForRedeclaration); 12533 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12534 && !isa<TagDecl>(PrevDecl)) { 12535 Diag(Loc, diag::err_duplicate_member) << II; 12536 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12537 NewID->setInvalidDecl(); 12538 } 12539 } 12540 12541 // Process attributes attached to the ivar. 12542 ProcessDeclAttributes(S, NewID, D); 12543 12544 if (D.isInvalidType()) 12545 NewID->setInvalidDecl(); 12546 12547 // In ARC, infer 'retaining' for ivars of retainable type. 12548 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12549 NewID->setInvalidDecl(); 12550 12551 if (D.getDeclSpec().isModulePrivateSpecified()) 12552 NewID->setModulePrivate(); 12553 12554 if (II) { 12555 // FIXME: When interfaces are DeclContexts, we'll need to add 12556 // these to the interface. 12557 S->AddDecl(NewID); 12558 IdResolver.AddDecl(NewID); 12559 } 12560 12561 if (LangOpts.ObjCRuntime.isNonFragile() && 12562 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12563 Diag(Loc, diag::warn_ivars_in_interface); 12564 12565 return NewID; 12566 } 12567 12568 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12569 /// class and class extensions. For every class \@interface and class 12570 /// extension \@interface, if the last ivar is a bitfield of any type, 12571 /// then add an implicit `char :0` ivar to the end of that interface. 12572 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12573 SmallVectorImpl<Decl *> &AllIvarDecls) { 12574 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12575 return; 12576 12577 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12578 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12579 12580 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12581 return; 12582 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12583 if (!ID) { 12584 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12585 if (!CD->IsClassExtension()) 12586 return; 12587 } 12588 // No need to add this to end of @implementation. 12589 else 12590 return; 12591 } 12592 // All conditions are met. Add a new bitfield to the tail end of ivars. 12593 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12594 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12595 12596 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12597 DeclLoc, DeclLoc, nullptr, 12598 Context.CharTy, 12599 Context.getTrivialTypeSourceInfo(Context.CharTy, 12600 DeclLoc), 12601 ObjCIvarDecl::Private, BW, 12602 true); 12603 AllIvarDecls.push_back(Ivar); 12604 } 12605 12606 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12607 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12608 SourceLocation RBrac, AttributeList *Attr) { 12609 assert(EnclosingDecl && "missing record or interface decl"); 12610 12611 // If this is an Objective-C @implementation or category and we have 12612 // new fields here we should reset the layout of the interface since 12613 // it will now change. 12614 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12615 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12616 switch (DC->getKind()) { 12617 default: break; 12618 case Decl::ObjCCategory: 12619 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12620 break; 12621 case Decl::ObjCImplementation: 12622 Context. 12623 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12624 break; 12625 } 12626 } 12627 12628 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12629 12630 // Start counting up the number of named members; make sure to include 12631 // members of anonymous structs and unions in the total. 12632 unsigned NumNamedMembers = 0; 12633 if (Record) { 12634 for (const auto *I : Record->decls()) { 12635 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12636 if (IFD->getDeclName()) 12637 ++NumNamedMembers; 12638 } 12639 } 12640 12641 // Verify that all the fields are okay. 12642 SmallVector<FieldDecl*, 32> RecFields; 12643 12644 bool ARCErrReported = false; 12645 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12646 i != end; ++i) { 12647 FieldDecl *FD = cast<FieldDecl>(*i); 12648 12649 // Get the type for the field. 12650 const Type *FDTy = FD->getType().getTypePtr(); 12651 12652 if (!FD->isAnonymousStructOrUnion()) { 12653 // Remember all fields written by the user. 12654 RecFields.push_back(FD); 12655 } 12656 12657 // If the field is already invalid for some reason, don't emit more 12658 // diagnostics about it. 12659 if (FD->isInvalidDecl()) { 12660 EnclosingDecl->setInvalidDecl(); 12661 continue; 12662 } 12663 12664 // C99 6.7.2.1p2: 12665 // A structure or union shall not contain a member with 12666 // incomplete or function type (hence, a structure shall not 12667 // contain an instance of itself, but may contain a pointer to 12668 // an instance of itself), except that the last member of a 12669 // structure with more than one named member may have incomplete 12670 // array type; such a structure (and any union containing, 12671 // possibly recursively, a member that is such a structure) 12672 // shall not be a member of a structure or an element of an 12673 // array. 12674 if (FDTy->isFunctionType()) { 12675 // Field declared as a function. 12676 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12677 << FD->getDeclName(); 12678 FD->setInvalidDecl(); 12679 EnclosingDecl->setInvalidDecl(); 12680 continue; 12681 } else if (FDTy->isIncompleteArrayType() && Record && 12682 ((i + 1 == Fields.end() && !Record->isUnion()) || 12683 ((getLangOpts().MicrosoftExt || 12684 getLangOpts().CPlusPlus) && 12685 (i + 1 == Fields.end() || Record->isUnion())))) { 12686 // Flexible array member. 12687 // Microsoft and g++ is more permissive regarding flexible array. 12688 // It will accept flexible array in union and also 12689 // as the sole element of a struct/class. 12690 unsigned DiagID = 0; 12691 if (Record->isUnion()) 12692 DiagID = getLangOpts().MicrosoftExt 12693 ? diag::ext_flexible_array_union_ms 12694 : getLangOpts().CPlusPlus 12695 ? diag::ext_flexible_array_union_gnu 12696 : diag::err_flexible_array_union; 12697 else if (Fields.size() == 1) 12698 DiagID = getLangOpts().MicrosoftExt 12699 ? diag::ext_flexible_array_empty_aggregate_ms 12700 : getLangOpts().CPlusPlus 12701 ? diag::ext_flexible_array_empty_aggregate_gnu 12702 : NumNamedMembers < 1 12703 ? diag::err_flexible_array_empty_aggregate 12704 : 0; 12705 12706 if (DiagID) 12707 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12708 << Record->getTagKind(); 12709 // While the layout of types that contain virtual bases is not specified 12710 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12711 // virtual bases after the derived members. This would make a flexible 12712 // array member declared at the end of an object not adjacent to the end 12713 // of the type. 12714 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12715 if (RD->getNumVBases() != 0) 12716 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12717 << FD->getDeclName() << Record->getTagKind(); 12718 if (!getLangOpts().C99) 12719 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12720 << FD->getDeclName() << Record->getTagKind(); 12721 12722 // If the element type has a non-trivial destructor, we would not 12723 // implicitly destroy the elements, so disallow it for now. 12724 // 12725 // FIXME: GCC allows this. We should probably either implicitly delete 12726 // the destructor of the containing class, or just allow this. 12727 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12728 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12729 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12730 << FD->getDeclName() << FD->getType(); 12731 FD->setInvalidDecl(); 12732 EnclosingDecl->setInvalidDecl(); 12733 continue; 12734 } 12735 // Okay, we have a legal flexible array member at the end of the struct. 12736 Record->setHasFlexibleArrayMember(true); 12737 } else if (!FDTy->isDependentType() && 12738 RequireCompleteType(FD->getLocation(), FD->getType(), 12739 diag::err_field_incomplete)) { 12740 // Incomplete type 12741 FD->setInvalidDecl(); 12742 EnclosingDecl->setInvalidDecl(); 12743 continue; 12744 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12745 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 12746 // A type which contains a flexible array member is considered to be a 12747 // flexible array member. 12748 Record->setHasFlexibleArrayMember(true); 12749 if (!Record->isUnion()) { 12750 // If this is a struct/class and this is not the last element, reject 12751 // it. Note that GCC supports variable sized arrays in the middle of 12752 // structures. 12753 if (i + 1 != Fields.end()) 12754 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12755 << FD->getDeclName() << FD->getType(); 12756 else { 12757 // We support flexible arrays at the end of structs in 12758 // other structs as an extension. 12759 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12760 << FD->getDeclName(); 12761 } 12762 } 12763 } 12764 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12765 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12766 diag::err_abstract_type_in_decl, 12767 AbstractIvarType)) { 12768 // Ivars can not have abstract class types 12769 FD->setInvalidDecl(); 12770 } 12771 if (Record && FDTTy->getDecl()->hasObjectMember()) 12772 Record->setHasObjectMember(true); 12773 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12774 Record->setHasVolatileMember(true); 12775 } else if (FDTy->isObjCObjectType()) { 12776 /// A field cannot be an Objective-c object 12777 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12778 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12779 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12780 FD->setType(T); 12781 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12782 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12783 // It's an error in ARC if a field has lifetime. 12784 // We don't want to report this in a system header, though, 12785 // so we just make the field unavailable. 12786 // FIXME: that's really not sufficient; we need to make the type 12787 // itself invalid to, say, initialize or copy. 12788 QualType T = FD->getType(); 12789 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12790 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12791 SourceLocation loc = FD->getLocation(); 12792 if (getSourceManager().isInSystemHeader(loc)) { 12793 if (!FD->hasAttr<UnavailableAttr>()) { 12794 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12795 "this system field has retaining ownership", 12796 loc)); 12797 } 12798 } else { 12799 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12800 << T->isBlockPointerType() << Record->getTagKind(); 12801 } 12802 ARCErrReported = true; 12803 } 12804 } else if (getLangOpts().ObjC1 && 12805 getLangOpts().getGC() != LangOptions::NonGC && 12806 Record && !Record->hasObjectMember()) { 12807 if (FD->getType()->isObjCObjectPointerType() || 12808 FD->getType().isObjCGCStrong()) 12809 Record->setHasObjectMember(true); 12810 else if (Context.getAsArrayType(FD->getType())) { 12811 QualType BaseType = Context.getBaseElementType(FD->getType()); 12812 if (BaseType->isRecordType() && 12813 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12814 Record->setHasObjectMember(true); 12815 else if (BaseType->isObjCObjectPointerType() || 12816 BaseType.isObjCGCStrong()) 12817 Record->setHasObjectMember(true); 12818 } 12819 } 12820 if (Record && FD->getType().isVolatileQualified()) 12821 Record->setHasVolatileMember(true); 12822 // Keep track of the number of named members. 12823 if (FD->getIdentifier()) 12824 ++NumNamedMembers; 12825 } 12826 12827 // Okay, we successfully defined 'Record'. 12828 if (Record) { 12829 bool Completed = false; 12830 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12831 if (!CXXRecord->isInvalidDecl()) { 12832 // Set access bits correctly on the directly-declared conversions. 12833 for (CXXRecordDecl::conversion_iterator 12834 I = CXXRecord->conversion_begin(), 12835 E = CXXRecord->conversion_end(); I != E; ++I) 12836 I.setAccess((*I)->getAccess()); 12837 12838 if (!CXXRecord->isDependentType()) { 12839 if (CXXRecord->hasUserDeclaredDestructor()) { 12840 // Adjust user-defined destructor exception spec. 12841 if (getLangOpts().CPlusPlus11) 12842 AdjustDestructorExceptionSpec(CXXRecord, 12843 CXXRecord->getDestructor()); 12844 } 12845 12846 // Add any implicitly-declared members to this class. 12847 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12848 12849 // If we have virtual base classes, we may end up finding multiple 12850 // final overriders for a given virtual function. Check for this 12851 // problem now. 12852 if (CXXRecord->getNumVBases()) { 12853 CXXFinalOverriderMap FinalOverriders; 12854 CXXRecord->getFinalOverriders(FinalOverriders); 12855 12856 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12857 MEnd = FinalOverriders.end(); 12858 M != MEnd; ++M) { 12859 for (OverridingMethods::iterator SO = M->second.begin(), 12860 SOEnd = M->second.end(); 12861 SO != SOEnd; ++SO) { 12862 assert(SO->second.size() > 0 && 12863 "Virtual function without overridding functions?"); 12864 if (SO->second.size() == 1) 12865 continue; 12866 12867 // C++ [class.virtual]p2: 12868 // In a derived class, if a virtual member function of a base 12869 // class subobject has more than one final overrider the 12870 // program is ill-formed. 12871 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12872 << (const NamedDecl *)M->first << Record; 12873 Diag(M->first->getLocation(), 12874 diag::note_overridden_virtual_function); 12875 for (OverridingMethods::overriding_iterator 12876 OM = SO->second.begin(), 12877 OMEnd = SO->second.end(); 12878 OM != OMEnd; ++OM) 12879 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12880 << (const NamedDecl *)M->first << OM->Method->getParent(); 12881 12882 Record->setInvalidDecl(); 12883 } 12884 } 12885 CXXRecord->completeDefinition(&FinalOverriders); 12886 Completed = true; 12887 } 12888 } 12889 } 12890 } 12891 12892 if (!Completed) 12893 Record->completeDefinition(); 12894 12895 if (Record->hasAttrs()) { 12896 CheckAlignasUnderalignment(Record); 12897 12898 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12899 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12900 IA->getRange(), IA->getBestCase(), 12901 IA->getSemanticSpelling()); 12902 } 12903 12904 // Check if the structure/union declaration is a type that can have zero 12905 // size in C. For C this is a language extension, for C++ it may cause 12906 // compatibility problems. 12907 bool CheckForZeroSize; 12908 if (!getLangOpts().CPlusPlus) { 12909 CheckForZeroSize = true; 12910 } else { 12911 // For C++ filter out types that cannot be referenced in C code. 12912 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12913 CheckForZeroSize = 12914 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12915 !CXXRecord->isDependentType() && 12916 CXXRecord->isCLike(); 12917 } 12918 if (CheckForZeroSize) { 12919 bool ZeroSize = true; 12920 bool IsEmpty = true; 12921 unsigned NonBitFields = 0; 12922 for (RecordDecl::field_iterator I = Record->field_begin(), 12923 E = Record->field_end(); 12924 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12925 IsEmpty = false; 12926 if (I->isUnnamedBitfield()) { 12927 if (I->getBitWidthValue(Context) > 0) 12928 ZeroSize = false; 12929 } else { 12930 ++NonBitFields; 12931 QualType FieldType = I->getType(); 12932 if (FieldType->isIncompleteType() || 12933 !Context.getTypeSizeInChars(FieldType).isZero()) 12934 ZeroSize = false; 12935 } 12936 } 12937 12938 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12939 // allowed in C++, but warn if its declaration is inside 12940 // extern "C" block. 12941 if (ZeroSize) { 12942 Diag(RecLoc, getLangOpts().CPlusPlus ? 12943 diag::warn_zero_size_struct_union_in_extern_c : 12944 diag::warn_zero_size_struct_union_compat) 12945 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12946 } 12947 12948 // Structs without named members are extension in C (C99 6.7.2.1p7), 12949 // but are accepted by GCC. 12950 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12951 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12952 diag::ext_no_named_members_in_struct_union) 12953 << Record->isUnion(); 12954 } 12955 } 12956 } else { 12957 ObjCIvarDecl **ClsFields = 12958 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12959 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12960 ID->setEndOfDefinitionLoc(RBrac); 12961 // Add ivar's to class's DeclContext. 12962 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12963 ClsFields[i]->setLexicalDeclContext(ID); 12964 ID->addDecl(ClsFields[i]); 12965 } 12966 // Must enforce the rule that ivars in the base classes may not be 12967 // duplicates. 12968 if (ID->getSuperClass()) 12969 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12970 } else if (ObjCImplementationDecl *IMPDecl = 12971 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12972 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12973 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12974 // Ivar declared in @implementation never belongs to the implementation. 12975 // Only it is in implementation's lexical context. 12976 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12977 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12978 IMPDecl->setIvarLBraceLoc(LBrac); 12979 IMPDecl->setIvarRBraceLoc(RBrac); 12980 } else if (ObjCCategoryDecl *CDecl = 12981 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12982 // case of ivars in class extension; all other cases have been 12983 // reported as errors elsewhere. 12984 // FIXME. Class extension does not have a LocEnd field. 12985 // CDecl->setLocEnd(RBrac); 12986 // Add ivar's to class extension's DeclContext. 12987 // Diagnose redeclaration of private ivars. 12988 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12989 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12990 if (IDecl) { 12991 if (const ObjCIvarDecl *ClsIvar = 12992 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12993 Diag(ClsFields[i]->getLocation(), 12994 diag::err_duplicate_ivar_declaration); 12995 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12996 continue; 12997 } 12998 for (const auto *Ext : IDecl->known_extensions()) { 12999 if (const ObjCIvarDecl *ClsExtIvar 13000 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13001 Diag(ClsFields[i]->getLocation(), 13002 diag::err_duplicate_ivar_declaration); 13003 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13004 continue; 13005 } 13006 } 13007 } 13008 ClsFields[i]->setLexicalDeclContext(CDecl); 13009 CDecl->addDecl(ClsFields[i]); 13010 } 13011 CDecl->setIvarLBraceLoc(LBrac); 13012 CDecl->setIvarRBraceLoc(RBrac); 13013 } 13014 } 13015 13016 if (Attr) 13017 ProcessDeclAttributeList(S, Record, Attr); 13018 } 13019 13020 /// \brief Determine whether the given integral value is representable within 13021 /// the given type T. 13022 static bool isRepresentableIntegerValue(ASTContext &Context, 13023 llvm::APSInt &Value, 13024 QualType T) { 13025 assert(T->isIntegralType(Context) && "Integral type required!"); 13026 unsigned BitWidth = Context.getIntWidth(T); 13027 13028 if (Value.isUnsigned() || Value.isNonNegative()) { 13029 if (T->isSignedIntegerOrEnumerationType()) 13030 --BitWidth; 13031 return Value.getActiveBits() <= BitWidth; 13032 } 13033 return Value.getMinSignedBits() <= BitWidth; 13034 } 13035 13036 // \brief Given an integral type, return the next larger integral type 13037 // (or a NULL type of no such type exists). 13038 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13039 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13040 // enum checking below. 13041 assert(T->isIntegralType(Context) && "Integral type required!"); 13042 const unsigned NumTypes = 4; 13043 QualType SignedIntegralTypes[NumTypes] = { 13044 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13045 }; 13046 QualType UnsignedIntegralTypes[NumTypes] = { 13047 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13048 Context.UnsignedLongLongTy 13049 }; 13050 13051 unsigned BitWidth = Context.getTypeSize(T); 13052 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13053 : UnsignedIntegralTypes; 13054 for (unsigned I = 0; I != NumTypes; ++I) 13055 if (Context.getTypeSize(Types[I]) > BitWidth) 13056 return Types[I]; 13057 13058 return QualType(); 13059 } 13060 13061 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13062 EnumConstantDecl *LastEnumConst, 13063 SourceLocation IdLoc, 13064 IdentifierInfo *Id, 13065 Expr *Val) { 13066 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13067 llvm::APSInt EnumVal(IntWidth); 13068 QualType EltTy; 13069 13070 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13071 Val = nullptr; 13072 13073 if (Val) 13074 Val = DefaultLvalueConversion(Val).get(); 13075 13076 if (Val) { 13077 if (Enum->isDependentType() || Val->isTypeDependent()) 13078 EltTy = Context.DependentTy; 13079 else { 13080 SourceLocation ExpLoc; 13081 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13082 !getLangOpts().MSVCCompat) { 13083 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13084 // constant-expression in the enumerator-definition shall be a converted 13085 // constant expression of the underlying type. 13086 EltTy = Enum->getIntegerType(); 13087 ExprResult Converted = 13088 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13089 CCEK_Enumerator); 13090 if (Converted.isInvalid()) 13091 Val = nullptr; 13092 else 13093 Val = Converted.get(); 13094 } else if (!Val->isValueDependent() && 13095 !(Val = VerifyIntegerConstantExpression(Val, 13096 &EnumVal).get())) { 13097 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13098 } else { 13099 if (Enum->isFixed()) { 13100 EltTy = Enum->getIntegerType(); 13101 13102 // In Obj-C and Microsoft mode, require the enumeration value to be 13103 // representable in the underlying type of the enumeration. In C++11, 13104 // we perform a non-narrowing conversion as part of converted constant 13105 // expression checking. 13106 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13107 if (getLangOpts().MSVCCompat) { 13108 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13109 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13110 } else 13111 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13112 } else 13113 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13114 } else if (getLangOpts().CPlusPlus) { 13115 // C++11 [dcl.enum]p5: 13116 // If the underlying type is not fixed, the type of each enumerator 13117 // is the type of its initializing value: 13118 // - If an initializer is specified for an enumerator, the 13119 // initializing value has the same type as the expression. 13120 EltTy = Val->getType(); 13121 } else { 13122 // C99 6.7.2.2p2: 13123 // The expression that defines the value of an enumeration constant 13124 // shall be an integer constant expression that has a value 13125 // representable as an int. 13126 13127 // Complain if the value is not representable in an int. 13128 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13129 Diag(IdLoc, diag::ext_enum_value_not_int) 13130 << EnumVal.toString(10) << Val->getSourceRange() 13131 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13132 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13133 // Force the type of the expression to 'int'. 13134 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13135 } 13136 EltTy = Val->getType(); 13137 } 13138 } 13139 } 13140 } 13141 13142 if (!Val) { 13143 if (Enum->isDependentType()) 13144 EltTy = Context.DependentTy; 13145 else if (!LastEnumConst) { 13146 // C++0x [dcl.enum]p5: 13147 // If the underlying type is not fixed, the type of each enumerator 13148 // is the type of its initializing value: 13149 // - If no initializer is specified for the first enumerator, the 13150 // initializing value has an unspecified integral type. 13151 // 13152 // GCC uses 'int' for its unspecified integral type, as does 13153 // C99 6.7.2.2p3. 13154 if (Enum->isFixed()) { 13155 EltTy = Enum->getIntegerType(); 13156 } 13157 else { 13158 EltTy = Context.IntTy; 13159 } 13160 } else { 13161 // Assign the last value + 1. 13162 EnumVal = LastEnumConst->getInitVal(); 13163 ++EnumVal; 13164 EltTy = LastEnumConst->getType(); 13165 13166 // Check for overflow on increment. 13167 if (EnumVal < LastEnumConst->getInitVal()) { 13168 // C++0x [dcl.enum]p5: 13169 // If the underlying type is not fixed, the type of each enumerator 13170 // is the type of its initializing value: 13171 // 13172 // - Otherwise the type of the initializing value is the same as 13173 // the type of the initializing value of the preceding enumerator 13174 // unless the incremented value is not representable in that type, 13175 // in which case the type is an unspecified integral type 13176 // sufficient to contain the incremented value. If no such type 13177 // exists, the program is ill-formed. 13178 QualType T = getNextLargerIntegralType(Context, EltTy); 13179 if (T.isNull() || Enum->isFixed()) { 13180 // There is no integral type larger enough to represent this 13181 // value. Complain, then allow the value to wrap around. 13182 EnumVal = LastEnumConst->getInitVal(); 13183 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13184 ++EnumVal; 13185 if (Enum->isFixed()) 13186 // When the underlying type is fixed, this is ill-formed. 13187 Diag(IdLoc, diag::err_enumerator_wrapped) 13188 << EnumVal.toString(10) 13189 << EltTy; 13190 else 13191 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13192 << EnumVal.toString(10); 13193 } else { 13194 EltTy = T; 13195 } 13196 13197 // Retrieve the last enumerator's value, extent that type to the 13198 // type that is supposed to be large enough to represent the incremented 13199 // value, then increment. 13200 EnumVal = LastEnumConst->getInitVal(); 13201 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13202 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13203 ++EnumVal; 13204 13205 // If we're not in C++, diagnose the overflow of enumerator values, 13206 // which in C99 means that the enumerator value is not representable in 13207 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13208 // permits enumerator values that are representable in some larger 13209 // integral type. 13210 if (!getLangOpts().CPlusPlus && !T.isNull()) 13211 Diag(IdLoc, diag::warn_enum_value_overflow); 13212 } else if (!getLangOpts().CPlusPlus && 13213 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13214 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13215 Diag(IdLoc, diag::ext_enum_value_not_int) 13216 << EnumVal.toString(10) << 1; 13217 } 13218 } 13219 } 13220 13221 if (!EltTy->isDependentType()) { 13222 // Make the enumerator value match the signedness and size of the 13223 // enumerator's type. 13224 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13225 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13226 } 13227 13228 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13229 Val, EnumVal); 13230 } 13231 13232 13233 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13234 SourceLocation IdLoc, IdentifierInfo *Id, 13235 AttributeList *Attr, 13236 SourceLocation EqualLoc, Expr *Val) { 13237 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13238 EnumConstantDecl *LastEnumConst = 13239 cast_or_null<EnumConstantDecl>(lastEnumConst); 13240 13241 // The scope passed in may not be a decl scope. Zip up the scope tree until 13242 // we find one that is. 13243 S = getNonFieldDeclScope(S); 13244 13245 // Verify that there isn't already something declared with this name in this 13246 // scope. 13247 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13248 ForRedeclaration); 13249 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13250 // Maybe we will complain about the shadowed template parameter. 13251 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13252 // Just pretend that we didn't see the previous declaration. 13253 PrevDecl = nullptr; 13254 } 13255 13256 if (PrevDecl) { 13257 // When in C++, we may get a TagDecl with the same name; in this case the 13258 // enum constant will 'hide' the tag. 13259 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13260 "Received TagDecl when not in C++!"); 13261 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13262 if (isa<EnumConstantDecl>(PrevDecl)) 13263 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13264 else 13265 Diag(IdLoc, diag::err_redefinition) << Id; 13266 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13267 return nullptr; 13268 } 13269 } 13270 13271 // C++ [class.mem]p15: 13272 // If T is the name of a class, then each of the following shall have a name 13273 // different from T: 13274 // - every enumerator of every member of class T that is an unscoped 13275 // enumerated type 13276 if (CXXRecordDecl *Record 13277 = dyn_cast<CXXRecordDecl>( 13278 TheEnumDecl->getDeclContext()->getRedeclContext())) 13279 if (!TheEnumDecl->isScoped() && 13280 Record->getIdentifier() && Record->getIdentifier() == Id) 13281 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13282 13283 EnumConstantDecl *New = 13284 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13285 13286 if (New) { 13287 // Process attributes. 13288 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13289 13290 // Register this decl in the current scope stack. 13291 New->setAccess(TheEnumDecl->getAccess()); 13292 PushOnScopeChains(New, S); 13293 } 13294 13295 ActOnDocumentableDecl(New); 13296 13297 return New; 13298 } 13299 13300 // Returns true when the enum initial expression does not trigger the 13301 // duplicate enum warning. A few common cases are exempted as follows: 13302 // Element2 = Element1 13303 // Element2 = Element1 + 1 13304 // Element2 = Element1 - 1 13305 // Where Element2 and Element1 are from the same enum. 13306 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13307 Expr *InitExpr = ECD->getInitExpr(); 13308 if (!InitExpr) 13309 return true; 13310 InitExpr = InitExpr->IgnoreImpCasts(); 13311 13312 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13313 if (!BO->isAdditiveOp()) 13314 return true; 13315 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13316 if (!IL) 13317 return true; 13318 if (IL->getValue() != 1) 13319 return true; 13320 13321 InitExpr = BO->getLHS(); 13322 } 13323 13324 // This checks if the elements are from the same enum. 13325 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13326 if (!DRE) 13327 return true; 13328 13329 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13330 if (!EnumConstant) 13331 return true; 13332 13333 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13334 Enum) 13335 return true; 13336 13337 return false; 13338 } 13339 13340 struct DupKey { 13341 int64_t val; 13342 bool isTombstoneOrEmptyKey; 13343 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13344 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13345 }; 13346 13347 static DupKey GetDupKey(const llvm::APSInt& Val) { 13348 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13349 false); 13350 } 13351 13352 struct DenseMapInfoDupKey { 13353 static DupKey getEmptyKey() { return DupKey(0, true); } 13354 static DupKey getTombstoneKey() { return DupKey(1, true); } 13355 static unsigned getHashValue(const DupKey Key) { 13356 return (unsigned)(Key.val * 37); 13357 } 13358 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13359 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13360 LHS.val == RHS.val; 13361 } 13362 }; 13363 13364 // Emits a warning when an element is implicitly set a value that 13365 // a previous element has already been set to. 13366 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13367 EnumDecl *Enum, 13368 QualType EnumType) { 13369 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13370 return; 13371 // Avoid anonymous enums 13372 if (!Enum->getIdentifier()) 13373 return; 13374 13375 // Only check for small enums. 13376 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13377 return; 13378 13379 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13380 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13381 13382 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13383 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13384 ValueToVectorMap; 13385 13386 DuplicatesVector DupVector; 13387 ValueToVectorMap EnumMap; 13388 13389 // Populate the EnumMap with all values represented by enum constants without 13390 // an initialier. 13391 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13392 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13393 13394 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13395 // this constant. Skip this enum since it may be ill-formed. 13396 if (!ECD) { 13397 return; 13398 } 13399 13400 if (ECD->getInitExpr()) 13401 continue; 13402 13403 DupKey Key = GetDupKey(ECD->getInitVal()); 13404 DeclOrVector &Entry = EnumMap[Key]; 13405 13406 // First time encountering this value. 13407 if (Entry.isNull()) 13408 Entry = ECD; 13409 } 13410 13411 // Create vectors for any values that has duplicates. 13412 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13413 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13414 if (!ValidDuplicateEnum(ECD, Enum)) 13415 continue; 13416 13417 DupKey Key = GetDupKey(ECD->getInitVal()); 13418 13419 DeclOrVector& Entry = EnumMap[Key]; 13420 if (Entry.isNull()) 13421 continue; 13422 13423 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13424 // Ensure constants are different. 13425 if (D == ECD) 13426 continue; 13427 13428 // Create new vector and push values onto it. 13429 ECDVector *Vec = new ECDVector(); 13430 Vec->push_back(D); 13431 Vec->push_back(ECD); 13432 13433 // Update entry to point to the duplicates vector. 13434 Entry = Vec; 13435 13436 // Store the vector somewhere we can consult later for quick emission of 13437 // diagnostics. 13438 DupVector.push_back(Vec); 13439 continue; 13440 } 13441 13442 ECDVector *Vec = Entry.get<ECDVector*>(); 13443 // Make sure constants are not added more than once. 13444 if (*Vec->begin() == ECD) 13445 continue; 13446 13447 Vec->push_back(ECD); 13448 } 13449 13450 // Emit diagnostics. 13451 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13452 DupVectorEnd = DupVector.end(); 13453 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13454 ECDVector *Vec = *DupVectorIter; 13455 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13456 13457 // Emit warning for one enum constant. 13458 ECDVector::iterator I = Vec->begin(); 13459 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13460 << (*I)->getName() << (*I)->getInitVal().toString(10) 13461 << (*I)->getSourceRange(); 13462 ++I; 13463 13464 // Emit one note for each of the remaining enum constants with 13465 // the same value. 13466 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13467 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13468 << (*I)->getName() << (*I)->getInitVal().toString(10) 13469 << (*I)->getSourceRange(); 13470 delete Vec; 13471 } 13472 } 13473 13474 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13475 SourceLocation RBraceLoc, Decl *EnumDeclX, 13476 ArrayRef<Decl *> Elements, 13477 Scope *S, AttributeList *Attr) { 13478 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13479 QualType EnumType = Context.getTypeDeclType(Enum); 13480 13481 if (Attr) 13482 ProcessDeclAttributeList(S, Enum, Attr); 13483 13484 if (Enum->isDependentType()) { 13485 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13486 EnumConstantDecl *ECD = 13487 cast_or_null<EnumConstantDecl>(Elements[i]); 13488 if (!ECD) continue; 13489 13490 ECD->setType(EnumType); 13491 } 13492 13493 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13494 return; 13495 } 13496 13497 // TODO: If the result value doesn't fit in an int, it must be a long or long 13498 // long value. ISO C does not support this, but GCC does as an extension, 13499 // emit a warning. 13500 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13501 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13502 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13503 13504 // Verify that all the values are okay, compute the size of the values, and 13505 // reverse the list. 13506 unsigned NumNegativeBits = 0; 13507 unsigned NumPositiveBits = 0; 13508 13509 // Keep track of whether all elements have type int. 13510 bool AllElementsInt = true; 13511 13512 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13513 EnumConstantDecl *ECD = 13514 cast_or_null<EnumConstantDecl>(Elements[i]); 13515 if (!ECD) continue; // Already issued a diagnostic. 13516 13517 const llvm::APSInt &InitVal = ECD->getInitVal(); 13518 13519 // Keep track of the size of positive and negative values. 13520 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13521 NumPositiveBits = std::max(NumPositiveBits, 13522 (unsigned)InitVal.getActiveBits()); 13523 else 13524 NumNegativeBits = std::max(NumNegativeBits, 13525 (unsigned)InitVal.getMinSignedBits()); 13526 13527 // Keep track of whether every enum element has type int (very commmon). 13528 if (AllElementsInt) 13529 AllElementsInt = ECD->getType() == Context.IntTy; 13530 } 13531 13532 // Figure out the type that should be used for this enum. 13533 QualType BestType; 13534 unsigned BestWidth; 13535 13536 // C++0x N3000 [conv.prom]p3: 13537 // An rvalue of an unscoped enumeration type whose underlying 13538 // type is not fixed can be converted to an rvalue of the first 13539 // of the following types that can represent all the values of 13540 // the enumeration: int, unsigned int, long int, unsigned long 13541 // int, long long int, or unsigned long long int. 13542 // C99 6.4.4.3p2: 13543 // An identifier declared as an enumeration constant has type int. 13544 // The C99 rule is modified by a gcc extension 13545 QualType BestPromotionType; 13546 13547 bool Packed = Enum->hasAttr<PackedAttr>(); 13548 // -fshort-enums is the equivalent to specifying the packed attribute on all 13549 // enum definitions. 13550 if (LangOpts.ShortEnums) 13551 Packed = true; 13552 13553 if (Enum->isFixed()) { 13554 BestType = Enum->getIntegerType(); 13555 if (BestType->isPromotableIntegerType()) 13556 BestPromotionType = Context.getPromotedIntegerType(BestType); 13557 else 13558 BestPromotionType = BestType; 13559 // We don't need to set BestWidth, because BestType is going to be the type 13560 // of the enumerators, but we do anyway because otherwise some compilers 13561 // warn that it might be used uninitialized. 13562 BestWidth = CharWidth; 13563 } 13564 else if (NumNegativeBits) { 13565 // If there is a negative value, figure out the smallest integer type (of 13566 // int/long/longlong) that fits. 13567 // If it's packed, check also if it fits a char or a short. 13568 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13569 BestType = Context.SignedCharTy; 13570 BestWidth = CharWidth; 13571 } else if (Packed && NumNegativeBits <= ShortWidth && 13572 NumPositiveBits < ShortWidth) { 13573 BestType = Context.ShortTy; 13574 BestWidth = ShortWidth; 13575 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13576 BestType = Context.IntTy; 13577 BestWidth = IntWidth; 13578 } else { 13579 BestWidth = Context.getTargetInfo().getLongWidth(); 13580 13581 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13582 BestType = Context.LongTy; 13583 } else { 13584 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13585 13586 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13587 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13588 BestType = Context.LongLongTy; 13589 } 13590 } 13591 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13592 } else { 13593 // If there is no negative value, figure out the smallest type that fits 13594 // all of the enumerator values. 13595 // If it's packed, check also if it fits a char or a short. 13596 if (Packed && NumPositiveBits <= CharWidth) { 13597 BestType = Context.UnsignedCharTy; 13598 BestPromotionType = Context.IntTy; 13599 BestWidth = CharWidth; 13600 } else if (Packed && NumPositiveBits <= ShortWidth) { 13601 BestType = Context.UnsignedShortTy; 13602 BestPromotionType = Context.IntTy; 13603 BestWidth = ShortWidth; 13604 } else if (NumPositiveBits <= IntWidth) { 13605 BestType = Context.UnsignedIntTy; 13606 BestWidth = IntWidth; 13607 BestPromotionType 13608 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13609 ? Context.UnsignedIntTy : Context.IntTy; 13610 } else if (NumPositiveBits <= 13611 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13612 BestType = Context.UnsignedLongTy; 13613 BestPromotionType 13614 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13615 ? Context.UnsignedLongTy : Context.LongTy; 13616 } else { 13617 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13618 assert(NumPositiveBits <= BestWidth && 13619 "How could an initializer get larger than ULL?"); 13620 BestType = Context.UnsignedLongLongTy; 13621 BestPromotionType 13622 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13623 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13624 } 13625 } 13626 13627 // Loop over all of the enumerator constants, changing their types to match 13628 // the type of the enum if needed. 13629 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13630 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13631 if (!ECD) continue; // Already issued a diagnostic. 13632 13633 // Standard C says the enumerators have int type, but we allow, as an 13634 // extension, the enumerators to be larger than int size. If each 13635 // enumerator value fits in an int, type it as an int, otherwise type it the 13636 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13637 // that X has type 'int', not 'unsigned'. 13638 13639 // Determine whether the value fits into an int. 13640 llvm::APSInt InitVal = ECD->getInitVal(); 13641 13642 // If it fits into an integer type, force it. Otherwise force it to match 13643 // the enum decl type. 13644 QualType NewTy; 13645 unsigned NewWidth; 13646 bool NewSign; 13647 if (!getLangOpts().CPlusPlus && 13648 !Enum->isFixed() && 13649 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13650 NewTy = Context.IntTy; 13651 NewWidth = IntWidth; 13652 NewSign = true; 13653 } else if (ECD->getType() == BestType) { 13654 // Already the right type! 13655 if (getLangOpts().CPlusPlus) 13656 // C++ [dcl.enum]p4: Following the closing brace of an 13657 // enum-specifier, each enumerator has the type of its 13658 // enumeration. 13659 ECD->setType(EnumType); 13660 continue; 13661 } else { 13662 NewTy = BestType; 13663 NewWidth = BestWidth; 13664 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13665 } 13666 13667 // Adjust the APSInt value. 13668 InitVal = InitVal.extOrTrunc(NewWidth); 13669 InitVal.setIsSigned(NewSign); 13670 ECD->setInitVal(InitVal); 13671 13672 // Adjust the Expr initializer and type. 13673 if (ECD->getInitExpr() && 13674 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13675 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13676 CK_IntegralCast, 13677 ECD->getInitExpr(), 13678 /*base paths*/ nullptr, 13679 VK_RValue)); 13680 if (getLangOpts().CPlusPlus) 13681 // C++ [dcl.enum]p4: Following the closing brace of an 13682 // enum-specifier, each enumerator has the type of its 13683 // enumeration. 13684 ECD->setType(EnumType); 13685 else 13686 ECD->setType(NewTy); 13687 } 13688 13689 Enum->completeDefinition(BestType, BestPromotionType, 13690 NumPositiveBits, NumNegativeBits); 13691 13692 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13693 13694 // Now that the enum type is defined, ensure it's not been underaligned. 13695 if (Enum->hasAttrs()) 13696 CheckAlignasUnderalignment(Enum); 13697 } 13698 13699 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13700 SourceLocation StartLoc, 13701 SourceLocation EndLoc) { 13702 StringLiteral *AsmString = cast<StringLiteral>(expr); 13703 13704 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13705 AsmString, StartLoc, 13706 EndLoc); 13707 CurContext->addDecl(New); 13708 return New; 13709 } 13710 13711 static void checkModuleImportContext(Sema &S, Module *M, 13712 SourceLocation ImportLoc, 13713 DeclContext *DC) { 13714 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13715 switch (LSD->getLanguage()) { 13716 case LinkageSpecDecl::lang_c: 13717 if (!M->IsExternC) { 13718 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13719 << M->getFullModuleName(); 13720 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13721 return; 13722 } 13723 break; 13724 case LinkageSpecDecl::lang_cxx: 13725 break; 13726 } 13727 DC = LSD->getParent(); 13728 } 13729 13730 while (isa<LinkageSpecDecl>(DC)) 13731 DC = DC->getParent(); 13732 if (!isa<TranslationUnitDecl>(DC)) { 13733 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13734 << M->getFullModuleName() << DC; 13735 S.Diag(cast<Decl>(DC)->getLocStart(), 13736 diag::note_module_import_not_at_top_level) 13737 << DC; 13738 } 13739 } 13740 13741 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13742 SourceLocation ImportLoc, 13743 ModuleIdPath Path) { 13744 Module *Mod = 13745 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13746 /*IsIncludeDirective=*/false); 13747 if (!Mod) 13748 return true; 13749 13750 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13751 13752 // FIXME: we should support importing a submodule within a different submodule 13753 // of the same top-level module. Until we do, make it an error rather than 13754 // silently ignoring the import. 13755 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13756 Diag(ImportLoc, diag::err_module_self_import) 13757 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13758 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13759 Diag(ImportLoc, diag::err_module_import_in_implementation) 13760 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13761 13762 SmallVector<SourceLocation, 2> IdentifierLocs; 13763 Module *ModCheck = Mod; 13764 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13765 // If we've run out of module parents, just drop the remaining identifiers. 13766 // We need the length to be consistent. 13767 if (!ModCheck) 13768 break; 13769 ModCheck = ModCheck->Parent; 13770 13771 IdentifierLocs.push_back(Path[I].second); 13772 } 13773 13774 ImportDecl *Import = ImportDecl::Create(Context, 13775 Context.getTranslationUnitDecl(), 13776 AtLoc.isValid()? AtLoc : ImportLoc, 13777 Mod, IdentifierLocs); 13778 Context.getTranslationUnitDecl()->addDecl(Import); 13779 return Import; 13780 } 13781 13782 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13783 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13784 13785 // FIXME: Should we synthesize an ImportDecl here? 13786 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13787 /*Complain=*/true); 13788 } 13789 13790 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13791 Module *Mod) { 13792 // Bail if we're not allowed to implicitly import a module here. 13793 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13794 return; 13795 13796 // Create the implicit import declaration. 13797 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13798 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13799 Loc, Mod, Loc); 13800 TU->addDecl(ImportD); 13801 Consumer.HandleImplicitImportDecl(ImportD); 13802 13803 // Make the module visible. 13804 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13805 /*Complain=*/false); 13806 } 13807 13808 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13809 IdentifierInfo* AliasName, 13810 SourceLocation PragmaLoc, 13811 SourceLocation NameLoc, 13812 SourceLocation AliasNameLoc) { 13813 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13814 LookupOrdinaryName); 13815 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13816 AliasName->getName(), 0); 13817 13818 if (PrevDecl) 13819 PrevDecl->addAttr(Attr); 13820 else 13821 (void)ExtnameUndeclaredIdentifiers.insert( 13822 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13823 } 13824 13825 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13826 SourceLocation PragmaLoc, 13827 SourceLocation NameLoc) { 13828 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13829 13830 if (PrevDecl) { 13831 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13832 } else { 13833 (void)WeakUndeclaredIdentifiers.insert( 13834 std::pair<IdentifierInfo*,WeakInfo> 13835 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 13836 } 13837 } 13838 13839 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13840 IdentifierInfo* AliasName, 13841 SourceLocation PragmaLoc, 13842 SourceLocation NameLoc, 13843 SourceLocation AliasNameLoc) { 13844 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13845 LookupOrdinaryName); 13846 WeakInfo W = WeakInfo(Name, NameLoc); 13847 13848 if (PrevDecl) { 13849 if (!PrevDecl->hasAttr<AliasAttr>()) 13850 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13851 DeclApplyPragmaWeak(TUScope, ND, W); 13852 } else { 13853 (void)WeakUndeclaredIdentifiers.insert( 13854 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13855 } 13856 } 13857 13858 Decl *Sema::getObjCDeclContext() const { 13859 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13860 } 13861 13862 AvailabilityResult Sema::getCurContextAvailability() const { 13863 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13864 // If we are within an Objective-C method, we should consult 13865 // both the availability of the method as well as the 13866 // enclosing class. If the class is (say) deprecated, 13867 // the entire method is considered deprecated from the 13868 // purpose of checking if the current context is deprecated. 13869 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13870 AvailabilityResult R = MD->getAvailability(); 13871 if (R != AR_Available) 13872 return R; 13873 D = MD->getClassInterface(); 13874 } 13875 // If we are within an Objective-c @implementation, it 13876 // gets the same availability context as the @interface. 13877 else if (const ObjCImplementationDecl *ID = 13878 dyn_cast<ObjCImplementationDecl>(D)) { 13879 D = ID->getClassInterface(); 13880 } 13881 // Recover from user error. 13882 return D ? D->getAvailability() : AR_Available; 13883 } 13884