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 const Type *Ty = SS->getScopeRep()->getAsType(); 502 503 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 504 for (const auto &Base : RD->bases()) 505 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 506 return true; 507 return S->isFunctionPrototypeScope(); 508 } 509 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 510 } 511 512 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 513 SourceLocation IILoc, 514 Scope *S, 515 CXXScopeSpec *SS, 516 ParsedType &SuggestedType, 517 bool AllowClassTemplates) { 518 // We don't have anything to suggest (yet). 519 SuggestedType = ParsedType(); 520 521 // There may have been a typo in the name of the type. Look up typo 522 // results, in case we have something that we can suggest. 523 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 524 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 525 LookupOrdinaryName, S, SS, 526 Validator, CTK_ErrorRecovery)) { 527 if (Corrected.isKeyword()) { 528 // We corrected to a keyword. 529 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 530 II = Corrected.getCorrectionAsIdentifierInfo(); 531 } else { 532 // We found a similarly-named type or interface; suggest that. 533 if (!SS || !SS->isSet()) { 534 diagnoseTypo(Corrected, 535 PDiag(diag::err_unknown_typename_suggest) << II); 536 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 537 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 538 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 539 II->getName().equals(CorrectedStr); 540 diagnoseTypo(Corrected, 541 PDiag(diag::err_unknown_nested_typename_suggest) 542 << II << DC << DroppedSpecifier << SS->getRange()); 543 } else { 544 llvm_unreachable("could not have corrected a typo here"); 545 } 546 547 CXXScopeSpec tmpSS; 548 if (Corrected.getCorrectionSpecifier()) 549 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 550 SourceRange(IILoc)); 551 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 552 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 553 false, ParsedType(), 554 /*IsCtorOrDtorName=*/false, 555 /*NonTrivialTypeSourceInfo=*/true); 556 } 557 return; 558 } 559 560 if (getLangOpts().CPlusPlus) { 561 // See if II is a class template that the user forgot to pass arguments to. 562 UnqualifiedId Name; 563 Name.setIdentifier(II, IILoc); 564 CXXScopeSpec EmptySS; 565 TemplateTy TemplateResult; 566 bool MemberOfUnknownSpecialization; 567 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 568 Name, ParsedType(), true, TemplateResult, 569 MemberOfUnknownSpecialization) == TNK_Type_template) { 570 TemplateName TplName = TemplateResult.get(); 571 Diag(IILoc, diag::err_template_missing_args) << TplName; 572 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 573 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 574 << TplDecl->getTemplateParameters()->getSourceRange(); 575 } 576 return; 577 } 578 } 579 580 // FIXME: Should we move the logic that tries to recover from a missing tag 581 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 582 583 if (!SS || (!SS->isSet() && !SS->isInvalid())) 584 Diag(IILoc, diag::err_unknown_typename) << II; 585 else if (DeclContext *DC = computeDeclContext(*SS, false)) 586 Diag(IILoc, diag::err_typename_nested_not_found) 587 << II << DC << SS->getRange(); 588 else if (isDependentScopeSpecifier(*SS)) { 589 unsigned DiagID = diag::err_typename_missing; 590 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 591 DiagID = diag::ext_typename_missing; 592 593 Diag(SS->getRange().getBegin(), DiagID) 594 << SS->getScopeRep() << II->getName() 595 << SourceRange(SS->getRange().getBegin(), IILoc) 596 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 597 SuggestedType = ActOnTypenameType(S, SourceLocation(), 598 *SS, *II, IILoc).get(); 599 } else { 600 assert(SS && SS->isInvalid() && 601 "Invalid scope specifier has already been diagnosed"); 602 } 603 } 604 605 /// \brief Determine whether the given result set contains either a type name 606 /// or 607 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 608 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 609 NextToken.is(tok::less); 610 611 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 612 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 613 return true; 614 615 if (CheckTemplate && isa<TemplateDecl>(*I)) 616 return true; 617 } 618 619 return false; 620 } 621 622 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 623 Scope *S, CXXScopeSpec &SS, 624 IdentifierInfo *&Name, 625 SourceLocation NameLoc) { 626 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 627 SemaRef.LookupParsedName(R, S, &SS); 628 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 629 StringRef FixItTagName; 630 switch (Tag->getTagKind()) { 631 case TTK_Class: 632 FixItTagName = "class "; 633 break; 634 635 case TTK_Enum: 636 FixItTagName = "enum "; 637 break; 638 639 case TTK_Struct: 640 FixItTagName = "struct "; 641 break; 642 643 case TTK_Interface: 644 FixItTagName = "__interface "; 645 break; 646 647 case TTK_Union: 648 FixItTagName = "union "; 649 break; 650 } 651 652 StringRef TagName = FixItTagName.drop_back(); 653 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 654 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 655 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 656 657 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 658 I != IEnd; ++I) 659 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 660 << Name << TagName; 661 662 // Replace lookup results with just the tag decl. 663 Result.clear(Sema::LookupTagName); 664 SemaRef.LookupParsedName(Result, S, &SS); 665 return true; 666 } 667 668 return false; 669 } 670 671 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 672 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 673 QualType T, SourceLocation NameLoc) { 674 ASTContext &Context = S.Context; 675 676 TypeLocBuilder Builder; 677 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 678 679 T = S.getElaboratedType(ETK_None, SS, T); 680 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 681 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 682 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 683 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 684 } 685 686 Sema::NameClassification Sema::ClassifyName(Scope *S, 687 CXXScopeSpec &SS, 688 IdentifierInfo *&Name, 689 SourceLocation NameLoc, 690 const Token &NextToken, 691 bool IsAddressOfOperand, 692 CorrectionCandidateCallback *CCC) { 693 DeclarationNameInfo NameInfo(Name, NameLoc); 694 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 695 696 if (NextToken.is(tok::coloncolon)) { 697 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 698 QualType(), false, SS, nullptr, false); 699 } 700 701 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 702 LookupParsedName(Result, S, &SS, !CurMethod); 703 704 // For unqualified lookup in a class template in MSVC mode, look into 705 // dependent base classes where the primary class template is known. 706 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 707 if (ParsedType TypeInBase = 708 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 709 return TypeInBase; 710 } 711 712 // Perform lookup for Objective-C instance variables (including automatically 713 // synthesized instance variables), if we're in an Objective-C method. 714 // FIXME: This lookup really, really needs to be folded in to the normal 715 // unqualified lookup mechanism. 716 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 717 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 718 if (E.get() || E.isInvalid()) 719 return E; 720 } 721 722 bool SecondTry = false; 723 bool IsFilteredTemplateName = false; 724 725 Corrected: 726 switch (Result.getResultKind()) { 727 case LookupResult::NotFound: 728 // If an unqualified-id is followed by a '(', then we have a function 729 // call. 730 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 731 // In C++, this is an ADL-only call. 732 // FIXME: Reference? 733 if (getLangOpts().CPlusPlus) 734 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 735 736 // C90 6.3.2.2: 737 // If the expression that precedes the parenthesized argument list in a 738 // function call consists solely of an identifier, and if no 739 // declaration is visible for this identifier, the identifier is 740 // implicitly declared exactly as if, in the innermost block containing 741 // the function call, the declaration 742 // 743 // extern int identifier (); 744 // 745 // appeared. 746 // 747 // We also allow this in C99 as an extension. 748 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 749 Result.addDecl(D); 750 Result.resolveKind(); 751 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 752 } 753 } 754 755 // In C, we first see whether there is a tag type by the same name, in 756 // which case it's likely that the user just forget to write "enum", 757 // "struct", or "union". 758 if (!getLangOpts().CPlusPlus && !SecondTry && 759 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 760 break; 761 } 762 763 // Perform typo correction to determine if there is another name that is 764 // close to this name. 765 if (!SecondTry && CCC) { 766 SecondTry = true; 767 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 768 Result.getLookupKind(), S, 769 &SS, *CCC, 770 CTK_ErrorRecovery)) { 771 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 772 unsigned QualifiedDiag = diag::err_no_member_suggest; 773 774 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 775 NamedDecl *UnderlyingFirstDecl 776 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 777 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 778 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 779 UnqualifiedDiag = diag::err_no_template_suggest; 780 QualifiedDiag = diag::err_no_member_template_suggest; 781 } else if (UnderlyingFirstDecl && 782 (isa<TypeDecl>(UnderlyingFirstDecl) || 783 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 784 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 785 UnqualifiedDiag = diag::err_unknown_typename_suggest; 786 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 787 } 788 789 if (SS.isEmpty()) { 790 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 791 } else {// FIXME: is this even reachable? Test it. 792 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 793 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 794 Name->getName().equals(CorrectedStr); 795 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 796 << Name << computeDeclContext(SS, false) 797 << DroppedSpecifier << SS.getRange()); 798 } 799 800 // Update the name, so that the caller has the new name. 801 Name = Corrected.getCorrectionAsIdentifierInfo(); 802 803 // Typo correction corrected to a keyword. 804 if (Corrected.isKeyword()) 805 return Name; 806 807 // Also update the LookupResult... 808 // FIXME: This should probably go away at some point 809 Result.clear(); 810 Result.setLookupName(Corrected.getCorrection()); 811 if (FirstDecl) 812 Result.addDecl(FirstDecl); 813 814 // If we found an Objective-C instance variable, let 815 // LookupInObjCMethod build the appropriate expression to 816 // reference the ivar. 817 // FIXME: This is a gross hack. 818 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 819 Result.clear(); 820 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 821 return E; 822 } 823 824 goto Corrected; 825 } 826 } 827 828 // We failed to correct; just fall through and let the parser deal with it. 829 Result.suppressDiagnostics(); 830 return NameClassification::Unknown(); 831 832 case LookupResult::NotFoundInCurrentInstantiation: { 833 // We performed name lookup into the current instantiation, and there were 834 // dependent bases, so we treat this result the same way as any other 835 // dependent nested-name-specifier. 836 837 // C++ [temp.res]p2: 838 // A name used in a template declaration or definition and that is 839 // dependent on a template-parameter is assumed not to name a type 840 // unless the applicable name lookup finds a type name or the name is 841 // qualified by the keyword typename. 842 // 843 // FIXME: If the next token is '<', we might want to ask the parser to 844 // perform some heroics to see if we actually have a 845 // template-argument-list, which would indicate a missing 'template' 846 // keyword here. 847 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 848 NameInfo, IsAddressOfOperand, 849 /*TemplateArgs=*/nullptr); 850 } 851 852 case LookupResult::Found: 853 case LookupResult::FoundOverloaded: 854 case LookupResult::FoundUnresolvedValue: 855 break; 856 857 case LookupResult::Ambiguous: 858 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 859 hasAnyAcceptableTemplateNames(Result)) { 860 // C++ [temp.local]p3: 861 // A lookup that finds an injected-class-name (10.2) can result in an 862 // ambiguity in certain cases (for example, if it is found in more than 863 // one base class). If all of the injected-class-names that are found 864 // refer to specializations of the same class template, and if the name 865 // is followed by a template-argument-list, the reference refers to the 866 // class template itself and not a specialization thereof, and is not 867 // ambiguous. 868 // 869 // This filtering can make an ambiguous result into an unambiguous one, 870 // so try again after filtering out template names. 871 FilterAcceptableTemplateNames(Result); 872 if (!Result.isAmbiguous()) { 873 IsFilteredTemplateName = true; 874 break; 875 } 876 } 877 878 // Diagnose the ambiguity and return an error. 879 return NameClassification::Error(); 880 } 881 882 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 883 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 884 // C++ [temp.names]p3: 885 // After name lookup (3.4) finds that a name is a template-name or that 886 // an operator-function-id or a literal- operator-id refers to a set of 887 // overloaded functions any member of which is a function template if 888 // this is followed by a <, the < is always taken as the delimiter of a 889 // template-argument-list and never as the less-than operator. 890 if (!IsFilteredTemplateName) 891 FilterAcceptableTemplateNames(Result); 892 893 if (!Result.empty()) { 894 bool IsFunctionTemplate; 895 bool IsVarTemplate; 896 TemplateName Template; 897 if (Result.end() - Result.begin() > 1) { 898 IsFunctionTemplate = true; 899 Template = Context.getOverloadedTemplateName(Result.begin(), 900 Result.end()); 901 } else { 902 TemplateDecl *TD 903 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 904 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 905 IsVarTemplate = isa<VarTemplateDecl>(TD); 906 907 if (SS.isSet() && !SS.isInvalid()) 908 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 909 /*TemplateKeyword=*/false, 910 TD); 911 else 912 Template = TemplateName(TD); 913 } 914 915 if (IsFunctionTemplate) { 916 // Function templates always go through overload resolution, at which 917 // point we'll perform the various checks (e.g., accessibility) we need 918 // to based on which function we selected. 919 Result.suppressDiagnostics(); 920 921 return NameClassification::FunctionTemplate(Template); 922 } 923 924 return IsVarTemplate ? NameClassification::VarTemplate(Template) 925 : NameClassification::TypeTemplate(Template); 926 } 927 } 928 929 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 930 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 931 DiagnoseUseOfDecl(Type, NameLoc); 932 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 933 QualType T = Context.getTypeDeclType(Type); 934 if (SS.isNotEmpty()) 935 return buildNestedType(*this, SS, T, NameLoc); 936 return ParsedType::make(T); 937 } 938 939 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 940 if (!Class) { 941 // FIXME: It's unfortunate that we don't have a Type node for handling this. 942 if (ObjCCompatibleAliasDecl *Alias = 943 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 944 Class = Alias->getClassInterface(); 945 } 946 947 if (Class) { 948 DiagnoseUseOfDecl(Class, NameLoc); 949 950 if (NextToken.is(tok::period)) { 951 // Interface. <something> is parsed as a property reference expression. 952 // Just return "unknown" as a fall-through for now. 953 Result.suppressDiagnostics(); 954 return NameClassification::Unknown(); 955 } 956 957 QualType T = Context.getObjCInterfaceType(Class); 958 return ParsedType::make(T); 959 } 960 961 // We can have a type template here if we're classifying a template argument. 962 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 963 return NameClassification::TypeTemplate( 964 TemplateName(cast<TemplateDecl>(FirstDecl))); 965 966 // Check for a tag type hidden by a non-type decl in a few cases where it 967 // seems likely a type is wanted instead of the non-type that was found. 968 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 969 if ((NextToken.is(tok::identifier) || 970 (NextIsOp && 971 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 972 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 973 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 974 DiagnoseUseOfDecl(Type, NameLoc); 975 QualType T = Context.getTypeDeclType(Type); 976 if (SS.isNotEmpty()) 977 return buildNestedType(*this, SS, T, NameLoc); 978 return ParsedType::make(T); 979 } 980 981 if (FirstDecl->isCXXClassMember()) 982 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 983 nullptr); 984 985 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 986 return BuildDeclarationNameExpr(SS, Result, ADL); 987 } 988 989 // Determines the context to return to after temporarily entering a 990 // context. This depends in an unnecessarily complicated way on the 991 // exact ordering of callbacks from the parser. 992 DeclContext *Sema::getContainingDC(DeclContext *DC) { 993 994 // Functions defined inline within classes aren't parsed until we've 995 // finished parsing the top-level class, so the top-level class is 996 // the context we'll need to return to. 997 // A Lambda call operator whose parent is a class must not be treated 998 // as an inline member function. A Lambda can be used legally 999 // either as an in-class member initializer or a default argument. These 1000 // are parsed once the class has been marked complete and so the containing 1001 // context would be the nested class (when the lambda is defined in one); 1002 // If the class is not complete, then the lambda is being used in an 1003 // ill-formed fashion (such as to specify the width of a bit-field, or 1004 // in an array-bound) - in which case we still want to return the 1005 // lexically containing DC (which could be a nested class). 1006 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1007 DC = DC->getLexicalParent(); 1008 1009 // A function not defined within a class will always return to its 1010 // lexical context. 1011 if (!isa<CXXRecordDecl>(DC)) 1012 return DC; 1013 1014 // A C++ inline method/friend is parsed *after* the topmost class 1015 // it was declared in is fully parsed ("complete"); the topmost 1016 // class is the context we need to return to. 1017 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1018 DC = RD; 1019 1020 // Return the declaration context of the topmost class the inline method is 1021 // declared in. 1022 return DC; 1023 } 1024 1025 return DC->getLexicalParent(); 1026 } 1027 1028 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1029 assert(getContainingDC(DC) == CurContext && 1030 "The next DeclContext should be lexically contained in the current one."); 1031 CurContext = DC; 1032 S->setEntity(DC); 1033 } 1034 1035 void Sema::PopDeclContext() { 1036 assert(CurContext && "DeclContext imbalance!"); 1037 1038 CurContext = getContainingDC(CurContext); 1039 assert(CurContext && "Popped translation unit!"); 1040 } 1041 1042 /// EnterDeclaratorContext - Used when we must lookup names in the context 1043 /// of a declarator's nested name specifier. 1044 /// 1045 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1046 // C++0x [basic.lookup.unqual]p13: 1047 // A name used in the definition of a static data member of class 1048 // X (after the qualified-id of the static member) is looked up as 1049 // if the name was used in a member function of X. 1050 // C++0x [basic.lookup.unqual]p14: 1051 // If a variable member of a namespace is defined outside of the 1052 // scope of its namespace then any name used in the definition of 1053 // the variable member (after the declarator-id) is looked up as 1054 // if the definition of the variable member occurred in its 1055 // namespace. 1056 // Both of these imply that we should push a scope whose context 1057 // is the semantic context of the declaration. We can't use 1058 // PushDeclContext here because that context is not necessarily 1059 // lexically contained in the current context. Fortunately, 1060 // the containing scope should have the appropriate information. 1061 1062 assert(!S->getEntity() && "scope already has entity"); 1063 1064 #ifndef NDEBUG 1065 Scope *Ancestor = S->getParent(); 1066 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1067 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1068 #endif 1069 1070 CurContext = DC; 1071 S->setEntity(DC); 1072 } 1073 1074 void Sema::ExitDeclaratorContext(Scope *S) { 1075 assert(S->getEntity() == CurContext && "Context imbalance!"); 1076 1077 // Switch back to the lexical context. The safety of this is 1078 // enforced by an assert in EnterDeclaratorContext. 1079 Scope *Ancestor = S->getParent(); 1080 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1081 CurContext = Ancestor->getEntity(); 1082 1083 // We don't need to do anything with the scope, which is going to 1084 // disappear. 1085 } 1086 1087 1088 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1089 // We assume that the caller has already called 1090 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1091 FunctionDecl *FD = D->getAsFunction(); 1092 if (!FD) 1093 return; 1094 1095 // Same implementation as PushDeclContext, but enters the context 1096 // from the lexical parent, rather than the top-level class. 1097 assert(CurContext == FD->getLexicalParent() && 1098 "The next DeclContext should be lexically contained in the current one."); 1099 CurContext = FD; 1100 S->setEntity(CurContext); 1101 1102 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1103 ParmVarDecl *Param = FD->getParamDecl(P); 1104 // If the parameter has an identifier, then add it to the scope 1105 if (Param->getIdentifier()) { 1106 S->AddDecl(Param); 1107 IdResolver.AddDecl(Param); 1108 } 1109 } 1110 } 1111 1112 1113 void Sema::ActOnExitFunctionContext() { 1114 // Same implementation as PopDeclContext, but returns to the lexical parent, 1115 // rather than the top-level class. 1116 assert(CurContext && "DeclContext imbalance!"); 1117 CurContext = CurContext->getLexicalParent(); 1118 assert(CurContext && "Popped translation unit!"); 1119 } 1120 1121 1122 /// \brief Determine whether we allow overloading of the function 1123 /// PrevDecl with another declaration. 1124 /// 1125 /// This routine determines whether overloading is possible, not 1126 /// whether some new function is actually an overload. It will return 1127 /// true in C++ (where we can always provide overloads) or, as an 1128 /// extension, in C when the previous function is already an 1129 /// overloaded function declaration or has the "overloadable" 1130 /// attribute. 1131 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1132 ASTContext &Context) { 1133 if (Context.getLangOpts().CPlusPlus) 1134 return true; 1135 1136 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1137 return true; 1138 1139 return (Previous.getResultKind() == LookupResult::Found 1140 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1141 } 1142 1143 /// Add this decl to the scope shadowed decl chains. 1144 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1145 // Move up the scope chain until we find the nearest enclosing 1146 // non-transparent context. The declaration will be introduced into this 1147 // scope. 1148 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1149 S = S->getParent(); 1150 1151 // Add scoped declarations into their context, so that they can be 1152 // found later. Declarations without a context won't be inserted 1153 // into any context. 1154 if (AddToContext) 1155 CurContext->addDecl(D); 1156 1157 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1158 // are function-local declarations. 1159 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1160 !D->getDeclContext()->getRedeclContext()->Equals( 1161 D->getLexicalDeclContext()->getRedeclContext()) && 1162 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1163 return; 1164 1165 // Template instantiations should also not be pushed into scope. 1166 if (isa<FunctionDecl>(D) && 1167 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1168 return; 1169 1170 // If this replaces anything in the current scope, 1171 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1172 IEnd = IdResolver.end(); 1173 for (; I != IEnd; ++I) { 1174 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1175 S->RemoveDecl(*I); 1176 IdResolver.RemoveDecl(*I); 1177 1178 // Should only need to replace one decl. 1179 break; 1180 } 1181 } 1182 1183 S->AddDecl(D); 1184 1185 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1186 // Implicitly-generated labels may end up getting generated in an order that 1187 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1188 // the label at the appropriate place in the identifier chain. 1189 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1190 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1191 if (IDC == CurContext) { 1192 if (!S->isDeclScope(*I)) 1193 continue; 1194 } else if (IDC->Encloses(CurContext)) 1195 break; 1196 } 1197 1198 IdResolver.InsertDeclAfter(I, D); 1199 } else { 1200 IdResolver.AddDecl(D); 1201 } 1202 } 1203 1204 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1205 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1206 TUScope->AddDecl(D); 1207 } 1208 1209 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1210 bool AllowInlineNamespace) { 1211 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1212 } 1213 1214 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1215 DeclContext *TargetDC = DC->getPrimaryContext(); 1216 do { 1217 if (DeclContext *ScopeDC = S->getEntity()) 1218 if (ScopeDC->getPrimaryContext() == TargetDC) 1219 return S; 1220 } while ((S = S->getParent())); 1221 1222 return nullptr; 1223 } 1224 1225 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1226 DeclContext*, 1227 ASTContext&); 1228 1229 /// Filters out lookup results that don't fall within the given scope 1230 /// as determined by isDeclInScope. 1231 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1232 bool ConsiderLinkage, 1233 bool AllowInlineNamespace) { 1234 LookupResult::Filter F = R.makeFilter(); 1235 while (F.hasNext()) { 1236 NamedDecl *D = F.next(); 1237 1238 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1239 continue; 1240 1241 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1242 continue; 1243 1244 F.erase(); 1245 } 1246 1247 F.done(); 1248 } 1249 1250 static bool isUsingDecl(NamedDecl *D) { 1251 return isa<UsingShadowDecl>(D) || 1252 isa<UnresolvedUsingTypenameDecl>(D) || 1253 isa<UnresolvedUsingValueDecl>(D); 1254 } 1255 1256 /// Removes using shadow declarations from the lookup results. 1257 static void RemoveUsingDecls(LookupResult &R) { 1258 LookupResult::Filter F = R.makeFilter(); 1259 while (F.hasNext()) 1260 if (isUsingDecl(F.next())) 1261 F.erase(); 1262 1263 F.done(); 1264 } 1265 1266 /// \brief Check for this common pattern: 1267 /// @code 1268 /// class S { 1269 /// S(const S&); // DO NOT IMPLEMENT 1270 /// void operator=(const S&); // DO NOT IMPLEMENT 1271 /// }; 1272 /// @endcode 1273 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1274 // FIXME: Should check for private access too but access is set after we get 1275 // the decl here. 1276 if (D->doesThisDeclarationHaveABody()) 1277 return false; 1278 1279 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1280 return CD->isCopyConstructor(); 1281 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1282 return Method->isCopyAssignmentOperator(); 1283 return false; 1284 } 1285 1286 // We need this to handle 1287 // 1288 // typedef struct { 1289 // void *foo() { return 0; } 1290 // } A; 1291 // 1292 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1293 // for example. If 'A', foo will have external linkage. If we have '*A', 1294 // foo will have no linkage. Since we can't know until we get to the end 1295 // of the typedef, this function finds out if D might have non-external linkage. 1296 // Callers should verify at the end of the TU if it D has external linkage or 1297 // not. 1298 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1299 const DeclContext *DC = D->getDeclContext(); 1300 while (!DC->isTranslationUnit()) { 1301 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1302 if (!RD->hasNameForLinkage()) 1303 return true; 1304 } 1305 DC = DC->getParent(); 1306 } 1307 1308 return !D->isExternallyVisible(); 1309 } 1310 1311 // FIXME: This needs to be refactored; some other isInMainFile users want 1312 // these semantics. 1313 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1314 if (S.TUKind != TU_Complete) 1315 return false; 1316 return S.SourceMgr.isInMainFile(Loc); 1317 } 1318 1319 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1320 assert(D); 1321 1322 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1323 return false; 1324 1325 // Ignore all entities declared within templates, and out-of-line definitions 1326 // of members of class templates. 1327 if (D->getDeclContext()->isDependentContext() || 1328 D->getLexicalDeclContext()->isDependentContext()) 1329 return false; 1330 1331 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1332 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1333 return false; 1334 1335 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1336 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1337 return false; 1338 } else { 1339 // 'static inline' functions are defined in headers; don't warn. 1340 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1341 return false; 1342 } 1343 1344 if (FD->doesThisDeclarationHaveABody() && 1345 Context.DeclMustBeEmitted(FD)) 1346 return false; 1347 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1348 // Constants and utility variables are defined in headers with internal 1349 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1350 // like "inline".) 1351 if (!isMainFileLoc(*this, VD->getLocation())) 1352 return false; 1353 1354 if (Context.DeclMustBeEmitted(VD)) 1355 return false; 1356 1357 if (VD->isStaticDataMember() && 1358 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1359 return false; 1360 } else { 1361 return false; 1362 } 1363 1364 // Only warn for unused decls internal to the translation unit. 1365 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1366 // for inline functions defined in the main source file, for instance. 1367 return mightHaveNonExternalLinkage(D); 1368 } 1369 1370 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1371 if (!D) 1372 return; 1373 1374 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1375 const FunctionDecl *First = FD->getFirstDecl(); 1376 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1377 return; // First should already be in the vector. 1378 } 1379 1380 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1381 const VarDecl *First = VD->getFirstDecl(); 1382 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1383 return; // First should already be in the vector. 1384 } 1385 1386 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1387 UnusedFileScopedDecls.push_back(D); 1388 } 1389 1390 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1391 if (D->isInvalidDecl()) 1392 return false; 1393 1394 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1395 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1396 return false; 1397 1398 if (isa<LabelDecl>(D)) 1399 return true; 1400 1401 // Except for labels, we only care about unused decls that are local to 1402 // functions. 1403 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1404 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1405 // For dependent types, the diagnostic is deferred. 1406 WithinFunction = 1407 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1408 if (!WithinFunction) 1409 return false; 1410 1411 if (isa<TypedefNameDecl>(D)) 1412 return true; 1413 1414 // White-list anything that isn't a local variable. 1415 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1416 return false; 1417 1418 // Types of valid local variables should be complete, so this should succeed. 1419 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1420 1421 // White-list anything with an __attribute__((unused)) type. 1422 QualType Ty = VD->getType(); 1423 1424 // Only look at the outermost level of typedef. 1425 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1426 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1427 return false; 1428 } 1429 1430 // If we failed to complete the type for some reason, or if the type is 1431 // dependent, don't diagnose the variable. 1432 if (Ty->isIncompleteType() || Ty->isDependentType()) 1433 return false; 1434 1435 if (const TagType *TT = Ty->getAs<TagType>()) { 1436 const TagDecl *Tag = TT->getDecl(); 1437 if (Tag->hasAttr<UnusedAttr>()) 1438 return false; 1439 1440 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1441 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1442 return false; 1443 1444 if (const Expr *Init = VD->getInit()) { 1445 if (const ExprWithCleanups *Cleanups = 1446 dyn_cast<ExprWithCleanups>(Init)) 1447 Init = Cleanups->getSubExpr(); 1448 const CXXConstructExpr *Construct = 1449 dyn_cast<CXXConstructExpr>(Init); 1450 if (Construct && !Construct->isElidable()) { 1451 CXXConstructorDecl *CD = Construct->getConstructor(); 1452 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1453 return false; 1454 } 1455 } 1456 } 1457 } 1458 1459 // TODO: __attribute__((unused)) templates? 1460 } 1461 1462 return true; 1463 } 1464 1465 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1466 FixItHint &Hint) { 1467 if (isa<LabelDecl>(D)) { 1468 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1469 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1470 if (AfterColon.isInvalid()) 1471 return; 1472 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1473 getCharRange(D->getLocStart(), AfterColon)); 1474 } 1475 return; 1476 } 1477 1478 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1479 if (D->getTypeForDecl()->isDependentType()) 1480 return; 1481 1482 for (auto *TmpD : D->decls()) { 1483 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1484 DiagnoseUnusedDecl(T); 1485 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1486 DiagnoseUnusedNestedTypedefs(R); 1487 } 1488 } 1489 1490 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1491 /// unless they are marked attr(unused). 1492 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1493 if (!ShouldDiagnoseUnusedDecl(D)) 1494 return; 1495 1496 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1497 // typedefs can be referenced later on, so the diagnostics are emitted 1498 // at end-of-translation-unit. 1499 UnusedLocalTypedefNameCandidates.insert(TD); 1500 return; 1501 } 1502 1503 FixItHint Hint; 1504 GenerateFixForUnusedDecl(D, Context, Hint); 1505 1506 unsigned DiagID; 1507 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1508 DiagID = diag::warn_unused_exception_param; 1509 else if (isa<LabelDecl>(D)) 1510 DiagID = diag::warn_unused_label; 1511 else 1512 DiagID = diag::warn_unused_variable; 1513 1514 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1515 } 1516 1517 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1518 // Verify that we have no forward references left. If so, there was a goto 1519 // or address of a label taken, but no definition of it. Label fwd 1520 // definitions are indicated with a null substmt which is also not a resolved 1521 // MS inline assembly label name. 1522 bool Diagnose = false; 1523 if (L->isMSAsmLabel()) 1524 Diagnose = !L->isResolvedMSAsmLabel(); 1525 else 1526 Diagnose = L->getStmt() == nullptr; 1527 if (Diagnose) 1528 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1529 } 1530 1531 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1532 S->mergeNRVOIntoParent(); 1533 1534 if (S->decl_empty()) return; 1535 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1536 "Scope shouldn't contain decls!"); 1537 1538 for (auto *TmpD : S->decls()) { 1539 assert(TmpD && "This decl didn't get pushed??"); 1540 1541 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1542 NamedDecl *D = cast<NamedDecl>(TmpD); 1543 1544 if (!D->getDeclName()) continue; 1545 1546 // Diagnose unused variables in this scope. 1547 if (!S->hasUnrecoverableErrorOccurred()) { 1548 DiagnoseUnusedDecl(D); 1549 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1550 DiagnoseUnusedNestedTypedefs(RD); 1551 } 1552 1553 // If this was a forward reference to a label, verify it was defined. 1554 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1555 CheckPoppedLabel(LD, *this); 1556 1557 // Remove this name from our lexical scope. 1558 IdResolver.RemoveDecl(D); 1559 } 1560 } 1561 1562 /// \brief Look for an Objective-C class in the translation unit. 1563 /// 1564 /// \param Id The name of the Objective-C class we're looking for. If 1565 /// typo-correction fixes this name, the Id will be updated 1566 /// to the fixed name. 1567 /// 1568 /// \param IdLoc The location of the name in the translation unit. 1569 /// 1570 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1571 /// if there is no class with the given name. 1572 /// 1573 /// \returns The declaration of the named Objective-C class, or NULL if the 1574 /// class could not be found. 1575 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1576 SourceLocation IdLoc, 1577 bool DoTypoCorrection) { 1578 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1579 // creation from this context. 1580 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1581 1582 if (!IDecl && DoTypoCorrection) { 1583 // Perform typo correction at the given location, but only if we 1584 // find an Objective-C class name. 1585 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1586 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1587 LookupOrdinaryName, TUScope, nullptr, 1588 Validator, CTK_ErrorRecovery)) { 1589 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1590 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1591 Id = IDecl->getIdentifier(); 1592 } 1593 } 1594 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1595 // This routine must always return a class definition, if any. 1596 if (Def && Def->getDefinition()) 1597 Def = Def->getDefinition(); 1598 return Def; 1599 } 1600 1601 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1602 /// from S, where a non-field would be declared. This routine copes 1603 /// with the difference between C and C++ scoping rules in structs and 1604 /// unions. For example, the following code is well-formed in C but 1605 /// ill-formed in C++: 1606 /// @code 1607 /// struct S6 { 1608 /// enum { BAR } e; 1609 /// }; 1610 /// 1611 /// void test_S6() { 1612 /// struct S6 a; 1613 /// a.e = BAR; 1614 /// } 1615 /// @endcode 1616 /// For the declaration of BAR, this routine will return a different 1617 /// scope. The scope S will be the scope of the unnamed enumeration 1618 /// within S6. In C++, this routine will return the scope associated 1619 /// with S6, because the enumeration's scope is a transparent 1620 /// context but structures can contain non-field names. In C, this 1621 /// routine will return the translation unit scope, since the 1622 /// enumeration's scope is a transparent context and structures cannot 1623 /// contain non-field names. 1624 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1625 while (((S->getFlags() & Scope::DeclScope) == 0) || 1626 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1627 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1628 S = S->getParent(); 1629 return S; 1630 } 1631 1632 /// \brief Looks up the declaration of "struct objc_super" and 1633 /// saves it for later use in building builtin declaration of 1634 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1635 /// pre-existing declaration exists no action takes place. 1636 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1637 IdentifierInfo *II) { 1638 if (!II->isStr("objc_msgSendSuper")) 1639 return; 1640 ASTContext &Context = ThisSema.Context; 1641 1642 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1643 SourceLocation(), Sema::LookupTagName); 1644 ThisSema.LookupName(Result, S); 1645 if (Result.getResultKind() == LookupResult::Found) 1646 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1647 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1648 } 1649 1650 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1651 switch (Error) { 1652 case ASTContext::GE_None: 1653 return ""; 1654 case ASTContext::GE_Missing_stdio: 1655 return "stdio.h"; 1656 case ASTContext::GE_Missing_setjmp: 1657 return "setjmp.h"; 1658 case ASTContext::GE_Missing_ucontext: 1659 return "ucontext.h"; 1660 } 1661 llvm_unreachable("unhandled error kind"); 1662 } 1663 1664 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1665 /// file scope. lazily create a decl for it. ForRedeclaration is true 1666 /// if we're creating this built-in in anticipation of redeclaring the 1667 /// built-in. 1668 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1669 Scope *S, bool ForRedeclaration, 1670 SourceLocation Loc) { 1671 LookupPredefedObjCSuperType(*this, S, II); 1672 1673 ASTContext::GetBuiltinTypeError Error; 1674 QualType R = Context.GetBuiltinType(ID, Error); 1675 if (Error) { 1676 if (ForRedeclaration) 1677 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1678 << getHeaderName(Error) 1679 << Context.BuiltinInfo.GetName(ID); 1680 return nullptr; 1681 } 1682 1683 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1684 Diag(Loc, diag::ext_implicit_lib_function_decl) 1685 << Context.BuiltinInfo.GetName(ID) 1686 << R; 1687 if (Context.BuiltinInfo.getHeaderName(ID) && 1688 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1689 Diag(Loc, diag::note_include_header_or_declare) 1690 << Context.BuiltinInfo.getHeaderName(ID) 1691 << Context.BuiltinInfo.GetName(ID); 1692 } 1693 1694 DeclContext *Parent = Context.getTranslationUnitDecl(); 1695 if (getLangOpts().CPlusPlus) { 1696 LinkageSpecDecl *CLinkageDecl = 1697 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1698 LinkageSpecDecl::lang_c, false); 1699 CLinkageDecl->setImplicit(); 1700 Parent->addDecl(CLinkageDecl); 1701 Parent = CLinkageDecl; 1702 } 1703 1704 FunctionDecl *New = FunctionDecl::Create(Context, 1705 Parent, 1706 Loc, Loc, II, R, /*TInfo=*/nullptr, 1707 SC_Extern, 1708 false, 1709 /*hasPrototype=*/true); 1710 New->setImplicit(); 1711 1712 // Create Decl objects for each parameter, adding them to the 1713 // FunctionDecl. 1714 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1715 SmallVector<ParmVarDecl*, 16> Params; 1716 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1717 ParmVarDecl *parm = 1718 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1719 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1720 SC_None, nullptr); 1721 parm->setScopeInfo(0, i); 1722 Params.push_back(parm); 1723 } 1724 New->setParams(Params); 1725 } 1726 1727 AddKnownFunctionAttributes(New); 1728 RegisterLocallyScopedExternCDecl(New, S); 1729 1730 // TUScope is the translation-unit scope to insert this function into. 1731 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1732 // relate Scopes to DeclContexts, and probably eliminate CurContext 1733 // entirely, but we're not there yet. 1734 DeclContext *SavedContext = CurContext; 1735 CurContext = Parent; 1736 PushOnScopeChains(New, TUScope); 1737 CurContext = SavedContext; 1738 return New; 1739 } 1740 1741 /// \brief Filter out any previous declarations that the given declaration 1742 /// should not consider because they are not permitted to conflict, e.g., 1743 /// because they come from hidden sub-modules and do not refer to the same 1744 /// entity. 1745 static void filterNonConflictingPreviousDecls(ASTContext &context, 1746 NamedDecl *decl, 1747 LookupResult &previous){ 1748 // This is only interesting when modules are enabled. 1749 if (!context.getLangOpts().Modules) 1750 return; 1751 1752 // Empty sets are uninteresting. 1753 if (previous.empty()) 1754 return; 1755 1756 LookupResult::Filter filter = previous.makeFilter(); 1757 while (filter.hasNext()) { 1758 NamedDecl *old = filter.next(); 1759 1760 // Non-hidden declarations are never ignored. 1761 if (!old->isHidden()) 1762 continue; 1763 1764 if (!old->isExternallyVisible()) 1765 filter.erase(); 1766 } 1767 1768 filter.done(); 1769 } 1770 1771 /// Typedef declarations don't have linkage, but they still denote the same 1772 /// entity if their types are the same. 1773 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1774 /// isSameEntity. 1775 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context, 1776 TypedefNameDecl *Decl, 1777 LookupResult &Previous) { 1778 // This is only interesting when modules are enabled. 1779 if (!Context.getLangOpts().Modules) 1780 return; 1781 1782 // Empty sets are uninteresting. 1783 if (Previous.empty()) 1784 return; 1785 1786 LookupResult::Filter Filter = Previous.makeFilter(); 1787 while (Filter.hasNext()) { 1788 NamedDecl *Old = Filter.next(); 1789 1790 // Non-hidden declarations are never ignored. 1791 if (!Old->isHidden()) 1792 continue; 1793 1794 // Declarations of the same entity are not ignored, even if they have 1795 // different linkages. 1796 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) 1797 if (Context.hasSameType(OldTD->getUnderlyingType(), 1798 Decl->getUnderlyingType())) 1799 continue; 1800 1801 if (!Old->isExternallyVisible()) 1802 Filter.erase(); 1803 } 1804 1805 Filter.done(); 1806 } 1807 1808 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1809 QualType OldType; 1810 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1811 OldType = OldTypedef->getUnderlyingType(); 1812 else 1813 OldType = Context.getTypeDeclType(Old); 1814 QualType NewType = New->getUnderlyingType(); 1815 1816 if (NewType->isVariablyModifiedType()) { 1817 // Must not redefine a typedef with a variably-modified type. 1818 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1819 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1820 << Kind << NewType; 1821 if (Old->getLocation().isValid()) 1822 Diag(Old->getLocation(), diag::note_previous_definition); 1823 New->setInvalidDecl(); 1824 return true; 1825 } 1826 1827 if (OldType != NewType && 1828 !OldType->isDependentType() && 1829 !NewType->isDependentType() && 1830 !Context.hasSameType(OldType, NewType)) { 1831 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1832 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1833 << Kind << NewType << OldType; 1834 if (Old->getLocation().isValid()) 1835 Diag(Old->getLocation(), diag::note_previous_definition); 1836 New->setInvalidDecl(); 1837 return true; 1838 } 1839 return false; 1840 } 1841 1842 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1843 /// same name and scope as a previous declaration 'Old'. Figure out 1844 /// how to resolve this situation, merging decls or emitting 1845 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1846 /// 1847 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1848 // If the new decl is known invalid already, don't bother doing any 1849 // merging checks. 1850 if (New->isInvalidDecl()) return; 1851 1852 // Allow multiple definitions for ObjC built-in typedefs. 1853 // FIXME: Verify the underlying types are equivalent! 1854 if (getLangOpts().ObjC1) { 1855 const IdentifierInfo *TypeID = New->getIdentifier(); 1856 switch (TypeID->getLength()) { 1857 default: break; 1858 case 2: 1859 { 1860 if (!TypeID->isStr("id")) 1861 break; 1862 QualType T = New->getUnderlyingType(); 1863 if (!T->isPointerType()) 1864 break; 1865 if (!T->isVoidPointerType()) { 1866 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1867 if (!PT->isStructureType()) 1868 break; 1869 } 1870 Context.setObjCIdRedefinitionType(T); 1871 // Install the built-in type for 'id', ignoring the current definition. 1872 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1873 return; 1874 } 1875 case 5: 1876 if (!TypeID->isStr("Class")) 1877 break; 1878 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1879 // Install the built-in type for 'Class', ignoring the current definition. 1880 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1881 return; 1882 case 3: 1883 if (!TypeID->isStr("SEL")) 1884 break; 1885 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1886 // Install the built-in type for 'SEL', ignoring the current definition. 1887 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1888 return; 1889 } 1890 // Fall through - the typedef name was not a builtin type. 1891 } 1892 1893 // Verify the old decl was also a type. 1894 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1895 if (!Old) { 1896 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1897 << New->getDeclName(); 1898 1899 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1900 if (OldD->getLocation().isValid()) 1901 Diag(OldD->getLocation(), diag::note_previous_definition); 1902 1903 return New->setInvalidDecl(); 1904 } 1905 1906 // If the old declaration is invalid, just give up here. 1907 if (Old->isInvalidDecl()) 1908 return New->setInvalidDecl(); 1909 1910 // If the typedef types are not identical, reject them in all languages and 1911 // with any extensions enabled. 1912 if (isIncompatibleTypedef(Old, New)) 1913 return; 1914 1915 // The types match. Link up the redeclaration chain and merge attributes if 1916 // the old declaration was a typedef. 1917 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1918 New->setPreviousDecl(Typedef); 1919 mergeDeclAttributes(New, Old); 1920 } 1921 1922 if (getLangOpts().MicrosoftExt) 1923 return; 1924 1925 if (getLangOpts().CPlusPlus) { 1926 // C++ [dcl.typedef]p2: 1927 // In a given non-class scope, a typedef specifier can be used to 1928 // redefine the name of any type declared in that scope to refer 1929 // to the type to which it already refers. 1930 if (!isa<CXXRecordDecl>(CurContext)) 1931 return; 1932 1933 // C++0x [dcl.typedef]p4: 1934 // In a given class scope, a typedef specifier can be used to redefine 1935 // any class-name declared in that scope that is not also a typedef-name 1936 // to refer to the type to which it already refers. 1937 // 1938 // This wording came in via DR424, which was a correction to the 1939 // wording in DR56, which accidentally banned code like: 1940 // 1941 // struct S { 1942 // typedef struct A { } A; 1943 // }; 1944 // 1945 // in the C++03 standard. We implement the C++0x semantics, which 1946 // allow the above but disallow 1947 // 1948 // struct S { 1949 // typedef int I; 1950 // typedef int I; 1951 // }; 1952 // 1953 // since that was the intent of DR56. 1954 if (!isa<TypedefNameDecl>(Old)) 1955 return; 1956 1957 Diag(New->getLocation(), diag::err_redefinition) 1958 << New->getDeclName(); 1959 Diag(Old->getLocation(), diag::note_previous_definition); 1960 return New->setInvalidDecl(); 1961 } 1962 1963 // Modules always permit redefinition of typedefs, as does C11. 1964 if (getLangOpts().Modules || getLangOpts().C11) 1965 return; 1966 1967 // If we have a redefinition of a typedef in C, emit a warning. This warning 1968 // is normally mapped to an error, but can be controlled with 1969 // -Wtypedef-redefinition. If either the original or the redefinition is 1970 // in a system header, don't emit this for compatibility with GCC. 1971 if (getDiagnostics().getSuppressSystemWarnings() && 1972 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1973 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1974 return; 1975 1976 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 1977 << New->getDeclName(); 1978 Diag(Old->getLocation(), diag::note_previous_definition); 1979 return; 1980 } 1981 1982 /// DeclhasAttr - returns true if decl Declaration already has the target 1983 /// attribute. 1984 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1985 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1986 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1987 for (const auto *i : D->attrs()) 1988 if (i->getKind() == A->getKind()) { 1989 if (Ann) { 1990 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1991 return true; 1992 continue; 1993 } 1994 // FIXME: Don't hardcode this check 1995 if (OA && isa<OwnershipAttr>(i)) 1996 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1997 return true; 1998 } 1999 2000 return false; 2001 } 2002 2003 static bool isAttributeTargetADefinition(Decl *D) { 2004 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2005 return VD->isThisDeclarationADefinition(); 2006 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2007 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2008 return true; 2009 } 2010 2011 /// Merge alignment attributes from \p Old to \p New, taking into account the 2012 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2013 /// 2014 /// \return \c true if any attributes were added to \p New. 2015 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2016 // Look for alignas attributes on Old, and pick out whichever attribute 2017 // specifies the strictest alignment requirement. 2018 AlignedAttr *OldAlignasAttr = nullptr; 2019 AlignedAttr *OldStrictestAlignAttr = nullptr; 2020 unsigned OldAlign = 0; 2021 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2022 // FIXME: We have no way of representing inherited dependent alignments 2023 // in a case like: 2024 // template<int A, int B> struct alignas(A) X; 2025 // template<int A, int B> struct alignas(B) X {}; 2026 // For now, we just ignore any alignas attributes which are not on the 2027 // definition in such a case. 2028 if (I->isAlignmentDependent()) 2029 return false; 2030 2031 if (I->isAlignas()) 2032 OldAlignasAttr = I; 2033 2034 unsigned Align = I->getAlignment(S.Context); 2035 if (Align > OldAlign) { 2036 OldAlign = Align; 2037 OldStrictestAlignAttr = I; 2038 } 2039 } 2040 2041 // Look for alignas attributes on New. 2042 AlignedAttr *NewAlignasAttr = nullptr; 2043 unsigned NewAlign = 0; 2044 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2045 if (I->isAlignmentDependent()) 2046 return false; 2047 2048 if (I->isAlignas()) 2049 NewAlignasAttr = I; 2050 2051 unsigned Align = I->getAlignment(S.Context); 2052 if (Align > NewAlign) 2053 NewAlign = Align; 2054 } 2055 2056 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2057 // Both declarations have 'alignas' attributes. We require them to match. 2058 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2059 // fall short. (If two declarations both have alignas, they must both match 2060 // every definition, and so must match each other if there is a definition.) 2061 2062 // If either declaration only contains 'alignas(0)' specifiers, then it 2063 // specifies the natural alignment for the type. 2064 if (OldAlign == 0 || NewAlign == 0) { 2065 QualType Ty; 2066 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2067 Ty = VD->getType(); 2068 else 2069 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2070 2071 if (OldAlign == 0) 2072 OldAlign = S.Context.getTypeAlign(Ty); 2073 if (NewAlign == 0) 2074 NewAlign = S.Context.getTypeAlign(Ty); 2075 } 2076 2077 if (OldAlign != NewAlign) { 2078 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2079 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2080 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2081 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2082 } 2083 } 2084 2085 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2086 // C++11 [dcl.align]p6: 2087 // if any declaration of an entity has an alignment-specifier, 2088 // every defining declaration of that entity shall specify an 2089 // equivalent alignment. 2090 // C11 6.7.5/7: 2091 // If the definition of an object does not have an alignment 2092 // specifier, any other declaration of that object shall also 2093 // have no alignment specifier. 2094 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2095 << OldAlignasAttr; 2096 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2097 << OldAlignasAttr; 2098 } 2099 2100 bool AnyAdded = false; 2101 2102 // Ensure we have an attribute representing the strictest alignment. 2103 if (OldAlign > NewAlign) { 2104 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2105 Clone->setInherited(true); 2106 New->addAttr(Clone); 2107 AnyAdded = true; 2108 } 2109 2110 // Ensure we have an alignas attribute if the old declaration had one. 2111 if (OldAlignasAttr && !NewAlignasAttr && 2112 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2113 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2114 Clone->setInherited(true); 2115 New->addAttr(Clone); 2116 AnyAdded = true; 2117 } 2118 2119 return AnyAdded; 2120 } 2121 2122 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2123 const InheritableAttr *Attr, bool Override) { 2124 InheritableAttr *NewAttr = nullptr; 2125 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2126 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2127 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2128 AA->getIntroduced(), AA->getDeprecated(), 2129 AA->getObsoleted(), AA->getUnavailable(), 2130 AA->getMessage(), Override, 2131 AttrSpellingListIndex); 2132 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2133 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2134 AttrSpellingListIndex); 2135 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2136 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2137 AttrSpellingListIndex); 2138 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2139 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2140 AttrSpellingListIndex); 2141 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2142 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2143 AttrSpellingListIndex); 2144 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2145 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2146 FA->getFormatIdx(), FA->getFirstArg(), 2147 AttrSpellingListIndex); 2148 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2149 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2150 AttrSpellingListIndex); 2151 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2152 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2153 AttrSpellingListIndex, 2154 IA->getSemanticSpelling()); 2155 else if (isa<AlignedAttr>(Attr)) 2156 // AlignedAttrs are handled separately, because we need to handle all 2157 // such attributes on a declaration at the same time. 2158 NewAttr = nullptr; 2159 else if (isa<DeprecatedAttr>(Attr) && Override) 2160 NewAttr = nullptr; 2161 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2162 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2163 2164 if (NewAttr) { 2165 NewAttr->setInherited(true); 2166 D->addAttr(NewAttr); 2167 return true; 2168 } 2169 2170 return false; 2171 } 2172 2173 static const Decl *getDefinition(const Decl *D) { 2174 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2175 return TD->getDefinition(); 2176 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2177 const VarDecl *Def = VD->getDefinition(); 2178 if (Def) 2179 return Def; 2180 return VD->getActingDefinition(); 2181 } 2182 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2183 const FunctionDecl* Def; 2184 if (FD->isDefined(Def)) 2185 return Def; 2186 } 2187 return nullptr; 2188 } 2189 2190 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2191 for (const auto *Attribute : D->attrs()) 2192 if (Attribute->getKind() == Kind) 2193 return true; 2194 return false; 2195 } 2196 2197 /// checkNewAttributesAfterDef - If we already have a definition, check that 2198 /// there are no new attributes in this declaration. 2199 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2200 if (!New->hasAttrs()) 2201 return; 2202 2203 const Decl *Def = getDefinition(Old); 2204 if (!Def || Def == New) 2205 return; 2206 2207 AttrVec &NewAttributes = New->getAttrs(); 2208 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2209 const Attr *NewAttribute = NewAttributes[I]; 2210 2211 if (isa<AliasAttr>(NewAttribute)) { 2212 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2213 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2214 else { 2215 VarDecl *VD = cast<VarDecl>(New); 2216 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2217 VarDecl::TentativeDefinition 2218 ? diag::err_alias_after_tentative 2219 : diag::err_redefinition; 2220 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2221 S.Diag(Def->getLocation(), diag::note_previous_definition); 2222 VD->setInvalidDecl(); 2223 } 2224 ++I; 2225 continue; 2226 } 2227 2228 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2229 // Tentative definitions are only interesting for the alias check above. 2230 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2231 ++I; 2232 continue; 2233 } 2234 } 2235 2236 if (hasAttribute(Def, NewAttribute->getKind())) { 2237 ++I; 2238 continue; // regular attr merging will take care of validating this. 2239 } 2240 2241 if (isa<C11NoReturnAttr>(NewAttribute)) { 2242 // C's _Noreturn is allowed to be added to a function after it is defined. 2243 ++I; 2244 continue; 2245 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2246 if (AA->isAlignas()) { 2247 // C++11 [dcl.align]p6: 2248 // if any declaration of an entity has an alignment-specifier, 2249 // every defining declaration of that entity shall specify an 2250 // equivalent alignment. 2251 // C11 6.7.5/7: 2252 // If the definition of an object does not have an alignment 2253 // specifier, any other declaration of that object shall also 2254 // have no alignment specifier. 2255 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2256 << AA; 2257 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2258 << AA; 2259 NewAttributes.erase(NewAttributes.begin() + I); 2260 --E; 2261 continue; 2262 } 2263 } 2264 2265 S.Diag(NewAttribute->getLocation(), 2266 diag::warn_attribute_precede_definition); 2267 S.Diag(Def->getLocation(), diag::note_previous_definition); 2268 NewAttributes.erase(NewAttributes.begin() + I); 2269 --E; 2270 } 2271 } 2272 2273 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2274 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2275 AvailabilityMergeKind AMK) { 2276 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2277 UsedAttr *NewAttr = OldAttr->clone(Context); 2278 NewAttr->setInherited(true); 2279 New->addAttr(NewAttr); 2280 } 2281 2282 if (!Old->hasAttrs() && !New->hasAttrs()) 2283 return; 2284 2285 // attributes declared post-definition are currently ignored 2286 checkNewAttributesAfterDef(*this, New, Old); 2287 2288 if (!Old->hasAttrs()) 2289 return; 2290 2291 bool foundAny = New->hasAttrs(); 2292 2293 // Ensure that any moving of objects within the allocated map is done before 2294 // we process them. 2295 if (!foundAny) New->setAttrs(AttrVec()); 2296 2297 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2298 bool Override = false; 2299 // Ignore deprecated/unavailable/availability attributes if requested. 2300 if (isa<DeprecatedAttr>(I) || 2301 isa<UnavailableAttr>(I) || 2302 isa<AvailabilityAttr>(I)) { 2303 switch (AMK) { 2304 case AMK_None: 2305 continue; 2306 2307 case AMK_Redeclaration: 2308 break; 2309 2310 case AMK_Override: 2311 Override = true; 2312 break; 2313 } 2314 } 2315 2316 // Already handled. 2317 if (isa<UsedAttr>(I)) 2318 continue; 2319 2320 if (mergeDeclAttribute(*this, New, I, Override)) 2321 foundAny = true; 2322 } 2323 2324 if (mergeAlignedAttrs(*this, New, Old)) 2325 foundAny = true; 2326 2327 if (!foundAny) New->dropAttrs(); 2328 } 2329 2330 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2331 /// to the new one. 2332 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2333 const ParmVarDecl *oldDecl, 2334 Sema &S) { 2335 // C++11 [dcl.attr.depend]p2: 2336 // The first declaration of a function shall specify the 2337 // carries_dependency attribute for its declarator-id if any declaration 2338 // of the function specifies the carries_dependency attribute. 2339 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2340 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2341 S.Diag(CDA->getLocation(), 2342 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2343 // Find the first declaration of the parameter. 2344 // FIXME: Should we build redeclaration chains for function parameters? 2345 const FunctionDecl *FirstFD = 2346 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2347 const ParmVarDecl *FirstVD = 2348 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2349 S.Diag(FirstVD->getLocation(), 2350 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2351 } 2352 2353 if (!oldDecl->hasAttrs()) 2354 return; 2355 2356 bool foundAny = newDecl->hasAttrs(); 2357 2358 // Ensure that any moving of objects within the allocated map is 2359 // done before we process them. 2360 if (!foundAny) newDecl->setAttrs(AttrVec()); 2361 2362 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2363 if (!DeclHasAttr(newDecl, I)) { 2364 InheritableAttr *newAttr = 2365 cast<InheritableParamAttr>(I->clone(S.Context)); 2366 newAttr->setInherited(true); 2367 newDecl->addAttr(newAttr); 2368 foundAny = true; 2369 } 2370 } 2371 2372 if (!foundAny) newDecl->dropAttrs(); 2373 } 2374 2375 namespace { 2376 2377 /// Used in MergeFunctionDecl to keep track of function parameters in 2378 /// C. 2379 struct GNUCompatibleParamWarning { 2380 ParmVarDecl *OldParm; 2381 ParmVarDecl *NewParm; 2382 QualType PromotedType; 2383 }; 2384 2385 } 2386 2387 /// getSpecialMember - get the special member enum for a method. 2388 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2389 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2390 if (Ctor->isDefaultConstructor()) 2391 return Sema::CXXDefaultConstructor; 2392 2393 if (Ctor->isCopyConstructor()) 2394 return Sema::CXXCopyConstructor; 2395 2396 if (Ctor->isMoveConstructor()) 2397 return Sema::CXXMoveConstructor; 2398 } else if (isa<CXXDestructorDecl>(MD)) { 2399 return Sema::CXXDestructor; 2400 } else if (MD->isCopyAssignmentOperator()) { 2401 return Sema::CXXCopyAssignment; 2402 } else if (MD->isMoveAssignmentOperator()) { 2403 return Sema::CXXMoveAssignment; 2404 } 2405 2406 return Sema::CXXInvalid; 2407 } 2408 2409 // Determine whether the previous declaration was a definition, implicit 2410 // declaration, or a declaration. 2411 template <typename T> 2412 static std::pair<diag::kind, SourceLocation> 2413 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2414 diag::kind PrevDiag; 2415 SourceLocation OldLocation = Old->getLocation(); 2416 if (Old->isThisDeclarationADefinition()) 2417 PrevDiag = diag::note_previous_definition; 2418 else if (Old->isImplicit()) { 2419 PrevDiag = diag::note_previous_implicit_declaration; 2420 if (OldLocation.isInvalid()) 2421 OldLocation = New->getLocation(); 2422 } else 2423 PrevDiag = diag::note_previous_declaration; 2424 return std::make_pair(PrevDiag, OldLocation); 2425 } 2426 2427 /// canRedefineFunction - checks if a function can be redefined. Currently, 2428 /// only extern inline functions can be redefined, and even then only in 2429 /// GNU89 mode. 2430 static bool canRedefineFunction(const FunctionDecl *FD, 2431 const LangOptions& LangOpts) { 2432 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2433 !LangOpts.CPlusPlus && 2434 FD->isInlineSpecified() && 2435 FD->getStorageClass() == SC_Extern); 2436 } 2437 2438 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2439 const AttributedType *AT = T->getAs<AttributedType>(); 2440 while (AT && !AT->isCallingConv()) 2441 AT = AT->getModifiedType()->getAs<AttributedType>(); 2442 return AT; 2443 } 2444 2445 template <typename T> 2446 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2447 const DeclContext *DC = Old->getDeclContext(); 2448 if (DC->isRecord()) 2449 return false; 2450 2451 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2452 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2453 return true; 2454 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2455 return true; 2456 return false; 2457 } 2458 2459 /// MergeFunctionDecl - We just parsed a function 'New' from 2460 /// declarator D which has the same name and scope as a previous 2461 /// declaration 'Old'. Figure out how to resolve this situation, 2462 /// merging decls or emitting diagnostics as appropriate. 2463 /// 2464 /// In C++, New and Old must be declarations that are not 2465 /// overloaded. Use IsOverload to determine whether New and Old are 2466 /// overloaded, and to select the Old declaration that New should be 2467 /// merged with. 2468 /// 2469 /// Returns true if there was an error, false otherwise. 2470 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2471 Scope *S, bool MergeTypeWithOld) { 2472 // Verify the old decl was also a function. 2473 FunctionDecl *Old = OldD->getAsFunction(); 2474 if (!Old) { 2475 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2476 if (New->getFriendObjectKind()) { 2477 Diag(New->getLocation(), diag::err_using_decl_friend); 2478 Diag(Shadow->getTargetDecl()->getLocation(), 2479 diag::note_using_decl_target); 2480 Diag(Shadow->getUsingDecl()->getLocation(), 2481 diag::note_using_decl) << 0; 2482 return true; 2483 } 2484 2485 // C++11 [namespace.udecl]p14: 2486 // If a function declaration in namespace scope or block scope has the 2487 // same name and the same parameter-type-list as a function introduced 2488 // by a using-declaration, and the declarations do not declare the same 2489 // function, the program is ill-formed. 2490 2491 // Check whether the two declarations might declare the same function. 2492 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2493 if (Old && 2494 !Old->getDeclContext()->getRedeclContext()->Equals( 2495 New->getDeclContext()->getRedeclContext()) && 2496 !(Old->isExternC() && New->isExternC())) 2497 Old = nullptr; 2498 2499 if (!Old) { 2500 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2501 Diag(Shadow->getTargetDecl()->getLocation(), 2502 diag::note_using_decl_target); 2503 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2504 return true; 2505 } 2506 OldD = Old; 2507 } else { 2508 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2509 << New->getDeclName(); 2510 Diag(OldD->getLocation(), diag::note_previous_definition); 2511 return true; 2512 } 2513 } 2514 2515 // If the old declaration is invalid, just give up here. 2516 if (Old->isInvalidDecl()) 2517 return true; 2518 2519 diag::kind PrevDiag; 2520 SourceLocation OldLocation; 2521 std::tie(PrevDiag, OldLocation) = 2522 getNoteDiagForInvalidRedeclaration(Old, New); 2523 2524 // Don't complain about this if we're in GNU89 mode and the old function 2525 // is an extern inline function. 2526 // Don't complain about specializations. They are not supposed to have 2527 // storage classes. 2528 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2529 New->getStorageClass() == SC_Static && 2530 Old->hasExternalFormalLinkage() && 2531 !New->getTemplateSpecializationInfo() && 2532 !canRedefineFunction(Old, getLangOpts())) { 2533 if (getLangOpts().MicrosoftExt) { 2534 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2535 Diag(OldLocation, PrevDiag); 2536 } else { 2537 Diag(New->getLocation(), diag::err_static_non_static) << New; 2538 Diag(OldLocation, PrevDiag); 2539 return true; 2540 } 2541 } 2542 2543 2544 // If a function is first declared with a calling convention, but is later 2545 // declared or defined without one, all following decls assume the calling 2546 // convention of the first. 2547 // 2548 // It's OK if a function is first declared without a calling convention, 2549 // but is later declared or defined with the default calling convention. 2550 // 2551 // To test if either decl has an explicit calling convention, we look for 2552 // AttributedType sugar nodes on the type as written. If they are missing or 2553 // were canonicalized away, we assume the calling convention was implicit. 2554 // 2555 // Note also that we DO NOT return at this point, because we still have 2556 // other tests to run. 2557 QualType OldQType = Context.getCanonicalType(Old->getType()); 2558 QualType NewQType = Context.getCanonicalType(New->getType()); 2559 const FunctionType *OldType = cast<FunctionType>(OldQType); 2560 const FunctionType *NewType = cast<FunctionType>(NewQType); 2561 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2562 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2563 bool RequiresAdjustment = false; 2564 2565 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2566 FunctionDecl *First = Old->getFirstDecl(); 2567 const FunctionType *FT = 2568 First->getType().getCanonicalType()->castAs<FunctionType>(); 2569 FunctionType::ExtInfo FI = FT->getExtInfo(); 2570 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2571 if (!NewCCExplicit) { 2572 // Inherit the CC from the previous declaration if it was specified 2573 // there but not here. 2574 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2575 RequiresAdjustment = true; 2576 } else { 2577 // Calling conventions aren't compatible, so complain. 2578 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2579 Diag(New->getLocation(), diag::err_cconv_change) 2580 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2581 << !FirstCCExplicit 2582 << (!FirstCCExplicit ? "" : 2583 FunctionType::getNameForCallConv(FI.getCC())); 2584 2585 // Put the note on the first decl, since it is the one that matters. 2586 Diag(First->getLocation(), diag::note_previous_declaration); 2587 return true; 2588 } 2589 } 2590 2591 // FIXME: diagnose the other way around? 2592 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2593 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2594 RequiresAdjustment = true; 2595 } 2596 2597 // Merge regparm attribute. 2598 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2599 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2600 if (NewTypeInfo.getHasRegParm()) { 2601 Diag(New->getLocation(), diag::err_regparm_mismatch) 2602 << NewType->getRegParmType() 2603 << OldType->getRegParmType(); 2604 Diag(OldLocation, diag::note_previous_declaration); 2605 return true; 2606 } 2607 2608 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2609 RequiresAdjustment = true; 2610 } 2611 2612 // Merge ns_returns_retained attribute. 2613 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2614 if (NewTypeInfo.getProducesResult()) { 2615 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2616 Diag(OldLocation, diag::note_previous_declaration); 2617 return true; 2618 } 2619 2620 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2621 RequiresAdjustment = true; 2622 } 2623 2624 if (RequiresAdjustment) { 2625 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2626 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2627 New->setType(QualType(AdjustedType, 0)); 2628 NewQType = Context.getCanonicalType(New->getType()); 2629 NewType = cast<FunctionType>(NewQType); 2630 } 2631 2632 // If this redeclaration makes the function inline, we may need to add it to 2633 // UndefinedButUsed. 2634 if (!Old->isInlined() && New->isInlined() && 2635 !New->hasAttr<GNUInlineAttr>() && 2636 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2637 Old->isUsed(false) && 2638 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2639 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2640 SourceLocation())); 2641 2642 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2643 // about it. 2644 if (New->hasAttr<GNUInlineAttr>() && 2645 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2646 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2647 } 2648 2649 if (getLangOpts().CPlusPlus) { 2650 // (C++98 13.1p2): 2651 // Certain function declarations cannot be overloaded: 2652 // -- Function declarations that differ only in the return type 2653 // cannot be overloaded. 2654 2655 // Go back to the type source info to compare the declared return types, 2656 // per C++1y [dcl.type.auto]p13: 2657 // Redeclarations or specializations of a function or function template 2658 // with a declared return type that uses a placeholder type shall also 2659 // use that placeholder, not a deduced type. 2660 QualType OldDeclaredReturnType = 2661 (Old->getTypeSourceInfo() 2662 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2663 : OldType)->getReturnType(); 2664 QualType NewDeclaredReturnType = 2665 (New->getTypeSourceInfo() 2666 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2667 : NewType)->getReturnType(); 2668 QualType ResQT; 2669 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2670 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2671 New->isLocalExternDecl())) { 2672 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2673 OldDeclaredReturnType->isObjCObjectPointerType()) 2674 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2675 if (ResQT.isNull()) { 2676 if (New->isCXXClassMember() && New->isOutOfLine()) 2677 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2678 << New << New->getReturnTypeSourceRange(); 2679 else 2680 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2681 << New->getReturnTypeSourceRange(); 2682 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2683 << Old->getReturnTypeSourceRange(); 2684 return true; 2685 } 2686 else 2687 NewQType = ResQT; 2688 } 2689 2690 QualType OldReturnType = OldType->getReturnType(); 2691 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2692 if (OldReturnType != NewReturnType) { 2693 // If this function has a deduced return type and has already been 2694 // defined, copy the deduced value from the old declaration. 2695 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2696 if (OldAT && OldAT->isDeduced()) { 2697 New->setType( 2698 SubstAutoType(New->getType(), 2699 OldAT->isDependentType() ? Context.DependentTy 2700 : OldAT->getDeducedType())); 2701 NewQType = Context.getCanonicalType( 2702 SubstAutoType(NewQType, 2703 OldAT->isDependentType() ? Context.DependentTy 2704 : OldAT->getDeducedType())); 2705 } 2706 } 2707 2708 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2709 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2710 if (OldMethod && NewMethod) { 2711 // Preserve triviality. 2712 NewMethod->setTrivial(OldMethod->isTrivial()); 2713 2714 // MSVC allows explicit template specialization at class scope: 2715 // 2 CXXMethodDecls referring to the same function will be injected. 2716 // We don't want a redeclaration error. 2717 bool IsClassScopeExplicitSpecialization = 2718 OldMethod->isFunctionTemplateSpecialization() && 2719 NewMethod->isFunctionTemplateSpecialization(); 2720 bool isFriend = NewMethod->getFriendObjectKind(); 2721 2722 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2723 !IsClassScopeExplicitSpecialization) { 2724 // -- Member function declarations with the same name and the 2725 // same parameter types cannot be overloaded if any of them 2726 // is a static member function declaration. 2727 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2728 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2729 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2730 return true; 2731 } 2732 2733 // C++ [class.mem]p1: 2734 // [...] A member shall not be declared twice in the 2735 // member-specification, except that a nested class or member 2736 // class template can be declared and then later defined. 2737 if (ActiveTemplateInstantiations.empty()) { 2738 unsigned NewDiag; 2739 if (isa<CXXConstructorDecl>(OldMethod)) 2740 NewDiag = diag::err_constructor_redeclared; 2741 else if (isa<CXXDestructorDecl>(NewMethod)) 2742 NewDiag = diag::err_destructor_redeclared; 2743 else if (isa<CXXConversionDecl>(NewMethod)) 2744 NewDiag = diag::err_conv_function_redeclared; 2745 else 2746 NewDiag = diag::err_member_redeclared; 2747 2748 Diag(New->getLocation(), NewDiag); 2749 } else { 2750 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2751 << New << New->getType(); 2752 } 2753 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2754 2755 // Complain if this is an explicit declaration of a special 2756 // member that was initially declared implicitly. 2757 // 2758 // As an exception, it's okay to befriend such methods in order 2759 // to permit the implicit constructor/destructor/operator calls. 2760 } else if (OldMethod->isImplicit()) { 2761 if (isFriend) { 2762 NewMethod->setImplicit(); 2763 } else { 2764 Diag(NewMethod->getLocation(), 2765 diag::err_definition_of_implicitly_declared_member) 2766 << New << getSpecialMember(OldMethod); 2767 return true; 2768 } 2769 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2770 Diag(NewMethod->getLocation(), 2771 diag::err_definition_of_explicitly_defaulted_member) 2772 << getSpecialMember(OldMethod); 2773 return true; 2774 } 2775 } 2776 2777 // C++11 [dcl.attr.noreturn]p1: 2778 // The first declaration of a function shall specify the noreturn 2779 // attribute if any declaration of that function specifies the noreturn 2780 // attribute. 2781 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2782 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2783 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2784 Diag(Old->getFirstDecl()->getLocation(), 2785 diag::note_noreturn_missing_first_decl); 2786 } 2787 2788 // C++11 [dcl.attr.depend]p2: 2789 // The first declaration of a function shall specify the 2790 // carries_dependency attribute for its declarator-id if any declaration 2791 // of the function specifies the carries_dependency attribute. 2792 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2793 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2794 Diag(CDA->getLocation(), 2795 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2796 Diag(Old->getFirstDecl()->getLocation(), 2797 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2798 } 2799 2800 // (C++98 8.3.5p3): 2801 // All declarations for a function shall agree exactly in both the 2802 // return type and the parameter-type-list. 2803 // We also want to respect all the extended bits except noreturn. 2804 2805 // noreturn should now match unless the old type info didn't have it. 2806 QualType OldQTypeForComparison = OldQType; 2807 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2808 assert(OldQType == QualType(OldType, 0)); 2809 const FunctionType *OldTypeForComparison 2810 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2811 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2812 assert(OldQTypeForComparison.isCanonical()); 2813 } 2814 2815 if (haveIncompatibleLanguageLinkages(Old, New)) { 2816 // As a special case, retain the language linkage from previous 2817 // declarations of a friend function as an extension. 2818 // 2819 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2820 // and is useful because there's otherwise no way to specify language 2821 // linkage within class scope. 2822 // 2823 // Check cautiously as the friend object kind isn't yet complete. 2824 if (New->getFriendObjectKind() != Decl::FOK_None) { 2825 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2826 Diag(OldLocation, PrevDiag); 2827 } else { 2828 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2829 Diag(OldLocation, PrevDiag); 2830 return true; 2831 } 2832 } 2833 2834 if (OldQTypeForComparison == NewQType) 2835 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2836 2837 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2838 New->isLocalExternDecl()) { 2839 // It's OK if we couldn't merge types for a local function declaraton 2840 // if either the old or new type is dependent. We'll merge the types 2841 // when we instantiate the function. 2842 return false; 2843 } 2844 2845 // Fall through for conflicting redeclarations and redefinitions. 2846 } 2847 2848 // C: Function types need to be compatible, not identical. This handles 2849 // duplicate function decls like "void f(int); void f(enum X);" properly. 2850 if (!getLangOpts().CPlusPlus && 2851 Context.typesAreCompatible(OldQType, NewQType)) { 2852 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2853 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2854 const FunctionProtoType *OldProto = nullptr; 2855 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2856 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2857 // The old declaration provided a function prototype, but the 2858 // new declaration does not. Merge in the prototype. 2859 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2860 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2861 NewQType = 2862 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2863 OldProto->getExtProtoInfo()); 2864 New->setType(NewQType); 2865 New->setHasInheritedPrototype(); 2866 2867 // Synthesize parameters with the same types. 2868 SmallVector<ParmVarDecl*, 16> Params; 2869 for (const auto &ParamType : OldProto->param_types()) { 2870 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2871 SourceLocation(), nullptr, 2872 ParamType, /*TInfo=*/nullptr, 2873 SC_None, nullptr); 2874 Param->setScopeInfo(0, Params.size()); 2875 Param->setImplicit(); 2876 Params.push_back(Param); 2877 } 2878 2879 New->setParams(Params); 2880 } 2881 2882 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2883 } 2884 2885 // GNU C permits a K&R definition to follow a prototype declaration 2886 // if the declared types of the parameters in the K&R definition 2887 // match the types in the prototype declaration, even when the 2888 // promoted types of the parameters from the K&R definition differ 2889 // from the types in the prototype. GCC then keeps the types from 2890 // the prototype. 2891 // 2892 // If a variadic prototype is followed by a non-variadic K&R definition, 2893 // the K&R definition becomes variadic. This is sort of an edge case, but 2894 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2895 // C99 6.9.1p8. 2896 if (!getLangOpts().CPlusPlus && 2897 Old->hasPrototype() && !New->hasPrototype() && 2898 New->getType()->getAs<FunctionProtoType>() && 2899 Old->getNumParams() == New->getNumParams()) { 2900 SmallVector<QualType, 16> ArgTypes; 2901 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2902 const FunctionProtoType *OldProto 2903 = Old->getType()->getAs<FunctionProtoType>(); 2904 const FunctionProtoType *NewProto 2905 = New->getType()->getAs<FunctionProtoType>(); 2906 2907 // Determine whether this is the GNU C extension. 2908 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2909 NewProto->getReturnType()); 2910 bool LooseCompatible = !MergedReturn.isNull(); 2911 for (unsigned Idx = 0, End = Old->getNumParams(); 2912 LooseCompatible && Idx != End; ++Idx) { 2913 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2914 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2915 if (Context.typesAreCompatible(OldParm->getType(), 2916 NewProto->getParamType(Idx))) { 2917 ArgTypes.push_back(NewParm->getType()); 2918 } else if (Context.typesAreCompatible(OldParm->getType(), 2919 NewParm->getType(), 2920 /*CompareUnqualified=*/true)) { 2921 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2922 NewProto->getParamType(Idx) }; 2923 Warnings.push_back(Warn); 2924 ArgTypes.push_back(NewParm->getType()); 2925 } else 2926 LooseCompatible = false; 2927 } 2928 2929 if (LooseCompatible) { 2930 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2931 Diag(Warnings[Warn].NewParm->getLocation(), 2932 diag::ext_param_promoted_not_compatible_with_prototype) 2933 << Warnings[Warn].PromotedType 2934 << Warnings[Warn].OldParm->getType(); 2935 if (Warnings[Warn].OldParm->getLocation().isValid()) 2936 Diag(Warnings[Warn].OldParm->getLocation(), 2937 diag::note_previous_declaration); 2938 } 2939 2940 if (MergeTypeWithOld) 2941 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2942 OldProto->getExtProtoInfo())); 2943 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2944 } 2945 2946 // Fall through to diagnose conflicting types. 2947 } 2948 2949 // A function that has already been declared has been redeclared or 2950 // defined with a different type; show an appropriate diagnostic. 2951 2952 // If the previous declaration was an implicitly-generated builtin 2953 // declaration, then at the very least we should use a specialized note. 2954 unsigned BuiltinID; 2955 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2956 // If it's actually a library-defined builtin function like 'malloc' 2957 // or 'printf', just warn about the incompatible redeclaration. 2958 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2959 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2960 Diag(OldLocation, diag::note_previous_builtin_declaration) 2961 << Old << Old->getType(); 2962 2963 // If this is a global redeclaration, just forget hereafter 2964 // about the "builtin-ness" of the function. 2965 // 2966 // Doing this for local extern declarations is problematic. If 2967 // the builtin declaration remains visible, a second invalid 2968 // local declaration will produce a hard error; if it doesn't 2969 // remain visible, a single bogus local redeclaration (which is 2970 // actually only a warning) could break all the downstream code. 2971 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2972 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2973 2974 return false; 2975 } 2976 2977 PrevDiag = diag::note_previous_builtin_declaration; 2978 } 2979 2980 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2981 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2982 return true; 2983 } 2984 2985 /// \brief Completes the merge of two function declarations that are 2986 /// known to be compatible. 2987 /// 2988 /// This routine handles the merging of attributes and other 2989 /// properties of function declarations from the old declaration to 2990 /// the new declaration, once we know that New is in fact a 2991 /// redeclaration of Old. 2992 /// 2993 /// \returns false 2994 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2995 Scope *S, bool MergeTypeWithOld) { 2996 // Merge the attributes 2997 mergeDeclAttributes(New, Old); 2998 2999 // Merge "pure" flag. 3000 if (Old->isPure()) 3001 New->setPure(); 3002 3003 // Merge "used" flag. 3004 if (Old->getMostRecentDecl()->isUsed(false)) 3005 New->setIsUsed(); 3006 3007 // Merge attributes from the parameters. These can mismatch with K&R 3008 // declarations. 3009 if (New->getNumParams() == Old->getNumParams()) 3010 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3011 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3012 *this); 3013 3014 if (getLangOpts().CPlusPlus) 3015 return MergeCXXFunctionDecl(New, Old, S); 3016 3017 // Merge the function types so the we get the composite types for the return 3018 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3019 // was visible. 3020 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3021 if (!Merged.isNull() && MergeTypeWithOld) 3022 New->setType(Merged); 3023 3024 return false; 3025 } 3026 3027 3028 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3029 ObjCMethodDecl *oldMethod) { 3030 3031 // Merge the attributes, including deprecated/unavailable 3032 AvailabilityMergeKind MergeKind = 3033 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3034 : AMK_Override; 3035 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3036 3037 // Merge attributes from the parameters. 3038 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3039 oe = oldMethod->param_end(); 3040 for (ObjCMethodDecl::param_iterator 3041 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3042 ni != ne && oi != oe; ++ni, ++oi) 3043 mergeParamDeclAttributes(*ni, *oi, *this); 3044 3045 CheckObjCMethodOverride(newMethod, oldMethod); 3046 } 3047 3048 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3049 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3050 /// emitting diagnostics as appropriate. 3051 /// 3052 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3053 /// to here in AddInitializerToDecl. We can't check them before the initializer 3054 /// is attached. 3055 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3056 bool MergeTypeWithOld) { 3057 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3058 return; 3059 3060 QualType MergedT; 3061 if (getLangOpts().CPlusPlus) { 3062 if (New->getType()->isUndeducedType()) { 3063 // We don't know what the new type is until the initializer is attached. 3064 return; 3065 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3066 // These could still be something that needs exception specs checked. 3067 return MergeVarDeclExceptionSpecs(New, Old); 3068 } 3069 // C++ [basic.link]p10: 3070 // [...] the types specified by all declarations referring to a given 3071 // object or function shall be identical, except that declarations for an 3072 // array object can specify array types that differ by the presence or 3073 // absence of a major array bound (8.3.4). 3074 else if (Old->getType()->isIncompleteArrayType() && 3075 New->getType()->isArrayType()) { 3076 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3077 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3078 if (Context.hasSameType(OldArray->getElementType(), 3079 NewArray->getElementType())) 3080 MergedT = New->getType(); 3081 } else if (Old->getType()->isArrayType() && 3082 New->getType()->isIncompleteArrayType()) { 3083 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3084 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3085 if (Context.hasSameType(OldArray->getElementType(), 3086 NewArray->getElementType())) 3087 MergedT = Old->getType(); 3088 } else if (New->getType()->isObjCObjectPointerType() && 3089 Old->getType()->isObjCObjectPointerType()) { 3090 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3091 Old->getType()); 3092 } 3093 } else { 3094 // C 6.2.7p2: 3095 // All declarations that refer to the same object or function shall have 3096 // compatible type. 3097 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3098 } 3099 if (MergedT.isNull()) { 3100 // It's OK if we couldn't merge types if either type is dependent, for a 3101 // block-scope variable. In other cases (static data members of class 3102 // templates, variable templates, ...), we require the types to be 3103 // equivalent. 3104 // FIXME: The C++ standard doesn't say anything about this. 3105 if ((New->getType()->isDependentType() || 3106 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3107 // If the old type was dependent, we can't merge with it, so the new type 3108 // becomes dependent for now. We'll reproduce the original type when we 3109 // instantiate the TypeSourceInfo for the variable. 3110 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3111 New->setType(Context.DependentTy); 3112 return; 3113 } 3114 3115 // FIXME: Even if this merging succeeds, some other non-visible declaration 3116 // of this variable might have an incompatible type. For instance: 3117 // 3118 // extern int arr[]; 3119 // void f() { extern int arr[2]; } 3120 // void g() { extern int arr[3]; } 3121 // 3122 // Neither C nor C++ requires a diagnostic for this, but we should still try 3123 // to diagnose it. 3124 Diag(New->getLocation(), diag::err_redefinition_different_type) 3125 << New->getDeclName() << New->getType() << Old->getType(); 3126 Diag(Old->getLocation(), diag::note_previous_definition); 3127 return New->setInvalidDecl(); 3128 } 3129 3130 // Don't actually update the type on the new declaration if the old 3131 // declaration was an extern declaration in a different scope. 3132 if (MergeTypeWithOld) 3133 New->setType(MergedT); 3134 } 3135 3136 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3137 LookupResult &Previous) { 3138 // C11 6.2.7p4: 3139 // For an identifier with internal or external linkage declared 3140 // in a scope in which a prior declaration of that identifier is 3141 // visible, if the prior declaration specifies internal or 3142 // external linkage, the type of the identifier at the later 3143 // declaration becomes the composite type. 3144 // 3145 // If the variable isn't visible, we do not merge with its type. 3146 if (Previous.isShadowed()) 3147 return false; 3148 3149 if (S.getLangOpts().CPlusPlus) { 3150 // C++11 [dcl.array]p3: 3151 // If there is a preceding declaration of the entity in the same 3152 // scope in which the bound was specified, an omitted array bound 3153 // is taken to be the same as in that earlier declaration. 3154 return NewVD->isPreviousDeclInSameBlockScope() || 3155 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3156 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3157 } else { 3158 // If the old declaration was function-local, don't merge with its 3159 // type unless we're in the same function. 3160 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3161 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3162 } 3163 } 3164 3165 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3166 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3167 /// situation, merging decls or emitting diagnostics as appropriate. 3168 /// 3169 /// Tentative definition rules (C99 6.9.2p2) are checked by 3170 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3171 /// definitions here, since the initializer hasn't been attached. 3172 /// 3173 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3174 // If the new decl is already invalid, don't do any other checking. 3175 if (New->isInvalidDecl()) 3176 return; 3177 3178 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3179 3180 // Verify the old decl was also a variable or variable template. 3181 VarDecl *Old = nullptr; 3182 VarTemplateDecl *OldTemplate = nullptr; 3183 if (Previous.isSingleResult()) { 3184 if (NewTemplate) { 3185 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3186 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3187 } else 3188 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3189 } 3190 if (!Old) { 3191 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3192 << New->getDeclName(); 3193 Diag(Previous.getRepresentativeDecl()->getLocation(), 3194 diag::note_previous_definition); 3195 return New->setInvalidDecl(); 3196 } 3197 3198 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3199 return; 3200 3201 // Ensure the template parameters are compatible. 3202 if (NewTemplate && 3203 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3204 OldTemplate->getTemplateParameters(), 3205 /*Complain=*/true, TPL_TemplateMatch)) 3206 return; 3207 3208 // C++ [class.mem]p1: 3209 // A member shall not be declared twice in the member-specification [...] 3210 // 3211 // Here, we need only consider static data members. 3212 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3213 Diag(New->getLocation(), diag::err_duplicate_member) 3214 << New->getIdentifier(); 3215 Diag(Old->getLocation(), diag::note_previous_declaration); 3216 New->setInvalidDecl(); 3217 } 3218 3219 mergeDeclAttributes(New, Old); 3220 // Warn if an already-declared variable is made a weak_import in a subsequent 3221 // declaration 3222 if (New->hasAttr<WeakImportAttr>() && 3223 Old->getStorageClass() == SC_None && 3224 !Old->hasAttr<WeakImportAttr>()) { 3225 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3226 Diag(Old->getLocation(), diag::note_previous_definition); 3227 // Remove weak_import attribute on new declaration. 3228 New->dropAttr<WeakImportAttr>(); 3229 } 3230 3231 // Merge the types. 3232 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3233 3234 if (New->isInvalidDecl()) 3235 return; 3236 3237 diag::kind PrevDiag; 3238 SourceLocation OldLocation; 3239 std::tie(PrevDiag, OldLocation) = 3240 getNoteDiagForInvalidRedeclaration(Old, New); 3241 3242 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3243 if (New->getStorageClass() == SC_Static && 3244 !New->isStaticDataMember() && 3245 Old->hasExternalFormalLinkage()) { 3246 if (getLangOpts().MicrosoftExt) { 3247 Diag(New->getLocation(), diag::ext_static_non_static) 3248 << New->getDeclName(); 3249 Diag(OldLocation, PrevDiag); 3250 } else { 3251 Diag(New->getLocation(), diag::err_static_non_static) 3252 << New->getDeclName(); 3253 Diag(OldLocation, PrevDiag); 3254 return New->setInvalidDecl(); 3255 } 3256 } 3257 // C99 6.2.2p4: 3258 // For an identifier declared with the storage-class specifier 3259 // extern in a scope in which a prior declaration of that 3260 // identifier is visible,23) if the prior declaration specifies 3261 // internal or external linkage, the linkage of the identifier at 3262 // the later declaration is the same as the linkage specified at 3263 // the prior declaration. If no prior declaration is visible, or 3264 // if the prior declaration specifies no linkage, then the 3265 // identifier has external linkage. 3266 if (New->hasExternalStorage() && Old->hasLinkage()) 3267 /* Okay */; 3268 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3269 !New->isStaticDataMember() && 3270 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3271 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3272 Diag(OldLocation, PrevDiag); 3273 return New->setInvalidDecl(); 3274 } 3275 3276 // Check if extern is followed by non-extern and vice-versa. 3277 if (New->hasExternalStorage() && 3278 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3279 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3280 Diag(OldLocation, PrevDiag); 3281 return New->setInvalidDecl(); 3282 } 3283 if (Old->hasLinkage() && New->isLocalVarDecl() && 3284 !New->hasExternalStorage()) { 3285 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3286 Diag(OldLocation, PrevDiag); 3287 return New->setInvalidDecl(); 3288 } 3289 3290 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3291 3292 // FIXME: The test for external storage here seems wrong? We still 3293 // need to check for mismatches. 3294 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3295 // Don't complain about out-of-line definitions of static members. 3296 !(Old->getLexicalDeclContext()->isRecord() && 3297 !New->getLexicalDeclContext()->isRecord())) { 3298 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3299 Diag(OldLocation, PrevDiag); 3300 return New->setInvalidDecl(); 3301 } 3302 3303 if (New->getTLSKind() != Old->getTLSKind()) { 3304 if (!Old->getTLSKind()) { 3305 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3306 Diag(OldLocation, PrevDiag); 3307 } else if (!New->getTLSKind()) { 3308 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3309 Diag(OldLocation, PrevDiag); 3310 } else { 3311 // Do not allow redeclaration to change the variable between requiring 3312 // static and dynamic initialization. 3313 // FIXME: GCC allows this, but uses the TLS keyword on the first 3314 // declaration to determine the kind. Do we need to be compatible here? 3315 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3316 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3317 Diag(OldLocation, PrevDiag); 3318 } 3319 } 3320 3321 // C++ doesn't have tentative definitions, so go right ahead and check here. 3322 const VarDecl *Def; 3323 if (getLangOpts().CPlusPlus && 3324 New->isThisDeclarationADefinition() == VarDecl::Definition && 3325 (Def = Old->getDefinition())) { 3326 Diag(New->getLocation(), diag::err_redefinition) << New; 3327 Diag(Def->getLocation(), diag::note_previous_definition); 3328 New->setInvalidDecl(); 3329 return; 3330 } 3331 3332 if (haveIncompatibleLanguageLinkages(Old, New)) { 3333 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3334 Diag(OldLocation, PrevDiag); 3335 New->setInvalidDecl(); 3336 return; 3337 } 3338 3339 // Merge "used" flag. 3340 if (Old->getMostRecentDecl()->isUsed(false)) 3341 New->setIsUsed(); 3342 3343 // Keep a chain of previous declarations. 3344 New->setPreviousDecl(Old); 3345 if (NewTemplate) 3346 NewTemplate->setPreviousDecl(OldTemplate); 3347 3348 // Inherit access appropriately. 3349 New->setAccess(Old->getAccess()); 3350 if (NewTemplate) 3351 NewTemplate->setAccess(New->getAccess()); 3352 } 3353 3354 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3355 /// no declarator (e.g. "struct foo;") is parsed. 3356 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3357 DeclSpec &DS) { 3358 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3359 } 3360 3361 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3362 if (!S.Context.getLangOpts().CPlusPlus) 3363 return; 3364 3365 if (isa<CXXRecordDecl>(Tag->getParent())) { 3366 // If this tag is the direct child of a class, number it if 3367 // it is anonymous. 3368 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3369 return; 3370 MangleNumberingContext &MCtx = 3371 S.Context.getManglingNumberContext(Tag->getParent()); 3372 S.Context.setManglingNumber( 3373 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3374 return; 3375 } 3376 3377 // If this tag isn't a direct child of a class, number it if it is local. 3378 Decl *ManglingContextDecl; 3379 if (MangleNumberingContext *MCtx = 3380 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3381 ManglingContextDecl)) { 3382 S.Context.setManglingNumber( 3383 Tag, 3384 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3385 } 3386 } 3387 3388 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3389 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3390 /// parameters to cope with template friend declarations. 3391 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3392 DeclSpec &DS, 3393 MultiTemplateParamsArg TemplateParams, 3394 bool IsExplicitInstantiation) { 3395 Decl *TagD = nullptr; 3396 TagDecl *Tag = nullptr; 3397 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3398 DS.getTypeSpecType() == DeclSpec::TST_struct || 3399 DS.getTypeSpecType() == DeclSpec::TST_interface || 3400 DS.getTypeSpecType() == DeclSpec::TST_union || 3401 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3402 TagD = DS.getRepAsDecl(); 3403 3404 if (!TagD) // We probably had an error 3405 return nullptr; 3406 3407 // Note that the above type specs guarantee that the 3408 // type rep is a Decl, whereas in many of the others 3409 // it's a Type. 3410 if (isa<TagDecl>(TagD)) 3411 Tag = cast<TagDecl>(TagD); 3412 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3413 Tag = CTD->getTemplatedDecl(); 3414 } 3415 3416 if (Tag) { 3417 HandleTagNumbering(*this, Tag, S); 3418 Tag->setFreeStanding(); 3419 if (Tag->isInvalidDecl()) 3420 return Tag; 3421 } 3422 3423 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3424 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3425 // or incomplete types shall not be restrict-qualified." 3426 if (TypeQuals & DeclSpec::TQ_restrict) 3427 Diag(DS.getRestrictSpecLoc(), 3428 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3429 << DS.getSourceRange(); 3430 } 3431 3432 if (DS.isConstexprSpecified()) { 3433 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3434 // and definitions of functions and variables. 3435 if (Tag) 3436 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3437 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3438 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3439 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3440 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3441 else 3442 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3443 // Don't emit warnings after this error. 3444 return TagD; 3445 } 3446 3447 DiagnoseFunctionSpecifiers(DS); 3448 3449 if (DS.isFriendSpecified()) { 3450 // If we're dealing with a decl but not a TagDecl, assume that 3451 // whatever routines created it handled the friendship aspect. 3452 if (TagD && !Tag) 3453 return nullptr; 3454 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3455 } 3456 3457 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3458 bool IsExplicitSpecialization = 3459 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3460 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3461 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3462 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3463 // nested-name-specifier unless it is an explicit instantiation 3464 // or an explicit specialization. 3465 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3466 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3467 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3468 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3469 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3470 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3471 << SS.getRange(); 3472 return nullptr; 3473 } 3474 3475 // Track whether this decl-specifier declares anything. 3476 bool DeclaresAnything = true; 3477 3478 // Handle anonymous struct definitions. 3479 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3480 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3481 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3482 if (getLangOpts().CPlusPlus || 3483 Record->getDeclContext()->isRecord()) 3484 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3485 3486 DeclaresAnything = false; 3487 } 3488 } 3489 3490 // C11 6.7.2.1p2: 3491 // A struct-declaration that does not declare an anonymous structure or 3492 // anonymous union shall contain a struct-declarator-list. 3493 // 3494 // This rule also existed in C89 and C99; the grammar for struct-declaration 3495 // did not permit a struct-declaration without a struct-declarator-list. 3496 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3497 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3498 // Check for Microsoft C extension: anonymous struct/union member. 3499 // Handle 2 kinds of anonymous struct/union: 3500 // struct STRUCT; 3501 // union UNION; 3502 // and 3503 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3504 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3505 if ((Tag && Tag->getDeclName()) || 3506 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3507 RecordDecl *Record = nullptr; 3508 if (Tag) 3509 Record = dyn_cast<RecordDecl>(Tag); 3510 else if (const RecordType *RT = 3511 DS.getRepAsType().get()->getAsStructureType()) 3512 Record = RT->getDecl(); 3513 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3514 Record = UT->getDecl(); 3515 3516 if (Record && getLangOpts().MicrosoftExt) { 3517 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3518 << Record->isUnion() << DS.getSourceRange(); 3519 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3520 } 3521 3522 DeclaresAnything = false; 3523 } 3524 } 3525 3526 // Skip all the checks below if we have a type error. 3527 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3528 (TagD && TagD->isInvalidDecl())) 3529 return TagD; 3530 3531 if (getLangOpts().CPlusPlus && 3532 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3533 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3534 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3535 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3536 DeclaresAnything = false; 3537 3538 if (!DS.isMissingDeclaratorOk()) { 3539 // Customize diagnostic for a typedef missing a name. 3540 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3541 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3542 << DS.getSourceRange(); 3543 else 3544 DeclaresAnything = false; 3545 } 3546 3547 if (DS.isModulePrivateSpecified() && 3548 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3549 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3550 << Tag->getTagKind() 3551 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3552 3553 ActOnDocumentableDecl(TagD); 3554 3555 // C 6.7/2: 3556 // A declaration [...] shall declare at least a declarator [...], a tag, 3557 // or the members of an enumeration. 3558 // C++ [dcl.dcl]p3: 3559 // [If there are no declarators], and except for the declaration of an 3560 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3561 // names into the program, or shall redeclare a name introduced by a 3562 // previous declaration. 3563 if (!DeclaresAnything) { 3564 // In C, we allow this as a (popular) extension / bug. Don't bother 3565 // producing further diagnostics for redundant qualifiers after this. 3566 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3567 return TagD; 3568 } 3569 3570 // C++ [dcl.stc]p1: 3571 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3572 // init-declarator-list of the declaration shall not be empty. 3573 // C++ [dcl.fct.spec]p1: 3574 // If a cv-qualifier appears in a decl-specifier-seq, the 3575 // init-declarator-list of the declaration shall not be empty. 3576 // 3577 // Spurious qualifiers here appear to be valid in C. 3578 unsigned DiagID = diag::warn_standalone_specifier; 3579 if (getLangOpts().CPlusPlus) 3580 DiagID = diag::ext_standalone_specifier; 3581 3582 // Note that a linkage-specification sets a storage class, but 3583 // 'extern "C" struct foo;' is actually valid and not theoretically 3584 // useless. 3585 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3586 if (SCS == DeclSpec::SCS_mutable) 3587 // Since mutable is not a viable storage class specifier in C, there is 3588 // no reason to treat it as an extension. Instead, diagnose as an error. 3589 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3590 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3591 Diag(DS.getStorageClassSpecLoc(), DiagID) 3592 << DeclSpec::getSpecifierName(SCS); 3593 } 3594 3595 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3596 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3597 << DeclSpec::getSpecifierName(TSCS); 3598 if (DS.getTypeQualifiers()) { 3599 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3600 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3601 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3602 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3603 // Restrict is covered above. 3604 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3605 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3606 } 3607 3608 // Warn about ignored type attributes, for example: 3609 // __attribute__((aligned)) struct A; 3610 // Attributes should be placed after tag to apply to type declaration. 3611 if (!DS.getAttributes().empty()) { 3612 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3613 if (TypeSpecType == DeclSpec::TST_class || 3614 TypeSpecType == DeclSpec::TST_struct || 3615 TypeSpecType == DeclSpec::TST_interface || 3616 TypeSpecType == DeclSpec::TST_union || 3617 TypeSpecType == DeclSpec::TST_enum) { 3618 AttributeList* attrs = DS.getAttributes().getList(); 3619 while (attrs) { 3620 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3621 << attrs->getName() 3622 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3623 TypeSpecType == DeclSpec::TST_struct ? 1 : 3624 TypeSpecType == DeclSpec::TST_union ? 2 : 3625 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3626 attrs = attrs->getNext(); 3627 } 3628 } 3629 } 3630 3631 return TagD; 3632 } 3633 3634 /// We are trying to inject an anonymous member into the given scope; 3635 /// check if there's an existing declaration that can't be overloaded. 3636 /// 3637 /// \return true if this is a forbidden redeclaration 3638 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3639 Scope *S, 3640 DeclContext *Owner, 3641 DeclarationName Name, 3642 SourceLocation NameLoc, 3643 unsigned diagnostic) { 3644 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3645 Sema::ForRedeclaration); 3646 if (!SemaRef.LookupName(R, S)) return false; 3647 3648 if (R.getAsSingle<TagDecl>()) 3649 return false; 3650 3651 // Pick a representative declaration. 3652 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3653 assert(PrevDecl && "Expected a non-null Decl"); 3654 3655 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3656 return false; 3657 3658 SemaRef.Diag(NameLoc, diagnostic) << Name; 3659 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3660 3661 return true; 3662 } 3663 3664 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3665 /// anonymous struct or union AnonRecord into the owning context Owner 3666 /// and scope S. This routine will be invoked just after we realize 3667 /// that an unnamed union or struct is actually an anonymous union or 3668 /// struct, e.g., 3669 /// 3670 /// @code 3671 /// union { 3672 /// int i; 3673 /// float f; 3674 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3675 /// // f into the surrounding scope.x 3676 /// @endcode 3677 /// 3678 /// This routine is recursive, injecting the names of nested anonymous 3679 /// structs/unions into the owning context and scope as well. 3680 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3681 DeclContext *Owner, 3682 RecordDecl *AnonRecord, 3683 AccessSpecifier AS, 3684 SmallVectorImpl<NamedDecl *> &Chaining, 3685 bool MSAnonStruct) { 3686 unsigned diagKind 3687 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3688 : diag::err_anonymous_struct_member_redecl; 3689 3690 bool Invalid = false; 3691 3692 // Look every FieldDecl and IndirectFieldDecl with a name. 3693 for (auto *D : AnonRecord->decls()) { 3694 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3695 cast<NamedDecl>(D)->getDeclName()) { 3696 ValueDecl *VD = cast<ValueDecl>(D); 3697 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3698 VD->getLocation(), diagKind)) { 3699 // C++ [class.union]p2: 3700 // The names of the members of an anonymous union shall be 3701 // distinct from the names of any other entity in the 3702 // scope in which the anonymous union is declared. 3703 Invalid = true; 3704 } else { 3705 // C++ [class.union]p2: 3706 // For the purpose of name lookup, after the anonymous union 3707 // definition, the members of the anonymous union are 3708 // considered to have been defined in the scope in which the 3709 // anonymous union is declared. 3710 unsigned OldChainingSize = Chaining.size(); 3711 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3712 for (auto *PI : IF->chain()) 3713 Chaining.push_back(PI); 3714 else 3715 Chaining.push_back(VD); 3716 3717 assert(Chaining.size() >= 2); 3718 NamedDecl **NamedChain = 3719 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3720 for (unsigned i = 0; i < Chaining.size(); i++) 3721 NamedChain[i] = Chaining[i]; 3722 3723 IndirectFieldDecl* IndirectField = 3724 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3725 VD->getIdentifier(), VD->getType(), 3726 NamedChain, Chaining.size()); 3727 3728 IndirectField->setAccess(AS); 3729 IndirectField->setImplicit(); 3730 SemaRef.PushOnScopeChains(IndirectField, S); 3731 3732 // That includes picking up the appropriate access specifier. 3733 if (AS != AS_none) IndirectField->setAccess(AS); 3734 3735 Chaining.resize(OldChainingSize); 3736 } 3737 } 3738 } 3739 3740 return Invalid; 3741 } 3742 3743 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3744 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3745 /// illegal input values are mapped to SC_None. 3746 static StorageClass 3747 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3748 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3749 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3750 "Parser allowed 'typedef' as storage class VarDecl."); 3751 switch (StorageClassSpec) { 3752 case DeclSpec::SCS_unspecified: return SC_None; 3753 case DeclSpec::SCS_extern: 3754 if (DS.isExternInLinkageSpec()) 3755 return SC_None; 3756 return SC_Extern; 3757 case DeclSpec::SCS_static: return SC_Static; 3758 case DeclSpec::SCS_auto: return SC_Auto; 3759 case DeclSpec::SCS_register: return SC_Register; 3760 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3761 // Illegal SCSs map to None: error reporting is up to the caller. 3762 case DeclSpec::SCS_mutable: // Fall through. 3763 case DeclSpec::SCS_typedef: return SC_None; 3764 } 3765 llvm_unreachable("unknown storage class specifier"); 3766 } 3767 3768 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3769 assert(Record->hasInClassInitializer()); 3770 3771 for (const auto *I : Record->decls()) { 3772 const auto *FD = dyn_cast<FieldDecl>(I); 3773 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3774 FD = IFD->getAnonField(); 3775 if (FD && FD->hasInClassInitializer()) 3776 return FD->getLocation(); 3777 } 3778 3779 llvm_unreachable("couldn't find in-class initializer"); 3780 } 3781 3782 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3783 SourceLocation DefaultInitLoc) { 3784 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3785 return; 3786 3787 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3788 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3789 } 3790 3791 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3792 CXXRecordDecl *AnonUnion) { 3793 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3794 return; 3795 3796 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3797 } 3798 3799 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3800 /// anonymous structure or union. Anonymous unions are a C++ feature 3801 /// (C++ [class.union]) and a C11 feature; anonymous structures 3802 /// are a C11 feature and GNU C++ extension. 3803 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3804 AccessSpecifier AS, 3805 RecordDecl *Record, 3806 const PrintingPolicy &Policy) { 3807 DeclContext *Owner = Record->getDeclContext(); 3808 3809 // Diagnose whether this anonymous struct/union is an extension. 3810 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3811 Diag(Record->getLocation(), diag::ext_anonymous_union); 3812 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3813 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3814 else if (!Record->isUnion() && !getLangOpts().C11) 3815 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3816 3817 // C and C++ require different kinds of checks for anonymous 3818 // structs/unions. 3819 bool Invalid = false; 3820 if (getLangOpts().CPlusPlus) { 3821 const char *PrevSpec = nullptr; 3822 unsigned DiagID; 3823 if (Record->isUnion()) { 3824 // C++ [class.union]p6: 3825 // Anonymous unions declared in a named namespace or in the 3826 // global namespace shall be declared static. 3827 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3828 (isa<TranslationUnitDecl>(Owner) || 3829 (isa<NamespaceDecl>(Owner) && 3830 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3831 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3832 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3833 3834 // Recover by adding 'static'. 3835 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3836 PrevSpec, DiagID, Policy); 3837 } 3838 // C++ [class.union]p6: 3839 // A storage class is not allowed in a declaration of an 3840 // anonymous union in a class scope. 3841 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3842 isa<RecordDecl>(Owner)) { 3843 Diag(DS.getStorageClassSpecLoc(), 3844 diag::err_anonymous_union_with_storage_spec) 3845 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3846 3847 // Recover by removing the storage specifier. 3848 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3849 SourceLocation(), 3850 PrevSpec, DiagID, Context.getPrintingPolicy()); 3851 } 3852 } 3853 3854 // Ignore const/volatile/restrict qualifiers. 3855 if (DS.getTypeQualifiers()) { 3856 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3857 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3858 << Record->isUnion() << "const" 3859 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3860 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3861 Diag(DS.getVolatileSpecLoc(), 3862 diag::ext_anonymous_struct_union_qualified) 3863 << Record->isUnion() << "volatile" 3864 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3865 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3866 Diag(DS.getRestrictSpecLoc(), 3867 diag::ext_anonymous_struct_union_qualified) 3868 << Record->isUnion() << "restrict" 3869 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3870 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3871 Diag(DS.getAtomicSpecLoc(), 3872 diag::ext_anonymous_struct_union_qualified) 3873 << Record->isUnion() << "_Atomic" 3874 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3875 3876 DS.ClearTypeQualifiers(); 3877 } 3878 3879 // C++ [class.union]p2: 3880 // The member-specification of an anonymous union shall only 3881 // define non-static data members. [Note: nested types and 3882 // functions cannot be declared within an anonymous union. ] 3883 for (auto *Mem : Record->decls()) { 3884 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3885 // C++ [class.union]p3: 3886 // An anonymous union shall not have private or protected 3887 // members (clause 11). 3888 assert(FD->getAccess() != AS_none); 3889 if (FD->getAccess() != AS_public) { 3890 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3891 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3892 Invalid = true; 3893 } 3894 3895 // C++ [class.union]p1 3896 // An object of a class with a non-trivial constructor, a non-trivial 3897 // copy constructor, a non-trivial destructor, or a non-trivial copy 3898 // assignment operator cannot be a member of a union, nor can an 3899 // array of such objects. 3900 if (CheckNontrivialField(FD)) 3901 Invalid = true; 3902 } else if (Mem->isImplicit()) { 3903 // Any implicit members are fine. 3904 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3905 // This is a type that showed up in an 3906 // elaborated-type-specifier inside the anonymous struct or 3907 // union, but which actually declares a type outside of the 3908 // anonymous struct or union. It's okay. 3909 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3910 if (!MemRecord->isAnonymousStructOrUnion() && 3911 MemRecord->getDeclName()) { 3912 // Visual C++ allows type definition in anonymous struct or union. 3913 if (getLangOpts().MicrosoftExt) 3914 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3915 << (int)Record->isUnion(); 3916 else { 3917 // This is a nested type declaration. 3918 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3919 << (int)Record->isUnion(); 3920 Invalid = true; 3921 } 3922 } else { 3923 // This is an anonymous type definition within another anonymous type. 3924 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3925 // not part of standard C++. 3926 Diag(MemRecord->getLocation(), 3927 diag::ext_anonymous_record_with_anonymous_type) 3928 << (int)Record->isUnion(); 3929 } 3930 } else if (isa<AccessSpecDecl>(Mem)) { 3931 // Any access specifier is fine. 3932 } else if (isa<StaticAssertDecl>(Mem)) { 3933 // In C++1z, static_assert declarations are also fine. 3934 } else { 3935 // We have something that isn't a non-static data 3936 // member. Complain about it. 3937 unsigned DK = diag::err_anonymous_record_bad_member; 3938 if (isa<TypeDecl>(Mem)) 3939 DK = diag::err_anonymous_record_with_type; 3940 else if (isa<FunctionDecl>(Mem)) 3941 DK = diag::err_anonymous_record_with_function; 3942 else if (isa<VarDecl>(Mem)) 3943 DK = diag::err_anonymous_record_with_static; 3944 3945 // Visual C++ allows type definition in anonymous struct or union. 3946 if (getLangOpts().MicrosoftExt && 3947 DK == diag::err_anonymous_record_with_type) 3948 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3949 << (int)Record->isUnion(); 3950 else { 3951 Diag(Mem->getLocation(), DK) 3952 << (int)Record->isUnion(); 3953 Invalid = true; 3954 } 3955 } 3956 } 3957 3958 // C++11 [class.union]p8 (DR1460): 3959 // At most one variant member of a union may have a 3960 // brace-or-equal-initializer. 3961 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3962 Owner->isRecord()) 3963 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3964 cast<CXXRecordDecl>(Record)); 3965 } 3966 3967 if (!Record->isUnion() && !Owner->isRecord()) { 3968 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3969 << (int)getLangOpts().CPlusPlus; 3970 Invalid = true; 3971 } 3972 3973 // Mock up a declarator. 3974 Declarator Dc(DS, Declarator::MemberContext); 3975 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3976 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3977 3978 // Create a declaration for this anonymous struct/union. 3979 NamedDecl *Anon = nullptr; 3980 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3981 Anon = FieldDecl::Create(Context, OwningClass, 3982 DS.getLocStart(), 3983 Record->getLocation(), 3984 /*IdentifierInfo=*/nullptr, 3985 Context.getTypeDeclType(Record), 3986 TInfo, 3987 /*BitWidth=*/nullptr, /*Mutable=*/false, 3988 /*InitStyle=*/ICIS_NoInit); 3989 Anon->setAccess(AS); 3990 if (getLangOpts().CPlusPlus) 3991 FieldCollector->Add(cast<FieldDecl>(Anon)); 3992 } else { 3993 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3994 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3995 if (SCSpec == DeclSpec::SCS_mutable) { 3996 // mutable can only appear on non-static class members, so it's always 3997 // an error here 3998 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3999 Invalid = true; 4000 SC = SC_None; 4001 } 4002 4003 Anon = VarDecl::Create(Context, Owner, 4004 DS.getLocStart(), 4005 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4006 Context.getTypeDeclType(Record), 4007 TInfo, SC); 4008 4009 // Default-initialize the implicit variable. This initialization will be 4010 // trivial in almost all cases, except if a union member has an in-class 4011 // initializer: 4012 // union { int n = 0; }; 4013 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4014 } 4015 Anon->setImplicit(); 4016 4017 // Mark this as an anonymous struct/union type. 4018 Record->setAnonymousStructOrUnion(true); 4019 4020 // Add the anonymous struct/union object to the current 4021 // context. We'll be referencing this object when we refer to one of 4022 // its members. 4023 Owner->addDecl(Anon); 4024 4025 // Inject the members of the anonymous struct/union into the owning 4026 // context and into the identifier resolver chain for name lookup 4027 // purposes. 4028 SmallVector<NamedDecl*, 2> Chain; 4029 Chain.push_back(Anon); 4030 4031 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4032 Chain, false)) 4033 Invalid = true; 4034 4035 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4036 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4037 Decl *ManglingContextDecl; 4038 if (MangleNumberingContext *MCtx = 4039 getCurrentMangleNumberContext(NewVD->getDeclContext(), 4040 ManglingContextDecl)) { 4041 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 4042 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4043 } 4044 } 4045 } 4046 4047 if (Invalid) 4048 Anon->setInvalidDecl(); 4049 4050 return Anon; 4051 } 4052 4053 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4054 /// Microsoft C anonymous structure. 4055 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4056 /// Example: 4057 /// 4058 /// struct A { int a; }; 4059 /// struct B { struct A; int b; }; 4060 /// 4061 /// void foo() { 4062 /// B var; 4063 /// var.a = 3; 4064 /// } 4065 /// 4066 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4067 RecordDecl *Record) { 4068 assert(Record && "expected a record!"); 4069 4070 // Mock up a declarator. 4071 Declarator Dc(DS, Declarator::TypeNameContext); 4072 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4073 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4074 4075 auto *ParentDecl = cast<RecordDecl>(CurContext); 4076 QualType RecTy = Context.getTypeDeclType(Record); 4077 4078 // Create a declaration for this anonymous struct. 4079 NamedDecl *Anon = FieldDecl::Create(Context, 4080 ParentDecl, 4081 DS.getLocStart(), 4082 DS.getLocStart(), 4083 /*IdentifierInfo=*/nullptr, 4084 RecTy, 4085 TInfo, 4086 /*BitWidth=*/nullptr, /*Mutable=*/false, 4087 /*InitStyle=*/ICIS_NoInit); 4088 Anon->setImplicit(); 4089 4090 // Add the anonymous struct object to the current context. 4091 CurContext->addDecl(Anon); 4092 4093 // Inject the members of the anonymous struct into the current 4094 // context and into the identifier resolver chain for name lookup 4095 // purposes. 4096 SmallVector<NamedDecl*, 2> Chain; 4097 Chain.push_back(Anon); 4098 4099 RecordDecl *RecordDef = Record->getDefinition(); 4100 if (RequireCompleteType(Anon->getLocation(), RecTy, 4101 diag::err_field_incomplete) || 4102 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4103 AS_none, Chain, true)) { 4104 Anon->setInvalidDecl(); 4105 ParentDecl->setInvalidDecl(); 4106 } 4107 4108 return Anon; 4109 } 4110 4111 /// GetNameForDeclarator - Determine the full declaration name for the 4112 /// given Declarator. 4113 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4114 return GetNameFromUnqualifiedId(D.getName()); 4115 } 4116 4117 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4118 DeclarationNameInfo 4119 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4120 DeclarationNameInfo NameInfo; 4121 NameInfo.setLoc(Name.StartLocation); 4122 4123 switch (Name.getKind()) { 4124 4125 case UnqualifiedId::IK_ImplicitSelfParam: 4126 case UnqualifiedId::IK_Identifier: 4127 NameInfo.setName(Name.Identifier); 4128 NameInfo.setLoc(Name.StartLocation); 4129 return NameInfo; 4130 4131 case UnqualifiedId::IK_OperatorFunctionId: 4132 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4133 Name.OperatorFunctionId.Operator)); 4134 NameInfo.setLoc(Name.StartLocation); 4135 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4136 = Name.OperatorFunctionId.SymbolLocations[0]; 4137 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4138 = Name.EndLocation.getRawEncoding(); 4139 return NameInfo; 4140 4141 case UnqualifiedId::IK_LiteralOperatorId: 4142 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4143 Name.Identifier)); 4144 NameInfo.setLoc(Name.StartLocation); 4145 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4146 return NameInfo; 4147 4148 case UnqualifiedId::IK_ConversionFunctionId: { 4149 TypeSourceInfo *TInfo; 4150 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4151 if (Ty.isNull()) 4152 return DeclarationNameInfo(); 4153 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4154 Context.getCanonicalType(Ty))); 4155 NameInfo.setLoc(Name.StartLocation); 4156 NameInfo.setNamedTypeInfo(TInfo); 4157 return NameInfo; 4158 } 4159 4160 case UnqualifiedId::IK_ConstructorName: { 4161 TypeSourceInfo *TInfo; 4162 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4163 if (Ty.isNull()) 4164 return DeclarationNameInfo(); 4165 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4166 Context.getCanonicalType(Ty))); 4167 NameInfo.setLoc(Name.StartLocation); 4168 NameInfo.setNamedTypeInfo(TInfo); 4169 return NameInfo; 4170 } 4171 4172 case UnqualifiedId::IK_ConstructorTemplateId: { 4173 // In well-formed code, we can only have a constructor 4174 // template-id that refers to the current context, so go there 4175 // to find the actual type being constructed. 4176 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4177 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4178 return DeclarationNameInfo(); 4179 4180 // Determine the type of the class being constructed. 4181 QualType CurClassType = Context.getTypeDeclType(CurClass); 4182 4183 // FIXME: Check two things: that the template-id names the same type as 4184 // CurClassType, and that the template-id does not occur when the name 4185 // was qualified. 4186 4187 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4188 Context.getCanonicalType(CurClassType))); 4189 NameInfo.setLoc(Name.StartLocation); 4190 // FIXME: should we retrieve TypeSourceInfo? 4191 NameInfo.setNamedTypeInfo(nullptr); 4192 return NameInfo; 4193 } 4194 4195 case UnqualifiedId::IK_DestructorName: { 4196 TypeSourceInfo *TInfo; 4197 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4198 if (Ty.isNull()) 4199 return DeclarationNameInfo(); 4200 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4201 Context.getCanonicalType(Ty))); 4202 NameInfo.setLoc(Name.StartLocation); 4203 NameInfo.setNamedTypeInfo(TInfo); 4204 return NameInfo; 4205 } 4206 4207 case UnqualifiedId::IK_TemplateId: { 4208 TemplateName TName = Name.TemplateId->Template.get(); 4209 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4210 return Context.getNameForTemplate(TName, TNameLoc); 4211 } 4212 4213 } // switch (Name.getKind()) 4214 4215 llvm_unreachable("Unknown name kind"); 4216 } 4217 4218 static QualType getCoreType(QualType Ty) { 4219 do { 4220 if (Ty->isPointerType() || Ty->isReferenceType()) 4221 Ty = Ty->getPointeeType(); 4222 else if (Ty->isArrayType()) 4223 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4224 else 4225 return Ty.withoutLocalFastQualifiers(); 4226 } while (true); 4227 } 4228 4229 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4230 /// and Definition have "nearly" matching parameters. This heuristic is 4231 /// used to improve diagnostics in the case where an out-of-line function 4232 /// definition doesn't match any declaration within the class or namespace. 4233 /// Also sets Params to the list of indices to the parameters that differ 4234 /// between the declaration and the definition. If hasSimilarParameters 4235 /// returns true and Params is empty, then all of the parameters match. 4236 static bool hasSimilarParameters(ASTContext &Context, 4237 FunctionDecl *Declaration, 4238 FunctionDecl *Definition, 4239 SmallVectorImpl<unsigned> &Params) { 4240 Params.clear(); 4241 if (Declaration->param_size() != Definition->param_size()) 4242 return false; 4243 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4244 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4245 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4246 4247 // The parameter types are identical 4248 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4249 continue; 4250 4251 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4252 QualType DefParamBaseTy = getCoreType(DefParamTy); 4253 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4254 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4255 4256 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4257 (DeclTyName && DeclTyName == DefTyName)) 4258 Params.push_back(Idx); 4259 else // The two parameters aren't even close 4260 return false; 4261 } 4262 4263 return true; 4264 } 4265 4266 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4267 /// declarator needs to be rebuilt in the current instantiation. 4268 /// Any bits of declarator which appear before the name are valid for 4269 /// consideration here. That's specifically the type in the decl spec 4270 /// and the base type in any member-pointer chunks. 4271 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4272 DeclarationName Name) { 4273 // The types we specifically need to rebuild are: 4274 // - typenames, typeofs, and decltypes 4275 // - types which will become injected class names 4276 // Of course, we also need to rebuild any type referencing such a 4277 // type. It's safest to just say "dependent", but we call out a 4278 // few cases here. 4279 4280 DeclSpec &DS = D.getMutableDeclSpec(); 4281 switch (DS.getTypeSpecType()) { 4282 case DeclSpec::TST_typename: 4283 case DeclSpec::TST_typeofType: 4284 case DeclSpec::TST_underlyingType: 4285 case DeclSpec::TST_atomic: { 4286 // Grab the type from the parser. 4287 TypeSourceInfo *TSI = nullptr; 4288 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4289 if (T.isNull() || !T->isDependentType()) break; 4290 4291 // Make sure there's a type source info. This isn't really much 4292 // of a waste; most dependent types should have type source info 4293 // attached already. 4294 if (!TSI) 4295 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4296 4297 // Rebuild the type in the current instantiation. 4298 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4299 if (!TSI) return true; 4300 4301 // Store the new type back in the decl spec. 4302 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4303 DS.UpdateTypeRep(LocType); 4304 break; 4305 } 4306 4307 case DeclSpec::TST_decltype: 4308 case DeclSpec::TST_typeofExpr: { 4309 Expr *E = DS.getRepAsExpr(); 4310 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4311 if (Result.isInvalid()) return true; 4312 DS.UpdateExprRep(Result.get()); 4313 break; 4314 } 4315 4316 default: 4317 // Nothing to do for these decl specs. 4318 break; 4319 } 4320 4321 // It doesn't matter what order we do this in. 4322 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4323 DeclaratorChunk &Chunk = D.getTypeObject(I); 4324 4325 // The only type information in the declarator which can come 4326 // before the declaration name is the base type of a member 4327 // pointer. 4328 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4329 continue; 4330 4331 // Rebuild the scope specifier in-place. 4332 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4333 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4334 return true; 4335 } 4336 4337 return false; 4338 } 4339 4340 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4341 D.setFunctionDefinitionKind(FDK_Declaration); 4342 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4343 4344 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4345 Dcl && Dcl->getDeclContext()->isFileContext()) 4346 Dcl->setTopLevelDeclInObjCContainer(); 4347 4348 return Dcl; 4349 } 4350 4351 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4352 /// If T is the name of a class, then each of the following shall have a 4353 /// name different from T: 4354 /// - every static data member of class T; 4355 /// - every member function of class T 4356 /// - every member of class T that is itself a type; 4357 /// \returns true if the declaration name violates these rules. 4358 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4359 DeclarationNameInfo NameInfo) { 4360 DeclarationName Name = NameInfo.getName(); 4361 4362 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4363 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4364 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4365 return true; 4366 } 4367 4368 return false; 4369 } 4370 4371 /// \brief Diagnose a declaration whose declarator-id has the given 4372 /// nested-name-specifier. 4373 /// 4374 /// \param SS The nested-name-specifier of the declarator-id. 4375 /// 4376 /// \param DC The declaration context to which the nested-name-specifier 4377 /// resolves. 4378 /// 4379 /// \param Name The name of the entity being declared. 4380 /// 4381 /// \param Loc The location of the name of the entity being declared. 4382 /// 4383 /// \returns true if we cannot safely recover from this error, false otherwise. 4384 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4385 DeclarationName Name, 4386 SourceLocation Loc) { 4387 DeclContext *Cur = CurContext; 4388 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4389 Cur = Cur->getParent(); 4390 4391 // If the user provided a superfluous scope specifier that refers back to the 4392 // class in which the entity is already declared, diagnose and ignore it. 4393 // 4394 // class X { 4395 // void X::f(); 4396 // }; 4397 // 4398 // Note, it was once ill-formed to give redundant qualification in all 4399 // contexts, but that rule was removed by DR482. 4400 if (Cur->Equals(DC)) { 4401 if (Cur->isRecord()) { 4402 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4403 : diag::err_member_extra_qualification) 4404 << Name << FixItHint::CreateRemoval(SS.getRange()); 4405 SS.clear(); 4406 } else { 4407 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4408 } 4409 return false; 4410 } 4411 4412 // Check whether the qualifying scope encloses the scope of the original 4413 // declaration. 4414 if (!Cur->Encloses(DC)) { 4415 if (Cur->isRecord()) 4416 Diag(Loc, diag::err_member_qualification) 4417 << Name << SS.getRange(); 4418 else if (isa<TranslationUnitDecl>(DC)) 4419 Diag(Loc, diag::err_invalid_declarator_global_scope) 4420 << Name << SS.getRange(); 4421 else if (isa<FunctionDecl>(Cur)) 4422 Diag(Loc, diag::err_invalid_declarator_in_function) 4423 << Name << SS.getRange(); 4424 else if (isa<BlockDecl>(Cur)) 4425 Diag(Loc, diag::err_invalid_declarator_in_block) 4426 << Name << SS.getRange(); 4427 else 4428 Diag(Loc, diag::err_invalid_declarator_scope) 4429 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4430 4431 return true; 4432 } 4433 4434 if (Cur->isRecord()) { 4435 // Cannot qualify members within a class. 4436 Diag(Loc, diag::err_member_qualification) 4437 << Name << SS.getRange(); 4438 SS.clear(); 4439 4440 // C++ constructors and destructors with incorrect scopes can break 4441 // our AST invariants by having the wrong underlying types. If 4442 // that's the case, then drop this declaration entirely. 4443 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4444 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4445 !Context.hasSameType(Name.getCXXNameType(), 4446 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4447 return true; 4448 4449 return false; 4450 } 4451 4452 // C++11 [dcl.meaning]p1: 4453 // [...] "The nested-name-specifier of the qualified declarator-id shall 4454 // not begin with a decltype-specifer" 4455 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4456 while (SpecLoc.getPrefix()) 4457 SpecLoc = SpecLoc.getPrefix(); 4458 if (dyn_cast_or_null<DecltypeType>( 4459 SpecLoc.getNestedNameSpecifier()->getAsType())) 4460 Diag(Loc, diag::err_decltype_in_declarator) 4461 << SpecLoc.getTypeLoc().getSourceRange(); 4462 4463 return false; 4464 } 4465 4466 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4467 MultiTemplateParamsArg TemplateParamLists) { 4468 // TODO: consider using NameInfo for diagnostic. 4469 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4470 DeclarationName Name = NameInfo.getName(); 4471 4472 // All of these full declarators require an identifier. If it doesn't have 4473 // one, the ParsedFreeStandingDeclSpec action should be used. 4474 if (!Name) { 4475 if (!D.isInvalidType()) // Reject this if we think it is valid. 4476 Diag(D.getDeclSpec().getLocStart(), 4477 diag::err_declarator_need_ident) 4478 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4479 return nullptr; 4480 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4481 return nullptr; 4482 4483 // The scope passed in may not be a decl scope. Zip up the scope tree until 4484 // we find one that is. 4485 while ((S->getFlags() & Scope::DeclScope) == 0 || 4486 (S->getFlags() & Scope::TemplateParamScope) != 0) 4487 S = S->getParent(); 4488 4489 DeclContext *DC = CurContext; 4490 if (D.getCXXScopeSpec().isInvalid()) 4491 D.setInvalidType(); 4492 else if (D.getCXXScopeSpec().isSet()) { 4493 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4494 UPPC_DeclarationQualifier)) 4495 return nullptr; 4496 4497 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4498 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4499 if (!DC || isa<EnumDecl>(DC)) { 4500 // If we could not compute the declaration context, it's because the 4501 // declaration context is dependent but does not refer to a class, 4502 // class template, or class template partial specialization. Complain 4503 // and return early, to avoid the coming semantic disaster. 4504 Diag(D.getIdentifierLoc(), 4505 diag::err_template_qualified_declarator_no_match) 4506 << D.getCXXScopeSpec().getScopeRep() 4507 << D.getCXXScopeSpec().getRange(); 4508 return nullptr; 4509 } 4510 bool IsDependentContext = DC->isDependentContext(); 4511 4512 if (!IsDependentContext && 4513 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4514 return nullptr; 4515 4516 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4517 Diag(D.getIdentifierLoc(), 4518 diag::err_member_def_undefined_record) 4519 << Name << DC << D.getCXXScopeSpec().getRange(); 4520 D.setInvalidType(); 4521 } else if (!D.getDeclSpec().isFriendSpecified()) { 4522 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4523 Name, D.getIdentifierLoc())) { 4524 if (DC->isRecord()) 4525 return nullptr; 4526 4527 D.setInvalidType(); 4528 } 4529 } 4530 4531 // Check whether we need to rebuild the type of the given 4532 // declaration in the current instantiation. 4533 if (EnteringContext && IsDependentContext && 4534 TemplateParamLists.size() != 0) { 4535 ContextRAII SavedContext(*this, DC); 4536 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4537 D.setInvalidType(); 4538 } 4539 } 4540 4541 if (DiagnoseClassNameShadow(DC, NameInfo)) 4542 // If this is a typedef, we'll end up spewing multiple diagnostics. 4543 // Just return early; it's safer. 4544 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4545 return nullptr; 4546 4547 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4548 QualType R = TInfo->getType(); 4549 4550 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4551 UPPC_DeclarationType)) 4552 D.setInvalidType(); 4553 4554 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4555 ForRedeclaration); 4556 4557 // See if this is a redefinition of a variable in the same scope. 4558 if (!D.getCXXScopeSpec().isSet()) { 4559 bool IsLinkageLookup = false; 4560 bool CreateBuiltins = false; 4561 4562 // If the declaration we're planning to build will be a function 4563 // or object with linkage, then look for another declaration with 4564 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4565 // 4566 // If the declaration we're planning to build will be declared with 4567 // external linkage in the translation unit, create any builtin with 4568 // the same name. 4569 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4570 /* Do nothing*/; 4571 else if (CurContext->isFunctionOrMethod() && 4572 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4573 R->isFunctionType())) { 4574 IsLinkageLookup = true; 4575 CreateBuiltins = 4576 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4577 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4578 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4579 CreateBuiltins = true; 4580 4581 if (IsLinkageLookup) 4582 Previous.clear(LookupRedeclarationWithLinkage); 4583 4584 LookupName(Previous, S, CreateBuiltins); 4585 } else { // Something like "int foo::x;" 4586 LookupQualifiedName(Previous, DC); 4587 4588 // C++ [dcl.meaning]p1: 4589 // When the declarator-id is qualified, the declaration shall refer to a 4590 // previously declared member of the class or namespace to which the 4591 // qualifier refers (or, in the case of a namespace, of an element of the 4592 // inline namespace set of that namespace (7.3.1)) or to a specialization 4593 // thereof; [...] 4594 // 4595 // Note that we already checked the context above, and that we do not have 4596 // enough information to make sure that Previous contains the declaration 4597 // we want to match. For example, given: 4598 // 4599 // class X { 4600 // void f(); 4601 // void f(float); 4602 // }; 4603 // 4604 // void X::f(int) { } // ill-formed 4605 // 4606 // In this case, Previous will point to the overload set 4607 // containing the two f's declared in X, but neither of them 4608 // matches. 4609 4610 // C++ [dcl.meaning]p1: 4611 // [...] the member shall not merely have been introduced by a 4612 // using-declaration in the scope of the class or namespace nominated by 4613 // the nested-name-specifier of the declarator-id. 4614 RemoveUsingDecls(Previous); 4615 } 4616 4617 if (Previous.isSingleResult() && 4618 Previous.getFoundDecl()->isTemplateParameter()) { 4619 // Maybe we will complain about the shadowed template parameter. 4620 if (!D.isInvalidType()) 4621 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4622 Previous.getFoundDecl()); 4623 4624 // Just pretend that we didn't see the previous declaration. 4625 Previous.clear(); 4626 } 4627 4628 // In C++, the previous declaration we find might be a tag type 4629 // (class or enum). In this case, the new declaration will hide the 4630 // tag type. Note that this does does not apply if we're declaring a 4631 // typedef (C++ [dcl.typedef]p4). 4632 if (Previous.isSingleTagDecl() && 4633 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4634 Previous.clear(); 4635 4636 // Check that there are no default arguments other than in the parameters 4637 // of a function declaration (C++ only). 4638 if (getLangOpts().CPlusPlus) 4639 CheckExtraCXXDefaultArguments(D); 4640 4641 NamedDecl *New; 4642 4643 bool AddToScope = true; 4644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4645 if (TemplateParamLists.size()) { 4646 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4647 return nullptr; 4648 } 4649 4650 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4651 } else if (R->isFunctionType()) { 4652 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4653 TemplateParamLists, 4654 AddToScope); 4655 } else { 4656 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4657 AddToScope); 4658 } 4659 4660 if (!New) 4661 return nullptr; 4662 4663 // If this has an identifier and is not an invalid redeclaration or 4664 // function template specialization, add it to the scope stack. 4665 if (New->getDeclName() && AddToScope && 4666 !(D.isRedeclaration() && New->isInvalidDecl())) { 4667 // Only make a locally-scoped extern declaration visible if it is the first 4668 // declaration of this entity. Qualified lookup for such an entity should 4669 // only find this declaration if there is no visible declaration of it. 4670 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4671 PushOnScopeChains(New, S, AddToContext); 4672 if (!AddToContext) 4673 CurContext->addHiddenDecl(New); 4674 } 4675 4676 return New; 4677 } 4678 4679 /// Helper method to turn variable array types into constant array 4680 /// types in certain situations which would otherwise be errors (for 4681 /// GCC compatibility). 4682 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4683 ASTContext &Context, 4684 bool &SizeIsNegative, 4685 llvm::APSInt &Oversized) { 4686 // This method tries to turn a variable array into a constant 4687 // array even when the size isn't an ICE. This is necessary 4688 // for compatibility with code that depends on gcc's buggy 4689 // constant expression folding, like struct {char x[(int)(char*)2];} 4690 SizeIsNegative = false; 4691 Oversized = 0; 4692 4693 if (T->isDependentType()) 4694 return QualType(); 4695 4696 QualifierCollector Qs; 4697 const Type *Ty = Qs.strip(T); 4698 4699 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4700 QualType Pointee = PTy->getPointeeType(); 4701 QualType FixedType = 4702 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4703 Oversized); 4704 if (FixedType.isNull()) return FixedType; 4705 FixedType = Context.getPointerType(FixedType); 4706 return Qs.apply(Context, FixedType); 4707 } 4708 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4709 QualType Inner = PTy->getInnerType(); 4710 QualType FixedType = 4711 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4712 Oversized); 4713 if (FixedType.isNull()) return FixedType; 4714 FixedType = Context.getParenType(FixedType); 4715 return Qs.apply(Context, FixedType); 4716 } 4717 4718 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4719 if (!VLATy) 4720 return QualType(); 4721 // FIXME: We should probably handle this case 4722 if (VLATy->getElementType()->isVariablyModifiedType()) 4723 return QualType(); 4724 4725 llvm::APSInt Res; 4726 if (!VLATy->getSizeExpr() || 4727 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4728 return QualType(); 4729 4730 // Check whether the array size is negative. 4731 if (Res.isSigned() && Res.isNegative()) { 4732 SizeIsNegative = true; 4733 return QualType(); 4734 } 4735 4736 // Check whether the array is too large to be addressed. 4737 unsigned ActiveSizeBits 4738 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4739 Res); 4740 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4741 Oversized = Res; 4742 return QualType(); 4743 } 4744 4745 return Context.getConstantArrayType(VLATy->getElementType(), 4746 Res, ArrayType::Normal, 0); 4747 } 4748 4749 static void 4750 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4751 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4752 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4753 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4754 DstPTL.getPointeeLoc()); 4755 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4756 return; 4757 } 4758 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4759 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4760 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4761 DstPTL.getInnerLoc()); 4762 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4763 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4764 return; 4765 } 4766 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4767 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4768 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4769 TypeLoc DstElemTL = DstATL.getElementLoc(); 4770 DstElemTL.initializeFullCopy(SrcElemTL); 4771 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4772 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4773 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4774 } 4775 4776 /// Helper method to turn variable array types into constant array 4777 /// types in certain situations which would otherwise be errors (for 4778 /// GCC compatibility). 4779 static TypeSourceInfo* 4780 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4781 ASTContext &Context, 4782 bool &SizeIsNegative, 4783 llvm::APSInt &Oversized) { 4784 QualType FixedTy 4785 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4786 SizeIsNegative, Oversized); 4787 if (FixedTy.isNull()) 4788 return nullptr; 4789 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4790 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4791 FixedTInfo->getTypeLoc()); 4792 return FixedTInfo; 4793 } 4794 4795 /// \brief Register the given locally-scoped extern "C" declaration so 4796 /// that it can be found later for redeclarations. We include any extern "C" 4797 /// declaration that is not visible in the translation unit here, not just 4798 /// function-scope declarations. 4799 void 4800 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4801 if (!getLangOpts().CPlusPlus && 4802 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4803 // Don't need to track declarations in the TU in C. 4804 return; 4805 4806 // Note that we have a locally-scoped external with this name. 4807 // FIXME: There can be multiple such declarations if they are functions marked 4808 // __attribute__((overloadable)) declared in function scope in C. 4809 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4810 } 4811 4812 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4813 if (ExternalSource) { 4814 // Load locally-scoped external decls from the external source. 4815 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4816 SmallVector<NamedDecl *, 4> Decls; 4817 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4818 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4819 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4820 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4821 if (Pos == LocallyScopedExternCDecls.end()) 4822 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4823 } 4824 } 4825 4826 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4827 return D ? D->getMostRecentDecl() : nullptr; 4828 } 4829 4830 /// \brief Diagnose function specifiers on a declaration of an identifier that 4831 /// does not identify a function. 4832 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4833 // FIXME: We should probably indicate the identifier in question to avoid 4834 // confusion for constructs like "inline int a(), b;" 4835 if (DS.isInlineSpecified()) 4836 Diag(DS.getInlineSpecLoc(), 4837 diag::err_inline_non_function); 4838 4839 if (DS.isVirtualSpecified()) 4840 Diag(DS.getVirtualSpecLoc(), 4841 diag::err_virtual_non_function); 4842 4843 if (DS.isExplicitSpecified()) 4844 Diag(DS.getExplicitSpecLoc(), 4845 diag::err_explicit_non_function); 4846 4847 if (DS.isNoreturnSpecified()) 4848 Diag(DS.getNoreturnSpecLoc(), 4849 diag::err_noreturn_non_function); 4850 } 4851 4852 NamedDecl* 4853 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4854 TypeSourceInfo *TInfo, LookupResult &Previous) { 4855 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4856 if (D.getCXXScopeSpec().isSet()) { 4857 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4858 << D.getCXXScopeSpec().getRange(); 4859 D.setInvalidType(); 4860 // Pretend we didn't see the scope specifier. 4861 DC = CurContext; 4862 Previous.clear(); 4863 } 4864 4865 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4866 4867 if (D.getDeclSpec().isConstexprSpecified()) 4868 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4869 << 1; 4870 4871 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4872 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4873 << D.getName().getSourceRange(); 4874 return nullptr; 4875 } 4876 4877 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4878 if (!NewTD) return nullptr; 4879 4880 // Handle attributes prior to checking for duplicates in MergeVarDecl 4881 ProcessDeclAttributes(S, NewTD, D); 4882 4883 CheckTypedefForVariablyModifiedType(S, NewTD); 4884 4885 bool Redeclaration = D.isRedeclaration(); 4886 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4887 D.setRedeclaration(Redeclaration); 4888 return ND; 4889 } 4890 4891 void 4892 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4893 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4894 // then it shall have block scope. 4895 // Note that variably modified types must be fixed before merging the decl so 4896 // that redeclarations will match. 4897 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4898 QualType T = TInfo->getType(); 4899 if (T->isVariablyModifiedType()) { 4900 getCurFunction()->setHasBranchProtectedScope(); 4901 4902 if (S->getFnParent() == nullptr) { 4903 bool SizeIsNegative; 4904 llvm::APSInt Oversized; 4905 TypeSourceInfo *FixedTInfo = 4906 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4907 SizeIsNegative, 4908 Oversized); 4909 if (FixedTInfo) { 4910 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4911 NewTD->setTypeSourceInfo(FixedTInfo); 4912 } else { 4913 if (SizeIsNegative) 4914 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4915 else if (T->isVariableArrayType()) 4916 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4917 else if (Oversized.getBoolValue()) 4918 Diag(NewTD->getLocation(), diag::err_array_too_large) 4919 << Oversized.toString(10); 4920 else 4921 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4922 NewTD->setInvalidDecl(); 4923 } 4924 } 4925 } 4926 } 4927 4928 4929 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4930 /// declares a typedef-name, either using the 'typedef' type specifier or via 4931 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4932 NamedDecl* 4933 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4934 LookupResult &Previous, bool &Redeclaration) { 4935 // Merge the decl with the existing one if appropriate. If the decl is 4936 // in an outer scope, it isn't the same thing. 4937 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4938 /*AllowInlineNamespace*/false); 4939 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 4940 if (!Previous.empty()) { 4941 Redeclaration = true; 4942 MergeTypedefNameDecl(NewTD, Previous); 4943 } 4944 4945 // If this is the C FILE type, notify the AST context. 4946 if (IdentifierInfo *II = NewTD->getIdentifier()) 4947 if (!NewTD->isInvalidDecl() && 4948 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4949 if (II->isStr("FILE")) 4950 Context.setFILEDecl(NewTD); 4951 else if (II->isStr("jmp_buf")) 4952 Context.setjmp_bufDecl(NewTD); 4953 else if (II->isStr("sigjmp_buf")) 4954 Context.setsigjmp_bufDecl(NewTD); 4955 else if (II->isStr("ucontext_t")) 4956 Context.setucontext_tDecl(NewTD); 4957 } 4958 4959 return NewTD; 4960 } 4961 4962 /// \brief Determines whether the given declaration is an out-of-scope 4963 /// previous declaration. 4964 /// 4965 /// This routine should be invoked when name lookup has found a 4966 /// previous declaration (PrevDecl) that is not in the scope where a 4967 /// new declaration by the same name is being introduced. If the new 4968 /// declaration occurs in a local scope, previous declarations with 4969 /// linkage may still be considered previous declarations (C99 4970 /// 6.2.2p4-5, C++ [basic.link]p6). 4971 /// 4972 /// \param PrevDecl the previous declaration found by name 4973 /// lookup 4974 /// 4975 /// \param DC the context in which the new declaration is being 4976 /// declared. 4977 /// 4978 /// \returns true if PrevDecl is an out-of-scope previous declaration 4979 /// for a new delcaration with the same name. 4980 static bool 4981 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4982 ASTContext &Context) { 4983 if (!PrevDecl) 4984 return false; 4985 4986 if (!PrevDecl->hasLinkage()) 4987 return false; 4988 4989 if (Context.getLangOpts().CPlusPlus) { 4990 // C++ [basic.link]p6: 4991 // If there is a visible declaration of an entity with linkage 4992 // having the same name and type, ignoring entities declared 4993 // outside the innermost enclosing namespace scope, the block 4994 // scope declaration declares that same entity and receives the 4995 // linkage of the previous declaration. 4996 DeclContext *OuterContext = DC->getRedeclContext(); 4997 if (!OuterContext->isFunctionOrMethod()) 4998 // This rule only applies to block-scope declarations. 4999 return false; 5000 5001 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5002 if (PrevOuterContext->isRecord()) 5003 // We found a member function: ignore it. 5004 return false; 5005 5006 // Find the innermost enclosing namespace for the new and 5007 // previous declarations. 5008 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5009 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5010 5011 // The previous declaration is in a different namespace, so it 5012 // isn't the same function. 5013 if (!OuterContext->Equals(PrevOuterContext)) 5014 return false; 5015 } 5016 5017 return true; 5018 } 5019 5020 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5021 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5022 if (!SS.isSet()) return; 5023 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5024 } 5025 5026 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5027 QualType type = decl->getType(); 5028 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5029 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5030 // Various kinds of declaration aren't allowed to be __autoreleasing. 5031 unsigned kind = -1U; 5032 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5033 if (var->hasAttr<BlocksAttr>()) 5034 kind = 0; // __block 5035 else if (!var->hasLocalStorage()) 5036 kind = 1; // global 5037 } else if (isa<ObjCIvarDecl>(decl)) { 5038 kind = 3; // ivar 5039 } else if (isa<FieldDecl>(decl)) { 5040 kind = 2; // field 5041 } 5042 5043 if (kind != -1U) { 5044 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5045 << kind; 5046 } 5047 } else if (lifetime == Qualifiers::OCL_None) { 5048 // Try to infer lifetime. 5049 if (!type->isObjCLifetimeType()) 5050 return false; 5051 5052 lifetime = type->getObjCARCImplicitLifetime(); 5053 type = Context.getLifetimeQualifiedType(type, lifetime); 5054 decl->setType(type); 5055 } 5056 5057 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5058 // Thread-local variables cannot have lifetime. 5059 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5060 var->getTLSKind()) { 5061 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5062 << var->getType(); 5063 return true; 5064 } 5065 } 5066 5067 return false; 5068 } 5069 5070 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5071 // Ensure that an auto decl is deduced otherwise the checks below might cache 5072 // the wrong linkage. 5073 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5074 5075 // 'weak' only applies to declarations with external linkage. 5076 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5077 if (!ND.isExternallyVisible()) { 5078 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5079 ND.dropAttr<WeakAttr>(); 5080 } 5081 } 5082 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5083 if (ND.isExternallyVisible()) { 5084 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5085 ND.dropAttr<WeakRefAttr>(); 5086 } 5087 } 5088 5089 // 'selectany' only applies to externally visible varable declarations. 5090 // It does not apply to functions. 5091 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5092 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5093 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5094 ND.dropAttr<SelectAnyAttr>(); 5095 } 5096 } 5097 5098 // dll attributes require external linkage. 5099 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 5100 if (!ND.isExternallyVisible()) { 5101 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5102 << &ND << Attr; 5103 ND.setInvalidDecl(); 5104 } 5105 } 5106 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 5107 if (!ND.isExternallyVisible()) { 5108 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5109 << &ND << Attr; 5110 ND.setInvalidDecl(); 5111 } 5112 } 5113 } 5114 5115 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5116 NamedDecl *NewDecl, 5117 bool IsSpecialization) { 5118 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5119 OldDecl = OldTD->getTemplatedDecl(); 5120 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5121 NewDecl = NewTD->getTemplatedDecl(); 5122 5123 if (!OldDecl || !NewDecl) 5124 return; 5125 5126 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5127 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5128 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5129 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5130 5131 // dllimport and dllexport are inheritable attributes so we have to exclude 5132 // inherited attribute instances. 5133 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5134 (NewExportAttr && !NewExportAttr->isInherited()); 5135 5136 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5137 // the only exception being explicit specializations. 5138 // Implicitly generated declarations are also excluded for now because there 5139 // is no other way to switch these to use dllimport or dllexport. 5140 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5141 5142 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5143 // If the declaration hasn't been used yet, allow with a warning for 5144 // free functions and global variables. 5145 bool JustWarn = false; 5146 if (!OldDecl->isUsed() && OldDecl->getDeclContext()->isFileContext()) { 5147 auto *VD = dyn_cast<VarDecl>(OldDecl); 5148 if (VD && !VD->getDescribedVarTemplate()) 5149 JustWarn = true; 5150 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5151 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5152 JustWarn = true; 5153 } 5154 5155 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5156 : diag::err_attribute_dll_redeclaration; 5157 S.Diag(NewDecl->getLocation(), DiagID) 5158 << NewDecl 5159 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5160 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5161 if (!JustWarn) { 5162 NewDecl->setInvalidDecl(); 5163 return; 5164 } 5165 } 5166 5167 // A redeclaration is not allowed to drop a dllimport attribute, the only 5168 // exceptions being inline function definitions, local extern declarations, 5169 // and qualified friend declarations. 5170 // NB: MSVC converts such a declaration to dllexport. 5171 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5172 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5173 // Ignore static data because out-of-line definitions are diagnosed 5174 // separately. 5175 IsStaticDataMember = VD->isStaticDataMember(); 5176 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5177 IsInline = FD->isInlined(); 5178 IsQualifiedFriend = FD->getQualifier() && 5179 FD->getFriendObjectKind() == Decl::FOK_Declared; 5180 } 5181 5182 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5183 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5184 S.Diag(NewDecl->getLocation(), 5185 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5186 << NewDecl << OldImportAttr; 5187 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5188 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5189 OldDecl->dropAttr<DLLImportAttr>(); 5190 NewDecl->dropAttr<DLLImportAttr>(); 5191 } 5192 } 5193 5194 /// Given that we are within the definition of the given function, 5195 /// will that definition behave like C99's 'inline', where the 5196 /// definition is discarded except for optimization purposes? 5197 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5198 // Try to avoid calling GetGVALinkageForFunction. 5199 5200 // All cases of this require the 'inline' keyword. 5201 if (!FD->isInlined()) return false; 5202 5203 // This is only possible in C++ with the gnu_inline attribute. 5204 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5205 return false; 5206 5207 // Okay, go ahead and call the relatively-more-expensive function. 5208 5209 #ifndef NDEBUG 5210 // AST quite reasonably asserts that it's working on a function 5211 // definition. We don't really have a way to tell it that we're 5212 // currently defining the function, so just lie to it in +Asserts 5213 // builds. This is an awful hack. 5214 FD->setLazyBody(1); 5215 #endif 5216 5217 bool isC99Inline = 5218 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5219 5220 #ifndef NDEBUG 5221 FD->setLazyBody(0); 5222 #endif 5223 5224 return isC99Inline; 5225 } 5226 5227 /// Determine whether a variable is extern "C" prior to attaching 5228 /// an initializer. We can't just call isExternC() here, because that 5229 /// will also compute and cache whether the declaration is externally 5230 /// visible, which might change when we attach the initializer. 5231 /// 5232 /// This can only be used if the declaration is known to not be a 5233 /// redeclaration of an internal linkage declaration. 5234 /// 5235 /// For instance: 5236 /// 5237 /// auto x = []{}; 5238 /// 5239 /// Attaching the initializer here makes this declaration not externally 5240 /// visible, because its type has internal linkage. 5241 /// 5242 /// FIXME: This is a hack. 5243 template<typename T> 5244 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5245 if (S.getLangOpts().CPlusPlus) { 5246 // In C++, the overloadable attribute negates the effects of extern "C". 5247 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5248 return false; 5249 } 5250 return D->isExternC(); 5251 } 5252 5253 static bool shouldConsiderLinkage(const VarDecl *VD) { 5254 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5255 if (DC->isFunctionOrMethod()) 5256 return VD->hasExternalStorage(); 5257 if (DC->isFileContext()) 5258 return true; 5259 if (DC->isRecord()) 5260 return false; 5261 llvm_unreachable("Unexpected context"); 5262 } 5263 5264 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5265 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5266 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5267 return true; 5268 if (DC->isRecord()) 5269 return false; 5270 llvm_unreachable("Unexpected context"); 5271 } 5272 5273 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5274 AttributeList::Kind Kind) { 5275 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5276 if (L->getKind() == Kind) 5277 return true; 5278 return false; 5279 } 5280 5281 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5282 AttributeList::Kind Kind) { 5283 // Check decl attributes on the DeclSpec. 5284 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5285 return true; 5286 5287 // Walk the declarator structure, checking decl attributes that were in a type 5288 // position to the decl itself. 5289 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5290 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5291 return true; 5292 } 5293 5294 // Finally, check attributes on the decl itself. 5295 return hasParsedAttr(S, PD.getAttributes(), Kind); 5296 } 5297 5298 /// Adjust the \c DeclContext for a function or variable that might be a 5299 /// function-local external declaration. 5300 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5301 if (!DC->isFunctionOrMethod()) 5302 return false; 5303 5304 // If this is a local extern function or variable declared within a function 5305 // template, don't add it into the enclosing namespace scope until it is 5306 // instantiated; it might have a dependent type right now. 5307 if (DC->isDependentContext()) 5308 return true; 5309 5310 // C++11 [basic.link]p7: 5311 // When a block scope declaration of an entity with linkage is not found to 5312 // refer to some other declaration, then that entity is a member of the 5313 // innermost enclosing namespace. 5314 // 5315 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5316 // semantically-enclosing namespace, not a lexically-enclosing one. 5317 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5318 DC = DC->getParent(); 5319 return true; 5320 } 5321 5322 NamedDecl * 5323 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5324 TypeSourceInfo *TInfo, LookupResult &Previous, 5325 MultiTemplateParamsArg TemplateParamLists, 5326 bool &AddToScope) { 5327 QualType R = TInfo->getType(); 5328 DeclarationName Name = GetNameForDeclarator(D).getName(); 5329 5330 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5331 VarDecl::StorageClass SC = 5332 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5333 5334 // dllimport globals without explicit storage class are treated as extern. We 5335 // have to change the storage class this early to get the right DeclContext. 5336 if (SC == SC_None && !DC->isRecord() && 5337 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5338 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5339 SC = SC_Extern; 5340 5341 DeclContext *OriginalDC = DC; 5342 bool IsLocalExternDecl = SC == SC_Extern && 5343 adjustContextForLocalExternDecl(DC); 5344 5345 if (getLangOpts().OpenCL) { 5346 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5347 QualType NR = R; 5348 while (NR->isPointerType()) { 5349 if (NR->isFunctionPointerType()) { 5350 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5351 D.setInvalidType(); 5352 break; 5353 } 5354 NR = NR->getPointeeType(); 5355 } 5356 5357 if (!getOpenCLOptions().cl_khr_fp16) { 5358 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5359 // half array type (unless the cl_khr_fp16 extension is enabled). 5360 if (Context.getBaseElementType(R)->isHalfType()) { 5361 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5362 D.setInvalidType(); 5363 } 5364 } 5365 } 5366 5367 if (SCSpec == DeclSpec::SCS_mutable) { 5368 // mutable can only appear on non-static class members, so it's always 5369 // an error here 5370 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5371 D.setInvalidType(); 5372 SC = SC_None; 5373 } 5374 5375 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5376 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5377 D.getDeclSpec().getStorageClassSpecLoc())) { 5378 // In C++11, the 'register' storage class specifier is deprecated. 5379 // Suppress the warning in system macros, it's used in macros in some 5380 // popular C system headers, such as in glibc's htonl() macro. 5381 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5382 diag::warn_deprecated_register) 5383 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5384 } 5385 5386 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5387 if (!II) { 5388 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5389 << Name; 5390 return nullptr; 5391 } 5392 5393 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5394 5395 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5396 // C99 6.9p2: The storage-class specifiers auto and register shall not 5397 // appear in the declaration specifiers in an external declaration. 5398 // Global Register+Asm is a GNU extension we support. 5399 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5400 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5401 D.setInvalidType(); 5402 } 5403 } 5404 5405 if (getLangOpts().OpenCL) { 5406 // Set up the special work-group-local storage class for variables in the 5407 // OpenCL __local address space. 5408 if (R.getAddressSpace() == LangAS::opencl_local) { 5409 SC = SC_OpenCLWorkGroupLocal; 5410 } 5411 5412 // OpenCL v1.2 s6.9.b p4: 5413 // The sampler type cannot be used with the __local and __global address 5414 // space qualifiers. 5415 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5416 R.getAddressSpace() == LangAS::opencl_global)) { 5417 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5418 } 5419 5420 // OpenCL 1.2 spec, p6.9 r: 5421 // The event type cannot be used to declare a program scope variable. 5422 // The event type cannot be used with the __local, __constant and __global 5423 // address space qualifiers. 5424 if (R->isEventT()) { 5425 if (S->getParent() == nullptr) { 5426 Diag(D.getLocStart(), diag::err_event_t_global_var); 5427 D.setInvalidType(); 5428 } 5429 5430 if (R.getAddressSpace()) { 5431 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5432 D.setInvalidType(); 5433 } 5434 } 5435 } 5436 5437 bool IsExplicitSpecialization = false; 5438 bool IsVariableTemplateSpecialization = false; 5439 bool IsPartialSpecialization = false; 5440 bool IsVariableTemplate = false; 5441 VarDecl *NewVD = nullptr; 5442 VarTemplateDecl *NewTemplate = nullptr; 5443 TemplateParameterList *TemplateParams = nullptr; 5444 if (!getLangOpts().CPlusPlus) { 5445 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5446 D.getIdentifierLoc(), II, 5447 R, TInfo, SC); 5448 5449 if (D.isInvalidType()) 5450 NewVD->setInvalidDecl(); 5451 } else { 5452 bool Invalid = false; 5453 5454 if (DC->isRecord() && !CurContext->isRecord()) { 5455 // This is an out-of-line definition of a static data member. 5456 switch (SC) { 5457 case SC_None: 5458 break; 5459 case SC_Static: 5460 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5461 diag::err_static_out_of_line) 5462 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5463 break; 5464 case SC_Auto: 5465 case SC_Register: 5466 case SC_Extern: 5467 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5468 // to names of variables declared in a block or to function parameters. 5469 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5470 // of class members 5471 5472 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5473 diag::err_storage_class_for_static_member) 5474 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5475 break; 5476 case SC_PrivateExtern: 5477 llvm_unreachable("C storage class in c++!"); 5478 case SC_OpenCLWorkGroupLocal: 5479 llvm_unreachable("OpenCL storage class in c++!"); 5480 } 5481 } 5482 5483 if (SC == SC_Static && CurContext->isRecord()) { 5484 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5485 if (RD->isLocalClass()) 5486 Diag(D.getIdentifierLoc(), 5487 diag::err_static_data_member_not_allowed_in_local_class) 5488 << Name << RD->getDeclName(); 5489 5490 // C++98 [class.union]p1: If a union contains a static data member, 5491 // the program is ill-formed. C++11 drops this restriction. 5492 if (RD->isUnion()) 5493 Diag(D.getIdentifierLoc(), 5494 getLangOpts().CPlusPlus11 5495 ? diag::warn_cxx98_compat_static_data_member_in_union 5496 : diag::ext_static_data_member_in_union) << Name; 5497 // We conservatively disallow static data members in anonymous structs. 5498 else if (!RD->getDeclName()) 5499 Diag(D.getIdentifierLoc(), 5500 diag::err_static_data_member_not_allowed_in_anon_struct) 5501 << Name << RD->isUnion(); 5502 } 5503 } 5504 5505 // Match up the template parameter lists with the scope specifier, then 5506 // determine whether we have a template or a template specialization. 5507 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5508 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5509 D.getCXXScopeSpec(), 5510 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5511 ? D.getName().TemplateId 5512 : nullptr, 5513 TemplateParamLists, 5514 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5515 5516 if (TemplateParams) { 5517 if (!TemplateParams->size() && 5518 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5519 // There is an extraneous 'template<>' for this variable. Complain 5520 // about it, but allow the declaration of the variable. 5521 Diag(TemplateParams->getTemplateLoc(), 5522 diag::err_template_variable_noparams) 5523 << II 5524 << SourceRange(TemplateParams->getTemplateLoc(), 5525 TemplateParams->getRAngleLoc()); 5526 TemplateParams = nullptr; 5527 } else { 5528 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5529 // This is an explicit specialization or a partial specialization. 5530 // FIXME: Check that we can declare a specialization here. 5531 IsVariableTemplateSpecialization = true; 5532 IsPartialSpecialization = TemplateParams->size() > 0; 5533 } else { // if (TemplateParams->size() > 0) 5534 // This is a template declaration. 5535 IsVariableTemplate = true; 5536 5537 // Check that we can declare a template here. 5538 if (CheckTemplateDeclScope(S, TemplateParams)) 5539 return nullptr; 5540 5541 // Only C++1y supports variable templates (N3651). 5542 Diag(D.getIdentifierLoc(), 5543 getLangOpts().CPlusPlus14 5544 ? diag::warn_cxx11_compat_variable_template 5545 : diag::ext_variable_template); 5546 } 5547 } 5548 } else { 5549 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5550 "should have a 'template<>' for this decl"); 5551 } 5552 5553 if (IsVariableTemplateSpecialization) { 5554 SourceLocation TemplateKWLoc = 5555 TemplateParamLists.size() > 0 5556 ? TemplateParamLists[0]->getTemplateLoc() 5557 : SourceLocation(); 5558 DeclResult Res = ActOnVarTemplateSpecialization( 5559 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5560 IsPartialSpecialization); 5561 if (Res.isInvalid()) 5562 return nullptr; 5563 NewVD = cast<VarDecl>(Res.get()); 5564 AddToScope = false; 5565 } else 5566 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5567 D.getIdentifierLoc(), II, R, TInfo, SC); 5568 5569 // If this is supposed to be a variable template, create it as such. 5570 if (IsVariableTemplate) { 5571 NewTemplate = 5572 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5573 TemplateParams, NewVD); 5574 NewVD->setDescribedVarTemplate(NewTemplate); 5575 } 5576 5577 // If this decl has an auto type in need of deduction, make a note of the 5578 // Decl so we can diagnose uses of it in its own initializer. 5579 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5580 ParsingInitForAutoVars.insert(NewVD); 5581 5582 if (D.isInvalidType() || Invalid) { 5583 NewVD->setInvalidDecl(); 5584 if (NewTemplate) 5585 NewTemplate->setInvalidDecl(); 5586 } 5587 5588 SetNestedNameSpecifier(NewVD, D); 5589 5590 // If we have any template parameter lists that don't directly belong to 5591 // the variable (matching the scope specifier), store them. 5592 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5593 if (TemplateParamLists.size() > VDTemplateParamLists) 5594 NewVD->setTemplateParameterListsInfo( 5595 Context, TemplateParamLists.size() - VDTemplateParamLists, 5596 TemplateParamLists.data()); 5597 5598 if (D.getDeclSpec().isConstexprSpecified()) 5599 NewVD->setConstexpr(true); 5600 } 5601 5602 // Set the lexical context. If the declarator has a C++ scope specifier, the 5603 // lexical context will be different from the semantic context. 5604 NewVD->setLexicalDeclContext(CurContext); 5605 if (NewTemplate) 5606 NewTemplate->setLexicalDeclContext(CurContext); 5607 5608 if (IsLocalExternDecl) 5609 NewVD->setLocalExternDecl(); 5610 5611 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5612 if (NewVD->hasLocalStorage()) { 5613 // C++11 [dcl.stc]p4: 5614 // When thread_local is applied to a variable of block scope the 5615 // storage-class-specifier static is implied if it does not appear 5616 // explicitly. 5617 // Core issue: 'static' is not implied if the variable is declared 5618 // 'extern'. 5619 if (SCSpec == DeclSpec::SCS_unspecified && 5620 TSCS == DeclSpec::TSCS_thread_local && 5621 DC->isFunctionOrMethod()) 5622 NewVD->setTSCSpec(TSCS); 5623 else 5624 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5625 diag::err_thread_non_global) 5626 << DeclSpec::getSpecifierName(TSCS); 5627 } else if (!Context.getTargetInfo().isTLSSupported()) 5628 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5629 diag::err_thread_unsupported); 5630 else 5631 NewVD->setTSCSpec(TSCS); 5632 } 5633 5634 // C99 6.7.4p3 5635 // An inline definition of a function with external linkage shall 5636 // not contain a definition of a modifiable object with static or 5637 // thread storage duration... 5638 // We only apply this when the function is required to be defined 5639 // elsewhere, i.e. when the function is not 'extern inline'. Note 5640 // that a local variable with thread storage duration still has to 5641 // be marked 'static'. Also note that it's possible to get these 5642 // semantics in C++ using __attribute__((gnu_inline)). 5643 if (SC == SC_Static && S->getFnParent() != nullptr && 5644 !NewVD->getType().isConstQualified()) { 5645 FunctionDecl *CurFD = getCurFunctionDecl(); 5646 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5647 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5648 diag::warn_static_local_in_extern_inline); 5649 MaybeSuggestAddingStaticToDecl(CurFD); 5650 } 5651 } 5652 5653 if (D.getDeclSpec().isModulePrivateSpecified()) { 5654 if (IsVariableTemplateSpecialization) 5655 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5656 << (IsPartialSpecialization ? 1 : 0) 5657 << FixItHint::CreateRemoval( 5658 D.getDeclSpec().getModulePrivateSpecLoc()); 5659 else if (IsExplicitSpecialization) 5660 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5661 << 2 5662 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5663 else if (NewVD->hasLocalStorage()) 5664 Diag(NewVD->getLocation(), diag::err_module_private_local) 5665 << 0 << NewVD->getDeclName() 5666 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5667 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5668 else { 5669 NewVD->setModulePrivate(); 5670 if (NewTemplate) 5671 NewTemplate->setModulePrivate(); 5672 } 5673 } 5674 5675 // Handle attributes prior to checking for duplicates in MergeVarDecl 5676 ProcessDeclAttributes(S, NewVD, D); 5677 5678 if (getLangOpts().CUDA) { 5679 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5680 // storage [duration]." 5681 if (SC == SC_None && S->getFnParent() != nullptr && 5682 (NewVD->hasAttr<CUDASharedAttr>() || 5683 NewVD->hasAttr<CUDAConstantAttr>())) { 5684 NewVD->setStorageClass(SC_Static); 5685 } 5686 } 5687 5688 // Ensure that dllimport globals without explicit storage class are treated as 5689 // extern. The storage class is set above using parsed attributes. Now we can 5690 // check the VarDecl itself. 5691 assert(!NewVD->hasAttr<DLLImportAttr>() || 5692 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5693 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5694 5695 // In auto-retain/release, infer strong retension for variables of 5696 // retainable type. 5697 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5698 NewVD->setInvalidDecl(); 5699 5700 // Handle GNU asm-label extension (encoded as an attribute). 5701 if (Expr *E = (Expr*)D.getAsmLabel()) { 5702 // The parser guarantees this is a string. 5703 StringLiteral *SE = cast<StringLiteral>(E); 5704 StringRef Label = SE->getString(); 5705 if (S->getFnParent() != nullptr) { 5706 switch (SC) { 5707 case SC_None: 5708 case SC_Auto: 5709 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5710 break; 5711 case SC_Register: 5712 // Local Named register 5713 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5714 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5715 break; 5716 case SC_Static: 5717 case SC_Extern: 5718 case SC_PrivateExtern: 5719 case SC_OpenCLWorkGroupLocal: 5720 break; 5721 } 5722 } else if (SC == SC_Register) { 5723 // Global Named register 5724 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5725 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5726 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5727 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5728 NewVD->setInvalidDecl(true); 5729 } 5730 } 5731 5732 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5733 Context, Label, 0)); 5734 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5735 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5736 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5737 if (I != ExtnameUndeclaredIdentifiers.end()) { 5738 NewVD->addAttr(I->second); 5739 ExtnameUndeclaredIdentifiers.erase(I); 5740 } 5741 } 5742 5743 // Diagnose shadowed variables before filtering for scope. 5744 if (D.getCXXScopeSpec().isEmpty()) 5745 CheckShadow(S, NewVD, Previous); 5746 5747 // Don't consider existing declarations that are in a different 5748 // scope and are out-of-semantic-context declarations (if the new 5749 // declaration has linkage). 5750 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5751 D.getCXXScopeSpec().isNotEmpty() || 5752 IsExplicitSpecialization || 5753 IsVariableTemplateSpecialization); 5754 5755 // Check whether the previous declaration is in the same block scope. This 5756 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5757 if (getLangOpts().CPlusPlus && 5758 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5759 NewVD->setPreviousDeclInSameBlockScope( 5760 Previous.isSingleResult() && !Previous.isShadowed() && 5761 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5762 5763 if (!getLangOpts().CPlusPlus) { 5764 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5765 } else { 5766 // If this is an explicit specialization of a static data member, check it. 5767 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5768 CheckMemberSpecialization(NewVD, Previous)) 5769 NewVD->setInvalidDecl(); 5770 5771 // Merge the decl with the existing one if appropriate. 5772 if (!Previous.empty()) { 5773 if (Previous.isSingleResult() && 5774 isa<FieldDecl>(Previous.getFoundDecl()) && 5775 D.getCXXScopeSpec().isSet()) { 5776 // The user tried to define a non-static data member 5777 // out-of-line (C++ [dcl.meaning]p1). 5778 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5779 << D.getCXXScopeSpec().getRange(); 5780 Previous.clear(); 5781 NewVD->setInvalidDecl(); 5782 } 5783 } else if (D.getCXXScopeSpec().isSet()) { 5784 // No previous declaration in the qualifying scope. 5785 Diag(D.getIdentifierLoc(), diag::err_no_member) 5786 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5787 << D.getCXXScopeSpec().getRange(); 5788 NewVD->setInvalidDecl(); 5789 } 5790 5791 if (!IsVariableTemplateSpecialization) 5792 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5793 5794 if (NewTemplate) { 5795 VarTemplateDecl *PrevVarTemplate = 5796 NewVD->getPreviousDecl() 5797 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5798 : nullptr; 5799 5800 // Check the template parameter list of this declaration, possibly 5801 // merging in the template parameter list from the previous variable 5802 // template declaration. 5803 if (CheckTemplateParameterList( 5804 TemplateParams, 5805 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5806 : nullptr, 5807 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5808 DC->isDependentContext()) 5809 ? TPC_ClassTemplateMember 5810 : TPC_VarTemplate)) 5811 NewVD->setInvalidDecl(); 5812 5813 // If we are providing an explicit specialization of a static variable 5814 // template, make a note of that. 5815 if (PrevVarTemplate && 5816 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5817 PrevVarTemplate->setMemberSpecialization(); 5818 } 5819 } 5820 5821 ProcessPragmaWeak(S, NewVD); 5822 5823 // If this is the first declaration of an extern C variable, update 5824 // the map of such variables. 5825 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5826 isIncompleteDeclExternC(*this, NewVD)) 5827 RegisterLocallyScopedExternCDecl(NewVD, S); 5828 5829 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5830 Decl *ManglingContextDecl; 5831 if (MangleNumberingContext *MCtx = 5832 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5833 ManglingContextDecl)) { 5834 Context.setManglingNumber( 5835 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5836 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5837 } 5838 } 5839 5840 if (D.isRedeclaration() && !Previous.empty()) { 5841 checkDLLAttributeRedeclaration( 5842 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5843 IsExplicitSpecialization); 5844 } 5845 5846 if (NewTemplate) { 5847 if (NewVD->isInvalidDecl()) 5848 NewTemplate->setInvalidDecl(); 5849 ActOnDocumentableDecl(NewTemplate); 5850 return NewTemplate; 5851 } 5852 5853 return NewVD; 5854 } 5855 5856 /// \brief Diagnose variable or built-in function shadowing. Implements 5857 /// -Wshadow. 5858 /// 5859 /// This method is called whenever a VarDecl is added to a "useful" 5860 /// scope. 5861 /// 5862 /// \param S the scope in which the shadowing name is being declared 5863 /// \param R the lookup of the name 5864 /// 5865 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5866 // Return if warning is ignored. 5867 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5868 return; 5869 5870 // Don't diagnose declarations at file scope. 5871 if (D->hasGlobalStorage()) 5872 return; 5873 5874 DeclContext *NewDC = D->getDeclContext(); 5875 5876 // Only diagnose if we're shadowing an unambiguous field or variable. 5877 if (R.getResultKind() != LookupResult::Found) 5878 return; 5879 5880 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5881 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5882 return; 5883 5884 // Fields are not shadowed by variables in C++ static methods. 5885 if (isa<FieldDecl>(ShadowedDecl)) 5886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5887 if (MD->isStatic()) 5888 return; 5889 5890 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5891 if (shadowedVar->isExternC()) { 5892 // For shadowing external vars, make sure that we point to the global 5893 // declaration, not a locally scoped extern declaration. 5894 for (auto I : shadowedVar->redecls()) 5895 if (I->isFileVarDecl()) { 5896 ShadowedDecl = I; 5897 break; 5898 } 5899 } 5900 5901 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5902 5903 // Only warn about certain kinds of shadowing for class members. 5904 if (NewDC && NewDC->isRecord()) { 5905 // In particular, don't warn about shadowing non-class members. 5906 if (!OldDC->isRecord()) 5907 return; 5908 5909 // TODO: should we warn about static data members shadowing 5910 // static data members from base classes? 5911 5912 // TODO: don't diagnose for inaccessible shadowed members. 5913 // This is hard to do perfectly because we might friend the 5914 // shadowing context, but that's just a false negative. 5915 } 5916 5917 // Determine what kind of declaration we're shadowing. 5918 unsigned Kind; 5919 if (isa<RecordDecl>(OldDC)) { 5920 if (isa<FieldDecl>(ShadowedDecl)) 5921 Kind = 3; // field 5922 else 5923 Kind = 2; // static data member 5924 } else if (OldDC->isFileContext()) 5925 Kind = 1; // global 5926 else 5927 Kind = 0; // local 5928 5929 DeclarationName Name = R.getLookupName(); 5930 5931 // Emit warning and note. 5932 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5933 return; 5934 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5935 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5936 } 5937 5938 /// \brief Check -Wshadow without the advantage of a previous lookup. 5939 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5940 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 5941 return; 5942 5943 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5944 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5945 LookupName(R, S); 5946 CheckShadow(S, D, R); 5947 } 5948 5949 /// Check for conflict between this global or extern "C" declaration and 5950 /// previous global or extern "C" declarations. This is only used in C++. 5951 template<typename T> 5952 static bool checkGlobalOrExternCConflict( 5953 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5954 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5955 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5956 5957 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5958 // The common case: this global doesn't conflict with any extern "C" 5959 // declaration. 5960 return false; 5961 } 5962 5963 if (Prev) { 5964 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5965 // Both the old and new declarations have C language linkage. This is a 5966 // redeclaration. 5967 Previous.clear(); 5968 Previous.addDecl(Prev); 5969 return true; 5970 } 5971 5972 // This is a global, non-extern "C" declaration, and there is a previous 5973 // non-global extern "C" declaration. Diagnose if this is a variable 5974 // declaration. 5975 if (!isa<VarDecl>(ND)) 5976 return false; 5977 } else { 5978 // The declaration is extern "C". Check for any declaration in the 5979 // translation unit which might conflict. 5980 if (IsGlobal) { 5981 // We have already performed the lookup into the translation unit. 5982 IsGlobal = false; 5983 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5984 I != E; ++I) { 5985 if (isa<VarDecl>(*I)) { 5986 Prev = *I; 5987 break; 5988 } 5989 } 5990 } else { 5991 DeclContext::lookup_result R = 5992 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5993 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5994 I != E; ++I) { 5995 if (isa<VarDecl>(*I)) { 5996 Prev = *I; 5997 break; 5998 } 5999 // FIXME: If we have any other entity with this name in global scope, 6000 // the declaration is ill-formed, but that is a defect: it breaks the 6001 // 'stat' hack, for instance. Only variables can have mangled name 6002 // clashes with extern "C" declarations, so only they deserve a 6003 // diagnostic. 6004 } 6005 } 6006 6007 if (!Prev) 6008 return false; 6009 } 6010 6011 // Use the first declaration's location to ensure we point at something which 6012 // is lexically inside an extern "C" linkage-spec. 6013 assert(Prev && "should have found a previous declaration to diagnose"); 6014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6015 Prev = FD->getFirstDecl(); 6016 else 6017 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6018 6019 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6020 << IsGlobal << ND; 6021 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6022 << IsGlobal; 6023 return false; 6024 } 6025 6026 /// Apply special rules for handling extern "C" declarations. Returns \c true 6027 /// if we have found that this is a redeclaration of some prior entity. 6028 /// 6029 /// Per C++ [dcl.link]p6: 6030 /// Two declarations [for a function or variable] with C language linkage 6031 /// with the same name that appear in different scopes refer to the same 6032 /// [entity]. An entity with C language linkage shall not be declared with 6033 /// the same name as an entity in global scope. 6034 template<typename T> 6035 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6036 LookupResult &Previous) { 6037 if (!S.getLangOpts().CPlusPlus) { 6038 // In C, when declaring a global variable, look for a corresponding 'extern' 6039 // variable declared in function scope. We don't need this in C++, because 6040 // we find local extern decls in the surrounding file-scope DeclContext. 6041 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6042 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6043 Previous.clear(); 6044 Previous.addDecl(Prev); 6045 return true; 6046 } 6047 } 6048 return false; 6049 } 6050 6051 // A declaration in the translation unit can conflict with an extern "C" 6052 // declaration. 6053 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6054 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6055 6056 // An extern "C" declaration can conflict with a declaration in the 6057 // translation unit or can be a redeclaration of an extern "C" declaration 6058 // in another scope. 6059 if (isIncompleteDeclExternC(S,ND)) 6060 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6061 6062 // Neither global nor extern "C": nothing to do. 6063 return false; 6064 } 6065 6066 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6067 // If the decl is already known invalid, don't check it. 6068 if (NewVD->isInvalidDecl()) 6069 return; 6070 6071 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6072 QualType T = TInfo->getType(); 6073 6074 // Defer checking an 'auto' type until its initializer is attached. 6075 if (T->isUndeducedType()) 6076 return; 6077 6078 if (NewVD->hasAttrs()) 6079 CheckAlignasUnderalignment(NewVD); 6080 6081 if (T->isObjCObjectType()) { 6082 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6083 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6084 T = Context.getObjCObjectPointerType(T); 6085 NewVD->setType(T); 6086 } 6087 6088 // Emit an error if an address space was applied to decl with local storage. 6089 // This includes arrays of objects with address space qualifiers, but not 6090 // automatic variables that point to other address spaces. 6091 // ISO/IEC TR 18037 S5.1.2 6092 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6093 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6094 NewVD->setInvalidDecl(); 6095 return; 6096 } 6097 6098 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6099 // __constant address space. 6100 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6101 && T.getAddressSpace() != LangAS::opencl_constant 6102 && !T->isSamplerT()){ 6103 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6104 NewVD->setInvalidDecl(); 6105 return; 6106 } 6107 6108 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6109 // scope. 6110 if ((getLangOpts().OpenCLVersion >= 120) 6111 && NewVD->isStaticLocal()) { 6112 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6113 NewVD->setInvalidDecl(); 6114 return; 6115 } 6116 6117 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6118 && !NewVD->hasAttr<BlocksAttr>()) { 6119 if (getLangOpts().getGC() != LangOptions::NonGC) 6120 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6121 else { 6122 assert(!getLangOpts().ObjCAutoRefCount); 6123 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6124 } 6125 } 6126 6127 bool isVM = T->isVariablyModifiedType(); 6128 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6129 NewVD->hasAttr<BlocksAttr>()) 6130 getCurFunction()->setHasBranchProtectedScope(); 6131 6132 if ((isVM && NewVD->hasLinkage()) || 6133 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6134 bool SizeIsNegative; 6135 llvm::APSInt Oversized; 6136 TypeSourceInfo *FixedTInfo = 6137 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6138 SizeIsNegative, Oversized); 6139 if (!FixedTInfo && T->isVariableArrayType()) { 6140 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6141 // FIXME: This won't give the correct result for 6142 // int a[10][n]; 6143 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6144 6145 if (NewVD->isFileVarDecl()) 6146 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6147 << SizeRange; 6148 else if (NewVD->isStaticLocal()) 6149 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6150 << SizeRange; 6151 else 6152 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6153 << SizeRange; 6154 NewVD->setInvalidDecl(); 6155 return; 6156 } 6157 6158 if (!FixedTInfo) { 6159 if (NewVD->isFileVarDecl()) 6160 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6161 else 6162 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6163 NewVD->setInvalidDecl(); 6164 return; 6165 } 6166 6167 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6168 NewVD->setType(FixedTInfo->getType()); 6169 NewVD->setTypeSourceInfo(FixedTInfo); 6170 } 6171 6172 if (T->isVoidType()) { 6173 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6174 // of objects and functions. 6175 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6176 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6177 << T; 6178 NewVD->setInvalidDecl(); 6179 return; 6180 } 6181 } 6182 6183 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6184 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6185 NewVD->setInvalidDecl(); 6186 return; 6187 } 6188 6189 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6190 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6191 NewVD->setInvalidDecl(); 6192 return; 6193 } 6194 6195 if (NewVD->isConstexpr() && !T->isDependentType() && 6196 RequireLiteralType(NewVD->getLocation(), T, 6197 diag::err_constexpr_var_non_literal)) { 6198 NewVD->setInvalidDecl(); 6199 return; 6200 } 6201 } 6202 6203 /// \brief Perform semantic checking on a newly-created variable 6204 /// declaration. 6205 /// 6206 /// This routine performs all of the type-checking required for a 6207 /// variable declaration once it has been built. It is used both to 6208 /// check variables after they have been parsed and their declarators 6209 /// have been translated into a declaration, and to check variables 6210 /// that have been instantiated from a template. 6211 /// 6212 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6213 /// 6214 /// Returns true if the variable declaration is a redeclaration. 6215 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6216 CheckVariableDeclarationType(NewVD); 6217 6218 // If the decl is already known invalid, don't check it. 6219 if (NewVD->isInvalidDecl()) 6220 return false; 6221 6222 // If we did not find anything by this name, look for a non-visible 6223 // extern "C" declaration with the same name. 6224 if (Previous.empty() && 6225 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6226 Previous.setShadowed(); 6227 6228 // Filter out any non-conflicting previous declarations. 6229 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6230 6231 if (!Previous.empty()) { 6232 MergeVarDecl(NewVD, Previous); 6233 return true; 6234 } 6235 return false; 6236 } 6237 6238 /// \brief Data used with FindOverriddenMethod 6239 struct FindOverriddenMethodData { 6240 Sema *S; 6241 CXXMethodDecl *Method; 6242 }; 6243 6244 /// \brief Member lookup function that determines whether a given C++ 6245 /// method overrides a method in a base class, to be used with 6246 /// CXXRecordDecl::lookupInBases(). 6247 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6248 CXXBasePath &Path, 6249 void *UserData) { 6250 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6251 6252 FindOverriddenMethodData *Data 6253 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6254 6255 DeclarationName Name = Data->Method->getDeclName(); 6256 6257 // FIXME: Do we care about other names here too? 6258 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6259 // We really want to find the base class destructor here. 6260 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6261 CanQualType CT = Data->S->Context.getCanonicalType(T); 6262 6263 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6264 } 6265 6266 for (Path.Decls = BaseRecord->lookup(Name); 6267 !Path.Decls.empty(); 6268 Path.Decls = Path.Decls.slice(1)) { 6269 NamedDecl *D = Path.Decls.front(); 6270 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6271 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6272 return true; 6273 } 6274 } 6275 6276 return false; 6277 } 6278 6279 namespace { 6280 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6281 } 6282 /// \brief Report an error regarding overriding, along with any relevant 6283 /// overriden methods. 6284 /// 6285 /// \param DiagID the primary error to report. 6286 /// \param MD the overriding method. 6287 /// \param OEK which overrides to include as notes. 6288 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6289 OverrideErrorKind OEK = OEK_All) { 6290 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6291 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6292 E = MD->end_overridden_methods(); 6293 I != E; ++I) { 6294 // This check (& the OEK parameter) could be replaced by a predicate, but 6295 // without lambdas that would be overkill. This is still nicer than writing 6296 // out the diag loop 3 times. 6297 if ((OEK == OEK_All) || 6298 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6299 (OEK == OEK_Deleted && (*I)->isDeleted())) 6300 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6301 } 6302 } 6303 6304 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6305 /// and if so, check that it's a valid override and remember it. 6306 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6307 // Look for virtual methods in base classes that this method might override. 6308 CXXBasePaths Paths; 6309 FindOverriddenMethodData Data; 6310 Data.Method = MD; 6311 Data.S = this; 6312 bool hasDeletedOverridenMethods = false; 6313 bool hasNonDeletedOverridenMethods = false; 6314 bool AddedAny = false; 6315 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6316 for (auto *I : Paths.found_decls()) { 6317 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6318 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6319 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6320 !CheckOverridingFunctionAttributes(MD, OldMD) && 6321 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6322 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6323 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6324 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6325 AddedAny = true; 6326 } 6327 } 6328 } 6329 } 6330 6331 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6332 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6333 } 6334 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6335 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6336 } 6337 6338 return AddedAny; 6339 } 6340 6341 namespace { 6342 // Struct for holding all of the extra arguments needed by 6343 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6344 struct ActOnFDArgs { 6345 Scope *S; 6346 Declarator &D; 6347 MultiTemplateParamsArg TemplateParamLists; 6348 bool AddToScope; 6349 }; 6350 } 6351 6352 namespace { 6353 6354 // Callback to only accept typo corrections that have a non-zero edit distance. 6355 // Also only accept corrections that have the same parent decl. 6356 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6357 public: 6358 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6359 CXXRecordDecl *Parent) 6360 : Context(Context), OriginalFD(TypoFD), 6361 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6362 6363 bool ValidateCandidate(const TypoCorrection &candidate) override { 6364 if (candidate.getEditDistance() == 0) 6365 return false; 6366 6367 SmallVector<unsigned, 1> MismatchedParams; 6368 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6369 CDeclEnd = candidate.end(); 6370 CDecl != CDeclEnd; ++CDecl) { 6371 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6372 6373 if (FD && !FD->hasBody() && 6374 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6375 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6376 CXXRecordDecl *Parent = MD->getParent(); 6377 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6378 return true; 6379 } else if (!ExpectedParent) { 6380 return true; 6381 } 6382 } 6383 } 6384 6385 return false; 6386 } 6387 6388 private: 6389 ASTContext &Context; 6390 FunctionDecl *OriginalFD; 6391 CXXRecordDecl *ExpectedParent; 6392 }; 6393 6394 } 6395 6396 /// \brief Generate diagnostics for an invalid function redeclaration. 6397 /// 6398 /// This routine handles generating the diagnostic messages for an invalid 6399 /// function redeclaration, including finding possible similar declarations 6400 /// or performing typo correction if there are no previous declarations with 6401 /// the same name. 6402 /// 6403 /// Returns a NamedDecl iff typo correction was performed and substituting in 6404 /// the new declaration name does not cause new errors. 6405 static NamedDecl *DiagnoseInvalidRedeclaration( 6406 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6407 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6408 DeclarationName Name = NewFD->getDeclName(); 6409 DeclContext *NewDC = NewFD->getDeclContext(); 6410 SmallVector<unsigned, 1> MismatchedParams; 6411 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6412 TypoCorrection Correction; 6413 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6414 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6415 : diag::err_member_decl_does_not_match; 6416 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6417 IsLocalFriend ? Sema::LookupLocalFriendName 6418 : Sema::LookupOrdinaryName, 6419 Sema::ForRedeclaration); 6420 6421 NewFD->setInvalidDecl(); 6422 if (IsLocalFriend) 6423 SemaRef.LookupName(Prev, S); 6424 else 6425 SemaRef.LookupQualifiedName(Prev, NewDC); 6426 assert(!Prev.isAmbiguous() && 6427 "Cannot have an ambiguity in previous-declaration lookup"); 6428 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6429 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6430 MD ? MD->getParent() : nullptr); 6431 if (!Prev.empty()) { 6432 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6433 Func != FuncEnd; ++Func) { 6434 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6435 if (FD && 6436 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6437 // Add 1 to the index so that 0 can mean the mismatch didn't 6438 // involve a parameter 6439 unsigned ParamNum = 6440 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6441 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6442 } 6443 } 6444 // If the qualified name lookup yielded nothing, try typo correction 6445 } else if ((Correction = SemaRef.CorrectTypo( 6446 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6447 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6448 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6449 // Set up everything for the call to ActOnFunctionDeclarator 6450 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6451 ExtraArgs.D.getIdentifierLoc()); 6452 Previous.clear(); 6453 Previous.setLookupName(Correction.getCorrection()); 6454 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6455 CDeclEnd = Correction.end(); 6456 CDecl != CDeclEnd; ++CDecl) { 6457 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6458 if (FD && !FD->hasBody() && 6459 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6460 Previous.addDecl(FD); 6461 } 6462 } 6463 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6464 6465 NamedDecl *Result; 6466 // Retry building the function declaration with the new previous 6467 // declarations, and with errors suppressed. 6468 { 6469 // Trap errors. 6470 Sema::SFINAETrap Trap(SemaRef); 6471 6472 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6473 // pieces need to verify the typo-corrected C++ declaration and hopefully 6474 // eliminate the need for the parameter pack ExtraArgs. 6475 Result = SemaRef.ActOnFunctionDeclarator( 6476 ExtraArgs.S, ExtraArgs.D, 6477 Correction.getCorrectionDecl()->getDeclContext(), 6478 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6479 ExtraArgs.AddToScope); 6480 6481 if (Trap.hasErrorOccurred()) 6482 Result = nullptr; 6483 } 6484 6485 if (Result) { 6486 // Determine which correction we picked. 6487 Decl *Canonical = Result->getCanonicalDecl(); 6488 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6489 I != E; ++I) 6490 if ((*I)->getCanonicalDecl() == Canonical) 6491 Correction.setCorrectionDecl(*I); 6492 6493 SemaRef.diagnoseTypo( 6494 Correction, 6495 SemaRef.PDiag(IsLocalFriend 6496 ? diag::err_no_matching_local_friend_suggest 6497 : diag::err_member_decl_does_not_match_suggest) 6498 << Name << NewDC << IsDefinition); 6499 return Result; 6500 } 6501 6502 // Pretend the typo correction never occurred 6503 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6504 ExtraArgs.D.getIdentifierLoc()); 6505 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6506 Previous.clear(); 6507 Previous.setLookupName(Name); 6508 } 6509 6510 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6511 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6512 6513 bool NewFDisConst = false; 6514 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6515 NewFDisConst = NewMD->isConst(); 6516 6517 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6518 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6519 NearMatch != NearMatchEnd; ++NearMatch) { 6520 FunctionDecl *FD = NearMatch->first; 6521 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6522 bool FDisConst = MD && MD->isConst(); 6523 bool IsMember = MD || !IsLocalFriend; 6524 6525 // FIXME: These notes are poorly worded for the local friend case. 6526 if (unsigned Idx = NearMatch->second) { 6527 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6528 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6529 if (Loc.isInvalid()) Loc = FD->getLocation(); 6530 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6531 : diag::note_local_decl_close_param_match) 6532 << Idx << FDParam->getType() 6533 << NewFD->getParamDecl(Idx - 1)->getType(); 6534 } else if (FDisConst != NewFDisConst) { 6535 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6536 << NewFDisConst << FD->getSourceRange().getEnd(); 6537 } else 6538 SemaRef.Diag(FD->getLocation(), 6539 IsMember ? diag::note_member_def_close_match 6540 : diag::note_local_decl_close_match); 6541 } 6542 return nullptr; 6543 } 6544 6545 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6546 Declarator &D) { 6547 switch (D.getDeclSpec().getStorageClassSpec()) { 6548 default: llvm_unreachable("Unknown storage class!"); 6549 case DeclSpec::SCS_auto: 6550 case DeclSpec::SCS_register: 6551 case DeclSpec::SCS_mutable: 6552 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6553 diag::err_typecheck_sclass_func); 6554 D.setInvalidType(); 6555 break; 6556 case DeclSpec::SCS_unspecified: break; 6557 case DeclSpec::SCS_extern: 6558 if (D.getDeclSpec().isExternInLinkageSpec()) 6559 return SC_None; 6560 return SC_Extern; 6561 case DeclSpec::SCS_static: { 6562 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6563 // C99 6.7.1p5: 6564 // The declaration of an identifier for a function that has 6565 // block scope shall have no explicit storage-class specifier 6566 // other than extern 6567 // See also (C++ [dcl.stc]p4). 6568 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6569 diag::err_static_block_func); 6570 break; 6571 } else 6572 return SC_Static; 6573 } 6574 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6575 } 6576 6577 // No explicit storage class has already been returned 6578 return SC_None; 6579 } 6580 6581 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6582 DeclContext *DC, QualType &R, 6583 TypeSourceInfo *TInfo, 6584 FunctionDecl::StorageClass SC, 6585 bool &IsVirtualOkay) { 6586 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6587 DeclarationName Name = NameInfo.getName(); 6588 6589 FunctionDecl *NewFD = nullptr; 6590 bool isInline = D.getDeclSpec().isInlineSpecified(); 6591 6592 if (!SemaRef.getLangOpts().CPlusPlus) { 6593 // Determine whether the function was written with a 6594 // prototype. This true when: 6595 // - there is a prototype in the declarator, or 6596 // - the type R of the function is some kind of typedef or other reference 6597 // to a type name (which eventually refers to a function type). 6598 bool HasPrototype = 6599 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6600 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6601 6602 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6603 D.getLocStart(), NameInfo, R, 6604 TInfo, SC, isInline, 6605 HasPrototype, false); 6606 if (D.isInvalidType()) 6607 NewFD->setInvalidDecl(); 6608 6609 // Set the lexical context. 6610 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6611 6612 return NewFD; 6613 } 6614 6615 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6616 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6617 6618 // Check that the return type is not an abstract class type. 6619 // For record types, this is done by the AbstractClassUsageDiagnoser once 6620 // the class has been completely parsed. 6621 if (!DC->isRecord() && 6622 SemaRef.RequireNonAbstractType( 6623 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6624 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6625 D.setInvalidType(); 6626 6627 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6628 // This is a C++ constructor declaration. 6629 assert(DC->isRecord() && 6630 "Constructors can only be declared in a member context"); 6631 6632 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6633 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6634 D.getLocStart(), NameInfo, 6635 R, TInfo, isExplicit, isInline, 6636 /*isImplicitlyDeclared=*/false, 6637 isConstexpr); 6638 6639 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6640 // This is a C++ destructor declaration. 6641 if (DC->isRecord()) { 6642 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6643 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6644 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6645 SemaRef.Context, Record, 6646 D.getLocStart(), 6647 NameInfo, R, TInfo, isInline, 6648 /*isImplicitlyDeclared=*/false); 6649 6650 // If the class is complete, then we now create the implicit exception 6651 // specification. If the class is incomplete or dependent, we can't do 6652 // it yet. 6653 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6654 Record->getDefinition() && !Record->isBeingDefined() && 6655 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6656 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6657 } 6658 6659 IsVirtualOkay = true; 6660 return NewDD; 6661 6662 } else { 6663 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6664 D.setInvalidType(); 6665 6666 // Create a FunctionDecl to satisfy the function definition parsing 6667 // code path. 6668 return FunctionDecl::Create(SemaRef.Context, DC, 6669 D.getLocStart(), 6670 D.getIdentifierLoc(), Name, R, TInfo, 6671 SC, isInline, 6672 /*hasPrototype=*/true, isConstexpr); 6673 } 6674 6675 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6676 if (!DC->isRecord()) { 6677 SemaRef.Diag(D.getIdentifierLoc(), 6678 diag::err_conv_function_not_member); 6679 return nullptr; 6680 } 6681 6682 SemaRef.CheckConversionDeclarator(D, R, SC); 6683 IsVirtualOkay = true; 6684 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6685 D.getLocStart(), NameInfo, 6686 R, TInfo, isInline, isExplicit, 6687 isConstexpr, SourceLocation()); 6688 6689 } else if (DC->isRecord()) { 6690 // If the name of the function is the same as the name of the record, 6691 // then this must be an invalid constructor that has a return type. 6692 // (The parser checks for a return type and makes the declarator a 6693 // constructor if it has no return type). 6694 if (Name.getAsIdentifierInfo() && 6695 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6696 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6697 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6698 << SourceRange(D.getIdentifierLoc()); 6699 return nullptr; 6700 } 6701 6702 // This is a C++ method declaration. 6703 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6704 cast<CXXRecordDecl>(DC), 6705 D.getLocStart(), NameInfo, R, 6706 TInfo, SC, isInline, 6707 isConstexpr, SourceLocation()); 6708 IsVirtualOkay = !Ret->isStatic(); 6709 return Ret; 6710 } else { 6711 // Determine whether the function was written with a 6712 // prototype. This true when: 6713 // - we're in C++ (where every function has a prototype), 6714 return FunctionDecl::Create(SemaRef.Context, DC, 6715 D.getLocStart(), 6716 NameInfo, R, TInfo, SC, isInline, 6717 true/*HasPrototype*/, isConstexpr); 6718 } 6719 } 6720 6721 enum OpenCLParamType { 6722 ValidKernelParam, 6723 PtrPtrKernelParam, 6724 PtrKernelParam, 6725 PrivatePtrKernelParam, 6726 InvalidKernelParam, 6727 RecordKernelParam 6728 }; 6729 6730 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6731 if (PT->isPointerType()) { 6732 QualType PointeeType = PT->getPointeeType(); 6733 if (PointeeType->isPointerType()) 6734 return PtrPtrKernelParam; 6735 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6736 : PtrKernelParam; 6737 } 6738 6739 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6740 // be used as builtin types. 6741 6742 if (PT->isImageType()) 6743 return PtrKernelParam; 6744 6745 if (PT->isBooleanType()) 6746 return InvalidKernelParam; 6747 6748 if (PT->isEventT()) 6749 return InvalidKernelParam; 6750 6751 if (PT->isHalfType()) 6752 return InvalidKernelParam; 6753 6754 if (PT->isRecordType()) 6755 return RecordKernelParam; 6756 6757 return ValidKernelParam; 6758 } 6759 6760 static void checkIsValidOpenCLKernelParameter( 6761 Sema &S, 6762 Declarator &D, 6763 ParmVarDecl *Param, 6764 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6765 QualType PT = Param->getType(); 6766 6767 // Cache the valid types we encounter to avoid rechecking structs that are 6768 // used again 6769 if (ValidTypes.count(PT.getTypePtr())) 6770 return; 6771 6772 switch (getOpenCLKernelParameterType(PT)) { 6773 case PtrPtrKernelParam: 6774 // OpenCL v1.2 s6.9.a: 6775 // A kernel function argument cannot be declared as a 6776 // pointer to a pointer type. 6777 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6778 D.setInvalidType(); 6779 return; 6780 6781 case PrivatePtrKernelParam: 6782 // OpenCL v1.2 s6.9.a: 6783 // A kernel function argument cannot be declared as a 6784 // pointer to the private address space. 6785 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6786 D.setInvalidType(); 6787 return; 6788 6789 // OpenCL v1.2 s6.9.k: 6790 // Arguments to kernel functions in a program cannot be declared with the 6791 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6792 // uintptr_t or a struct and/or union that contain fields declared to be 6793 // one of these built-in scalar types. 6794 6795 case InvalidKernelParam: 6796 // OpenCL v1.2 s6.8 n: 6797 // A kernel function argument cannot be declared 6798 // of event_t type. 6799 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6800 D.setInvalidType(); 6801 return; 6802 6803 case PtrKernelParam: 6804 case ValidKernelParam: 6805 ValidTypes.insert(PT.getTypePtr()); 6806 return; 6807 6808 case RecordKernelParam: 6809 break; 6810 } 6811 6812 // Track nested structs we will inspect 6813 SmallVector<const Decl *, 4> VisitStack; 6814 6815 // Track where we are in the nested structs. Items will migrate from 6816 // VisitStack to HistoryStack as we do the DFS for bad field. 6817 SmallVector<const FieldDecl *, 4> HistoryStack; 6818 HistoryStack.push_back(nullptr); 6819 6820 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6821 VisitStack.push_back(PD); 6822 6823 assert(VisitStack.back() && "First decl null?"); 6824 6825 do { 6826 const Decl *Next = VisitStack.pop_back_val(); 6827 if (!Next) { 6828 assert(!HistoryStack.empty()); 6829 // Found a marker, we have gone up a level 6830 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6831 ValidTypes.insert(Hist->getType().getTypePtr()); 6832 6833 continue; 6834 } 6835 6836 // Adds everything except the original parameter declaration (which is not a 6837 // field itself) to the history stack. 6838 const RecordDecl *RD; 6839 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6840 HistoryStack.push_back(Field); 6841 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6842 } else { 6843 RD = cast<RecordDecl>(Next); 6844 } 6845 6846 // Add a null marker so we know when we've gone back up a level 6847 VisitStack.push_back(nullptr); 6848 6849 for (const auto *FD : RD->fields()) { 6850 QualType QT = FD->getType(); 6851 6852 if (ValidTypes.count(QT.getTypePtr())) 6853 continue; 6854 6855 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6856 if (ParamType == ValidKernelParam) 6857 continue; 6858 6859 if (ParamType == RecordKernelParam) { 6860 VisitStack.push_back(FD); 6861 continue; 6862 } 6863 6864 // OpenCL v1.2 s6.9.p: 6865 // Arguments to kernel functions that are declared to be a struct or union 6866 // do not allow OpenCL objects to be passed as elements of the struct or 6867 // union. 6868 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6869 ParamType == PrivatePtrKernelParam) { 6870 S.Diag(Param->getLocation(), 6871 diag::err_record_with_pointers_kernel_param) 6872 << PT->isUnionType() 6873 << PT; 6874 } else { 6875 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6876 } 6877 6878 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6879 << PD->getDeclName(); 6880 6881 // We have an error, now let's go back up through history and show where 6882 // the offending field came from 6883 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6884 E = HistoryStack.end(); I != E; ++I) { 6885 const FieldDecl *OuterField = *I; 6886 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6887 << OuterField->getType(); 6888 } 6889 6890 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6891 << QT->isPointerType() 6892 << QT; 6893 D.setInvalidType(); 6894 return; 6895 } 6896 } while (!VisitStack.empty()); 6897 } 6898 6899 NamedDecl* 6900 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6901 TypeSourceInfo *TInfo, LookupResult &Previous, 6902 MultiTemplateParamsArg TemplateParamLists, 6903 bool &AddToScope) { 6904 QualType R = TInfo->getType(); 6905 6906 assert(R.getTypePtr()->isFunctionType()); 6907 6908 // TODO: consider using NameInfo for diagnostic. 6909 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6910 DeclarationName Name = NameInfo.getName(); 6911 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6912 6913 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6914 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6915 diag::err_invalid_thread) 6916 << DeclSpec::getSpecifierName(TSCS); 6917 6918 if (D.isFirstDeclarationOfMember()) 6919 adjustMemberFunctionCC(R, D.isStaticMember()); 6920 6921 bool isFriend = false; 6922 FunctionTemplateDecl *FunctionTemplate = nullptr; 6923 bool isExplicitSpecialization = false; 6924 bool isFunctionTemplateSpecialization = false; 6925 6926 bool isDependentClassScopeExplicitSpecialization = false; 6927 bool HasExplicitTemplateArgs = false; 6928 TemplateArgumentListInfo TemplateArgs; 6929 6930 bool isVirtualOkay = false; 6931 6932 DeclContext *OriginalDC = DC; 6933 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6934 6935 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6936 isVirtualOkay); 6937 if (!NewFD) return nullptr; 6938 6939 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6940 NewFD->setTopLevelDeclInObjCContainer(); 6941 6942 // Set the lexical context. If this is a function-scope declaration, or has a 6943 // C++ scope specifier, or is the object of a friend declaration, the lexical 6944 // context will be different from the semantic context. 6945 NewFD->setLexicalDeclContext(CurContext); 6946 6947 if (IsLocalExternDecl) 6948 NewFD->setLocalExternDecl(); 6949 6950 if (getLangOpts().CPlusPlus) { 6951 bool isInline = D.getDeclSpec().isInlineSpecified(); 6952 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6953 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6954 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6955 isFriend = D.getDeclSpec().isFriendSpecified(); 6956 if (isFriend && !isInline && D.isFunctionDefinition()) { 6957 // C++ [class.friend]p5 6958 // A function can be defined in a friend declaration of a 6959 // class . . . . Such a function is implicitly inline. 6960 NewFD->setImplicitlyInline(); 6961 } 6962 6963 // If this is a method defined in an __interface, and is not a constructor 6964 // or an overloaded operator, then set the pure flag (isVirtual will already 6965 // return true). 6966 if (const CXXRecordDecl *Parent = 6967 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6968 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6969 NewFD->setPure(true); 6970 } 6971 6972 SetNestedNameSpecifier(NewFD, D); 6973 isExplicitSpecialization = false; 6974 isFunctionTemplateSpecialization = false; 6975 if (D.isInvalidType()) 6976 NewFD->setInvalidDecl(); 6977 6978 // Match up the template parameter lists with the scope specifier, then 6979 // determine whether we have a template or a template specialization. 6980 bool Invalid = false; 6981 if (TemplateParameterList *TemplateParams = 6982 MatchTemplateParametersToScopeSpecifier( 6983 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6984 D.getCXXScopeSpec(), 6985 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6986 ? D.getName().TemplateId 6987 : nullptr, 6988 TemplateParamLists, isFriend, isExplicitSpecialization, 6989 Invalid)) { 6990 if (TemplateParams->size() > 0) { 6991 // This is a function template 6992 6993 // Check that we can declare a template here. 6994 if (CheckTemplateDeclScope(S, TemplateParams)) 6995 return nullptr; 6996 6997 // A destructor cannot be a template. 6998 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6999 Diag(NewFD->getLocation(), diag::err_destructor_template); 7000 return nullptr; 7001 } 7002 7003 // If we're adding a template to a dependent context, we may need to 7004 // rebuilding some of the types used within the template parameter list, 7005 // now that we know what the current instantiation is. 7006 if (DC->isDependentContext()) { 7007 ContextRAII SavedContext(*this, DC); 7008 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7009 Invalid = true; 7010 } 7011 7012 7013 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7014 NewFD->getLocation(), 7015 Name, TemplateParams, 7016 NewFD); 7017 FunctionTemplate->setLexicalDeclContext(CurContext); 7018 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7019 7020 // For source fidelity, store the other template param lists. 7021 if (TemplateParamLists.size() > 1) { 7022 NewFD->setTemplateParameterListsInfo(Context, 7023 TemplateParamLists.size() - 1, 7024 TemplateParamLists.data()); 7025 } 7026 } else { 7027 // This is a function template specialization. 7028 isFunctionTemplateSpecialization = true; 7029 // For source fidelity, store all the template param lists. 7030 if (TemplateParamLists.size() > 0) 7031 NewFD->setTemplateParameterListsInfo(Context, 7032 TemplateParamLists.size(), 7033 TemplateParamLists.data()); 7034 7035 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7036 if (isFriend) { 7037 // We want to remove the "template<>", found here. 7038 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7039 7040 // If we remove the template<> and the name is not a 7041 // template-id, we're actually silently creating a problem: 7042 // the friend declaration will refer to an untemplated decl, 7043 // and clearly the user wants a template specialization. So 7044 // we need to insert '<>' after the name. 7045 SourceLocation InsertLoc; 7046 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7047 InsertLoc = D.getName().getSourceRange().getEnd(); 7048 InsertLoc = getLocForEndOfToken(InsertLoc); 7049 } 7050 7051 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7052 << Name << RemoveRange 7053 << FixItHint::CreateRemoval(RemoveRange) 7054 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7055 } 7056 } 7057 } 7058 else { 7059 // All template param lists were matched against the scope specifier: 7060 // this is NOT (an explicit specialization of) a template. 7061 if (TemplateParamLists.size() > 0) 7062 // For source fidelity, store all the template param lists. 7063 NewFD->setTemplateParameterListsInfo(Context, 7064 TemplateParamLists.size(), 7065 TemplateParamLists.data()); 7066 } 7067 7068 if (Invalid) { 7069 NewFD->setInvalidDecl(); 7070 if (FunctionTemplate) 7071 FunctionTemplate->setInvalidDecl(); 7072 } 7073 7074 // C++ [dcl.fct.spec]p5: 7075 // The virtual specifier shall only be used in declarations of 7076 // nonstatic class member functions that appear within a 7077 // member-specification of a class declaration; see 10.3. 7078 // 7079 if (isVirtual && !NewFD->isInvalidDecl()) { 7080 if (!isVirtualOkay) { 7081 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7082 diag::err_virtual_non_function); 7083 } else if (!CurContext->isRecord()) { 7084 // 'virtual' was specified outside of the class. 7085 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7086 diag::err_virtual_out_of_class) 7087 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7088 } else if (NewFD->getDescribedFunctionTemplate()) { 7089 // C++ [temp.mem]p3: 7090 // A member function template shall not be virtual. 7091 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7092 diag::err_virtual_member_function_template) 7093 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7094 } else { 7095 // Okay: Add virtual to the method. 7096 NewFD->setVirtualAsWritten(true); 7097 } 7098 7099 if (getLangOpts().CPlusPlus14 && 7100 NewFD->getReturnType()->isUndeducedType()) 7101 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7102 } 7103 7104 if (getLangOpts().CPlusPlus14 && 7105 (NewFD->isDependentContext() || 7106 (isFriend && CurContext->isDependentContext())) && 7107 NewFD->getReturnType()->isUndeducedType()) { 7108 // If the function template is referenced directly (for instance, as a 7109 // member of the current instantiation), pretend it has a dependent type. 7110 // This is not really justified by the standard, but is the only sane 7111 // thing to do. 7112 // FIXME: For a friend function, we have not marked the function as being 7113 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7114 const FunctionProtoType *FPT = 7115 NewFD->getType()->castAs<FunctionProtoType>(); 7116 QualType Result = 7117 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7118 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7119 FPT->getExtProtoInfo())); 7120 } 7121 7122 // C++ [dcl.fct.spec]p3: 7123 // The inline specifier shall not appear on a block scope function 7124 // declaration. 7125 if (isInline && !NewFD->isInvalidDecl()) { 7126 if (CurContext->isFunctionOrMethod()) { 7127 // 'inline' is not allowed on block scope function declaration. 7128 Diag(D.getDeclSpec().getInlineSpecLoc(), 7129 diag::err_inline_declaration_block_scope) << Name 7130 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7131 } 7132 } 7133 7134 // C++ [dcl.fct.spec]p6: 7135 // The explicit specifier shall be used only in the declaration of a 7136 // constructor or conversion function within its class definition; 7137 // see 12.3.1 and 12.3.2. 7138 if (isExplicit && !NewFD->isInvalidDecl()) { 7139 if (!CurContext->isRecord()) { 7140 // 'explicit' was specified outside of the class. 7141 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7142 diag::err_explicit_out_of_class) 7143 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7144 } else if (!isa<CXXConstructorDecl>(NewFD) && 7145 !isa<CXXConversionDecl>(NewFD)) { 7146 // 'explicit' was specified on a function that wasn't a constructor 7147 // or conversion function. 7148 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7149 diag::err_explicit_non_ctor_or_conv_function) 7150 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7151 } 7152 } 7153 7154 if (isConstexpr) { 7155 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7156 // are implicitly inline. 7157 NewFD->setImplicitlyInline(); 7158 7159 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7160 // be either constructors or to return a literal type. Therefore, 7161 // destructors cannot be declared constexpr. 7162 if (isa<CXXDestructorDecl>(NewFD)) 7163 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7164 } 7165 7166 // If __module_private__ was specified, mark the function accordingly. 7167 if (D.getDeclSpec().isModulePrivateSpecified()) { 7168 if (isFunctionTemplateSpecialization) { 7169 SourceLocation ModulePrivateLoc 7170 = D.getDeclSpec().getModulePrivateSpecLoc(); 7171 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7172 << 0 7173 << FixItHint::CreateRemoval(ModulePrivateLoc); 7174 } else { 7175 NewFD->setModulePrivate(); 7176 if (FunctionTemplate) 7177 FunctionTemplate->setModulePrivate(); 7178 } 7179 } 7180 7181 if (isFriend) { 7182 if (FunctionTemplate) { 7183 FunctionTemplate->setObjectOfFriendDecl(); 7184 FunctionTemplate->setAccess(AS_public); 7185 } 7186 NewFD->setObjectOfFriendDecl(); 7187 NewFD->setAccess(AS_public); 7188 } 7189 7190 // If a function is defined as defaulted or deleted, mark it as such now. 7191 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7192 // definition kind to FDK_Definition. 7193 switch (D.getFunctionDefinitionKind()) { 7194 case FDK_Declaration: 7195 case FDK_Definition: 7196 break; 7197 7198 case FDK_Defaulted: 7199 NewFD->setDefaulted(); 7200 break; 7201 7202 case FDK_Deleted: 7203 NewFD->setDeletedAsWritten(); 7204 break; 7205 } 7206 7207 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7208 D.isFunctionDefinition()) { 7209 // C++ [class.mfct]p2: 7210 // A member function may be defined (8.4) in its class definition, in 7211 // which case it is an inline member function (7.1.2) 7212 NewFD->setImplicitlyInline(); 7213 } 7214 7215 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7216 !CurContext->isRecord()) { 7217 // C++ [class.static]p1: 7218 // A data or function member of a class may be declared static 7219 // in a class definition, in which case it is a static member of 7220 // the class. 7221 7222 // Complain about the 'static' specifier if it's on an out-of-line 7223 // member function definition. 7224 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7225 diag::err_static_out_of_line) 7226 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7227 } 7228 7229 // C++11 [except.spec]p15: 7230 // A deallocation function with no exception-specification is treated 7231 // as if it were specified with noexcept(true). 7232 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7233 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7234 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7235 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7236 NewFD->setType(Context.getFunctionType( 7237 FPT->getReturnType(), FPT->getParamTypes(), 7238 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7239 } 7240 7241 // Filter out previous declarations that don't match the scope. 7242 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7243 D.getCXXScopeSpec().isNotEmpty() || 7244 isExplicitSpecialization || 7245 isFunctionTemplateSpecialization); 7246 7247 // Handle GNU asm-label extension (encoded as an attribute). 7248 if (Expr *E = (Expr*) D.getAsmLabel()) { 7249 // The parser guarantees this is a string. 7250 StringLiteral *SE = cast<StringLiteral>(E); 7251 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7252 SE->getString(), 0)); 7253 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7254 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7255 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7256 if (I != ExtnameUndeclaredIdentifiers.end()) { 7257 NewFD->addAttr(I->second); 7258 ExtnameUndeclaredIdentifiers.erase(I); 7259 } 7260 } 7261 7262 // Copy the parameter declarations from the declarator D to the function 7263 // declaration NewFD, if they are available. First scavenge them into Params. 7264 SmallVector<ParmVarDecl*, 16> Params; 7265 if (D.isFunctionDeclarator()) { 7266 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7267 7268 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7269 // function that takes no arguments, not a function that takes a 7270 // single void argument. 7271 // We let through "const void" here because Sema::GetTypeForDeclarator 7272 // already checks for that case. 7273 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7274 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7275 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7276 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7277 Param->setDeclContext(NewFD); 7278 Params.push_back(Param); 7279 7280 if (Param->isInvalidDecl()) 7281 NewFD->setInvalidDecl(); 7282 } 7283 } 7284 7285 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7286 // When we're declaring a function with a typedef, typeof, etc as in the 7287 // following example, we'll need to synthesize (unnamed) 7288 // parameters for use in the declaration. 7289 // 7290 // @code 7291 // typedef void fn(int); 7292 // fn f; 7293 // @endcode 7294 7295 // Synthesize a parameter for each argument type. 7296 for (const auto &AI : FT->param_types()) { 7297 ParmVarDecl *Param = 7298 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7299 Param->setScopeInfo(0, Params.size()); 7300 Params.push_back(Param); 7301 } 7302 } else { 7303 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7304 "Should not need args for typedef of non-prototype fn"); 7305 } 7306 7307 // Finally, we know we have the right number of parameters, install them. 7308 NewFD->setParams(Params); 7309 7310 // Find all anonymous symbols defined during the declaration of this function 7311 // and add to NewFD. This lets us track decls such 'enum Y' in: 7312 // 7313 // void f(enum Y {AA} x) {} 7314 // 7315 // which would otherwise incorrectly end up in the translation unit scope. 7316 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7317 DeclsInPrototypeScope.clear(); 7318 7319 if (D.getDeclSpec().isNoreturnSpecified()) 7320 NewFD->addAttr( 7321 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7322 Context, 0)); 7323 7324 // Functions returning a variably modified type violate C99 6.7.5.2p2 7325 // because all functions have linkage. 7326 if (!NewFD->isInvalidDecl() && 7327 NewFD->getReturnType()->isVariablyModifiedType()) { 7328 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7329 NewFD->setInvalidDecl(); 7330 } 7331 7332 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7333 !NewFD->hasAttr<SectionAttr>()) { 7334 NewFD->addAttr( 7335 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7336 CodeSegStack.CurrentValue->getString(), 7337 CodeSegStack.CurrentPragmaLocation)); 7338 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7339 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7340 NewFD->dropAttr<SectionAttr>(); 7341 } 7342 7343 // Handle attributes. 7344 ProcessDeclAttributes(S, NewFD, D); 7345 7346 QualType RetType = NewFD->getReturnType(); 7347 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7348 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7349 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7350 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7351 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7352 // Attach WarnUnusedResult to functions returning types with that attribute. 7353 // Don't apply the attribute to that type's own non-static member functions 7354 // (to avoid warning on things like assignment operators) 7355 if (!MD || MD->getParent() != Ret) 7356 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7357 } 7358 7359 if (getLangOpts().OpenCL) { 7360 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7361 // type declaration will generate a compilation error. 7362 unsigned AddressSpace = RetType.getAddressSpace(); 7363 if (AddressSpace == LangAS::opencl_local || 7364 AddressSpace == LangAS::opencl_global || 7365 AddressSpace == LangAS::opencl_constant) { 7366 Diag(NewFD->getLocation(), 7367 diag::err_opencl_return_value_with_address_space); 7368 NewFD->setInvalidDecl(); 7369 } 7370 } 7371 7372 if (!getLangOpts().CPlusPlus) { 7373 // Perform semantic checking on the function declaration. 7374 bool isExplicitSpecialization=false; 7375 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7376 CheckMain(NewFD, D.getDeclSpec()); 7377 7378 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7379 CheckMSVCRTEntryPoint(NewFD); 7380 7381 if (!NewFD->isInvalidDecl()) 7382 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7383 isExplicitSpecialization)); 7384 else if (!Previous.empty()) 7385 // Make graceful recovery from an invalid redeclaration. 7386 D.setRedeclaration(true); 7387 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7388 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7389 "previous declaration set still overloaded"); 7390 } else { 7391 // C++11 [replacement.functions]p3: 7392 // The program's definitions shall not be specified as inline. 7393 // 7394 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7395 // 7396 // Suppress the diagnostic if the function is __attribute__((used)), since 7397 // that forces an external definition to be emitted. 7398 if (D.getDeclSpec().isInlineSpecified() && 7399 NewFD->isReplaceableGlobalAllocationFunction() && 7400 !NewFD->hasAttr<UsedAttr>()) 7401 Diag(D.getDeclSpec().getInlineSpecLoc(), 7402 diag::ext_operator_new_delete_declared_inline) 7403 << NewFD->getDeclName(); 7404 7405 // If the declarator is a template-id, translate the parser's template 7406 // argument list into our AST format. 7407 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7408 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7409 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7410 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7411 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7412 TemplateId->NumArgs); 7413 translateTemplateArguments(TemplateArgsPtr, 7414 TemplateArgs); 7415 7416 HasExplicitTemplateArgs = true; 7417 7418 if (NewFD->isInvalidDecl()) { 7419 HasExplicitTemplateArgs = false; 7420 } else if (FunctionTemplate) { 7421 // Function template with explicit template arguments. 7422 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7423 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7424 7425 HasExplicitTemplateArgs = false; 7426 } else { 7427 assert((isFunctionTemplateSpecialization || 7428 D.getDeclSpec().isFriendSpecified()) && 7429 "should have a 'template<>' for this decl"); 7430 // "friend void foo<>(int);" is an implicit specialization decl. 7431 isFunctionTemplateSpecialization = true; 7432 } 7433 } else if (isFriend && isFunctionTemplateSpecialization) { 7434 // This combination is only possible in a recovery case; the user 7435 // wrote something like: 7436 // template <> friend void foo(int); 7437 // which we're recovering from as if the user had written: 7438 // friend void foo<>(int); 7439 // Go ahead and fake up a template id. 7440 HasExplicitTemplateArgs = true; 7441 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7442 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7443 } 7444 7445 // If it's a friend (and only if it's a friend), it's possible 7446 // that either the specialized function type or the specialized 7447 // template is dependent, and therefore matching will fail. In 7448 // this case, don't check the specialization yet. 7449 bool InstantiationDependent = false; 7450 if (isFunctionTemplateSpecialization && isFriend && 7451 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7452 TemplateSpecializationType::anyDependentTemplateArguments( 7453 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7454 InstantiationDependent))) { 7455 assert(HasExplicitTemplateArgs && 7456 "friend function specialization without template args"); 7457 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7458 Previous)) 7459 NewFD->setInvalidDecl(); 7460 } else if (isFunctionTemplateSpecialization) { 7461 if (CurContext->isDependentContext() && CurContext->isRecord() 7462 && !isFriend) { 7463 isDependentClassScopeExplicitSpecialization = true; 7464 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7465 diag::ext_function_specialization_in_class : 7466 diag::err_function_specialization_in_class) 7467 << NewFD->getDeclName(); 7468 } else if (CheckFunctionTemplateSpecialization(NewFD, 7469 (HasExplicitTemplateArgs ? &TemplateArgs 7470 : nullptr), 7471 Previous)) 7472 NewFD->setInvalidDecl(); 7473 7474 // C++ [dcl.stc]p1: 7475 // A storage-class-specifier shall not be specified in an explicit 7476 // specialization (14.7.3) 7477 FunctionTemplateSpecializationInfo *Info = 7478 NewFD->getTemplateSpecializationInfo(); 7479 if (Info && SC != SC_None) { 7480 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7481 Diag(NewFD->getLocation(), 7482 diag::err_explicit_specialization_inconsistent_storage_class) 7483 << SC 7484 << FixItHint::CreateRemoval( 7485 D.getDeclSpec().getStorageClassSpecLoc()); 7486 7487 else 7488 Diag(NewFD->getLocation(), 7489 diag::ext_explicit_specialization_storage_class) 7490 << FixItHint::CreateRemoval( 7491 D.getDeclSpec().getStorageClassSpecLoc()); 7492 } 7493 7494 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7495 if (CheckMemberSpecialization(NewFD, Previous)) 7496 NewFD->setInvalidDecl(); 7497 } 7498 7499 // Perform semantic checking on the function declaration. 7500 if (!isDependentClassScopeExplicitSpecialization) { 7501 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7502 CheckMain(NewFD, D.getDeclSpec()); 7503 7504 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7505 CheckMSVCRTEntryPoint(NewFD); 7506 7507 if (!NewFD->isInvalidDecl()) 7508 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7509 isExplicitSpecialization)); 7510 } 7511 7512 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7513 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7514 "previous declaration set still overloaded"); 7515 7516 NamedDecl *PrincipalDecl = (FunctionTemplate 7517 ? cast<NamedDecl>(FunctionTemplate) 7518 : NewFD); 7519 7520 if (isFriend && D.isRedeclaration()) { 7521 AccessSpecifier Access = AS_public; 7522 if (!NewFD->isInvalidDecl()) 7523 Access = NewFD->getPreviousDecl()->getAccess(); 7524 7525 NewFD->setAccess(Access); 7526 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7527 } 7528 7529 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7530 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7531 PrincipalDecl->setNonMemberOperator(); 7532 7533 // If we have a function template, check the template parameter 7534 // list. This will check and merge default template arguments. 7535 if (FunctionTemplate) { 7536 FunctionTemplateDecl *PrevTemplate = 7537 FunctionTemplate->getPreviousDecl(); 7538 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7539 PrevTemplate ? PrevTemplate->getTemplateParameters() 7540 : nullptr, 7541 D.getDeclSpec().isFriendSpecified() 7542 ? (D.isFunctionDefinition() 7543 ? TPC_FriendFunctionTemplateDefinition 7544 : TPC_FriendFunctionTemplate) 7545 : (D.getCXXScopeSpec().isSet() && 7546 DC && DC->isRecord() && 7547 DC->isDependentContext()) 7548 ? TPC_ClassTemplateMember 7549 : TPC_FunctionTemplate); 7550 } 7551 7552 if (NewFD->isInvalidDecl()) { 7553 // Ignore all the rest of this. 7554 } else if (!D.isRedeclaration()) { 7555 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7556 AddToScope }; 7557 // Fake up an access specifier if it's supposed to be a class member. 7558 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7559 NewFD->setAccess(AS_public); 7560 7561 // Qualified decls generally require a previous declaration. 7562 if (D.getCXXScopeSpec().isSet()) { 7563 // ...with the major exception of templated-scope or 7564 // dependent-scope friend declarations. 7565 7566 // TODO: we currently also suppress this check in dependent 7567 // contexts because (1) the parameter depth will be off when 7568 // matching friend templates and (2) we might actually be 7569 // selecting a friend based on a dependent factor. But there 7570 // are situations where these conditions don't apply and we 7571 // can actually do this check immediately. 7572 if (isFriend && 7573 (TemplateParamLists.size() || 7574 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7575 CurContext->isDependentContext())) { 7576 // ignore these 7577 } else { 7578 // The user tried to provide an out-of-line definition for a 7579 // function that is a member of a class or namespace, but there 7580 // was no such member function declared (C++ [class.mfct]p2, 7581 // C++ [namespace.memdef]p2). For example: 7582 // 7583 // class X { 7584 // void f() const; 7585 // }; 7586 // 7587 // void X::f() { } // ill-formed 7588 // 7589 // Complain about this problem, and attempt to suggest close 7590 // matches (e.g., those that differ only in cv-qualifiers and 7591 // whether the parameter types are references). 7592 7593 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7594 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7595 AddToScope = ExtraArgs.AddToScope; 7596 return Result; 7597 } 7598 } 7599 7600 // Unqualified local friend declarations are required to resolve 7601 // to something. 7602 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7603 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7604 *this, Previous, NewFD, ExtraArgs, true, S)) { 7605 AddToScope = ExtraArgs.AddToScope; 7606 return Result; 7607 } 7608 } 7609 7610 } else if (!D.isFunctionDefinition() && 7611 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7612 !isFriend && !isFunctionTemplateSpecialization && 7613 !isExplicitSpecialization) { 7614 // An out-of-line member function declaration must also be a 7615 // definition (C++ [class.mfct]p2). 7616 // Note that this is not the case for explicit specializations of 7617 // function templates or member functions of class templates, per 7618 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7619 // extension for compatibility with old SWIG code which likes to 7620 // generate them. 7621 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7622 << D.getCXXScopeSpec().getRange(); 7623 } 7624 } 7625 7626 ProcessPragmaWeak(S, NewFD); 7627 checkAttributesAfterMerging(*this, *NewFD); 7628 7629 AddKnownFunctionAttributes(NewFD); 7630 7631 if (NewFD->hasAttr<OverloadableAttr>() && 7632 !NewFD->getType()->getAs<FunctionProtoType>()) { 7633 Diag(NewFD->getLocation(), 7634 diag::err_attribute_overloadable_no_prototype) 7635 << NewFD; 7636 7637 // Turn this into a variadic function with no parameters. 7638 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7639 FunctionProtoType::ExtProtoInfo EPI( 7640 Context.getDefaultCallingConvention(true, false)); 7641 EPI.Variadic = true; 7642 EPI.ExtInfo = FT->getExtInfo(); 7643 7644 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7645 NewFD->setType(R); 7646 } 7647 7648 // If there's a #pragma GCC visibility in scope, and this isn't a class 7649 // member, set the visibility of this function. 7650 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7651 AddPushedVisibilityAttribute(NewFD); 7652 7653 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7654 // marking the function. 7655 AddCFAuditedAttribute(NewFD); 7656 7657 // If this is a function definition, check if we have to apply optnone due to 7658 // a pragma. 7659 if(D.isFunctionDefinition()) 7660 AddRangeBasedOptnone(NewFD); 7661 7662 // If this is the first declaration of an extern C variable, update 7663 // the map of such variables. 7664 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7665 isIncompleteDeclExternC(*this, NewFD)) 7666 RegisterLocallyScopedExternCDecl(NewFD, S); 7667 7668 // Set this FunctionDecl's range up to the right paren. 7669 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7670 7671 if (D.isRedeclaration() && !Previous.empty()) { 7672 checkDLLAttributeRedeclaration( 7673 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7674 isExplicitSpecialization || isFunctionTemplateSpecialization); 7675 } 7676 7677 if (getLangOpts().CPlusPlus) { 7678 if (FunctionTemplate) { 7679 if (NewFD->isInvalidDecl()) 7680 FunctionTemplate->setInvalidDecl(); 7681 return FunctionTemplate; 7682 } 7683 } 7684 7685 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7686 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7687 if ((getLangOpts().OpenCLVersion >= 120) 7688 && (SC == SC_Static)) { 7689 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7690 D.setInvalidType(); 7691 } 7692 7693 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7694 if (!NewFD->getReturnType()->isVoidType()) { 7695 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7696 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7697 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7698 : FixItHint()); 7699 D.setInvalidType(); 7700 } 7701 7702 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7703 for (auto Param : NewFD->params()) 7704 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7705 } 7706 7707 MarkUnusedFileScopedDecl(NewFD); 7708 7709 if (getLangOpts().CUDA) 7710 if (IdentifierInfo *II = NewFD->getIdentifier()) 7711 if (!NewFD->isInvalidDecl() && 7712 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7713 if (II->isStr("cudaConfigureCall")) { 7714 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7715 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7716 7717 Context.setcudaConfigureCallDecl(NewFD); 7718 } 7719 } 7720 7721 // Here we have an function template explicit specialization at class scope. 7722 // The actually specialization will be postponed to template instatiation 7723 // time via the ClassScopeFunctionSpecializationDecl node. 7724 if (isDependentClassScopeExplicitSpecialization) { 7725 ClassScopeFunctionSpecializationDecl *NewSpec = 7726 ClassScopeFunctionSpecializationDecl::Create( 7727 Context, CurContext, SourceLocation(), 7728 cast<CXXMethodDecl>(NewFD), 7729 HasExplicitTemplateArgs, TemplateArgs); 7730 CurContext->addDecl(NewSpec); 7731 AddToScope = false; 7732 } 7733 7734 return NewFD; 7735 } 7736 7737 /// \brief Perform semantic checking of a new function declaration. 7738 /// 7739 /// Performs semantic analysis of the new function declaration 7740 /// NewFD. This routine performs all semantic checking that does not 7741 /// require the actual declarator involved in the declaration, and is 7742 /// used both for the declaration of functions as they are parsed 7743 /// (called via ActOnDeclarator) and for the declaration of functions 7744 /// that have been instantiated via C++ template instantiation (called 7745 /// via InstantiateDecl). 7746 /// 7747 /// \param IsExplicitSpecialization whether this new function declaration is 7748 /// an explicit specialization of the previous declaration. 7749 /// 7750 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7751 /// 7752 /// \returns true if the function declaration is a redeclaration. 7753 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7754 LookupResult &Previous, 7755 bool IsExplicitSpecialization) { 7756 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7757 "Variably modified return types are not handled here"); 7758 7759 // Determine whether the type of this function should be merged with 7760 // a previous visible declaration. This never happens for functions in C++, 7761 // and always happens in C if the previous declaration was visible. 7762 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7763 !Previous.isShadowed(); 7764 7765 // Filter out any non-conflicting previous declarations. 7766 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7767 7768 bool Redeclaration = false; 7769 NamedDecl *OldDecl = nullptr; 7770 7771 // Merge or overload the declaration with an existing declaration of 7772 // the same name, if appropriate. 7773 if (!Previous.empty()) { 7774 // Determine whether NewFD is an overload of PrevDecl or 7775 // a declaration that requires merging. If it's an overload, 7776 // there's no more work to do here; we'll just add the new 7777 // function to the scope. 7778 if (!AllowOverloadingOfFunction(Previous, Context)) { 7779 NamedDecl *Candidate = Previous.getFoundDecl(); 7780 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7781 Redeclaration = true; 7782 OldDecl = Candidate; 7783 } 7784 } else { 7785 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7786 /*NewIsUsingDecl*/ false)) { 7787 case Ovl_Match: 7788 Redeclaration = true; 7789 break; 7790 7791 case Ovl_NonFunction: 7792 Redeclaration = true; 7793 break; 7794 7795 case Ovl_Overload: 7796 Redeclaration = false; 7797 break; 7798 } 7799 7800 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7801 // If a function name is overloadable in C, then every function 7802 // with that name must be marked "overloadable". 7803 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7804 << Redeclaration << NewFD; 7805 NamedDecl *OverloadedDecl = nullptr; 7806 if (Redeclaration) 7807 OverloadedDecl = OldDecl; 7808 else if (!Previous.empty()) 7809 OverloadedDecl = Previous.getRepresentativeDecl(); 7810 if (OverloadedDecl) 7811 Diag(OverloadedDecl->getLocation(), 7812 diag::note_attribute_overloadable_prev_overload); 7813 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7814 } 7815 } 7816 } 7817 7818 // Check for a previous extern "C" declaration with this name. 7819 if (!Redeclaration && 7820 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7821 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7822 if (!Previous.empty()) { 7823 // This is an extern "C" declaration with the same name as a previous 7824 // declaration, and thus redeclares that entity... 7825 Redeclaration = true; 7826 OldDecl = Previous.getFoundDecl(); 7827 MergeTypeWithPrevious = false; 7828 7829 // ... except in the presence of __attribute__((overloadable)). 7830 if (OldDecl->hasAttr<OverloadableAttr>()) { 7831 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7832 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7833 << Redeclaration << NewFD; 7834 Diag(Previous.getFoundDecl()->getLocation(), 7835 diag::note_attribute_overloadable_prev_overload); 7836 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7837 } 7838 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7839 Redeclaration = false; 7840 OldDecl = nullptr; 7841 } 7842 } 7843 } 7844 } 7845 7846 // C++11 [dcl.constexpr]p8: 7847 // A constexpr specifier for a non-static member function that is not 7848 // a constructor declares that member function to be const. 7849 // 7850 // This needs to be delayed until we know whether this is an out-of-line 7851 // definition of a static member function. 7852 // 7853 // This rule is not present in C++1y, so we produce a backwards 7854 // compatibility warning whenever it happens in C++11. 7855 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7856 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7857 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7858 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7859 CXXMethodDecl *OldMD = nullptr; 7860 if (OldDecl) 7861 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7862 if (!OldMD || !OldMD->isStatic()) { 7863 const FunctionProtoType *FPT = 7864 MD->getType()->castAs<FunctionProtoType>(); 7865 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7866 EPI.TypeQuals |= Qualifiers::Const; 7867 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7868 FPT->getParamTypes(), EPI)); 7869 7870 // Warn that we did this, if we're not performing template instantiation. 7871 // In that case, we'll have warned already when the template was defined. 7872 if (ActiveTemplateInstantiations.empty()) { 7873 SourceLocation AddConstLoc; 7874 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7875 .IgnoreParens().getAs<FunctionTypeLoc>()) 7876 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7877 7878 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 7879 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7880 } 7881 } 7882 } 7883 7884 if (Redeclaration) { 7885 // NewFD and OldDecl represent declarations that need to be 7886 // merged. 7887 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7888 NewFD->setInvalidDecl(); 7889 return Redeclaration; 7890 } 7891 7892 Previous.clear(); 7893 Previous.addDecl(OldDecl); 7894 7895 if (FunctionTemplateDecl *OldTemplateDecl 7896 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7897 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7898 FunctionTemplateDecl *NewTemplateDecl 7899 = NewFD->getDescribedFunctionTemplate(); 7900 assert(NewTemplateDecl && "Template/non-template mismatch"); 7901 if (CXXMethodDecl *Method 7902 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7903 Method->setAccess(OldTemplateDecl->getAccess()); 7904 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7905 } 7906 7907 // If this is an explicit specialization of a member that is a function 7908 // template, mark it as a member specialization. 7909 if (IsExplicitSpecialization && 7910 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7911 NewTemplateDecl->setMemberSpecialization(); 7912 assert(OldTemplateDecl->isMemberSpecialization()); 7913 } 7914 7915 } else { 7916 // This needs to happen first so that 'inline' propagates. 7917 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7918 7919 if (isa<CXXMethodDecl>(NewFD)) { 7920 // A valid redeclaration of a C++ method must be out-of-line, 7921 // but (unfortunately) it's not necessarily a definition 7922 // because of templates, which means that the previous 7923 // declaration is not necessarily from the class definition. 7924 7925 // For just setting the access, that doesn't matter. 7926 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7927 NewFD->setAccess(oldMethod->getAccess()); 7928 7929 // Update the key-function state if necessary for this ABI. 7930 if (NewFD->isInlined() && 7931 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7932 // setNonKeyFunction needs to work with the original 7933 // declaration from the class definition, and isVirtual() is 7934 // just faster in that case, so map back to that now. 7935 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7936 if (oldMethod->isVirtual()) { 7937 Context.setNonKeyFunction(oldMethod); 7938 } 7939 } 7940 } 7941 } 7942 } 7943 7944 // Semantic checking for this function declaration (in isolation). 7945 7946 // Diagnose the use of callee-cleanup calls on unprototyped functions. 7947 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 7948 const FunctionType *NewType = cast<FunctionType>(NewQType); 7949 if (isa<FunctionNoProtoType>(NewType)) { 7950 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 7951 if (isCalleeCleanup(NewTypeInfo.getCC())) { 7952 // Windows system headers sometimes accidentally use stdcall without 7953 // (void) parameters, so use a default-error warning in this case :-/ 7954 int DiagID = NewTypeInfo.getCC() == CC_X86StdCall 7955 ? diag::warn_cconv_knr : diag::err_cconv_knr; 7956 Diag(NewFD->getLocation(), DiagID) 7957 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()); 7958 } 7959 } 7960 7961 if (getLangOpts().CPlusPlus) { 7962 // C++-specific checks. 7963 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7964 CheckConstructor(Constructor); 7965 } else if (CXXDestructorDecl *Destructor = 7966 dyn_cast<CXXDestructorDecl>(NewFD)) { 7967 CXXRecordDecl *Record = Destructor->getParent(); 7968 QualType ClassType = Context.getTypeDeclType(Record); 7969 7970 // FIXME: Shouldn't we be able to perform this check even when the class 7971 // type is dependent? Both gcc and edg can handle that. 7972 if (!ClassType->isDependentType()) { 7973 DeclarationName Name 7974 = Context.DeclarationNames.getCXXDestructorName( 7975 Context.getCanonicalType(ClassType)); 7976 if (NewFD->getDeclName() != Name) { 7977 Diag(NewFD->getLocation(), diag::err_destructor_name); 7978 NewFD->setInvalidDecl(); 7979 return Redeclaration; 7980 } 7981 } 7982 } else if (CXXConversionDecl *Conversion 7983 = dyn_cast<CXXConversionDecl>(NewFD)) { 7984 ActOnConversionDeclarator(Conversion); 7985 } 7986 7987 // Find any virtual functions that this function overrides. 7988 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7989 if (!Method->isFunctionTemplateSpecialization() && 7990 !Method->getDescribedFunctionTemplate() && 7991 Method->isCanonicalDecl()) { 7992 if (AddOverriddenMethods(Method->getParent(), Method)) { 7993 // If the function was marked as "static", we have a problem. 7994 if (NewFD->getStorageClass() == SC_Static) { 7995 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7996 } 7997 } 7998 } 7999 8000 if (Method->isStatic()) 8001 checkThisInStaticMemberFunctionType(Method); 8002 } 8003 8004 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8005 if (NewFD->isOverloadedOperator() && 8006 CheckOverloadedOperatorDeclaration(NewFD)) { 8007 NewFD->setInvalidDecl(); 8008 return Redeclaration; 8009 } 8010 8011 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8012 if (NewFD->getLiteralIdentifier() && 8013 CheckLiteralOperatorDeclaration(NewFD)) { 8014 NewFD->setInvalidDecl(); 8015 return Redeclaration; 8016 } 8017 8018 // In C++, check default arguments now that we have merged decls. Unless 8019 // the lexical context is the class, because in this case this is done 8020 // during delayed parsing anyway. 8021 if (!CurContext->isRecord()) 8022 CheckCXXDefaultArguments(NewFD); 8023 8024 // If this function declares a builtin function, check the type of this 8025 // declaration against the expected type for the builtin. 8026 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8027 ASTContext::GetBuiltinTypeError Error; 8028 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8029 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8030 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8031 // The type of this function differs from the type of the builtin, 8032 // so forget about the builtin entirely. 8033 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8034 } 8035 } 8036 8037 // If this function is declared as being extern "C", then check to see if 8038 // the function returns a UDT (class, struct, or union type) that is not C 8039 // compatible, and if it does, warn the user. 8040 // But, issue any diagnostic on the first declaration only. 8041 if (NewFD->isExternC() && Previous.empty()) { 8042 QualType R = NewFD->getReturnType(); 8043 if (R->isIncompleteType() && !R->isVoidType()) 8044 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8045 << NewFD << R; 8046 else if (!R.isPODType(Context) && !R->isVoidType() && 8047 !R->isObjCObjectPointerType()) 8048 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8049 } 8050 } 8051 return Redeclaration; 8052 } 8053 8054 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8055 // C++11 [basic.start.main]p3: 8056 // A program that [...] declares main to be inline, static or 8057 // constexpr is ill-formed. 8058 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8059 // appear in a declaration of main. 8060 // static main is not an error under C99, but we should warn about it. 8061 // We accept _Noreturn main as an extension. 8062 if (FD->getStorageClass() == SC_Static) 8063 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8064 ? diag::err_static_main : diag::warn_static_main) 8065 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8066 if (FD->isInlineSpecified()) 8067 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8068 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8069 if (DS.isNoreturnSpecified()) { 8070 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8071 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8072 Diag(NoreturnLoc, diag::ext_noreturn_main); 8073 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8074 << FixItHint::CreateRemoval(NoreturnRange); 8075 } 8076 if (FD->isConstexpr()) { 8077 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8078 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8079 FD->setConstexpr(false); 8080 } 8081 8082 if (getLangOpts().OpenCL) { 8083 Diag(FD->getLocation(), diag::err_opencl_no_main) 8084 << FD->hasAttr<OpenCLKernelAttr>(); 8085 FD->setInvalidDecl(); 8086 return; 8087 } 8088 8089 QualType T = FD->getType(); 8090 assert(T->isFunctionType() && "function decl is not of function type"); 8091 const FunctionType* FT = T->castAs<FunctionType>(); 8092 8093 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8094 // In C with GNU extensions we allow main() to have non-integer return 8095 // type, but we should warn about the extension, and we disable the 8096 // implicit-return-zero rule. 8097 8098 // GCC in C mode accepts qualified 'int'. 8099 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8100 FD->setHasImplicitReturnZero(true); 8101 else { 8102 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8103 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8104 if (RTRange.isValid()) 8105 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8106 << FixItHint::CreateReplacement(RTRange, "int"); 8107 } 8108 } else { 8109 // In C and C++, main magically returns 0 if you fall off the end; 8110 // set the flag which tells us that. 8111 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8112 8113 // All the standards say that main() should return 'int'. 8114 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8115 FD->setHasImplicitReturnZero(true); 8116 else { 8117 // Otherwise, this is just a flat-out error. 8118 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8119 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8120 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8121 : FixItHint()); 8122 FD->setInvalidDecl(true); 8123 } 8124 } 8125 8126 // Treat protoless main() as nullary. 8127 if (isa<FunctionNoProtoType>(FT)) return; 8128 8129 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8130 unsigned nparams = FTP->getNumParams(); 8131 assert(FD->getNumParams() == nparams); 8132 8133 bool HasExtraParameters = (nparams > 3); 8134 8135 // Darwin passes an undocumented fourth argument of type char**. If 8136 // other platforms start sprouting these, the logic below will start 8137 // getting shifty. 8138 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8139 HasExtraParameters = false; 8140 8141 if (HasExtraParameters) { 8142 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8143 FD->setInvalidDecl(true); 8144 nparams = 3; 8145 } 8146 8147 // FIXME: a lot of the following diagnostics would be improved 8148 // if we had some location information about types. 8149 8150 QualType CharPP = 8151 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8152 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8153 8154 for (unsigned i = 0; i < nparams; ++i) { 8155 QualType AT = FTP->getParamType(i); 8156 8157 bool mismatch = true; 8158 8159 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8160 mismatch = false; 8161 else if (Expected[i] == CharPP) { 8162 // As an extension, the following forms are okay: 8163 // char const ** 8164 // char const * const * 8165 // char * const * 8166 8167 QualifierCollector qs; 8168 const PointerType* PT; 8169 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8170 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8171 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8172 Context.CharTy)) { 8173 qs.removeConst(); 8174 mismatch = !qs.empty(); 8175 } 8176 } 8177 8178 if (mismatch) { 8179 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8180 // TODO: suggest replacing given type with expected type 8181 FD->setInvalidDecl(true); 8182 } 8183 } 8184 8185 if (nparams == 1 && !FD->isInvalidDecl()) { 8186 Diag(FD->getLocation(), diag::warn_main_one_arg); 8187 } 8188 8189 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8190 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8191 FD->setInvalidDecl(); 8192 } 8193 } 8194 8195 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8196 QualType T = FD->getType(); 8197 assert(T->isFunctionType() && "function decl is not of function type"); 8198 const FunctionType *FT = T->castAs<FunctionType>(); 8199 8200 // Set an implicit return of 'zero' if the function can return some integral, 8201 // enumeration, pointer or nullptr type. 8202 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8203 FT->getReturnType()->isAnyPointerType() || 8204 FT->getReturnType()->isNullPtrType()) 8205 // DllMain is exempt because a return value of zero means it failed. 8206 if (FD->getName() != "DllMain") 8207 FD->setHasImplicitReturnZero(true); 8208 8209 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8210 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8211 FD->setInvalidDecl(); 8212 } 8213 } 8214 8215 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8216 // FIXME: Need strict checking. In C89, we need to check for 8217 // any assignment, increment, decrement, function-calls, or 8218 // commas outside of a sizeof. In C99, it's the same list, 8219 // except that the aforementioned are allowed in unevaluated 8220 // expressions. Everything else falls under the 8221 // "may accept other forms of constant expressions" exception. 8222 // (We never end up here for C++, so the constant expression 8223 // rules there don't matter.) 8224 const Expr *Culprit; 8225 if (Init->isConstantInitializer(Context, false, &Culprit)) 8226 return false; 8227 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8228 << Culprit->getSourceRange(); 8229 return true; 8230 } 8231 8232 namespace { 8233 // Visits an initialization expression to see if OrigDecl is evaluated in 8234 // its own initialization and throws a warning if it does. 8235 class SelfReferenceChecker 8236 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8237 Sema &S; 8238 Decl *OrigDecl; 8239 bool isRecordType; 8240 bool isPODType; 8241 bool isReferenceType; 8242 8243 bool isInitList; 8244 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8245 public: 8246 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8247 8248 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8249 S(S), OrigDecl(OrigDecl) { 8250 isPODType = false; 8251 isRecordType = false; 8252 isReferenceType = false; 8253 isInitList = false; 8254 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8255 isPODType = VD->getType().isPODType(S.Context); 8256 isRecordType = VD->getType()->isRecordType(); 8257 isReferenceType = VD->getType()->isReferenceType(); 8258 } 8259 } 8260 8261 // For most expressions, just call the visitor. For initializer lists, 8262 // track the index of the field being initialized since fields are 8263 // initialized in order allowing use of previously initialized fields. 8264 void CheckExpr(Expr *E) { 8265 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8266 if (!InitList) { 8267 Visit(E); 8268 return; 8269 } 8270 8271 // Track and increment the index here. 8272 isInitList = true; 8273 InitFieldIndex.push_back(0); 8274 for (auto Child : InitList->children()) { 8275 CheckExpr(cast<Expr>(Child)); 8276 ++InitFieldIndex.back(); 8277 } 8278 InitFieldIndex.pop_back(); 8279 } 8280 8281 // Returns true if MemberExpr is checked and no futher checking is needed. 8282 // Returns false if additional checking is required. 8283 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8284 llvm::SmallVector<FieldDecl*, 4> Fields; 8285 Expr *Base = E; 8286 bool ReferenceField = false; 8287 8288 // Get the field memebers used. 8289 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8290 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8291 if (!FD) 8292 return false; 8293 Fields.push_back(FD); 8294 if (FD->getType()->isReferenceType()) 8295 ReferenceField = true; 8296 Base = ME->getBase()->IgnoreParenImpCasts(); 8297 } 8298 8299 // Keep checking only if the base Decl is the same. 8300 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8301 if (!DRE || DRE->getDecl() != OrigDecl) 8302 return false; 8303 8304 // A reference field can be bound to an unininitialized field. 8305 if (CheckReference && !ReferenceField) 8306 return true; 8307 8308 // Convert FieldDecls to their index number. 8309 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8310 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8311 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8312 } 8313 8314 // See if a warning is needed by checking the first difference in index 8315 // numbers. If field being used has index less than the field being 8316 // initialized, then the use is safe. 8317 for (auto UsedIter = UsedFieldIndex.begin(), 8318 UsedEnd = UsedFieldIndex.end(), 8319 OrigIter = InitFieldIndex.begin(), 8320 OrigEnd = InitFieldIndex.end(); 8321 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8322 if (*UsedIter < *OrigIter) 8323 return true; 8324 if (*UsedIter > *OrigIter) 8325 break; 8326 } 8327 8328 // TODO: Add a different warning which will print the field names. 8329 HandleDeclRefExpr(DRE); 8330 return true; 8331 } 8332 8333 // For most expressions, the cast is directly above the DeclRefExpr. 8334 // For conditional operators, the cast can be outside the conditional 8335 // operator if both expressions are DeclRefExpr's. 8336 void HandleValue(Expr *E) { 8337 E = E->IgnoreParens(); 8338 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8339 HandleDeclRefExpr(DRE); 8340 return; 8341 } 8342 8343 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8344 HandleValue(CO->getTrueExpr()); 8345 HandleValue(CO->getFalseExpr()); 8346 return; 8347 } 8348 8349 if (BinaryConditionalOperator *BCO = 8350 dyn_cast<BinaryConditionalOperator>(E)) { 8351 Visit(BCO->getCond()); 8352 HandleValue(BCO->getFalseExpr()); 8353 return; 8354 } 8355 8356 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8357 HandleValue(OVE->getSourceExpr()); 8358 return; 8359 } 8360 8361 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8362 if (BO->getOpcode() == BO_Comma) { 8363 Visit(BO->getLHS()); 8364 HandleValue(BO->getRHS()); 8365 return; 8366 } 8367 } 8368 8369 if (isa<MemberExpr>(E)) { 8370 if (isInitList) { 8371 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8372 false /*CheckReference*/)) 8373 return; 8374 } 8375 8376 Expr *Base = E->IgnoreParenImpCasts(); 8377 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8378 // Check for static member variables and don't warn on them. 8379 if (!isa<FieldDecl>(ME->getMemberDecl())) 8380 return; 8381 Base = ME->getBase()->IgnoreParenImpCasts(); 8382 } 8383 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8384 HandleDeclRefExpr(DRE); 8385 return; 8386 } 8387 8388 Visit(E); 8389 } 8390 8391 // Reference types not handled in HandleValue are handled here since all 8392 // uses of references are bad, not just r-value uses. 8393 void VisitDeclRefExpr(DeclRefExpr *E) { 8394 if (isReferenceType) 8395 HandleDeclRefExpr(E); 8396 } 8397 8398 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8399 if (E->getCastKind() == CK_LValueToRValue || 8400 (isRecordType && E->getCastKind() == CK_NoOp)) { 8401 HandleValue(E->getSubExpr()); 8402 return; 8403 } 8404 8405 Inherited::VisitImplicitCastExpr(E); 8406 } 8407 8408 void VisitMemberExpr(MemberExpr *E) { 8409 if (isInitList) { 8410 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8411 return; 8412 } 8413 8414 // Don't warn on arrays since they can be treated as pointers. 8415 if (E->getType()->canDecayToPointerType()) return; 8416 8417 // Warn when a non-static method call is followed by non-static member 8418 // field accesses, which is followed by a DeclRefExpr. 8419 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8420 bool Warn = (MD && !MD->isStatic()); 8421 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8422 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8423 if (!isa<FieldDecl>(ME->getMemberDecl())) 8424 Warn = false; 8425 Base = ME->getBase()->IgnoreParenImpCasts(); 8426 } 8427 8428 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8429 if (Warn) 8430 HandleDeclRefExpr(DRE); 8431 return; 8432 } 8433 8434 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8435 // Visit that expression. 8436 Visit(Base); 8437 } 8438 8439 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8440 if (E->getNumArgs() > 0) 8441 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8442 HandleDeclRefExpr(DRE); 8443 8444 Inherited::VisitCXXOperatorCallExpr(E); 8445 } 8446 8447 void VisitUnaryOperator(UnaryOperator *E) { 8448 // For POD record types, addresses of its own members are well-defined. 8449 if (E->getOpcode() == UO_AddrOf && isRecordType && 8450 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8451 if (!isPODType) 8452 HandleValue(E->getSubExpr()); 8453 return; 8454 } 8455 Inherited::VisitUnaryOperator(E); 8456 } 8457 8458 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8459 8460 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8461 if (E->getConstructor()->isCopyConstructor()) { 8462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) { 8463 HandleDeclRefExpr(DRE); 8464 } 8465 } 8466 Inherited::VisitCXXConstructExpr(E); 8467 } 8468 8469 void VisitCallExpr(CallExpr *E) { 8470 // Treat std::move as a use. 8471 if (E->getNumArgs() == 1) { 8472 if (FunctionDecl *FD = E->getDirectCallee()) { 8473 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 8474 HandleValue(E->getArg(0)); 8475 return; 8476 } 8477 } 8478 } 8479 8480 Inherited::VisitCallExpr(E); 8481 } 8482 8483 // A custom visitor for BinaryConditionalOperator is needed because the 8484 // regular visitor would check the condition and true expression separately 8485 // but both point to the same place giving duplicate diagnostics. 8486 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8487 Visit(E->getCond()); 8488 Visit(E->getFalseExpr()); 8489 } 8490 8491 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8492 Decl* ReferenceDecl = DRE->getDecl(); 8493 if (OrigDecl != ReferenceDecl) return; 8494 unsigned diag; 8495 if (isReferenceType) { 8496 diag = diag::warn_uninit_self_reference_in_reference_init; 8497 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8498 diag = diag::warn_static_self_reference_in_init; 8499 } else { 8500 diag = diag::warn_uninit_self_reference_in_init; 8501 } 8502 8503 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8504 S.PDiag(diag) 8505 << DRE->getNameInfo().getName() 8506 << OrigDecl->getLocation() 8507 << DRE->getSourceRange()); 8508 } 8509 }; 8510 8511 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8512 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8513 bool DirectInit) { 8514 // Parameters arguments are occassionially constructed with itself, 8515 // for instance, in recursive functions. Skip them. 8516 if (isa<ParmVarDecl>(OrigDecl)) 8517 return; 8518 8519 E = E->IgnoreParens(); 8520 8521 // Skip checking T a = a where T is not a record or reference type. 8522 // Doing so is a way to silence uninitialized warnings. 8523 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8524 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8525 if (ICE->getCastKind() == CK_LValueToRValue) 8526 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8527 if (DRE->getDecl() == OrigDecl) 8528 return; 8529 8530 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8531 } 8532 } 8533 8534 /// AddInitializerToDecl - Adds the initializer Init to the 8535 /// declaration dcl. If DirectInit is true, this is C++ direct 8536 /// initialization rather than copy initialization. 8537 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8538 bool DirectInit, bool TypeMayContainAuto) { 8539 // If there is no declaration, there was an error parsing it. Just ignore 8540 // the initializer. 8541 if (!RealDecl || RealDecl->isInvalidDecl()) 8542 return; 8543 8544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8545 // With declarators parsed the way they are, the parser cannot 8546 // distinguish between a normal initializer and a pure-specifier. 8547 // Thus this grotesque test. 8548 IntegerLiteral *IL; 8549 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8550 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8551 CheckPureMethod(Method, Init->getSourceRange()); 8552 else { 8553 Diag(Method->getLocation(), diag::err_member_function_initialization) 8554 << Method->getDeclName() << Init->getSourceRange(); 8555 Method->setInvalidDecl(); 8556 } 8557 return; 8558 } 8559 8560 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8561 if (!VDecl) { 8562 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8563 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8564 RealDecl->setInvalidDecl(); 8565 return; 8566 } 8567 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8568 8569 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8570 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8571 Expr *DeduceInit = Init; 8572 // Initializer could be a C++ direct-initializer. Deduction only works if it 8573 // contains exactly one expression. 8574 if (CXXDirectInit) { 8575 if (CXXDirectInit->getNumExprs() == 0) { 8576 // It isn't possible to write this directly, but it is possible to 8577 // end up in this situation with "auto x(some_pack...);" 8578 Diag(CXXDirectInit->getLocStart(), 8579 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8580 : diag::err_auto_var_init_no_expression) 8581 << VDecl->getDeclName() << VDecl->getType() 8582 << VDecl->getSourceRange(); 8583 RealDecl->setInvalidDecl(); 8584 return; 8585 } else if (CXXDirectInit->getNumExprs() > 1) { 8586 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8587 VDecl->isInitCapture() 8588 ? diag::err_init_capture_multiple_expressions 8589 : diag::err_auto_var_init_multiple_expressions) 8590 << VDecl->getDeclName() << VDecl->getType() 8591 << VDecl->getSourceRange(); 8592 RealDecl->setInvalidDecl(); 8593 return; 8594 } else { 8595 DeduceInit = CXXDirectInit->getExpr(0); 8596 if (isa<InitListExpr>(DeduceInit)) 8597 Diag(CXXDirectInit->getLocStart(), 8598 diag::err_auto_var_init_paren_braces) 8599 << VDecl->getDeclName() << VDecl->getType() 8600 << VDecl->getSourceRange(); 8601 } 8602 } 8603 8604 // Expressions default to 'id' when we're in a debugger. 8605 bool DefaultedToAuto = false; 8606 if (getLangOpts().DebuggerCastResultToId && 8607 Init->getType() == Context.UnknownAnyTy) { 8608 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8609 if (Result.isInvalid()) { 8610 VDecl->setInvalidDecl(); 8611 return; 8612 } 8613 Init = Result.get(); 8614 DefaultedToAuto = true; 8615 } 8616 8617 QualType DeducedType; 8618 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8619 DAR_Failed) 8620 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8621 if (DeducedType.isNull()) { 8622 RealDecl->setInvalidDecl(); 8623 return; 8624 } 8625 VDecl->setType(DeducedType); 8626 assert(VDecl->isLinkageValid()); 8627 8628 // In ARC, infer lifetime. 8629 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8630 VDecl->setInvalidDecl(); 8631 8632 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8633 // 'id' instead of a specific object type prevents most of our usual checks. 8634 // We only want to warn outside of template instantiations, though: 8635 // inside a template, the 'id' could have come from a parameter. 8636 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8637 DeducedType->isObjCIdType()) { 8638 SourceLocation Loc = 8639 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8640 Diag(Loc, diag::warn_auto_var_is_id) 8641 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8642 } 8643 8644 // If this is a redeclaration, check that the type we just deduced matches 8645 // the previously declared type. 8646 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8647 // We never need to merge the type, because we cannot form an incomplete 8648 // array of auto, nor deduce such a type. 8649 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8650 } 8651 8652 // Check the deduced type is valid for a variable declaration. 8653 CheckVariableDeclarationType(VDecl); 8654 if (VDecl->isInvalidDecl()) 8655 return; 8656 } 8657 8658 // dllimport cannot be used on variable definitions. 8659 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8660 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8661 VDecl->setInvalidDecl(); 8662 return; 8663 } 8664 8665 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8666 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8667 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8668 VDecl->setInvalidDecl(); 8669 return; 8670 } 8671 8672 if (!VDecl->getType()->isDependentType()) { 8673 // A definition must end up with a complete type, which means it must be 8674 // complete with the restriction that an array type might be completed by 8675 // the initializer; note that later code assumes this restriction. 8676 QualType BaseDeclType = VDecl->getType(); 8677 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8678 BaseDeclType = Array->getElementType(); 8679 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8680 diag::err_typecheck_decl_incomplete_type)) { 8681 RealDecl->setInvalidDecl(); 8682 return; 8683 } 8684 8685 // The variable can not have an abstract class type. 8686 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8687 diag::err_abstract_type_in_decl, 8688 AbstractVariableType)) 8689 VDecl->setInvalidDecl(); 8690 } 8691 8692 const VarDecl *Def; 8693 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8694 Diag(VDecl->getLocation(), diag::err_redefinition) 8695 << VDecl->getDeclName(); 8696 Diag(Def->getLocation(), diag::note_previous_definition); 8697 VDecl->setInvalidDecl(); 8698 return; 8699 } 8700 8701 const VarDecl *PrevInit = nullptr; 8702 if (getLangOpts().CPlusPlus) { 8703 // C++ [class.static.data]p4 8704 // If a static data member is of const integral or const 8705 // enumeration type, its declaration in the class definition can 8706 // specify a constant-initializer which shall be an integral 8707 // constant expression (5.19). In that case, the member can appear 8708 // in integral constant expressions. The member shall still be 8709 // defined in a namespace scope if it is used in the program and the 8710 // namespace scope definition shall not contain an initializer. 8711 // 8712 // We already performed a redefinition check above, but for static 8713 // data members we also need to check whether there was an in-class 8714 // declaration with an initializer. 8715 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8716 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8717 << VDecl->getDeclName(); 8718 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8719 return; 8720 } 8721 8722 if (VDecl->hasLocalStorage()) 8723 getCurFunction()->setHasBranchProtectedScope(); 8724 8725 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8726 VDecl->setInvalidDecl(); 8727 return; 8728 } 8729 } 8730 8731 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8732 // a kernel function cannot be initialized." 8733 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8734 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8735 VDecl->setInvalidDecl(); 8736 return; 8737 } 8738 8739 // Get the decls type and save a reference for later, since 8740 // CheckInitializerTypes may change it. 8741 QualType DclT = VDecl->getType(), SavT = DclT; 8742 8743 // Expressions default to 'id' when we're in a debugger 8744 // and we are assigning it to a variable of Objective-C pointer type. 8745 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8746 Init->getType() == Context.UnknownAnyTy) { 8747 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8748 if (Result.isInvalid()) { 8749 VDecl->setInvalidDecl(); 8750 return; 8751 } 8752 Init = Result.get(); 8753 } 8754 8755 // Perform the initialization. 8756 if (!VDecl->isInvalidDecl()) { 8757 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8758 InitializationKind Kind 8759 = DirectInit ? 8760 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8761 Init->getLocStart(), 8762 Init->getLocEnd()) 8763 : InitializationKind::CreateDirectList( 8764 VDecl->getLocation()) 8765 : InitializationKind::CreateCopy(VDecl->getLocation(), 8766 Init->getLocStart()); 8767 8768 MultiExprArg Args = Init; 8769 if (CXXDirectInit) 8770 Args = MultiExprArg(CXXDirectInit->getExprs(), 8771 CXXDirectInit->getNumExprs()); 8772 8773 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8774 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8775 if (Result.isInvalid()) { 8776 VDecl->setInvalidDecl(); 8777 return; 8778 } 8779 8780 Init = Result.getAs<Expr>(); 8781 } 8782 8783 // Check for self-references within variable initializers. 8784 // Variables declared within a function/method body (except for references) 8785 // are handled by a dataflow analysis. 8786 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8787 VDecl->getType()->isReferenceType()) { 8788 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8789 } 8790 8791 // If the type changed, it means we had an incomplete type that was 8792 // completed by the initializer. For example: 8793 // int ary[] = { 1, 3, 5 }; 8794 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8795 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8796 VDecl->setType(DclT); 8797 8798 if (!VDecl->isInvalidDecl()) { 8799 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8800 8801 if (VDecl->hasAttr<BlocksAttr>()) 8802 checkRetainCycles(VDecl, Init); 8803 8804 // It is safe to assign a weak reference into a strong variable. 8805 // Although this code can still have problems: 8806 // id x = self.weakProp; 8807 // id y = self.weakProp; 8808 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8809 // paths through the function. This should be revisited if 8810 // -Wrepeated-use-of-weak is made flow-sensitive. 8811 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8812 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8813 Init->getLocStart())) 8814 getCurFunction()->markSafeWeakUse(Init); 8815 } 8816 8817 // The initialization is usually a full-expression. 8818 // 8819 // FIXME: If this is a braced initialization of an aggregate, it is not 8820 // an expression, and each individual field initializer is a separate 8821 // full-expression. For instance, in: 8822 // 8823 // struct Temp { ~Temp(); }; 8824 // struct S { S(Temp); }; 8825 // struct T { S a, b; } t = { Temp(), Temp() } 8826 // 8827 // we should destroy the first Temp before constructing the second. 8828 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8829 false, 8830 VDecl->isConstexpr()); 8831 if (Result.isInvalid()) { 8832 VDecl->setInvalidDecl(); 8833 return; 8834 } 8835 Init = Result.get(); 8836 8837 // Attach the initializer to the decl. 8838 VDecl->setInit(Init); 8839 8840 if (VDecl->isLocalVarDecl()) { 8841 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8842 // static storage duration shall be constant expressions or string literals. 8843 // C++ does not have this restriction. 8844 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8845 const Expr *Culprit; 8846 if (VDecl->getStorageClass() == SC_Static) 8847 CheckForConstantInitializer(Init, DclT); 8848 // C89 is stricter than C99 for non-static aggregate types. 8849 // C89 6.5.7p3: All the expressions [...] in an initializer list 8850 // for an object that has aggregate or union type shall be 8851 // constant expressions. 8852 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8853 isa<InitListExpr>(Init) && 8854 !Init->isConstantInitializer(Context, false, &Culprit)) 8855 Diag(Culprit->getExprLoc(), 8856 diag::ext_aggregate_init_not_constant) 8857 << Culprit->getSourceRange(); 8858 } 8859 } else if (VDecl->isStaticDataMember() && 8860 VDecl->getLexicalDeclContext()->isRecord()) { 8861 // This is an in-class initialization for a static data member, e.g., 8862 // 8863 // struct S { 8864 // static const int value = 17; 8865 // }; 8866 8867 // C++ [class.mem]p4: 8868 // A member-declarator can contain a constant-initializer only 8869 // if it declares a static member (9.4) of const integral or 8870 // const enumeration type, see 9.4.2. 8871 // 8872 // C++11 [class.static.data]p3: 8873 // If a non-volatile const static data member is of integral or 8874 // enumeration type, its declaration in the class definition can 8875 // specify a brace-or-equal-initializer in which every initalizer-clause 8876 // that is an assignment-expression is a constant expression. A static 8877 // data member of literal type can be declared in the class definition 8878 // with the constexpr specifier; if so, its declaration shall specify a 8879 // brace-or-equal-initializer in which every initializer-clause that is 8880 // an assignment-expression is a constant expression. 8881 8882 // Do nothing on dependent types. 8883 if (DclT->isDependentType()) { 8884 8885 // Allow any 'static constexpr' members, whether or not they are of literal 8886 // type. We separately check that every constexpr variable is of literal 8887 // type. 8888 } else if (VDecl->isConstexpr()) { 8889 8890 // Require constness. 8891 } else if (!DclT.isConstQualified()) { 8892 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8893 << Init->getSourceRange(); 8894 VDecl->setInvalidDecl(); 8895 8896 // We allow integer constant expressions in all cases. 8897 } else if (DclT->isIntegralOrEnumerationType()) { 8898 // Check whether the expression is a constant expression. 8899 SourceLocation Loc; 8900 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8901 // In C++11, a non-constexpr const static data member with an 8902 // in-class initializer cannot be volatile. 8903 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8904 else if (Init->isValueDependent()) 8905 ; // Nothing to check. 8906 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8907 ; // Ok, it's an ICE! 8908 else if (Init->isEvaluatable(Context)) { 8909 // If we can constant fold the initializer through heroics, accept it, 8910 // but report this as a use of an extension for -pedantic. 8911 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8912 << Init->getSourceRange(); 8913 } else { 8914 // Otherwise, this is some crazy unknown case. Report the issue at the 8915 // location provided by the isIntegerConstantExpr failed check. 8916 Diag(Loc, diag::err_in_class_initializer_non_constant) 8917 << Init->getSourceRange(); 8918 VDecl->setInvalidDecl(); 8919 } 8920 8921 // We allow foldable floating-point constants as an extension. 8922 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8923 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8924 // it anyway and provide a fixit to add the 'constexpr'. 8925 if (getLangOpts().CPlusPlus11) { 8926 Diag(VDecl->getLocation(), 8927 diag::ext_in_class_initializer_float_type_cxx11) 8928 << DclT << Init->getSourceRange(); 8929 Diag(VDecl->getLocStart(), 8930 diag::note_in_class_initializer_float_type_cxx11) 8931 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8932 } else { 8933 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8934 << DclT << Init->getSourceRange(); 8935 8936 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8937 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8938 << Init->getSourceRange(); 8939 VDecl->setInvalidDecl(); 8940 } 8941 } 8942 8943 // Suggest adding 'constexpr' in C++11 for literal types. 8944 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8945 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8946 << DclT << Init->getSourceRange() 8947 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8948 VDecl->setConstexpr(true); 8949 8950 } else { 8951 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8952 << DclT << Init->getSourceRange(); 8953 VDecl->setInvalidDecl(); 8954 } 8955 } else if (VDecl->isFileVarDecl()) { 8956 if (VDecl->getStorageClass() == SC_Extern && 8957 (!getLangOpts().CPlusPlus || 8958 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8959 VDecl->isExternC())) && 8960 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8961 Diag(VDecl->getLocation(), diag::warn_extern_init); 8962 8963 // C99 6.7.8p4. All file scoped initializers need to be constant. 8964 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8965 CheckForConstantInitializer(Init, DclT); 8966 } 8967 8968 // We will represent direct-initialization similarly to copy-initialization: 8969 // int x(1); -as-> int x = 1; 8970 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8971 // 8972 // Clients that want to distinguish between the two forms, can check for 8973 // direct initializer using VarDecl::getInitStyle(). 8974 // A major benefit is that clients that don't particularly care about which 8975 // exactly form was it (like the CodeGen) can handle both cases without 8976 // special case code. 8977 8978 // C++ 8.5p11: 8979 // The form of initialization (using parentheses or '=') is generally 8980 // insignificant, but does matter when the entity being initialized has a 8981 // class type. 8982 if (CXXDirectInit) { 8983 assert(DirectInit && "Call-style initializer must be direct init."); 8984 VDecl->setInitStyle(VarDecl::CallInit); 8985 } else if (DirectInit) { 8986 // This must be list-initialization. No other way is direct-initialization. 8987 VDecl->setInitStyle(VarDecl::ListInit); 8988 } 8989 8990 CheckCompleteVariableDeclaration(VDecl); 8991 } 8992 8993 /// ActOnInitializerError - Given that there was an error parsing an 8994 /// initializer for the given declaration, try to return to some form 8995 /// of sanity. 8996 void Sema::ActOnInitializerError(Decl *D) { 8997 // Our main concern here is re-establishing invariants like "a 8998 // variable's type is either dependent or complete". 8999 if (!D || D->isInvalidDecl()) return; 9000 9001 VarDecl *VD = dyn_cast<VarDecl>(D); 9002 if (!VD) return; 9003 9004 // Auto types are meaningless if we can't make sense of the initializer. 9005 if (ParsingInitForAutoVars.count(D)) { 9006 D->setInvalidDecl(); 9007 return; 9008 } 9009 9010 QualType Ty = VD->getType(); 9011 if (Ty->isDependentType()) return; 9012 9013 // Require a complete type. 9014 if (RequireCompleteType(VD->getLocation(), 9015 Context.getBaseElementType(Ty), 9016 diag::err_typecheck_decl_incomplete_type)) { 9017 VD->setInvalidDecl(); 9018 return; 9019 } 9020 9021 // Require a non-abstract type. 9022 if (RequireNonAbstractType(VD->getLocation(), Ty, 9023 diag::err_abstract_type_in_decl, 9024 AbstractVariableType)) { 9025 VD->setInvalidDecl(); 9026 return; 9027 } 9028 9029 // Don't bother complaining about constructors or destructors, 9030 // though. 9031 } 9032 9033 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9034 bool TypeMayContainAuto) { 9035 // If there is no declaration, there was an error parsing it. Just ignore it. 9036 if (!RealDecl) 9037 return; 9038 9039 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9040 QualType Type = Var->getType(); 9041 9042 // C++11 [dcl.spec.auto]p3 9043 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9044 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9045 << Var->getDeclName() << Type; 9046 Var->setInvalidDecl(); 9047 return; 9048 } 9049 9050 // C++11 [class.static.data]p3: A static data member can be declared with 9051 // the constexpr specifier; if so, its declaration shall specify 9052 // a brace-or-equal-initializer. 9053 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9054 // the definition of a variable [...] or the declaration of a static data 9055 // member. 9056 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9057 if (Var->isStaticDataMember()) 9058 Diag(Var->getLocation(), 9059 diag::err_constexpr_static_mem_var_requires_init) 9060 << Var->getDeclName(); 9061 else 9062 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9063 Var->setInvalidDecl(); 9064 return; 9065 } 9066 9067 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9068 // be initialized. 9069 if (!Var->isInvalidDecl() && 9070 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9071 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9072 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9073 Var->setInvalidDecl(); 9074 return; 9075 } 9076 9077 switch (Var->isThisDeclarationADefinition()) { 9078 case VarDecl::Definition: 9079 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9080 break; 9081 9082 // We have an out-of-line definition of a static data member 9083 // that has an in-class initializer, so we type-check this like 9084 // a declaration. 9085 // 9086 // Fall through 9087 9088 case VarDecl::DeclarationOnly: 9089 // It's only a declaration. 9090 9091 // Block scope. C99 6.7p7: If an identifier for an object is 9092 // declared with no linkage (C99 6.2.2p6), the type for the 9093 // object shall be complete. 9094 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9095 !Var->hasLinkage() && !Var->isInvalidDecl() && 9096 RequireCompleteType(Var->getLocation(), Type, 9097 diag::err_typecheck_decl_incomplete_type)) 9098 Var->setInvalidDecl(); 9099 9100 // Make sure that the type is not abstract. 9101 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9102 RequireNonAbstractType(Var->getLocation(), Type, 9103 diag::err_abstract_type_in_decl, 9104 AbstractVariableType)) 9105 Var->setInvalidDecl(); 9106 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9107 Var->getStorageClass() == SC_PrivateExtern) { 9108 Diag(Var->getLocation(), diag::warn_private_extern); 9109 Diag(Var->getLocation(), diag::note_private_extern); 9110 } 9111 9112 return; 9113 9114 case VarDecl::TentativeDefinition: 9115 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9116 // object that has file scope without an initializer, and without a 9117 // storage-class specifier or with the storage-class specifier "static", 9118 // constitutes a tentative definition. Note: A tentative definition with 9119 // external linkage is valid (C99 6.2.2p5). 9120 if (!Var->isInvalidDecl()) { 9121 if (const IncompleteArrayType *ArrayT 9122 = Context.getAsIncompleteArrayType(Type)) { 9123 if (RequireCompleteType(Var->getLocation(), 9124 ArrayT->getElementType(), 9125 diag::err_illegal_decl_array_incomplete_type)) 9126 Var->setInvalidDecl(); 9127 } else if (Var->getStorageClass() == SC_Static) { 9128 // C99 6.9.2p3: If the declaration of an identifier for an object is 9129 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9130 // declared type shall not be an incomplete type. 9131 // NOTE: code such as the following 9132 // static struct s; 9133 // struct s { int a; }; 9134 // is accepted by gcc. Hence here we issue a warning instead of 9135 // an error and we do not invalidate the static declaration. 9136 // NOTE: to avoid multiple warnings, only check the first declaration. 9137 if (Var->isFirstDecl()) 9138 RequireCompleteType(Var->getLocation(), Type, 9139 diag::ext_typecheck_decl_incomplete_type); 9140 } 9141 } 9142 9143 // Record the tentative definition; we're done. 9144 if (!Var->isInvalidDecl()) 9145 TentativeDefinitions.push_back(Var); 9146 return; 9147 } 9148 9149 // Provide a specific diagnostic for uninitialized variable 9150 // definitions with incomplete array type. 9151 if (Type->isIncompleteArrayType()) { 9152 Diag(Var->getLocation(), 9153 diag::err_typecheck_incomplete_array_needs_initializer); 9154 Var->setInvalidDecl(); 9155 return; 9156 } 9157 9158 // Provide a specific diagnostic for uninitialized variable 9159 // definitions with reference type. 9160 if (Type->isReferenceType()) { 9161 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9162 << Var->getDeclName() 9163 << SourceRange(Var->getLocation(), Var->getLocation()); 9164 Var->setInvalidDecl(); 9165 return; 9166 } 9167 9168 // Do not attempt to type-check the default initializer for a 9169 // variable with dependent type. 9170 if (Type->isDependentType()) 9171 return; 9172 9173 if (Var->isInvalidDecl()) 9174 return; 9175 9176 if (!Var->hasAttr<AliasAttr>()) { 9177 if (RequireCompleteType(Var->getLocation(), 9178 Context.getBaseElementType(Type), 9179 diag::err_typecheck_decl_incomplete_type)) { 9180 Var->setInvalidDecl(); 9181 return; 9182 } 9183 } 9184 9185 // The variable can not have an abstract class type. 9186 if (RequireNonAbstractType(Var->getLocation(), Type, 9187 diag::err_abstract_type_in_decl, 9188 AbstractVariableType)) { 9189 Var->setInvalidDecl(); 9190 return; 9191 } 9192 9193 // Check for jumps past the implicit initializer. C++0x 9194 // clarifies that this applies to a "variable with automatic 9195 // storage duration", not a "local variable". 9196 // C++11 [stmt.dcl]p3 9197 // A program that jumps from a point where a variable with automatic 9198 // storage duration is not in scope to a point where it is in scope is 9199 // ill-formed unless the variable has scalar type, class type with a 9200 // trivial default constructor and a trivial destructor, a cv-qualified 9201 // version of one of these types, or an array of one of the preceding 9202 // types and is declared without an initializer. 9203 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9204 if (const RecordType *Record 9205 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9206 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9207 // Mark the function for further checking even if the looser rules of 9208 // C++11 do not require such checks, so that we can diagnose 9209 // incompatibilities with C++98. 9210 if (!CXXRecord->isPOD()) 9211 getCurFunction()->setHasBranchProtectedScope(); 9212 } 9213 } 9214 9215 // C++03 [dcl.init]p9: 9216 // If no initializer is specified for an object, and the 9217 // object is of (possibly cv-qualified) non-POD class type (or 9218 // array thereof), the object shall be default-initialized; if 9219 // the object is of const-qualified type, the underlying class 9220 // type shall have a user-declared default 9221 // constructor. Otherwise, if no initializer is specified for 9222 // a non- static object, the object and its subobjects, if 9223 // any, have an indeterminate initial value); if the object 9224 // or any of its subobjects are of const-qualified type, the 9225 // program is ill-formed. 9226 // C++0x [dcl.init]p11: 9227 // If no initializer is specified for an object, the object is 9228 // default-initialized; [...]. 9229 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9230 InitializationKind Kind 9231 = InitializationKind::CreateDefault(Var->getLocation()); 9232 9233 InitializationSequence InitSeq(*this, Entity, Kind, None); 9234 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9235 if (Init.isInvalid()) 9236 Var->setInvalidDecl(); 9237 else if (Init.get()) { 9238 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9239 // This is important for template substitution. 9240 Var->setInitStyle(VarDecl::CallInit); 9241 } 9242 9243 CheckCompleteVariableDeclaration(Var); 9244 } 9245 } 9246 9247 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9248 VarDecl *VD = dyn_cast<VarDecl>(D); 9249 if (!VD) { 9250 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9251 D->setInvalidDecl(); 9252 return; 9253 } 9254 9255 VD->setCXXForRangeDecl(true); 9256 9257 // for-range-declaration cannot be given a storage class specifier. 9258 int Error = -1; 9259 switch (VD->getStorageClass()) { 9260 case SC_None: 9261 break; 9262 case SC_Extern: 9263 Error = 0; 9264 break; 9265 case SC_Static: 9266 Error = 1; 9267 break; 9268 case SC_PrivateExtern: 9269 Error = 2; 9270 break; 9271 case SC_Auto: 9272 Error = 3; 9273 break; 9274 case SC_Register: 9275 Error = 4; 9276 break; 9277 case SC_OpenCLWorkGroupLocal: 9278 llvm_unreachable("Unexpected storage class"); 9279 } 9280 if (VD->isConstexpr()) 9281 Error = 5; 9282 if (Error != -1) { 9283 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9284 << VD->getDeclName() << Error; 9285 D->setInvalidDecl(); 9286 } 9287 } 9288 9289 StmtResult 9290 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9291 IdentifierInfo *Ident, 9292 ParsedAttributes &Attrs, 9293 SourceLocation AttrEnd) { 9294 // C++1y [stmt.iter]p1: 9295 // A range-based for statement of the form 9296 // for ( for-range-identifier : for-range-initializer ) statement 9297 // is equivalent to 9298 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9299 DeclSpec DS(Attrs.getPool().getFactory()); 9300 9301 const char *PrevSpec; 9302 unsigned DiagID; 9303 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9304 getPrintingPolicy()); 9305 9306 Declarator D(DS, Declarator::ForContext); 9307 D.SetIdentifier(Ident, IdentLoc); 9308 D.takeAttributes(Attrs, AttrEnd); 9309 9310 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9311 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9312 EmptyAttrs, IdentLoc); 9313 Decl *Var = ActOnDeclarator(S, D); 9314 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9315 FinalizeDeclaration(Var); 9316 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9317 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9318 } 9319 9320 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9321 if (var->isInvalidDecl()) return; 9322 9323 // In ARC, don't allow jumps past the implicit initialization of a 9324 // local retaining variable. 9325 if (getLangOpts().ObjCAutoRefCount && 9326 var->hasLocalStorage()) { 9327 switch (var->getType().getObjCLifetime()) { 9328 case Qualifiers::OCL_None: 9329 case Qualifiers::OCL_ExplicitNone: 9330 case Qualifiers::OCL_Autoreleasing: 9331 break; 9332 9333 case Qualifiers::OCL_Weak: 9334 case Qualifiers::OCL_Strong: 9335 getCurFunction()->setHasBranchProtectedScope(); 9336 break; 9337 } 9338 } 9339 9340 // Warn about externally-visible variables being defined without a 9341 // prior declaration. We only want to do this for global 9342 // declarations, but we also specifically need to avoid doing it for 9343 // class members because the linkage of an anonymous class can 9344 // change if it's later given a typedef name. 9345 if (var->isThisDeclarationADefinition() && 9346 var->getDeclContext()->getRedeclContext()->isFileContext() && 9347 var->isExternallyVisible() && var->hasLinkage() && 9348 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9349 var->getLocation())) { 9350 // Find a previous declaration that's not a definition. 9351 VarDecl *prev = var->getPreviousDecl(); 9352 while (prev && prev->isThisDeclarationADefinition()) 9353 prev = prev->getPreviousDecl(); 9354 9355 if (!prev) 9356 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9357 } 9358 9359 if (var->getTLSKind() == VarDecl::TLS_Static) { 9360 const Expr *Culprit; 9361 if (var->getType().isDestructedType()) { 9362 // GNU C++98 edits for __thread, [basic.start.term]p3: 9363 // The type of an object with thread storage duration shall not 9364 // have a non-trivial destructor. 9365 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9366 if (getLangOpts().CPlusPlus11) 9367 Diag(var->getLocation(), diag::note_use_thread_local); 9368 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9369 !var->getInit()->isConstantInitializer( 9370 Context, var->getType()->isReferenceType(), &Culprit)) { 9371 // GNU C++98 edits for __thread, [basic.start.init]p4: 9372 // An object of thread storage duration shall not require dynamic 9373 // initialization. 9374 // FIXME: Need strict checking here. 9375 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9376 << Culprit->getSourceRange(); 9377 if (getLangOpts().CPlusPlus11) 9378 Diag(var->getLocation(), diag::note_use_thread_local); 9379 } 9380 9381 } 9382 9383 if (var->isThisDeclarationADefinition() && 9384 ActiveTemplateInstantiations.empty()) { 9385 PragmaStack<StringLiteral *> *Stack = nullptr; 9386 int SectionFlags = PSF_Implicit | PSF_Read; 9387 if (var->getType().isConstQualified()) 9388 Stack = &ConstSegStack; 9389 else if (!var->getInit()) { 9390 Stack = &BSSSegStack; 9391 SectionFlags |= PSF_Write; 9392 } else { 9393 Stack = &DataSegStack; 9394 SectionFlags |= PSF_Write; 9395 } 9396 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9397 var->addAttr( 9398 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9399 Stack->CurrentValue->getString(), 9400 Stack->CurrentPragmaLocation)); 9401 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9402 if (UnifySection(SA->getName(), SectionFlags, var)) 9403 var->dropAttr<SectionAttr>(); 9404 9405 // Apply the init_seg attribute if this has an initializer. If the 9406 // initializer turns out to not be dynamic, we'll end up ignoring this 9407 // attribute. 9408 if (CurInitSeg && var->getInit()) 9409 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9410 CurInitSegLoc)); 9411 } 9412 9413 // All the following checks are C++ only. 9414 if (!getLangOpts().CPlusPlus) return; 9415 9416 QualType type = var->getType(); 9417 if (type->isDependentType()) return; 9418 9419 // __block variables might require us to capture a copy-initializer. 9420 if (var->hasAttr<BlocksAttr>()) { 9421 // It's currently invalid to ever have a __block variable with an 9422 // array type; should we diagnose that here? 9423 9424 // Regardless, we don't want to ignore array nesting when 9425 // constructing this copy. 9426 if (type->isStructureOrClassType()) { 9427 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9428 SourceLocation poi = var->getLocation(); 9429 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9430 ExprResult result 9431 = PerformMoveOrCopyInitialization( 9432 InitializedEntity::InitializeBlock(poi, type, false), 9433 var, var->getType(), varRef, /*AllowNRVO=*/true); 9434 if (!result.isInvalid()) { 9435 result = MaybeCreateExprWithCleanups(result); 9436 Expr *init = result.getAs<Expr>(); 9437 Context.setBlockVarCopyInits(var, init); 9438 } 9439 } 9440 } 9441 9442 Expr *Init = var->getInit(); 9443 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9444 QualType baseType = Context.getBaseElementType(type); 9445 9446 if (!var->getDeclContext()->isDependentContext() && 9447 Init && !Init->isValueDependent()) { 9448 if (IsGlobal && !var->isConstexpr() && 9449 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9450 var->getLocation())) { 9451 // Warn about globals which don't have a constant initializer. Don't 9452 // warn about globals with a non-trivial destructor because we already 9453 // warned about them. 9454 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9455 if (!(RD && !RD->hasTrivialDestructor()) && 9456 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9457 Diag(var->getLocation(), diag::warn_global_constructor) 9458 << Init->getSourceRange(); 9459 } 9460 9461 if (var->isConstexpr()) { 9462 SmallVector<PartialDiagnosticAt, 8> Notes; 9463 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9464 SourceLocation DiagLoc = var->getLocation(); 9465 // If the note doesn't add any useful information other than a source 9466 // location, fold it into the primary diagnostic. 9467 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9468 diag::note_invalid_subexpr_in_const_expr) { 9469 DiagLoc = Notes[0].first; 9470 Notes.clear(); 9471 } 9472 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9473 << var << Init->getSourceRange(); 9474 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9475 Diag(Notes[I].first, Notes[I].second); 9476 } 9477 } else if (var->isUsableInConstantExpressions(Context)) { 9478 // Check whether the initializer of a const variable of integral or 9479 // enumeration type is an ICE now, since we can't tell whether it was 9480 // initialized by a constant expression if we check later. 9481 var->checkInitIsICE(); 9482 } 9483 } 9484 9485 // Require the destructor. 9486 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9487 FinalizeVarWithDestructor(var, recordType); 9488 } 9489 9490 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9491 /// any semantic actions necessary after any initializer has been attached. 9492 void 9493 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9494 // Note that we are no longer parsing the initializer for this declaration. 9495 ParsingInitForAutoVars.erase(ThisDecl); 9496 9497 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9498 if (!VD) 9499 return; 9500 9501 checkAttributesAfterMerging(*this, *VD); 9502 9503 // Static locals inherit dll attributes from their function. 9504 if (VD->isStaticLocal()) { 9505 if (FunctionDecl *FD = 9506 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9507 if (Attr *A = getDLLAttr(FD)) { 9508 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9509 NewAttr->setInherited(true); 9510 VD->addAttr(NewAttr); 9511 } 9512 } 9513 } 9514 9515 // Imported static data members cannot be defined out-of-line. 9516 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) { 9517 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9518 VD->isThisDeclarationADefinition()) { 9519 // We allow definitions of dllimport class template static data members 9520 // with a warning. 9521 CXXRecordDecl *Context = 9522 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9523 bool IsClassTemplateMember = 9524 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9525 Context->getDescribedClassTemplate(); 9526 9527 Diag(VD->getLocation(), 9528 IsClassTemplateMember 9529 ? diag::warn_attribute_dllimport_static_field_definition 9530 : diag::err_attribute_dllimport_static_field_definition); 9531 Diag(IA->getLocation(), diag::note_attribute); 9532 if (!IsClassTemplateMember) 9533 VD->setInvalidDecl(); 9534 } 9535 } 9536 9537 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9538 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9539 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9540 VD->dropAttr<UsedAttr>(); 9541 } 9542 } 9543 9544 if (!VD->isInvalidDecl() && 9545 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9546 if (const VarDecl *Def = VD->getDefinition()) { 9547 if (Def->hasAttr<AliasAttr>()) { 9548 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9549 << VD->getDeclName(); 9550 Diag(Def->getLocation(), diag::note_previous_definition); 9551 VD->setInvalidDecl(); 9552 } 9553 } 9554 } 9555 9556 const DeclContext *DC = VD->getDeclContext(); 9557 // If there's a #pragma GCC visibility in scope, and this isn't a class 9558 // member, set the visibility of this variable. 9559 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9560 AddPushedVisibilityAttribute(VD); 9561 9562 // FIXME: Warn on unused templates. 9563 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9564 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9565 MarkUnusedFileScopedDecl(VD); 9566 9567 // Now we have parsed the initializer and can update the table of magic 9568 // tag values. 9569 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9570 !VD->getType()->isIntegralOrEnumerationType()) 9571 return; 9572 9573 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9574 const Expr *MagicValueExpr = VD->getInit(); 9575 if (!MagicValueExpr) { 9576 continue; 9577 } 9578 llvm::APSInt MagicValueInt; 9579 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9580 Diag(I->getRange().getBegin(), 9581 diag::err_type_tag_for_datatype_not_ice) 9582 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9583 continue; 9584 } 9585 if (MagicValueInt.getActiveBits() > 64) { 9586 Diag(I->getRange().getBegin(), 9587 diag::err_type_tag_for_datatype_too_large) 9588 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9589 continue; 9590 } 9591 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9592 RegisterTypeTagForDatatype(I->getArgumentKind(), 9593 MagicValue, 9594 I->getMatchingCType(), 9595 I->getLayoutCompatible(), 9596 I->getMustBeNull()); 9597 } 9598 } 9599 9600 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9601 ArrayRef<Decl *> Group) { 9602 SmallVector<Decl*, 8> Decls; 9603 9604 if (DS.isTypeSpecOwned()) 9605 Decls.push_back(DS.getRepAsDecl()); 9606 9607 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9608 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9609 if (Decl *D = Group[i]) { 9610 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9611 if (!FirstDeclaratorInGroup) 9612 FirstDeclaratorInGroup = DD; 9613 Decls.push_back(D); 9614 } 9615 9616 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9617 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9618 HandleTagNumbering(*this, Tag, S); 9619 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9620 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9621 } 9622 } 9623 9624 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9625 } 9626 9627 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9628 /// group, performing any necessary semantic checking. 9629 Sema::DeclGroupPtrTy 9630 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9631 bool TypeMayContainAuto) { 9632 // C++0x [dcl.spec.auto]p7: 9633 // If the type deduced for the template parameter U is not the same in each 9634 // deduction, the program is ill-formed. 9635 // FIXME: When initializer-list support is added, a distinction is needed 9636 // between the deduced type U and the deduced type which 'auto' stands for. 9637 // auto a = 0, b = { 1, 2, 3 }; 9638 // is legal because the deduced type U is 'int' in both cases. 9639 if (TypeMayContainAuto && Group.size() > 1) { 9640 QualType Deduced; 9641 CanQualType DeducedCanon; 9642 VarDecl *DeducedDecl = nullptr; 9643 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9644 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9645 AutoType *AT = D->getType()->getContainedAutoType(); 9646 // Don't reissue diagnostics when instantiating a template. 9647 if (AT && D->isInvalidDecl()) 9648 break; 9649 QualType U = AT ? AT->getDeducedType() : QualType(); 9650 if (!U.isNull()) { 9651 CanQualType UCanon = Context.getCanonicalType(U); 9652 if (Deduced.isNull()) { 9653 Deduced = U; 9654 DeducedCanon = UCanon; 9655 DeducedDecl = D; 9656 } else if (DeducedCanon != UCanon) { 9657 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9658 diag::err_auto_different_deductions) 9659 << (AT->isDecltypeAuto() ? 1 : 0) 9660 << Deduced << DeducedDecl->getDeclName() 9661 << U << D->getDeclName() 9662 << DeducedDecl->getInit()->getSourceRange() 9663 << D->getInit()->getSourceRange(); 9664 D->setInvalidDecl(); 9665 break; 9666 } 9667 } 9668 } 9669 } 9670 } 9671 9672 ActOnDocumentableDecls(Group); 9673 9674 return DeclGroupPtrTy::make( 9675 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9676 } 9677 9678 void Sema::ActOnDocumentableDecl(Decl *D) { 9679 ActOnDocumentableDecls(D); 9680 } 9681 9682 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9683 // Don't parse the comment if Doxygen diagnostics are ignored. 9684 if (Group.empty() || !Group[0]) 9685 return; 9686 9687 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9688 return; 9689 9690 if (Group.size() >= 2) { 9691 // This is a decl group. Normally it will contain only declarations 9692 // produced from declarator list. But in case we have any definitions or 9693 // additional declaration references: 9694 // 'typedef struct S {} S;' 9695 // 'typedef struct S *S;' 9696 // 'struct S *pS;' 9697 // FinalizeDeclaratorGroup adds these as separate declarations. 9698 Decl *MaybeTagDecl = Group[0]; 9699 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9700 Group = Group.slice(1); 9701 } 9702 } 9703 9704 // See if there are any new comments that are not attached to a decl. 9705 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9706 if (!Comments.empty() && 9707 !Comments.back()->isAttached()) { 9708 // There is at least one comment that not attached to a decl. 9709 // Maybe it should be attached to one of these decls? 9710 // 9711 // Note that this way we pick up not only comments that precede the 9712 // declaration, but also comments that *follow* the declaration -- thanks to 9713 // the lookahead in the lexer: we've consumed the semicolon and looked 9714 // ahead through comments. 9715 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9716 Context.getCommentForDecl(Group[i], &PP); 9717 } 9718 } 9719 9720 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9721 /// to introduce parameters into function prototype scope. 9722 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9723 const DeclSpec &DS = D.getDeclSpec(); 9724 9725 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9726 9727 // C++03 [dcl.stc]p2 also permits 'auto'. 9728 VarDecl::StorageClass StorageClass = SC_None; 9729 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9730 StorageClass = SC_Register; 9731 } else if (getLangOpts().CPlusPlus && 9732 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9733 StorageClass = SC_Auto; 9734 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9735 Diag(DS.getStorageClassSpecLoc(), 9736 diag::err_invalid_storage_class_in_func_decl); 9737 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9738 } 9739 9740 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9741 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9742 << DeclSpec::getSpecifierName(TSCS); 9743 if (DS.isConstexprSpecified()) 9744 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9745 << 0; 9746 9747 DiagnoseFunctionSpecifiers(DS); 9748 9749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9750 QualType parmDeclType = TInfo->getType(); 9751 9752 if (getLangOpts().CPlusPlus) { 9753 // Check that there are no default arguments inside the type of this 9754 // parameter. 9755 CheckExtraCXXDefaultArguments(D); 9756 9757 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9758 if (D.getCXXScopeSpec().isSet()) { 9759 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9760 << D.getCXXScopeSpec().getRange(); 9761 D.getCXXScopeSpec().clear(); 9762 } 9763 } 9764 9765 // Ensure we have a valid name 9766 IdentifierInfo *II = nullptr; 9767 if (D.hasName()) { 9768 II = D.getIdentifier(); 9769 if (!II) { 9770 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9771 << GetNameForDeclarator(D).getName(); 9772 D.setInvalidType(true); 9773 } 9774 } 9775 9776 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9777 if (II) { 9778 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9779 ForRedeclaration); 9780 LookupName(R, S); 9781 if (R.isSingleResult()) { 9782 NamedDecl *PrevDecl = R.getFoundDecl(); 9783 if (PrevDecl->isTemplateParameter()) { 9784 // Maybe we will complain about the shadowed template parameter. 9785 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9786 // Just pretend that we didn't see the previous declaration. 9787 PrevDecl = nullptr; 9788 } else if (S->isDeclScope(PrevDecl)) { 9789 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9790 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9791 9792 // Recover by removing the name 9793 II = nullptr; 9794 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9795 D.setInvalidType(true); 9796 } 9797 } 9798 } 9799 9800 // Temporarily put parameter variables in the translation unit, not 9801 // the enclosing context. This prevents them from accidentally 9802 // looking like class members in C++. 9803 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9804 D.getLocStart(), 9805 D.getIdentifierLoc(), II, 9806 parmDeclType, TInfo, 9807 StorageClass); 9808 9809 if (D.isInvalidType()) 9810 New->setInvalidDecl(); 9811 9812 assert(S->isFunctionPrototypeScope()); 9813 assert(S->getFunctionPrototypeDepth() >= 1); 9814 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9815 S->getNextFunctionPrototypeIndex()); 9816 9817 // Add the parameter declaration into this scope. 9818 S->AddDecl(New); 9819 if (II) 9820 IdResolver.AddDecl(New); 9821 9822 ProcessDeclAttributes(S, New, D); 9823 9824 if (D.getDeclSpec().isModulePrivateSpecified()) 9825 Diag(New->getLocation(), diag::err_module_private_local) 9826 << 1 << New->getDeclName() 9827 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9828 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9829 9830 if (New->hasAttr<BlocksAttr>()) { 9831 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9832 } 9833 return New; 9834 } 9835 9836 /// \brief Synthesizes a variable for a parameter arising from a 9837 /// typedef. 9838 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9839 SourceLocation Loc, 9840 QualType T) { 9841 /* FIXME: setting StartLoc == Loc. 9842 Would it be worth to modify callers so as to provide proper source 9843 location for the unnamed parameters, embedding the parameter's type? */ 9844 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9845 T, Context.getTrivialTypeSourceInfo(T, Loc), 9846 SC_None, nullptr); 9847 Param->setImplicit(); 9848 return Param; 9849 } 9850 9851 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9852 ParmVarDecl * const *ParamEnd) { 9853 // Don't diagnose unused-parameter errors in template instantiations; we 9854 // will already have done so in the template itself. 9855 if (!ActiveTemplateInstantiations.empty()) 9856 return; 9857 9858 for (; Param != ParamEnd; ++Param) { 9859 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9860 !(*Param)->hasAttr<UnusedAttr>()) { 9861 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9862 << (*Param)->getDeclName(); 9863 } 9864 } 9865 } 9866 9867 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9868 ParmVarDecl * const *ParamEnd, 9869 QualType ReturnTy, 9870 NamedDecl *D) { 9871 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9872 return; 9873 9874 // Warn if the return value is pass-by-value and larger than the specified 9875 // threshold. 9876 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9877 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9878 if (Size > LangOpts.NumLargeByValueCopy) 9879 Diag(D->getLocation(), diag::warn_return_value_size) 9880 << D->getDeclName() << Size; 9881 } 9882 9883 // Warn if any parameter is pass-by-value and larger than the specified 9884 // threshold. 9885 for (; Param != ParamEnd; ++Param) { 9886 QualType T = (*Param)->getType(); 9887 if (T->isDependentType() || !T.isPODType(Context)) 9888 continue; 9889 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9890 if (Size > LangOpts.NumLargeByValueCopy) 9891 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9892 << (*Param)->getDeclName() << Size; 9893 } 9894 } 9895 9896 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9897 SourceLocation NameLoc, IdentifierInfo *Name, 9898 QualType T, TypeSourceInfo *TSInfo, 9899 VarDecl::StorageClass StorageClass) { 9900 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9901 if (getLangOpts().ObjCAutoRefCount && 9902 T.getObjCLifetime() == Qualifiers::OCL_None && 9903 T->isObjCLifetimeType()) { 9904 9905 Qualifiers::ObjCLifetime lifetime; 9906 9907 // Special cases for arrays: 9908 // - if it's const, use __unsafe_unretained 9909 // - otherwise, it's an error 9910 if (T->isArrayType()) { 9911 if (!T.isConstQualified()) { 9912 DelayedDiagnostics.add( 9913 sema::DelayedDiagnostic::makeForbiddenType( 9914 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9915 } 9916 lifetime = Qualifiers::OCL_ExplicitNone; 9917 } else { 9918 lifetime = T->getObjCARCImplicitLifetime(); 9919 } 9920 T = Context.getLifetimeQualifiedType(T, lifetime); 9921 } 9922 9923 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9924 Context.getAdjustedParameterType(T), 9925 TSInfo, 9926 StorageClass, nullptr); 9927 9928 // Parameters can not be abstract class types. 9929 // For record types, this is done by the AbstractClassUsageDiagnoser once 9930 // the class has been completely parsed. 9931 if (!CurContext->isRecord() && 9932 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9933 AbstractParamType)) 9934 New->setInvalidDecl(); 9935 9936 // Parameter declarators cannot be interface types. All ObjC objects are 9937 // passed by reference. 9938 if (T->isObjCObjectType()) { 9939 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9940 Diag(NameLoc, 9941 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9942 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9943 T = Context.getObjCObjectPointerType(T); 9944 New->setType(T); 9945 } 9946 9947 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9948 // duration shall not be qualified by an address-space qualifier." 9949 // Since all parameters have automatic store duration, they can not have 9950 // an address space. 9951 if (T.getAddressSpace() != 0) { 9952 // OpenCL allows function arguments declared to be an array of a type 9953 // to be qualified with an address space. 9954 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9955 Diag(NameLoc, diag::err_arg_with_address_space); 9956 New->setInvalidDecl(); 9957 } 9958 } 9959 9960 return New; 9961 } 9962 9963 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9964 SourceLocation LocAfterDecls) { 9965 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9966 9967 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9968 // for a K&R function. 9969 if (!FTI.hasPrototype) { 9970 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9971 --i; 9972 if (FTI.Params[i].Param == nullptr) { 9973 SmallString<256> Code; 9974 llvm::raw_svector_ostream(Code) 9975 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9976 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9977 << FTI.Params[i].Ident 9978 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9979 9980 // Implicitly declare the argument as type 'int' for lack of a better 9981 // type. 9982 AttributeFactory attrs; 9983 DeclSpec DS(attrs); 9984 const char* PrevSpec; // unused 9985 unsigned DiagID; // unused 9986 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9987 DiagID, Context.getPrintingPolicy()); 9988 // Use the identifier location for the type source range. 9989 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9990 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9991 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9992 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9993 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9994 } 9995 } 9996 } 9997 } 9998 9999 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10000 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10001 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10002 Scope *ParentScope = FnBodyScope->getParent(); 10003 10004 D.setFunctionDefinitionKind(FDK_Definition); 10005 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10006 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10007 } 10008 10009 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10010 Consumer.HandleInlineMethodDefinition(D); 10011 } 10012 10013 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10014 const FunctionDecl*& PossibleZeroParamPrototype) { 10015 // Don't warn about invalid declarations. 10016 if (FD->isInvalidDecl()) 10017 return false; 10018 10019 // Or declarations that aren't global. 10020 if (!FD->isGlobal()) 10021 return false; 10022 10023 // Don't warn about C++ member functions. 10024 if (isa<CXXMethodDecl>(FD)) 10025 return false; 10026 10027 // Don't warn about 'main'. 10028 if (FD->isMain()) 10029 return false; 10030 10031 // Don't warn about inline functions. 10032 if (FD->isInlined()) 10033 return false; 10034 10035 // Don't warn about function templates. 10036 if (FD->getDescribedFunctionTemplate()) 10037 return false; 10038 10039 // Don't warn about function template specializations. 10040 if (FD->isFunctionTemplateSpecialization()) 10041 return false; 10042 10043 // Don't warn for OpenCL kernels. 10044 if (FD->hasAttr<OpenCLKernelAttr>()) 10045 return false; 10046 10047 bool MissingPrototype = true; 10048 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10049 Prev; Prev = Prev->getPreviousDecl()) { 10050 // Ignore any declarations that occur in function or method 10051 // scope, because they aren't visible from the header. 10052 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10053 continue; 10054 10055 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10056 if (FD->getNumParams() == 0) 10057 PossibleZeroParamPrototype = Prev; 10058 break; 10059 } 10060 10061 return MissingPrototype; 10062 } 10063 10064 void 10065 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10066 const FunctionDecl *EffectiveDefinition) { 10067 // Don't complain if we're in GNU89 mode and the previous definition 10068 // was an extern inline function. 10069 const FunctionDecl *Definition = EffectiveDefinition; 10070 if (!Definition) 10071 if (!FD->isDefined(Definition)) 10072 return; 10073 10074 if (canRedefineFunction(Definition, getLangOpts())) 10075 return; 10076 10077 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10078 Definition->getStorageClass() == SC_Extern) 10079 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10080 << FD->getDeclName() << getLangOpts().CPlusPlus; 10081 else 10082 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10083 10084 Diag(Definition->getLocation(), diag::note_previous_definition); 10085 FD->setInvalidDecl(); 10086 } 10087 10088 10089 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10090 Sema &S) { 10091 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10092 10093 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10094 LSI->CallOperator = CallOperator; 10095 LSI->Lambda = LambdaClass; 10096 LSI->ReturnType = CallOperator->getReturnType(); 10097 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10098 10099 if (LCD == LCD_None) 10100 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10101 else if (LCD == LCD_ByCopy) 10102 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10103 else if (LCD == LCD_ByRef) 10104 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10105 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10106 10107 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10108 LSI->Mutable = !CallOperator->isConst(); 10109 10110 // Add the captures to the LSI so they can be noted as already 10111 // captured within tryCaptureVar. 10112 auto I = LambdaClass->field_begin(); 10113 for (const auto &C : LambdaClass->captures()) { 10114 if (C.capturesVariable()) { 10115 VarDecl *VD = C.getCapturedVar(); 10116 if (VD->isInitCapture()) 10117 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10118 QualType CaptureType = VD->getType(); 10119 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10120 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10121 /*RefersToEnclosingLocal*/true, C.getLocation(), 10122 /*EllipsisLoc*/C.isPackExpansion() 10123 ? C.getEllipsisLoc() : SourceLocation(), 10124 CaptureType, /*Expr*/ nullptr); 10125 10126 } else if (C.capturesThis()) { 10127 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10128 S.getCurrentThisType(), /*Expr*/ nullptr); 10129 } else { 10130 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10131 } 10132 ++I; 10133 } 10134 } 10135 10136 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10137 // Clear the last template instantiation error context. 10138 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10139 10140 if (!D) 10141 return D; 10142 FunctionDecl *FD = nullptr; 10143 10144 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10145 FD = FunTmpl->getTemplatedDecl(); 10146 else 10147 FD = cast<FunctionDecl>(D); 10148 // If we are instantiating a generic lambda call operator, push 10149 // a LambdaScopeInfo onto the function stack. But use the information 10150 // that's already been calculated (ActOnLambdaExpr) to prime the current 10151 // LambdaScopeInfo. 10152 // When the template operator is being specialized, the LambdaScopeInfo, 10153 // has to be properly restored so that tryCaptureVariable doesn't try 10154 // and capture any new variables. In addition when calculating potential 10155 // captures during transformation of nested lambdas, it is necessary to 10156 // have the LSI properly restored. 10157 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10158 assert(ActiveTemplateInstantiations.size() && 10159 "There should be an active template instantiation on the stack " 10160 "when instantiating a generic lambda!"); 10161 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10162 } 10163 else 10164 // Enter a new function scope 10165 PushFunctionScope(); 10166 10167 // See if this is a redefinition. 10168 if (!FD->isLateTemplateParsed()) 10169 CheckForFunctionRedefinition(FD); 10170 10171 // Builtin functions cannot be defined. 10172 if (unsigned BuiltinID = FD->getBuiltinID()) { 10173 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10174 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10175 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10176 FD->setInvalidDecl(); 10177 } 10178 } 10179 10180 // The return type of a function definition must be complete 10181 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10182 QualType ResultType = FD->getReturnType(); 10183 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10184 !FD->isInvalidDecl() && 10185 RequireCompleteType(FD->getLocation(), ResultType, 10186 diag::err_func_def_incomplete_result)) 10187 FD->setInvalidDecl(); 10188 10189 // GNU warning -Wmissing-prototypes: 10190 // Warn if a global function is defined without a previous 10191 // prototype declaration. This warning is issued even if the 10192 // definition itself provides a prototype. The aim is to detect 10193 // global functions that fail to be declared in header files. 10194 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10195 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10196 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10197 10198 if (PossibleZeroParamPrototype) { 10199 // We found a declaration that is not a prototype, 10200 // but that could be a zero-parameter prototype 10201 if (TypeSourceInfo *TI = 10202 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10203 TypeLoc TL = TI->getTypeLoc(); 10204 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10205 Diag(PossibleZeroParamPrototype->getLocation(), 10206 diag::note_declaration_not_a_prototype) 10207 << PossibleZeroParamPrototype 10208 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10209 } 10210 } 10211 } 10212 10213 if (FnBodyScope) 10214 PushDeclContext(FnBodyScope, FD); 10215 10216 // Check the validity of our function parameters 10217 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10218 /*CheckParameterNames=*/true); 10219 10220 // Introduce our parameters into the function scope 10221 for (auto Param : FD->params()) { 10222 Param->setOwningFunction(FD); 10223 10224 // If this has an identifier, add it to the scope stack. 10225 if (Param->getIdentifier() && FnBodyScope) { 10226 CheckShadow(FnBodyScope, Param); 10227 10228 PushOnScopeChains(Param, FnBodyScope); 10229 } 10230 } 10231 10232 // If we had any tags defined in the function prototype, 10233 // introduce them into the function scope. 10234 if (FnBodyScope) { 10235 for (ArrayRef<NamedDecl *>::iterator 10236 I = FD->getDeclsInPrototypeScope().begin(), 10237 E = FD->getDeclsInPrototypeScope().end(); 10238 I != E; ++I) { 10239 NamedDecl *D = *I; 10240 10241 // Some of these decls (like enums) may have been pinned to the translation unit 10242 // for lack of a real context earlier. If so, remove from the translation unit 10243 // and reattach to the current context. 10244 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10245 // Is the decl actually in the context? 10246 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10247 if (DI == D) { 10248 Context.getTranslationUnitDecl()->removeDecl(D); 10249 break; 10250 } 10251 } 10252 // Either way, reassign the lexical decl context to our FunctionDecl. 10253 D->setLexicalDeclContext(CurContext); 10254 } 10255 10256 // If the decl has a non-null name, make accessible in the current scope. 10257 if (!D->getName().empty()) 10258 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10259 10260 // Similarly, dive into enums and fish their constants out, making them 10261 // accessible in this scope. 10262 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10263 for (auto *EI : ED->enumerators()) 10264 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10265 } 10266 } 10267 } 10268 10269 // Ensure that the function's exception specification is instantiated. 10270 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10271 ResolveExceptionSpec(D->getLocation(), FPT); 10272 10273 // dllimport cannot be applied to non-inline function definitions. 10274 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10275 !FD->isTemplateInstantiation()) { 10276 assert(!FD->hasAttr<DLLExportAttr>()); 10277 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10278 FD->setInvalidDecl(); 10279 return D; 10280 } 10281 // We want to attach documentation to original Decl (which might be 10282 // a function template). 10283 ActOnDocumentableDecl(D); 10284 if (getCurLexicalContext()->isObjCContainer() && 10285 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10286 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10287 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10288 10289 return D; 10290 } 10291 10292 /// \brief Given the set of return statements within a function body, 10293 /// compute the variables that are subject to the named return value 10294 /// optimization. 10295 /// 10296 /// Each of the variables that is subject to the named return value 10297 /// optimization will be marked as NRVO variables in the AST, and any 10298 /// return statement that has a marked NRVO variable as its NRVO candidate can 10299 /// use the named return value optimization. 10300 /// 10301 /// This function applies a very simplistic algorithm for NRVO: if every return 10302 /// statement in the scope of a variable has the same NRVO candidate, that 10303 /// candidate is an NRVO variable. 10304 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10305 ReturnStmt **Returns = Scope->Returns.data(); 10306 10307 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10308 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10309 if (!NRVOCandidate->isNRVOVariable()) 10310 Returns[I]->setNRVOCandidate(nullptr); 10311 } 10312 } 10313 } 10314 10315 bool Sema::canDelayFunctionBody(const Declarator &D) { 10316 // We can't delay parsing the body of a constexpr function template (yet). 10317 if (D.getDeclSpec().isConstexprSpecified()) 10318 return false; 10319 10320 // We can't delay parsing the body of a function template with a deduced 10321 // return type (yet). 10322 if (D.getDeclSpec().containsPlaceholderType()) { 10323 // If the placeholder introduces a non-deduced trailing return type, 10324 // we can still delay parsing it. 10325 if (D.getNumTypeObjects()) { 10326 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10327 if (Outer.Kind == DeclaratorChunk::Function && 10328 Outer.Fun.hasTrailingReturnType()) { 10329 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10330 return Ty.isNull() || !Ty->isUndeducedType(); 10331 } 10332 } 10333 return false; 10334 } 10335 10336 return true; 10337 } 10338 10339 bool Sema::canSkipFunctionBody(Decl *D) { 10340 // We cannot skip the body of a function (or function template) which is 10341 // constexpr, since we may need to evaluate its body in order to parse the 10342 // rest of the file. 10343 // We cannot skip the body of a function with an undeduced return type, 10344 // because any callers of that function need to know the type. 10345 if (const FunctionDecl *FD = D->getAsFunction()) 10346 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10347 return false; 10348 return Consumer.shouldSkipFunctionBody(D); 10349 } 10350 10351 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10352 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10353 FD->setHasSkippedBody(); 10354 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10355 MD->setHasSkippedBody(); 10356 return ActOnFinishFunctionBody(Decl, nullptr); 10357 } 10358 10359 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10360 return ActOnFinishFunctionBody(D, BodyArg, false); 10361 } 10362 10363 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10364 bool IsInstantiation) { 10365 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10366 10367 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10368 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10369 10370 if (FD) { 10371 FD->setBody(Body); 10372 10373 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10374 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10375 // If the function has a deduced result type but contains no 'return' 10376 // statements, the result type as written must be exactly 'auto', and 10377 // the deduced result type is 'void'. 10378 if (!FD->getReturnType()->getAs<AutoType>()) { 10379 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10380 << FD->getReturnType(); 10381 FD->setInvalidDecl(); 10382 } else { 10383 // Substitute 'void' for the 'auto' in the type. 10384 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 10385 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 10386 Context.adjustDeducedFunctionResultType( 10387 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10388 } 10389 } 10390 10391 // The only way to be included in UndefinedButUsed is if there is an 10392 // ODR use before the definition. Avoid the expensive map lookup if this 10393 // is the first declaration. 10394 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10395 if (!FD->isExternallyVisible()) 10396 UndefinedButUsed.erase(FD); 10397 else if (FD->isInlined() && 10398 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10399 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10400 UndefinedButUsed.erase(FD); 10401 } 10402 10403 // If the function implicitly returns zero (like 'main') or is naked, 10404 // don't complain about missing return statements. 10405 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10406 WP.disableCheckFallThrough(); 10407 10408 // MSVC permits the use of pure specifier (=0) on function definition, 10409 // defined at class scope, warn about this non-standard construct. 10410 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10411 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10412 10413 if (!FD->isInvalidDecl()) { 10414 // Don't diagnose unused parameters of defaulted or deleted functions. 10415 if (Body) 10416 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10417 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10418 FD->getReturnType(), FD); 10419 10420 // If this is a constructor, we need a vtable. 10421 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10422 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10423 10424 // Try to apply the named return value optimization. We have to check 10425 // if we can do this here because lambdas keep return statements around 10426 // to deduce an implicit return type. 10427 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10428 !FD->isDependentContext()) 10429 computeNRVO(Body, getCurFunction()); 10430 } 10431 10432 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10433 "Function parsing confused"); 10434 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10435 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10436 MD->setBody(Body); 10437 if (!MD->isInvalidDecl()) { 10438 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10439 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10440 MD->getReturnType(), MD); 10441 10442 if (Body) 10443 computeNRVO(Body, getCurFunction()); 10444 } 10445 if (getCurFunction()->ObjCShouldCallSuper) { 10446 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10447 << MD->getSelector().getAsString(); 10448 getCurFunction()->ObjCShouldCallSuper = false; 10449 } 10450 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10451 const ObjCMethodDecl *InitMethod = nullptr; 10452 bool isDesignated = 10453 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10454 assert(isDesignated && InitMethod); 10455 (void)isDesignated; 10456 10457 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10458 auto IFace = MD->getClassInterface(); 10459 if (!IFace) 10460 return false; 10461 auto SuperD = IFace->getSuperClass(); 10462 if (!SuperD) 10463 return false; 10464 return SuperD->getIdentifier() == 10465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10466 }; 10467 // Don't issue this warning for unavailable inits or direct subclasses 10468 // of NSObject. 10469 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10470 Diag(MD->getLocation(), 10471 diag::warn_objc_designated_init_missing_super_call); 10472 Diag(InitMethod->getLocation(), 10473 diag::note_objc_designated_init_marked_here); 10474 } 10475 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10476 } 10477 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10478 // Don't issue this warning for unavaialable inits. 10479 if (!MD->isUnavailable()) 10480 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10481 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10482 } 10483 } else { 10484 return nullptr; 10485 } 10486 10487 assert(!getCurFunction()->ObjCShouldCallSuper && 10488 "This should only be set for ObjC methods, which should have been " 10489 "handled in the block above."); 10490 10491 // Verify and clean out per-function state. 10492 if (Body) { 10493 // C++ constructors that have function-try-blocks can't have return 10494 // statements in the handlers of that block. (C++ [except.handle]p14) 10495 // Verify this. 10496 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10497 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10498 10499 // Verify that gotos and switch cases don't jump into scopes illegally. 10500 if (getCurFunction()->NeedsScopeChecking() && 10501 !PP.isCodeCompletionEnabled()) 10502 DiagnoseInvalidJumps(Body); 10503 10504 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10505 if (!Destructor->getParent()->isDependentType()) 10506 CheckDestructor(Destructor); 10507 10508 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10509 Destructor->getParent()); 10510 } 10511 10512 // If any errors have occurred, clear out any temporaries that may have 10513 // been leftover. This ensures that these temporaries won't be picked up for 10514 // deletion in some later function. 10515 if (getDiagnostics().hasErrorOccurred() || 10516 getDiagnostics().getSuppressAllDiagnostics()) { 10517 DiscardCleanupsInEvaluationContext(); 10518 } 10519 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10520 !isa<FunctionTemplateDecl>(dcl)) { 10521 // Since the body is valid, issue any analysis-based warnings that are 10522 // enabled. 10523 ActivePolicy = &WP; 10524 } 10525 10526 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10527 (!CheckConstexprFunctionDecl(FD) || 10528 !CheckConstexprFunctionBody(FD, Body))) 10529 FD->setInvalidDecl(); 10530 10531 if (FD && FD->hasAttr<NakedAttr>()) { 10532 for (const Stmt *S : Body->children()) { 10533 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10534 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10535 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10536 FD->setInvalidDecl(); 10537 break; 10538 } 10539 } 10540 } 10541 10542 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10543 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10544 assert(MaybeODRUseExprs.empty() && 10545 "Leftover expressions for odr-use checking"); 10546 } 10547 10548 if (!IsInstantiation) 10549 PopDeclContext(); 10550 10551 PopFunctionScopeInfo(ActivePolicy, dcl); 10552 // If any errors have occurred, clear out any temporaries that may have 10553 // been leftover. This ensures that these temporaries won't be picked up for 10554 // deletion in some later function. 10555 if (getDiagnostics().hasErrorOccurred()) { 10556 DiscardCleanupsInEvaluationContext(); 10557 } 10558 10559 return dcl; 10560 } 10561 10562 10563 /// When we finish delayed parsing of an attribute, we must attach it to the 10564 /// relevant Decl. 10565 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10566 ParsedAttributes &Attrs) { 10567 // Always attach attributes to the underlying decl. 10568 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10569 D = TD->getTemplatedDecl(); 10570 ProcessDeclAttributeList(S, D, Attrs.getList()); 10571 10572 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10573 if (Method->isStatic()) 10574 checkThisInStaticMemberFunctionAttributes(Method); 10575 } 10576 10577 10578 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10579 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10580 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10581 IdentifierInfo &II, Scope *S) { 10582 // Before we produce a declaration for an implicitly defined 10583 // function, see whether there was a locally-scoped declaration of 10584 // this name as a function or variable. If so, use that 10585 // (non-visible) declaration, and complain about it. 10586 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10587 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10588 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10589 return ExternCPrev; 10590 } 10591 10592 // Extension in C99. Legal in C90, but warn about it. 10593 unsigned diag_id; 10594 if (II.getName().startswith("__builtin_")) 10595 diag_id = diag::warn_builtin_unknown; 10596 else if (getLangOpts().C99) 10597 diag_id = diag::ext_implicit_function_decl; 10598 else 10599 diag_id = diag::warn_implicit_function_decl; 10600 Diag(Loc, diag_id) << &II; 10601 10602 // Because typo correction is expensive, only do it if the implicit 10603 // function declaration is going to be treated as an error. 10604 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10605 TypoCorrection Corrected; 10606 DeclFilterCCC<FunctionDecl> Validator; 10607 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10608 LookupOrdinaryName, S, nullptr, Validator, 10609 CTK_NonError))) 10610 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10611 /*ErrorRecovery*/false); 10612 } 10613 10614 // Set a Declarator for the implicit definition: int foo(); 10615 const char *Dummy; 10616 AttributeFactory attrFactory; 10617 DeclSpec DS(attrFactory); 10618 unsigned DiagID; 10619 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10620 Context.getPrintingPolicy()); 10621 (void)Error; // Silence warning. 10622 assert(!Error && "Error setting up implicit decl!"); 10623 SourceLocation NoLoc; 10624 Declarator D(DS, Declarator::BlockContext); 10625 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10626 /*IsAmbiguous=*/false, 10627 /*LParenLoc=*/NoLoc, 10628 /*Params=*/nullptr, 10629 /*NumParams=*/0, 10630 /*EllipsisLoc=*/NoLoc, 10631 /*RParenLoc=*/NoLoc, 10632 /*TypeQuals=*/0, 10633 /*RefQualifierIsLvalueRef=*/true, 10634 /*RefQualifierLoc=*/NoLoc, 10635 /*ConstQualifierLoc=*/NoLoc, 10636 /*VolatileQualifierLoc=*/NoLoc, 10637 /*MutableLoc=*/NoLoc, 10638 EST_None, 10639 /*ESpecLoc=*/NoLoc, 10640 /*Exceptions=*/nullptr, 10641 /*ExceptionRanges=*/nullptr, 10642 /*NumExceptions=*/0, 10643 /*NoexceptExpr=*/nullptr, 10644 Loc, Loc, D), 10645 DS.getAttributes(), 10646 SourceLocation()); 10647 D.SetIdentifier(&II, Loc); 10648 10649 // Insert this function into translation-unit scope. 10650 10651 DeclContext *PrevDC = CurContext; 10652 CurContext = Context.getTranslationUnitDecl(); 10653 10654 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10655 FD->setImplicit(); 10656 10657 CurContext = PrevDC; 10658 10659 AddKnownFunctionAttributes(FD); 10660 10661 return FD; 10662 } 10663 10664 /// \brief Adds any function attributes that we know a priori based on 10665 /// the declaration of this function. 10666 /// 10667 /// These attributes can apply both to implicitly-declared builtins 10668 /// (like __builtin___printf_chk) or to library-declared functions 10669 /// like NSLog or printf. 10670 /// 10671 /// We need to check for duplicate attributes both here and where user-written 10672 /// attributes are applied to declarations. 10673 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10674 if (FD->isInvalidDecl()) 10675 return; 10676 10677 // If this is a built-in function, map its builtin attributes to 10678 // actual attributes. 10679 if (unsigned BuiltinID = FD->getBuiltinID()) { 10680 // Handle printf-formatting attributes. 10681 unsigned FormatIdx; 10682 bool HasVAListArg; 10683 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10684 if (!FD->hasAttr<FormatAttr>()) { 10685 const char *fmt = "printf"; 10686 unsigned int NumParams = FD->getNumParams(); 10687 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10688 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10689 fmt = "NSString"; 10690 FD->addAttr(FormatAttr::CreateImplicit(Context, 10691 &Context.Idents.get(fmt), 10692 FormatIdx+1, 10693 HasVAListArg ? 0 : FormatIdx+2, 10694 FD->getLocation())); 10695 } 10696 } 10697 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10698 HasVAListArg)) { 10699 if (!FD->hasAttr<FormatAttr>()) 10700 FD->addAttr(FormatAttr::CreateImplicit(Context, 10701 &Context.Idents.get("scanf"), 10702 FormatIdx+1, 10703 HasVAListArg ? 0 : FormatIdx+2, 10704 FD->getLocation())); 10705 } 10706 10707 // Mark const if we don't care about errno and that is the only 10708 // thing preventing the function from being const. This allows 10709 // IRgen to use LLVM intrinsics for such functions. 10710 if (!getLangOpts().MathErrno && 10711 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10712 if (!FD->hasAttr<ConstAttr>()) 10713 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10714 } 10715 10716 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10717 !FD->hasAttr<ReturnsTwiceAttr>()) 10718 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10719 FD->getLocation())); 10720 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10721 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10722 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10723 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10724 } 10725 10726 IdentifierInfo *Name = FD->getIdentifier(); 10727 if (!Name) 10728 return; 10729 if ((!getLangOpts().CPlusPlus && 10730 FD->getDeclContext()->isTranslationUnit()) || 10731 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10732 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10733 LinkageSpecDecl::lang_c)) { 10734 // Okay: this could be a libc/libm/Objective-C function we know 10735 // about. 10736 } else 10737 return; 10738 10739 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10740 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10741 // target-specific builtins, perhaps? 10742 if (!FD->hasAttr<FormatAttr>()) 10743 FD->addAttr(FormatAttr::CreateImplicit(Context, 10744 &Context.Idents.get("printf"), 2, 10745 Name->isStr("vasprintf") ? 0 : 3, 10746 FD->getLocation())); 10747 } 10748 10749 if (Name->isStr("__CFStringMakeConstantString")) { 10750 // We already have a __builtin___CFStringMakeConstantString, 10751 // but builds that use -fno-constant-cfstrings don't go through that. 10752 if (!FD->hasAttr<FormatArgAttr>()) 10753 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10754 FD->getLocation())); 10755 } 10756 } 10757 10758 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10759 TypeSourceInfo *TInfo) { 10760 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10761 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10762 10763 if (!TInfo) { 10764 assert(D.isInvalidType() && "no declarator info for valid type"); 10765 TInfo = Context.getTrivialTypeSourceInfo(T); 10766 } 10767 10768 // Scope manipulation handled by caller. 10769 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10770 D.getLocStart(), 10771 D.getIdentifierLoc(), 10772 D.getIdentifier(), 10773 TInfo); 10774 10775 // Bail out immediately if we have an invalid declaration. 10776 if (D.isInvalidType()) { 10777 NewTD->setInvalidDecl(); 10778 return NewTD; 10779 } 10780 10781 if (D.getDeclSpec().isModulePrivateSpecified()) { 10782 if (CurContext->isFunctionOrMethod()) 10783 Diag(NewTD->getLocation(), diag::err_module_private_local) 10784 << 2 << NewTD->getDeclName() 10785 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10786 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10787 else 10788 NewTD->setModulePrivate(); 10789 } 10790 10791 // C++ [dcl.typedef]p8: 10792 // If the typedef declaration defines an unnamed class (or 10793 // enum), the first typedef-name declared by the declaration 10794 // to be that class type (or enum type) is used to denote the 10795 // class type (or enum type) for linkage purposes only. 10796 // We need to check whether the type was declared in the declaration. 10797 switch (D.getDeclSpec().getTypeSpecType()) { 10798 case TST_enum: 10799 case TST_struct: 10800 case TST_interface: 10801 case TST_union: 10802 case TST_class: { 10803 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10804 10805 // Do nothing if the tag is not anonymous or already has an 10806 // associated typedef (from an earlier typedef in this decl group). 10807 if (tagFromDeclSpec->getIdentifier()) break; 10808 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10809 10810 // A well-formed anonymous tag must always be a TUK_Definition. 10811 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10812 10813 // The type must match the tag exactly; no qualifiers allowed. 10814 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10815 break; 10816 10817 // If we've already computed linkage for the anonymous tag, then 10818 // adding a typedef name for the anonymous decl can change that 10819 // linkage, which might be a serious problem. Diagnose this as 10820 // unsupported and ignore the typedef name. TODO: we should 10821 // pursue this as a language defect and establish a formal rule 10822 // for how to handle it. 10823 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10824 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10825 10826 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10827 tagLoc = getLocForEndOfToken(tagLoc); 10828 10829 llvm::SmallString<40> textToInsert; 10830 textToInsert += ' '; 10831 textToInsert += D.getIdentifier()->getName(); 10832 Diag(tagLoc, diag::note_typedef_changes_linkage) 10833 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10834 break; 10835 } 10836 10837 // Otherwise, set this is the anon-decl typedef for the tag. 10838 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10839 break; 10840 } 10841 10842 default: 10843 break; 10844 } 10845 10846 return NewTD; 10847 } 10848 10849 10850 /// \brief Check that this is a valid underlying type for an enum declaration. 10851 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10852 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10853 QualType T = TI->getType(); 10854 10855 if (T->isDependentType()) 10856 return false; 10857 10858 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10859 if (BT->isInteger()) 10860 return false; 10861 10862 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10863 return true; 10864 } 10865 10866 /// Check whether this is a valid redeclaration of a previous enumeration. 10867 /// \return true if the redeclaration was invalid. 10868 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10869 QualType EnumUnderlyingTy, 10870 const EnumDecl *Prev) { 10871 bool IsFixed = !EnumUnderlyingTy.isNull(); 10872 10873 if (IsScoped != Prev->isScoped()) { 10874 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10875 << Prev->isScoped(); 10876 Diag(Prev->getLocation(), diag::note_previous_declaration); 10877 return true; 10878 } 10879 10880 if (IsFixed && Prev->isFixed()) { 10881 if (!EnumUnderlyingTy->isDependentType() && 10882 !Prev->getIntegerType()->isDependentType() && 10883 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10884 Prev->getIntegerType())) { 10885 // TODO: Highlight the underlying type of the redeclaration. 10886 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10887 << EnumUnderlyingTy << Prev->getIntegerType(); 10888 Diag(Prev->getLocation(), diag::note_previous_declaration) 10889 << Prev->getIntegerTypeRange(); 10890 return true; 10891 } 10892 } else if (IsFixed != Prev->isFixed()) { 10893 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10894 << Prev->isFixed(); 10895 Diag(Prev->getLocation(), diag::note_previous_declaration); 10896 return true; 10897 } 10898 10899 return false; 10900 } 10901 10902 /// \brief Get diagnostic %select index for tag kind for 10903 /// redeclaration diagnostic message. 10904 /// WARNING: Indexes apply to particular diagnostics only! 10905 /// 10906 /// \returns diagnostic %select index. 10907 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10908 switch (Tag) { 10909 case TTK_Struct: return 0; 10910 case TTK_Interface: return 1; 10911 case TTK_Class: return 2; 10912 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10913 } 10914 } 10915 10916 /// \brief Determine if tag kind is a class-key compatible with 10917 /// class for redeclaration (class, struct, or __interface). 10918 /// 10919 /// \returns true iff the tag kind is compatible. 10920 static bool isClassCompatTagKind(TagTypeKind Tag) 10921 { 10922 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10923 } 10924 10925 /// \brief Determine whether a tag with a given kind is acceptable 10926 /// as a redeclaration of the given tag declaration. 10927 /// 10928 /// \returns true if the new tag kind is acceptable, false otherwise. 10929 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10930 TagTypeKind NewTag, bool isDefinition, 10931 SourceLocation NewTagLoc, 10932 const IdentifierInfo &Name) { 10933 // C++ [dcl.type.elab]p3: 10934 // The class-key or enum keyword present in the 10935 // elaborated-type-specifier shall agree in kind with the 10936 // declaration to which the name in the elaborated-type-specifier 10937 // refers. This rule also applies to the form of 10938 // elaborated-type-specifier that declares a class-name or 10939 // friend class since it can be construed as referring to the 10940 // definition of the class. Thus, in any 10941 // elaborated-type-specifier, the enum keyword shall be used to 10942 // refer to an enumeration (7.2), the union class-key shall be 10943 // used to refer to a union (clause 9), and either the class or 10944 // struct class-key shall be used to refer to a class (clause 9) 10945 // declared using the class or struct class-key. 10946 TagTypeKind OldTag = Previous->getTagKind(); 10947 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10948 if (OldTag == NewTag) 10949 return true; 10950 10951 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10952 // Warn about the struct/class tag mismatch. 10953 bool isTemplate = false; 10954 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10955 isTemplate = Record->getDescribedClassTemplate(); 10956 10957 if (!ActiveTemplateInstantiations.empty()) { 10958 // In a template instantiation, do not offer fix-its for tag mismatches 10959 // since they usually mess up the template instead of fixing the problem. 10960 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10961 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10962 << getRedeclDiagFromTagKind(OldTag); 10963 return true; 10964 } 10965 10966 if (isDefinition) { 10967 // On definitions, check previous tags and issue a fix-it for each 10968 // one that doesn't match the current tag. 10969 if (Previous->getDefinition()) { 10970 // Don't suggest fix-its for redefinitions. 10971 return true; 10972 } 10973 10974 bool previousMismatch = false; 10975 for (auto I : Previous->redecls()) { 10976 if (I->getTagKind() != NewTag) { 10977 if (!previousMismatch) { 10978 previousMismatch = true; 10979 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10980 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10981 << getRedeclDiagFromTagKind(I->getTagKind()); 10982 } 10983 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10984 << getRedeclDiagFromTagKind(NewTag) 10985 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10986 TypeWithKeyword::getTagTypeKindName(NewTag)); 10987 } 10988 } 10989 return true; 10990 } 10991 10992 // Check for a previous definition. If current tag and definition 10993 // are same type, do nothing. If no definition, but disagree with 10994 // with previous tag type, give a warning, but no fix-it. 10995 const TagDecl *Redecl = Previous->getDefinition() ? 10996 Previous->getDefinition() : Previous; 10997 if (Redecl->getTagKind() == NewTag) { 10998 return true; 10999 } 11000 11001 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11002 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11003 << getRedeclDiagFromTagKind(OldTag); 11004 Diag(Redecl->getLocation(), diag::note_previous_use); 11005 11006 // If there is a previous definition, suggest a fix-it. 11007 if (Previous->getDefinition()) { 11008 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11009 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11010 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11011 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11012 } 11013 11014 return true; 11015 } 11016 return false; 11017 } 11018 11019 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11020 /// from an outer enclosing namespace or file scope inside a friend declaration. 11021 /// This should provide the commented out code in the following snippet: 11022 /// namespace N { 11023 /// struct X; 11024 /// namespace M { 11025 /// struct Y { friend struct /*N::*/ X; }; 11026 /// } 11027 /// } 11028 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11029 SourceLocation NameLoc) { 11030 // While the decl is in a namespace, do repeated lookup of that name and see 11031 // if we get the same namespace back. If we do not, continue until 11032 // translation unit scope, at which point we have a fully qualified NNS. 11033 SmallVector<IdentifierInfo *, 4> Namespaces; 11034 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11035 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11036 // This tag should be declared in a namespace, which can only be enclosed by 11037 // other namespaces. Bail if there's an anonymous namespace in the chain. 11038 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11039 if (!Namespace || Namespace->isAnonymousNamespace()) 11040 return FixItHint(); 11041 IdentifierInfo *II = Namespace->getIdentifier(); 11042 Namespaces.push_back(II); 11043 NamedDecl *Lookup = SemaRef.LookupSingleName( 11044 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11045 if (Lookup == Namespace) 11046 break; 11047 } 11048 11049 // Once we have all the namespaces, reverse them to go outermost first, and 11050 // build an NNS. 11051 SmallString<64> Insertion; 11052 llvm::raw_svector_ostream OS(Insertion); 11053 if (DC->isTranslationUnit()) 11054 OS << "::"; 11055 std::reverse(Namespaces.begin(), Namespaces.end()); 11056 for (auto *II : Namespaces) 11057 OS << II->getName() << "::"; 11058 OS.flush(); 11059 return FixItHint::CreateInsertion(NameLoc, Insertion); 11060 } 11061 11062 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11063 /// former case, Name will be non-null. In the later case, Name will be null. 11064 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11065 /// reference/declaration/definition of a tag. 11066 /// 11067 /// IsTypeSpecifier is true if this is a type-specifier (or 11068 /// trailing-type-specifier) other than one in an alias-declaration. 11069 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11070 SourceLocation KWLoc, CXXScopeSpec &SS, 11071 IdentifierInfo *Name, SourceLocation NameLoc, 11072 AttributeList *Attr, AccessSpecifier AS, 11073 SourceLocation ModulePrivateLoc, 11074 MultiTemplateParamsArg TemplateParameterLists, 11075 bool &OwnedDecl, bool &IsDependent, 11076 SourceLocation ScopedEnumKWLoc, 11077 bool ScopedEnumUsesClassTag, 11078 TypeResult UnderlyingType, 11079 bool IsTypeSpecifier) { 11080 // If this is not a definition, it must have a name. 11081 IdentifierInfo *OrigName = Name; 11082 assert((Name != nullptr || TUK == TUK_Definition) && 11083 "Nameless record must be a definition!"); 11084 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11085 11086 OwnedDecl = false; 11087 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11088 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11089 11090 // FIXME: Check explicit specializations more carefully. 11091 bool isExplicitSpecialization = false; 11092 bool Invalid = false; 11093 11094 // We only need to do this matching if we have template parameters 11095 // or a scope specifier, which also conveniently avoids this work 11096 // for non-C++ cases. 11097 if (TemplateParameterLists.size() > 0 || 11098 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11099 if (TemplateParameterList *TemplateParams = 11100 MatchTemplateParametersToScopeSpecifier( 11101 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11102 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11103 if (Kind == TTK_Enum) { 11104 Diag(KWLoc, diag::err_enum_template); 11105 return nullptr; 11106 } 11107 11108 if (TemplateParams->size() > 0) { 11109 // This is a declaration or definition of a class template (which may 11110 // be a member of another template). 11111 11112 if (Invalid) 11113 return nullptr; 11114 11115 OwnedDecl = false; 11116 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11117 SS, Name, NameLoc, Attr, 11118 TemplateParams, AS, 11119 ModulePrivateLoc, 11120 /*FriendLoc*/SourceLocation(), 11121 TemplateParameterLists.size()-1, 11122 TemplateParameterLists.data()); 11123 return Result.get(); 11124 } else { 11125 // The "template<>" header is extraneous. 11126 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11127 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11128 isExplicitSpecialization = true; 11129 } 11130 } 11131 } 11132 11133 // Figure out the underlying type if this a enum declaration. We need to do 11134 // this early, because it's needed to detect if this is an incompatible 11135 // redeclaration. 11136 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11137 11138 if (Kind == TTK_Enum) { 11139 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11140 // No underlying type explicitly specified, or we failed to parse the 11141 // type, default to int. 11142 EnumUnderlying = Context.IntTy.getTypePtr(); 11143 else if (UnderlyingType.get()) { 11144 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11145 // integral type; any cv-qualification is ignored. 11146 TypeSourceInfo *TI = nullptr; 11147 GetTypeFromParser(UnderlyingType.get(), &TI); 11148 EnumUnderlying = TI; 11149 11150 if (CheckEnumUnderlyingType(TI)) 11151 // Recover by falling back to int. 11152 EnumUnderlying = Context.IntTy.getTypePtr(); 11153 11154 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11155 UPPC_FixedUnderlyingType)) 11156 EnumUnderlying = Context.IntTy.getTypePtr(); 11157 11158 } else if (getLangOpts().MSVCCompat) 11159 // Microsoft enums are always of int type. 11160 EnumUnderlying = Context.IntTy.getTypePtr(); 11161 } 11162 11163 DeclContext *SearchDC = CurContext; 11164 DeclContext *DC = CurContext; 11165 bool isStdBadAlloc = false; 11166 11167 RedeclarationKind Redecl = ForRedeclaration; 11168 if (TUK == TUK_Friend || TUK == TUK_Reference) 11169 Redecl = NotForRedeclaration; 11170 11171 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11172 if (Name && SS.isNotEmpty()) { 11173 // We have a nested-name tag ('struct foo::bar'). 11174 11175 // Check for invalid 'foo::'. 11176 if (SS.isInvalid()) { 11177 Name = nullptr; 11178 goto CreateNewDecl; 11179 } 11180 11181 // If this is a friend or a reference to a class in a dependent 11182 // context, don't try to make a decl for it. 11183 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11184 DC = computeDeclContext(SS, false); 11185 if (!DC) { 11186 IsDependent = true; 11187 return nullptr; 11188 } 11189 } else { 11190 DC = computeDeclContext(SS, true); 11191 if (!DC) { 11192 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11193 << SS.getRange(); 11194 return nullptr; 11195 } 11196 } 11197 11198 if (RequireCompleteDeclContext(SS, DC)) 11199 return nullptr; 11200 11201 SearchDC = DC; 11202 // Look-up name inside 'foo::'. 11203 LookupQualifiedName(Previous, DC); 11204 11205 if (Previous.isAmbiguous()) 11206 return nullptr; 11207 11208 if (Previous.empty()) { 11209 // Name lookup did not find anything. However, if the 11210 // nested-name-specifier refers to the current instantiation, 11211 // and that current instantiation has any dependent base 11212 // classes, we might find something at instantiation time: treat 11213 // this as a dependent elaborated-type-specifier. 11214 // But this only makes any sense for reference-like lookups. 11215 if (Previous.wasNotFoundInCurrentInstantiation() && 11216 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11217 IsDependent = true; 11218 return nullptr; 11219 } 11220 11221 // A tag 'foo::bar' must already exist. 11222 Diag(NameLoc, diag::err_not_tag_in_scope) 11223 << Kind << Name << DC << SS.getRange(); 11224 Name = nullptr; 11225 Invalid = true; 11226 goto CreateNewDecl; 11227 } 11228 } else if (Name) { 11229 // If this is a named struct, check to see if there was a previous forward 11230 // declaration or definition. 11231 // FIXME: We're looking into outer scopes here, even when we 11232 // shouldn't be. Doing so can result in ambiguities that we 11233 // shouldn't be diagnosing. 11234 LookupName(Previous, S); 11235 11236 // When declaring or defining a tag, ignore ambiguities introduced 11237 // by types using'ed into this scope. 11238 if (Previous.isAmbiguous() && 11239 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11240 LookupResult::Filter F = Previous.makeFilter(); 11241 while (F.hasNext()) { 11242 NamedDecl *ND = F.next(); 11243 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11244 F.erase(); 11245 } 11246 F.done(); 11247 } 11248 11249 // C++11 [namespace.memdef]p3: 11250 // If the name in a friend declaration is neither qualified nor 11251 // a template-id and the declaration is a function or an 11252 // elaborated-type-specifier, the lookup to determine whether 11253 // the entity has been previously declared shall not consider 11254 // any scopes outside the innermost enclosing namespace. 11255 // 11256 // MSVC doesn't implement the above rule for types, so a friend tag 11257 // declaration may be a redeclaration of a type declared in an enclosing 11258 // scope. They do implement this rule for friend functions. 11259 // 11260 // Does it matter that this should be by scope instead of by 11261 // semantic context? 11262 if (!Previous.empty() && TUK == TUK_Friend) { 11263 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11264 LookupResult::Filter F = Previous.makeFilter(); 11265 bool FriendSawTagOutsideEnclosingNamespace = false; 11266 while (F.hasNext()) { 11267 NamedDecl *ND = F.next(); 11268 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11269 if (DC->isFileContext() && 11270 !EnclosingNS->Encloses(ND->getDeclContext())) { 11271 if (getLangOpts().MSVCCompat) 11272 FriendSawTagOutsideEnclosingNamespace = true; 11273 else 11274 F.erase(); 11275 } 11276 } 11277 F.done(); 11278 11279 // Diagnose this MSVC extension in the easy case where lookup would have 11280 // unambiguously found something outside the enclosing namespace. 11281 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11282 NamedDecl *ND = Previous.getFoundDecl(); 11283 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11284 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11285 } 11286 } 11287 11288 // Note: there used to be some attempt at recovery here. 11289 if (Previous.isAmbiguous()) 11290 return nullptr; 11291 11292 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11293 // FIXME: This makes sure that we ignore the contexts associated 11294 // with C structs, unions, and enums when looking for a matching 11295 // tag declaration or definition. See the similar lookup tweak 11296 // in Sema::LookupName; is there a better way to deal with this? 11297 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11298 SearchDC = SearchDC->getParent(); 11299 } 11300 } 11301 11302 if (Previous.isSingleResult() && 11303 Previous.getFoundDecl()->isTemplateParameter()) { 11304 // Maybe we will complain about the shadowed template parameter. 11305 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11306 // Just pretend that we didn't see the previous declaration. 11307 Previous.clear(); 11308 } 11309 11310 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11311 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11312 // This is a declaration of or a reference to "std::bad_alloc". 11313 isStdBadAlloc = true; 11314 11315 if (Previous.empty() && StdBadAlloc) { 11316 // std::bad_alloc has been implicitly declared (but made invisible to 11317 // name lookup). Fill in this implicit declaration as the previous 11318 // declaration, so that the declarations get chained appropriately. 11319 Previous.addDecl(getStdBadAlloc()); 11320 } 11321 } 11322 11323 // If we didn't find a previous declaration, and this is a reference 11324 // (or friend reference), move to the correct scope. In C++, we 11325 // also need to do a redeclaration lookup there, just in case 11326 // there's a shadow friend decl. 11327 if (Name && Previous.empty() && 11328 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11329 if (Invalid) goto CreateNewDecl; 11330 assert(SS.isEmpty()); 11331 11332 if (TUK == TUK_Reference) { 11333 // C++ [basic.scope.pdecl]p5: 11334 // -- for an elaborated-type-specifier of the form 11335 // 11336 // class-key identifier 11337 // 11338 // if the elaborated-type-specifier is used in the 11339 // decl-specifier-seq or parameter-declaration-clause of a 11340 // function defined in namespace scope, the identifier is 11341 // declared as a class-name in the namespace that contains 11342 // the declaration; otherwise, except as a friend 11343 // declaration, the identifier is declared in the smallest 11344 // non-class, non-function-prototype scope that contains the 11345 // declaration. 11346 // 11347 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11348 // C structs and unions. 11349 // 11350 // It is an error in C++ to declare (rather than define) an enum 11351 // type, including via an elaborated type specifier. We'll 11352 // diagnose that later; for now, declare the enum in the same 11353 // scope as we would have picked for any other tag type. 11354 // 11355 // GNU C also supports this behavior as part of its incomplete 11356 // enum types extension, while GNU C++ does not. 11357 // 11358 // Find the context where we'll be declaring the tag. 11359 // FIXME: We would like to maintain the current DeclContext as the 11360 // lexical context, 11361 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11362 SearchDC = SearchDC->getParent(); 11363 11364 // Find the scope where we'll be declaring the tag. 11365 while (S->isClassScope() || 11366 (getLangOpts().CPlusPlus && 11367 S->isFunctionPrototypeScope()) || 11368 ((S->getFlags() & Scope::DeclScope) == 0) || 11369 (S->getEntity() && S->getEntity()->isTransparentContext())) 11370 S = S->getParent(); 11371 } else { 11372 assert(TUK == TUK_Friend); 11373 // C++ [namespace.memdef]p3: 11374 // If a friend declaration in a non-local class first declares a 11375 // class or function, the friend class or function is a member of 11376 // the innermost enclosing namespace. 11377 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11378 } 11379 11380 // In C++, we need to do a redeclaration lookup to properly 11381 // diagnose some problems. 11382 if (getLangOpts().CPlusPlus) { 11383 Previous.setRedeclarationKind(ForRedeclaration); 11384 LookupQualifiedName(Previous, SearchDC); 11385 } 11386 } 11387 11388 if (!Previous.empty()) { 11389 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11390 NamedDecl *DirectPrevDecl = 11391 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11392 11393 // It's okay to have a tag decl in the same scope as a typedef 11394 // which hides a tag decl in the same scope. Finding this 11395 // insanity with a redeclaration lookup can only actually happen 11396 // in C++. 11397 // 11398 // This is also okay for elaborated-type-specifiers, which is 11399 // technically forbidden by the current standard but which is 11400 // okay according to the likely resolution of an open issue; 11401 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11402 if (getLangOpts().CPlusPlus) { 11403 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11404 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11405 TagDecl *Tag = TT->getDecl(); 11406 if (Tag->getDeclName() == Name && 11407 Tag->getDeclContext()->getRedeclContext() 11408 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11409 PrevDecl = Tag; 11410 Previous.clear(); 11411 Previous.addDecl(Tag); 11412 Previous.resolveKind(); 11413 } 11414 } 11415 } 11416 } 11417 11418 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11419 // If this is a use of a previous tag, or if the tag is already declared 11420 // in the same scope (so that the definition/declaration completes or 11421 // rementions the tag), reuse the decl. 11422 if (TUK == TUK_Reference || TUK == TUK_Friend || 11423 isDeclInScope(DirectPrevDecl, SearchDC, S, 11424 SS.isNotEmpty() || isExplicitSpecialization)) { 11425 // Make sure that this wasn't declared as an enum and now used as a 11426 // struct or something similar. 11427 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11428 TUK == TUK_Definition, KWLoc, 11429 *Name)) { 11430 bool SafeToContinue 11431 = (PrevTagDecl->getTagKind() != TTK_Enum && 11432 Kind != TTK_Enum); 11433 if (SafeToContinue) 11434 Diag(KWLoc, diag::err_use_with_wrong_tag) 11435 << Name 11436 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11437 PrevTagDecl->getKindName()); 11438 else 11439 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11440 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11441 11442 if (SafeToContinue) 11443 Kind = PrevTagDecl->getTagKind(); 11444 else { 11445 // Recover by making this an anonymous redefinition. 11446 Name = nullptr; 11447 Previous.clear(); 11448 Invalid = true; 11449 } 11450 } 11451 11452 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11453 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11454 11455 // If this is an elaborated-type-specifier for a scoped enumeration, 11456 // the 'class' keyword is not necessary and not permitted. 11457 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11458 if (ScopedEnum) 11459 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11460 << PrevEnum->isScoped() 11461 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11462 return PrevTagDecl; 11463 } 11464 11465 QualType EnumUnderlyingTy; 11466 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11467 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11468 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11469 EnumUnderlyingTy = QualType(T, 0); 11470 11471 // All conflicts with previous declarations are recovered by 11472 // returning the previous declaration, unless this is a definition, 11473 // in which case we want the caller to bail out. 11474 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11475 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11476 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11477 } 11478 11479 // C++11 [class.mem]p1: 11480 // A member shall not be declared twice in the member-specification, 11481 // except that a nested class or member class template can be declared 11482 // and then later defined. 11483 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11484 S->isDeclScope(PrevDecl)) { 11485 Diag(NameLoc, diag::ext_member_redeclared); 11486 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11487 } 11488 11489 if (!Invalid) { 11490 // If this is a use, just return the declaration we found, unless 11491 // we have attributes. 11492 11493 // FIXME: In the future, return a variant or some other clue 11494 // for the consumer of this Decl to know it doesn't own it. 11495 // For our current ASTs this shouldn't be a problem, but will 11496 // need to be changed with DeclGroups. 11497 if (!Attr && 11498 ((TUK == TUK_Reference && 11499 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11500 || TUK == TUK_Friend)) 11501 return PrevTagDecl; 11502 11503 // Diagnose attempts to redefine a tag. 11504 if (TUK == TUK_Definition) { 11505 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11506 // If we're defining a specialization and the previous definition 11507 // is from an implicit instantiation, don't emit an error 11508 // here; we'll catch this in the general case below. 11509 bool IsExplicitSpecializationAfterInstantiation = false; 11510 if (isExplicitSpecialization) { 11511 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11512 IsExplicitSpecializationAfterInstantiation = 11513 RD->getTemplateSpecializationKind() != 11514 TSK_ExplicitSpecialization; 11515 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11516 IsExplicitSpecializationAfterInstantiation = 11517 ED->getTemplateSpecializationKind() != 11518 TSK_ExplicitSpecialization; 11519 } 11520 11521 if (!IsExplicitSpecializationAfterInstantiation) { 11522 // A redeclaration in function prototype scope in C isn't 11523 // visible elsewhere, so merely issue a warning. 11524 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11525 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11526 else 11527 Diag(NameLoc, diag::err_redefinition) << Name; 11528 Diag(Def->getLocation(), diag::note_previous_definition); 11529 // If this is a redefinition, recover by making this 11530 // struct be anonymous, which will make any later 11531 // references get the previous definition. 11532 Name = nullptr; 11533 Previous.clear(); 11534 Invalid = true; 11535 } 11536 } else { 11537 // If the type is currently being defined, complain 11538 // about a nested redefinition. 11539 const TagType *Tag 11540 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 11541 if (Tag->isBeingDefined()) { 11542 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11543 Diag(PrevTagDecl->getLocation(), 11544 diag::note_previous_definition); 11545 Name = nullptr; 11546 Previous.clear(); 11547 Invalid = true; 11548 } 11549 } 11550 11551 // Okay, this is definition of a previously declared or referenced 11552 // tag. We're going to create a new Decl for it. 11553 } 11554 11555 // Okay, we're going to make a redeclaration. If this is some kind 11556 // of reference, make sure we build the redeclaration in the same DC 11557 // as the original, and ignore the current access specifier. 11558 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11559 SearchDC = PrevTagDecl->getDeclContext(); 11560 AS = AS_none; 11561 } 11562 } 11563 // If we get here we have (another) forward declaration or we 11564 // have a definition. Just create a new decl. 11565 11566 } else { 11567 // If we get here, this is a definition of a new tag type in a nested 11568 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11569 // new decl/type. We set PrevDecl to NULL so that the entities 11570 // have distinct types. 11571 Previous.clear(); 11572 } 11573 // If we get here, we're going to create a new Decl. If PrevDecl 11574 // is non-NULL, it's a definition of the tag declared by 11575 // PrevDecl. If it's NULL, we have a new definition. 11576 11577 11578 // Otherwise, PrevDecl is not a tag, but was found with tag 11579 // lookup. This is only actually possible in C++, where a few 11580 // things like templates still live in the tag namespace. 11581 } else { 11582 // Use a better diagnostic if an elaborated-type-specifier 11583 // found the wrong kind of type on the first 11584 // (non-redeclaration) lookup. 11585 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11586 !Previous.isForRedeclaration()) { 11587 unsigned Kind = 0; 11588 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11589 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11590 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11591 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11592 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11593 Invalid = true; 11594 11595 // Otherwise, only diagnose if the declaration is in scope. 11596 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11597 SS.isNotEmpty() || isExplicitSpecialization)) { 11598 // do nothing 11599 11600 // Diagnose implicit declarations introduced by elaborated types. 11601 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11602 unsigned Kind = 0; 11603 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11604 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11605 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11606 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11607 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11608 Invalid = true; 11609 11610 // Otherwise it's a declaration. Call out a particularly common 11611 // case here. 11612 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11613 unsigned Kind = 0; 11614 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11615 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11616 << Name << Kind << TND->getUnderlyingType(); 11617 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11618 Invalid = true; 11619 11620 // Otherwise, diagnose. 11621 } else { 11622 // The tag name clashes with something else in the target scope, 11623 // issue an error and recover by making this tag be anonymous. 11624 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11625 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11626 Name = nullptr; 11627 Invalid = true; 11628 } 11629 11630 // The existing declaration isn't relevant to us; we're in a 11631 // new scope, so clear out the previous declaration. 11632 Previous.clear(); 11633 } 11634 } 11635 11636 CreateNewDecl: 11637 11638 TagDecl *PrevDecl = nullptr; 11639 if (Previous.isSingleResult()) 11640 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11641 11642 // If there is an identifier, use the location of the identifier as the 11643 // location of the decl, otherwise use the location of the struct/union 11644 // keyword. 11645 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11646 11647 // Otherwise, create a new declaration. If there is a previous 11648 // declaration of the same entity, the two will be linked via 11649 // PrevDecl. 11650 TagDecl *New; 11651 11652 bool IsForwardReference = false; 11653 if (Kind == TTK_Enum) { 11654 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11655 // enum X { A, B, C } D; D should chain to X. 11656 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11657 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11658 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11659 // If this is an undefined enum, warn. 11660 if (TUK != TUK_Definition && !Invalid) { 11661 TagDecl *Def; 11662 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11663 cast<EnumDecl>(New)->isFixed()) { 11664 // C++0x: 7.2p2: opaque-enum-declaration. 11665 // Conflicts are diagnosed above. Do nothing. 11666 } 11667 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11668 Diag(Loc, diag::ext_forward_ref_enum_def) 11669 << New; 11670 Diag(Def->getLocation(), diag::note_previous_definition); 11671 } else { 11672 unsigned DiagID = diag::ext_forward_ref_enum; 11673 if (getLangOpts().MSVCCompat) 11674 DiagID = diag::ext_ms_forward_ref_enum; 11675 else if (getLangOpts().CPlusPlus) 11676 DiagID = diag::err_forward_ref_enum; 11677 Diag(Loc, DiagID); 11678 11679 // If this is a forward-declared reference to an enumeration, make a 11680 // note of it; we won't actually be introducing the declaration into 11681 // the declaration context. 11682 if (TUK == TUK_Reference) 11683 IsForwardReference = true; 11684 } 11685 } 11686 11687 if (EnumUnderlying) { 11688 EnumDecl *ED = cast<EnumDecl>(New); 11689 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11690 ED->setIntegerTypeSourceInfo(TI); 11691 else 11692 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11693 ED->setPromotionType(ED->getIntegerType()); 11694 } 11695 11696 } else { 11697 // struct/union/class 11698 11699 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11700 // struct X { int A; } D; D should chain to X. 11701 if (getLangOpts().CPlusPlus) { 11702 // FIXME: Look for a way to use RecordDecl for simple structs. 11703 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11704 cast_or_null<CXXRecordDecl>(PrevDecl)); 11705 11706 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11707 StdBadAlloc = cast<CXXRecordDecl>(New); 11708 } else 11709 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11710 cast_or_null<RecordDecl>(PrevDecl)); 11711 } 11712 11713 // C++11 [dcl.type]p3: 11714 // A type-specifier-seq shall not define a class or enumeration [...]. 11715 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11716 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11717 << Context.getTagDeclType(New); 11718 Invalid = true; 11719 } 11720 11721 // Maybe add qualifier info. 11722 if (SS.isNotEmpty()) { 11723 if (SS.isSet()) { 11724 // If this is either a declaration or a definition, check the 11725 // nested-name-specifier against the current context. We don't do this 11726 // for explicit specializations, because they have similar checking 11727 // (with more specific diagnostics) in the call to 11728 // CheckMemberSpecialization, below. 11729 if (!isExplicitSpecialization && 11730 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11731 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11732 Invalid = true; 11733 11734 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11735 if (TemplateParameterLists.size() > 0) { 11736 New->setTemplateParameterListsInfo(Context, 11737 TemplateParameterLists.size(), 11738 TemplateParameterLists.data()); 11739 } 11740 } 11741 else 11742 Invalid = true; 11743 } 11744 11745 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11746 // Add alignment attributes if necessary; these attributes are checked when 11747 // the ASTContext lays out the structure. 11748 // 11749 // It is important for implementing the correct semantics that this 11750 // happen here (in act on tag decl). The #pragma pack stack is 11751 // maintained as a result of parser callbacks which can occur at 11752 // many points during the parsing of a struct declaration (because 11753 // the #pragma tokens are effectively skipped over during the 11754 // parsing of the struct). 11755 if (TUK == TUK_Definition) { 11756 AddAlignmentAttributesForRecord(RD); 11757 AddMsStructLayoutForRecord(RD); 11758 } 11759 } 11760 11761 if (ModulePrivateLoc.isValid()) { 11762 if (isExplicitSpecialization) 11763 Diag(New->getLocation(), diag::err_module_private_specialization) 11764 << 2 11765 << FixItHint::CreateRemoval(ModulePrivateLoc); 11766 // __module_private__ does not apply to local classes. However, we only 11767 // diagnose this as an error when the declaration specifiers are 11768 // freestanding. Here, we just ignore the __module_private__. 11769 else if (!SearchDC->isFunctionOrMethod()) 11770 New->setModulePrivate(); 11771 } 11772 11773 // If this is a specialization of a member class (of a class template), 11774 // check the specialization. 11775 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11776 Invalid = true; 11777 11778 // If we're declaring or defining a tag in function prototype scope in C, 11779 // note that this type can only be used within the function and add it to 11780 // the list of decls to inject into the function definition scope. 11781 if ((Name || Kind == TTK_Enum) && 11782 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11783 if (getLangOpts().CPlusPlus) { 11784 // C++ [dcl.fct]p6: 11785 // Types shall not be defined in return or parameter types. 11786 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11787 Diag(Loc, diag::err_type_defined_in_param_type) 11788 << Name; 11789 Invalid = true; 11790 } 11791 } else { 11792 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11793 } 11794 DeclsInPrototypeScope.push_back(New); 11795 } 11796 11797 if (Invalid) 11798 New->setInvalidDecl(); 11799 11800 if (Attr) 11801 ProcessDeclAttributeList(S, New, Attr); 11802 11803 // Set the lexical context. If the tag has a C++ scope specifier, the 11804 // lexical context will be different from the semantic context. 11805 New->setLexicalDeclContext(CurContext); 11806 11807 // Mark this as a friend decl if applicable. 11808 // In Microsoft mode, a friend declaration also acts as a forward 11809 // declaration so we always pass true to setObjectOfFriendDecl to make 11810 // the tag name visible. 11811 if (TUK == TUK_Friend) 11812 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11813 11814 // Set the access specifier. 11815 if (!Invalid && SearchDC->isRecord()) 11816 SetMemberAccessSpecifier(New, PrevDecl, AS); 11817 11818 if (TUK == TUK_Definition) 11819 New->startDefinition(); 11820 11821 // If this has an identifier, add it to the scope stack. 11822 if (TUK == TUK_Friend) { 11823 // We might be replacing an existing declaration in the lookup tables; 11824 // if so, borrow its access specifier. 11825 if (PrevDecl) 11826 New->setAccess(PrevDecl->getAccess()); 11827 11828 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11829 DC->makeDeclVisibleInContext(New); 11830 if (Name) // can be null along some error paths 11831 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11832 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11833 } else if (Name) { 11834 S = getNonFieldDeclScope(S); 11835 PushOnScopeChains(New, S, !IsForwardReference); 11836 if (IsForwardReference) 11837 SearchDC->makeDeclVisibleInContext(New); 11838 11839 } else { 11840 CurContext->addDecl(New); 11841 } 11842 11843 // If this is the C FILE type, notify the AST context. 11844 if (IdentifierInfo *II = New->getIdentifier()) 11845 if (!New->isInvalidDecl() && 11846 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11847 II->isStr("FILE")) 11848 Context.setFILEDecl(New); 11849 11850 if (PrevDecl) 11851 mergeDeclAttributes(New, PrevDecl); 11852 11853 // If there's a #pragma GCC visibility in scope, set the visibility of this 11854 // record. 11855 AddPushedVisibilityAttribute(New); 11856 11857 OwnedDecl = true; 11858 // In C++, don't return an invalid declaration. We can't recover well from 11859 // the cases where we make the type anonymous. 11860 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11861 } 11862 11863 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11864 AdjustDeclIfTemplate(TagD); 11865 TagDecl *Tag = cast<TagDecl>(TagD); 11866 11867 // Enter the tag context. 11868 PushDeclContext(S, Tag); 11869 11870 ActOnDocumentableDecl(TagD); 11871 11872 // If there's a #pragma GCC visibility in scope, set the visibility of this 11873 // record. 11874 AddPushedVisibilityAttribute(Tag); 11875 } 11876 11877 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11878 assert(isa<ObjCContainerDecl>(IDecl) && 11879 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11880 DeclContext *OCD = cast<DeclContext>(IDecl); 11881 assert(getContainingDC(OCD) == CurContext && 11882 "The next DeclContext should be lexically contained in the current one."); 11883 CurContext = OCD; 11884 return IDecl; 11885 } 11886 11887 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11888 SourceLocation FinalLoc, 11889 bool IsFinalSpelledSealed, 11890 SourceLocation LBraceLoc) { 11891 AdjustDeclIfTemplate(TagD); 11892 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11893 11894 FieldCollector->StartClass(); 11895 11896 if (!Record->getIdentifier()) 11897 return; 11898 11899 if (FinalLoc.isValid()) 11900 Record->addAttr(new (Context) 11901 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11902 11903 // C++ [class]p2: 11904 // [...] The class-name is also inserted into the scope of the 11905 // class itself; this is known as the injected-class-name. For 11906 // purposes of access checking, the injected-class-name is treated 11907 // as if it were a public member name. 11908 CXXRecordDecl *InjectedClassName 11909 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11910 Record->getLocStart(), Record->getLocation(), 11911 Record->getIdentifier(), 11912 /*PrevDecl=*/nullptr, 11913 /*DelayTypeCreation=*/true); 11914 Context.getTypeDeclType(InjectedClassName, Record); 11915 InjectedClassName->setImplicit(); 11916 InjectedClassName->setAccess(AS_public); 11917 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11918 InjectedClassName->setDescribedClassTemplate(Template); 11919 PushOnScopeChains(InjectedClassName, S); 11920 assert(InjectedClassName->isInjectedClassName() && 11921 "Broken injected-class-name"); 11922 } 11923 11924 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11925 SourceLocation RBraceLoc) { 11926 AdjustDeclIfTemplate(TagD); 11927 TagDecl *Tag = cast<TagDecl>(TagD); 11928 Tag->setRBraceLoc(RBraceLoc); 11929 11930 // Make sure we "complete" the definition even it is invalid. 11931 if (Tag->isBeingDefined()) { 11932 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11933 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11934 RD->completeDefinition(); 11935 } 11936 11937 if (isa<CXXRecordDecl>(Tag)) 11938 FieldCollector->FinishClass(); 11939 11940 // Exit this scope of this tag's definition. 11941 PopDeclContext(); 11942 11943 if (getCurLexicalContext()->isObjCContainer() && 11944 Tag->getDeclContext()->isFileContext()) 11945 Tag->setTopLevelDeclInObjCContainer(); 11946 11947 // Notify the consumer that we've defined a tag. 11948 if (!Tag->isInvalidDecl()) 11949 Consumer.HandleTagDeclDefinition(Tag); 11950 } 11951 11952 void Sema::ActOnObjCContainerFinishDefinition() { 11953 // Exit this scope of this interface definition. 11954 PopDeclContext(); 11955 } 11956 11957 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11958 assert(DC == CurContext && "Mismatch of container contexts"); 11959 OriginalLexicalContext = DC; 11960 ActOnObjCContainerFinishDefinition(); 11961 } 11962 11963 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11964 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11965 OriginalLexicalContext = nullptr; 11966 } 11967 11968 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11969 AdjustDeclIfTemplate(TagD); 11970 TagDecl *Tag = cast<TagDecl>(TagD); 11971 Tag->setInvalidDecl(); 11972 11973 // Make sure we "complete" the definition even it is invalid. 11974 if (Tag->isBeingDefined()) { 11975 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11976 RD->completeDefinition(); 11977 } 11978 11979 // We're undoing ActOnTagStartDefinition here, not 11980 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11981 // the FieldCollector. 11982 11983 PopDeclContext(); 11984 } 11985 11986 // Note that FieldName may be null for anonymous bitfields. 11987 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11988 IdentifierInfo *FieldName, 11989 QualType FieldTy, bool IsMsStruct, 11990 Expr *BitWidth, bool *ZeroWidth) { 11991 // Default to true; that shouldn't confuse checks for emptiness 11992 if (ZeroWidth) 11993 *ZeroWidth = true; 11994 11995 // C99 6.7.2.1p4 - verify the field type. 11996 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11997 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11998 // Handle incomplete types with specific error. 11999 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12000 return ExprError(); 12001 if (FieldName) 12002 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12003 << FieldName << FieldTy << BitWidth->getSourceRange(); 12004 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12005 << FieldTy << BitWidth->getSourceRange(); 12006 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12007 UPPC_BitFieldWidth)) 12008 return ExprError(); 12009 12010 // If the bit-width is type- or value-dependent, don't try to check 12011 // it now. 12012 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12013 return BitWidth; 12014 12015 llvm::APSInt Value; 12016 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12017 if (ICE.isInvalid()) 12018 return ICE; 12019 BitWidth = ICE.get(); 12020 12021 if (Value != 0 && ZeroWidth) 12022 *ZeroWidth = false; 12023 12024 // Zero-width bitfield is ok for anonymous field. 12025 if (Value == 0 && FieldName) 12026 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12027 12028 if (Value.isSigned() && Value.isNegative()) { 12029 if (FieldName) 12030 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12031 << FieldName << Value.toString(10); 12032 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12033 << Value.toString(10); 12034 } 12035 12036 if (!FieldTy->isDependentType()) { 12037 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12038 if (Value.getZExtValue() > TypeSize) { 12039 if (!getLangOpts().CPlusPlus || IsMsStruct || 12040 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12041 if (FieldName) 12042 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12043 << FieldName << (unsigned)Value.getZExtValue() 12044 << (unsigned)TypeSize; 12045 12046 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12047 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12048 } 12049 12050 if (FieldName) 12051 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12052 << FieldName << (unsigned)Value.getZExtValue() 12053 << (unsigned)TypeSize; 12054 else 12055 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12056 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12057 } 12058 } 12059 12060 return BitWidth; 12061 } 12062 12063 /// ActOnField - Each field of a C struct/union is passed into this in order 12064 /// to create a FieldDecl object for it. 12065 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12066 Declarator &D, Expr *BitfieldWidth) { 12067 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12068 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12069 /*InitStyle=*/ICIS_NoInit, AS_public); 12070 return Res; 12071 } 12072 12073 /// HandleField - Analyze a field of a C struct or a C++ data member. 12074 /// 12075 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12076 SourceLocation DeclStart, 12077 Declarator &D, Expr *BitWidth, 12078 InClassInitStyle InitStyle, 12079 AccessSpecifier AS) { 12080 IdentifierInfo *II = D.getIdentifier(); 12081 SourceLocation Loc = DeclStart; 12082 if (II) Loc = D.getIdentifierLoc(); 12083 12084 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12085 QualType T = TInfo->getType(); 12086 if (getLangOpts().CPlusPlus) { 12087 CheckExtraCXXDefaultArguments(D); 12088 12089 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12090 UPPC_DataMemberType)) { 12091 D.setInvalidType(); 12092 T = Context.IntTy; 12093 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12094 } 12095 } 12096 12097 // TR 18037 does not allow fields to be declared with address spaces. 12098 if (T.getQualifiers().hasAddressSpace()) { 12099 Diag(Loc, diag::err_field_with_address_space); 12100 D.setInvalidType(); 12101 } 12102 12103 // OpenCL 1.2 spec, s6.9 r: 12104 // The event type cannot be used to declare a structure or union field. 12105 if (LangOpts.OpenCL && T->isEventT()) { 12106 Diag(Loc, diag::err_event_t_struct_field); 12107 D.setInvalidType(); 12108 } 12109 12110 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12111 12112 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12113 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12114 diag::err_invalid_thread) 12115 << DeclSpec::getSpecifierName(TSCS); 12116 12117 // Check to see if this name was declared as a member previously 12118 NamedDecl *PrevDecl = nullptr; 12119 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12120 LookupName(Previous, S); 12121 switch (Previous.getResultKind()) { 12122 case LookupResult::Found: 12123 case LookupResult::FoundUnresolvedValue: 12124 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12125 break; 12126 12127 case LookupResult::FoundOverloaded: 12128 PrevDecl = Previous.getRepresentativeDecl(); 12129 break; 12130 12131 case LookupResult::NotFound: 12132 case LookupResult::NotFoundInCurrentInstantiation: 12133 case LookupResult::Ambiguous: 12134 break; 12135 } 12136 Previous.suppressDiagnostics(); 12137 12138 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12139 // Maybe we will complain about the shadowed template parameter. 12140 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12141 // Just pretend that we didn't see the previous declaration. 12142 PrevDecl = nullptr; 12143 } 12144 12145 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12146 PrevDecl = nullptr; 12147 12148 bool Mutable 12149 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12150 SourceLocation TSSL = D.getLocStart(); 12151 FieldDecl *NewFD 12152 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12153 TSSL, AS, PrevDecl, &D); 12154 12155 if (NewFD->isInvalidDecl()) 12156 Record->setInvalidDecl(); 12157 12158 if (D.getDeclSpec().isModulePrivateSpecified()) 12159 NewFD->setModulePrivate(); 12160 12161 if (NewFD->isInvalidDecl() && PrevDecl) { 12162 // Don't introduce NewFD into scope; there's already something 12163 // with the same name in the same scope. 12164 } else if (II) { 12165 PushOnScopeChains(NewFD, S); 12166 } else 12167 Record->addDecl(NewFD); 12168 12169 return NewFD; 12170 } 12171 12172 /// \brief Build a new FieldDecl and check its well-formedness. 12173 /// 12174 /// This routine builds a new FieldDecl given the fields name, type, 12175 /// record, etc. \p PrevDecl should refer to any previous declaration 12176 /// with the same name and in the same scope as the field to be 12177 /// created. 12178 /// 12179 /// \returns a new FieldDecl. 12180 /// 12181 /// \todo The Declarator argument is a hack. It will be removed once 12182 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12183 TypeSourceInfo *TInfo, 12184 RecordDecl *Record, SourceLocation Loc, 12185 bool Mutable, Expr *BitWidth, 12186 InClassInitStyle InitStyle, 12187 SourceLocation TSSL, 12188 AccessSpecifier AS, NamedDecl *PrevDecl, 12189 Declarator *D) { 12190 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12191 bool InvalidDecl = false; 12192 if (D) InvalidDecl = D->isInvalidType(); 12193 12194 // If we receive a broken type, recover by assuming 'int' and 12195 // marking this declaration as invalid. 12196 if (T.isNull()) { 12197 InvalidDecl = true; 12198 T = Context.IntTy; 12199 } 12200 12201 QualType EltTy = Context.getBaseElementType(T); 12202 if (!EltTy->isDependentType()) { 12203 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12204 // Fields of incomplete type force their record to be invalid. 12205 Record->setInvalidDecl(); 12206 InvalidDecl = true; 12207 } else { 12208 NamedDecl *Def; 12209 EltTy->isIncompleteType(&Def); 12210 if (Def && Def->isInvalidDecl()) { 12211 Record->setInvalidDecl(); 12212 InvalidDecl = true; 12213 } 12214 } 12215 } 12216 12217 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12218 if (BitWidth && getLangOpts().OpenCL) { 12219 Diag(Loc, diag::err_opencl_bitfields); 12220 InvalidDecl = true; 12221 } 12222 12223 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12224 // than a variably modified type. 12225 if (!InvalidDecl && T->isVariablyModifiedType()) { 12226 bool SizeIsNegative; 12227 llvm::APSInt Oversized; 12228 12229 TypeSourceInfo *FixedTInfo = 12230 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12231 SizeIsNegative, 12232 Oversized); 12233 if (FixedTInfo) { 12234 Diag(Loc, diag::warn_illegal_constant_array_size); 12235 TInfo = FixedTInfo; 12236 T = FixedTInfo->getType(); 12237 } else { 12238 if (SizeIsNegative) 12239 Diag(Loc, diag::err_typecheck_negative_array_size); 12240 else if (Oversized.getBoolValue()) 12241 Diag(Loc, diag::err_array_too_large) 12242 << Oversized.toString(10); 12243 else 12244 Diag(Loc, diag::err_typecheck_field_variable_size); 12245 InvalidDecl = true; 12246 } 12247 } 12248 12249 // Fields can not have abstract class types 12250 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12251 diag::err_abstract_type_in_decl, 12252 AbstractFieldType)) 12253 InvalidDecl = true; 12254 12255 bool ZeroWidth = false; 12256 // If this is declared as a bit-field, check the bit-field. 12257 if (!InvalidDecl && BitWidth) { 12258 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12259 &ZeroWidth).get(); 12260 if (!BitWidth) { 12261 InvalidDecl = true; 12262 BitWidth = nullptr; 12263 ZeroWidth = false; 12264 } 12265 } 12266 12267 // Check that 'mutable' is consistent with the type of the declaration. 12268 if (!InvalidDecl && Mutable) { 12269 unsigned DiagID = 0; 12270 if (T->isReferenceType()) 12271 DiagID = diag::err_mutable_reference; 12272 else if (T.isConstQualified()) 12273 DiagID = diag::err_mutable_const; 12274 12275 if (DiagID) { 12276 SourceLocation ErrLoc = Loc; 12277 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12278 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12279 Diag(ErrLoc, DiagID); 12280 Mutable = false; 12281 InvalidDecl = true; 12282 } 12283 } 12284 12285 // C++11 [class.union]p8 (DR1460): 12286 // At most one variant member of a union may have a 12287 // brace-or-equal-initializer. 12288 if (InitStyle != ICIS_NoInit) 12289 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12290 12291 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12292 BitWidth, Mutable, InitStyle); 12293 if (InvalidDecl) 12294 NewFD->setInvalidDecl(); 12295 12296 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12297 Diag(Loc, diag::err_duplicate_member) << II; 12298 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12299 NewFD->setInvalidDecl(); 12300 } 12301 12302 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12303 if (Record->isUnion()) { 12304 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12305 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12306 if (RDecl->getDefinition()) { 12307 // C++ [class.union]p1: An object of a class with a non-trivial 12308 // constructor, a non-trivial copy constructor, a non-trivial 12309 // destructor, or a non-trivial copy assignment operator 12310 // cannot be a member of a union, nor can an array of such 12311 // objects. 12312 if (CheckNontrivialField(NewFD)) 12313 NewFD->setInvalidDecl(); 12314 } 12315 } 12316 12317 // C++ [class.union]p1: If a union contains a member of reference type, 12318 // the program is ill-formed, except when compiling with MSVC extensions 12319 // enabled. 12320 if (EltTy->isReferenceType()) { 12321 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12322 diag::ext_union_member_of_reference_type : 12323 diag::err_union_member_of_reference_type) 12324 << NewFD->getDeclName() << EltTy; 12325 if (!getLangOpts().MicrosoftExt) 12326 NewFD->setInvalidDecl(); 12327 } 12328 } 12329 } 12330 12331 // FIXME: We need to pass in the attributes given an AST 12332 // representation, not a parser representation. 12333 if (D) { 12334 // FIXME: The current scope is almost... but not entirely... correct here. 12335 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12336 12337 if (NewFD->hasAttrs()) 12338 CheckAlignasUnderalignment(NewFD); 12339 } 12340 12341 // In auto-retain/release, infer strong retension for fields of 12342 // retainable type. 12343 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12344 NewFD->setInvalidDecl(); 12345 12346 if (T.isObjCGCWeak()) 12347 Diag(Loc, diag::warn_attribute_weak_on_field); 12348 12349 NewFD->setAccess(AS); 12350 return NewFD; 12351 } 12352 12353 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12354 assert(FD); 12355 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12356 12357 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12358 return false; 12359 12360 QualType EltTy = Context.getBaseElementType(FD->getType()); 12361 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12362 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12363 if (RDecl->getDefinition()) { 12364 // We check for copy constructors before constructors 12365 // because otherwise we'll never get complaints about 12366 // copy constructors. 12367 12368 CXXSpecialMember member = CXXInvalid; 12369 // We're required to check for any non-trivial constructors. Since the 12370 // implicit default constructor is suppressed if there are any 12371 // user-declared constructors, we just need to check that there is a 12372 // trivial default constructor and a trivial copy constructor. (We don't 12373 // worry about move constructors here, since this is a C++98 check.) 12374 if (RDecl->hasNonTrivialCopyConstructor()) 12375 member = CXXCopyConstructor; 12376 else if (!RDecl->hasTrivialDefaultConstructor()) 12377 member = CXXDefaultConstructor; 12378 else if (RDecl->hasNonTrivialCopyAssignment()) 12379 member = CXXCopyAssignment; 12380 else if (RDecl->hasNonTrivialDestructor()) 12381 member = CXXDestructor; 12382 12383 if (member != CXXInvalid) { 12384 if (!getLangOpts().CPlusPlus11 && 12385 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12386 // Objective-C++ ARC: it is an error to have a non-trivial field of 12387 // a union. However, system headers in Objective-C programs 12388 // occasionally have Objective-C lifetime objects within unions, 12389 // and rather than cause the program to fail, we make those 12390 // members unavailable. 12391 SourceLocation Loc = FD->getLocation(); 12392 if (getSourceManager().isInSystemHeader(Loc)) { 12393 if (!FD->hasAttr<UnavailableAttr>()) 12394 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12395 "this system field has retaining ownership", 12396 Loc)); 12397 return false; 12398 } 12399 } 12400 12401 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12402 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12403 diag::err_illegal_union_or_anon_struct_member) 12404 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12405 DiagnoseNontrivial(RDecl, member); 12406 return !getLangOpts().CPlusPlus11; 12407 } 12408 } 12409 } 12410 12411 return false; 12412 } 12413 12414 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12415 /// AST enum value. 12416 static ObjCIvarDecl::AccessControl 12417 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12418 switch (ivarVisibility) { 12419 default: llvm_unreachable("Unknown visitibility kind"); 12420 case tok::objc_private: return ObjCIvarDecl::Private; 12421 case tok::objc_public: return ObjCIvarDecl::Public; 12422 case tok::objc_protected: return ObjCIvarDecl::Protected; 12423 case tok::objc_package: return ObjCIvarDecl::Package; 12424 } 12425 } 12426 12427 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12428 /// in order to create an IvarDecl object for it. 12429 Decl *Sema::ActOnIvar(Scope *S, 12430 SourceLocation DeclStart, 12431 Declarator &D, Expr *BitfieldWidth, 12432 tok::ObjCKeywordKind Visibility) { 12433 12434 IdentifierInfo *II = D.getIdentifier(); 12435 Expr *BitWidth = (Expr*)BitfieldWidth; 12436 SourceLocation Loc = DeclStart; 12437 if (II) Loc = D.getIdentifierLoc(); 12438 12439 // FIXME: Unnamed fields can be handled in various different ways, for 12440 // example, unnamed unions inject all members into the struct namespace! 12441 12442 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12443 QualType T = TInfo->getType(); 12444 12445 if (BitWidth) { 12446 // 6.7.2.1p3, 6.7.2.1p4 12447 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12448 if (!BitWidth) 12449 D.setInvalidType(); 12450 } else { 12451 // Not a bitfield. 12452 12453 // validate II. 12454 12455 } 12456 if (T->isReferenceType()) { 12457 Diag(Loc, diag::err_ivar_reference_type); 12458 D.setInvalidType(); 12459 } 12460 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12461 // than a variably modified type. 12462 else if (T->isVariablyModifiedType()) { 12463 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12464 D.setInvalidType(); 12465 } 12466 12467 // Get the visibility (access control) for this ivar. 12468 ObjCIvarDecl::AccessControl ac = 12469 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12470 : ObjCIvarDecl::None; 12471 // Must set ivar's DeclContext to its enclosing interface. 12472 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12473 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12474 return nullptr; 12475 ObjCContainerDecl *EnclosingContext; 12476 if (ObjCImplementationDecl *IMPDecl = 12477 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12478 if (LangOpts.ObjCRuntime.isFragile()) { 12479 // Case of ivar declared in an implementation. Context is that of its class. 12480 EnclosingContext = IMPDecl->getClassInterface(); 12481 assert(EnclosingContext && "Implementation has no class interface!"); 12482 } 12483 else 12484 EnclosingContext = EnclosingDecl; 12485 } else { 12486 if (ObjCCategoryDecl *CDecl = 12487 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12488 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12489 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12490 return nullptr; 12491 } 12492 } 12493 EnclosingContext = EnclosingDecl; 12494 } 12495 12496 // Construct the decl. 12497 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12498 DeclStart, Loc, II, T, 12499 TInfo, ac, (Expr *)BitfieldWidth); 12500 12501 if (II) { 12502 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12503 ForRedeclaration); 12504 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12505 && !isa<TagDecl>(PrevDecl)) { 12506 Diag(Loc, diag::err_duplicate_member) << II; 12507 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12508 NewID->setInvalidDecl(); 12509 } 12510 } 12511 12512 // Process attributes attached to the ivar. 12513 ProcessDeclAttributes(S, NewID, D); 12514 12515 if (D.isInvalidType()) 12516 NewID->setInvalidDecl(); 12517 12518 // In ARC, infer 'retaining' for ivars of retainable type. 12519 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12520 NewID->setInvalidDecl(); 12521 12522 if (D.getDeclSpec().isModulePrivateSpecified()) 12523 NewID->setModulePrivate(); 12524 12525 if (II) { 12526 // FIXME: When interfaces are DeclContexts, we'll need to add 12527 // these to the interface. 12528 S->AddDecl(NewID); 12529 IdResolver.AddDecl(NewID); 12530 } 12531 12532 if (LangOpts.ObjCRuntime.isNonFragile() && 12533 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12534 Diag(Loc, diag::warn_ivars_in_interface); 12535 12536 return NewID; 12537 } 12538 12539 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12540 /// class and class extensions. For every class \@interface and class 12541 /// extension \@interface, if the last ivar is a bitfield of any type, 12542 /// then add an implicit `char :0` ivar to the end of that interface. 12543 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12544 SmallVectorImpl<Decl *> &AllIvarDecls) { 12545 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12546 return; 12547 12548 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12549 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12550 12551 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12552 return; 12553 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12554 if (!ID) { 12555 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12556 if (!CD->IsClassExtension()) 12557 return; 12558 } 12559 // No need to add this to end of @implementation. 12560 else 12561 return; 12562 } 12563 // All conditions are met. Add a new bitfield to the tail end of ivars. 12564 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12565 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12566 12567 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12568 DeclLoc, DeclLoc, nullptr, 12569 Context.CharTy, 12570 Context.getTrivialTypeSourceInfo(Context.CharTy, 12571 DeclLoc), 12572 ObjCIvarDecl::Private, BW, 12573 true); 12574 AllIvarDecls.push_back(Ivar); 12575 } 12576 12577 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12578 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12579 SourceLocation RBrac, AttributeList *Attr) { 12580 assert(EnclosingDecl && "missing record or interface decl"); 12581 12582 // If this is an Objective-C @implementation or category and we have 12583 // new fields here we should reset the layout of the interface since 12584 // it will now change. 12585 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12586 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12587 switch (DC->getKind()) { 12588 default: break; 12589 case Decl::ObjCCategory: 12590 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12591 break; 12592 case Decl::ObjCImplementation: 12593 Context. 12594 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12595 break; 12596 } 12597 } 12598 12599 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12600 12601 // Start counting up the number of named members; make sure to include 12602 // members of anonymous structs and unions in the total. 12603 unsigned NumNamedMembers = 0; 12604 if (Record) { 12605 for (const auto *I : Record->decls()) { 12606 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12607 if (IFD->getDeclName()) 12608 ++NumNamedMembers; 12609 } 12610 } 12611 12612 // Verify that all the fields are okay. 12613 SmallVector<FieldDecl*, 32> RecFields; 12614 12615 bool ARCErrReported = false; 12616 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12617 i != end; ++i) { 12618 FieldDecl *FD = cast<FieldDecl>(*i); 12619 12620 // Get the type for the field. 12621 const Type *FDTy = FD->getType().getTypePtr(); 12622 12623 if (!FD->isAnonymousStructOrUnion()) { 12624 // Remember all fields written by the user. 12625 RecFields.push_back(FD); 12626 } 12627 12628 // If the field is already invalid for some reason, don't emit more 12629 // diagnostics about it. 12630 if (FD->isInvalidDecl()) { 12631 EnclosingDecl->setInvalidDecl(); 12632 continue; 12633 } 12634 12635 // C99 6.7.2.1p2: 12636 // A structure or union shall not contain a member with 12637 // incomplete or function type (hence, a structure shall not 12638 // contain an instance of itself, but may contain a pointer to 12639 // an instance of itself), except that the last member of a 12640 // structure with more than one named member may have incomplete 12641 // array type; such a structure (and any union containing, 12642 // possibly recursively, a member that is such a structure) 12643 // shall not be a member of a structure or an element of an 12644 // array. 12645 if (FDTy->isFunctionType()) { 12646 // Field declared as a function. 12647 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12648 << FD->getDeclName(); 12649 FD->setInvalidDecl(); 12650 EnclosingDecl->setInvalidDecl(); 12651 continue; 12652 } else if (FDTy->isIncompleteArrayType() && Record && 12653 ((i + 1 == Fields.end() && !Record->isUnion()) || 12654 ((getLangOpts().MicrosoftExt || 12655 getLangOpts().CPlusPlus) && 12656 (i + 1 == Fields.end() || Record->isUnion())))) { 12657 // Flexible array member. 12658 // Microsoft and g++ is more permissive regarding flexible array. 12659 // It will accept flexible array in union and also 12660 // as the sole element of a struct/class. 12661 unsigned DiagID = 0; 12662 if (Record->isUnion()) 12663 DiagID = getLangOpts().MicrosoftExt 12664 ? diag::ext_flexible_array_union_ms 12665 : getLangOpts().CPlusPlus 12666 ? diag::ext_flexible_array_union_gnu 12667 : diag::err_flexible_array_union; 12668 else if (Fields.size() == 1) 12669 DiagID = getLangOpts().MicrosoftExt 12670 ? diag::ext_flexible_array_empty_aggregate_ms 12671 : getLangOpts().CPlusPlus 12672 ? diag::ext_flexible_array_empty_aggregate_gnu 12673 : NumNamedMembers < 1 12674 ? diag::err_flexible_array_empty_aggregate 12675 : 0; 12676 12677 if (DiagID) 12678 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12679 << Record->getTagKind(); 12680 // While the layout of types that contain virtual bases is not specified 12681 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12682 // virtual bases after the derived members. This would make a flexible 12683 // array member declared at the end of an object not adjacent to the end 12684 // of the type. 12685 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12686 if (RD->getNumVBases() != 0) 12687 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12688 << FD->getDeclName() << Record->getTagKind(); 12689 if (!getLangOpts().C99) 12690 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12691 << FD->getDeclName() << Record->getTagKind(); 12692 12693 // If the element type has a non-trivial destructor, we would not 12694 // implicitly destroy the elements, so disallow it for now. 12695 // 12696 // FIXME: GCC allows this. We should probably either implicitly delete 12697 // the destructor of the containing class, or just allow this. 12698 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12699 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12700 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12701 << FD->getDeclName() << FD->getType(); 12702 FD->setInvalidDecl(); 12703 EnclosingDecl->setInvalidDecl(); 12704 continue; 12705 } 12706 // Okay, we have a legal flexible array member at the end of the struct. 12707 if (Record) 12708 Record->setHasFlexibleArrayMember(true); 12709 } else if (!FDTy->isDependentType() && 12710 RequireCompleteType(FD->getLocation(), FD->getType(), 12711 diag::err_field_incomplete)) { 12712 // Incomplete type 12713 FD->setInvalidDecl(); 12714 EnclosingDecl->setInvalidDecl(); 12715 continue; 12716 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12717 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12718 // If this is a member of a union, then entire union becomes "flexible". 12719 if (Record && Record->isUnion()) { 12720 Record->setHasFlexibleArrayMember(true); 12721 } else { 12722 // If this is a struct/class and this is not the last element, reject 12723 // it. Note that GCC supports variable sized arrays in the middle of 12724 // structures. 12725 if (i + 1 != Fields.end()) 12726 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12727 << FD->getDeclName() << FD->getType(); 12728 else { 12729 // We support flexible arrays at the end of structs in 12730 // other structs as an extension. 12731 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12732 << FD->getDeclName(); 12733 if (Record) 12734 Record->setHasFlexibleArrayMember(true); 12735 } 12736 } 12737 } 12738 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12739 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12740 diag::err_abstract_type_in_decl, 12741 AbstractIvarType)) { 12742 // Ivars can not have abstract class types 12743 FD->setInvalidDecl(); 12744 } 12745 if (Record && FDTTy->getDecl()->hasObjectMember()) 12746 Record->setHasObjectMember(true); 12747 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12748 Record->setHasVolatileMember(true); 12749 } else if (FDTy->isObjCObjectType()) { 12750 /// A field cannot be an Objective-c object 12751 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12752 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12753 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12754 FD->setType(T); 12755 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12756 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12757 // It's an error in ARC if a field has lifetime. 12758 // We don't want to report this in a system header, though, 12759 // so we just make the field unavailable. 12760 // FIXME: that's really not sufficient; we need to make the type 12761 // itself invalid to, say, initialize or copy. 12762 QualType T = FD->getType(); 12763 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12764 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12765 SourceLocation loc = FD->getLocation(); 12766 if (getSourceManager().isInSystemHeader(loc)) { 12767 if (!FD->hasAttr<UnavailableAttr>()) { 12768 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12769 "this system field has retaining ownership", 12770 loc)); 12771 } 12772 } else { 12773 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12774 << T->isBlockPointerType() << Record->getTagKind(); 12775 } 12776 ARCErrReported = true; 12777 } 12778 } else if (getLangOpts().ObjC1 && 12779 getLangOpts().getGC() != LangOptions::NonGC && 12780 Record && !Record->hasObjectMember()) { 12781 if (FD->getType()->isObjCObjectPointerType() || 12782 FD->getType().isObjCGCStrong()) 12783 Record->setHasObjectMember(true); 12784 else if (Context.getAsArrayType(FD->getType())) { 12785 QualType BaseType = Context.getBaseElementType(FD->getType()); 12786 if (BaseType->isRecordType() && 12787 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12788 Record->setHasObjectMember(true); 12789 else if (BaseType->isObjCObjectPointerType() || 12790 BaseType.isObjCGCStrong()) 12791 Record->setHasObjectMember(true); 12792 } 12793 } 12794 if (Record && FD->getType().isVolatileQualified()) 12795 Record->setHasVolatileMember(true); 12796 // Keep track of the number of named members. 12797 if (FD->getIdentifier()) 12798 ++NumNamedMembers; 12799 } 12800 12801 // Okay, we successfully defined 'Record'. 12802 if (Record) { 12803 bool Completed = false; 12804 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12805 if (!CXXRecord->isInvalidDecl()) { 12806 // Set access bits correctly on the directly-declared conversions. 12807 for (CXXRecordDecl::conversion_iterator 12808 I = CXXRecord->conversion_begin(), 12809 E = CXXRecord->conversion_end(); I != E; ++I) 12810 I.setAccess((*I)->getAccess()); 12811 12812 if (!CXXRecord->isDependentType()) { 12813 if (CXXRecord->hasUserDeclaredDestructor()) { 12814 // Adjust user-defined destructor exception spec. 12815 if (getLangOpts().CPlusPlus11) 12816 AdjustDestructorExceptionSpec(CXXRecord, 12817 CXXRecord->getDestructor()); 12818 } 12819 12820 // Add any implicitly-declared members to this class. 12821 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12822 12823 // If we have virtual base classes, we may end up finding multiple 12824 // final overriders for a given virtual function. Check for this 12825 // problem now. 12826 if (CXXRecord->getNumVBases()) { 12827 CXXFinalOverriderMap FinalOverriders; 12828 CXXRecord->getFinalOverriders(FinalOverriders); 12829 12830 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12831 MEnd = FinalOverriders.end(); 12832 M != MEnd; ++M) { 12833 for (OverridingMethods::iterator SO = M->second.begin(), 12834 SOEnd = M->second.end(); 12835 SO != SOEnd; ++SO) { 12836 assert(SO->second.size() > 0 && 12837 "Virtual function without overridding functions?"); 12838 if (SO->second.size() == 1) 12839 continue; 12840 12841 // C++ [class.virtual]p2: 12842 // In a derived class, if a virtual member function of a base 12843 // class subobject has more than one final overrider the 12844 // program is ill-formed. 12845 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12846 << (const NamedDecl *)M->first << Record; 12847 Diag(M->first->getLocation(), 12848 diag::note_overridden_virtual_function); 12849 for (OverridingMethods::overriding_iterator 12850 OM = SO->second.begin(), 12851 OMEnd = SO->second.end(); 12852 OM != OMEnd; ++OM) 12853 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12854 << (const NamedDecl *)M->first << OM->Method->getParent(); 12855 12856 Record->setInvalidDecl(); 12857 } 12858 } 12859 CXXRecord->completeDefinition(&FinalOverriders); 12860 Completed = true; 12861 } 12862 } 12863 } 12864 } 12865 12866 if (!Completed) 12867 Record->completeDefinition(); 12868 12869 if (Record->hasAttrs()) { 12870 CheckAlignasUnderalignment(Record); 12871 12872 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12873 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12874 IA->getRange(), IA->getBestCase(), 12875 IA->getSemanticSpelling()); 12876 } 12877 12878 // Check if the structure/union declaration is a type that can have zero 12879 // size in C. For C this is a language extension, for C++ it may cause 12880 // compatibility problems. 12881 bool CheckForZeroSize; 12882 if (!getLangOpts().CPlusPlus) { 12883 CheckForZeroSize = true; 12884 } else { 12885 // For C++ filter out types that cannot be referenced in C code. 12886 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12887 CheckForZeroSize = 12888 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12889 !CXXRecord->isDependentType() && 12890 CXXRecord->isCLike(); 12891 } 12892 if (CheckForZeroSize) { 12893 bool ZeroSize = true; 12894 bool IsEmpty = true; 12895 unsigned NonBitFields = 0; 12896 for (RecordDecl::field_iterator I = Record->field_begin(), 12897 E = Record->field_end(); 12898 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12899 IsEmpty = false; 12900 if (I->isUnnamedBitfield()) { 12901 if (I->getBitWidthValue(Context) > 0) 12902 ZeroSize = false; 12903 } else { 12904 ++NonBitFields; 12905 QualType FieldType = I->getType(); 12906 if (FieldType->isIncompleteType() || 12907 !Context.getTypeSizeInChars(FieldType).isZero()) 12908 ZeroSize = false; 12909 } 12910 } 12911 12912 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12913 // allowed in C++, but warn if its declaration is inside 12914 // extern "C" block. 12915 if (ZeroSize) { 12916 Diag(RecLoc, getLangOpts().CPlusPlus ? 12917 diag::warn_zero_size_struct_union_in_extern_c : 12918 diag::warn_zero_size_struct_union_compat) 12919 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12920 } 12921 12922 // Structs without named members are extension in C (C99 6.7.2.1p7), 12923 // but are accepted by GCC. 12924 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12925 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12926 diag::ext_no_named_members_in_struct_union) 12927 << Record->isUnion(); 12928 } 12929 } 12930 } else { 12931 ObjCIvarDecl **ClsFields = 12932 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12933 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12934 ID->setEndOfDefinitionLoc(RBrac); 12935 // Add ivar's to class's DeclContext. 12936 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12937 ClsFields[i]->setLexicalDeclContext(ID); 12938 ID->addDecl(ClsFields[i]); 12939 } 12940 // Must enforce the rule that ivars in the base classes may not be 12941 // duplicates. 12942 if (ID->getSuperClass()) 12943 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12944 } else if (ObjCImplementationDecl *IMPDecl = 12945 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12946 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12947 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12948 // Ivar declared in @implementation never belongs to the implementation. 12949 // Only it is in implementation's lexical context. 12950 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12951 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12952 IMPDecl->setIvarLBraceLoc(LBrac); 12953 IMPDecl->setIvarRBraceLoc(RBrac); 12954 } else if (ObjCCategoryDecl *CDecl = 12955 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12956 // case of ivars in class extension; all other cases have been 12957 // reported as errors elsewhere. 12958 // FIXME. Class extension does not have a LocEnd field. 12959 // CDecl->setLocEnd(RBrac); 12960 // Add ivar's to class extension's DeclContext. 12961 // Diagnose redeclaration of private ivars. 12962 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12963 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12964 if (IDecl) { 12965 if (const ObjCIvarDecl *ClsIvar = 12966 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12967 Diag(ClsFields[i]->getLocation(), 12968 diag::err_duplicate_ivar_declaration); 12969 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12970 continue; 12971 } 12972 for (const auto *Ext : IDecl->known_extensions()) { 12973 if (const ObjCIvarDecl *ClsExtIvar 12974 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12975 Diag(ClsFields[i]->getLocation(), 12976 diag::err_duplicate_ivar_declaration); 12977 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12978 continue; 12979 } 12980 } 12981 } 12982 ClsFields[i]->setLexicalDeclContext(CDecl); 12983 CDecl->addDecl(ClsFields[i]); 12984 } 12985 CDecl->setIvarLBraceLoc(LBrac); 12986 CDecl->setIvarRBraceLoc(RBrac); 12987 } 12988 } 12989 12990 if (Attr) 12991 ProcessDeclAttributeList(S, Record, Attr); 12992 } 12993 12994 /// \brief Determine whether the given integral value is representable within 12995 /// the given type T. 12996 static bool isRepresentableIntegerValue(ASTContext &Context, 12997 llvm::APSInt &Value, 12998 QualType T) { 12999 assert(T->isIntegralType(Context) && "Integral type required!"); 13000 unsigned BitWidth = Context.getIntWidth(T); 13001 13002 if (Value.isUnsigned() || Value.isNonNegative()) { 13003 if (T->isSignedIntegerOrEnumerationType()) 13004 --BitWidth; 13005 return Value.getActiveBits() <= BitWidth; 13006 } 13007 return Value.getMinSignedBits() <= BitWidth; 13008 } 13009 13010 // \brief Given an integral type, return the next larger integral type 13011 // (or a NULL type of no such type exists). 13012 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13013 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13014 // enum checking below. 13015 assert(T->isIntegralType(Context) && "Integral type required!"); 13016 const unsigned NumTypes = 4; 13017 QualType SignedIntegralTypes[NumTypes] = { 13018 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13019 }; 13020 QualType UnsignedIntegralTypes[NumTypes] = { 13021 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13022 Context.UnsignedLongLongTy 13023 }; 13024 13025 unsigned BitWidth = Context.getTypeSize(T); 13026 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13027 : UnsignedIntegralTypes; 13028 for (unsigned I = 0; I != NumTypes; ++I) 13029 if (Context.getTypeSize(Types[I]) > BitWidth) 13030 return Types[I]; 13031 13032 return QualType(); 13033 } 13034 13035 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13036 EnumConstantDecl *LastEnumConst, 13037 SourceLocation IdLoc, 13038 IdentifierInfo *Id, 13039 Expr *Val) { 13040 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13041 llvm::APSInt EnumVal(IntWidth); 13042 QualType EltTy; 13043 13044 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13045 Val = nullptr; 13046 13047 if (Val) 13048 Val = DefaultLvalueConversion(Val).get(); 13049 13050 if (Val) { 13051 if (Enum->isDependentType() || Val->isTypeDependent()) 13052 EltTy = Context.DependentTy; 13053 else { 13054 SourceLocation ExpLoc; 13055 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13056 !getLangOpts().MSVCCompat) { 13057 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13058 // constant-expression in the enumerator-definition shall be a converted 13059 // constant expression of the underlying type. 13060 EltTy = Enum->getIntegerType(); 13061 ExprResult Converted = 13062 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13063 CCEK_Enumerator); 13064 if (Converted.isInvalid()) 13065 Val = nullptr; 13066 else 13067 Val = Converted.get(); 13068 } else if (!Val->isValueDependent() && 13069 !(Val = VerifyIntegerConstantExpression(Val, 13070 &EnumVal).get())) { 13071 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13072 } else { 13073 if (Enum->isFixed()) { 13074 EltTy = Enum->getIntegerType(); 13075 13076 // In Obj-C and Microsoft mode, require the enumeration value to be 13077 // representable in the underlying type of the enumeration. In C++11, 13078 // we perform a non-narrowing conversion as part of converted constant 13079 // expression checking. 13080 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13081 if (getLangOpts().MSVCCompat) { 13082 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13083 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13084 } else 13085 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13086 } else 13087 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13088 } else if (getLangOpts().CPlusPlus) { 13089 // C++11 [dcl.enum]p5: 13090 // If the underlying type is not fixed, the type of each enumerator 13091 // is the type of its initializing value: 13092 // - If an initializer is specified for an enumerator, the 13093 // initializing value has the same type as the expression. 13094 EltTy = Val->getType(); 13095 } else { 13096 // C99 6.7.2.2p2: 13097 // The expression that defines the value of an enumeration constant 13098 // shall be an integer constant expression that has a value 13099 // representable as an int. 13100 13101 // Complain if the value is not representable in an int. 13102 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13103 Diag(IdLoc, diag::ext_enum_value_not_int) 13104 << EnumVal.toString(10) << Val->getSourceRange() 13105 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13106 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13107 // Force the type of the expression to 'int'. 13108 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13109 } 13110 EltTy = Val->getType(); 13111 } 13112 } 13113 } 13114 } 13115 13116 if (!Val) { 13117 if (Enum->isDependentType()) 13118 EltTy = Context.DependentTy; 13119 else if (!LastEnumConst) { 13120 // C++0x [dcl.enum]p5: 13121 // If the underlying type is not fixed, the type of each enumerator 13122 // is the type of its initializing value: 13123 // - If no initializer is specified for the first enumerator, the 13124 // initializing value has an unspecified integral type. 13125 // 13126 // GCC uses 'int' for its unspecified integral type, as does 13127 // C99 6.7.2.2p3. 13128 if (Enum->isFixed()) { 13129 EltTy = Enum->getIntegerType(); 13130 } 13131 else { 13132 EltTy = Context.IntTy; 13133 } 13134 } else { 13135 // Assign the last value + 1. 13136 EnumVal = LastEnumConst->getInitVal(); 13137 ++EnumVal; 13138 EltTy = LastEnumConst->getType(); 13139 13140 // Check for overflow on increment. 13141 if (EnumVal < LastEnumConst->getInitVal()) { 13142 // C++0x [dcl.enum]p5: 13143 // If the underlying type is not fixed, the type of each enumerator 13144 // is the type of its initializing value: 13145 // 13146 // - Otherwise the type of the initializing value is the same as 13147 // the type of the initializing value of the preceding enumerator 13148 // unless the incremented value is not representable in that type, 13149 // in which case the type is an unspecified integral type 13150 // sufficient to contain the incremented value. If no such type 13151 // exists, the program is ill-formed. 13152 QualType T = getNextLargerIntegralType(Context, EltTy); 13153 if (T.isNull() || Enum->isFixed()) { 13154 // There is no integral type larger enough to represent this 13155 // value. Complain, then allow the value to wrap around. 13156 EnumVal = LastEnumConst->getInitVal(); 13157 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13158 ++EnumVal; 13159 if (Enum->isFixed()) 13160 // When the underlying type is fixed, this is ill-formed. 13161 Diag(IdLoc, diag::err_enumerator_wrapped) 13162 << EnumVal.toString(10) 13163 << EltTy; 13164 else 13165 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13166 << EnumVal.toString(10); 13167 } else { 13168 EltTy = T; 13169 } 13170 13171 // Retrieve the last enumerator's value, extent that type to the 13172 // type that is supposed to be large enough to represent the incremented 13173 // value, then increment. 13174 EnumVal = LastEnumConst->getInitVal(); 13175 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13176 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13177 ++EnumVal; 13178 13179 // If we're not in C++, diagnose the overflow of enumerator values, 13180 // which in C99 means that the enumerator value is not representable in 13181 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13182 // permits enumerator values that are representable in some larger 13183 // integral type. 13184 if (!getLangOpts().CPlusPlus && !T.isNull()) 13185 Diag(IdLoc, diag::warn_enum_value_overflow); 13186 } else if (!getLangOpts().CPlusPlus && 13187 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13188 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13189 Diag(IdLoc, diag::ext_enum_value_not_int) 13190 << EnumVal.toString(10) << 1; 13191 } 13192 } 13193 } 13194 13195 if (!EltTy->isDependentType()) { 13196 // Make the enumerator value match the signedness and size of the 13197 // enumerator's type. 13198 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13199 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13200 } 13201 13202 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13203 Val, EnumVal); 13204 } 13205 13206 13207 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13208 SourceLocation IdLoc, IdentifierInfo *Id, 13209 AttributeList *Attr, 13210 SourceLocation EqualLoc, Expr *Val) { 13211 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13212 EnumConstantDecl *LastEnumConst = 13213 cast_or_null<EnumConstantDecl>(lastEnumConst); 13214 13215 // The scope passed in may not be a decl scope. Zip up the scope tree until 13216 // we find one that is. 13217 S = getNonFieldDeclScope(S); 13218 13219 // Verify that there isn't already something declared with this name in this 13220 // scope. 13221 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13222 ForRedeclaration); 13223 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13224 // Maybe we will complain about the shadowed template parameter. 13225 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13226 // Just pretend that we didn't see the previous declaration. 13227 PrevDecl = nullptr; 13228 } 13229 13230 if (PrevDecl) { 13231 // When in C++, we may get a TagDecl with the same name; in this case the 13232 // enum constant will 'hide' the tag. 13233 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13234 "Received TagDecl when not in C++!"); 13235 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13236 if (isa<EnumConstantDecl>(PrevDecl)) 13237 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13238 else 13239 Diag(IdLoc, diag::err_redefinition) << Id; 13240 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13241 return nullptr; 13242 } 13243 } 13244 13245 // C++ [class.mem]p15: 13246 // If T is the name of a class, then each of the following shall have a name 13247 // different from T: 13248 // - every enumerator of every member of class T that is an unscoped 13249 // enumerated type 13250 if (CXXRecordDecl *Record 13251 = dyn_cast<CXXRecordDecl>( 13252 TheEnumDecl->getDeclContext()->getRedeclContext())) 13253 if (!TheEnumDecl->isScoped() && 13254 Record->getIdentifier() && Record->getIdentifier() == Id) 13255 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13256 13257 EnumConstantDecl *New = 13258 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13259 13260 if (New) { 13261 // Process attributes. 13262 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13263 13264 // Register this decl in the current scope stack. 13265 New->setAccess(TheEnumDecl->getAccess()); 13266 PushOnScopeChains(New, S); 13267 } 13268 13269 ActOnDocumentableDecl(New); 13270 13271 return New; 13272 } 13273 13274 // Returns true when the enum initial expression does not trigger the 13275 // duplicate enum warning. A few common cases are exempted as follows: 13276 // Element2 = Element1 13277 // Element2 = Element1 + 1 13278 // Element2 = Element1 - 1 13279 // Where Element2 and Element1 are from the same enum. 13280 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13281 Expr *InitExpr = ECD->getInitExpr(); 13282 if (!InitExpr) 13283 return true; 13284 InitExpr = InitExpr->IgnoreImpCasts(); 13285 13286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13287 if (!BO->isAdditiveOp()) 13288 return true; 13289 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13290 if (!IL) 13291 return true; 13292 if (IL->getValue() != 1) 13293 return true; 13294 13295 InitExpr = BO->getLHS(); 13296 } 13297 13298 // This checks if the elements are from the same enum. 13299 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13300 if (!DRE) 13301 return true; 13302 13303 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13304 if (!EnumConstant) 13305 return true; 13306 13307 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13308 Enum) 13309 return true; 13310 13311 return false; 13312 } 13313 13314 struct DupKey { 13315 int64_t val; 13316 bool isTombstoneOrEmptyKey; 13317 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13318 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13319 }; 13320 13321 static DupKey GetDupKey(const llvm::APSInt& Val) { 13322 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13323 false); 13324 } 13325 13326 struct DenseMapInfoDupKey { 13327 static DupKey getEmptyKey() { return DupKey(0, true); } 13328 static DupKey getTombstoneKey() { return DupKey(1, true); } 13329 static unsigned getHashValue(const DupKey Key) { 13330 return (unsigned)(Key.val * 37); 13331 } 13332 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13333 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13334 LHS.val == RHS.val; 13335 } 13336 }; 13337 13338 // Emits a warning when an element is implicitly set a value that 13339 // a previous element has already been set to. 13340 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13341 EnumDecl *Enum, 13342 QualType EnumType) { 13343 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13344 return; 13345 // Avoid anonymous enums 13346 if (!Enum->getIdentifier()) 13347 return; 13348 13349 // Only check for small enums. 13350 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13351 return; 13352 13353 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13354 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13355 13356 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13357 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13358 ValueToVectorMap; 13359 13360 DuplicatesVector DupVector; 13361 ValueToVectorMap EnumMap; 13362 13363 // Populate the EnumMap with all values represented by enum constants without 13364 // an initialier. 13365 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13366 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13367 13368 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13369 // this constant. Skip this enum since it may be ill-formed. 13370 if (!ECD) { 13371 return; 13372 } 13373 13374 if (ECD->getInitExpr()) 13375 continue; 13376 13377 DupKey Key = GetDupKey(ECD->getInitVal()); 13378 DeclOrVector &Entry = EnumMap[Key]; 13379 13380 // First time encountering this value. 13381 if (Entry.isNull()) 13382 Entry = ECD; 13383 } 13384 13385 // Create vectors for any values that has duplicates. 13386 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13387 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13388 if (!ValidDuplicateEnum(ECD, Enum)) 13389 continue; 13390 13391 DupKey Key = GetDupKey(ECD->getInitVal()); 13392 13393 DeclOrVector& Entry = EnumMap[Key]; 13394 if (Entry.isNull()) 13395 continue; 13396 13397 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13398 // Ensure constants are different. 13399 if (D == ECD) 13400 continue; 13401 13402 // Create new vector and push values onto it. 13403 ECDVector *Vec = new ECDVector(); 13404 Vec->push_back(D); 13405 Vec->push_back(ECD); 13406 13407 // Update entry to point to the duplicates vector. 13408 Entry = Vec; 13409 13410 // Store the vector somewhere we can consult later for quick emission of 13411 // diagnostics. 13412 DupVector.push_back(Vec); 13413 continue; 13414 } 13415 13416 ECDVector *Vec = Entry.get<ECDVector*>(); 13417 // Make sure constants are not added more than once. 13418 if (*Vec->begin() == ECD) 13419 continue; 13420 13421 Vec->push_back(ECD); 13422 } 13423 13424 // Emit diagnostics. 13425 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13426 DupVectorEnd = DupVector.end(); 13427 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13428 ECDVector *Vec = *DupVectorIter; 13429 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13430 13431 // Emit warning for one enum constant. 13432 ECDVector::iterator I = Vec->begin(); 13433 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13434 << (*I)->getName() << (*I)->getInitVal().toString(10) 13435 << (*I)->getSourceRange(); 13436 ++I; 13437 13438 // Emit one note for each of the remaining enum constants with 13439 // the same value. 13440 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13441 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13442 << (*I)->getName() << (*I)->getInitVal().toString(10) 13443 << (*I)->getSourceRange(); 13444 delete Vec; 13445 } 13446 } 13447 13448 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13449 SourceLocation RBraceLoc, Decl *EnumDeclX, 13450 ArrayRef<Decl *> Elements, 13451 Scope *S, AttributeList *Attr) { 13452 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13453 QualType EnumType = Context.getTypeDeclType(Enum); 13454 13455 if (Attr) 13456 ProcessDeclAttributeList(S, Enum, Attr); 13457 13458 if (Enum->isDependentType()) { 13459 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13460 EnumConstantDecl *ECD = 13461 cast_or_null<EnumConstantDecl>(Elements[i]); 13462 if (!ECD) continue; 13463 13464 ECD->setType(EnumType); 13465 } 13466 13467 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13468 return; 13469 } 13470 13471 // TODO: If the result value doesn't fit in an int, it must be a long or long 13472 // long value. ISO C does not support this, but GCC does as an extension, 13473 // emit a warning. 13474 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13475 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13476 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13477 13478 // Verify that all the values are okay, compute the size of the values, and 13479 // reverse the list. 13480 unsigned NumNegativeBits = 0; 13481 unsigned NumPositiveBits = 0; 13482 13483 // Keep track of whether all elements have type int. 13484 bool AllElementsInt = true; 13485 13486 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13487 EnumConstantDecl *ECD = 13488 cast_or_null<EnumConstantDecl>(Elements[i]); 13489 if (!ECD) continue; // Already issued a diagnostic. 13490 13491 const llvm::APSInt &InitVal = ECD->getInitVal(); 13492 13493 // Keep track of the size of positive and negative values. 13494 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13495 NumPositiveBits = std::max(NumPositiveBits, 13496 (unsigned)InitVal.getActiveBits()); 13497 else 13498 NumNegativeBits = std::max(NumNegativeBits, 13499 (unsigned)InitVal.getMinSignedBits()); 13500 13501 // Keep track of whether every enum element has type int (very commmon). 13502 if (AllElementsInt) 13503 AllElementsInt = ECD->getType() == Context.IntTy; 13504 } 13505 13506 // Figure out the type that should be used for this enum. 13507 QualType BestType; 13508 unsigned BestWidth; 13509 13510 // C++0x N3000 [conv.prom]p3: 13511 // An rvalue of an unscoped enumeration type whose underlying 13512 // type is not fixed can be converted to an rvalue of the first 13513 // of the following types that can represent all the values of 13514 // the enumeration: int, unsigned int, long int, unsigned long 13515 // int, long long int, or unsigned long long int. 13516 // C99 6.4.4.3p2: 13517 // An identifier declared as an enumeration constant has type int. 13518 // The C99 rule is modified by a gcc extension 13519 QualType BestPromotionType; 13520 13521 bool Packed = Enum->hasAttr<PackedAttr>(); 13522 // -fshort-enums is the equivalent to specifying the packed attribute on all 13523 // enum definitions. 13524 if (LangOpts.ShortEnums) 13525 Packed = true; 13526 13527 if (Enum->isFixed()) { 13528 BestType = Enum->getIntegerType(); 13529 if (BestType->isPromotableIntegerType()) 13530 BestPromotionType = Context.getPromotedIntegerType(BestType); 13531 else 13532 BestPromotionType = BestType; 13533 // We don't need to set BestWidth, because BestType is going to be the type 13534 // of the enumerators, but we do anyway because otherwise some compilers 13535 // warn that it might be used uninitialized. 13536 BestWidth = CharWidth; 13537 } 13538 else if (NumNegativeBits) { 13539 // If there is a negative value, figure out the smallest integer type (of 13540 // int/long/longlong) that fits. 13541 // If it's packed, check also if it fits a char or a short. 13542 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13543 BestType = Context.SignedCharTy; 13544 BestWidth = CharWidth; 13545 } else if (Packed && NumNegativeBits <= ShortWidth && 13546 NumPositiveBits < ShortWidth) { 13547 BestType = Context.ShortTy; 13548 BestWidth = ShortWidth; 13549 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13550 BestType = Context.IntTy; 13551 BestWidth = IntWidth; 13552 } else { 13553 BestWidth = Context.getTargetInfo().getLongWidth(); 13554 13555 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13556 BestType = Context.LongTy; 13557 } else { 13558 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13559 13560 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13561 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13562 BestType = Context.LongLongTy; 13563 } 13564 } 13565 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13566 } else { 13567 // If there is no negative value, figure out the smallest type that fits 13568 // all of the enumerator values. 13569 // If it's packed, check also if it fits a char or a short. 13570 if (Packed && NumPositiveBits <= CharWidth) { 13571 BestType = Context.UnsignedCharTy; 13572 BestPromotionType = Context.IntTy; 13573 BestWidth = CharWidth; 13574 } else if (Packed && NumPositiveBits <= ShortWidth) { 13575 BestType = Context.UnsignedShortTy; 13576 BestPromotionType = Context.IntTy; 13577 BestWidth = ShortWidth; 13578 } else if (NumPositiveBits <= IntWidth) { 13579 BestType = Context.UnsignedIntTy; 13580 BestWidth = IntWidth; 13581 BestPromotionType 13582 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13583 ? Context.UnsignedIntTy : Context.IntTy; 13584 } else if (NumPositiveBits <= 13585 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13586 BestType = Context.UnsignedLongTy; 13587 BestPromotionType 13588 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13589 ? Context.UnsignedLongTy : Context.LongTy; 13590 } else { 13591 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13592 assert(NumPositiveBits <= BestWidth && 13593 "How could an initializer get larger than ULL?"); 13594 BestType = Context.UnsignedLongLongTy; 13595 BestPromotionType 13596 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13597 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13598 } 13599 } 13600 13601 // Loop over all of the enumerator constants, changing their types to match 13602 // the type of the enum if needed. 13603 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13604 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13605 if (!ECD) continue; // Already issued a diagnostic. 13606 13607 // Standard C says the enumerators have int type, but we allow, as an 13608 // extension, the enumerators to be larger than int size. If each 13609 // enumerator value fits in an int, type it as an int, otherwise type it the 13610 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13611 // that X has type 'int', not 'unsigned'. 13612 13613 // Determine whether the value fits into an int. 13614 llvm::APSInt InitVal = ECD->getInitVal(); 13615 13616 // If it fits into an integer type, force it. Otherwise force it to match 13617 // the enum decl type. 13618 QualType NewTy; 13619 unsigned NewWidth; 13620 bool NewSign; 13621 if (!getLangOpts().CPlusPlus && 13622 !Enum->isFixed() && 13623 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13624 NewTy = Context.IntTy; 13625 NewWidth = IntWidth; 13626 NewSign = true; 13627 } else if (ECD->getType() == BestType) { 13628 // Already the right type! 13629 if (getLangOpts().CPlusPlus) 13630 // C++ [dcl.enum]p4: Following the closing brace of an 13631 // enum-specifier, each enumerator has the type of its 13632 // enumeration. 13633 ECD->setType(EnumType); 13634 continue; 13635 } else { 13636 NewTy = BestType; 13637 NewWidth = BestWidth; 13638 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13639 } 13640 13641 // Adjust the APSInt value. 13642 InitVal = InitVal.extOrTrunc(NewWidth); 13643 InitVal.setIsSigned(NewSign); 13644 ECD->setInitVal(InitVal); 13645 13646 // Adjust the Expr initializer and type. 13647 if (ECD->getInitExpr() && 13648 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13649 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13650 CK_IntegralCast, 13651 ECD->getInitExpr(), 13652 /*base paths*/ nullptr, 13653 VK_RValue)); 13654 if (getLangOpts().CPlusPlus) 13655 // C++ [dcl.enum]p4: Following the closing brace of an 13656 // enum-specifier, each enumerator has the type of its 13657 // enumeration. 13658 ECD->setType(EnumType); 13659 else 13660 ECD->setType(NewTy); 13661 } 13662 13663 Enum->completeDefinition(BestType, BestPromotionType, 13664 NumPositiveBits, NumNegativeBits); 13665 13666 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13667 13668 // Now that the enum type is defined, ensure it's not been underaligned. 13669 if (Enum->hasAttrs()) 13670 CheckAlignasUnderalignment(Enum); 13671 } 13672 13673 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13674 SourceLocation StartLoc, 13675 SourceLocation EndLoc) { 13676 StringLiteral *AsmString = cast<StringLiteral>(expr); 13677 13678 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13679 AsmString, StartLoc, 13680 EndLoc); 13681 CurContext->addDecl(New); 13682 return New; 13683 } 13684 13685 static void checkModuleImportContext(Sema &S, Module *M, 13686 SourceLocation ImportLoc, 13687 DeclContext *DC) { 13688 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13689 switch (LSD->getLanguage()) { 13690 case LinkageSpecDecl::lang_c: 13691 if (!M->IsExternC) { 13692 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13693 << M->getFullModuleName(); 13694 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13695 return; 13696 } 13697 break; 13698 case LinkageSpecDecl::lang_cxx: 13699 break; 13700 } 13701 DC = LSD->getParent(); 13702 } 13703 13704 while (isa<LinkageSpecDecl>(DC)) 13705 DC = DC->getParent(); 13706 if (!isa<TranslationUnitDecl>(DC)) { 13707 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13708 << M->getFullModuleName() << DC; 13709 S.Diag(cast<Decl>(DC)->getLocStart(), 13710 diag::note_module_import_not_at_top_level) 13711 << DC; 13712 } 13713 } 13714 13715 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13716 SourceLocation ImportLoc, 13717 ModuleIdPath Path) { 13718 Module *Mod = 13719 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13720 /*IsIncludeDirective=*/false); 13721 if (!Mod) 13722 return true; 13723 13724 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13725 13726 // FIXME: we should support importing a submodule within a different submodule 13727 // of the same top-level module. Until we do, make it an error rather than 13728 // silently ignoring the import. 13729 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13730 Diag(ImportLoc, diag::err_module_self_import) 13731 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13732 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13733 Diag(ImportLoc, diag::err_module_import_in_implementation) 13734 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13735 13736 SmallVector<SourceLocation, 2> IdentifierLocs; 13737 Module *ModCheck = Mod; 13738 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13739 // If we've run out of module parents, just drop the remaining identifiers. 13740 // We need the length to be consistent. 13741 if (!ModCheck) 13742 break; 13743 ModCheck = ModCheck->Parent; 13744 13745 IdentifierLocs.push_back(Path[I].second); 13746 } 13747 13748 ImportDecl *Import = ImportDecl::Create(Context, 13749 Context.getTranslationUnitDecl(), 13750 AtLoc.isValid()? AtLoc : ImportLoc, 13751 Mod, IdentifierLocs); 13752 Context.getTranslationUnitDecl()->addDecl(Import); 13753 return Import; 13754 } 13755 13756 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13757 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13758 13759 // FIXME: Should we synthesize an ImportDecl here? 13760 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13761 /*Complain=*/true); 13762 } 13763 13764 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13765 Module *Mod) { 13766 // Bail if we're not allowed to implicitly import a module here. 13767 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13768 return; 13769 13770 // Create the implicit import declaration. 13771 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13772 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13773 Loc, Mod, Loc); 13774 TU->addDecl(ImportD); 13775 Consumer.HandleImplicitImportDecl(ImportD); 13776 13777 // Make the module visible. 13778 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13779 /*Complain=*/false); 13780 } 13781 13782 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13783 IdentifierInfo* AliasName, 13784 SourceLocation PragmaLoc, 13785 SourceLocation NameLoc, 13786 SourceLocation AliasNameLoc) { 13787 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13788 LookupOrdinaryName); 13789 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13790 AliasName->getName(), 0); 13791 13792 if (PrevDecl) 13793 PrevDecl->addAttr(Attr); 13794 else 13795 (void)ExtnameUndeclaredIdentifiers.insert( 13796 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13797 } 13798 13799 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13800 SourceLocation PragmaLoc, 13801 SourceLocation NameLoc) { 13802 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13803 13804 if (PrevDecl) { 13805 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13806 } else { 13807 (void)WeakUndeclaredIdentifiers.insert( 13808 std::pair<IdentifierInfo*,WeakInfo> 13809 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 13810 } 13811 } 13812 13813 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13814 IdentifierInfo* AliasName, 13815 SourceLocation PragmaLoc, 13816 SourceLocation NameLoc, 13817 SourceLocation AliasNameLoc) { 13818 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13819 LookupOrdinaryName); 13820 WeakInfo W = WeakInfo(Name, NameLoc); 13821 13822 if (PrevDecl) { 13823 if (!PrevDecl->hasAttr<AliasAttr>()) 13824 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13825 DeclApplyPragmaWeak(TUScope, ND, W); 13826 } else { 13827 (void)WeakUndeclaredIdentifiers.insert( 13828 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13829 } 13830 } 13831 13832 Decl *Sema::getObjCDeclContext() const { 13833 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13834 } 13835 13836 AvailabilityResult Sema::getCurContextAvailability() const { 13837 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13838 // If we are within an Objective-C method, we should consult 13839 // both the availability of the method as well as the 13840 // enclosing class. If the class is (say) deprecated, 13841 // the entire method is considered deprecated from the 13842 // purpose of checking if the current context is deprecated. 13843 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13844 AvailabilityResult R = MD->getAvailability(); 13845 if (R != AR_Available) 13846 return R; 13847 D = MD->getClassInterface(); 13848 } 13849 // If we are within an Objective-c @implementation, it 13850 // gets the same availability context as the @interface. 13851 else if (const ObjCImplementationDecl *ID = 13852 dyn_cast<ObjCImplementationDecl>(D)) { 13853 D = ID->getClassInterface(); 13854 } 13855 // Recover from user error. 13856 return D ? D->getAvailability() : AR_Available; 13857 } 13858