1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 default: 152 break; 153 } 154 155 return false; 156 } 157 158 namespace { 159 enum class UnqualifiedTypeNameLookupResult { 160 NotFound, 161 FoundNonType, 162 FoundType 163 }; 164 } // end anonymous namespace 165 166 /// \brief Tries to perform unqualified lookup of the type decls in bases for 167 /// dependent class. 168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 169 /// type decl, \a FoundType if only type decls are found. 170 static UnqualifiedTypeNameLookupResult 171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 172 SourceLocation NameLoc, 173 const CXXRecordDecl *RD) { 174 if (!RD->hasDefinition()) 175 return UnqualifiedTypeNameLookupResult::NotFound; 176 // Look for type decls in base classes. 177 UnqualifiedTypeNameLookupResult FoundTypeDecl = 178 UnqualifiedTypeNameLookupResult::NotFound; 179 for (const auto &Base : RD->bases()) { 180 const CXXRecordDecl *BaseRD = nullptr; 181 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 182 BaseRD = BaseTT->getAsCXXRecordDecl(); 183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 184 // Look for type decls in dependent base classes that have known primary 185 // templates. 186 if (!TST || !TST->isDependentType()) 187 continue; 188 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 189 if (!TD) 190 continue; 191 if (auto *BasePrimaryTemplate = 192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 194 BaseRD = BasePrimaryTemplate; 195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 196 if (const ClassTemplatePartialSpecializationDecl *PS = 197 CTD->findPartialSpecialization(Base.getType())) 198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 199 BaseRD = PS; 200 } 201 } 202 } 203 if (BaseRD) { 204 for (NamedDecl *ND : BaseRD->lookup(&II)) { 205 if (!isa<TypeDecl>(ND)) 206 return UnqualifiedTypeNameLookupResult::FoundNonType; 207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 208 } 209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 211 case UnqualifiedTypeNameLookupResult::FoundNonType: 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 case UnqualifiedTypeNameLookupResult::FoundType: 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 break; 216 case UnqualifiedTypeNameLookupResult::NotFound: 217 break; 218 } 219 } 220 } 221 } 222 223 return FoundTypeDecl; 224 } 225 226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 227 const IdentifierInfo &II, 228 SourceLocation NameLoc) { 229 // Lookup in the parent class template context, if any. 230 const CXXRecordDecl *RD = nullptr; 231 UnqualifiedTypeNameLookupResult FoundTypeDecl = 232 UnqualifiedTypeNameLookupResult::NotFound; 233 for (DeclContext *DC = S.CurContext; 234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 235 DC = DC->getParent()) { 236 // Look for type decls in dependent base classes that have known primary 237 // templates. 238 RD = dyn_cast<CXXRecordDecl>(DC); 239 if (RD && RD->getDescribedClassTemplate()) 240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 241 } 242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 243 return nullptr; 244 245 // We found some types in dependent base classes. Recover as if the user 246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 247 // lookup during template instantiation. 248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 249 250 ASTContext &Context = S.Context; 251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 252 cast<Type>(Context.getRecordType(RD))); 253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 254 255 CXXScopeSpec SS; 256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 257 258 TypeLocBuilder Builder; 259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 260 DepTL.setNameLoc(NameLoc); 261 DepTL.setElaboratedKeywordLoc(SourceLocation()); 262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 264 } 265 266 /// \brief If the identifier refers to a type name within this scope, 267 /// return the declaration of that type. 268 /// 269 /// This routine performs ordinary name lookup of the identifier II 270 /// within the given scope, with optional C++ scope specifier SS, to 271 /// determine whether the name refers to a type. If so, returns an 272 /// opaque pointer (actually a QualType) corresponding to that 273 /// type. Otherwise, returns NULL. 274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 275 Scope *S, CXXScopeSpec *SS, 276 bool isClassName, bool HasTrailingDot, 277 ParsedType ObjectTypePtr, 278 bool IsCtorOrDtorName, 279 bool WantNontrivialTypeSourceInfo, 280 bool IsClassTemplateDeductionContext, 281 IdentifierInfo **CorrectedII) { 282 // FIXME: Consider allowing this outside C++1z mode as an extension. 283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 284 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 285 !isClassName && !HasTrailingDot; 286 287 // Determine where we will perform name lookup. 288 DeclContext *LookupCtx = nullptr; 289 if (ObjectTypePtr) { 290 QualType ObjectType = ObjectTypePtr.get(); 291 if (ObjectType->isRecordType()) 292 LookupCtx = computeDeclContext(ObjectType); 293 } else if (SS && SS->isNotEmpty()) { 294 LookupCtx = computeDeclContext(*SS, false); 295 296 if (!LookupCtx) { 297 if (isDependentScopeSpecifier(*SS)) { 298 // C++ [temp.res]p3: 299 // A qualified-id that refers to a type and in which the 300 // nested-name-specifier depends on a template-parameter (14.6.2) 301 // shall be prefixed by the keyword typename to indicate that the 302 // qualified-id denotes a type, forming an 303 // elaborated-type-specifier (7.1.5.3). 304 // 305 // We therefore do not perform any name lookup if the result would 306 // refer to a member of an unknown specialization. 307 if (!isClassName && !IsCtorOrDtorName) 308 return nullptr; 309 310 // We know from the grammar that this name refers to a type, 311 // so build a dependent node to describe the type. 312 if (WantNontrivialTypeSourceInfo) 313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 314 315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 317 II, NameLoc); 318 return ParsedType::make(T); 319 } 320 321 return nullptr; 322 } 323 324 if (!LookupCtx->isDependentContext() && 325 RequireCompleteDeclContext(*SS, LookupCtx)) 326 return nullptr; 327 } 328 329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 330 // lookup for class-names. 331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 332 LookupOrdinaryName; 333 LookupResult Result(*this, &II, NameLoc, Kind); 334 if (LookupCtx) { 335 // Perform "qualified" name lookup into the declaration context we 336 // computed, which is either the type of the base of a member access 337 // expression or the declaration context associated with a prior 338 // nested-name-specifier. 339 LookupQualifiedName(Result, LookupCtx); 340 341 if (ObjectTypePtr && Result.empty()) { 342 // C++ [basic.lookup.classref]p3: 343 // If the unqualified-id is ~type-name, the type-name is looked up 344 // in the context of the entire postfix-expression. If the type T of 345 // the object expression is of a class type C, the type-name is also 346 // looked up in the scope of class C. At least one of the lookups shall 347 // find a name that refers to (possibly cv-qualified) T. 348 LookupName(Result, S); 349 } 350 } else { 351 // Perform unqualified name lookup. 352 LookupName(Result, S); 353 354 // For unqualified lookup in a class template in MSVC mode, look into 355 // dependent base classes where the primary class template is known. 356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 357 if (ParsedType TypeInBase = 358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 359 return TypeInBase; 360 } 361 } 362 363 NamedDecl *IIDecl = nullptr; 364 switch (Result.getResultKind()) { 365 case LookupResult::NotFound: 366 case LookupResult::NotFoundInCurrentInstantiation: 367 if (CorrectedII) { 368 TypoCorrection Correction = 369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 370 llvm::make_unique<TypeNameValidatorCCC>( 371 true, isClassName, AllowDeducedTemplate), 372 CTK_ErrorRecovery); 373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 374 TemplateTy Template; 375 bool MemberOfUnknownSpecialization; 376 UnqualifiedId TemplateName; 377 TemplateName.setIdentifier(NewII, NameLoc); 378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 379 CXXScopeSpec NewSS, *NewSSPtr = SS; 380 if (SS && NNS) { 381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 382 NewSSPtr = &NewSS; 383 } 384 if (Correction && (NNS || NewII != &II) && 385 // Ignore a correction to a template type as the to-be-corrected 386 // identifier is not a template (typo correction for template names 387 // is handled elsewhere). 388 !(getLangOpts().CPlusPlus && NewSSPtr && 389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 390 Template, MemberOfUnknownSpecialization))) { 391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 392 isClassName, HasTrailingDot, ObjectTypePtr, 393 IsCtorOrDtorName, 394 WantNontrivialTypeSourceInfo, 395 IsClassTemplateDeductionContext); 396 if (Ty) { 397 diagnoseTypo(Correction, 398 PDiag(diag::err_unknown_type_or_class_name_suggest) 399 << Result.getLookupName() << isClassName); 400 if (SS && NNS) 401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 402 *CorrectedII = NewII; 403 return Ty; 404 } 405 } 406 } 407 // If typo correction failed or was not performed, fall through 408 LLVM_FALLTHROUGH; 409 case LookupResult::FoundOverloaded: 410 case LookupResult::FoundUnresolvedValue: 411 Result.suppressDiagnostics(); 412 return nullptr; 413 414 case LookupResult::Ambiguous: 415 // Recover from type-hiding ambiguities by hiding the type. We'll 416 // do the lookup again when looking for an object, and we can 417 // diagnose the error then. If we don't do this, then the error 418 // about hiding the type will be immediately followed by an error 419 // that only makes sense if the identifier was treated like a type. 420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 421 Result.suppressDiagnostics(); 422 return nullptr; 423 } 424 425 // Look to see if we have a type anywhere in the list of results. 426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 427 Res != ResEnd; ++Res) { 428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 430 if (!IIDecl || 431 (*Res)->getLocation().getRawEncoding() < 432 IIDecl->getLocation().getRawEncoding()) 433 IIDecl = *Res; 434 } 435 } 436 437 if (!IIDecl) { 438 // None of the entities we found is a type, so there is no way 439 // to even assume that the result is a type. In this case, don't 440 // complain about the ambiguity. The parser will either try to 441 // perform this lookup again (e.g., as an object name), which 442 // will produce the ambiguity, or will complain that it expected 443 // a type name. 444 Result.suppressDiagnostics(); 445 return nullptr; 446 } 447 448 // We found a type within the ambiguous lookup; diagnose the 449 // ambiguity and then return that type. This might be the right 450 // answer, or it might not be, but it suppresses any attempt to 451 // perform the name lookup again. 452 break; 453 454 case LookupResult::Found: 455 IIDecl = Result.getFoundDecl(); 456 break; 457 } 458 459 assert(IIDecl && "Didn't find decl"); 460 461 QualType T; 462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 463 // C++ [class.qual]p2: A lookup that would find the injected-class-name 464 // instead names the constructors of the class, except when naming a class. 465 // This is ill-formed when we're not actually forming a ctor or dtor name. 466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 469 FoundRD->isInjectedClassName() && 470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 472 << &II << /*Type*/1; 473 474 DiagnoseUseOfDecl(IIDecl, NameLoc); 475 476 T = Context.getTypeDeclType(TD); 477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 479 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 480 if (!HasTrailingDot) 481 T = Context.getObjCInterfaceType(IDecl); 482 } else if (AllowDeducedTemplate) { 483 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 485 QualType(), false); 486 } 487 488 if (T.isNull()) { 489 // If it's not plausibly a type, suppress diagnostics. 490 Result.suppressDiagnostics(); 491 return nullptr; 492 } 493 494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 495 // constructor or destructor name (in such a case, the scope specifier 496 // will be attached to the enclosing Expr or Decl node). 497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 498 !isa<ObjCInterfaceDecl>(IIDecl)) { 499 if (WantNontrivialTypeSourceInfo) { 500 // Construct a type with type-source information. 501 TypeLocBuilder Builder; 502 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 503 504 T = getElaboratedType(ETK_None, *SS, T); 505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 506 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 509 } else { 510 T = getElaboratedType(ETK_None, *SS, T); 511 } 512 } 513 514 return ParsedType::make(T); 515 } 516 517 // Builds a fake NNS for the given decl context. 518 static NestedNameSpecifier * 519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 520 for (;; DC = DC->getLookupParent()) { 521 DC = DC->getPrimaryContext(); 522 auto *ND = dyn_cast<NamespaceDecl>(DC); 523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 524 return NestedNameSpecifier::Create(Context, nullptr, ND); 525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 527 RD->getTypeForDecl()); 528 else if (isa<TranslationUnitDecl>(DC)) 529 return NestedNameSpecifier::GlobalSpecifier(Context); 530 } 531 llvm_unreachable("something isn't in TU scope?"); 532 } 533 534 /// Find the parent class with dependent bases of the innermost enclosing method 535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 536 /// up allowing unqualified dependent type names at class-level, which MSVC 537 /// correctly rejects. 538 static const CXXRecordDecl * 539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 541 DC = DC->getPrimaryContext(); 542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 543 if (MD->getParent()->hasAnyDependentBases()) 544 return MD->getParent(); 545 } 546 return nullptr; 547 } 548 549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 550 SourceLocation NameLoc, 551 bool IsTemplateTypeArg) { 552 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 553 554 NestedNameSpecifier *NNS = nullptr; 555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 556 // If we weren't able to parse a default template argument, delay lookup 557 // until instantiation time by making a non-dependent DependentTypeName. We 558 // pretend we saw a NestedNameSpecifier referring to the current scope, and 559 // lookup is retried. 560 // FIXME: This hurts our diagnostic quality, since we get errors like "no 561 // type named 'Foo' in 'current_namespace'" when the user didn't write any 562 // name specifiers. 563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 565 } else if (const CXXRecordDecl *RD = 566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 567 // Build a DependentNameType that will perform lookup into RD at 568 // instantiation time. 569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 570 RD->getTypeForDecl()); 571 572 // Diagnose that this identifier was undeclared, and retry the lookup during 573 // template instantiation. 574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 575 << RD; 576 } else { 577 // This is not a situation that we should recover from. 578 return ParsedType(); 579 } 580 581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 582 583 // Build type location information. We synthesized the qualifier, so we have 584 // to build a fake NestedNameSpecifierLoc. 585 NestedNameSpecifierLocBuilder NNSLocBuilder; 586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 588 589 TypeLocBuilder Builder; 590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 591 DepTL.setNameLoc(NameLoc); 592 DepTL.setElaboratedKeywordLoc(SourceLocation()); 593 DepTL.setQualifierLoc(QualifierLoc); 594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 595 } 596 597 /// isTagName() - This method is called *for error recovery purposes only* 598 /// to determine if the specified name is a valid tag name ("struct foo"). If 599 /// so, this returns the TST for the tag corresponding to it (TST_enum, 600 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 601 /// cases in C where the user forgot to specify the tag. 602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 603 // Do a tag name lookup in this scope. 604 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 605 LookupName(R, S, false); 606 R.suppressDiagnostics(); 607 if (R.getResultKind() == LookupResult::Found) 608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 609 switch (TD->getTagKind()) { 610 case TTK_Struct: return DeclSpec::TST_struct; 611 case TTK_Interface: return DeclSpec::TST_interface; 612 case TTK_Union: return DeclSpec::TST_union; 613 case TTK_Class: return DeclSpec::TST_class; 614 case TTK_Enum: return DeclSpec::TST_enum; 615 } 616 } 617 618 return DeclSpec::TST_unspecified; 619 } 620 621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 623 /// then downgrade the missing typename error to a warning. 624 /// This is needed for MSVC compatibility; Example: 625 /// @code 626 /// template<class T> class A { 627 /// public: 628 /// typedef int TYPE; 629 /// }; 630 /// template<class T> class B : public A<T> { 631 /// public: 632 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 633 /// }; 634 /// @endcode 635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 636 if (CurContext->isRecord()) { 637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 638 return true; 639 640 const Type *Ty = SS->getScopeRep()->getAsType(); 641 642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 643 for (const auto &Base : RD->bases()) 644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 645 return true; 646 return S->isFunctionPrototypeScope(); 647 } 648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 649 } 650 651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 652 SourceLocation IILoc, 653 Scope *S, 654 CXXScopeSpec *SS, 655 ParsedType &SuggestedType, 656 bool IsTemplateName) { 657 // Don't report typename errors for editor placeholders. 658 if (II->isEditorPlaceholder()) 659 return; 660 // We don't have anything to suggest (yet). 661 SuggestedType = nullptr; 662 663 // There may have been a typo in the name of the type. Look up typo 664 // results, in case we have something that we can suggest. 665 if (TypoCorrection Corrected = 666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 667 llvm::make_unique<TypeNameValidatorCCC>( 668 false, false, IsTemplateName, !IsTemplateName), 669 CTK_ErrorRecovery)) { 670 // FIXME: Support error recovery for the template-name case. 671 bool CanRecover = !IsTemplateName; 672 if (Corrected.isKeyword()) { 673 // We corrected to a keyword. 674 diagnoseTypo(Corrected, 675 PDiag(IsTemplateName ? diag::err_no_template_suggest 676 : diag::err_unknown_typename_suggest) 677 << II); 678 II = Corrected.getCorrectionAsIdentifierInfo(); 679 } else { 680 // We found a similarly-named type or interface; suggest that. 681 if (!SS || !SS->isSet()) { 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II, CanRecover); 686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 687 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 689 II->getName().equals(CorrectedStr); 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName 692 ? diag::err_no_member_template_suggest 693 : diag::err_unknown_nested_typename_suggest) 694 << II << DC << DroppedSpecifier << SS->getRange(), 695 CanRecover); 696 } else { 697 llvm_unreachable("could not have corrected a typo here"); 698 } 699 700 if (!CanRecover) 701 return; 702 703 CXXScopeSpec tmpSS; 704 if (Corrected.getCorrectionSpecifier()) 705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 706 SourceRange(IILoc)); 707 // FIXME: Support class template argument deduction here. 708 SuggestedType = 709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 711 /*IsCtorOrDtorName=*/false, 712 /*NonTrivialTypeSourceInfo=*/true); 713 } 714 return; 715 } 716 717 if (getLangOpts().CPlusPlus && !IsTemplateName) { 718 // See if II is a class template that the user forgot to pass arguments to. 719 UnqualifiedId Name; 720 Name.setIdentifier(II, IILoc); 721 CXXScopeSpec EmptySS; 722 TemplateTy TemplateResult; 723 bool MemberOfUnknownSpecialization; 724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 725 Name, nullptr, true, TemplateResult, 726 MemberOfUnknownSpecialization) == TNK_Type_template) { 727 TemplateName TplName = TemplateResult.get(); 728 Diag(IILoc, diag::err_template_missing_args) 729 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 730 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 731 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 732 << TplDecl->getTemplateParameters()->getSourceRange(); 733 } 734 return; 735 } 736 } 737 738 // FIXME: Should we move the logic that tries to recover from a missing tag 739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 740 741 if (!SS || (!SS->isSet() && !SS->isInvalid())) 742 Diag(IILoc, IsTemplateName ? diag::err_no_template 743 : diag::err_unknown_typename) 744 << II; 745 else if (DeclContext *DC = computeDeclContext(*SS, false)) 746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 747 : diag::err_typename_nested_not_found) 748 << II << DC << SS->getRange(); 749 else if (isDependentScopeSpecifier(*SS)) { 750 unsigned DiagID = diag::err_typename_missing; 751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 752 DiagID = diag::ext_typename_missing; 753 754 Diag(SS->getRange().getBegin(), DiagID) 755 << SS->getScopeRep() << II->getName() 756 << SourceRange(SS->getRange().getBegin(), IILoc) 757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 758 SuggestedType = ActOnTypenameType(S, SourceLocation(), 759 *SS, *II, IILoc).get(); 760 } else { 761 assert(SS && SS->isInvalid() && 762 "Invalid scope specifier has already been diagnosed"); 763 } 764 } 765 766 /// \brief Determine whether the given result set contains either a type name 767 /// or 768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 770 NextToken.is(tok::less); 771 772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 774 return true; 775 776 if (CheckTemplate && isa<TemplateDecl>(*I)) 777 return true; 778 } 779 780 return false; 781 } 782 783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 784 Scope *S, CXXScopeSpec &SS, 785 IdentifierInfo *&Name, 786 SourceLocation NameLoc) { 787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 788 SemaRef.LookupParsedName(R, S, &SS); 789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 790 StringRef FixItTagName; 791 switch (Tag->getTagKind()) { 792 case TTK_Class: 793 FixItTagName = "class "; 794 break; 795 796 case TTK_Enum: 797 FixItTagName = "enum "; 798 break; 799 800 case TTK_Struct: 801 FixItTagName = "struct "; 802 break; 803 804 case TTK_Interface: 805 FixItTagName = "__interface "; 806 break; 807 808 case TTK_Union: 809 FixItTagName = "union "; 810 break; 811 } 812 813 StringRef TagName = FixItTagName.drop_back(); 814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 816 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 817 818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 819 I != IEnd; ++I) 820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 821 << Name << TagName; 822 823 // Replace lookup results with just the tag decl. 824 Result.clear(Sema::LookupTagName); 825 SemaRef.LookupParsedName(Result, S, &SS); 826 return true; 827 } 828 829 return false; 830 } 831 832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 834 QualType T, SourceLocation NameLoc) { 835 ASTContext &Context = S.Context; 836 837 TypeLocBuilder Builder; 838 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 839 840 T = S.getElaboratedType(ETK_None, SS, T); 841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 842 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 845 } 846 847 Sema::NameClassification 848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 849 SourceLocation NameLoc, const Token &NextToken, 850 bool IsAddressOfOperand, 851 std::unique_ptr<CorrectionCandidateCallback> CCC) { 852 DeclarationNameInfo NameInfo(Name, NameLoc); 853 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 854 855 if (NextToken.is(tok::coloncolon)) { 856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 858 } else if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 // For unqualified lookup in a class template in MSVC mode, look into 871 // dependent base classes where the primary class template is known. 872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 873 if (ParsedType TypeInBase = 874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 875 return TypeInBase; 876 } 877 878 // Perform lookup for Objective-C instance variables (including automatically 879 // synthesized instance variables), if we're in an Objective-C method. 880 // FIXME: This lookup really, really needs to be folded in to the normal 881 // unqualified lookup mechanism. 882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 883 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 884 if (E.get() || E.isInvalid()) 885 return E; 886 } 887 888 bool SecondTry = false; 889 bool IsFilteredTemplateName = false; 890 891 Corrected: 892 switch (Result.getResultKind()) { 893 case LookupResult::NotFound: 894 // If an unqualified-id is followed by a '(', then we have a function 895 // call. 896 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 897 // In C++, this is an ADL-only call. 898 // FIXME: Reference? 899 if (getLangOpts().CPlusPlus) 900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 901 902 // C90 6.3.2.2: 903 // If the expression that precedes the parenthesized argument list in a 904 // function call consists solely of an identifier, and if no 905 // declaration is visible for this identifier, the identifier is 906 // implicitly declared exactly as if, in the innermost block containing 907 // the function call, the declaration 908 // 909 // extern int identifier (); 910 // 911 // appeared. 912 // 913 // We also allow this in C99 as an extension. 914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 915 Result.addDecl(D); 916 Result.resolveKind(); 917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 918 } 919 } 920 921 // In C, we first see whether there is a tag type by the same name, in 922 // which case it's likely that the user just forgot to write "enum", 923 // "struct", or "union". 924 if (!getLangOpts().CPlusPlus && !SecondTry && 925 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 926 break; 927 } 928 929 // Perform typo correction to determine if there is another name that is 930 // close to this name. 931 if (!SecondTry && CCC) { 932 SecondTry = true; 933 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 934 Result.getLookupKind(), S, 935 &SS, std::move(CCC), 936 CTK_ErrorRecovery)) { 937 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 938 unsigned QualifiedDiag = diag::err_no_member_suggest; 939 940 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 941 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 942 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 943 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 944 UnqualifiedDiag = diag::err_no_template_suggest; 945 QualifiedDiag = diag::err_no_member_template_suggest; 946 } else if (UnderlyingFirstDecl && 947 (isa<TypeDecl>(UnderlyingFirstDecl) || 948 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 949 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 950 UnqualifiedDiag = diag::err_unknown_typename_suggest; 951 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 952 } 953 954 if (SS.isEmpty()) { 955 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 956 } else {// FIXME: is this even reachable? Test it. 957 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 958 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 959 Name->getName().equals(CorrectedStr); 960 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 961 << Name << computeDeclContext(SS, false) 962 << DroppedSpecifier << SS.getRange()); 963 } 964 965 // Update the name, so that the caller has the new name. 966 Name = Corrected.getCorrectionAsIdentifierInfo(); 967 968 // Typo correction corrected to a keyword. 969 if (Corrected.isKeyword()) 970 return Name; 971 972 // Also update the LookupResult... 973 // FIXME: This should probably go away at some point 974 Result.clear(); 975 Result.setLookupName(Corrected.getCorrection()); 976 if (FirstDecl) 977 Result.addDecl(FirstDecl); 978 979 // If we found an Objective-C instance variable, let 980 // LookupInObjCMethod build the appropriate expression to 981 // reference the ivar. 982 // FIXME: This is a gross hack. 983 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 984 Result.clear(); 985 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 986 return E; 987 } 988 989 goto Corrected; 990 } 991 } 992 993 // We failed to correct; just fall through and let the parser deal with it. 994 Result.suppressDiagnostics(); 995 return NameClassification::Unknown(); 996 997 case LookupResult::NotFoundInCurrentInstantiation: { 998 // We performed name lookup into the current instantiation, and there were 999 // dependent bases, so we treat this result the same way as any other 1000 // dependent nested-name-specifier. 1001 1002 // C++ [temp.res]p2: 1003 // A name used in a template declaration or definition and that is 1004 // dependent on a template-parameter is assumed not to name a type 1005 // unless the applicable name lookup finds a type name or the name is 1006 // qualified by the keyword typename. 1007 // 1008 // FIXME: If the next token is '<', we might want to ask the parser to 1009 // perform some heroics to see if we actually have a 1010 // template-argument-list, which would indicate a missing 'template' 1011 // keyword here. 1012 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1013 NameInfo, IsAddressOfOperand, 1014 /*TemplateArgs=*/nullptr); 1015 } 1016 1017 case LookupResult::Found: 1018 case LookupResult::FoundOverloaded: 1019 case LookupResult::FoundUnresolvedValue: 1020 break; 1021 1022 case LookupResult::Ambiguous: 1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1024 hasAnyAcceptableTemplateNames(Result)) { 1025 // C++ [temp.local]p3: 1026 // A lookup that finds an injected-class-name (10.2) can result in an 1027 // ambiguity in certain cases (for example, if it is found in more than 1028 // one base class). If all of the injected-class-names that are found 1029 // refer to specializations of the same class template, and if the name 1030 // is followed by a template-argument-list, the reference refers to the 1031 // class template itself and not a specialization thereof, and is not 1032 // ambiguous. 1033 // 1034 // This filtering can make an ambiguous result into an unambiguous one, 1035 // so try again after filtering out template names. 1036 FilterAcceptableTemplateNames(Result); 1037 if (!Result.isAmbiguous()) { 1038 IsFilteredTemplateName = true; 1039 break; 1040 } 1041 } 1042 1043 // Diagnose the ambiguity and return an error. 1044 return NameClassification::Error(); 1045 } 1046 1047 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1048 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1049 // C++ [temp.names]p3: 1050 // After name lookup (3.4) finds that a name is a template-name or that 1051 // an operator-function-id or a literal- operator-id refers to a set of 1052 // overloaded functions any member of which is a function template if 1053 // this is followed by a <, the < is always taken as the delimiter of a 1054 // template-argument-list and never as the less-than operator. 1055 if (!IsFilteredTemplateName) 1056 FilterAcceptableTemplateNames(Result); 1057 1058 if (!Result.empty()) { 1059 bool IsFunctionTemplate; 1060 bool IsVarTemplate; 1061 TemplateName Template; 1062 if (Result.end() - Result.begin() > 1) { 1063 IsFunctionTemplate = true; 1064 Template = Context.getOverloadedTemplateName(Result.begin(), 1065 Result.end()); 1066 } else { 1067 TemplateDecl *TD 1068 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1069 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1070 IsVarTemplate = isa<VarTemplateDecl>(TD); 1071 1072 if (SS.isSet() && !SS.isInvalid()) 1073 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1074 /*TemplateKeyword=*/false, 1075 TD); 1076 else 1077 Template = TemplateName(TD); 1078 } 1079 1080 if (IsFunctionTemplate) { 1081 // Function templates always go through overload resolution, at which 1082 // point we'll perform the various checks (e.g., accessibility) we need 1083 // to based on which function we selected. 1084 Result.suppressDiagnostics(); 1085 1086 return NameClassification::FunctionTemplate(Template); 1087 } 1088 1089 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1090 : NameClassification::TypeTemplate(Template); 1091 } 1092 } 1093 1094 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1095 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1096 DiagnoseUseOfDecl(Type, NameLoc); 1097 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1098 QualType T = Context.getTypeDeclType(Type); 1099 if (SS.isNotEmpty()) 1100 return buildNestedType(*this, SS, T, NameLoc); 1101 return ParsedType::make(T); 1102 } 1103 1104 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1105 if (!Class) { 1106 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1107 if (ObjCCompatibleAliasDecl *Alias = 1108 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1109 Class = Alias->getClassInterface(); 1110 } 1111 1112 if (Class) { 1113 DiagnoseUseOfDecl(Class, NameLoc); 1114 1115 if (NextToken.is(tok::period)) { 1116 // Interface. <something> is parsed as a property reference expression. 1117 // Just return "unknown" as a fall-through for now. 1118 Result.suppressDiagnostics(); 1119 return NameClassification::Unknown(); 1120 } 1121 1122 QualType T = Context.getObjCInterfaceType(Class); 1123 return ParsedType::make(T); 1124 } 1125 1126 // We can have a type template here if we're classifying a template argument. 1127 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1128 !isa<VarTemplateDecl>(FirstDecl)) 1129 return NameClassification::TypeTemplate( 1130 TemplateName(cast<TemplateDecl>(FirstDecl))); 1131 1132 // Check for a tag type hidden by a non-type decl in a few cases where it 1133 // seems likely a type is wanted instead of the non-type that was found. 1134 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1135 if ((NextToken.is(tok::identifier) || 1136 (NextIsOp && 1137 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1138 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1139 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1140 DiagnoseUseOfDecl(Type, NameLoc); 1141 QualType T = Context.getTypeDeclType(Type); 1142 if (SS.isNotEmpty()) 1143 return buildNestedType(*this, SS, T, NameLoc); 1144 return ParsedType::make(T); 1145 } 1146 1147 if (FirstDecl->isCXXClassMember()) 1148 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1149 nullptr, S); 1150 1151 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1152 return BuildDeclarationNameExpr(SS, Result, ADL); 1153 } 1154 1155 Sema::TemplateNameKindForDiagnostics 1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1157 auto *TD = Name.getAsTemplateDecl(); 1158 if (!TD) 1159 return TemplateNameKindForDiagnostics::DependentTemplate; 1160 if (isa<ClassTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::ClassTemplate; 1162 if (isa<FunctionTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::FunctionTemplate; 1164 if (isa<VarTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::VarTemplate; 1166 if (isa<TypeAliasTemplateDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::AliasTemplate; 1168 if (isa<TemplateTemplateParmDecl>(TD)) 1169 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1170 return TemplateNameKindForDiagnostics::DependentTemplate; 1171 } 1172 1173 // Determines the context to return to after temporarily entering a 1174 // context. This depends in an unnecessarily complicated way on the 1175 // exact ordering of callbacks from the parser. 1176 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1177 1178 // Functions defined inline within classes aren't parsed until we've 1179 // finished parsing the top-level class, so the top-level class is 1180 // the context we'll need to return to. 1181 // A Lambda call operator whose parent is a class must not be treated 1182 // as an inline member function. A Lambda can be used legally 1183 // either as an in-class member initializer or a default argument. These 1184 // are parsed once the class has been marked complete and so the containing 1185 // context would be the nested class (when the lambda is defined in one); 1186 // If the class is not complete, then the lambda is being used in an 1187 // ill-formed fashion (such as to specify the width of a bit-field, or 1188 // in an array-bound) - in which case we still want to return the 1189 // lexically containing DC (which could be a nested class). 1190 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1191 DC = DC->getLexicalParent(); 1192 1193 // A function not defined within a class will always return to its 1194 // lexical context. 1195 if (!isa<CXXRecordDecl>(DC)) 1196 return DC; 1197 1198 // A C++ inline method/friend is parsed *after* the topmost class 1199 // it was declared in is fully parsed ("complete"); the topmost 1200 // class is the context we need to return to. 1201 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1202 DC = RD; 1203 1204 // Return the declaration context of the topmost class the inline method is 1205 // declared in. 1206 return DC; 1207 } 1208 1209 return DC->getLexicalParent(); 1210 } 1211 1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1213 assert(getContainingDC(DC) == CurContext && 1214 "The next DeclContext should be lexically contained in the current one."); 1215 CurContext = DC; 1216 S->setEntity(DC); 1217 } 1218 1219 void Sema::PopDeclContext() { 1220 assert(CurContext && "DeclContext imbalance!"); 1221 1222 CurContext = getContainingDC(CurContext); 1223 assert(CurContext && "Popped translation unit!"); 1224 } 1225 1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1227 Decl *D) { 1228 // Unlike PushDeclContext, the context to which we return is not necessarily 1229 // the containing DC of TD, because the new context will be some pre-existing 1230 // TagDecl definition instead of a fresh one. 1231 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1232 CurContext = cast<TagDecl>(D)->getDefinition(); 1233 assert(CurContext && "skipping definition of undefined tag"); 1234 // Start lookups from the parent of the current context; we don't want to look 1235 // into the pre-existing complete definition. 1236 S->setEntity(CurContext->getLookupParent()); 1237 return Result; 1238 } 1239 1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1241 CurContext = static_cast<decltype(CurContext)>(Context); 1242 } 1243 1244 /// EnterDeclaratorContext - Used when we must lookup names in the context 1245 /// of a declarator's nested name specifier. 1246 /// 1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1248 // C++0x [basic.lookup.unqual]p13: 1249 // A name used in the definition of a static data member of class 1250 // X (after the qualified-id of the static member) is looked up as 1251 // if the name was used in a member function of X. 1252 // C++0x [basic.lookup.unqual]p14: 1253 // If a variable member of a namespace is defined outside of the 1254 // scope of its namespace then any name used in the definition of 1255 // the variable member (after the declarator-id) is looked up as 1256 // if the definition of the variable member occurred in its 1257 // namespace. 1258 // Both of these imply that we should push a scope whose context 1259 // is the semantic context of the declaration. We can't use 1260 // PushDeclContext here because that context is not necessarily 1261 // lexically contained in the current context. Fortunately, 1262 // the containing scope should have the appropriate information. 1263 1264 assert(!S->getEntity() && "scope already has entity"); 1265 1266 #ifndef NDEBUG 1267 Scope *Ancestor = S->getParent(); 1268 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1269 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1270 #endif 1271 1272 CurContext = DC; 1273 S->setEntity(DC); 1274 } 1275 1276 void Sema::ExitDeclaratorContext(Scope *S) { 1277 assert(S->getEntity() == CurContext && "Context imbalance!"); 1278 1279 // Switch back to the lexical context. The safety of this is 1280 // enforced by an assert in EnterDeclaratorContext. 1281 Scope *Ancestor = S->getParent(); 1282 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1283 CurContext = Ancestor->getEntity(); 1284 1285 // We don't need to do anything with the scope, which is going to 1286 // disappear. 1287 } 1288 1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1290 // We assume that the caller has already called 1291 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1292 FunctionDecl *FD = D->getAsFunction(); 1293 if (!FD) 1294 return; 1295 1296 // Same implementation as PushDeclContext, but enters the context 1297 // from the lexical parent, rather than the top-level class. 1298 assert(CurContext == FD->getLexicalParent() && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = FD; 1301 S->setEntity(CurContext); 1302 1303 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1304 ParmVarDecl *Param = FD->getParamDecl(P); 1305 // If the parameter has an identifier, then add it to the scope 1306 if (Param->getIdentifier()) { 1307 S->AddDecl(Param); 1308 IdResolver.AddDecl(Param); 1309 } 1310 } 1311 } 1312 1313 void Sema::ActOnExitFunctionContext() { 1314 // Same implementation as PopDeclContext, but returns to the lexical parent, 1315 // rather than the top-level class. 1316 assert(CurContext && "DeclContext imbalance!"); 1317 CurContext = CurContext->getLexicalParent(); 1318 assert(CurContext && "Popped translation unit!"); 1319 } 1320 1321 /// \brief Determine whether we allow overloading of the function 1322 /// PrevDecl with another declaration. 1323 /// 1324 /// This routine determines whether overloading is possible, not 1325 /// whether some new function is actually an overload. It will return 1326 /// true in C++ (where we can always provide overloads) or, as an 1327 /// extension, in C when the previous function is already an 1328 /// overloaded function declaration or has the "overloadable" 1329 /// attribute. 1330 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1331 ASTContext &Context, 1332 const FunctionDecl *New) { 1333 if (Context.getLangOpts().CPlusPlus) 1334 return true; 1335 1336 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1337 return true; 1338 1339 return Previous.getResultKind() == LookupResult::Found && 1340 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1341 New->hasAttr<OverloadableAttr>()); 1342 } 1343 1344 /// Add this decl to the scope shadowed decl chains. 1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1346 // Move up the scope chain until we find the nearest enclosing 1347 // non-transparent context. The declaration will be introduced into this 1348 // scope. 1349 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1350 S = S->getParent(); 1351 1352 // Add scoped declarations into their context, so that they can be 1353 // found later. Declarations without a context won't be inserted 1354 // into any context. 1355 if (AddToContext) 1356 CurContext->addDecl(D); 1357 1358 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1359 // are function-local declarations. 1360 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1361 !D->getDeclContext()->getRedeclContext()->Equals( 1362 D->getLexicalDeclContext()->getRedeclContext()) && 1363 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1364 return; 1365 1366 // Template instantiations should also not be pushed into scope. 1367 if (isa<FunctionDecl>(D) && 1368 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1369 return; 1370 1371 // If this replaces anything in the current scope, 1372 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1373 IEnd = IdResolver.end(); 1374 for (; I != IEnd; ++I) { 1375 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1376 S->RemoveDecl(*I); 1377 IdResolver.RemoveDecl(*I); 1378 1379 // Should only need to replace one decl. 1380 break; 1381 } 1382 } 1383 1384 S->AddDecl(D); 1385 1386 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1387 // Implicitly-generated labels may end up getting generated in an order that 1388 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1389 // the label at the appropriate place in the identifier chain. 1390 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1391 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1392 if (IDC == CurContext) { 1393 if (!S->isDeclScope(*I)) 1394 continue; 1395 } else if (IDC->Encloses(CurContext)) 1396 break; 1397 } 1398 1399 IdResolver.InsertDeclAfter(I, D); 1400 } else { 1401 IdResolver.AddDecl(D); 1402 } 1403 } 1404 1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1406 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1407 TUScope->AddDecl(D); 1408 } 1409 1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1411 bool AllowInlineNamespace) { 1412 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1413 } 1414 1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1416 DeclContext *TargetDC = DC->getPrimaryContext(); 1417 do { 1418 if (DeclContext *ScopeDC = S->getEntity()) 1419 if (ScopeDC->getPrimaryContext() == TargetDC) 1420 return S; 1421 } while ((S = S->getParent())); 1422 1423 return nullptr; 1424 } 1425 1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1427 DeclContext*, 1428 ASTContext&); 1429 1430 /// Filters out lookup results that don't fall within the given scope 1431 /// as determined by isDeclInScope. 1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1433 bool ConsiderLinkage, 1434 bool AllowInlineNamespace) { 1435 LookupResult::Filter F = R.makeFilter(); 1436 while (F.hasNext()) { 1437 NamedDecl *D = F.next(); 1438 1439 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1440 continue; 1441 1442 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1443 continue; 1444 1445 F.erase(); 1446 } 1447 1448 F.done(); 1449 } 1450 1451 static bool isUsingDecl(NamedDecl *D) { 1452 return isa<UsingShadowDecl>(D) || 1453 isa<UnresolvedUsingTypenameDecl>(D) || 1454 isa<UnresolvedUsingValueDecl>(D); 1455 } 1456 1457 /// Removes using shadow declarations from the lookup results. 1458 static void RemoveUsingDecls(LookupResult &R) { 1459 LookupResult::Filter F = R.makeFilter(); 1460 while (F.hasNext()) 1461 if (isUsingDecl(F.next())) 1462 F.erase(); 1463 1464 F.done(); 1465 } 1466 1467 /// \brief Check for this common pattern: 1468 /// @code 1469 /// class S { 1470 /// S(const S&); // DO NOT IMPLEMENT 1471 /// void operator=(const S&); // DO NOT IMPLEMENT 1472 /// }; 1473 /// @endcode 1474 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1475 // FIXME: Should check for private access too but access is set after we get 1476 // the decl here. 1477 if (D->doesThisDeclarationHaveABody()) 1478 return false; 1479 1480 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1481 return CD->isCopyConstructor(); 1482 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1483 return Method->isCopyAssignmentOperator(); 1484 return false; 1485 } 1486 1487 // We need this to handle 1488 // 1489 // typedef struct { 1490 // void *foo() { return 0; } 1491 // } A; 1492 // 1493 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1494 // for example. If 'A', foo will have external linkage. If we have '*A', 1495 // foo will have no linkage. Since we can't know until we get to the end 1496 // of the typedef, this function finds out if D might have non-external linkage. 1497 // Callers should verify at the end of the TU if it D has external linkage or 1498 // not. 1499 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1500 const DeclContext *DC = D->getDeclContext(); 1501 while (!DC->isTranslationUnit()) { 1502 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1503 if (!RD->hasNameForLinkage()) 1504 return true; 1505 } 1506 DC = DC->getParent(); 1507 } 1508 1509 return !D->isExternallyVisible(); 1510 } 1511 1512 // FIXME: This needs to be refactored; some other isInMainFile users want 1513 // these semantics. 1514 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1515 if (S.TUKind != TU_Complete) 1516 return false; 1517 return S.SourceMgr.isInMainFile(Loc); 1518 } 1519 1520 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1521 assert(D); 1522 1523 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1524 return false; 1525 1526 // Ignore all entities declared within templates, and out-of-line definitions 1527 // of members of class templates. 1528 if (D->getDeclContext()->isDependentContext() || 1529 D->getLexicalDeclContext()->isDependentContext()) 1530 return false; 1531 1532 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1533 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1534 return false; 1535 // A non-out-of-line declaration of a member specialization was implicitly 1536 // instantiated; it's the out-of-line declaration that we're interested in. 1537 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1538 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1539 return false; 1540 1541 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1542 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1543 return false; 1544 } else { 1545 // 'static inline' functions are defined in headers; don't warn. 1546 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1547 return false; 1548 } 1549 1550 if (FD->doesThisDeclarationHaveABody() && 1551 Context.DeclMustBeEmitted(FD)) 1552 return false; 1553 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1554 // Constants and utility variables are defined in headers with internal 1555 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1556 // like "inline".) 1557 if (!isMainFileLoc(*this, VD->getLocation())) 1558 return false; 1559 1560 if (Context.DeclMustBeEmitted(VD)) 1561 return false; 1562 1563 if (VD->isStaticDataMember() && 1564 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1565 return false; 1566 if (VD->isStaticDataMember() && 1567 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1568 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1569 return false; 1570 1571 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1572 return false; 1573 } else { 1574 return false; 1575 } 1576 1577 // Only warn for unused decls internal to the translation unit. 1578 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1579 // for inline functions defined in the main source file, for instance. 1580 return mightHaveNonExternalLinkage(D); 1581 } 1582 1583 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1584 if (!D) 1585 return; 1586 1587 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1588 const FunctionDecl *First = FD->getFirstDecl(); 1589 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1590 return; // First should already be in the vector. 1591 } 1592 1593 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1594 const VarDecl *First = VD->getFirstDecl(); 1595 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1596 return; // First should already be in the vector. 1597 } 1598 1599 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1600 UnusedFileScopedDecls.push_back(D); 1601 } 1602 1603 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1604 if (D->isInvalidDecl()) 1605 return false; 1606 1607 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1608 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1609 return false; 1610 1611 if (isa<LabelDecl>(D)) 1612 return true; 1613 1614 // Except for labels, we only care about unused decls that are local to 1615 // functions. 1616 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1617 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1618 // For dependent types, the diagnostic is deferred. 1619 WithinFunction = 1620 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1621 if (!WithinFunction) 1622 return false; 1623 1624 if (isa<TypedefNameDecl>(D)) 1625 return true; 1626 1627 // White-list anything that isn't a local variable. 1628 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1629 return false; 1630 1631 // Types of valid local variables should be complete, so this should succeed. 1632 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1633 1634 // White-list anything with an __attribute__((unused)) type. 1635 const auto *Ty = VD->getType().getTypePtr(); 1636 1637 // Only look at the outermost level of typedef. 1638 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1639 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1640 return false; 1641 } 1642 1643 // If we failed to complete the type for some reason, or if the type is 1644 // dependent, don't diagnose the variable. 1645 if (Ty->isIncompleteType() || Ty->isDependentType()) 1646 return false; 1647 1648 // Look at the element type to ensure that the warning behaviour is 1649 // consistent for both scalars and arrays. 1650 Ty = Ty->getBaseElementTypeUnsafe(); 1651 1652 if (const TagType *TT = Ty->getAs<TagType>()) { 1653 const TagDecl *Tag = TT->getDecl(); 1654 if (Tag->hasAttr<UnusedAttr>()) 1655 return false; 1656 1657 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1658 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1659 return false; 1660 1661 if (const Expr *Init = VD->getInit()) { 1662 if (const ExprWithCleanups *Cleanups = 1663 dyn_cast<ExprWithCleanups>(Init)) 1664 Init = Cleanups->getSubExpr(); 1665 const CXXConstructExpr *Construct = 1666 dyn_cast<CXXConstructExpr>(Init); 1667 if (Construct && !Construct->isElidable()) { 1668 CXXConstructorDecl *CD = Construct->getConstructor(); 1669 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1670 return false; 1671 } 1672 } 1673 } 1674 } 1675 1676 // TODO: __attribute__((unused)) templates? 1677 } 1678 1679 return true; 1680 } 1681 1682 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1683 FixItHint &Hint) { 1684 if (isa<LabelDecl>(D)) { 1685 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1686 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1687 if (AfterColon.isInvalid()) 1688 return; 1689 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1690 getCharRange(D->getLocStart(), AfterColon)); 1691 } 1692 } 1693 1694 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1695 if (D->getTypeForDecl()->isDependentType()) 1696 return; 1697 1698 for (auto *TmpD : D->decls()) { 1699 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1700 DiagnoseUnusedDecl(T); 1701 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1702 DiagnoseUnusedNestedTypedefs(R); 1703 } 1704 } 1705 1706 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1707 /// unless they are marked attr(unused). 1708 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1709 if (!ShouldDiagnoseUnusedDecl(D)) 1710 return; 1711 1712 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1713 // typedefs can be referenced later on, so the diagnostics are emitted 1714 // at end-of-translation-unit. 1715 UnusedLocalTypedefNameCandidates.insert(TD); 1716 return; 1717 } 1718 1719 FixItHint Hint; 1720 GenerateFixForUnusedDecl(D, Context, Hint); 1721 1722 unsigned DiagID; 1723 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1724 DiagID = diag::warn_unused_exception_param; 1725 else if (isa<LabelDecl>(D)) 1726 DiagID = diag::warn_unused_label; 1727 else 1728 DiagID = diag::warn_unused_variable; 1729 1730 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1731 } 1732 1733 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1734 // Verify that we have no forward references left. If so, there was a goto 1735 // or address of a label taken, but no definition of it. Label fwd 1736 // definitions are indicated with a null substmt which is also not a resolved 1737 // MS inline assembly label name. 1738 bool Diagnose = false; 1739 if (L->isMSAsmLabel()) 1740 Diagnose = !L->isResolvedMSAsmLabel(); 1741 else 1742 Diagnose = L->getStmt() == nullptr; 1743 if (Diagnose) 1744 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1745 } 1746 1747 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1748 S->mergeNRVOIntoParent(); 1749 1750 if (S->decl_empty()) return; 1751 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1752 "Scope shouldn't contain decls!"); 1753 1754 for (auto *TmpD : S->decls()) { 1755 assert(TmpD && "This decl didn't get pushed??"); 1756 1757 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1758 NamedDecl *D = cast<NamedDecl>(TmpD); 1759 1760 if (!D->getDeclName()) continue; 1761 1762 // Diagnose unused variables in this scope. 1763 if (!S->hasUnrecoverableErrorOccurred()) { 1764 DiagnoseUnusedDecl(D); 1765 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1766 DiagnoseUnusedNestedTypedefs(RD); 1767 } 1768 1769 // If this was a forward reference to a label, verify it was defined. 1770 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1771 CheckPoppedLabel(LD, *this); 1772 1773 // Remove this name from our lexical scope, and warn on it if we haven't 1774 // already. 1775 IdResolver.RemoveDecl(D); 1776 auto ShadowI = ShadowingDecls.find(D); 1777 if (ShadowI != ShadowingDecls.end()) { 1778 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1779 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1780 << D << FD << FD->getParent(); 1781 Diag(FD->getLocation(), diag::note_previous_declaration); 1782 } 1783 ShadowingDecls.erase(ShadowI); 1784 } 1785 } 1786 } 1787 1788 /// \brief Look for an Objective-C class in the translation unit. 1789 /// 1790 /// \param Id The name of the Objective-C class we're looking for. If 1791 /// typo-correction fixes this name, the Id will be updated 1792 /// to the fixed name. 1793 /// 1794 /// \param IdLoc The location of the name in the translation unit. 1795 /// 1796 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1797 /// if there is no class with the given name. 1798 /// 1799 /// \returns The declaration of the named Objective-C class, or NULL if the 1800 /// class could not be found. 1801 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1802 SourceLocation IdLoc, 1803 bool DoTypoCorrection) { 1804 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1805 // creation from this context. 1806 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1807 1808 if (!IDecl && DoTypoCorrection) { 1809 // Perform typo correction at the given location, but only if we 1810 // find an Objective-C class name. 1811 if (TypoCorrection C = CorrectTypo( 1812 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1813 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1814 CTK_ErrorRecovery)) { 1815 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1816 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1817 Id = IDecl->getIdentifier(); 1818 } 1819 } 1820 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1821 // This routine must always return a class definition, if any. 1822 if (Def && Def->getDefinition()) 1823 Def = Def->getDefinition(); 1824 return Def; 1825 } 1826 1827 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1828 /// from S, where a non-field would be declared. This routine copes 1829 /// with the difference between C and C++ scoping rules in structs and 1830 /// unions. For example, the following code is well-formed in C but 1831 /// ill-formed in C++: 1832 /// @code 1833 /// struct S6 { 1834 /// enum { BAR } e; 1835 /// }; 1836 /// 1837 /// void test_S6() { 1838 /// struct S6 a; 1839 /// a.e = BAR; 1840 /// } 1841 /// @endcode 1842 /// For the declaration of BAR, this routine will return a different 1843 /// scope. The scope S will be the scope of the unnamed enumeration 1844 /// within S6. In C++, this routine will return the scope associated 1845 /// with S6, because the enumeration's scope is a transparent 1846 /// context but structures can contain non-field names. In C, this 1847 /// routine will return the translation unit scope, since the 1848 /// enumeration's scope is a transparent context and structures cannot 1849 /// contain non-field names. 1850 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1851 while (((S->getFlags() & Scope::DeclScope) == 0) || 1852 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1853 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1854 S = S->getParent(); 1855 return S; 1856 } 1857 1858 /// \brief Looks up the declaration of "struct objc_super" and 1859 /// saves it for later use in building builtin declaration of 1860 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1861 /// pre-existing declaration exists no action takes place. 1862 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1863 IdentifierInfo *II) { 1864 if (!II->isStr("objc_msgSendSuper")) 1865 return; 1866 ASTContext &Context = ThisSema.Context; 1867 1868 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1869 SourceLocation(), Sema::LookupTagName); 1870 ThisSema.LookupName(Result, S); 1871 if (Result.getResultKind() == LookupResult::Found) 1872 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1873 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1874 } 1875 1876 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1877 switch (Error) { 1878 case ASTContext::GE_None: 1879 return ""; 1880 case ASTContext::GE_Missing_stdio: 1881 return "stdio.h"; 1882 case ASTContext::GE_Missing_setjmp: 1883 return "setjmp.h"; 1884 case ASTContext::GE_Missing_ucontext: 1885 return "ucontext.h"; 1886 } 1887 llvm_unreachable("unhandled error kind"); 1888 } 1889 1890 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1891 /// file scope. lazily create a decl for it. ForRedeclaration is true 1892 /// if we're creating this built-in in anticipation of redeclaring the 1893 /// built-in. 1894 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1895 Scope *S, bool ForRedeclaration, 1896 SourceLocation Loc) { 1897 LookupPredefedObjCSuperType(*this, S, II); 1898 1899 ASTContext::GetBuiltinTypeError Error; 1900 QualType R = Context.GetBuiltinType(ID, Error); 1901 if (Error) { 1902 if (ForRedeclaration) 1903 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1904 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1905 return nullptr; 1906 } 1907 1908 if (!ForRedeclaration && 1909 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1910 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1911 Diag(Loc, diag::ext_implicit_lib_function_decl) 1912 << Context.BuiltinInfo.getName(ID) << R; 1913 if (Context.BuiltinInfo.getHeaderName(ID) && 1914 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1915 Diag(Loc, diag::note_include_header_or_declare) 1916 << Context.BuiltinInfo.getHeaderName(ID) 1917 << Context.BuiltinInfo.getName(ID); 1918 } 1919 1920 if (R.isNull()) 1921 return nullptr; 1922 1923 DeclContext *Parent = Context.getTranslationUnitDecl(); 1924 if (getLangOpts().CPlusPlus) { 1925 LinkageSpecDecl *CLinkageDecl = 1926 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1927 LinkageSpecDecl::lang_c, false); 1928 CLinkageDecl->setImplicit(); 1929 Parent->addDecl(CLinkageDecl); 1930 Parent = CLinkageDecl; 1931 } 1932 1933 FunctionDecl *New = FunctionDecl::Create(Context, 1934 Parent, 1935 Loc, Loc, II, R, /*TInfo=*/nullptr, 1936 SC_Extern, 1937 false, 1938 R->isFunctionProtoType()); 1939 New->setImplicit(); 1940 1941 // Create Decl objects for each parameter, adding them to the 1942 // FunctionDecl. 1943 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1944 SmallVector<ParmVarDecl*, 16> Params; 1945 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1946 ParmVarDecl *parm = 1947 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1948 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1949 SC_None, nullptr); 1950 parm->setScopeInfo(0, i); 1951 Params.push_back(parm); 1952 } 1953 New->setParams(Params); 1954 } 1955 1956 AddKnownFunctionAttributes(New); 1957 RegisterLocallyScopedExternCDecl(New, S); 1958 1959 // TUScope is the translation-unit scope to insert this function into. 1960 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1961 // relate Scopes to DeclContexts, and probably eliminate CurContext 1962 // entirely, but we're not there yet. 1963 DeclContext *SavedContext = CurContext; 1964 CurContext = Parent; 1965 PushOnScopeChains(New, TUScope); 1966 CurContext = SavedContext; 1967 return New; 1968 } 1969 1970 /// Typedef declarations don't have linkage, but they still denote the same 1971 /// entity if their types are the same. 1972 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1973 /// isSameEntity. 1974 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1975 TypedefNameDecl *Decl, 1976 LookupResult &Previous) { 1977 // This is only interesting when modules are enabled. 1978 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1979 return; 1980 1981 // Empty sets are uninteresting. 1982 if (Previous.empty()) 1983 return; 1984 1985 LookupResult::Filter Filter = Previous.makeFilter(); 1986 while (Filter.hasNext()) { 1987 NamedDecl *Old = Filter.next(); 1988 1989 // Non-hidden declarations are never ignored. 1990 if (S.isVisible(Old)) 1991 continue; 1992 1993 // Declarations of the same entity are not ignored, even if they have 1994 // different linkages. 1995 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1996 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1997 Decl->getUnderlyingType())) 1998 continue; 1999 2000 // If both declarations give a tag declaration a typedef name for linkage 2001 // purposes, then they declare the same entity. 2002 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2003 Decl->getAnonDeclWithTypedefName()) 2004 continue; 2005 } 2006 2007 Filter.erase(); 2008 } 2009 2010 Filter.done(); 2011 } 2012 2013 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2014 QualType OldType; 2015 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2016 OldType = OldTypedef->getUnderlyingType(); 2017 else 2018 OldType = Context.getTypeDeclType(Old); 2019 QualType NewType = New->getUnderlyingType(); 2020 2021 if (NewType->isVariablyModifiedType()) { 2022 // Must not redefine a typedef with a variably-modified type. 2023 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2024 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2025 << Kind << NewType; 2026 if (Old->getLocation().isValid()) 2027 notePreviousDefinition(Old, New->getLocation()); 2028 New->setInvalidDecl(); 2029 return true; 2030 } 2031 2032 if (OldType != NewType && 2033 !OldType->isDependentType() && 2034 !NewType->isDependentType() && 2035 !Context.hasSameType(OldType, NewType)) { 2036 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2037 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2038 << Kind << NewType << OldType; 2039 if (Old->getLocation().isValid()) 2040 notePreviousDefinition(Old, New->getLocation()); 2041 New->setInvalidDecl(); 2042 return true; 2043 } 2044 return false; 2045 } 2046 2047 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2048 /// same name and scope as a previous declaration 'Old'. Figure out 2049 /// how to resolve this situation, merging decls or emitting 2050 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2051 /// 2052 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2053 LookupResult &OldDecls) { 2054 // If the new decl is known invalid already, don't bother doing any 2055 // merging checks. 2056 if (New->isInvalidDecl()) return; 2057 2058 // Allow multiple definitions for ObjC built-in typedefs. 2059 // FIXME: Verify the underlying types are equivalent! 2060 if (getLangOpts().ObjC1) { 2061 const IdentifierInfo *TypeID = New->getIdentifier(); 2062 switch (TypeID->getLength()) { 2063 default: break; 2064 case 2: 2065 { 2066 if (!TypeID->isStr("id")) 2067 break; 2068 QualType T = New->getUnderlyingType(); 2069 if (!T->isPointerType()) 2070 break; 2071 if (!T->isVoidPointerType()) { 2072 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2073 if (!PT->isStructureType()) 2074 break; 2075 } 2076 Context.setObjCIdRedefinitionType(T); 2077 // Install the built-in type for 'id', ignoring the current definition. 2078 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2079 return; 2080 } 2081 case 5: 2082 if (!TypeID->isStr("Class")) 2083 break; 2084 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2085 // Install the built-in type for 'Class', ignoring the current definition. 2086 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2087 return; 2088 case 3: 2089 if (!TypeID->isStr("SEL")) 2090 break; 2091 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2092 // Install the built-in type for 'SEL', ignoring the current definition. 2093 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2094 return; 2095 } 2096 // Fall through - the typedef name was not a builtin type. 2097 } 2098 2099 // Verify the old decl was also a type. 2100 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2101 if (!Old) { 2102 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2103 << New->getDeclName(); 2104 2105 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2106 if (OldD->getLocation().isValid()) 2107 notePreviousDefinition(OldD, New->getLocation()); 2108 2109 return New->setInvalidDecl(); 2110 } 2111 2112 // If the old declaration is invalid, just give up here. 2113 if (Old->isInvalidDecl()) 2114 return New->setInvalidDecl(); 2115 2116 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2117 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2118 auto *NewTag = New->getAnonDeclWithTypedefName(); 2119 NamedDecl *Hidden = nullptr; 2120 if (OldTag && NewTag && 2121 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2122 !hasVisibleDefinition(OldTag, &Hidden)) { 2123 // There is a definition of this tag, but it is not visible. Use it 2124 // instead of our tag. 2125 New->setTypeForDecl(OldTD->getTypeForDecl()); 2126 if (OldTD->isModed()) 2127 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2128 OldTD->getUnderlyingType()); 2129 else 2130 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2131 2132 // Make the old tag definition visible. 2133 makeMergedDefinitionVisible(Hidden); 2134 2135 // If this was an unscoped enumeration, yank all of its enumerators 2136 // out of the scope. 2137 if (isa<EnumDecl>(NewTag)) { 2138 Scope *EnumScope = getNonFieldDeclScope(S); 2139 for (auto *D : NewTag->decls()) { 2140 auto *ED = cast<EnumConstantDecl>(D); 2141 assert(EnumScope->isDeclScope(ED)); 2142 EnumScope->RemoveDecl(ED); 2143 IdResolver.RemoveDecl(ED); 2144 ED->getLexicalDeclContext()->removeDecl(ED); 2145 } 2146 } 2147 } 2148 } 2149 2150 // If the typedef types are not identical, reject them in all languages and 2151 // with any extensions enabled. 2152 if (isIncompatibleTypedef(Old, New)) 2153 return; 2154 2155 // The types match. Link up the redeclaration chain and merge attributes if 2156 // the old declaration was a typedef. 2157 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2158 New->setPreviousDecl(Typedef); 2159 mergeDeclAttributes(New, Old); 2160 } 2161 2162 if (getLangOpts().MicrosoftExt) 2163 return; 2164 2165 if (getLangOpts().CPlusPlus) { 2166 // C++ [dcl.typedef]p2: 2167 // In a given non-class scope, a typedef specifier can be used to 2168 // redefine the name of any type declared in that scope to refer 2169 // to the type to which it already refers. 2170 if (!isa<CXXRecordDecl>(CurContext)) 2171 return; 2172 2173 // C++0x [dcl.typedef]p4: 2174 // In a given class scope, a typedef specifier can be used to redefine 2175 // any class-name declared in that scope that is not also a typedef-name 2176 // to refer to the type to which it already refers. 2177 // 2178 // This wording came in via DR424, which was a correction to the 2179 // wording in DR56, which accidentally banned code like: 2180 // 2181 // struct S { 2182 // typedef struct A { } A; 2183 // }; 2184 // 2185 // in the C++03 standard. We implement the C++0x semantics, which 2186 // allow the above but disallow 2187 // 2188 // struct S { 2189 // typedef int I; 2190 // typedef int I; 2191 // }; 2192 // 2193 // since that was the intent of DR56. 2194 if (!isa<TypedefNameDecl>(Old)) 2195 return; 2196 2197 Diag(New->getLocation(), diag::err_redefinition) 2198 << New->getDeclName(); 2199 notePreviousDefinition(Old, New->getLocation()); 2200 return New->setInvalidDecl(); 2201 } 2202 2203 // Modules always permit redefinition of typedefs, as does C11. 2204 if (getLangOpts().Modules || getLangOpts().C11) 2205 return; 2206 2207 // If we have a redefinition of a typedef in C, emit a warning. This warning 2208 // is normally mapped to an error, but can be controlled with 2209 // -Wtypedef-redefinition. If either the original or the redefinition is 2210 // in a system header, don't emit this for compatibility with GCC. 2211 if (getDiagnostics().getSuppressSystemWarnings() && 2212 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2213 (Old->isImplicit() || 2214 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2215 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2216 return; 2217 2218 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2219 << New->getDeclName(); 2220 notePreviousDefinition(Old, New->getLocation()); 2221 } 2222 2223 /// DeclhasAttr - returns true if decl Declaration already has the target 2224 /// attribute. 2225 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2226 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2227 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2228 for (const auto *i : D->attrs()) 2229 if (i->getKind() == A->getKind()) { 2230 if (Ann) { 2231 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2232 return true; 2233 continue; 2234 } 2235 // FIXME: Don't hardcode this check 2236 if (OA && isa<OwnershipAttr>(i)) 2237 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2238 return true; 2239 } 2240 2241 return false; 2242 } 2243 2244 static bool isAttributeTargetADefinition(Decl *D) { 2245 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2246 return VD->isThisDeclarationADefinition(); 2247 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2248 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2249 return true; 2250 } 2251 2252 /// Merge alignment attributes from \p Old to \p New, taking into account the 2253 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2254 /// 2255 /// \return \c true if any attributes were added to \p New. 2256 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2257 // Look for alignas attributes on Old, and pick out whichever attribute 2258 // specifies the strictest alignment requirement. 2259 AlignedAttr *OldAlignasAttr = nullptr; 2260 AlignedAttr *OldStrictestAlignAttr = nullptr; 2261 unsigned OldAlign = 0; 2262 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2263 // FIXME: We have no way of representing inherited dependent alignments 2264 // in a case like: 2265 // template<int A, int B> struct alignas(A) X; 2266 // template<int A, int B> struct alignas(B) X {}; 2267 // For now, we just ignore any alignas attributes which are not on the 2268 // definition in such a case. 2269 if (I->isAlignmentDependent()) 2270 return false; 2271 2272 if (I->isAlignas()) 2273 OldAlignasAttr = I; 2274 2275 unsigned Align = I->getAlignment(S.Context); 2276 if (Align > OldAlign) { 2277 OldAlign = Align; 2278 OldStrictestAlignAttr = I; 2279 } 2280 } 2281 2282 // Look for alignas attributes on New. 2283 AlignedAttr *NewAlignasAttr = nullptr; 2284 unsigned NewAlign = 0; 2285 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2286 if (I->isAlignmentDependent()) 2287 return false; 2288 2289 if (I->isAlignas()) 2290 NewAlignasAttr = I; 2291 2292 unsigned Align = I->getAlignment(S.Context); 2293 if (Align > NewAlign) 2294 NewAlign = Align; 2295 } 2296 2297 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2298 // Both declarations have 'alignas' attributes. We require them to match. 2299 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2300 // fall short. (If two declarations both have alignas, they must both match 2301 // every definition, and so must match each other if there is a definition.) 2302 2303 // If either declaration only contains 'alignas(0)' specifiers, then it 2304 // specifies the natural alignment for the type. 2305 if (OldAlign == 0 || NewAlign == 0) { 2306 QualType Ty; 2307 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2308 Ty = VD->getType(); 2309 else 2310 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2311 2312 if (OldAlign == 0) 2313 OldAlign = S.Context.getTypeAlign(Ty); 2314 if (NewAlign == 0) 2315 NewAlign = S.Context.getTypeAlign(Ty); 2316 } 2317 2318 if (OldAlign != NewAlign) { 2319 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2320 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2321 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2322 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2323 } 2324 } 2325 2326 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2327 // C++11 [dcl.align]p6: 2328 // if any declaration of an entity has an alignment-specifier, 2329 // every defining declaration of that entity shall specify an 2330 // equivalent alignment. 2331 // C11 6.7.5/7: 2332 // If the definition of an object does not have an alignment 2333 // specifier, any other declaration of that object shall also 2334 // have no alignment specifier. 2335 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2336 << OldAlignasAttr; 2337 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2338 << OldAlignasAttr; 2339 } 2340 2341 bool AnyAdded = false; 2342 2343 // Ensure we have an attribute representing the strictest alignment. 2344 if (OldAlign > NewAlign) { 2345 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2346 Clone->setInherited(true); 2347 New->addAttr(Clone); 2348 AnyAdded = true; 2349 } 2350 2351 // Ensure we have an alignas attribute if the old declaration had one. 2352 if (OldAlignasAttr && !NewAlignasAttr && 2353 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2354 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2355 Clone->setInherited(true); 2356 New->addAttr(Clone); 2357 AnyAdded = true; 2358 } 2359 2360 return AnyAdded; 2361 } 2362 2363 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2364 const InheritableAttr *Attr, 2365 Sema::AvailabilityMergeKind AMK) { 2366 // This function copies an attribute Attr from a previous declaration to the 2367 // new declaration D if the new declaration doesn't itself have that attribute 2368 // yet or if that attribute allows duplicates. 2369 // If you're adding a new attribute that requires logic different from 2370 // "use explicit attribute on decl if present, else use attribute from 2371 // previous decl", for example if the attribute needs to be consistent 2372 // between redeclarations, you need to call a custom merge function here. 2373 InheritableAttr *NewAttr = nullptr; 2374 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2375 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2376 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2377 AA->isImplicit(), AA->getIntroduced(), 2378 AA->getDeprecated(), 2379 AA->getObsoleted(), AA->getUnavailable(), 2380 AA->getMessage(), AA->getStrict(), 2381 AA->getReplacement(), AMK, 2382 AttrSpellingListIndex); 2383 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2384 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2385 AttrSpellingListIndex); 2386 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2387 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2388 AttrSpellingListIndex); 2389 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2390 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2391 AttrSpellingListIndex); 2392 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2393 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2394 AttrSpellingListIndex); 2395 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2396 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2397 FA->getFormatIdx(), FA->getFirstArg(), 2398 AttrSpellingListIndex); 2399 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2400 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2401 AttrSpellingListIndex); 2402 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2403 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2404 AttrSpellingListIndex, 2405 IA->getSemanticSpelling()); 2406 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2407 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2408 &S.Context.Idents.get(AA->getSpelling()), 2409 AttrSpellingListIndex); 2410 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2411 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2412 isa<CUDAGlobalAttr>(Attr))) { 2413 // CUDA target attributes are part of function signature for 2414 // overloading purposes and must not be merged. 2415 return false; 2416 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2417 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2418 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2419 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2420 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2421 NewAttr = S.mergeInternalLinkageAttr( 2422 D, InternalLinkageA->getRange(), 2423 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2424 AttrSpellingListIndex); 2425 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2426 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2427 &S.Context.Idents.get(CommonA->getSpelling()), 2428 AttrSpellingListIndex); 2429 else if (isa<AlignedAttr>(Attr)) 2430 // AlignedAttrs are handled separately, because we need to handle all 2431 // such attributes on a declaration at the same time. 2432 NewAttr = nullptr; 2433 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2434 (AMK == Sema::AMK_Override || 2435 AMK == Sema::AMK_ProtocolImplementation)) 2436 NewAttr = nullptr; 2437 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2438 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2439 UA->getGuid()); 2440 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2441 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2442 2443 if (NewAttr) { 2444 NewAttr->setInherited(true); 2445 D->addAttr(NewAttr); 2446 if (isa<MSInheritanceAttr>(NewAttr)) 2447 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2448 return true; 2449 } 2450 2451 return false; 2452 } 2453 2454 static const NamedDecl *getDefinition(const Decl *D) { 2455 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2456 return TD->getDefinition(); 2457 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2458 const VarDecl *Def = VD->getDefinition(); 2459 if (Def) 2460 return Def; 2461 return VD->getActingDefinition(); 2462 } 2463 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2464 return FD->getDefinition(); 2465 return nullptr; 2466 } 2467 2468 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2469 for (const auto *Attribute : D->attrs()) 2470 if (Attribute->getKind() == Kind) 2471 return true; 2472 return false; 2473 } 2474 2475 /// checkNewAttributesAfterDef - If we already have a definition, check that 2476 /// there are no new attributes in this declaration. 2477 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2478 if (!New->hasAttrs()) 2479 return; 2480 2481 const NamedDecl *Def = getDefinition(Old); 2482 if (!Def || Def == New) 2483 return; 2484 2485 AttrVec &NewAttributes = New->getAttrs(); 2486 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2487 const Attr *NewAttribute = NewAttributes[I]; 2488 2489 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2490 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2491 Sema::SkipBodyInfo SkipBody; 2492 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2493 2494 // If we're skipping this definition, drop the "alias" attribute. 2495 if (SkipBody.ShouldSkip) { 2496 NewAttributes.erase(NewAttributes.begin() + I); 2497 --E; 2498 continue; 2499 } 2500 } else { 2501 VarDecl *VD = cast<VarDecl>(New); 2502 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2503 VarDecl::TentativeDefinition 2504 ? diag::err_alias_after_tentative 2505 : diag::err_redefinition; 2506 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2507 if (Diag == diag::err_redefinition) 2508 S.notePreviousDefinition(Def, VD->getLocation()); 2509 else 2510 S.Diag(Def->getLocation(), diag::note_previous_definition); 2511 VD->setInvalidDecl(); 2512 } 2513 ++I; 2514 continue; 2515 } 2516 2517 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2518 // Tentative definitions are only interesting for the alias check above. 2519 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2520 ++I; 2521 continue; 2522 } 2523 } 2524 2525 if (hasAttribute(Def, NewAttribute->getKind())) { 2526 ++I; 2527 continue; // regular attr merging will take care of validating this. 2528 } 2529 2530 if (isa<C11NoReturnAttr>(NewAttribute)) { 2531 // C's _Noreturn is allowed to be added to a function after it is defined. 2532 ++I; 2533 continue; 2534 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2535 if (AA->isAlignas()) { 2536 // C++11 [dcl.align]p6: 2537 // if any declaration of an entity has an alignment-specifier, 2538 // every defining declaration of that entity shall specify an 2539 // equivalent alignment. 2540 // C11 6.7.5/7: 2541 // If the definition of an object does not have an alignment 2542 // specifier, any other declaration of that object shall also 2543 // have no alignment specifier. 2544 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2545 << AA; 2546 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2547 << AA; 2548 NewAttributes.erase(NewAttributes.begin() + I); 2549 --E; 2550 continue; 2551 } 2552 } 2553 2554 S.Diag(NewAttribute->getLocation(), 2555 diag::warn_attribute_precede_definition); 2556 S.Diag(Def->getLocation(), diag::note_previous_definition); 2557 NewAttributes.erase(NewAttributes.begin() + I); 2558 --E; 2559 } 2560 } 2561 2562 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2563 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2564 AvailabilityMergeKind AMK) { 2565 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2566 UsedAttr *NewAttr = OldAttr->clone(Context); 2567 NewAttr->setInherited(true); 2568 New->addAttr(NewAttr); 2569 } 2570 2571 if (!Old->hasAttrs() && !New->hasAttrs()) 2572 return; 2573 2574 // Attributes declared post-definition are currently ignored. 2575 checkNewAttributesAfterDef(*this, New, Old); 2576 2577 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2578 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2579 if (OldA->getLabel() != NewA->getLabel()) { 2580 // This redeclaration changes __asm__ label. 2581 Diag(New->getLocation(), diag::err_different_asm_label); 2582 Diag(OldA->getLocation(), diag::note_previous_declaration); 2583 } 2584 } else if (Old->isUsed()) { 2585 // This redeclaration adds an __asm__ label to a declaration that has 2586 // already been ODR-used. 2587 Diag(New->getLocation(), diag::err_late_asm_label_name) 2588 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2589 } 2590 } 2591 2592 // Re-declaration cannot add abi_tag's. 2593 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2594 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2595 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2596 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2597 NewTag) == OldAbiTagAttr->tags_end()) { 2598 Diag(NewAbiTagAttr->getLocation(), 2599 diag::err_new_abi_tag_on_redeclaration) 2600 << NewTag; 2601 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2602 } 2603 } 2604 } else { 2605 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2606 Diag(Old->getLocation(), diag::note_previous_declaration); 2607 } 2608 } 2609 2610 // This redeclaration adds a section attribute. 2611 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2612 if (auto *VD = dyn_cast<VarDecl>(New)) { 2613 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2614 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2615 Diag(Old->getLocation(), diag::note_previous_declaration); 2616 } 2617 } 2618 } 2619 2620 if (!Old->hasAttrs()) 2621 return; 2622 2623 bool foundAny = New->hasAttrs(); 2624 2625 // Ensure that any moving of objects within the allocated map is done before 2626 // we process them. 2627 if (!foundAny) New->setAttrs(AttrVec()); 2628 2629 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2630 // Ignore deprecated/unavailable/availability attributes if requested. 2631 AvailabilityMergeKind LocalAMK = AMK_None; 2632 if (isa<DeprecatedAttr>(I) || 2633 isa<UnavailableAttr>(I) || 2634 isa<AvailabilityAttr>(I)) { 2635 switch (AMK) { 2636 case AMK_None: 2637 continue; 2638 2639 case AMK_Redeclaration: 2640 case AMK_Override: 2641 case AMK_ProtocolImplementation: 2642 LocalAMK = AMK; 2643 break; 2644 } 2645 } 2646 2647 // Already handled. 2648 if (isa<UsedAttr>(I)) 2649 continue; 2650 2651 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2652 foundAny = true; 2653 } 2654 2655 if (mergeAlignedAttrs(*this, New, Old)) 2656 foundAny = true; 2657 2658 if (!foundAny) New->dropAttrs(); 2659 } 2660 2661 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2662 /// to the new one. 2663 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2664 const ParmVarDecl *oldDecl, 2665 Sema &S) { 2666 // C++11 [dcl.attr.depend]p2: 2667 // The first declaration of a function shall specify the 2668 // carries_dependency attribute for its declarator-id if any declaration 2669 // of the function specifies the carries_dependency attribute. 2670 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2671 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2672 S.Diag(CDA->getLocation(), 2673 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2674 // Find the first declaration of the parameter. 2675 // FIXME: Should we build redeclaration chains for function parameters? 2676 const FunctionDecl *FirstFD = 2677 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2678 const ParmVarDecl *FirstVD = 2679 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2680 S.Diag(FirstVD->getLocation(), 2681 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2682 } 2683 2684 if (!oldDecl->hasAttrs()) 2685 return; 2686 2687 bool foundAny = newDecl->hasAttrs(); 2688 2689 // Ensure that any moving of objects within the allocated map is 2690 // done before we process them. 2691 if (!foundAny) newDecl->setAttrs(AttrVec()); 2692 2693 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2694 if (!DeclHasAttr(newDecl, I)) { 2695 InheritableAttr *newAttr = 2696 cast<InheritableParamAttr>(I->clone(S.Context)); 2697 newAttr->setInherited(true); 2698 newDecl->addAttr(newAttr); 2699 foundAny = true; 2700 } 2701 } 2702 2703 if (!foundAny) newDecl->dropAttrs(); 2704 } 2705 2706 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2707 const ParmVarDecl *OldParam, 2708 Sema &S) { 2709 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2710 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2711 if (*Oldnullability != *Newnullability) { 2712 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2713 << DiagNullabilityKind( 2714 *Newnullability, 2715 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2716 != 0)) 2717 << DiagNullabilityKind( 2718 *Oldnullability, 2719 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2720 != 0)); 2721 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2722 } 2723 } else { 2724 QualType NewT = NewParam->getType(); 2725 NewT = S.Context.getAttributedType( 2726 AttributedType::getNullabilityAttrKind(*Oldnullability), 2727 NewT, NewT); 2728 NewParam->setType(NewT); 2729 } 2730 } 2731 } 2732 2733 namespace { 2734 2735 /// Used in MergeFunctionDecl to keep track of function parameters in 2736 /// C. 2737 struct GNUCompatibleParamWarning { 2738 ParmVarDecl *OldParm; 2739 ParmVarDecl *NewParm; 2740 QualType PromotedType; 2741 }; 2742 2743 } // end anonymous namespace 2744 2745 /// getSpecialMember - get the special member enum for a method. 2746 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2747 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2748 if (Ctor->isDefaultConstructor()) 2749 return Sema::CXXDefaultConstructor; 2750 2751 if (Ctor->isCopyConstructor()) 2752 return Sema::CXXCopyConstructor; 2753 2754 if (Ctor->isMoveConstructor()) 2755 return Sema::CXXMoveConstructor; 2756 } else if (isa<CXXDestructorDecl>(MD)) { 2757 return Sema::CXXDestructor; 2758 } else if (MD->isCopyAssignmentOperator()) { 2759 return Sema::CXXCopyAssignment; 2760 } else if (MD->isMoveAssignmentOperator()) { 2761 return Sema::CXXMoveAssignment; 2762 } 2763 2764 return Sema::CXXInvalid; 2765 } 2766 2767 // Determine whether the previous declaration was a definition, implicit 2768 // declaration, or a declaration. 2769 template <typename T> 2770 static std::pair<diag::kind, SourceLocation> 2771 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2772 diag::kind PrevDiag; 2773 SourceLocation OldLocation = Old->getLocation(); 2774 if (Old->isThisDeclarationADefinition()) 2775 PrevDiag = diag::note_previous_definition; 2776 else if (Old->isImplicit()) { 2777 PrevDiag = diag::note_previous_implicit_declaration; 2778 if (OldLocation.isInvalid()) 2779 OldLocation = New->getLocation(); 2780 } else 2781 PrevDiag = diag::note_previous_declaration; 2782 return std::make_pair(PrevDiag, OldLocation); 2783 } 2784 2785 /// canRedefineFunction - checks if a function can be redefined. Currently, 2786 /// only extern inline functions can be redefined, and even then only in 2787 /// GNU89 mode. 2788 static bool canRedefineFunction(const FunctionDecl *FD, 2789 const LangOptions& LangOpts) { 2790 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2791 !LangOpts.CPlusPlus && 2792 FD->isInlineSpecified() && 2793 FD->getStorageClass() == SC_Extern); 2794 } 2795 2796 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2797 const AttributedType *AT = T->getAs<AttributedType>(); 2798 while (AT && !AT->isCallingConv()) 2799 AT = AT->getModifiedType()->getAs<AttributedType>(); 2800 return AT; 2801 } 2802 2803 template <typename T> 2804 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2805 const DeclContext *DC = Old->getDeclContext(); 2806 if (DC->isRecord()) 2807 return false; 2808 2809 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2810 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2811 return true; 2812 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2813 return true; 2814 return false; 2815 } 2816 2817 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2818 static bool isExternC(VarTemplateDecl *) { return false; } 2819 2820 /// \brief Check whether a redeclaration of an entity introduced by a 2821 /// using-declaration is valid, given that we know it's not an overload 2822 /// (nor a hidden tag declaration). 2823 template<typename ExpectedDecl> 2824 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2825 ExpectedDecl *New) { 2826 // C++11 [basic.scope.declarative]p4: 2827 // Given a set of declarations in a single declarative region, each of 2828 // which specifies the same unqualified name, 2829 // -- they shall all refer to the same entity, or all refer to functions 2830 // and function templates; or 2831 // -- exactly one declaration shall declare a class name or enumeration 2832 // name that is not a typedef name and the other declarations shall all 2833 // refer to the same variable or enumerator, or all refer to functions 2834 // and function templates; in this case the class name or enumeration 2835 // name is hidden (3.3.10). 2836 2837 // C++11 [namespace.udecl]p14: 2838 // If a function declaration in namespace scope or block scope has the 2839 // same name and the same parameter-type-list as a function introduced 2840 // by a using-declaration, and the declarations do not declare the same 2841 // function, the program is ill-formed. 2842 2843 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2844 if (Old && 2845 !Old->getDeclContext()->getRedeclContext()->Equals( 2846 New->getDeclContext()->getRedeclContext()) && 2847 !(isExternC(Old) && isExternC(New))) 2848 Old = nullptr; 2849 2850 if (!Old) { 2851 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2852 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2853 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2854 return true; 2855 } 2856 return false; 2857 } 2858 2859 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2860 const FunctionDecl *B) { 2861 assert(A->getNumParams() == B->getNumParams()); 2862 2863 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2864 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2865 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2866 if (AttrA == AttrB) 2867 return true; 2868 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2869 }; 2870 2871 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2872 } 2873 2874 /// MergeFunctionDecl - We just parsed a function 'New' from 2875 /// declarator D which has the same name and scope as a previous 2876 /// declaration 'Old'. Figure out how to resolve this situation, 2877 /// merging decls or emitting diagnostics as appropriate. 2878 /// 2879 /// In C++, New and Old must be declarations that are not 2880 /// overloaded. Use IsOverload to determine whether New and Old are 2881 /// overloaded, and to select the Old declaration that New should be 2882 /// merged with. 2883 /// 2884 /// Returns true if there was an error, false otherwise. 2885 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2886 Scope *S, bool MergeTypeWithOld) { 2887 // Verify the old decl was also a function. 2888 FunctionDecl *Old = OldD->getAsFunction(); 2889 if (!Old) { 2890 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2891 if (New->getFriendObjectKind()) { 2892 Diag(New->getLocation(), diag::err_using_decl_friend); 2893 Diag(Shadow->getTargetDecl()->getLocation(), 2894 diag::note_using_decl_target); 2895 Diag(Shadow->getUsingDecl()->getLocation(), 2896 diag::note_using_decl) << 0; 2897 return true; 2898 } 2899 2900 // Check whether the two declarations might declare the same function. 2901 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2902 return true; 2903 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2904 } else { 2905 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2906 << New->getDeclName(); 2907 notePreviousDefinition(OldD, New->getLocation()); 2908 return true; 2909 } 2910 } 2911 2912 // If the old declaration is invalid, just give up here. 2913 if (Old->isInvalidDecl()) 2914 return true; 2915 2916 diag::kind PrevDiag; 2917 SourceLocation OldLocation; 2918 std::tie(PrevDiag, OldLocation) = 2919 getNoteDiagForInvalidRedeclaration(Old, New); 2920 2921 // Don't complain about this if we're in GNU89 mode and the old function 2922 // is an extern inline function. 2923 // Don't complain about specializations. They are not supposed to have 2924 // storage classes. 2925 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2926 New->getStorageClass() == SC_Static && 2927 Old->hasExternalFormalLinkage() && 2928 !New->getTemplateSpecializationInfo() && 2929 !canRedefineFunction(Old, getLangOpts())) { 2930 if (getLangOpts().MicrosoftExt) { 2931 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2932 Diag(OldLocation, PrevDiag); 2933 } else { 2934 Diag(New->getLocation(), diag::err_static_non_static) << New; 2935 Diag(OldLocation, PrevDiag); 2936 return true; 2937 } 2938 } 2939 2940 if (New->hasAttr<InternalLinkageAttr>() && 2941 !Old->hasAttr<InternalLinkageAttr>()) { 2942 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2943 << New->getDeclName(); 2944 notePreviousDefinition(Old, New->getLocation()); 2945 New->dropAttr<InternalLinkageAttr>(); 2946 } 2947 2948 if (!getLangOpts().CPlusPlus) { 2949 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 2950 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 2951 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 2952 << New << OldOvl; 2953 2954 // Try our best to find a decl that actually has the overloadable 2955 // attribute for the note. In most cases (e.g. programs with only one 2956 // broken declaration/definition), this won't matter. 2957 // 2958 // FIXME: We could do this if we juggled some extra state in 2959 // OverloadableAttr, rather than just removing it. 2960 const Decl *DiagOld = Old; 2961 if (OldOvl) { 2962 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 2963 const auto *A = D->getAttr<OverloadableAttr>(); 2964 return A && !A->isImplicit(); 2965 }); 2966 // If we've implicitly added *all* of the overloadable attrs to this 2967 // chain, emitting a "previous redecl" note is pointless. 2968 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 2969 } 2970 2971 if (DiagOld) 2972 Diag(DiagOld->getLocation(), 2973 diag::note_attribute_overloadable_prev_overload) 2974 << OldOvl; 2975 2976 if (OldOvl) 2977 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 2978 else 2979 New->dropAttr<OverloadableAttr>(); 2980 } 2981 } 2982 2983 // If a function is first declared with a calling convention, but is later 2984 // declared or defined without one, all following decls assume the calling 2985 // convention of the first. 2986 // 2987 // It's OK if a function is first declared without a calling convention, 2988 // but is later declared or defined with the default calling convention. 2989 // 2990 // To test if either decl has an explicit calling convention, we look for 2991 // AttributedType sugar nodes on the type as written. If they are missing or 2992 // were canonicalized away, we assume the calling convention was implicit. 2993 // 2994 // Note also that we DO NOT return at this point, because we still have 2995 // other tests to run. 2996 QualType OldQType = Context.getCanonicalType(Old->getType()); 2997 QualType NewQType = Context.getCanonicalType(New->getType()); 2998 const FunctionType *OldType = cast<FunctionType>(OldQType); 2999 const FunctionType *NewType = cast<FunctionType>(NewQType); 3000 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3001 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3002 bool RequiresAdjustment = false; 3003 3004 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3005 FunctionDecl *First = Old->getFirstDecl(); 3006 const FunctionType *FT = 3007 First->getType().getCanonicalType()->castAs<FunctionType>(); 3008 FunctionType::ExtInfo FI = FT->getExtInfo(); 3009 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3010 if (!NewCCExplicit) { 3011 // Inherit the CC from the previous declaration if it was specified 3012 // there but not here. 3013 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3014 RequiresAdjustment = true; 3015 } else { 3016 // Calling conventions aren't compatible, so complain. 3017 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3018 Diag(New->getLocation(), diag::err_cconv_change) 3019 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3020 << !FirstCCExplicit 3021 << (!FirstCCExplicit ? "" : 3022 FunctionType::getNameForCallConv(FI.getCC())); 3023 3024 // Put the note on the first decl, since it is the one that matters. 3025 Diag(First->getLocation(), diag::note_previous_declaration); 3026 return true; 3027 } 3028 } 3029 3030 // FIXME: diagnose the other way around? 3031 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3032 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3033 RequiresAdjustment = true; 3034 } 3035 3036 // Merge regparm attribute. 3037 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3038 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3039 if (NewTypeInfo.getHasRegParm()) { 3040 Diag(New->getLocation(), diag::err_regparm_mismatch) 3041 << NewType->getRegParmType() 3042 << OldType->getRegParmType(); 3043 Diag(OldLocation, diag::note_previous_declaration); 3044 return true; 3045 } 3046 3047 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3048 RequiresAdjustment = true; 3049 } 3050 3051 // Merge ns_returns_retained attribute. 3052 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3053 if (NewTypeInfo.getProducesResult()) { 3054 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3055 << "'ns_returns_retained'"; 3056 Diag(OldLocation, diag::note_previous_declaration); 3057 return true; 3058 } 3059 3060 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3061 RequiresAdjustment = true; 3062 } 3063 3064 if (OldTypeInfo.getNoCallerSavedRegs() != 3065 NewTypeInfo.getNoCallerSavedRegs()) { 3066 if (NewTypeInfo.getNoCallerSavedRegs()) { 3067 AnyX86NoCallerSavedRegistersAttr *Attr = 3068 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3069 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3070 Diag(OldLocation, diag::note_previous_declaration); 3071 return true; 3072 } 3073 3074 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3075 RequiresAdjustment = true; 3076 } 3077 3078 if (RequiresAdjustment) { 3079 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3080 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3081 New->setType(QualType(AdjustedType, 0)); 3082 NewQType = Context.getCanonicalType(New->getType()); 3083 NewType = cast<FunctionType>(NewQType); 3084 } 3085 3086 // If this redeclaration makes the function inline, we may need to add it to 3087 // UndefinedButUsed. 3088 if (!Old->isInlined() && New->isInlined() && 3089 !New->hasAttr<GNUInlineAttr>() && 3090 !getLangOpts().GNUInline && 3091 Old->isUsed(false) && 3092 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3093 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3094 SourceLocation())); 3095 3096 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3097 // about it. 3098 if (New->hasAttr<GNUInlineAttr>() && 3099 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3100 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3101 } 3102 3103 // If pass_object_size params don't match up perfectly, this isn't a valid 3104 // redeclaration. 3105 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3106 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3107 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3108 << New->getDeclName(); 3109 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3110 return true; 3111 } 3112 3113 if (getLangOpts().CPlusPlus) { 3114 // C++1z [over.load]p2 3115 // Certain function declarations cannot be overloaded: 3116 // -- Function declarations that differ only in the return type, 3117 // the exception specification, or both cannot be overloaded. 3118 3119 // Check the exception specifications match. This may recompute the type of 3120 // both Old and New if it resolved exception specifications, so grab the 3121 // types again after this. Because this updates the type, we do this before 3122 // any of the other checks below, which may update the "de facto" NewQType 3123 // but do not necessarily update the type of New. 3124 if (CheckEquivalentExceptionSpec(Old, New)) 3125 return true; 3126 OldQType = Context.getCanonicalType(Old->getType()); 3127 NewQType = Context.getCanonicalType(New->getType()); 3128 3129 // Go back to the type source info to compare the declared return types, 3130 // per C++1y [dcl.type.auto]p13: 3131 // Redeclarations or specializations of a function or function template 3132 // with a declared return type that uses a placeholder type shall also 3133 // use that placeholder, not a deduced type. 3134 QualType OldDeclaredReturnType = 3135 (Old->getTypeSourceInfo() 3136 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3137 : OldType)->getReturnType(); 3138 QualType NewDeclaredReturnType = 3139 (New->getTypeSourceInfo() 3140 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3141 : NewType)->getReturnType(); 3142 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3143 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3144 New->isLocalExternDecl())) { 3145 QualType ResQT; 3146 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3147 OldDeclaredReturnType->isObjCObjectPointerType()) 3148 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3149 if (ResQT.isNull()) { 3150 if (New->isCXXClassMember() && New->isOutOfLine()) 3151 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3152 << New << New->getReturnTypeSourceRange(); 3153 else 3154 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3155 << New->getReturnTypeSourceRange(); 3156 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3157 << Old->getReturnTypeSourceRange(); 3158 return true; 3159 } 3160 else 3161 NewQType = ResQT; 3162 } 3163 3164 QualType OldReturnType = OldType->getReturnType(); 3165 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3166 if (OldReturnType != NewReturnType) { 3167 // If this function has a deduced return type and has already been 3168 // defined, copy the deduced value from the old declaration. 3169 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3170 if (OldAT && OldAT->isDeduced()) { 3171 New->setType( 3172 SubstAutoType(New->getType(), 3173 OldAT->isDependentType() ? Context.DependentTy 3174 : OldAT->getDeducedType())); 3175 NewQType = Context.getCanonicalType( 3176 SubstAutoType(NewQType, 3177 OldAT->isDependentType() ? Context.DependentTy 3178 : OldAT->getDeducedType())); 3179 } 3180 } 3181 3182 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3183 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3184 if (OldMethod && NewMethod) { 3185 // Preserve triviality. 3186 NewMethod->setTrivial(OldMethod->isTrivial()); 3187 3188 // MSVC allows explicit template specialization at class scope: 3189 // 2 CXXMethodDecls referring to the same function will be injected. 3190 // We don't want a redeclaration error. 3191 bool IsClassScopeExplicitSpecialization = 3192 OldMethod->isFunctionTemplateSpecialization() && 3193 NewMethod->isFunctionTemplateSpecialization(); 3194 bool isFriend = NewMethod->getFriendObjectKind(); 3195 3196 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3197 !IsClassScopeExplicitSpecialization) { 3198 // -- Member function declarations with the same name and the 3199 // same parameter types cannot be overloaded if any of them 3200 // is a static member function declaration. 3201 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3202 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3203 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3204 return true; 3205 } 3206 3207 // C++ [class.mem]p1: 3208 // [...] A member shall not be declared twice in the 3209 // member-specification, except that a nested class or member 3210 // class template can be declared and then later defined. 3211 if (!inTemplateInstantiation()) { 3212 unsigned NewDiag; 3213 if (isa<CXXConstructorDecl>(OldMethod)) 3214 NewDiag = diag::err_constructor_redeclared; 3215 else if (isa<CXXDestructorDecl>(NewMethod)) 3216 NewDiag = diag::err_destructor_redeclared; 3217 else if (isa<CXXConversionDecl>(NewMethod)) 3218 NewDiag = diag::err_conv_function_redeclared; 3219 else 3220 NewDiag = diag::err_member_redeclared; 3221 3222 Diag(New->getLocation(), NewDiag); 3223 } else { 3224 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3225 << New << New->getType(); 3226 } 3227 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3228 return true; 3229 3230 // Complain if this is an explicit declaration of a special 3231 // member that was initially declared implicitly. 3232 // 3233 // As an exception, it's okay to befriend such methods in order 3234 // to permit the implicit constructor/destructor/operator calls. 3235 } else if (OldMethod->isImplicit()) { 3236 if (isFriend) { 3237 NewMethod->setImplicit(); 3238 } else { 3239 Diag(NewMethod->getLocation(), 3240 diag::err_definition_of_implicitly_declared_member) 3241 << New << getSpecialMember(OldMethod); 3242 return true; 3243 } 3244 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3245 Diag(NewMethod->getLocation(), 3246 diag::err_definition_of_explicitly_defaulted_member) 3247 << getSpecialMember(OldMethod); 3248 return true; 3249 } 3250 } 3251 3252 // C++11 [dcl.attr.noreturn]p1: 3253 // The first declaration of a function shall specify the noreturn 3254 // attribute if any declaration of that function specifies the noreturn 3255 // attribute. 3256 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3257 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3258 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3259 Diag(Old->getFirstDecl()->getLocation(), 3260 diag::note_noreturn_missing_first_decl); 3261 } 3262 3263 // C++11 [dcl.attr.depend]p2: 3264 // The first declaration of a function shall specify the 3265 // carries_dependency attribute for its declarator-id if any declaration 3266 // of the function specifies the carries_dependency attribute. 3267 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3268 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3269 Diag(CDA->getLocation(), 3270 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3271 Diag(Old->getFirstDecl()->getLocation(), 3272 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3273 } 3274 3275 // (C++98 8.3.5p3): 3276 // All declarations for a function shall agree exactly in both the 3277 // return type and the parameter-type-list. 3278 // We also want to respect all the extended bits except noreturn. 3279 3280 // noreturn should now match unless the old type info didn't have it. 3281 QualType OldQTypeForComparison = OldQType; 3282 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3283 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3284 const FunctionType *OldTypeForComparison 3285 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3286 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3287 assert(OldQTypeForComparison.isCanonical()); 3288 } 3289 3290 if (haveIncompatibleLanguageLinkages(Old, New)) { 3291 // As a special case, retain the language linkage from previous 3292 // declarations of a friend function as an extension. 3293 // 3294 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3295 // and is useful because there's otherwise no way to specify language 3296 // linkage within class scope. 3297 // 3298 // Check cautiously as the friend object kind isn't yet complete. 3299 if (New->getFriendObjectKind() != Decl::FOK_None) { 3300 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3301 Diag(OldLocation, PrevDiag); 3302 } else { 3303 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3304 Diag(OldLocation, PrevDiag); 3305 return true; 3306 } 3307 } 3308 3309 if (OldQTypeForComparison == NewQType) 3310 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3311 3312 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3313 New->isLocalExternDecl()) { 3314 // It's OK if we couldn't merge types for a local function declaraton 3315 // if either the old or new type is dependent. We'll merge the types 3316 // when we instantiate the function. 3317 return false; 3318 } 3319 3320 // Fall through for conflicting redeclarations and redefinitions. 3321 } 3322 3323 // C: Function types need to be compatible, not identical. This handles 3324 // duplicate function decls like "void f(int); void f(enum X);" properly. 3325 if (!getLangOpts().CPlusPlus && 3326 Context.typesAreCompatible(OldQType, NewQType)) { 3327 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3328 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3329 const FunctionProtoType *OldProto = nullptr; 3330 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3331 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3332 // The old declaration provided a function prototype, but the 3333 // new declaration does not. Merge in the prototype. 3334 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3335 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3336 NewQType = 3337 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3338 OldProto->getExtProtoInfo()); 3339 New->setType(NewQType); 3340 New->setHasInheritedPrototype(); 3341 3342 // Synthesize parameters with the same types. 3343 SmallVector<ParmVarDecl*, 16> Params; 3344 for (const auto &ParamType : OldProto->param_types()) { 3345 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3346 SourceLocation(), nullptr, 3347 ParamType, /*TInfo=*/nullptr, 3348 SC_None, nullptr); 3349 Param->setScopeInfo(0, Params.size()); 3350 Param->setImplicit(); 3351 Params.push_back(Param); 3352 } 3353 3354 New->setParams(Params); 3355 } 3356 3357 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3358 } 3359 3360 // GNU C permits a K&R definition to follow a prototype declaration 3361 // if the declared types of the parameters in the K&R definition 3362 // match the types in the prototype declaration, even when the 3363 // promoted types of the parameters from the K&R definition differ 3364 // from the types in the prototype. GCC then keeps the types from 3365 // the prototype. 3366 // 3367 // If a variadic prototype is followed by a non-variadic K&R definition, 3368 // the K&R definition becomes variadic. This is sort of an edge case, but 3369 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3370 // C99 6.9.1p8. 3371 if (!getLangOpts().CPlusPlus && 3372 Old->hasPrototype() && !New->hasPrototype() && 3373 New->getType()->getAs<FunctionProtoType>() && 3374 Old->getNumParams() == New->getNumParams()) { 3375 SmallVector<QualType, 16> ArgTypes; 3376 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3377 const FunctionProtoType *OldProto 3378 = Old->getType()->getAs<FunctionProtoType>(); 3379 const FunctionProtoType *NewProto 3380 = New->getType()->getAs<FunctionProtoType>(); 3381 3382 // Determine whether this is the GNU C extension. 3383 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3384 NewProto->getReturnType()); 3385 bool LooseCompatible = !MergedReturn.isNull(); 3386 for (unsigned Idx = 0, End = Old->getNumParams(); 3387 LooseCompatible && Idx != End; ++Idx) { 3388 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3389 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3390 if (Context.typesAreCompatible(OldParm->getType(), 3391 NewProto->getParamType(Idx))) { 3392 ArgTypes.push_back(NewParm->getType()); 3393 } else if (Context.typesAreCompatible(OldParm->getType(), 3394 NewParm->getType(), 3395 /*CompareUnqualified=*/true)) { 3396 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3397 NewProto->getParamType(Idx) }; 3398 Warnings.push_back(Warn); 3399 ArgTypes.push_back(NewParm->getType()); 3400 } else 3401 LooseCompatible = false; 3402 } 3403 3404 if (LooseCompatible) { 3405 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3406 Diag(Warnings[Warn].NewParm->getLocation(), 3407 diag::ext_param_promoted_not_compatible_with_prototype) 3408 << Warnings[Warn].PromotedType 3409 << Warnings[Warn].OldParm->getType(); 3410 if (Warnings[Warn].OldParm->getLocation().isValid()) 3411 Diag(Warnings[Warn].OldParm->getLocation(), 3412 diag::note_previous_declaration); 3413 } 3414 3415 if (MergeTypeWithOld) 3416 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3417 OldProto->getExtProtoInfo())); 3418 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3419 } 3420 3421 // Fall through to diagnose conflicting types. 3422 } 3423 3424 // A function that has already been declared has been redeclared or 3425 // defined with a different type; show an appropriate diagnostic. 3426 3427 // If the previous declaration was an implicitly-generated builtin 3428 // declaration, then at the very least we should use a specialized note. 3429 unsigned BuiltinID; 3430 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3431 // If it's actually a library-defined builtin function like 'malloc' 3432 // or 'printf', just warn about the incompatible redeclaration. 3433 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3434 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3435 Diag(OldLocation, diag::note_previous_builtin_declaration) 3436 << Old << Old->getType(); 3437 3438 // If this is a global redeclaration, just forget hereafter 3439 // about the "builtin-ness" of the function. 3440 // 3441 // Doing this for local extern declarations is problematic. If 3442 // the builtin declaration remains visible, a second invalid 3443 // local declaration will produce a hard error; if it doesn't 3444 // remain visible, a single bogus local redeclaration (which is 3445 // actually only a warning) could break all the downstream code. 3446 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3447 New->getIdentifier()->revertBuiltin(); 3448 3449 return false; 3450 } 3451 3452 PrevDiag = diag::note_previous_builtin_declaration; 3453 } 3454 3455 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3456 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3457 return true; 3458 } 3459 3460 /// \brief Completes the merge of two function declarations that are 3461 /// known to be compatible. 3462 /// 3463 /// This routine handles the merging of attributes and other 3464 /// properties of function declarations from the old declaration to 3465 /// the new declaration, once we know that New is in fact a 3466 /// redeclaration of Old. 3467 /// 3468 /// \returns false 3469 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3470 Scope *S, bool MergeTypeWithOld) { 3471 // Merge the attributes 3472 mergeDeclAttributes(New, Old); 3473 3474 // Merge "pure" flag. 3475 if (Old->isPure()) 3476 New->setPure(); 3477 3478 // Merge "used" flag. 3479 if (Old->getMostRecentDecl()->isUsed(false)) 3480 New->setIsUsed(); 3481 3482 // Merge attributes from the parameters. These can mismatch with K&R 3483 // declarations. 3484 if (New->getNumParams() == Old->getNumParams()) 3485 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3486 ParmVarDecl *NewParam = New->getParamDecl(i); 3487 ParmVarDecl *OldParam = Old->getParamDecl(i); 3488 mergeParamDeclAttributes(NewParam, OldParam, *this); 3489 mergeParamDeclTypes(NewParam, OldParam, *this); 3490 } 3491 3492 if (getLangOpts().CPlusPlus) 3493 return MergeCXXFunctionDecl(New, Old, S); 3494 3495 // Merge the function types so the we get the composite types for the return 3496 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3497 // was visible. 3498 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3499 if (!Merged.isNull() && MergeTypeWithOld) 3500 New->setType(Merged); 3501 3502 return false; 3503 } 3504 3505 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3506 ObjCMethodDecl *oldMethod) { 3507 // Merge the attributes, including deprecated/unavailable 3508 AvailabilityMergeKind MergeKind = 3509 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3510 ? AMK_ProtocolImplementation 3511 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3512 : AMK_Override; 3513 3514 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3515 3516 // Merge attributes from the parameters. 3517 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3518 oe = oldMethod->param_end(); 3519 for (ObjCMethodDecl::param_iterator 3520 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3521 ni != ne && oi != oe; ++ni, ++oi) 3522 mergeParamDeclAttributes(*ni, *oi, *this); 3523 3524 CheckObjCMethodOverride(newMethod, oldMethod); 3525 } 3526 3527 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3528 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3529 3530 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3531 ? diag::err_redefinition_different_type 3532 : diag::err_redeclaration_different_type) 3533 << New->getDeclName() << New->getType() << Old->getType(); 3534 3535 diag::kind PrevDiag; 3536 SourceLocation OldLocation; 3537 std::tie(PrevDiag, OldLocation) 3538 = getNoteDiagForInvalidRedeclaration(Old, New); 3539 S.Diag(OldLocation, PrevDiag); 3540 New->setInvalidDecl(); 3541 } 3542 3543 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3544 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3545 /// emitting diagnostics as appropriate. 3546 /// 3547 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3548 /// to here in AddInitializerToDecl. We can't check them before the initializer 3549 /// is attached. 3550 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3551 bool MergeTypeWithOld) { 3552 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3553 return; 3554 3555 QualType MergedT; 3556 if (getLangOpts().CPlusPlus) { 3557 if (New->getType()->isUndeducedType()) { 3558 // We don't know what the new type is until the initializer is attached. 3559 return; 3560 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3561 // These could still be something that needs exception specs checked. 3562 return MergeVarDeclExceptionSpecs(New, Old); 3563 } 3564 // C++ [basic.link]p10: 3565 // [...] the types specified by all declarations referring to a given 3566 // object or function shall be identical, except that declarations for an 3567 // array object can specify array types that differ by the presence or 3568 // absence of a major array bound (8.3.4). 3569 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3570 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3571 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3572 3573 // We are merging a variable declaration New into Old. If it has an array 3574 // bound, and that bound differs from Old's bound, we should diagnose the 3575 // mismatch. 3576 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3577 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3578 PrevVD = PrevVD->getPreviousDecl()) { 3579 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3580 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3581 continue; 3582 3583 if (!Context.hasSameType(NewArray, PrevVDTy)) 3584 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3585 } 3586 } 3587 3588 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3589 if (Context.hasSameType(OldArray->getElementType(), 3590 NewArray->getElementType())) 3591 MergedT = New->getType(); 3592 } 3593 // FIXME: Check visibility. New is hidden but has a complete type. If New 3594 // has no array bound, it should not inherit one from Old, if Old is not 3595 // visible. 3596 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3597 if (Context.hasSameType(OldArray->getElementType(), 3598 NewArray->getElementType())) 3599 MergedT = Old->getType(); 3600 } 3601 } 3602 else if (New->getType()->isObjCObjectPointerType() && 3603 Old->getType()->isObjCObjectPointerType()) { 3604 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3605 Old->getType()); 3606 } 3607 } else { 3608 // C 6.2.7p2: 3609 // All declarations that refer to the same object or function shall have 3610 // compatible type. 3611 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3612 } 3613 if (MergedT.isNull()) { 3614 // It's OK if we couldn't merge types if either type is dependent, for a 3615 // block-scope variable. In other cases (static data members of class 3616 // templates, variable templates, ...), we require the types to be 3617 // equivalent. 3618 // FIXME: The C++ standard doesn't say anything about this. 3619 if ((New->getType()->isDependentType() || 3620 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3621 // If the old type was dependent, we can't merge with it, so the new type 3622 // becomes dependent for now. We'll reproduce the original type when we 3623 // instantiate the TypeSourceInfo for the variable. 3624 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3625 New->setType(Context.DependentTy); 3626 return; 3627 } 3628 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3629 } 3630 3631 // Don't actually update the type on the new declaration if the old 3632 // declaration was an extern declaration in a different scope. 3633 if (MergeTypeWithOld) 3634 New->setType(MergedT); 3635 } 3636 3637 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3638 LookupResult &Previous) { 3639 // C11 6.2.7p4: 3640 // For an identifier with internal or external linkage declared 3641 // in a scope in which a prior declaration of that identifier is 3642 // visible, if the prior declaration specifies internal or 3643 // external linkage, the type of the identifier at the later 3644 // declaration becomes the composite type. 3645 // 3646 // If the variable isn't visible, we do not merge with its type. 3647 if (Previous.isShadowed()) 3648 return false; 3649 3650 if (S.getLangOpts().CPlusPlus) { 3651 // C++11 [dcl.array]p3: 3652 // If there is a preceding declaration of the entity in the same 3653 // scope in which the bound was specified, an omitted array bound 3654 // is taken to be the same as in that earlier declaration. 3655 return NewVD->isPreviousDeclInSameBlockScope() || 3656 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3657 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3658 } else { 3659 // If the old declaration was function-local, don't merge with its 3660 // type unless we're in the same function. 3661 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3662 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3663 } 3664 } 3665 3666 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3667 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3668 /// situation, merging decls or emitting diagnostics as appropriate. 3669 /// 3670 /// Tentative definition rules (C99 6.9.2p2) are checked by 3671 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3672 /// definitions here, since the initializer hasn't been attached. 3673 /// 3674 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3675 // If the new decl is already invalid, don't do any other checking. 3676 if (New->isInvalidDecl()) 3677 return; 3678 3679 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3680 return; 3681 3682 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3683 3684 // Verify the old decl was also a variable or variable template. 3685 VarDecl *Old = nullptr; 3686 VarTemplateDecl *OldTemplate = nullptr; 3687 if (Previous.isSingleResult()) { 3688 if (NewTemplate) { 3689 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3690 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3691 3692 if (auto *Shadow = 3693 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3694 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3695 return New->setInvalidDecl(); 3696 } else { 3697 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3698 3699 if (auto *Shadow = 3700 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3701 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3702 return New->setInvalidDecl(); 3703 } 3704 } 3705 if (!Old) { 3706 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3707 << New->getDeclName(); 3708 notePreviousDefinition(Previous.getRepresentativeDecl(), 3709 New->getLocation()); 3710 return New->setInvalidDecl(); 3711 } 3712 3713 // Ensure the template parameters are compatible. 3714 if (NewTemplate && 3715 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3716 OldTemplate->getTemplateParameters(), 3717 /*Complain=*/true, TPL_TemplateMatch)) 3718 return New->setInvalidDecl(); 3719 3720 // C++ [class.mem]p1: 3721 // A member shall not be declared twice in the member-specification [...] 3722 // 3723 // Here, we need only consider static data members. 3724 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3725 Diag(New->getLocation(), diag::err_duplicate_member) 3726 << New->getIdentifier(); 3727 Diag(Old->getLocation(), diag::note_previous_declaration); 3728 New->setInvalidDecl(); 3729 } 3730 3731 mergeDeclAttributes(New, Old); 3732 // Warn if an already-declared variable is made a weak_import in a subsequent 3733 // declaration 3734 if (New->hasAttr<WeakImportAttr>() && 3735 Old->getStorageClass() == SC_None && 3736 !Old->hasAttr<WeakImportAttr>()) { 3737 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3738 notePreviousDefinition(Old, New->getLocation()); 3739 // Remove weak_import attribute on new declaration. 3740 New->dropAttr<WeakImportAttr>(); 3741 } 3742 3743 if (New->hasAttr<InternalLinkageAttr>() && 3744 !Old->hasAttr<InternalLinkageAttr>()) { 3745 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3746 << New->getDeclName(); 3747 notePreviousDefinition(Old, New->getLocation()); 3748 New->dropAttr<InternalLinkageAttr>(); 3749 } 3750 3751 // Merge the types. 3752 VarDecl *MostRecent = Old->getMostRecentDecl(); 3753 if (MostRecent != Old) { 3754 MergeVarDeclTypes(New, MostRecent, 3755 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3756 if (New->isInvalidDecl()) 3757 return; 3758 } 3759 3760 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3761 if (New->isInvalidDecl()) 3762 return; 3763 3764 diag::kind PrevDiag; 3765 SourceLocation OldLocation; 3766 std::tie(PrevDiag, OldLocation) = 3767 getNoteDiagForInvalidRedeclaration(Old, New); 3768 3769 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3770 if (New->getStorageClass() == SC_Static && 3771 !New->isStaticDataMember() && 3772 Old->hasExternalFormalLinkage()) { 3773 if (getLangOpts().MicrosoftExt) { 3774 Diag(New->getLocation(), diag::ext_static_non_static) 3775 << New->getDeclName(); 3776 Diag(OldLocation, PrevDiag); 3777 } else { 3778 Diag(New->getLocation(), diag::err_static_non_static) 3779 << New->getDeclName(); 3780 Diag(OldLocation, PrevDiag); 3781 return New->setInvalidDecl(); 3782 } 3783 } 3784 // C99 6.2.2p4: 3785 // For an identifier declared with the storage-class specifier 3786 // extern in a scope in which a prior declaration of that 3787 // identifier is visible,23) if the prior declaration specifies 3788 // internal or external linkage, the linkage of the identifier at 3789 // the later declaration is the same as the linkage specified at 3790 // the prior declaration. If no prior declaration is visible, or 3791 // if the prior declaration specifies no linkage, then the 3792 // identifier has external linkage. 3793 if (New->hasExternalStorage() && Old->hasLinkage()) 3794 /* Okay */; 3795 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3796 !New->isStaticDataMember() && 3797 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3798 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3799 Diag(OldLocation, PrevDiag); 3800 return New->setInvalidDecl(); 3801 } 3802 3803 // Check if extern is followed by non-extern and vice-versa. 3804 if (New->hasExternalStorage() && 3805 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3806 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3807 Diag(OldLocation, PrevDiag); 3808 return New->setInvalidDecl(); 3809 } 3810 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3811 !New->hasExternalStorage()) { 3812 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3813 Diag(OldLocation, PrevDiag); 3814 return New->setInvalidDecl(); 3815 } 3816 3817 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3818 3819 // FIXME: The test for external storage here seems wrong? We still 3820 // need to check for mismatches. 3821 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3822 // Don't complain about out-of-line definitions of static members. 3823 !(Old->getLexicalDeclContext()->isRecord() && 3824 !New->getLexicalDeclContext()->isRecord())) { 3825 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3826 Diag(OldLocation, PrevDiag); 3827 return New->setInvalidDecl(); 3828 } 3829 3830 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3831 if (VarDecl *Def = Old->getDefinition()) { 3832 // C++1z [dcl.fcn.spec]p4: 3833 // If the definition of a variable appears in a translation unit before 3834 // its first declaration as inline, the program is ill-formed. 3835 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3836 Diag(Def->getLocation(), diag::note_previous_definition); 3837 } 3838 } 3839 3840 // If this redeclaration makes the variable inline, we may need to add it to 3841 // UndefinedButUsed. 3842 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3843 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3844 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3845 SourceLocation())); 3846 3847 if (New->getTLSKind() != Old->getTLSKind()) { 3848 if (!Old->getTLSKind()) { 3849 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3850 Diag(OldLocation, PrevDiag); 3851 } else if (!New->getTLSKind()) { 3852 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3853 Diag(OldLocation, PrevDiag); 3854 } else { 3855 // Do not allow redeclaration to change the variable between requiring 3856 // static and dynamic initialization. 3857 // FIXME: GCC allows this, but uses the TLS keyword on the first 3858 // declaration to determine the kind. Do we need to be compatible here? 3859 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3860 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3861 Diag(OldLocation, PrevDiag); 3862 } 3863 } 3864 3865 // C++ doesn't have tentative definitions, so go right ahead and check here. 3866 if (getLangOpts().CPlusPlus && 3867 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3868 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3869 Old->getCanonicalDecl()->isConstexpr()) { 3870 // This definition won't be a definition any more once it's been merged. 3871 Diag(New->getLocation(), 3872 diag::warn_deprecated_redundant_constexpr_static_def); 3873 } else if (VarDecl *Def = Old->getDefinition()) { 3874 if (checkVarDeclRedefinition(Def, New)) 3875 return; 3876 } 3877 } 3878 3879 if (haveIncompatibleLanguageLinkages(Old, New)) { 3880 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3881 Diag(OldLocation, PrevDiag); 3882 New->setInvalidDecl(); 3883 return; 3884 } 3885 3886 // Merge "used" flag. 3887 if (Old->getMostRecentDecl()->isUsed(false)) 3888 New->setIsUsed(); 3889 3890 // Keep a chain of previous declarations. 3891 New->setPreviousDecl(Old); 3892 if (NewTemplate) 3893 NewTemplate->setPreviousDecl(OldTemplate); 3894 3895 // Inherit access appropriately. 3896 New->setAccess(Old->getAccess()); 3897 if (NewTemplate) 3898 NewTemplate->setAccess(New->getAccess()); 3899 3900 if (Old->isInline()) 3901 New->setImplicitlyInline(); 3902 } 3903 3904 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 3905 SourceManager &SrcMgr = getSourceManager(); 3906 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3907 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3908 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3909 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3910 auto &HSI = PP.getHeaderSearchInfo(); 3911 StringRef HdrFilename = 3912 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3913 3914 auto noteFromModuleOrInclude = [&](Module *Mod, 3915 SourceLocation IncLoc) -> bool { 3916 // Redefinition errors with modules are common with non modular mapped 3917 // headers, example: a non-modular header H in module A that also gets 3918 // included directly in a TU. Pointing twice to the same header/definition 3919 // is confusing, try to get better diagnostics when modules is on. 3920 if (IncLoc.isValid()) { 3921 if (Mod) { 3922 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3923 << HdrFilename.str() << Mod->getFullModuleName(); 3924 if (!Mod->DefinitionLoc.isInvalid()) 3925 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3926 << Mod->getFullModuleName(); 3927 } else { 3928 Diag(IncLoc, diag::note_redefinition_include_same_file) 3929 << HdrFilename.str(); 3930 } 3931 return true; 3932 } 3933 3934 return false; 3935 }; 3936 3937 // Is it the same file and same offset? Provide more information on why 3938 // this leads to a redefinition error. 3939 bool EmittedDiag = false; 3940 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3941 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3942 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3943 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 3944 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 3945 3946 // If the header has no guards, emit a note suggesting one. 3947 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3948 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 3949 3950 if (EmittedDiag) 3951 return; 3952 } 3953 3954 // Redefinition coming from different files or couldn't do better above. 3955 Diag(Old->getLocation(), diag::note_previous_definition); 3956 } 3957 3958 /// We've just determined that \p Old and \p New both appear to be definitions 3959 /// of the same variable. Either diagnose or fix the problem. 3960 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3961 if (!hasVisibleDefinition(Old) && 3962 (New->getFormalLinkage() == InternalLinkage || 3963 New->isInline() || 3964 New->getDescribedVarTemplate() || 3965 New->getNumTemplateParameterLists() || 3966 New->getDeclContext()->isDependentContext())) { 3967 // The previous definition is hidden, and multiple definitions are 3968 // permitted (in separate TUs). Demote this to a declaration. 3969 New->demoteThisDefinitionToDeclaration(); 3970 3971 // Make the canonical definition visible. 3972 if (auto *OldTD = Old->getDescribedVarTemplate()) 3973 makeMergedDefinitionVisible(OldTD); 3974 makeMergedDefinitionVisible(Old); 3975 return false; 3976 } else { 3977 Diag(New->getLocation(), diag::err_redefinition) << New; 3978 notePreviousDefinition(Old, New->getLocation()); 3979 New->setInvalidDecl(); 3980 return true; 3981 } 3982 } 3983 3984 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3985 /// no declarator (e.g. "struct foo;") is parsed. 3986 Decl * 3987 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3988 RecordDecl *&AnonRecord) { 3989 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3990 AnonRecord); 3991 } 3992 3993 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3994 // disambiguate entities defined in different scopes. 3995 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3996 // compatibility. 3997 // We will pick our mangling number depending on which version of MSVC is being 3998 // targeted. 3999 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4000 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4001 ? S->getMSCurManglingNumber() 4002 : S->getMSLastManglingNumber(); 4003 } 4004 4005 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4006 if (!Context.getLangOpts().CPlusPlus) 4007 return; 4008 4009 if (isa<CXXRecordDecl>(Tag->getParent())) { 4010 // If this tag is the direct child of a class, number it if 4011 // it is anonymous. 4012 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4013 return; 4014 MangleNumberingContext &MCtx = 4015 Context.getManglingNumberContext(Tag->getParent()); 4016 Context.setManglingNumber( 4017 Tag, MCtx.getManglingNumber( 4018 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4019 return; 4020 } 4021 4022 // If this tag isn't a direct child of a class, number it if it is local. 4023 Decl *ManglingContextDecl; 4024 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4025 Tag->getDeclContext(), ManglingContextDecl)) { 4026 Context.setManglingNumber( 4027 Tag, MCtx->getManglingNumber( 4028 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4029 } 4030 } 4031 4032 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4033 TypedefNameDecl *NewTD) { 4034 if (TagFromDeclSpec->isInvalidDecl()) 4035 return; 4036 4037 // Do nothing if the tag already has a name for linkage purposes. 4038 if (TagFromDeclSpec->hasNameForLinkage()) 4039 return; 4040 4041 // A well-formed anonymous tag must always be a TUK_Definition. 4042 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4043 4044 // The type must match the tag exactly; no qualifiers allowed. 4045 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4046 Context.getTagDeclType(TagFromDeclSpec))) { 4047 if (getLangOpts().CPlusPlus) 4048 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4049 return; 4050 } 4051 4052 // If we've already computed linkage for the anonymous tag, then 4053 // adding a typedef name for the anonymous decl can change that 4054 // linkage, which might be a serious problem. Diagnose this as 4055 // unsupported and ignore the typedef name. TODO: we should 4056 // pursue this as a language defect and establish a formal rule 4057 // for how to handle it. 4058 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4059 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4060 4061 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4062 tagLoc = getLocForEndOfToken(tagLoc); 4063 4064 llvm::SmallString<40> textToInsert; 4065 textToInsert += ' '; 4066 textToInsert += NewTD->getIdentifier()->getName(); 4067 Diag(tagLoc, diag::note_typedef_changes_linkage) 4068 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4069 return; 4070 } 4071 4072 // Otherwise, set this is the anon-decl typedef for the tag. 4073 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4074 } 4075 4076 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4077 switch (T) { 4078 case DeclSpec::TST_class: 4079 return 0; 4080 case DeclSpec::TST_struct: 4081 return 1; 4082 case DeclSpec::TST_interface: 4083 return 2; 4084 case DeclSpec::TST_union: 4085 return 3; 4086 case DeclSpec::TST_enum: 4087 return 4; 4088 default: 4089 llvm_unreachable("unexpected type specifier"); 4090 } 4091 } 4092 4093 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4094 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4095 /// parameters to cope with template friend declarations. 4096 Decl * 4097 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4098 MultiTemplateParamsArg TemplateParams, 4099 bool IsExplicitInstantiation, 4100 RecordDecl *&AnonRecord) { 4101 Decl *TagD = nullptr; 4102 TagDecl *Tag = nullptr; 4103 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4104 DS.getTypeSpecType() == DeclSpec::TST_struct || 4105 DS.getTypeSpecType() == DeclSpec::TST_interface || 4106 DS.getTypeSpecType() == DeclSpec::TST_union || 4107 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4108 TagD = DS.getRepAsDecl(); 4109 4110 if (!TagD) // We probably had an error 4111 return nullptr; 4112 4113 // Note that the above type specs guarantee that the 4114 // type rep is a Decl, whereas in many of the others 4115 // it's a Type. 4116 if (isa<TagDecl>(TagD)) 4117 Tag = cast<TagDecl>(TagD); 4118 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4119 Tag = CTD->getTemplatedDecl(); 4120 } 4121 4122 if (Tag) { 4123 handleTagNumbering(Tag, S); 4124 Tag->setFreeStanding(); 4125 if (Tag->isInvalidDecl()) 4126 return Tag; 4127 } 4128 4129 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4130 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4131 // or incomplete types shall not be restrict-qualified." 4132 if (TypeQuals & DeclSpec::TQ_restrict) 4133 Diag(DS.getRestrictSpecLoc(), 4134 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4135 << DS.getSourceRange(); 4136 } 4137 4138 if (DS.isInlineSpecified()) 4139 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4140 << getLangOpts().CPlusPlus1z; 4141 4142 if (DS.isConstexprSpecified()) { 4143 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4144 // and definitions of functions and variables. 4145 if (Tag) 4146 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4147 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4148 else 4149 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4150 // Don't emit warnings after this error. 4151 return TagD; 4152 } 4153 4154 if (DS.isConceptSpecified()) { 4155 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4156 // either a function concept and its definition or a variable concept and 4157 // its initializer. 4158 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4159 return TagD; 4160 } 4161 4162 DiagnoseFunctionSpecifiers(DS); 4163 4164 if (DS.isFriendSpecified()) { 4165 // If we're dealing with a decl but not a TagDecl, assume that 4166 // whatever routines created it handled the friendship aspect. 4167 if (TagD && !Tag) 4168 return nullptr; 4169 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4170 } 4171 4172 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4173 bool IsExplicitSpecialization = 4174 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4175 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4176 !IsExplicitInstantiation && !IsExplicitSpecialization && 4177 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4178 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4179 // nested-name-specifier unless it is an explicit instantiation 4180 // or an explicit specialization. 4181 // 4182 // FIXME: We allow class template partial specializations here too, per the 4183 // obvious intent of DR1819. 4184 // 4185 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4186 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4187 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4188 return nullptr; 4189 } 4190 4191 // Track whether this decl-specifier declares anything. 4192 bool DeclaresAnything = true; 4193 4194 // Handle anonymous struct definitions. 4195 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4196 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4197 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4198 if (getLangOpts().CPlusPlus || 4199 Record->getDeclContext()->isRecord()) { 4200 // If CurContext is a DeclContext that can contain statements, 4201 // RecursiveASTVisitor won't visit the decls that 4202 // BuildAnonymousStructOrUnion() will put into CurContext. 4203 // Also store them here so that they can be part of the 4204 // DeclStmt that gets created in this case. 4205 // FIXME: Also return the IndirectFieldDecls created by 4206 // BuildAnonymousStructOr union, for the same reason? 4207 if (CurContext->isFunctionOrMethod()) 4208 AnonRecord = Record; 4209 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4210 Context.getPrintingPolicy()); 4211 } 4212 4213 DeclaresAnything = false; 4214 } 4215 } 4216 4217 // C11 6.7.2.1p2: 4218 // A struct-declaration that does not declare an anonymous structure or 4219 // anonymous union shall contain a struct-declarator-list. 4220 // 4221 // This rule also existed in C89 and C99; the grammar for struct-declaration 4222 // did not permit a struct-declaration without a struct-declarator-list. 4223 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4224 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4225 // Check for Microsoft C extension: anonymous struct/union member. 4226 // Handle 2 kinds of anonymous struct/union: 4227 // struct STRUCT; 4228 // union UNION; 4229 // and 4230 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4231 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4232 if ((Tag && Tag->getDeclName()) || 4233 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4234 RecordDecl *Record = nullptr; 4235 if (Tag) 4236 Record = dyn_cast<RecordDecl>(Tag); 4237 else if (const RecordType *RT = 4238 DS.getRepAsType().get()->getAsStructureType()) 4239 Record = RT->getDecl(); 4240 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4241 Record = UT->getDecl(); 4242 4243 if (Record && getLangOpts().MicrosoftExt) { 4244 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4245 << Record->isUnion() << DS.getSourceRange(); 4246 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4247 } 4248 4249 DeclaresAnything = false; 4250 } 4251 } 4252 4253 // Skip all the checks below if we have a type error. 4254 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4255 (TagD && TagD->isInvalidDecl())) 4256 return TagD; 4257 4258 if (getLangOpts().CPlusPlus && 4259 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4260 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4261 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4262 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4263 DeclaresAnything = false; 4264 4265 if (!DS.isMissingDeclaratorOk()) { 4266 // Customize diagnostic for a typedef missing a name. 4267 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4268 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4269 << DS.getSourceRange(); 4270 else 4271 DeclaresAnything = false; 4272 } 4273 4274 if (DS.isModulePrivateSpecified() && 4275 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4276 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4277 << Tag->getTagKind() 4278 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4279 4280 ActOnDocumentableDecl(TagD); 4281 4282 // C 6.7/2: 4283 // A declaration [...] shall declare at least a declarator [...], a tag, 4284 // or the members of an enumeration. 4285 // C++ [dcl.dcl]p3: 4286 // [If there are no declarators], and except for the declaration of an 4287 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4288 // names into the program, or shall redeclare a name introduced by a 4289 // previous declaration. 4290 if (!DeclaresAnything) { 4291 // In C, we allow this as a (popular) extension / bug. Don't bother 4292 // producing further diagnostics for redundant qualifiers after this. 4293 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4294 return TagD; 4295 } 4296 4297 // C++ [dcl.stc]p1: 4298 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4299 // init-declarator-list of the declaration shall not be empty. 4300 // C++ [dcl.fct.spec]p1: 4301 // If a cv-qualifier appears in a decl-specifier-seq, the 4302 // init-declarator-list of the declaration shall not be empty. 4303 // 4304 // Spurious qualifiers here appear to be valid in C. 4305 unsigned DiagID = diag::warn_standalone_specifier; 4306 if (getLangOpts().CPlusPlus) 4307 DiagID = diag::ext_standalone_specifier; 4308 4309 // Note that a linkage-specification sets a storage class, but 4310 // 'extern "C" struct foo;' is actually valid and not theoretically 4311 // useless. 4312 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4313 if (SCS == DeclSpec::SCS_mutable) 4314 // Since mutable is not a viable storage class specifier in C, there is 4315 // no reason to treat it as an extension. Instead, diagnose as an error. 4316 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4317 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4318 Diag(DS.getStorageClassSpecLoc(), DiagID) 4319 << DeclSpec::getSpecifierName(SCS); 4320 } 4321 4322 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4323 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4324 << DeclSpec::getSpecifierName(TSCS); 4325 if (DS.getTypeQualifiers()) { 4326 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4327 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4328 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4329 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4330 // Restrict is covered above. 4331 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4332 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4333 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4334 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4335 } 4336 4337 // Warn about ignored type attributes, for example: 4338 // __attribute__((aligned)) struct A; 4339 // Attributes should be placed after tag to apply to type declaration. 4340 if (!DS.getAttributes().empty()) { 4341 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4342 if (TypeSpecType == DeclSpec::TST_class || 4343 TypeSpecType == DeclSpec::TST_struct || 4344 TypeSpecType == DeclSpec::TST_interface || 4345 TypeSpecType == DeclSpec::TST_union || 4346 TypeSpecType == DeclSpec::TST_enum) { 4347 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4348 attrs = attrs->getNext()) 4349 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4350 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4351 } 4352 } 4353 4354 return TagD; 4355 } 4356 4357 /// We are trying to inject an anonymous member into the given scope; 4358 /// check if there's an existing declaration that can't be overloaded. 4359 /// 4360 /// \return true if this is a forbidden redeclaration 4361 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4362 Scope *S, 4363 DeclContext *Owner, 4364 DeclarationName Name, 4365 SourceLocation NameLoc, 4366 bool IsUnion) { 4367 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4368 Sema::ForRedeclaration); 4369 if (!SemaRef.LookupName(R, S)) return false; 4370 4371 // Pick a representative declaration. 4372 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4373 assert(PrevDecl && "Expected a non-null Decl"); 4374 4375 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4376 return false; 4377 4378 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4379 << IsUnion << Name; 4380 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4381 4382 return true; 4383 } 4384 4385 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4386 /// anonymous struct or union AnonRecord into the owning context Owner 4387 /// and scope S. This routine will be invoked just after we realize 4388 /// that an unnamed union or struct is actually an anonymous union or 4389 /// struct, e.g., 4390 /// 4391 /// @code 4392 /// union { 4393 /// int i; 4394 /// float f; 4395 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4396 /// // f into the surrounding scope.x 4397 /// @endcode 4398 /// 4399 /// This routine is recursive, injecting the names of nested anonymous 4400 /// structs/unions into the owning context and scope as well. 4401 static bool 4402 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4403 RecordDecl *AnonRecord, AccessSpecifier AS, 4404 SmallVectorImpl<NamedDecl *> &Chaining) { 4405 bool Invalid = false; 4406 4407 // Look every FieldDecl and IndirectFieldDecl with a name. 4408 for (auto *D : AnonRecord->decls()) { 4409 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4410 cast<NamedDecl>(D)->getDeclName()) { 4411 ValueDecl *VD = cast<ValueDecl>(D); 4412 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4413 VD->getLocation(), 4414 AnonRecord->isUnion())) { 4415 // C++ [class.union]p2: 4416 // The names of the members of an anonymous union shall be 4417 // distinct from the names of any other entity in the 4418 // scope in which the anonymous union is declared. 4419 Invalid = true; 4420 } else { 4421 // C++ [class.union]p2: 4422 // For the purpose of name lookup, after the anonymous union 4423 // definition, the members of the anonymous union are 4424 // considered to have been defined in the scope in which the 4425 // anonymous union is declared. 4426 unsigned OldChainingSize = Chaining.size(); 4427 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4428 Chaining.append(IF->chain_begin(), IF->chain_end()); 4429 else 4430 Chaining.push_back(VD); 4431 4432 assert(Chaining.size() >= 2); 4433 NamedDecl **NamedChain = 4434 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4435 for (unsigned i = 0; i < Chaining.size(); i++) 4436 NamedChain[i] = Chaining[i]; 4437 4438 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4439 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4440 VD->getType(), {NamedChain, Chaining.size()}); 4441 4442 for (const auto *Attr : VD->attrs()) 4443 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4444 4445 IndirectField->setAccess(AS); 4446 IndirectField->setImplicit(); 4447 SemaRef.PushOnScopeChains(IndirectField, S); 4448 4449 // That includes picking up the appropriate access specifier. 4450 if (AS != AS_none) IndirectField->setAccess(AS); 4451 4452 Chaining.resize(OldChainingSize); 4453 } 4454 } 4455 } 4456 4457 return Invalid; 4458 } 4459 4460 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4461 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4462 /// illegal input values are mapped to SC_None. 4463 static StorageClass 4464 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4465 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4466 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4467 "Parser allowed 'typedef' as storage class VarDecl."); 4468 switch (StorageClassSpec) { 4469 case DeclSpec::SCS_unspecified: return SC_None; 4470 case DeclSpec::SCS_extern: 4471 if (DS.isExternInLinkageSpec()) 4472 return SC_None; 4473 return SC_Extern; 4474 case DeclSpec::SCS_static: return SC_Static; 4475 case DeclSpec::SCS_auto: return SC_Auto; 4476 case DeclSpec::SCS_register: return SC_Register; 4477 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4478 // Illegal SCSs map to None: error reporting is up to the caller. 4479 case DeclSpec::SCS_mutable: // Fall through. 4480 case DeclSpec::SCS_typedef: return SC_None; 4481 } 4482 llvm_unreachable("unknown storage class specifier"); 4483 } 4484 4485 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4486 assert(Record->hasInClassInitializer()); 4487 4488 for (const auto *I : Record->decls()) { 4489 const auto *FD = dyn_cast<FieldDecl>(I); 4490 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4491 FD = IFD->getAnonField(); 4492 if (FD && FD->hasInClassInitializer()) 4493 return FD->getLocation(); 4494 } 4495 4496 llvm_unreachable("couldn't find in-class initializer"); 4497 } 4498 4499 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4500 SourceLocation DefaultInitLoc) { 4501 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4502 return; 4503 4504 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4505 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4506 } 4507 4508 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4509 CXXRecordDecl *AnonUnion) { 4510 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4511 return; 4512 4513 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4514 } 4515 4516 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4517 /// anonymous structure or union. Anonymous unions are a C++ feature 4518 /// (C++ [class.union]) and a C11 feature; anonymous structures 4519 /// are a C11 feature and GNU C++ extension. 4520 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4521 AccessSpecifier AS, 4522 RecordDecl *Record, 4523 const PrintingPolicy &Policy) { 4524 DeclContext *Owner = Record->getDeclContext(); 4525 4526 // Diagnose whether this anonymous struct/union is an extension. 4527 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4528 Diag(Record->getLocation(), diag::ext_anonymous_union); 4529 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4530 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4531 else if (!Record->isUnion() && !getLangOpts().C11) 4532 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4533 4534 // C and C++ require different kinds of checks for anonymous 4535 // structs/unions. 4536 bool Invalid = false; 4537 if (getLangOpts().CPlusPlus) { 4538 const char *PrevSpec = nullptr; 4539 unsigned DiagID; 4540 if (Record->isUnion()) { 4541 // C++ [class.union]p6: 4542 // Anonymous unions declared in a named namespace or in the 4543 // global namespace shall be declared static. 4544 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4545 (isa<TranslationUnitDecl>(Owner) || 4546 (isa<NamespaceDecl>(Owner) && 4547 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4548 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4549 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4550 4551 // Recover by adding 'static'. 4552 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4553 PrevSpec, DiagID, Policy); 4554 } 4555 // C++ [class.union]p6: 4556 // A storage class is not allowed in a declaration of an 4557 // anonymous union in a class scope. 4558 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4559 isa<RecordDecl>(Owner)) { 4560 Diag(DS.getStorageClassSpecLoc(), 4561 diag::err_anonymous_union_with_storage_spec) 4562 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4563 4564 // Recover by removing the storage specifier. 4565 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4566 SourceLocation(), 4567 PrevSpec, DiagID, Context.getPrintingPolicy()); 4568 } 4569 } 4570 4571 // Ignore const/volatile/restrict qualifiers. 4572 if (DS.getTypeQualifiers()) { 4573 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4574 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4575 << Record->isUnion() << "const" 4576 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4577 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4578 Diag(DS.getVolatileSpecLoc(), 4579 diag::ext_anonymous_struct_union_qualified) 4580 << Record->isUnion() << "volatile" 4581 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4582 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4583 Diag(DS.getRestrictSpecLoc(), 4584 diag::ext_anonymous_struct_union_qualified) 4585 << Record->isUnion() << "restrict" 4586 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4587 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4588 Diag(DS.getAtomicSpecLoc(), 4589 diag::ext_anonymous_struct_union_qualified) 4590 << Record->isUnion() << "_Atomic" 4591 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4592 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4593 Diag(DS.getUnalignedSpecLoc(), 4594 diag::ext_anonymous_struct_union_qualified) 4595 << Record->isUnion() << "__unaligned" 4596 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4597 4598 DS.ClearTypeQualifiers(); 4599 } 4600 4601 // C++ [class.union]p2: 4602 // The member-specification of an anonymous union shall only 4603 // define non-static data members. [Note: nested types and 4604 // functions cannot be declared within an anonymous union. ] 4605 for (auto *Mem : Record->decls()) { 4606 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4607 // C++ [class.union]p3: 4608 // An anonymous union shall not have private or protected 4609 // members (clause 11). 4610 assert(FD->getAccess() != AS_none); 4611 if (FD->getAccess() != AS_public) { 4612 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4613 << Record->isUnion() << (FD->getAccess() == AS_protected); 4614 Invalid = true; 4615 } 4616 4617 // C++ [class.union]p1 4618 // An object of a class with a non-trivial constructor, a non-trivial 4619 // copy constructor, a non-trivial destructor, or a non-trivial copy 4620 // assignment operator cannot be a member of a union, nor can an 4621 // array of such objects. 4622 if (CheckNontrivialField(FD)) 4623 Invalid = true; 4624 } else if (Mem->isImplicit()) { 4625 // Any implicit members are fine. 4626 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4627 // This is a type that showed up in an 4628 // elaborated-type-specifier inside the anonymous struct or 4629 // union, but which actually declares a type outside of the 4630 // anonymous struct or union. It's okay. 4631 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4632 if (!MemRecord->isAnonymousStructOrUnion() && 4633 MemRecord->getDeclName()) { 4634 // Visual C++ allows type definition in anonymous struct or union. 4635 if (getLangOpts().MicrosoftExt) 4636 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4637 << Record->isUnion(); 4638 else { 4639 // This is a nested type declaration. 4640 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4641 << Record->isUnion(); 4642 Invalid = true; 4643 } 4644 } else { 4645 // This is an anonymous type definition within another anonymous type. 4646 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4647 // not part of standard C++. 4648 Diag(MemRecord->getLocation(), 4649 diag::ext_anonymous_record_with_anonymous_type) 4650 << Record->isUnion(); 4651 } 4652 } else if (isa<AccessSpecDecl>(Mem)) { 4653 // Any access specifier is fine. 4654 } else if (isa<StaticAssertDecl>(Mem)) { 4655 // In C++1z, static_assert declarations are also fine. 4656 } else { 4657 // We have something that isn't a non-static data 4658 // member. Complain about it. 4659 unsigned DK = diag::err_anonymous_record_bad_member; 4660 if (isa<TypeDecl>(Mem)) 4661 DK = diag::err_anonymous_record_with_type; 4662 else if (isa<FunctionDecl>(Mem)) 4663 DK = diag::err_anonymous_record_with_function; 4664 else if (isa<VarDecl>(Mem)) 4665 DK = diag::err_anonymous_record_with_static; 4666 4667 // Visual C++ allows type definition in anonymous struct or union. 4668 if (getLangOpts().MicrosoftExt && 4669 DK == diag::err_anonymous_record_with_type) 4670 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4671 << Record->isUnion(); 4672 else { 4673 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4674 Invalid = true; 4675 } 4676 } 4677 } 4678 4679 // C++11 [class.union]p8 (DR1460): 4680 // At most one variant member of a union may have a 4681 // brace-or-equal-initializer. 4682 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4683 Owner->isRecord()) 4684 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4685 cast<CXXRecordDecl>(Record)); 4686 } 4687 4688 if (!Record->isUnion() && !Owner->isRecord()) { 4689 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4690 << getLangOpts().CPlusPlus; 4691 Invalid = true; 4692 } 4693 4694 // Mock up a declarator. 4695 Declarator Dc(DS, Declarator::MemberContext); 4696 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4697 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4698 4699 // Create a declaration for this anonymous struct/union. 4700 NamedDecl *Anon = nullptr; 4701 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4702 Anon = FieldDecl::Create(Context, OwningClass, 4703 DS.getLocStart(), 4704 Record->getLocation(), 4705 /*IdentifierInfo=*/nullptr, 4706 Context.getTypeDeclType(Record), 4707 TInfo, 4708 /*BitWidth=*/nullptr, /*Mutable=*/false, 4709 /*InitStyle=*/ICIS_NoInit); 4710 Anon->setAccess(AS); 4711 if (getLangOpts().CPlusPlus) 4712 FieldCollector->Add(cast<FieldDecl>(Anon)); 4713 } else { 4714 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4715 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4716 if (SCSpec == DeclSpec::SCS_mutable) { 4717 // mutable can only appear on non-static class members, so it's always 4718 // an error here 4719 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4720 Invalid = true; 4721 SC = SC_None; 4722 } 4723 4724 Anon = VarDecl::Create(Context, Owner, 4725 DS.getLocStart(), 4726 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4727 Context.getTypeDeclType(Record), 4728 TInfo, SC); 4729 4730 // Default-initialize the implicit variable. This initialization will be 4731 // trivial in almost all cases, except if a union member has an in-class 4732 // initializer: 4733 // union { int n = 0; }; 4734 ActOnUninitializedDecl(Anon); 4735 } 4736 Anon->setImplicit(); 4737 4738 // Mark this as an anonymous struct/union type. 4739 Record->setAnonymousStructOrUnion(true); 4740 4741 // Add the anonymous struct/union object to the current 4742 // context. We'll be referencing this object when we refer to one of 4743 // its members. 4744 Owner->addDecl(Anon); 4745 4746 // Inject the members of the anonymous struct/union into the owning 4747 // context and into the identifier resolver chain for name lookup 4748 // purposes. 4749 SmallVector<NamedDecl*, 2> Chain; 4750 Chain.push_back(Anon); 4751 4752 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4753 Invalid = true; 4754 4755 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4756 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4757 Decl *ManglingContextDecl; 4758 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4759 NewVD->getDeclContext(), ManglingContextDecl)) { 4760 Context.setManglingNumber( 4761 NewVD, MCtx->getManglingNumber( 4762 NewVD, getMSManglingNumber(getLangOpts(), S))); 4763 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4764 } 4765 } 4766 } 4767 4768 if (Invalid) 4769 Anon->setInvalidDecl(); 4770 4771 return Anon; 4772 } 4773 4774 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4775 /// Microsoft C anonymous structure. 4776 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4777 /// Example: 4778 /// 4779 /// struct A { int a; }; 4780 /// struct B { struct A; int b; }; 4781 /// 4782 /// void foo() { 4783 /// B var; 4784 /// var.a = 3; 4785 /// } 4786 /// 4787 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4788 RecordDecl *Record) { 4789 assert(Record && "expected a record!"); 4790 4791 // Mock up a declarator. 4792 Declarator Dc(DS, Declarator::TypeNameContext); 4793 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4794 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4795 4796 auto *ParentDecl = cast<RecordDecl>(CurContext); 4797 QualType RecTy = Context.getTypeDeclType(Record); 4798 4799 // Create a declaration for this anonymous struct. 4800 NamedDecl *Anon = FieldDecl::Create(Context, 4801 ParentDecl, 4802 DS.getLocStart(), 4803 DS.getLocStart(), 4804 /*IdentifierInfo=*/nullptr, 4805 RecTy, 4806 TInfo, 4807 /*BitWidth=*/nullptr, /*Mutable=*/false, 4808 /*InitStyle=*/ICIS_NoInit); 4809 Anon->setImplicit(); 4810 4811 // Add the anonymous struct object to the current context. 4812 CurContext->addDecl(Anon); 4813 4814 // Inject the members of the anonymous struct into the current 4815 // context and into the identifier resolver chain for name lookup 4816 // purposes. 4817 SmallVector<NamedDecl*, 2> Chain; 4818 Chain.push_back(Anon); 4819 4820 RecordDecl *RecordDef = Record->getDefinition(); 4821 if (RequireCompleteType(Anon->getLocation(), RecTy, 4822 diag::err_field_incomplete) || 4823 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4824 AS_none, Chain)) { 4825 Anon->setInvalidDecl(); 4826 ParentDecl->setInvalidDecl(); 4827 } 4828 4829 return Anon; 4830 } 4831 4832 /// GetNameForDeclarator - Determine the full declaration name for the 4833 /// given Declarator. 4834 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4835 return GetNameFromUnqualifiedId(D.getName()); 4836 } 4837 4838 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4839 DeclarationNameInfo 4840 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4841 DeclarationNameInfo NameInfo; 4842 NameInfo.setLoc(Name.StartLocation); 4843 4844 switch (Name.getKind()) { 4845 4846 case UnqualifiedId::IK_ImplicitSelfParam: 4847 case UnqualifiedId::IK_Identifier: 4848 NameInfo.setName(Name.Identifier); 4849 NameInfo.setLoc(Name.StartLocation); 4850 return NameInfo; 4851 4852 case UnqualifiedId::IK_DeductionGuideName: { 4853 // C++ [temp.deduct.guide]p3: 4854 // The simple-template-id shall name a class template specialization. 4855 // The template-name shall be the same identifier as the template-name 4856 // of the simple-template-id. 4857 // These together intend to imply that the template-name shall name a 4858 // class template. 4859 // FIXME: template<typename T> struct X {}; 4860 // template<typename T> using Y = X<T>; 4861 // Y(int) -> Y<int>; 4862 // satisfies these rules but does not name a class template. 4863 TemplateName TN = Name.TemplateName.get().get(); 4864 auto *Template = TN.getAsTemplateDecl(); 4865 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4866 Diag(Name.StartLocation, 4867 diag::err_deduction_guide_name_not_class_template) 4868 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4869 if (Template) 4870 Diag(Template->getLocation(), diag::note_template_decl_here); 4871 return DeclarationNameInfo(); 4872 } 4873 4874 NameInfo.setName( 4875 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4876 NameInfo.setLoc(Name.StartLocation); 4877 return NameInfo; 4878 } 4879 4880 case UnqualifiedId::IK_OperatorFunctionId: 4881 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4882 Name.OperatorFunctionId.Operator)); 4883 NameInfo.setLoc(Name.StartLocation); 4884 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4885 = Name.OperatorFunctionId.SymbolLocations[0]; 4886 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4887 = Name.EndLocation.getRawEncoding(); 4888 return NameInfo; 4889 4890 case UnqualifiedId::IK_LiteralOperatorId: 4891 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4892 Name.Identifier)); 4893 NameInfo.setLoc(Name.StartLocation); 4894 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4895 return NameInfo; 4896 4897 case UnqualifiedId::IK_ConversionFunctionId: { 4898 TypeSourceInfo *TInfo; 4899 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4900 if (Ty.isNull()) 4901 return DeclarationNameInfo(); 4902 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4903 Context.getCanonicalType(Ty))); 4904 NameInfo.setLoc(Name.StartLocation); 4905 NameInfo.setNamedTypeInfo(TInfo); 4906 return NameInfo; 4907 } 4908 4909 case UnqualifiedId::IK_ConstructorName: { 4910 TypeSourceInfo *TInfo; 4911 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4912 if (Ty.isNull()) 4913 return DeclarationNameInfo(); 4914 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4915 Context.getCanonicalType(Ty))); 4916 NameInfo.setLoc(Name.StartLocation); 4917 NameInfo.setNamedTypeInfo(TInfo); 4918 return NameInfo; 4919 } 4920 4921 case UnqualifiedId::IK_ConstructorTemplateId: { 4922 // In well-formed code, we can only have a constructor 4923 // template-id that refers to the current context, so go there 4924 // to find the actual type being constructed. 4925 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4926 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4927 return DeclarationNameInfo(); 4928 4929 // Determine the type of the class being constructed. 4930 QualType CurClassType = Context.getTypeDeclType(CurClass); 4931 4932 // FIXME: Check two things: that the template-id names the same type as 4933 // CurClassType, and that the template-id does not occur when the name 4934 // was qualified. 4935 4936 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4937 Context.getCanonicalType(CurClassType))); 4938 NameInfo.setLoc(Name.StartLocation); 4939 // FIXME: should we retrieve TypeSourceInfo? 4940 NameInfo.setNamedTypeInfo(nullptr); 4941 return NameInfo; 4942 } 4943 4944 case UnqualifiedId::IK_DestructorName: { 4945 TypeSourceInfo *TInfo; 4946 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4947 if (Ty.isNull()) 4948 return DeclarationNameInfo(); 4949 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4950 Context.getCanonicalType(Ty))); 4951 NameInfo.setLoc(Name.StartLocation); 4952 NameInfo.setNamedTypeInfo(TInfo); 4953 return NameInfo; 4954 } 4955 4956 case UnqualifiedId::IK_TemplateId: { 4957 TemplateName TName = Name.TemplateId->Template.get(); 4958 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4959 return Context.getNameForTemplate(TName, TNameLoc); 4960 } 4961 4962 } // switch (Name.getKind()) 4963 4964 llvm_unreachable("Unknown name kind"); 4965 } 4966 4967 static QualType getCoreType(QualType Ty) { 4968 do { 4969 if (Ty->isPointerType() || Ty->isReferenceType()) 4970 Ty = Ty->getPointeeType(); 4971 else if (Ty->isArrayType()) 4972 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4973 else 4974 return Ty.withoutLocalFastQualifiers(); 4975 } while (true); 4976 } 4977 4978 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4979 /// and Definition have "nearly" matching parameters. This heuristic is 4980 /// used to improve diagnostics in the case where an out-of-line function 4981 /// definition doesn't match any declaration within the class or namespace. 4982 /// Also sets Params to the list of indices to the parameters that differ 4983 /// between the declaration and the definition. If hasSimilarParameters 4984 /// returns true and Params is empty, then all of the parameters match. 4985 static bool hasSimilarParameters(ASTContext &Context, 4986 FunctionDecl *Declaration, 4987 FunctionDecl *Definition, 4988 SmallVectorImpl<unsigned> &Params) { 4989 Params.clear(); 4990 if (Declaration->param_size() != Definition->param_size()) 4991 return false; 4992 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4993 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4994 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4995 4996 // The parameter types are identical 4997 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4998 continue; 4999 5000 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5001 QualType DefParamBaseTy = getCoreType(DefParamTy); 5002 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5003 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5004 5005 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5006 (DeclTyName && DeclTyName == DefTyName)) 5007 Params.push_back(Idx); 5008 else // The two parameters aren't even close 5009 return false; 5010 } 5011 5012 return true; 5013 } 5014 5015 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5016 /// declarator needs to be rebuilt in the current instantiation. 5017 /// Any bits of declarator which appear before the name are valid for 5018 /// consideration here. That's specifically the type in the decl spec 5019 /// and the base type in any member-pointer chunks. 5020 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5021 DeclarationName Name) { 5022 // The types we specifically need to rebuild are: 5023 // - typenames, typeofs, and decltypes 5024 // - types which will become injected class names 5025 // Of course, we also need to rebuild any type referencing such a 5026 // type. It's safest to just say "dependent", but we call out a 5027 // few cases here. 5028 5029 DeclSpec &DS = D.getMutableDeclSpec(); 5030 switch (DS.getTypeSpecType()) { 5031 case DeclSpec::TST_typename: 5032 case DeclSpec::TST_typeofType: 5033 case DeclSpec::TST_underlyingType: 5034 case DeclSpec::TST_atomic: { 5035 // Grab the type from the parser. 5036 TypeSourceInfo *TSI = nullptr; 5037 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5038 if (T.isNull() || !T->isDependentType()) break; 5039 5040 // Make sure there's a type source info. This isn't really much 5041 // of a waste; most dependent types should have type source info 5042 // attached already. 5043 if (!TSI) 5044 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5045 5046 // Rebuild the type in the current instantiation. 5047 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5048 if (!TSI) return true; 5049 5050 // Store the new type back in the decl spec. 5051 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5052 DS.UpdateTypeRep(LocType); 5053 break; 5054 } 5055 5056 case DeclSpec::TST_decltype: 5057 case DeclSpec::TST_typeofExpr: { 5058 Expr *E = DS.getRepAsExpr(); 5059 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5060 if (Result.isInvalid()) return true; 5061 DS.UpdateExprRep(Result.get()); 5062 break; 5063 } 5064 5065 default: 5066 // Nothing to do for these decl specs. 5067 break; 5068 } 5069 5070 // It doesn't matter what order we do this in. 5071 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5072 DeclaratorChunk &Chunk = D.getTypeObject(I); 5073 5074 // The only type information in the declarator which can come 5075 // before the declaration name is the base type of a member 5076 // pointer. 5077 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5078 continue; 5079 5080 // Rebuild the scope specifier in-place. 5081 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5082 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5083 return true; 5084 } 5085 5086 return false; 5087 } 5088 5089 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5090 D.setFunctionDefinitionKind(FDK_Declaration); 5091 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5092 5093 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5094 Dcl && Dcl->getDeclContext()->isFileContext()) 5095 Dcl->setTopLevelDeclInObjCContainer(); 5096 5097 if (getLangOpts().OpenCL) 5098 setCurrentOpenCLExtensionForDecl(Dcl); 5099 5100 return Dcl; 5101 } 5102 5103 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5104 /// If T is the name of a class, then each of the following shall have a 5105 /// name different from T: 5106 /// - every static data member of class T; 5107 /// - every member function of class T 5108 /// - every member of class T that is itself a type; 5109 /// \returns true if the declaration name violates these rules. 5110 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5111 DeclarationNameInfo NameInfo) { 5112 DeclarationName Name = NameInfo.getName(); 5113 5114 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5115 while (Record && Record->isAnonymousStructOrUnion()) 5116 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5117 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5118 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5119 return true; 5120 } 5121 5122 return false; 5123 } 5124 5125 /// \brief Diagnose a declaration whose declarator-id has the given 5126 /// nested-name-specifier. 5127 /// 5128 /// \param SS The nested-name-specifier of the declarator-id. 5129 /// 5130 /// \param DC The declaration context to which the nested-name-specifier 5131 /// resolves. 5132 /// 5133 /// \param Name The name of the entity being declared. 5134 /// 5135 /// \param Loc The location of the name of the entity being declared. 5136 /// 5137 /// \returns true if we cannot safely recover from this error, false otherwise. 5138 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5139 DeclarationName Name, 5140 SourceLocation Loc) { 5141 DeclContext *Cur = CurContext; 5142 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5143 Cur = Cur->getParent(); 5144 5145 // If the user provided a superfluous scope specifier that refers back to the 5146 // class in which the entity is already declared, diagnose and ignore it. 5147 // 5148 // class X { 5149 // void X::f(); 5150 // }; 5151 // 5152 // Note, it was once ill-formed to give redundant qualification in all 5153 // contexts, but that rule was removed by DR482. 5154 if (Cur->Equals(DC)) { 5155 if (Cur->isRecord()) { 5156 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5157 : diag::err_member_extra_qualification) 5158 << Name << FixItHint::CreateRemoval(SS.getRange()); 5159 SS.clear(); 5160 } else { 5161 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5162 } 5163 return false; 5164 } 5165 5166 // Check whether the qualifying scope encloses the scope of the original 5167 // declaration. 5168 if (!Cur->Encloses(DC)) { 5169 if (Cur->isRecord()) 5170 Diag(Loc, diag::err_member_qualification) 5171 << Name << SS.getRange(); 5172 else if (isa<TranslationUnitDecl>(DC)) 5173 Diag(Loc, diag::err_invalid_declarator_global_scope) 5174 << Name << SS.getRange(); 5175 else if (isa<FunctionDecl>(Cur)) 5176 Diag(Loc, diag::err_invalid_declarator_in_function) 5177 << Name << SS.getRange(); 5178 else if (isa<BlockDecl>(Cur)) 5179 Diag(Loc, diag::err_invalid_declarator_in_block) 5180 << Name << SS.getRange(); 5181 else 5182 Diag(Loc, diag::err_invalid_declarator_scope) 5183 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5184 5185 return true; 5186 } 5187 5188 if (Cur->isRecord()) { 5189 // Cannot qualify members within a class. 5190 Diag(Loc, diag::err_member_qualification) 5191 << Name << SS.getRange(); 5192 SS.clear(); 5193 5194 // C++ constructors and destructors with incorrect scopes can break 5195 // our AST invariants by having the wrong underlying types. If 5196 // that's the case, then drop this declaration entirely. 5197 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5198 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5199 !Context.hasSameType(Name.getCXXNameType(), 5200 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5201 return true; 5202 5203 return false; 5204 } 5205 5206 // C++11 [dcl.meaning]p1: 5207 // [...] "The nested-name-specifier of the qualified declarator-id shall 5208 // not begin with a decltype-specifer" 5209 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5210 while (SpecLoc.getPrefix()) 5211 SpecLoc = SpecLoc.getPrefix(); 5212 if (dyn_cast_or_null<DecltypeType>( 5213 SpecLoc.getNestedNameSpecifier()->getAsType())) 5214 Diag(Loc, diag::err_decltype_in_declarator) 5215 << SpecLoc.getTypeLoc().getSourceRange(); 5216 5217 return false; 5218 } 5219 5220 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5221 MultiTemplateParamsArg TemplateParamLists) { 5222 // TODO: consider using NameInfo for diagnostic. 5223 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5224 DeclarationName Name = NameInfo.getName(); 5225 5226 // All of these full declarators require an identifier. If it doesn't have 5227 // one, the ParsedFreeStandingDeclSpec action should be used. 5228 if (D.isDecompositionDeclarator()) { 5229 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5230 } else if (!Name) { 5231 if (!D.isInvalidType()) // Reject this if we think it is valid. 5232 Diag(D.getDeclSpec().getLocStart(), 5233 diag::err_declarator_need_ident) 5234 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5235 return nullptr; 5236 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5237 return nullptr; 5238 5239 // The scope passed in may not be a decl scope. Zip up the scope tree until 5240 // we find one that is. 5241 while ((S->getFlags() & Scope::DeclScope) == 0 || 5242 (S->getFlags() & Scope::TemplateParamScope) != 0) 5243 S = S->getParent(); 5244 5245 DeclContext *DC = CurContext; 5246 if (D.getCXXScopeSpec().isInvalid()) 5247 D.setInvalidType(); 5248 else if (D.getCXXScopeSpec().isSet()) { 5249 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5250 UPPC_DeclarationQualifier)) 5251 return nullptr; 5252 5253 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5254 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5255 if (!DC || isa<EnumDecl>(DC)) { 5256 // If we could not compute the declaration context, it's because the 5257 // declaration context is dependent but does not refer to a class, 5258 // class template, or class template partial specialization. Complain 5259 // and return early, to avoid the coming semantic disaster. 5260 Diag(D.getIdentifierLoc(), 5261 diag::err_template_qualified_declarator_no_match) 5262 << D.getCXXScopeSpec().getScopeRep() 5263 << D.getCXXScopeSpec().getRange(); 5264 return nullptr; 5265 } 5266 bool IsDependentContext = DC->isDependentContext(); 5267 5268 if (!IsDependentContext && 5269 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5270 return nullptr; 5271 5272 // If a class is incomplete, do not parse entities inside it. 5273 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5274 Diag(D.getIdentifierLoc(), 5275 diag::err_member_def_undefined_record) 5276 << Name << DC << D.getCXXScopeSpec().getRange(); 5277 return nullptr; 5278 } 5279 if (!D.getDeclSpec().isFriendSpecified()) { 5280 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5281 Name, D.getIdentifierLoc())) { 5282 if (DC->isRecord()) 5283 return nullptr; 5284 5285 D.setInvalidType(); 5286 } 5287 } 5288 5289 // Check whether we need to rebuild the type of the given 5290 // declaration in the current instantiation. 5291 if (EnteringContext && IsDependentContext && 5292 TemplateParamLists.size() != 0) { 5293 ContextRAII SavedContext(*this, DC); 5294 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5295 D.setInvalidType(); 5296 } 5297 } 5298 5299 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5300 QualType R = TInfo->getType(); 5301 5302 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5303 UPPC_DeclarationType)) 5304 D.setInvalidType(); 5305 5306 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5307 ForRedeclaration); 5308 5309 // See if this is a redefinition of a variable in the same scope. 5310 if (!D.getCXXScopeSpec().isSet()) { 5311 bool IsLinkageLookup = false; 5312 bool CreateBuiltins = false; 5313 5314 // If the declaration we're planning to build will be a function 5315 // or object with linkage, then look for another declaration with 5316 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5317 // 5318 // If the declaration we're planning to build will be declared with 5319 // external linkage in the translation unit, create any builtin with 5320 // the same name. 5321 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5322 /* Do nothing*/; 5323 else if (CurContext->isFunctionOrMethod() && 5324 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5325 R->isFunctionType())) { 5326 IsLinkageLookup = true; 5327 CreateBuiltins = 5328 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5329 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5330 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5331 CreateBuiltins = true; 5332 5333 if (IsLinkageLookup) 5334 Previous.clear(LookupRedeclarationWithLinkage); 5335 5336 LookupName(Previous, S, CreateBuiltins); 5337 } else { // Something like "int foo::x;" 5338 LookupQualifiedName(Previous, DC); 5339 5340 // C++ [dcl.meaning]p1: 5341 // When the declarator-id is qualified, the declaration shall refer to a 5342 // previously declared member of the class or namespace to which the 5343 // qualifier refers (or, in the case of a namespace, of an element of the 5344 // inline namespace set of that namespace (7.3.1)) or to a specialization 5345 // thereof; [...] 5346 // 5347 // Note that we already checked the context above, and that we do not have 5348 // enough information to make sure that Previous contains the declaration 5349 // we want to match. For example, given: 5350 // 5351 // class X { 5352 // void f(); 5353 // void f(float); 5354 // }; 5355 // 5356 // void X::f(int) { } // ill-formed 5357 // 5358 // In this case, Previous will point to the overload set 5359 // containing the two f's declared in X, but neither of them 5360 // matches. 5361 5362 // C++ [dcl.meaning]p1: 5363 // [...] the member shall not merely have been introduced by a 5364 // using-declaration in the scope of the class or namespace nominated by 5365 // the nested-name-specifier of the declarator-id. 5366 RemoveUsingDecls(Previous); 5367 } 5368 5369 if (Previous.isSingleResult() && 5370 Previous.getFoundDecl()->isTemplateParameter()) { 5371 // Maybe we will complain about the shadowed template parameter. 5372 if (!D.isInvalidType()) 5373 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5374 Previous.getFoundDecl()); 5375 5376 // Just pretend that we didn't see the previous declaration. 5377 Previous.clear(); 5378 } 5379 5380 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5381 // Forget that the previous declaration is the injected-class-name. 5382 Previous.clear(); 5383 5384 // In C++, the previous declaration we find might be a tag type 5385 // (class or enum). In this case, the new declaration will hide the 5386 // tag type. Note that this applies to functions, function templates, and 5387 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5388 if (Previous.isSingleTagDecl() && 5389 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5390 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5391 Previous.clear(); 5392 5393 // Check that there are no default arguments other than in the parameters 5394 // of a function declaration (C++ only). 5395 if (getLangOpts().CPlusPlus) 5396 CheckExtraCXXDefaultArguments(D); 5397 5398 if (D.getDeclSpec().isConceptSpecified()) { 5399 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5400 // applied only to the definition of a function template or variable 5401 // template, declared in namespace scope 5402 if (!TemplateParamLists.size()) { 5403 Diag(D.getDeclSpec().getConceptSpecLoc(), 5404 diag:: err_concept_wrong_decl_kind); 5405 return nullptr; 5406 } 5407 5408 if (!DC->getRedeclContext()->isFileContext()) { 5409 Diag(D.getIdentifierLoc(), 5410 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5411 return nullptr; 5412 } 5413 } 5414 5415 NamedDecl *New; 5416 5417 bool AddToScope = true; 5418 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5419 if (TemplateParamLists.size()) { 5420 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5421 return nullptr; 5422 } 5423 5424 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5425 } else if (R->isFunctionType()) { 5426 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5427 TemplateParamLists, 5428 AddToScope); 5429 } else { 5430 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5431 AddToScope); 5432 } 5433 5434 if (!New) 5435 return nullptr; 5436 5437 // If this has an identifier and is not a function template specialization, 5438 // add it to the scope stack. 5439 if (New->getDeclName() && AddToScope) { 5440 // Only make a locally-scoped extern declaration visible if it is the first 5441 // declaration of this entity. Qualified lookup for such an entity should 5442 // only find this declaration if there is no visible declaration of it. 5443 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5444 PushOnScopeChains(New, S, AddToContext); 5445 if (!AddToContext) 5446 CurContext->addHiddenDecl(New); 5447 } 5448 5449 if (isInOpenMPDeclareTargetContext()) 5450 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5451 5452 return New; 5453 } 5454 5455 /// Helper method to turn variable array types into constant array 5456 /// types in certain situations which would otherwise be errors (for 5457 /// GCC compatibility). 5458 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5459 ASTContext &Context, 5460 bool &SizeIsNegative, 5461 llvm::APSInt &Oversized) { 5462 // This method tries to turn a variable array into a constant 5463 // array even when the size isn't an ICE. This is necessary 5464 // for compatibility with code that depends on gcc's buggy 5465 // constant expression folding, like struct {char x[(int)(char*)2];} 5466 SizeIsNegative = false; 5467 Oversized = 0; 5468 5469 if (T->isDependentType()) 5470 return QualType(); 5471 5472 QualifierCollector Qs; 5473 const Type *Ty = Qs.strip(T); 5474 5475 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5476 QualType Pointee = PTy->getPointeeType(); 5477 QualType FixedType = 5478 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5479 Oversized); 5480 if (FixedType.isNull()) return FixedType; 5481 FixedType = Context.getPointerType(FixedType); 5482 return Qs.apply(Context, FixedType); 5483 } 5484 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5485 QualType Inner = PTy->getInnerType(); 5486 QualType FixedType = 5487 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5488 Oversized); 5489 if (FixedType.isNull()) return FixedType; 5490 FixedType = Context.getParenType(FixedType); 5491 return Qs.apply(Context, FixedType); 5492 } 5493 5494 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5495 if (!VLATy) 5496 return QualType(); 5497 // FIXME: We should probably handle this case 5498 if (VLATy->getElementType()->isVariablyModifiedType()) 5499 return QualType(); 5500 5501 llvm::APSInt Res; 5502 if (!VLATy->getSizeExpr() || 5503 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5504 return QualType(); 5505 5506 // Check whether the array size is negative. 5507 if (Res.isSigned() && Res.isNegative()) { 5508 SizeIsNegative = true; 5509 return QualType(); 5510 } 5511 5512 // Check whether the array is too large to be addressed. 5513 unsigned ActiveSizeBits 5514 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5515 Res); 5516 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5517 Oversized = Res; 5518 return QualType(); 5519 } 5520 5521 return Context.getConstantArrayType(VLATy->getElementType(), 5522 Res, ArrayType::Normal, 0); 5523 } 5524 5525 static void 5526 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5527 SrcTL = SrcTL.getUnqualifiedLoc(); 5528 DstTL = DstTL.getUnqualifiedLoc(); 5529 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5530 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5531 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5532 DstPTL.getPointeeLoc()); 5533 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5534 return; 5535 } 5536 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5537 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5538 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5539 DstPTL.getInnerLoc()); 5540 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5541 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5542 return; 5543 } 5544 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5545 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5546 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5547 TypeLoc DstElemTL = DstATL.getElementLoc(); 5548 DstElemTL.initializeFullCopy(SrcElemTL); 5549 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5550 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5551 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5552 } 5553 5554 /// Helper method to turn variable array types into constant array 5555 /// types in certain situations which would otherwise be errors (for 5556 /// GCC compatibility). 5557 static TypeSourceInfo* 5558 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5559 ASTContext &Context, 5560 bool &SizeIsNegative, 5561 llvm::APSInt &Oversized) { 5562 QualType FixedTy 5563 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5564 SizeIsNegative, Oversized); 5565 if (FixedTy.isNull()) 5566 return nullptr; 5567 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5568 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5569 FixedTInfo->getTypeLoc()); 5570 return FixedTInfo; 5571 } 5572 5573 /// \brief Register the given locally-scoped extern "C" declaration so 5574 /// that it can be found later for redeclarations. We include any extern "C" 5575 /// declaration that is not visible in the translation unit here, not just 5576 /// function-scope declarations. 5577 void 5578 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5579 if (!getLangOpts().CPlusPlus && 5580 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5581 // Don't need to track declarations in the TU in C. 5582 return; 5583 5584 // Note that we have a locally-scoped external with this name. 5585 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5586 } 5587 5588 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5589 // FIXME: We can have multiple results via __attribute__((overloadable)). 5590 auto Result = Context.getExternCContextDecl()->lookup(Name); 5591 return Result.empty() ? nullptr : *Result.begin(); 5592 } 5593 5594 /// \brief Diagnose function specifiers on a declaration of an identifier that 5595 /// does not identify a function. 5596 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5597 // FIXME: We should probably indicate the identifier in question to avoid 5598 // confusion for constructs like "virtual int a(), b;" 5599 if (DS.isVirtualSpecified()) 5600 Diag(DS.getVirtualSpecLoc(), 5601 diag::err_virtual_non_function); 5602 5603 if (DS.isExplicitSpecified()) 5604 Diag(DS.getExplicitSpecLoc(), 5605 diag::err_explicit_non_function); 5606 5607 if (DS.isNoreturnSpecified()) 5608 Diag(DS.getNoreturnSpecLoc(), 5609 diag::err_noreturn_non_function); 5610 } 5611 5612 NamedDecl* 5613 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5614 TypeSourceInfo *TInfo, LookupResult &Previous) { 5615 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5616 if (D.getCXXScopeSpec().isSet()) { 5617 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5618 << D.getCXXScopeSpec().getRange(); 5619 D.setInvalidType(); 5620 // Pretend we didn't see the scope specifier. 5621 DC = CurContext; 5622 Previous.clear(); 5623 } 5624 5625 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5626 5627 if (D.getDeclSpec().isInlineSpecified()) 5628 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5629 << getLangOpts().CPlusPlus1z; 5630 if (D.getDeclSpec().isConstexprSpecified()) 5631 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5632 << 1; 5633 if (D.getDeclSpec().isConceptSpecified()) 5634 Diag(D.getDeclSpec().getConceptSpecLoc(), 5635 diag::err_concept_wrong_decl_kind); 5636 5637 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5638 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5639 Diag(D.getName().StartLocation, 5640 diag::err_deduction_guide_invalid_specifier) 5641 << "typedef"; 5642 else 5643 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5644 << D.getName().getSourceRange(); 5645 return nullptr; 5646 } 5647 5648 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5649 if (!NewTD) return nullptr; 5650 5651 // Handle attributes prior to checking for duplicates in MergeVarDecl 5652 ProcessDeclAttributes(S, NewTD, D); 5653 5654 CheckTypedefForVariablyModifiedType(S, NewTD); 5655 5656 bool Redeclaration = D.isRedeclaration(); 5657 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5658 D.setRedeclaration(Redeclaration); 5659 return ND; 5660 } 5661 5662 void 5663 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5664 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5665 // then it shall have block scope. 5666 // Note that variably modified types must be fixed before merging the decl so 5667 // that redeclarations will match. 5668 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5669 QualType T = TInfo->getType(); 5670 if (T->isVariablyModifiedType()) { 5671 getCurFunction()->setHasBranchProtectedScope(); 5672 5673 if (S->getFnParent() == nullptr) { 5674 bool SizeIsNegative; 5675 llvm::APSInt Oversized; 5676 TypeSourceInfo *FixedTInfo = 5677 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5678 SizeIsNegative, 5679 Oversized); 5680 if (FixedTInfo) { 5681 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5682 NewTD->setTypeSourceInfo(FixedTInfo); 5683 } else { 5684 if (SizeIsNegative) 5685 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5686 else if (T->isVariableArrayType()) 5687 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5688 else if (Oversized.getBoolValue()) 5689 Diag(NewTD->getLocation(), diag::err_array_too_large) 5690 << Oversized.toString(10); 5691 else 5692 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5693 NewTD->setInvalidDecl(); 5694 } 5695 } 5696 } 5697 } 5698 5699 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5700 /// declares a typedef-name, either using the 'typedef' type specifier or via 5701 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5702 NamedDecl* 5703 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5704 LookupResult &Previous, bool &Redeclaration) { 5705 5706 // Find the shadowed declaration before filtering for scope. 5707 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5708 5709 // Merge the decl with the existing one if appropriate. If the decl is 5710 // in an outer scope, it isn't the same thing. 5711 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5712 /*AllowInlineNamespace*/false); 5713 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5714 if (!Previous.empty()) { 5715 Redeclaration = true; 5716 MergeTypedefNameDecl(S, NewTD, Previous); 5717 } 5718 5719 if (ShadowedDecl && !Redeclaration) 5720 CheckShadow(NewTD, ShadowedDecl, Previous); 5721 5722 // If this is the C FILE type, notify the AST context. 5723 if (IdentifierInfo *II = NewTD->getIdentifier()) 5724 if (!NewTD->isInvalidDecl() && 5725 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5726 if (II->isStr("FILE")) 5727 Context.setFILEDecl(NewTD); 5728 else if (II->isStr("jmp_buf")) 5729 Context.setjmp_bufDecl(NewTD); 5730 else if (II->isStr("sigjmp_buf")) 5731 Context.setsigjmp_bufDecl(NewTD); 5732 else if (II->isStr("ucontext_t")) 5733 Context.setucontext_tDecl(NewTD); 5734 } 5735 5736 return NewTD; 5737 } 5738 5739 /// \brief Determines whether the given declaration is an out-of-scope 5740 /// previous declaration. 5741 /// 5742 /// This routine should be invoked when name lookup has found a 5743 /// previous declaration (PrevDecl) that is not in the scope where a 5744 /// new declaration by the same name is being introduced. If the new 5745 /// declaration occurs in a local scope, previous declarations with 5746 /// linkage may still be considered previous declarations (C99 5747 /// 6.2.2p4-5, C++ [basic.link]p6). 5748 /// 5749 /// \param PrevDecl the previous declaration found by name 5750 /// lookup 5751 /// 5752 /// \param DC the context in which the new declaration is being 5753 /// declared. 5754 /// 5755 /// \returns true if PrevDecl is an out-of-scope previous declaration 5756 /// for a new delcaration with the same name. 5757 static bool 5758 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5759 ASTContext &Context) { 5760 if (!PrevDecl) 5761 return false; 5762 5763 if (!PrevDecl->hasLinkage()) 5764 return false; 5765 5766 if (Context.getLangOpts().CPlusPlus) { 5767 // C++ [basic.link]p6: 5768 // If there is a visible declaration of an entity with linkage 5769 // having the same name and type, ignoring entities declared 5770 // outside the innermost enclosing namespace scope, the block 5771 // scope declaration declares that same entity and receives the 5772 // linkage of the previous declaration. 5773 DeclContext *OuterContext = DC->getRedeclContext(); 5774 if (!OuterContext->isFunctionOrMethod()) 5775 // This rule only applies to block-scope declarations. 5776 return false; 5777 5778 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5779 if (PrevOuterContext->isRecord()) 5780 // We found a member function: ignore it. 5781 return false; 5782 5783 // Find the innermost enclosing namespace for the new and 5784 // previous declarations. 5785 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5786 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5787 5788 // The previous declaration is in a different namespace, so it 5789 // isn't the same function. 5790 if (!OuterContext->Equals(PrevOuterContext)) 5791 return false; 5792 } 5793 5794 return true; 5795 } 5796 5797 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5798 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5799 if (!SS.isSet()) return; 5800 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5801 } 5802 5803 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5804 QualType type = decl->getType(); 5805 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5806 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5807 // Various kinds of declaration aren't allowed to be __autoreleasing. 5808 unsigned kind = -1U; 5809 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5810 if (var->hasAttr<BlocksAttr>()) 5811 kind = 0; // __block 5812 else if (!var->hasLocalStorage()) 5813 kind = 1; // global 5814 } else if (isa<ObjCIvarDecl>(decl)) { 5815 kind = 3; // ivar 5816 } else if (isa<FieldDecl>(decl)) { 5817 kind = 2; // field 5818 } 5819 5820 if (kind != -1U) { 5821 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5822 << kind; 5823 } 5824 } else if (lifetime == Qualifiers::OCL_None) { 5825 // Try to infer lifetime. 5826 if (!type->isObjCLifetimeType()) 5827 return false; 5828 5829 lifetime = type->getObjCARCImplicitLifetime(); 5830 type = Context.getLifetimeQualifiedType(type, lifetime); 5831 decl->setType(type); 5832 } 5833 5834 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5835 // Thread-local variables cannot have lifetime. 5836 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5837 var->getTLSKind()) { 5838 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5839 << var->getType(); 5840 return true; 5841 } 5842 } 5843 5844 return false; 5845 } 5846 5847 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5848 // Ensure that an auto decl is deduced otherwise the checks below might cache 5849 // the wrong linkage. 5850 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5851 5852 // 'weak' only applies to declarations with external linkage. 5853 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5854 if (!ND.isExternallyVisible()) { 5855 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5856 ND.dropAttr<WeakAttr>(); 5857 } 5858 } 5859 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5860 if (ND.isExternallyVisible()) { 5861 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5862 ND.dropAttr<WeakRefAttr>(); 5863 ND.dropAttr<AliasAttr>(); 5864 } 5865 } 5866 5867 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5868 if (VD->hasInit()) { 5869 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5870 assert(VD->isThisDeclarationADefinition() && 5871 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5872 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5873 VD->dropAttr<AliasAttr>(); 5874 } 5875 } 5876 } 5877 5878 // 'selectany' only applies to externally visible variable declarations. 5879 // It does not apply to functions. 5880 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5881 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5882 S.Diag(Attr->getLocation(), 5883 diag::err_attribute_selectany_non_extern_data); 5884 ND.dropAttr<SelectAnyAttr>(); 5885 } 5886 } 5887 5888 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5889 // dll attributes require external linkage. Static locals may have external 5890 // linkage but still cannot be explicitly imported or exported. 5891 auto *VD = dyn_cast<VarDecl>(&ND); 5892 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5893 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5894 << &ND << Attr; 5895 ND.setInvalidDecl(); 5896 } 5897 } 5898 5899 // Virtual functions cannot be marked as 'notail'. 5900 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5901 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5902 if (MD->isVirtual()) { 5903 S.Diag(ND.getLocation(), 5904 diag::err_invalid_attribute_on_virtual_function) 5905 << Attr; 5906 ND.dropAttr<NotTailCalledAttr>(); 5907 } 5908 } 5909 5910 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5911 NamedDecl *NewDecl, 5912 bool IsSpecialization, 5913 bool IsDefinition) { 5914 if (OldDecl->isInvalidDecl()) 5915 return; 5916 5917 bool IsTemplate = false; 5918 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5919 OldDecl = OldTD->getTemplatedDecl(); 5920 IsTemplate = true; 5921 if (!IsSpecialization) 5922 IsDefinition = false; 5923 } 5924 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5925 NewDecl = NewTD->getTemplatedDecl(); 5926 IsTemplate = true; 5927 } 5928 5929 if (!OldDecl || !NewDecl) 5930 return; 5931 5932 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5933 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5934 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5935 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5936 5937 // dllimport and dllexport are inheritable attributes so we have to exclude 5938 // inherited attribute instances. 5939 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5940 (NewExportAttr && !NewExportAttr->isInherited()); 5941 5942 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5943 // the only exception being explicit specializations. 5944 // Implicitly generated declarations are also excluded for now because there 5945 // is no other way to switch these to use dllimport or dllexport. 5946 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5947 5948 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5949 // Allow with a warning for free functions and global variables. 5950 bool JustWarn = false; 5951 if (!OldDecl->isCXXClassMember()) { 5952 auto *VD = dyn_cast<VarDecl>(OldDecl); 5953 if (VD && !VD->getDescribedVarTemplate()) 5954 JustWarn = true; 5955 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5956 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5957 JustWarn = true; 5958 } 5959 5960 // We cannot change a declaration that's been used because IR has already 5961 // been emitted. Dllimported functions will still work though (modulo 5962 // address equality) as they can use the thunk. 5963 if (OldDecl->isUsed()) 5964 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5965 JustWarn = false; 5966 5967 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5968 : diag::err_attribute_dll_redeclaration; 5969 S.Diag(NewDecl->getLocation(), DiagID) 5970 << NewDecl 5971 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5972 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5973 if (!JustWarn) { 5974 NewDecl->setInvalidDecl(); 5975 return; 5976 } 5977 } 5978 5979 // A redeclaration is not allowed to drop a dllimport attribute, the only 5980 // exceptions being inline function definitions (except for function 5981 // templates), local extern declarations, qualified friend declarations or 5982 // special MSVC extension: in the last case, the declaration is treated as if 5983 // it were marked dllexport. 5984 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5985 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5986 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5987 // Ignore static data because out-of-line definitions are diagnosed 5988 // separately. 5989 IsStaticDataMember = VD->isStaticDataMember(); 5990 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5991 VarDecl::DeclarationOnly; 5992 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5993 IsInline = FD->isInlined(); 5994 IsQualifiedFriend = FD->getQualifier() && 5995 FD->getFriendObjectKind() == Decl::FOK_Declared; 5996 } 5997 5998 if (OldImportAttr && !HasNewAttr && 5999 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6000 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6001 if (IsMicrosoft && IsDefinition) { 6002 S.Diag(NewDecl->getLocation(), 6003 diag::warn_redeclaration_without_import_attribute) 6004 << NewDecl; 6005 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6006 NewDecl->dropAttr<DLLImportAttr>(); 6007 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6008 NewImportAttr->getRange(), S.Context, 6009 NewImportAttr->getSpellingListIndex())); 6010 } else { 6011 S.Diag(NewDecl->getLocation(), 6012 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6013 << NewDecl << OldImportAttr; 6014 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6015 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6016 OldDecl->dropAttr<DLLImportAttr>(); 6017 NewDecl->dropAttr<DLLImportAttr>(); 6018 } 6019 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6020 // In MinGW, seeing a function declared inline drops the dllimport attribute. 6021 OldDecl->dropAttr<DLLImportAttr>(); 6022 NewDecl->dropAttr<DLLImportAttr>(); 6023 S.Diag(NewDecl->getLocation(), 6024 diag::warn_dllimport_dropped_from_inline_function) 6025 << NewDecl << OldImportAttr; 6026 } 6027 } 6028 6029 /// Given that we are within the definition of the given function, 6030 /// will that definition behave like C99's 'inline', where the 6031 /// definition is discarded except for optimization purposes? 6032 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6033 // Try to avoid calling GetGVALinkageForFunction. 6034 6035 // All cases of this require the 'inline' keyword. 6036 if (!FD->isInlined()) return false; 6037 6038 // This is only possible in C++ with the gnu_inline attribute. 6039 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6040 return false; 6041 6042 // Okay, go ahead and call the relatively-more-expensive function. 6043 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6044 } 6045 6046 /// Determine whether a variable is extern "C" prior to attaching 6047 /// an initializer. We can't just call isExternC() here, because that 6048 /// will also compute and cache whether the declaration is externally 6049 /// visible, which might change when we attach the initializer. 6050 /// 6051 /// This can only be used if the declaration is known to not be a 6052 /// redeclaration of an internal linkage declaration. 6053 /// 6054 /// For instance: 6055 /// 6056 /// auto x = []{}; 6057 /// 6058 /// Attaching the initializer here makes this declaration not externally 6059 /// visible, because its type has internal linkage. 6060 /// 6061 /// FIXME: This is a hack. 6062 template<typename T> 6063 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6064 if (S.getLangOpts().CPlusPlus) { 6065 // In C++, the overloadable attribute negates the effects of extern "C". 6066 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6067 return false; 6068 6069 // So do CUDA's host/device attributes. 6070 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6071 D->template hasAttr<CUDAHostAttr>())) 6072 return false; 6073 } 6074 return D->isExternC(); 6075 } 6076 6077 static bool shouldConsiderLinkage(const VarDecl *VD) { 6078 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6079 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6080 return VD->hasExternalStorage(); 6081 if (DC->isFileContext()) 6082 return true; 6083 if (DC->isRecord()) 6084 return false; 6085 llvm_unreachable("Unexpected context"); 6086 } 6087 6088 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6089 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6090 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6091 isa<OMPDeclareReductionDecl>(DC)) 6092 return true; 6093 if (DC->isRecord()) 6094 return false; 6095 llvm_unreachable("Unexpected context"); 6096 } 6097 6098 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6099 AttributeList::Kind Kind) { 6100 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6101 if (L->getKind() == Kind) 6102 return true; 6103 return false; 6104 } 6105 6106 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6107 AttributeList::Kind Kind) { 6108 // Check decl attributes on the DeclSpec. 6109 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6110 return true; 6111 6112 // Walk the declarator structure, checking decl attributes that were in a type 6113 // position to the decl itself. 6114 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6115 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6116 return true; 6117 } 6118 6119 // Finally, check attributes on the decl itself. 6120 return hasParsedAttr(S, PD.getAttributes(), Kind); 6121 } 6122 6123 /// Adjust the \c DeclContext for a function or variable that might be a 6124 /// function-local external declaration. 6125 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6126 if (!DC->isFunctionOrMethod()) 6127 return false; 6128 6129 // If this is a local extern function or variable declared within a function 6130 // template, don't add it into the enclosing namespace scope until it is 6131 // instantiated; it might have a dependent type right now. 6132 if (DC->isDependentContext()) 6133 return true; 6134 6135 // C++11 [basic.link]p7: 6136 // When a block scope declaration of an entity with linkage is not found to 6137 // refer to some other declaration, then that entity is a member of the 6138 // innermost enclosing namespace. 6139 // 6140 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6141 // semantically-enclosing namespace, not a lexically-enclosing one. 6142 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6143 DC = DC->getParent(); 6144 return true; 6145 } 6146 6147 /// \brief Returns true if given declaration has external C language linkage. 6148 static bool isDeclExternC(const Decl *D) { 6149 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6150 return FD->isExternC(); 6151 if (const auto *VD = dyn_cast<VarDecl>(D)) 6152 return VD->isExternC(); 6153 6154 llvm_unreachable("Unknown type of decl!"); 6155 } 6156 6157 NamedDecl *Sema::ActOnVariableDeclarator( 6158 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6159 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6160 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6161 QualType R = TInfo->getType(); 6162 DeclarationName Name = GetNameForDeclarator(D).getName(); 6163 6164 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6165 6166 if (D.isDecompositionDeclarator()) { 6167 AddToScope = false; 6168 // Take the name of the first declarator as our name for diagnostic 6169 // purposes. 6170 auto &Decomp = D.getDecompositionDeclarator(); 6171 if (!Decomp.bindings().empty()) { 6172 II = Decomp.bindings()[0].Name; 6173 Name = II; 6174 } 6175 } else if (!II) { 6176 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6177 return nullptr; 6178 } 6179 6180 if (getLangOpts().OpenCL) { 6181 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6182 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6183 // argument. 6184 if (R->isImageType() || R->isPipeType()) { 6185 Diag(D.getIdentifierLoc(), 6186 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6187 << R; 6188 D.setInvalidType(); 6189 return nullptr; 6190 } 6191 6192 // OpenCL v1.2 s6.9.r: 6193 // The event type cannot be used to declare a program scope variable. 6194 // OpenCL v2.0 s6.9.q: 6195 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6196 if (NULL == S->getParent()) { 6197 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6198 Diag(D.getIdentifierLoc(), 6199 diag::err_invalid_type_for_program_scope_var) << R; 6200 D.setInvalidType(); 6201 return nullptr; 6202 } 6203 } 6204 6205 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6206 QualType NR = R; 6207 while (NR->isPointerType()) { 6208 if (NR->isFunctionPointerType()) { 6209 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6210 D.setInvalidType(); 6211 break; 6212 } 6213 NR = NR->getPointeeType(); 6214 } 6215 6216 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6217 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6218 // half array type (unless the cl_khr_fp16 extension is enabled). 6219 if (Context.getBaseElementType(R)->isHalfType()) { 6220 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6221 D.setInvalidType(); 6222 } 6223 } 6224 6225 if (R->isSamplerT()) { 6226 // OpenCL v1.2 s6.9.b p4: 6227 // The sampler type cannot be used with the __local and __global address 6228 // space qualifiers. 6229 if (R.getAddressSpace() == LangAS::opencl_local || 6230 R.getAddressSpace() == LangAS::opencl_global) { 6231 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6232 } 6233 6234 // OpenCL v1.2 s6.12.14.1: 6235 // A global sampler must be declared with either the constant address 6236 // space qualifier or with the const qualifier. 6237 if (DC->isTranslationUnit() && 6238 !(R.getAddressSpace() == LangAS::opencl_constant || 6239 R.isConstQualified())) { 6240 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6241 D.setInvalidType(); 6242 } 6243 } 6244 6245 // OpenCL v1.2 s6.9.r: 6246 // The event type cannot be used with the __local, __constant and __global 6247 // address space qualifiers. 6248 if (R->isEventT()) { 6249 if (R.getAddressSpace()) { 6250 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6251 D.setInvalidType(); 6252 } 6253 } 6254 } 6255 6256 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6257 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6258 6259 // dllimport globals without explicit storage class are treated as extern. We 6260 // have to change the storage class this early to get the right DeclContext. 6261 if (SC == SC_None && !DC->isRecord() && 6262 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6263 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6264 SC = SC_Extern; 6265 6266 DeclContext *OriginalDC = DC; 6267 bool IsLocalExternDecl = SC == SC_Extern && 6268 adjustContextForLocalExternDecl(DC); 6269 6270 if (SCSpec == DeclSpec::SCS_mutable) { 6271 // mutable can only appear on non-static class members, so it's always 6272 // an error here 6273 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6274 D.setInvalidType(); 6275 SC = SC_None; 6276 } 6277 6278 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6279 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6280 D.getDeclSpec().getStorageClassSpecLoc())) { 6281 // In C++11, the 'register' storage class specifier is deprecated. 6282 // Suppress the warning in system macros, it's used in macros in some 6283 // popular C system headers, such as in glibc's htonl() macro. 6284 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6285 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6286 : diag::warn_deprecated_register) 6287 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6288 } 6289 6290 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6291 6292 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6293 // C99 6.9p2: The storage-class specifiers auto and register shall not 6294 // appear in the declaration specifiers in an external declaration. 6295 // Global Register+Asm is a GNU extension we support. 6296 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6297 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6298 D.setInvalidType(); 6299 } 6300 } 6301 6302 bool IsMemberSpecialization = false; 6303 bool IsVariableTemplateSpecialization = false; 6304 bool IsPartialSpecialization = false; 6305 bool IsVariableTemplate = false; 6306 VarDecl *NewVD = nullptr; 6307 VarTemplateDecl *NewTemplate = nullptr; 6308 TemplateParameterList *TemplateParams = nullptr; 6309 if (!getLangOpts().CPlusPlus) { 6310 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6311 D.getIdentifierLoc(), II, 6312 R, TInfo, SC); 6313 6314 if (R->getContainedDeducedType()) 6315 ParsingInitForAutoVars.insert(NewVD); 6316 6317 if (D.isInvalidType()) 6318 NewVD->setInvalidDecl(); 6319 } else { 6320 bool Invalid = false; 6321 6322 if (DC->isRecord() && !CurContext->isRecord()) { 6323 // This is an out-of-line definition of a static data member. 6324 switch (SC) { 6325 case SC_None: 6326 break; 6327 case SC_Static: 6328 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6329 diag::err_static_out_of_line) 6330 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6331 break; 6332 case SC_Auto: 6333 case SC_Register: 6334 case SC_Extern: 6335 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6336 // to names of variables declared in a block or to function parameters. 6337 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6338 // of class members 6339 6340 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6341 diag::err_storage_class_for_static_member) 6342 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6343 break; 6344 case SC_PrivateExtern: 6345 llvm_unreachable("C storage class in c++!"); 6346 } 6347 } 6348 6349 if (SC == SC_Static && CurContext->isRecord()) { 6350 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6351 if (RD->isLocalClass()) 6352 Diag(D.getIdentifierLoc(), 6353 diag::err_static_data_member_not_allowed_in_local_class) 6354 << Name << RD->getDeclName(); 6355 6356 // C++98 [class.union]p1: If a union contains a static data member, 6357 // the program is ill-formed. C++11 drops this restriction. 6358 if (RD->isUnion()) 6359 Diag(D.getIdentifierLoc(), 6360 getLangOpts().CPlusPlus11 6361 ? diag::warn_cxx98_compat_static_data_member_in_union 6362 : diag::ext_static_data_member_in_union) << Name; 6363 // We conservatively disallow static data members in anonymous structs. 6364 else if (!RD->getDeclName()) 6365 Diag(D.getIdentifierLoc(), 6366 diag::err_static_data_member_not_allowed_in_anon_struct) 6367 << Name << RD->isUnion(); 6368 } 6369 } 6370 6371 // Match up the template parameter lists with the scope specifier, then 6372 // determine whether we have a template or a template specialization. 6373 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6374 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6375 D.getCXXScopeSpec(), 6376 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6377 ? D.getName().TemplateId 6378 : nullptr, 6379 TemplateParamLists, 6380 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6381 6382 if (TemplateParams) { 6383 if (!TemplateParams->size() && 6384 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6385 // There is an extraneous 'template<>' for this variable. Complain 6386 // about it, but allow the declaration of the variable. 6387 Diag(TemplateParams->getTemplateLoc(), 6388 diag::err_template_variable_noparams) 6389 << II 6390 << SourceRange(TemplateParams->getTemplateLoc(), 6391 TemplateParams->getRAngleLoc()); 6392 TemplateParams = nullptr; 6393 } else { 6394 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6395 // This is an explicit specialization or a partial specialization. 6396 // FIXME: Check that we can declare a specialization here. 6397 IsVariableTemplateSpecialization = true; 6398 IsPartialSpecialization = TemplateParams->size() > 0; 6399 } else { // if (TemplateParams->size() > 0) 6400 // This is a template declaration. 6401 IsVariableTemplate = true; 6402 6403 // Check that we can declare a template here. 6404 if (CheckTemplateDeclScope(S, TemplateParams)) 6405 return nullptr; 6406 6407 // Only C++1y supports variable templates (N3651). 6408 Diag(D.getIdentifierLoc(), 6409 getLangOpts().CPlusPlus14 6410 ? diag::warn_cxx11_compat_variable_template 6411 : diag::ext_variable_template); 6412 } 6413 } 6414 } else { 6415 assert( 6416 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6417 "should have a 'template<>' for this decl"); 6418 } 6419 6420 if (IsVariableTemplateSpecialization) { 6421 SourceLocation TemplateKWLoc = 6422 TemplateParamLists.size() > 0 6423 ? TemplateParamLists[0]->getTemplateLoc() 6424 : SourceLocation(); 6425 DeclResult Res = ActOnVarTemplateSpecialization( 6426 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6427 IsPartialSpecialization); 6428 if (Res.isInvalid()) 6429 return nullptr; 6430 NewVD = cast<VarDecl>(Res.get()); 6431 AddToScope = false; 6432 } else if (D.isDecompositionDeclarator()) { 6433 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6434 D.getIdentifierLoc(), R, TInfo, SC, 6435 Bindings); 6436 } else 6437 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6438 D.getIdentifierLoc(), II, R, TInfo, SC); 6439 6440 // If this is supposed to be a variable template, create it as such. 6441 if (IsVariableTemplate) { 6442 NewTemplate = 6443 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6444 TemplateParams, NewVD); 6445 NewVD->setDescribedVarTemplate(NewTemplate); 6446 } 6447 6448 // If this decl has an auto type in need of deduction, make a note of the 6449 // Decl so we can diagnose uses of it in its own initializer. 6450 if (R->getContainedDeducedType()) 6451 ParsingInitForAutoVars.insert(NewVD); 6452 6453 if (D.isInvalidType() || Invalid) { 6454 NewVD->setInvalidDecl(); 6455 if (NewTemplate) 6456 NewTemplate->setInvalidDecl(); 6457 } 6458 6459 SetNestedNameSpecifier(NewVD, D); 6460 6461 // If we have any template parameter lists that don't directly belong to 6462 // the variable (matching the scope specifier), store them. 6463 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6464 if (TemplateParamLists.size() > VDTemplateParamLists) 6465 NewVD->setTemplateParameterListsInfo( 6466 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6467 6468 if (D.getDeclSpec().isConstexprSpecified()) { 6469 NewVD->setConstexpr(true); 6470 // C++1z [dcl.spec.constexpr]p1: 6471 // A static data member declared with the constexpr specifier is 6472 // implicitly an inline variable. 6473 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6474 NewVD->setImplicitlyInline(); 6475 } 6476 6477 if (D.getDeclSpec().isConceptSpecified()) { 6478 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6479 VTD->setConcept(); 6480 6481 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6482 // be declared with the thread_local, inline, friend, or constexpr 6483 // specifiers, [...] 6484 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6485 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6486 diag::err_concept_decl_invalid_specifiers) 6487 << 0 << 0; 6488 NewVD->setInvalidDecl(true); 6489 } 6490 6491 if (D.getDeclSpec().isConstexprSpecified()) { 6492 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6493 diag::err_concept_decl_invalid_specifiers) 6494 << 0 << 3; 6495 NewVD->setInvalidDecl(true); 6496 } 6497 6498 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6499 // applied only to the definition of a function template or variable 6500 // template, declared in namespace scope. 6501 if (IsVariableTemplateSpecialization) { 6502 Diag(D.getDeclSpec().getConceptSpecLoc(), 6503 diag::err_concept_specified_specialization) 6504 << (IsPartialSpecialization ? 2 : 1); 6505 } 6506 6507 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6508 // following restrictions: 6509 // - The declared type shall have the type bool. 6510 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6511 !NewVD->isInvalidDecl()) { 6512 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6513 NewVD->setInvalidDecl(true); 6514 } 6515 } 6516 } 6517 6518 if (D.getDeclSpec().isInlineSpecified()) { 6519 if (!getLangOpts().CPlusPlus) { 6520 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6521 << 0; 6522 } else if (CurContext->isFunctionOrMethod()) { 6523 // 'inline' is not allowed on block scope variable declaration. 6524 Diag(D.getDeclSpec().getInlineSpecLoc(), 6525 diag::err_inline_declaration_block_scope) << Name 6526 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6527 } else { 6528 Diag(D.getDeclSpec().getInlineSpecLoc(), 6529 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6530 : diag::ext_inline_variable); 6531 NewVD->setInlineSpecified(); 6532 } 6533 } 6534 6535 // Set the lexical context. If the declarator has a C++ scope specifier, the 6536 // lexical context will be different from the semantic context. 6537 NewVD->setLexicalDeclContext(CurContext); 6538 if (NewTemplate) 6539 NewTemplate->setLexicalDeclContext(CurContext); 6540 6541 if (IsLocalExternDecl) { 6542 if (D.isDecompositionDeclarator()) 6543 for (auto *B : Bindings) 6544 B->setLocalExternDecl(); 6545 else 6546 NewVD->setLocalExternDecl(); 6547 } 6548 6549 bool EmitTLSUnsupportedError = false; 6550 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6551 // C++11 [dcl.stc]p4: 6552 // When thread_local is applied to a variable of block scope the 6553 // storage-class-specifier static is implied if it does not appear 6554 // explicitly. 6555 // Core issue: 'static' is not implied if the variable is declared 6556 // 'extern'. 6557 if (NewVD->hasLocalStorage() && 6558 (SCSpec != DeclSpec::SCS_unspecified || 6559 TSCS != DeclSpec::TSCS_thread_local || 6560 !DC->isFunctionOrMethod())) 6561 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6562 diag::err_thread_non_global) 6563 << DeclSpec::getSpecifierName(TSCS); 6564 else if (!Context.getTargetInfo().isTLSSupported()) { 6565 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6566 // Postpone error emission until we've collected attributes required to 6567 // figure out whether it's a host or device variable and whether the 6568 // error should be ignored. 6569 EmitTLSUnsupportedError = true; 6570 // We still need to mark the variable as TLS so it shows up in AST with 6571 // proper storage class for other tools to use even if we're not going 6572 // to emit any code for it. 6573 NewVD->setTSCSpec(TSCS); 6574 } else 6575 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6576 diag::err_thread_unsupported); 6577 } else 6578 NewVD->setTSCSpec(TSCS); 6579 } 6580 6581 // C99 6.7.4p3 6582 // An inline definition of a function with external linkage shall 6583 // not contain a definition of a modifiable object with static or 6584 // thread storage duration... 6585 // We only apply this when the function is required to be defined 6586 // elsewhere, i.e. when the function is not 'extern inline'. Note 6587 // that a local variable with thread storage duration still has to 6588 // be marked 'static'. Also note that it's possible to get these 6589 // semantics in C++ using __attribute__((gnu_inline)). 6590 if (SC == SC_Static && S->getFnParent() != nullptr && 6591 !NewVD->getType().isConstQualified()) { 6592 FunctionDecl *CurFD = getCurFunctionDecl(); 6593 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6594 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6595 diag::warn_static_local_in_extern_inline); 6596 MaybeSuggestAddingStaticToDecl(CurFD); 6597 } 6598 } 6599 6600 if (D.getDeclSpec().isModulePrivateSpecified()) { 6601 if (IsVariableTemplateSpecialization) 6602 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6603 << (IsPartialSpecialization ? 1 : 0) 6604 << FixItHint::CreateRemoval( 6605 D.getDeclSpec().getModulePrivateSpecLoc()); 6606 else if (IsMemberSpecialization) 6607 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6608 << 2 6609 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6610 else if (NewVD->hasLocalStorage()) 6611 Diag(NewVD->getLocation(), diag::err_module_private_local) 6612 << 0 << NewVD->getDeclName() 6613 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6614 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6615 else { 6616 NewVD->setModulePrivate(); 6617 if (NewTemplate) 6618 NewTemplate->setModulePrivate(); 6619 for (auto *B : Bindings) 6620 B->setModulePrivate(); 6621 } 6622 } 6623 6624 // Handle attributes prior to checking for duplicates in MergeVarDecl 6625 ProcessDeclAttributes(S, NewVD, D); 6626 6627 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6628 if (EmitTLSUnsupportedError && 6629 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6630 (getLangOpts().OpenMPIsDevice && 6631 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6632 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6633 diag::err_thread_unsupported); 6634 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6635 // storage [duration]." 6636 if (SC == SC_None && S->getFnParent() != nullptr && 6637 (NewVD->hasAttr<CUDASharedAttr>() || 6638 NewVD->hasAttr<CUDAConstantAttr>())) { 6639 NewVD->setStorageClass(SC_Static); 6640 } 6641 } 6642 6643 // Ensure that dllimport globals without explicit storage class are treated as 6644 // extern. The storage class is set above using parsed attributes. Now we can 6645 // check the VarDecl itself. 6646 assert(!NewVD->hasAttr<DLLImportAttr>() || 6647 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6648 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6649 6650 // In auto-retain/release, infer strong retension for variables of 6651 // retainable type. 6652 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6653 NewVD->setInvalidDecl(); 6654 6655 // Handle GNU asm-label extension (encoded as an attribute). 6656 if (Expr *E = (Expr*)D.getAsmLabel()) { 6657 // The parser guarantees this is a string. 6658 StringLiteral *SE = cast<StringLiteral>(E); 6659 StringRef Label = SE->getString(); 6660 if (S->getFnParent() != nullptr) { 6661 switch (SC) { 6662 case SC_None: 6663 case SC_Auto: 6664 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6665 break; 6666 case SC_Register: 6667 // Local Named register 6668 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6669 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6670 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6671 break; 6672 case SC_Static: 6673 case SC_Extern: 6674 case SC_PrivateExtern: 6675 break; 6676 } 6677 } else if (SC == SC_Register) { 6678 // Global Named register 6679 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6680 const auto &TI = Context.getTargetInfo(); 6681 bool HasSizeMismatch; 6682 6683 if (!TI.isValidGCCRegisterName(Label)) 6684 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6685 else if (!TI.validateGlobalRegisterVariable(Label, 6686 Context.getTypeSize(R), 6687 HasSizeMismatch)) 6688 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6689 else if (HasSizeMismatch) 6690 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6691 } 6692 6693 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6694 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6695 NewVD->setInvalidDecl(true); 6696 } 6697 } 6698 6699 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6700 Context, Label, 0)); 6701 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6702 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6703 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6704 if (I != ExtnameUndeclaredIdentifiers.end()) { 6705 if (isDeclExternC(NewVD)) { 6706 NewVD->addAttr(I->second); 6707 ExtnameUndeclaredIdentifiers.erase(I); 6708 } else 6709 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6710 << /*Variable*/1 << NewVD; 6711 } 6712 } 6713 6714 // Find the shadowed declaration before filtering for scope. 6715 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6716 ? getShadowedDeclaration(NewVD, Previous) 6717 : nullptr; 6718 6719 // Don't consider existing declarations that are in a different 6720 // scope and are out-of-semantic-context declarations (if the new 6721 // declaration has linkage). 6722 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6723 D.getCXXScopeSpec().isNotEmpty() || 6724 IsMemberSpecialization || 6725 IsVariableTemplateSpecialization); 6726 6727 // Check whether the previous declaration is in the same block scope. This 6728 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6729 if (getLangOpts().CPlusPlus && 6730 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6731 NewVD->setPreviousDeclInSameBlockScope( 6732 Previous.isSingleResult() && !Previous.isShadowed() && 6733 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6734 6735 if (!getLangOpts().CPlusPlus) { 6736 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6737 } else { 6738 // If this is an explicit specialization of a static data member, check it. 6739 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6740 CheckMemberSpecialization(NewVD, Previous)) 6741 NewVD->setInvalidDecl(); 6742 6743 // Merge the decl with the existing one if appropriate. 6744 if (!Previous.empty()) { 6745 if (Previous.isSingleResult() && 6746 isa<FieldDecl>(Previous.getFoundDecl()) && 6747 D.getCXXScopeSpec().isSet()) { 6748 // The user tried to define a non-static data member 6749 // out-of-line (C++ [dcl.meaning]p1). 6750 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6751 << D.getCXXScopeSpec().getRange(); 6752 Previous.clear(); 6753 NewVD->setInvalidDecl(); 6754 } 6755 } else if (D.getCXXScopeSpec().isSet()) { 6756 // No previous declaration in the qualifying scope. 6757 Diag(D.getIdentifierLoc(), diag::err_no_member) 6758 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6759 << D.getCXXScopeSpec().getRange(); 6760 NewVD->setInvalidDecl(); 6761 } 6762 6763 if (!IsVariableTemplateSpecialization) 6764 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6765 6766 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6767 // an explicit specialization (14.8.3) or a partial specialization of a 6768 // concept definition. 6769 if (IsVariableTemplateSpecialization && 6770 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6771 Previous.isSingleResult()) { 6772 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6773 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6774 if (VarTmpl->isConcept()) { 6775 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6776 << 1 /*variable*/ 6777 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6778 : 1 /*explicitly specialized*/); 6779 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6780 NewVD->setInvalidDecl(); 6781 } 6782 } 6783 } 6784 6785 if (NewTemplate) { 6786 VarTemplateDecl *PrevVarTemplate = 6787 NewVD->getPreviousDecl() 6788 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6789 : nullptr; 6790 6791 // Check the template parameter list of this declaration, possibly 6792 // merging in the template parameter list from the previous variable 6793 // template declaration. 6794 if (CheckTemplateParameterList( 6795 TemplateParams, 6796 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6797 : nullptr, 6798 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6799 DC->isDependentContext()) 6800 ? TPC_ClassTemplateMember 6801 : TPC_VarTemplate)) 6802 NewVD->setInvalidDecl(); 6803 6804 // If we are providing an explicit specialization of a static variable 6805 // template, make a note of that. 6806 if (PrevVarTemplate && 6807 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6808 PrevVarTemplate->setMemberSpecialization(); 6809 } 6810 } 6811 6812 // Diagnose shadowed variables iff this isn't a redeclaration. 6813 if (ShadowedDecl && !D.isRedeclaration()) 6814 CheckShadow(NewVD, ShadowedDecl, Previous); 6815 6816 ProcessPragmaWeak(S, NewVD); 6817 6818 // If this is the first declaration of an extern C variable, update 6819 // the map of such variables. 6820 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6821 isIncompleteDeclExternC(*this, NewVD)) 6822 RegisterLocallyScopedExternCDecl(NewVD, S); 6823 6824 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6825 Decl *ManglingContextDecl; 6826 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6827 NewVD->getDeclContext(), ManglingContextDecl)) { 6828 Context.setManglingNumber( 6829 NewVD, MCtx->getManglingNumber( 6830 NewVD, getMSManglingNumber(getLangOpts(), S))); 6831 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6832 } 6833 } 6834 6835 // Special handling of variable named 'main'. 6836 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6837 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6838 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6839 6840 // C++ [basic.start.main]p3 6841 // A program that declares a variable main at global scope is ill-formed. 6842 if (getLangOpts().CPlusPlus) 6843 Diag(D.getLocStart(), diag::err_main_global_variable); 6844 6845 // In C, and external-linkage variable named main results in undefined 6846 // behavior. 6847 else if (NewVD->hasExternalFormalLinkage()) 6848 Diag(D.getLocStart(), diag::warn_main_redefined); 6849 } 6850 6851 if (D.isRedeclaration() && !Previous.empty()) { 6852 checkDLLAttributeRedeclaration( 6853 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6854 IsMemberSpecialization, D.isFunctionDefinition()); 6855 } 6856 6857 if (NewTemplate) { 6858 if (NewVD->isInvalidDecl()) 6859 NewTemplate->setInvalidDecl(); 6860 ActOnDocumentableDecl(NewTemplate); 6861 return NewTemplate; 6862 } 6863 6864 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6865 CompleteMemberSpecialization(NewVD, Previous); 6866 6867 return NewVD; 6868 } 6869 6870 /// Enum describing the %select options in diag::warn_decl_shadow. 6871 enum ShadowedDeclKind { 6872 SDK_Local, 6873 SDK_Global, 6874 SDK_StaticMember, 6875 SDK_Field, 6876 SDK_Typedef, 6877 SDK_Using 6878 }; 6879 6880 /// Determine what kind of declaration we're shadowing. 6881 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6882 const DeclContext *OldDC) { 6883 if (isa<TypeAliasDecl>(ShadowedDecl)) 6884 return SDK_Using; 6885 else if (isa<TypedefDecl>(ShadowedDecl)) 6886 return SDK_Typedef; 6887 else if (isa<RecordDecl>(OldDC)) 6888 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6889 6890 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6891 } 6892 6893 /// Return the location of the capture if the given lambda captures the given 6894 /// variable \p VD, or an invalid source location otherwise. 6895 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6896 const VarDecl *VD) { 6897 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6898 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6899 return Capture.getLocation(); 6900 } 6901 return SourceLocation(); 6902 } 6903 6904 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6905 const LookupResult &R) { 6906 // Only diagnose if we're shadowing an unambiguous field or variable. 6907 if (R.getResultKind() != LookupResult::Found) 6908 return false; 6909 6910 // Return false if warning is ignored. 6911 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6912 } 6913 6914 /// \brief Return the declaration shadowed by the given variable \p D, or null 6915 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6916 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6917 const LookupResult &R) { 6918 if (!shouldWarnIfShadowedDecl(Diags, R)) 6919 return nullptr; 6920 6921 // Don't diagnose declarations at file scope. 6922 if (D->hasGlobalStorage()) 6923 return nullptr; 6924 6925 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6926 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6927 ? ShadowedDecl 6928 : nullptr; 6929 } 6930 6931 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6932 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6933 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6934 const LookupResult &R) { 6935 // Don't warn if typedef declaration is part of a class 6936 if (D->getDeclContext()->isRecord()) 6937 return nullptr; 6938 6939 if (!shouldWarnIfShadowedDecl(Diags, R)) 6940 return nullptr; 6941 6942 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6943 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6944 } 6945 6946 /// \brief Diagnose variable or built-in function shadowing. Implements 6947 /// -Wshadow. 6948 /// 6949 /// This method is called whenever a VarDecl is added to a "useful" 6950 /// scope. 6951 /// 6952 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6953 /// \param R the lookup of the name 6954 /// 6955 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6956 const LookupResult &R) { 6957 DeclContext *NewDC = D->getDeclContext(); 6958 6959 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6960 // Fields are not shadowed by variables in C++ static methods. 6961 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6962 if (MD->isStatic()) 6963 return; 6964 6965 // Fields shadowed by constructor parameters are a special case. Usually 6966 // the constructor initializes the field with the parameter. 6967 if (isa<CXXConstructorDecl>(NewDC)) 6968 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6969 // Remember that this was shadowed so we can either warn about its 6970 // modification or its existence depending on warning settings. 6971 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6972 return; 6973 } 6974 } 6975 6976 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6977 if (shadowedVar->isExternC()) { 6978 // For shadowing external vars, make sure that we point to the global 6979 // declaration, not a locally scoped extern declaration. 6980 for (auto I : shadowedVar->redecls()) 6981 if (I->isFileVarDecl()) { 6982 ShadowedDecl = I; 6983 break; 6984 } 6985 } 6986 6987 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 6988 6989 unsigned WarningDiag = diag::warn_decl_shadow; 6990 SourceLocation CaptureLoc; 6991 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6992 isa<CXXMethodDecl>(NewDC)) { 6993 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6994 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6995 if (RD->getLambdaCaptureDefault() == LCD_None) { 6996 // Try to avoid warnings for lambdas with an explicit capture list. 6997 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6998 // Warn only when the lambda captures the shadowed decl explicitly. 6999 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7000 if (CaptureLoc.isInvalid()) 7001 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7002 } else { 7003 // Remember that this was shadowed so we can avoid the warning if the 7004 // shadowed decl isn't captured and the warning settings allow it. 7005 cast<LambdaScopeInfo>(getCurFunction()) 7006 ->ShadowingDecls.push_back( 7007 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7008 return; 7009 } 7010 } 7011 7012 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7013 // A variable can't shadow a local variable in an enclosing scope, if 7014 // they are separated by a non-capturing declaration context. 7015 for (DeclContext *ParentDC = NewDC; 7016 ParentDC && !ParentDC->Equals(OldDC); 7017 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7018 // Only block literals, captured statements, and lambda expressions 7019 // can capture; other scopes don't. 7020 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7021 !isLambdaCallOperator(ParentDC)) { 7022 return; 7023 } 7024 } 7025 } 7026 } 7027 } 7028 7029 // Only warn about certain kinds of shadowing for class members. 7030 if (NewDC && NewDC->isRecord()) { 7031 // In particular, don't warn about shadowing non-class members. 7032 if (!OldDC->isRecord()) 7033 return; 7034 7035 // TODO: should we warn about static data members shadowing 7036 // static data members from base classes? 7037 7038 // TODO: don't diagnose for inaccessible shadowed members. 7039 // This is hard to do perfectly because we might friend the 7040 // shadowing context, but that's just a false negative. 7041 } 7042 7043 7044 DeclarationName Name = R.getLookupName(); 7045 7046 // Emit warning and note. 7047 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7048 return; 7049 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7050 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7051 if (!CaptureLoc.isInvalid()) 7052 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7053 << Name << /*explicitly*/ 1; 7054 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7055 } 7056 7057 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7058 /// when these variables are captured by the lambda. 7059 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7060 for (const auto &Shadow : LSI->ShadowingDecls) { 7061 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7062 // Try to avoid the warning when the shadowed decl isn't captured. 7063 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7064 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7065 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7066 ? diag::warn_decl_shadow_uncaptured_local 7067 : diag::warn_decl_shadow) 7068 << Shadow.VD->getDeclName() 7069 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7070 if (!CaptureLoc.isInvalid()) 7071 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7072 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7073 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7074 } 7075 } 7076 7077 /// \brief Check -Wshadow without the advantage of a previous lookup. 7078 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7079 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7080 return; 7081 7082 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7083 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7084 LookupName(R, S); 7085 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7086 CheckShadow(D, ShadowedDecl, R); 7087 } 7088 7089 /// Check if 'E', which is an expression that is about to be modified, refers 7090 /// to a constructor parameter that shadows a field. 7091 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7092 // Quickly ignore expressions that can't be shadowing ctor parameters. 7093 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7094 return; 7095 E = E->IgnoreParenImpCasts(); 7096 auto *DRE = dyn_cast<DeclRefExpr>(E); 7097 if (!DRE) 7098 return; 7099 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7100 auto I = ShadowingDecls.find(D); 7101 if (I == ShadowingDecls.end()) 7102 return; 7103 const NamedDecl *ShadowedDecl = I->second; 7104 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7105 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7106 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7107 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7108 7109 // Avoid issuing multiple warnings about the same decl. 7110 ShadowingDecls.erase(I); 7111 } 7112 7113 /// Check for conflict between this global or extern "C" declaration and 7114 /// previous global or extern "C" declarations. This is only used in C++. 7115 template<typename T> 7116 static bool checkGlobalOrExternCConflict( 7117 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7118 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7119 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7120 7121 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7122 // The common case: this global doesn't conflict with any extern "C" 7123 // declaration. 7124 return false; 7125 } 7126 7127 if (Prev) { 7128 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7129 // Both the old and new declarations have C language linkage. This is a 7130 // redeclaration. 7131 Previous.clear(); 7132 Previous.addDecl(Prev); 7133 return true; 7134 } 7135 7136 // This is a global, non-extern "C" declaration, and there is a previous 7137 // non-global extern "C" declaration. Diagnose if this is a variable 7138 // declaration. 7139 if (!isa<VarDecl>(ND)) 7140 return false; 7141 } else { 7142 // The declaration is extern "C". Check for any declaration in the 7143 // translation unit which might conflict. 7144 if (IsGlobal) { 7145 // We have already performed the lookup into the translation unit. 7146 IsGlobal = false; 7147 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7148 I != E; ++I) { 7149 if (isa<VarDecl>(*I)) { 7150 Prev = *I; 7151 break; 7152 } 7153 } 7154 } else { 7155 DeclContext::lookup_result R = 7156 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7157 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7158 I != E; ++I) { 7159 if (isa<VarDecl>(*I)) { 7160 Prev = *I; 7161 break; 7162 } 7163 // FIXME: If we have any other entity with this name in global scope, 7164 // the declaration is ill-formed, but that is a defect: it breaks the 7165 // 'stat' hack, for instance. Only variables can have mangled name 7166 // clashes with extern "C" declarations, so only they deserve a 7167 // diagnostic. 7168 } 7169 } 7170 7171 if (!Prev) 7172 return false; 7173 } 7174 7175 // Use the first declaration's location to ensure we point at something which 7176 // is lexically inside an extern "C" linkage-spec. 7177 assert(Prev && "should have found a previous declaration to diagnose"); 7178 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7179 Prev = FD->getFirstDecl(); 7180 else 7181 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7182 7183 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7184 << IsGlobal << ND; 7185 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7186 << IsGlobal; 7187 return false; 7188 } 7189 7190 /// Apply special rules for handling extern "C" declarations. Returns \c true 7191 /// if we have found that this is a redeclaration of some prior entity. 7192 /// 7193 /// Per C++ [dcl.link]p6: 7194 /// Two declarations [for a function or variable] with C language linkage 7195 /// with the same name that appear in different scopes refer to the same 7196 /// [entity]. An entity with C language linkage shall not be declared with 7197 /// the same name as an entity in global scope. 7198 template<typename T> 7199 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7200 LookupResult &Previous) { 7201 if (!S.getLangOpts().CPlusPlus) { 7202 // In C, when declaring a global variable, look for a corresponding 'extern' 7203 // variable declared in function scope. We don't need this in C++, because 7204 // we find local extern decls in the surrounding file-scope DeclContext. 7205 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7206 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7207 Previous.clear(); 7208 Previous.addDecl(Prev); 7209 return true; 7210 } 7211 } 7212 return false; 7213 } 7214 7215 // A declaration in the translation unit can conflict with an extern "C" 7216 // declaration. 7217 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7218 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7219 7220 // An extern "C" declaration can conflict with a declaration in the 7221 // translation unit or can be a redeclaration of an extern "C" declaration 7222 // in another scope. 7223 if (isIncompleteDeclExternC(S,ND)) 7224 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7225 7226 // Neither global nor extern "C": nothing to do. 7227 return false; 7228 } 7229 7230 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7231 // If the decl is already known invalid, don't check it. 7232 if (NewVD->isInvalidDecl()) 7233 return; 7234 7235 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7236 QualType T = TInfo->getType(); 7237 7238 // Defer checking an 'auto' type until its initializer is attached. 7239 if (T->isUndeducedType()) 7240 return; 7241 7242 if (NewVD->hasAttrs()) 7243 CheckAlignasUnderalignment(NewVD); 7244 7245 if (T->isObjCObjectType()) { 7246 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7247 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7248 T = Context.getObjCObjectPointerType(T); 7249 NewVD->setType(T); 7250 } 7251 7252 // Emit an error if an address space was applied to decl with local storage. 7253 // This includes arrays of objects with address space qualifiers, but not 7254 // automatic variables that point to other address spaces. 7255 // ISO/IEC TR 18037 S5.1.2 7256 if (!getLangOpts().OpenCL 7257 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7258 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7259 NewVD->setInvalidDecl(); 7260 return; 7261 } 7262 7263 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7264 // scope. 7265 if (getLangOpts().OpenCLVersion == 120 && 7266 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7267 NewVD->isStaticLocal()) { 7268 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7269 NewVD->setInvalidDecl(); 7270 return; 7271 } 7272 7273 if (getLangOpts().OpenCL) { 7274 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7275 if (NewVD->hasAttr<BlocksAttr>()) { 7276 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7277 return; 7278 } 7279 7280 if (T->isBlockPointerType()) { 7281 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7282 // can't use 'extern' storage class. 7283 if (!T.isConstQualified()) { 7284 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7285 << 0 /*const*/; 7286 NewVD->setInvalidDecl(); 7287 return; 7288 } 7289 if (NewVD->hasExternalStorage()) { 7290 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7291 NewVD->setInvalidDecl(); 7292 return; 7293 } 7294 } 7295 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7296 // __constant address space. 7297 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7298 // variables inside a function can also be declared in the global 7299 // address space. 7300 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7301 NewVD->hasExternalStorage()) { 7302 if (!T->isSamplerT() && 7303 !(T.getAddressSpace() == LangAS::opencl_constant || 7304 (T.getAddressSpace() == LangAS::opencl_global && 7305 getLangOpts().OpenCLVersion == 200))) { 7306 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7307 if (getLangOpts().OpenCLVersion == 200) 7308 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7309 << Scope << "global or constant"; 7310 else 7311 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7312 << Scope << "constant"; 7313 NewVD->setInvalidDecl(); 7314 return; 7315 } 7316 } else { 7317 if (T.getAddressSpace() == LangAS::opencl_global) { 7318 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7319 << 1 /*is any function*/ << "global"; 7320 NewVD->setInvalidDecl(); 7321 return; 7322 } 7323 if (T.getAddressSpace() == LangAS::opencl_constant || 7324 T.getAddressSpace() == LangAS::opencl_local) { 7325 FunctionDecl *FD = getCurFunctionDecl(); 7326 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7327 // in functions. 7328 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7329 if (T.getAddressSpace() == LangAS::opencl_constant) 7330 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7331 << 0 /*non-kernel only*/ << "constant"; 7332 else 7333 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7334 << 0 /*non-kernel only*/ << "local"; 7335 NewVD->setInvalidDecl(); 7336 return; 7337 } 7338 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7339 // in the outermost scope of a kernel function. 7340 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7341 if (!getCurScope()->isFunctionScope()) { 7342 if (T.getAddressSpace() == LangAS::opencl_constant) 7343 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7344 << "constant"; 7345 else 7346 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7347 << "local"; 7348 NewVD->setInvalidDecl(); 7349 return; 7350 } 7351 } 7352 } else if (T.getAddressSpace() != LangAS::Default) { 7353 // Do not allow other address spaces on automatic variable. 7354 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7355 NewVD->setInvalidDecl(); 7356 return; 7357 } 7358 } 7359 } 7360 7361 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7362 && !NewVD->hasAttr<BlocksAttr>()) { 7363 if (getLangOpts().getGC() != LangOptions::NonGC) 7364 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7365 else { 7366 assert(!getLangOpts().ObjCAutoRefCount); 7367 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7368 } 7369 } 7370 7371 bool isVM = T->isVariablyModifiedType(); 7372 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7373 NewVD->hasAttr<BlocksAttr>()) 7374 getCurFunction()->setHasBranchProtectedScope(); 7375 7376 if ((isVM && NewVD->hasLinkage()) || 7377 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7378 bool SizeIsNegative; 7379 llvm::APSInt Oversized; 7380 TypeSourceInfo *FixedTInfo = 7381 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7382 SizeIsNegative, Oversized); 7383 if (!FixedTInfo && T->isVariableArrayType()) { 7384 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7385 // FIXME: This won't give the correct result for 7386 // int a[10][n]; 7387 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7388 7389 if (NewVD->isFileVarDecl()) 7390 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7391 << SizeRange; 7392 else if (NewVD->isStaticLocal()) 7393 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7394 << SizeRange; 7395 else 7396 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7397 << SizeRange; 7398 NewVD->setInvalidDecl(); 7399 return; 7400 } 7401 7402 if (!FixedTInfo) { 7403 if (NewVD->isFileVarDecl()) 7404 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7405 else 7406 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7407 NewVD->setInvalidDecl(); 7408 return; 7409 } 7410 7411 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7412 NewVD->setType(FixedTInfo->getType()); 7413 NewVD->setTypeSourceInfo(FixedTInfo); 7414 } 7415 7416 if (T->isVoidType()) { 7417 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7418 // of objects and functions. 7419 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7420 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7421 << T; 7422 NewVD->setInvalidDecl(); 7423 return; 7424 } 7425 } 7426 7427 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7428 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7429 NewVD->setInvalidDecl(); 7430 return; 7431 } 7432 7433 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7434 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7435 NewVD->setInvalidDecl(); 7436 return; 7437 } 7438 7439 if (NewVD->isConstexpr() && !T->isDependentType() && 7440 RequireLiteralType(NewVD->getLocation(), T, 7441 diag::err_constexpr_var_non_literal)) { 7442 NewVD->setInvalidDecl(); 7443 return; 7444 } 7445 } 7446 7447 /// \brief Perform semantic checking on a newly-created variable 7448 /// declaration. 7449 /// 7450 /// This routine performs all of the type-checking required for a 7451 /// variable declaration once it has been built. It is used both to 7452 /// check variables after they have been parsed and their declarators 7453 /// have been translated into a declaration, and to check variables 7454 /// that have been instantiated from a template. 7455 /// 7456 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7457 /// 7458 /// Returns true if the variable declaration is a redeclaration. 7459 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7460 CheckVariableDeclarationType(NewVD); 7461 7462 // If the decl is already known invalid, don't check it. 7463 if (NewVD->isInvalidDecl()) 7464 return false; 7465 7466 // If we did not find anything by this name, look for a non-visible 7467 // extern "C" declaration with the same name. 7468 if (Previous.empty() && 7469 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7470 Previous.setShadowed(); 7471 7472 if (!Previous.empty()) { 7473 MergeVarDecl(NewVD, Previous); 7474 return true; 7475 } 7476 return false; 7477 } 7478 7479 namespace { 7480 struct FindOverriddenMethod { 7481 Sema *S; 7482 CXXMethodDecl *Method; 7483 7484 /// Member lookup function that determines whether a given C++ 7485 /// method overrides a method in a base class, to be used with 7486 /// CXXRecordDecl::lookupInBases(). 7487 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7488 RecordDecl *BaseRecord = 7489 Specifier->getType()->getAs<RecordType>()->getDecl(); 7490 7491 DeclarationName Name = Method->getDeclName(); 7492 7493 // FIXME: Do we care about other names here too? 7494 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7495 // We really want to find the base class destructor here. 7496 QualType T = S->Context.getTypeDeclType(BaseRecord); 7497 CanQualType CT = S->Context.getCanonicalType(T); 7498 7499 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7500 } 7501 7502 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7503 Path.Decls = Path.Decls.slice(1)) { 7504 NamedDecl *D = Path.Decls.front(); 7505 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7506 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7507 return true; 7508 } 7509 } 7510 7511 return false; 7512 } 7513 }; 7514 7515 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7516 } // end anonymous namespace 7517 7518 /// \brief Report an error regarding overriding, along with any relevant 7519 /// overriden methods. 7520 /// 7521 /// \param DiagID the primary error to report. 7522 /// \param MD the overriding method. 7523 /// \param OEK which overrides to include as notes. 7524 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7525 OverrideErrorKind OEK = OEK_All) { 7526 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7527 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7528 E = MD->end_overridden_methods(); 7529 I != E; ++I) { 7530 // This check (& the OEK parameter) could be replaced by a predicate, but 7531 // without lambdas that would be overkill. This is still nicer than writing 7532 // out the diag loop 3 times. 7533 if ((OEK == OEK_All) || 7534 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7535 (OEK == OEK_Deleted && (*I)->isDeleted())) 7536 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7537 } 7538 } 7539 7540 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7541 /// and if so, check that it's a valid override and remember it. 7542 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7543 // Look for methods in base classes that this method might override. 7544 CXXBasePaths Paths; 7545 FindOverriddenMethod FOM; 7546 FOM.Method = MD; 7547 FOM.S = this; 7548 bool hasDeletedOverridenMethods = false; 7549 bool hasNonDeletedOverridenMethods = false; 7550 bool AddedAny = false; 7551 if (DC->lookupInBases(FOM, Paths)) { 7552 for (auto *I : Paths.found_decls()) { 7553 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7554 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7555 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7556 !CheckOverridingFunctionAttributes(MD, OldMD) && 7557 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7558 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7559 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7560 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7561 AddedAny = true; 7562 } 7563 } 7564 } 7565 } 7566 7567 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7568 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7569 } 7570 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7571 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7572 } 7573 7574 return AddedAny; 7575 } 7576 7577 namespace { 7578 // Struct for holding all of the extra arguments needed by 7579 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7580 struct ActOnFDArgs { 7581 Scope *S; 7582 Declarator &D; 7583 MultiTemplateParamsArg TemplateParamLists; 7584 bool AddToScope; 7585 }; 7586 } // end anonymous namespace 7587 7588 namespace { 7589 7590 // Callback to only accept typo corrections that have a non-zero edit distance. 7591 // Also only accept corrections that have the same parent decl. 7592 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7593 public: 7594 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7595 CXXRecordDecl *Parent) 7596 : Context(Context), OriginalFD(TypoFD), 7597 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7598 7599 bool ValidateCandidate(const TypoCorrection &candidate) override { 7600 if (candidate.getEditDistance() == 0) 7601 return false; 7602 7603 SmallVector<unsigned, 1> MismatchedParams; 7604 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7605 CDeclEnd = candidate.end(); 7606 CDecl != CDeclEnd; ++CDecl) { 7607 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7608 7609 if (FD && !FD->hasBody() && 7610 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7611 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7612 CXXRecordDecl *Parent = MD->getParent(); 7613 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7614 return true; 7615 } else if (!ExpectedParent) { 7616 return true; 7617 } 7618 } 7619 } 7620 7621 return false; 7622 } 7623 7624 private: 7625 ASTContext &Context; 7626 FunctionDecl *OriginalFD; 7627 CXXRecordDecl *ExpectedParent; 7628 }; 7629 7630 } // end anonymous namespace 7631 7632 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7633 TypoCorrectedFunctionDefinitions.insert(F); 7634 } 7635 7636 /// \brief Generate diagnostics for an invalid function redeclaration. 7637 /// 7638 /// This routine handles generating the diagnostic messages for an invalid 7639 /// function redeclaration, including finding possible similar declarations 7640 /// or performing typo correction if there are no previous declarations with 7641 /// the same name. 7642 /// 7643 /// Returns a NamedDecl iff typo correction was performed and substituting in 7644 /// the new declaration name does not cause new errors. 7645 static NamedDecl *DiagnoseInvalidRedeclaration( 7646 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7647 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7648 DeclarationName Name = NewFD->getDeclName(); 7649 DeclContext *NewDC = NewFD->getDeclContext(); 7650 SmallVector<unsigned, 1> MismatchedParams; 7651 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7652 TypoCorrection Correction; 7653 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7654 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7655 : diag::err_member_decl_does_not_match; 7656 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7657 IsLocalFriend ? Sema::LookupLocalFriendName 7658 : Sema::LookupOrdinaryName, 7659 Sema::ForRedeclaration); 7660 7661 NewFD->setInvalidDecl(); 7662 if (IsLocalFriend) 7663 SemaRef.LookupName(Prev, S); 7664 else 7665 SemaRef.LookupQualifiedName(Prev, NewDC); 7666 assert(!Prev.isAmbiguous() && 7667 "Cannot have an ambiguity in previous-declaration lookup"); 7668 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7669 if (!Prev.empty()) { 7670 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7671 Func != FuncEnd; ++Func) { 7672 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7673 if (FD && 7674 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7675 // Add 1 to the index so that 0 can mean the mismatch didn't 7676 // involve a parameter 7677 unsigned ParamNum = 7678 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7679 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7680 } 7681 } 7682 // If the qualified name lookup yielded nothing, try typo correction 7683 } else if ((Correction = SemaRef.CorrectTypo( 7684 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7685 &ExtraArgs.D.getCXXScopeSpec(), 7686 llvm::make_unique<DifferentNameValidatorCCC>( 7687 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7688 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7689 // Set up everything for the call to ActOnFunctionDeclarator 7690 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7691 ExtraArgs.D.getIdentifierLoc()); 7692 Previous.clear(); 7693 Previous.setLookupName(Correction.getCorrection()); 7694 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7695 CDeclEnd = Correction.end(); 7696 CDecl != CDeclEnd; ++CDecl) { 7697 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7698 if (FD && !FD->hasBody() && 7699 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7700 Previous.addDecl(FD); 7701 } 7702 } 7703 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7704 7705 NamedDecl *Result; 7706 // Retry building the function declaration with the new previous 7707 // declarations, and with errors suppressed. 7708 { 7709 // Trap errors. 7710 Sema::SFINAETrap Trap(SemaRef); 7711 7712 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7713 // pieces need to verify the typo-corrected C++ declaration and hopefully 7714 // eliminate the need for the parameter pack ExtraArgs. 7715 Result = SemaRef.ActOnFunctionDeclarator( 7716 ExtraArgs.S, ExtraArgs.D, 7717 Correction.getCorrectionDecl()->getDeclContext(), 7718 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7719 ExtraArgs.AddToScope); 7720 7721 if (Trap.hasErrorOccurred()) 7722 Result = nullptr; 7723 } 7724 7725 if (Result) { 7726 // Determine which correction we picked. 7727 Decl *Canonical = Result->getCanonicalDecl(); 7728 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7729 I != E; ++I) 7730 if ((*I)->getCanonicalDecl() == Canonical) 7731 Correction.setCorrectionDecl(*I); 7732 7733 // Let Sema know about the correction. 7734 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7735 SemaRef.diagnoseTypo( 7736 Correction, 7737 SemaRef.PDiag(IsLocalFriend 7738 ? diag::err_no_matching_local_friend_suggest 7739 : diag::err_member_decl_does_not_match_suggest) 7740 << Name << NewDC << IsDefinition); 7741 return Result; 7742 } 7743 7744 // Pretend the typo correction never occurred 7745 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7746 ExtraArgs.D.getIdentifierLoc()); 7747 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7748 Previous.clear(); 7749 Previous.setLookupName(Name); 7750 } 7751 7752 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7753 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7754 7755 bool NewFDisConst = false; 7756 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7757 NewFDisConst = NewMD->isConst(); 7758 7759 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7760 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7761 NearMatch != NearMatchEnd; ++NearMatch) { 7762 FunctionDecl *FD = NearMatch->first; 7763 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7764 bool FDisConst = MD && MD->isConst(); 7765 bool IsMember = MD || !IsLocalFriend; 7766 7767 // FIXME: These notes are poorly worded for the local friend case. 7768 if (unsigned Idx = NearMatch->second) { 7769 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7770 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7771 if (Loc.isInvalid()) Loc = FD->getLocation(); 7772 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7773 : diag::note_local_decl_close_param_match) 7774 << Idx << FDParam->getType() 7775 << NewFD->getParamDecl(Idx - 1)->getType(); 7776 } else if (FDisConst != NewFDisConst) { 7777 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7778 << NewFDisConst << FD->getSourceRange().getEnd(); 7779 } else 7780 SemaRef.Diag(FD->getLocation(), 7781 IsMember ? diag::note_member_def_close_match 7782 : diag::note_local_decl_close_match); 7783 } 7784 return nullptr; 7785 } 7786 7787 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7788 switch (D.getDeclSpec().getStorageClassSpec()) { 7789 default: llvm_unreachable("Unknown storage class!"); 7790 case DeclSpec::SCS_auto: 7791 case DeclSpec::SCS_register: 7792 case DeclSpec::SCS_mutable: 7793 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7794 diag::err_typecheck_sclass_func); 7795 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7796 D.setInvalidType(); 7797 break; 7798 case DeclSpec::SCS_unspecified: break; 7799 case DeclSpec::SCS_extern: 7800 if (D.getDeclSpec().isExternInLinkageSpec()) 7801 return SC_None; 7802 return SC_Extern; 7803 case DeclSpec::SCS_static: { 7804 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7805 // C99 6.7.1p5: 7806 // The declaration of an identifier for a function that has 7807 // block scope shall have no explicit storage-class specifier 7808 // other than extern 7809 // See also (C++ [dcl.stc]p4). 7810 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7811 diag::err_static_block_func); 7812 break; 7813 } else 7814 return SC_Static; 7815 } 7816 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7817 } 7818 7819 // No explicit storage class has already been returned 7820 return SC_None; 7821 } 7822 7823 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7824 DeclContext *DC, QualType &R, 7825 TypeSourceInfo *TInfo, 7826 StorageClass SC, 7827 bool &IsVirtualOkay) { 7828 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7829 DeclarationName Name = NameInfo.getName(); 7830 7831 FunctionDecl *NewFD = nullptr; 7832 bool isInline = D.getDeclSpec().isInlineSpecified(); 7833 7834 if (!SemaRef.getLangOpts().CPlusPlus) { 7835 // Determine whether the function was written with a 7836 // prototype. This true when: 7837 // - there is a prototype in the declarator, or 7838 // - the type R of the function is some kind of typedef or other non- 7839 // attributed reference to a type name (which eventually refers to a 7840 // function type). 7841 bool HasPrototype = 7842 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7843 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7844 7845 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7846 D.getLocStart(), NameInfo, R, 7847 TInfo, SC, isInline, 7848 HasPrototype, false); 7849 if (D.isInvalidType()) 7850 NewFD->setInvalidDecl(); 7851 7852 return NewFD; 7853 } 7854 7855 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7856 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7857 7858 // Check that the return type is not an abstract class type. 7859 // For record types, this is done by the AbstractClassUsageDiagnoser once 7860 // the class has been completely parsed. 7861 if (!DC->isRecord() && 7862 SemaRef.RequireNonAbstractType( 7863 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7864 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7865 D.setInvalidType(); 7866 7867 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7868 // This is a C++ constructor declaration. 7869 assert(DC->isRecord() && 7870 "Constructors can only be declared in a member context"); 7871 7872 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7873 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7874 D.getLocStart(), NameInfo, 7875 R, TInfo, isExplicit, isInline, 7876 /*isImplicitlyDeclared=*/false, 7877 isConstexpr); 7878 7879 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7880 // This is a C++ destructor declaration. 7881 if (DC->isRecord()) { 7882 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7883 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7884 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7885 SemaRef.Context, Record, 7886 D.getLocStart(), 7887 NameInfo, R, TInfo, isInline, 7888 /*isImplicitlyDeclared=*/false); 7889 7890 // If the class is complete, then we now create the implicit exception 7891 // specification. If the class is incomplete or dependent, we can't do 7892 // it yet. 7893 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7894 Record->getDefinition() && !Record->isBeingDefined() && 7895 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7896 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7897 } 7898 7899 IsVirtualOkay = true; 7900 return NewDD; 7901 7902 } else { 7903 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7904 D.setInvalidType(); 7905 7906 // Create a FunctionDecl to satisfy the function definition parsing 7907 // code path. 7908 return FunctionDecl::Create(SemaRef.Context, DC, 7909 D.getLocStart(), 7910 D.getIdentifierLoc(), Name, R, TInfo, 7911 SC, isInline, 7912 /*hasPrototype=*/true, isConstexpr); 7913 } 7914 7915 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7916 if (!DC->isRecord()) { 7917 SemaRef.Diag(D.getIdentifierLoc(), 7918 diag::err_conv_function_not_member); 7919 return nullptr; 7920 } 7921 7922 SemaRef.CheckConversionDeclarator(D, R, SC); 7923 IsVirtualOkay = true; 7924 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7925 D.getLocStart(), NameInfo, 7926 R, TInfo, isInline, isExplicit, 7927 isConstexpr, SourceLocation()); 7928 7929 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7930 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7931 7932 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7933 isExplicit, NameInfo, R, TInfo, 7934 D.getLocEnd()); 7935 } else if (DC->isRecord()) { 7936 // If the name of the function is the same as the name of the record, 7937 // then this must be an invalid constructor that has a return type. 7938 // (The parser checks for a return type and makes the declarator a 7939 // constructor if it has no return type). 7940 if (Name.getAsIdentifierInfo() && 7941 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7942 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7943 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7944 << SourceRange(D.getIdentifierLoc()); 7945 return nullptr; 7946 } 7947 7948 // This is a C++ method declaration. 7949 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7950 cast<CXXRecordDecl>(DC), 7951 D.getLocStart(), NameInfo, R, 7952 TInfo, SC, isInline, 7953 isConstexpr, SourceLocation()); 7954 IsVirtualOkay = !Ret->isStatic(); 7955 return Ret; 7956 } else { 7957 bool isFriend = 7958 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7959 if (!isFriend && SemaRef.CurContext->isRecord()) 7960 return nullptr; 7961 7962 // Determine whether the function was written with a 7963 // prototype. This true when: 7964 // - we're in C++ (where every function has a prototype), 7965 return FunctionDecl::Create(SemaRef.Context, DC, 7966 D.getLocStart(), 7967 NameInfo, R, TInfo, SC, isInline, 7968 true/*HasPrototype*/, isConstexpr); 7969 } 7970 } 7971 7972 enum OpenCLParamType { 7973 ValidKernelParam, 7974 PtrPtrKernelParam, 7975 PtrKernelParam, 7976 InvalidAddrSpacePtrKernelParam, 7977 InvalidKernelParam, 7978 RecordKernelParam 7979 }; 7980 7981 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7982 if (PT->isPointerType()) { 7983 QualType PointeeType = PT->getPointeeType(); 7984 if (PointeeType->isPointerType()) 7985 return PtrPtrKernelParam; 7986 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7987 PointeeType.getAddressSpace() == 0) 7988 return InvalidAddrSpacePtrKernelParam; 7989 return PtrKernelParam; 7990 } 7991 7992 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7993 // be used as builtin types. 7994 7995 if (PT->isImageType()) 7996 return PtrKernelParam; 7997 7998 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 7999 return InvalidKernelParam; 8000 8001 // OpenCL extension spec v1.2 s9.5: 8002 // This extension adds support for half scalar and vector types as built-in 8003 // types that can be used for arithmetic operations, conversions etc. 8004 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8005 return InvalidKernelParam; 8006 8007 if (PT->isRecordType()) 8008 return RecordKernelParam; 8009 8010 return ValidKernelParam; 8011 } 8012 8013 static void checkIsValidOpenCLKernelParameter( 8014 Sema &S, 8015 Declarator &D, 8016 ParmVarDecl *Param, 8017 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8018 QualType PT = Param->getType(); 8019 8020 // Cache the valid types we encounter to avoid rechecking structs that are 8021 // used again 8022 if (ValidTypes.count(PT.getTypePtr())) 8023 return; 8024 8025 switch (getOpenCLKernelParameterType(S, PT)) { 8026 case PtrPtrKernelParam: 8027 // OpenCL v1.2 s6.9.a: 8028 // A kernel function argument cannot be declared as a 8029 // pointer to a pointer type. 8030 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8031 D.setInvalidType(); 8032 return; 8033 8034 case InvalidAddrSpacePtrKernelParam: 8035 // OpenCL v1.0 s6.5: 8036 // __kernel function arguments declared to be a pointer of a type can point 8037 // to one of the following address spaces only : __global, __local or 8038 // __constant. 8039 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8040 D.setInvalidType(); 8041 return; 8042 8043 // OpenCL v1.2 s6.9.k: 8044 // Arguments to kernel functions in a program cannot be declared with the 8045 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8046 // uintptr_t or a struct and/or union that contain fields declared to be 8047 // one of these built-in scalar types. 8048 8049 case InvalidKernelParam: 8050 // OpenCL v1.2 s6.8 n: 8051 // A kernel function argument cannot be declared 8052 // of event_t type. 8053 // Do not diagnose half type since it is diagnosed as invalid argument 8054 // type for any function elsewhere. 8055 if (!PT->isHalfType()) 8056 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8057 D.setInvalidType(); 8058 return; 8059 8060 case PtrKernelParam: 8061 case ValidKernelParam: 8062 ValidTypes.insert(PT.getTypePtr()); 8063 return; 8064 8065 case RecordKernelParam: 8066 break; 8067 } 8068 8069 // Track nested structs we will inspect 8070 SmallVector<const Decl *, 4> VisitStack; 8071 8072 // Track where we are in the nested structs. Items will migrate from 8073 // VisitStack to HistoryStack as we do the DFS for bad field. 8074 SmallVector<const FieldDecl *, 4> HistoryStack; 8075 HistoryStack.push_back(nullptr); 8076 8077 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8078 VisitStack.push_back(PD); 8079 8080 assert(VisitStack.back() && "First decl null?"); 8081 8082 do { 8083 const Decl *Next = VisitStack.pop_back_val(); 8084 if (!Next) { 8085 assert(!HistoryStack.empty()); 8086 // Found a marker, we have gone up a level 8087 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8088 ValidTypes.insert(Hist->getType().getTypePtr()); 8089 8090 continue; 8091 } 8092 8093 // Adds everything except the original parameter declaration (which is not a 8094 // field itself) to the history stack. 8095 const RecordDecl *RD; 8096 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8097 HistoryStack.push_back(Field); 8098 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8099 } else { 8100 RD = cast<RecordDecl>(Next); 8101 } 8102 8103 // Add a null marker so we know when we've gone back up a level 8104 VisitStack.push_back(nullptr); 8105 8106 for (const auto *FD : RD->fields()) { 8107 QualType QT = FD->getType(); 8108 8109 if (ValidTypes.count(QT.getTypePtr())) 8110 continue; 8111 8112 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8113 if (ParamType == ValidKernelParam) 8114 continue; 8115 8116 if (ParamType == RecordKernelParam) { 8117 VisitStack.push_back(FD); 8118 continue; 8119 } 8120 8121 // OpenCL v1.2 s6.9.p: 8122 // Arguments to kernel functions that are declared to be a struct or union 8123 // do not allow OpenCL objects to be passed as elements of the struct or 8124 // union. 8125 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8126 ParamType == InvalidAddrSpacePtrKernelParam) { 8127 S.Diag(Param->getLocation(), 8128 diag::err_record_with_pointers_kernel_param) 8129 << PT->isUnionType() 8130 << PT; 8131 } else { 8132 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8133 } 8134 8135 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8136 << PD->getDeclName(); 8137 8138 // We have an error, now let's go back up through history and show where 8139 // the offending field came from 8140 for (ArrayRef<const FieldDecl *>::const_iterator 8141 I = HistoryStack.begin() + 1, 8142 E = HistoryStack.end(); 8143 I != E; ++I) { 8144 const FieldDecl *OuterField = *I; 8145 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8146 << OuterField->getType(); 8147 } 8148 8149 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8150 << QT->isPointerType() 8151 << QT; 8152 D.setInvalidType(); 8153 return; 8154 } 8155 } while (!VisitStack.empty()); 8156 } 8157 8158 /// Find the DeclContext in which a tag is implicitly declared if we see an 8159 /// elaborated type specifier in the specified context, and lookup finds 8160 /// nothing. 8161 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8162 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8163 DC = DC->getParent(); 8164 return DC; 8165 } 8166 8167 /// Find the Scope in which a tag is implicitly declared if we see an 8168 /// elaborated type specifier in the specified context, and lookup finds 8169 /// nothing. 8170 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8171 while (S->isClassScope() || 8172 (LangOpts.CPlusPlus && 8173 S->isFunctionPrototypeScope()) || 8174 ((S->getFlags() & Scope::DeclScope) == 0) || 8175 (S->getEntity() && S->getEntity()->isTransparentContext())) 8176 S = S->getParent(); 8177 return S; 8178 } 8179 8180 NamedDecl* 8181 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8182 TypeSourceInfo *TInfo, LookupResult &Previous, 8183 MultiTemplateParamsArg TemplateParamLists, 8184 bool &AddToScope) { 8185 QualType R = TInfo->getType(); 8186 8187 assert(R.getTypePtr()->isFunctionType()); 8188 8189 // TODO: consider using NameInfo for diagnostic. 8190 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8191 DeclarationName Name = NameInfo.getName(); 8192 StorageClass SC = getFunctionStorageClass(*this, D); 8193 8194 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8195 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8196 diag::err_invalid_thread) 8197 << DeclSpec::getSpecifierName(TSCS); 8198 8199 if (D.isFirstDeclarationOfMember()) 8200 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8201 D.getIdentifierLoc()); 8202 8203 bool isFriend = false; 8204 FunctionTemplateDecl *FunctionTemplate = nullptr; 8205 bool isMemberSpecialization = false; 8206 bool isFunctionTemplateSpecialization = false; 8207 8208 bool isDependentClassScopeExplicitSpecialization = false; 8209 bool HasExplicitTemplateArgs = false; 8210 TemplateArgumentListInfo TemplateArgs; 8211 8212 bool isVirtualOkay = false; 8213 8214 DeclContext *OriginalDC = DC; 8215 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8216 8217 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8218 isVirtualOkay); 8219 if (!NewFD) return nullptr; 8220 8221 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8222 NewFD->setTopLevelDeclInObjCContainer(); 8223 8224 // Set the lexical context. If this is a function-scope declaration, or has a 8225 // C++ scope specifier, or is the object of a friend declaration, the lexical 8226 // context will be different from the semantic context. 8227 NewFD->setLexicalDeclContext(CurContext); 8228 8229 if (IsLocalExternDecl) 8230 NewFD->setLocalExternDecl(); 8231 8232 if (getLangOpts().CPlusPlus) { 8233 bool isInline = D.getDeclSpec().isInlineSpecified(); 8234 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8235 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8236 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8237 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8238 isFriend = D.getDeclSpec().isFriendSpecified(); 8239 if (isFriend && !isInline && D.isFunctionDefinition()) { 8240 // C++ [class.friend]p5 8241 // A function can be defined in a friend declaration of a 8242 // class . . . . Such a function is implicitly inline. 8243 NewFD->setImplicitlyInline(); 8244 } 8245 8246 // If this is a method defined in an __interface, and is not a constructor 8247 // or an overloaded operator, then set the pure flag (isVirtual will already 8248 // return true). 8249 if (const CXXRecordDecl *Parent = 8250 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8251 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8252 NewFD->setPure(true); 8253 8254 // C++ [class.union]p2 8255 // A union can have member functions, but not virtual functions. 8256 if (isVirtual && Parent->isUnion()) 8257 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8258 } 8259 8260 SetNestedNameSpecifier(NewFD, D); 8261 isMemberSpecialization = false; 8262 isFunctionTemplateSpecialization = false; 8263 if (D.isInvalidType()) 8264 NewFD->setInvalidDecl(); 8265 8266 // Match up the template parameter lists with the scope specifier, then 8267 // determine whether we have a template or a template specialization. 8268 bool Invalid = false; 8269 if (TemplateParameterList *TemplateParams = 8270 MatchTemplateParametersToScopeSpecifier( 8271 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8272 D.getCXXScopeSpec(), 8273 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8274 ? D.getName().TemplateId 8275 : nullptr, 8276 TemplateParamLists, isFriend, isMemberSpecialization, 8277 Invalid)) { 8278 if (TemplateParams->size() > 0) { 8279 // This is a function template 8280 8281 // Check that we can declare a template here. 8282 if (CheckTemplateDeclScope(S, TemplateParams)) 8283 NewFD->setInvalidDecl(); 8284 8285 // A destructor cannot be a template. 8286 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8287 Diag(NewFD->getLocation(), diag::err_destructor_template); 8288 NewFD->setInvalidDecl(); 8289 } 8290 8291 // If we're adding a template to a dependent context, we may need to 8292 // rebuilding some of the types used within the template parameter list, 8293 // now that we know what the current instantiation is. 8294 if (DC->isDependentContext()) { 8295 ContextRAII SavedContext(*this, DC); 8296 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8297 Invalid = true; 8298 } 8299 8300 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8301 NewFD->getLocation(), 8302 Name, TemplateParams, 8303 NewFD); 8304 FunctionTemplate->setLexicalDeclContext(CurContext); 8305 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8306 8307 // For source fidelity, store the other template param lists. 8308 if (TemplateParamLists.size() > 1) { 8309 NewFD->setTemplateParameterListsInfo(Context, 8310 TemplateParamLists.drop_back(1)); 8311 } 8312 } else { 8313 // This is a function template specialization. 8314 isFunctionTemplateSpecialization = true; 8315 // For source fidelity, store all the template param lists. 8316 if (TemplateParamLists.size() > 0) 8317 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8318 8319 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8320 if (isFriend) { 8321 // We want to remove the "template<>", found here. 8322 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8323 8324 // If we remove the template<> and the name is not a 8325 // template-id, we're actually silently creating a problem: 8326 // the friend declaration will refer to an untemplated decl, 8327 // and clearly the user wants a template specialization. So 8328 // we need to insert '<>' after the name. 8329 SourceLocation InsertLoc; 8330 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8331 InsertLoc = D.getName().getSourceRange().getEnd(); 8332 InsertLoc = getLocForEndOfToken(InsertLoc); 8333 } 8334 8335 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8336 << Name << RemoveRange 8337 << FixItHint::CreateRemoval(RemoveRange) 8338 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8339 } 8340 } 8341 } 8342 else { 8343 // All template param lists were matched against the scope specifier: 8344 // this is NOT (an explicit specialization of) a template. 8345 if (TemplateParamLists.size() > 0) 8346 // For source fidelity, store all the template param lists. 8347 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8348 } 8349 8350 if (Invalid) { 8351 NewFD->setInvalidDecl(); 8352 if (FunctionTemplate) 8353 FunctionTemplate->setInvalidDecl(); 8354 } 8355 8356 // C++ [dcl.fct.spec]p5: 8357 // The virtual specifier shall only be used in declarations of 8358 // nonstatic class member functions that appear within a 8359 // member-specification of a class declaration; see 10.3. 8360 // 8361 if (isVirtual && !NewFD->isInvalidDecl()) { 8362 if (!isVirtualOkay) { 8363 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8364 diag::err_virtual_non_function); 8365 } else if (!CurContext->isRecord()) { 8366 // 'virtual' was specified outside of the class. 8367 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8368 diag::err_virtual_out_of_class) 8369 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8370 } else if (NewFD->getDescribedFunctionTemplate()) { 8371 // C++ [temp.mem]p3: 8372 // A member function template shall not be virtual. 8373 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8374 diag::err_virtual_member_function_template) 8375 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8376 } else { 8377 // Okay: Add virtual to the method. 8378 NewFD->setVirtualAsWritten(true); 8379 } 8380 8381 if (getLangOpts().CPlusPlus14 && 8382 NewFD->getReturnType()->isUndeducedType()) 8383 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8384 } 8385 8386 if (getLangOpts().CPlusPlus14 && 8387 (NewFD->isDependentContext() || 8388 (isFriend && CurContext->isDependentContext())) && 8389 NewFD->getReturnType()->isUndeducedType()) { 8390 // If the function template is referenced directly (for instance, as a 8391 // member of the current instantiation), pretend it has a dependent type. 8392 // This is not really justified by the standard, but is the only sane 8393 // thing to do. 8394 // FIXME: For a friend function, we have not marked the function as being 8395 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8396 const FunctionProtoType *FPT = 8397 NewFD->getType()->castAs<FunctionProtoType>(); 8398 QualType Result = 8399 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8400 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8401 FPT->getExtProtoInfo())); 8402 } 8403 8404 // C++ [dcl.fct.spec]p3: 8405 // The inline specifier shall not appear on a block scope function 8406 // declaration. 8407 if (isInline && !NewFD->isInvalidDecl()) { 8408 if (CurContext->isFunctionOrMethod()) { 8409 // 'inline' is not allowed on block scope function declaration. 8410 Diag(D.getDeclSpec().getInlineSpecLoc(), 8411 diag::err_inline_declaration_block_scope) << Name 8412 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8413 } 8414 } 8415 8416 // C++ [dcl.fct.spec]p6: 8417 // The explicit specifier shall be used only in the declaration of a 8418 // constructor or conversion function within its class definition; 8419 // see 12.3.1 and 12.3.2. 8420 if (isExplicit && !NewFD->isInvalidDecl() && 8421 !isa<CXXDeductionGuideDecl>(NewFD)) { 8422 if (!CurContext->isRecord()) { 8423 // 'explicit' was specified outside of the class. 8424 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8425 diag::err_explicit_out_of_class) 8426 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8427 } else if (!isa<CXXConstructorDecl>(NewFD) && 8428 !isa<CXXConversionDecl>(NewFD)) { 8429 // 'explicit' was specified on a function that wasn't a constructor 8430 // or conversion function. 8431 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8432 diag::err_explicit_non_ctor_or_conv_function) 8433 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8434 } 8435 } 8436 8437 if (isConstexpr) { 8438 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8439 // are implicitly inline. 8440 NewFD->setImplicitlyInline(); 8441 8442 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8443 // be either constructors or to return a literal type. Therefore, 8444 // destructors cannot be declared constexpr. 8445 if (isa<CXXDestructorDecl>(NewFD)) 8446 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8447 } 8448 8449 if (isConcept) { 8450 // This is a function concept. 8451 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8452 FTD->setConcept(); 8453 8454 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8455 // applied only to the definition of a function template [...] 8456 if (!D.isFunctionDefinition()) { 8457 Diag(D.getDeclSpec().getConceptSpecLoc(), 8458 diag::err_function_concept_not_defined); 8459 NewFD->setInvalidDecl(); 8460 } 8461 8462 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8463 // have no exception-specification and is treated as if it were specified 8464 // with noexcept(true) (15.4). [...] 8465 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8466 if (FPT->hasExceptionSpec()) { 8467 SourceRange Range; 8468 if (D.isFunctionDeclarator()) 8469 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8470 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8471 << FixItHint::CreateRemoval(Range); 8472 NewFD->setInvalidDecl(); 8473 } else { 8474 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8475 } 8476 8477 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8478 // following restrictions: 8479 // - The declared return type shall have the type bool. 8480 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8481 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8482 NewFD->setInvalidDecl(); 8483 } 8484 8485 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8486 // following restrictions: 8487 // - The declaration's parameter list shall be equivalent to an empty 8488 // parameter list. 8489 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8490 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8491 } 8492 8493 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8494 // implicity defined to be a constexpr declaration (implicitly inline) 8495 NewFD->setImplicitlyInline(); 8496 8497 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8498 // be declared with the thread_local, inline, friend, or constexpr 8499 // specifiers, [...] 8500 if (isInline) { 8501 Diag(D.getDeclSpec().getInlineSpecLoc(), 8502 diag::err_concept_decl_invalid_specifiers) 8503 << 1 << 1; 8504 NewFD->setInvalidDecl(true); 8505 } 8506 8507 if (isFriend) { 8508 Diag(D.getDeclSpec().getFriendSpecLoc(), 8509 diag::err_concept_decl_invalid_specifiers) 8510 << 1 << 2; 8511 NewFD->setInvalidDecl(true); 8512 } 8513 8514 if (isConstexpr) { 8515 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8516 diag::err_concept_decl_invalid_specifiers) 8517 << 1 << 3; 8518 NewFD->setInvalidDecl(true); 8519 } 8520 8521 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8522 // applied only to the definition of a function template or variable 8523 // template, declared in namespace scope. 8524 if (isFunctionTemplateSpecialization) { 8525 Diag(D.getDeclSpec().getConceptSpecLoc(), 8526 diag::err_concept_specified_specialization) << 1; 8527 NewFD->setInvalidDecl(true); 8528 return NewFD; 8529 } 8530 } 8531 8532 // If __module_private__ was specified, mark the function accordingly. 8533 if (D.getDeclSpec().isModulePrivateSpecified()) { 8534 if (isFunctionTemplateSpecialization) { 8535 SourceLocation ModulePrivateLoc 8536 = D.getDeclSpec().getModulePrivateSpecLoc(); 8537 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8538 << 0 8539 << FixItHint::CreateRemoval(ModulePrivateLoc); 8540 } else { 8541 NewFD->setModulePrivate(); 8542 if (FunctionTemplate) 8543 FunctionTemplate->setModulePrivate(); 8544 } 8545 } 8546 8547 if (isFriend) { 8548 if (FunctionTemplate) { 8549 FunctionTemplate->setObjectOfFriendDecl(); 8550 FunctionTemplate->setAccess(AS_public); 8551 } 8552 NewFD->setObjectOfFriendDecl(); 8553 NewFD->setAccess(AS_public); 8554 } 8555 8556 // If a function is defined as defaulted or deleted, mark it as such now. 8557 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8558 // definition kind to FDK_Definition. 8559 switch (D.getFunctionDefinitionKind()) { 8560 case FDK_Declaration: 8561 case FDK_Definition: 8562 break; 8563 8564 case FDK_Defaulted: 8565 NewFD->setDefaulted(); 8566 break; 8567 8568 case FDK_Deleted: 8569 NewFD->setDeletedAsWritten(); 8570 break; 8571 } 8572 8573 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8574 D.isFunctionDefinition()) { 8575 // C++ [class.mfct]p2: 8576 // A member function may be defined (8.4) in its class definition, in 8577 // which case it is an inline member function (7.1.2) 8578 NewFD->setImplicitlyInline(); 8579 } 8580 8581 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8582 !CurContext->isRecord()) { 8583 // C++ [class.static]p1: 8584 // A data or function member of a class may be declared static 8585 // in a class definition, in which case it is a static member of 8586 // the class. 8587 8588 // Complain about the 'static' specifier if it's on an out-of-line 8589 // member function definition. 8590 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8591 diag::err_static_out_of_line) 8592 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8593 } 8594 8595 // C++11 [except.spec]p15: 8596 // A deallocation function with no exception-specification is treated 8597 // as if it were specified with noexcept(true). 8598 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8599 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8600 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8601 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8602 NewFD->setType(Context.getFunctionType( 8603 FPT->getReturnType(), FPT->getParamTypes(), 8604 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8605 } 8606 8607 // Filter out previous declarations that don't match the scope. 8608 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8609 D.getCXXScopeSpec().isNotEmpty() || 8610 isMemberSpecialization || 8611 isFunctionTemplateSpecialization); 8612 8613 // Handle GNU asm-label extension (encoded as an attribute). 8614 if (Expr *E = (Expr*) D.getAsmLabel()) { 8615 // The parser guarantees this is a string. 8616 StringLiteral *SE = cast<StringLiteral>(E); 8617 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8618 SE->getString(), 0)); 8619 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8620 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8621 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8622 if (I != ExtnameUndeclaredIdentifiers.end()) { 8623 if (isDeclExternC(NewFD)) { 8624 NewFD->addAttr(I->second); 8625 ExtnameUndeclaredIdentifiers.erase(I); 8626 } else 8627 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8628 << /*Variable*/0 << NewFD; 8629 } 8630 } 8631 8632 // Copy the parameter declarations from the declarator D to the function 8633 // declaration NewFD, if they are available. First scavenge them into Params. 8634 SmallVector<ParmVarDecl*, 16> Params; 8635 unsigned FTIIdx; 8636 if (D.isFunctionDeclarator(FTIIdx)) { 8637 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8638 8639 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8640 // function that takes no arguments, not a function that takes a 8641 // single void argument. 8642 // We let through "const void" here because Sema::GetTypeForDeclarator 8643 // already checks for that case. 8644 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8645 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8646 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8647 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8648 Param->setDeclContext(NewFD); 8649 Params.push_back(Param); 8650 8651 if (Param->isInvalidDecl()) 8652 NewFD->setInvalidDecl(); 8653 } 8654 } 8655 8656 if (!getLangOpts().CPlusPlus) { 8657 // In C, find all the tag declarations from the prototype and move them 8658 // into the function DeclContext. Remove them from the surrounding tag 8659 // injection context of the function, which is typically but not always 8660 // the TU. 8661 DeclContext *PrototypeTagContext = 8662 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8663 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8664 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8665 8666 // We don't want to reparent enumerators. Look at their parent enum 8667 // instead. 8668 if (!TD) { 8669 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8670 TD = cast<EnumDecl>(ECD->getDeclContext()); 8671 } 8672 if (!TD) 8673 continue; 8674 DeclContext *TagDC = TD->getLexicalDeclContext(); 8675 if (!TagDC->containsDecl(TD)) 8676 continue; 8677 TagDC->removeDecl(TD); 8678 TD->setDeclContext(NewFD); 8679 NewFD->addDecl(TD); 8680 8681 // Preserve the lexical DeclContext if it is not the surrounding tag 8682 // injection context of the FD. In this example, the semantic context of 8683 // E will be f and the lexical context will be S, while both the 8684 // semantic and lexical contexts of S will be f: 8685 // void f(struct S { enum E { a } f; } s); 8686 if (TagDC != PrototypeTagContext) 8687 TD->setLexicalDeclContext(TagDC); 8688 } 8689 } 8690 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8691 // When we're declaring a function with a typedef, typeof, etc as in the 8692 // following example, we'll need to synthesize (unnamed) 8693 // parameters for use in the declaration. 8694 // 8695 // @code 8696 // typedef void fn(int); 8697 // fn f; 8698 // @endcode 8699 8700 // Synthesize a parameter for each argument type. 8701 for (const auto &AI : FT->param_types()) { 8702 ParmVarDecl *Param = 8703 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8704 Param->setScopeInfo(0, Params.size()); 8705 Params.push_back(Param); 8706 } 8707 } else { 8708 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8709 "Should not need args for typedef of non-prototype fn"); 8710 } 8711 8712 // Finally, we know we have the right number of parameters, install them. 8713 NewFD->setParams(Params); 8714 8715 if (D.getDeclSpec().isNoreturnSpecified()) 8716 NewFD->addAttr( 8717 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8718 Context, 0)); 8719 8720 // Functions returning a variably modified type violate C99 6.7.5.2p2 8721 // because all functions have linkage. 8722 if (!NewFD->isInvalidDecl() && 8723 NewFD->getReturnType()->isVariablyModifiedType()) { 8724 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8725 NewFD->setInvalidDecl(); 8726 } 8727 8728 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8729 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8730 !NewFD->hasAttr<SectionAttr>()) { 8731 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8732 PragmaClangTextSection.SectionName, 8733 PragmaClangTextSection.PragmaLocation)); 8734 } 8735 8736 // Apply an implicit SectionAttr if #pragma code_seg is active. 8737 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8738 !NewFD->hasAttr<SectionAttr>()) { 8739 NewFD->addAttr( 8740 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8741 CodeSegStack.CurrentValue->getString(), 8742 CodeSegStack.CurrentPragmaLocation)); 8743 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8744 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8745 ASTContext::PSF_Read, 8746 NewFD)) 8747 NewFD->dropAttr<SectionAttr>(); 8748 } 8749 8750 // Handle attributes. 8751 ProcessDeclAttributes(S, NewFD, D); 8752 8753 if (getLangOpts().OpenCL) { 8754 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8755 // type declaration will generate a compilation error. 8756 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8757 if (AddressSpace == LangAS::opencl_local || 8758 AddressSpace == LangAS::opencl_global || 8759 AddressSpace == LangAS::opencl_constant) { 8760 Diag(NewFD->getLocation(), 8761 diag::err_opencl_return_value_with_address_space); 8762 NewFD->setInvalidDecl(); 8763 } 8764 } 8765 8766 if (!getLangOpts().CPlusPlus) { 8767 // Perform semantic checking on the function declaration. 8768 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8769 CheckMain(NewFD, D.getDeclSpec()); 8770 8771 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8772 CheckMSVCRTEntryPoint(NewFD); 8773 8774 if (!NewFD->isInvalidDecl()) 8775 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8776 isMemberSpecialization)); 8777 else if (!Previous.empty()) 8778 // Recover gracefully from an invalid redeclaration. 8779 D.setRedeclaration(true); 8780 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8781 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8782 "previous declaration set still overloaded"); 8783 8784 // Diagnose no-prototype function declarations with calling conventions that 8785 // don't support variadic calls. Only do this in C and do it after merging 8786 // possibly prototyped redeclarations. 8787 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8788 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8789 CallingConv CC = FT->getExtInfo().getCC(); 8790 if (!supportsVariadicCall(CC)) { 8791 // Windows system headers sometimes accidentally use stdcall without 8792 // (void) parameters, so we relax this to a warning. 8793 int DiagID = 8794 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8795 Diag(NewFD->getLocation(), DiagID) 8796 << FunctionType::getNameForCallConv(CC); 8797 } 8798 } 8799 } else { 8800 // C++11 [replacement.functions]p3: 8801 // The program's definitions shall not be specified as inline. 8802 // 8803 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8804 // 8805 // Suppress the diagnostic if the function is __attribute__((used)), since 8806 // that forces an external definition to be emitted. 8807 if (D.getDeclSpec().isInlineSpecified() && 8808 NewFD->isReplaceableGlobalAllocationFunction() && 8809 !NewFD->hasAttr<UsedAttr>()) 8810 Diag(D.getDeclSpec().getInlineSpecLoc(), 8811 diag::ext_operator_new_delete_declared_inline) 8812 << NewFD->getDeclName(); 8813 8814 // If the declarator is a template-id, translate the parser's template 8815 // argument list into our AST format. 8816 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8817 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8818 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8819 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8820 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8821 TemplateId->NumArgs); 8822 translateTemplateArguments(TemplateArgsPtr, 8823 TemplateArgs); 8824 8825 HasExplicitTemplateArgs = true; 8826 8827 if (NewFD->isInvalidDecl()) { 8828 HasExplicitTemplateArgs = false; 8829 } else if (FunctionTemplate) { 8830 // Function template with explicit template arguments. 8831 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8832 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8833 8834 HasExplicitTemplateArgs = false; 8835 } else { 8836 assert((isFunctionTemplateSpecialization || 8837 D.getDeclSpec().isFriendSpecified()) && 8838 "should have a 'template<>' for this decl"); 8839 // "friend void foo<>(int);" is an implicit specialization decl. 8840 isFunctionTemplateSpecialization = true; 8841 } 8842 } else if (isFriend && isFunctionTemplateSpecialization) { 8843 // This combination is only possible in a recovery case; the user 8844 // wrote something like: 8845 // template <> friend void foo(int); 8846 // which we're recovering from as if the user had written: 8847 // friend void foo<>(int); 8848 // Go ahead and fake up a template id. 8849 HasExplicitTemplateArgs = true; 8850 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8851 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8852 } 8853 8854 // We do not add HD attributes to specializations here because 8855 // they may have different constexpr-ness compared to their 8856 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8857 // may end up with different effective targets. Instead, a 8858 // specialization inherits its target attributes from its template 8859 // in the CheckFunctionTemplateSpecialization() call below. 8860 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8861 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8862 8863 // If it's a friend (and only if it's a friend), it's possible 8864 // that either the specialized function type or the specialized 8865 // template is dependent, and therefore matching will fail. In 8866 // this case, don't check the specialization yet. 8867 bool InstantiationDependent = false; 8868 if (isFunctionTemplateSpecialization && isFriend && 8869 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8870 TemplateSpecializationType::anyDependentTemplateArguments( 8871 TemplateArgs, 8872 InstantiationDependent))) { 8873 assert(HasExplicitTemplateArgs && 8874 "friend function specialization without template args"); 8875 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8876 Previous)) 8877 NewFD->setInvalidDecl(); 8878 } else if (isFunctionTemplateSpecialization) { 8879 if (CurContext->isDependentContext() && CurContext->isRecord() 8880 && !isFriend) { 8881 isDependentClassScopeExplicitSpecialization = true; 8882 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8883 diag::ext_function_specialization_in_class : 8884 diag::err_function_specialization_in_class) 8885 << NewFD->getDeclName(); 8886 } else if (CheckFunctionTemplateSpecialization(NewFD, 8887 (HasExplicitTemplateArgs ? &TemplateArgs 8888 : nullptr), 8889 Previous)) 8890 NewFD->setInvalidDecl(); 8891 8892 // C++ [dcl.stc]p1: 8893 // A storage-class-specifier shall not be specified in an explicit 8894 // specialization (14.7.3) 8895 FunctionTemplateSpecializationInfo *Info = 8896 NewFD->getTemplateSpecializationInfo(); 8897 if (Info && SC != SC_None) { 8898 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8899 Diag(NewFD->getLocation(), 8900 diag::err_explicit_specialization_inconsistent_storage_class) 8901 << SC 8902 << FixItHint::CreateRemoval( 8903 D.getDeclSpec().getStorageClassSpecLoc()); 8904 8905 else 8906 Diag(NewFD->getLocation(), 8907 diag::ext_explicit_specialization_storage_class) 8908 << FixItHint::CreateRemoval( 8909 D.getDeclSpec().getStorageClassSpecLoc()); 8910 } 8911 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8912 if (CheckMemberSpecialization(NewFD, Previous)) 8913 NewFD->setInvalidDecl(); 8914 } 8915 8916 // Perform semantic checking on the function declaration. 8917 if (!isDependentClassScopeExplicitSpecialization) { 8918 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8919 CheckMain(NewFD, D.getDeclSpec()); 8920 8921 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8922 CheckMSVCRTEntryPoint(NewFD); 8923 8924 if (!NewFD->isInvalidDecl()) 8925 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8926 isMemberSpecialization)); 8927 else if (!Previous.empty()) 8928 // Recover gracefully from an invalid redeclaration. 8929 D.setRedeclaration(true); 8930 } 8931 8932 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8933 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8934 "previous declaration set still overloaded"); 8935 8936 NamedDecl *PrincipalDecl = (FunctionTemplate 8937 ? cast<NamedDecl>(FunctionTemplate) 8938 : NewFD); 8939 8940 if (isFriend && NewFD->getPreviousDecl()) { 8941 AccessSpecifier Access = AS_public; 8942 if (!NewFD->isInvalidDecl()) 8943 Access = NewFD->getPreviousDecl()->getAccess(); 8944 8945 NewFD->setAccess(Access); 8946 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8947 } 8948 8949 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8950 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8951 PrincipalDecl->setNonMemberOperator(); 8952 8953 // If we have a function template, check the template parameter 8954 // list. This will check and merge default template arguments. 8955 if (FunctionTemplate) { 8956 FunctionTemplateDecl *PrevTemplate = 8957 FunctionTemplate->getPreviousDecl(); 8958 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8959 PrevTemplate ? PrevTemplate->getTemplateParameters() 8960 : nullptr, 8961 D.getDeclSpec().isFriendSpecified() 8962 ? (D.isFunctionDefinition() 8963 ? TPC_FriendFunctionTemplateDefinition 8964 : TPC_FriendFunctionTemplate) 8965 : (D.getCXXScopeSpec().isSet() && 8966 DC && DC->isRecord() && 8967 DC->isDependentContext()) 8968 ? TPC_ClassTemplateMember 8969 : TPC_FunctionTemplate); 8970 } 8971 8972 if (NewFD->isInvalidDecl()) { 8973 // Ignore all the rest of this. 8974 } else if (!D.isRedeclaration()) { 8975 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8976 AddToScope }; 8977 // Fake up an access specifier if it's supposed to be a class member. 8978 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8979 NewFD->setAccess(AS_public); 8980 8981 // Qualified decls generally require a previous declaration. 8982 if (D.getCXXScopeSpec().isSet()) { 8983 // ...with the major exception of templated-scope or 8984 // dependent-scope friend declarations. 8985 8986 // TODO: we currently also suppress this check in dependent 8987 // contexts because (1) the parameter depth will be off when 8988 // matching friend templates and (2) we might actually be 8989 // selecting a friend based on a dependent factor. But there 8990 // are situations where these conditions don't apply and we 8991 // can actually do this check immediately. 8992 if (isFriend && 8993 (TemplateParamLists.size() || 8994 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8995 CurContext->isDependentContext())) { 8996 // ignore these 8997 } else { 8998 // The user tried to provide an out-of-line definition for a 8999 // function that is a member of a class or namespace, but there 9000 // was no such member function declared (C++ [class.mfct]p2, 9001 // C++ [namespace.memdef]p2). For example: 9002 // 9003 // class X { 9004 // void f() const; 9005 // }; 9006 // 9007 // void X::f() { } // ill-formed 9008 // 9009 // Complain about this problem, and attempt to suggest close 9010 // matches (e.g., those that differ only in cv-qualifiers and 9011 // whether the parameter types are references). 9012 9013 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9014 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9015 AddToScope = ExtraArgs.AddToScope; 9016 return Result; 9017 } 9018 } 9019 9020 // Unqualified local friend declarations are required to resolve 9021 // to something. 9022 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9023 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9024 *this, Previous, NewFD, ExtraArgs, true, S)) { 9025 AddToScope = ExtraArgs.AddToScope; 9026 return Result; 9027 } 9028 } 9029 } else if (!D.isFunctionDefinition() && 9030 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9031 !isFriend && !isFunctionTemplateSpecialization && 9032 !isMemberSpecialization) { 9033 // An out-of-line member function declaration must also be a 9034 // definition (C++ [class.mfct]p2). 9035 // Note that this is not the case for explicit specializations of 9036 // function templates or member functions of class templates, per 9037 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9038 // extension for compatibility with old SWIG code which likes to 9039 // generate them. 9040 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9041 << D.getCXXScopeSpec().getRange(); 9042 } 9043 } 9044 9045 ProcessPragmaWeak(S, NewFD); 9046 checkAttributesAfterMerging(*this, *NewFD); 9047 9048 AddKnownFunctionAttributes(NewFD); 9049 9050 if (NewFD->hasAttr<OverloadableAttr>() && 9051 !NewFD->getType()->getAs<FunctionProtoType>()) { 9052 Diag(NewFD->getLocation(), 9053 diag::err_attribute_overloadable_no_prototype) 9054 << NewFD; 9055 9056 // Turn this into a variadic function with no parameters. 9057 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9058 FunctionProtoType::ExtProtoInfo EPI( 9059 Context.getDefaultCallingConvention(true, false)); 9060 EPI.Variadic = true; 9061 EPI.ExtInfo = FT->getExtInfo(); 9062 9063 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9064 NewFD->setType(R); 9065 } 9066 9067 // If there's a #pragma GCC visibility in scope, and this isn't a class 9068 // member, set the visibility of this function. 9069 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9070 AddPushedVisibilityAttribute(NewFD); 9071 9072 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9073 // marking the function. 9074 AddCFAuditedAttribute(NewFD); 9075 9076 // If this is a function definition, check if we have to apply optnone due to 9077 // a pragma. 9078 if(D.isFunctionDefinition()) 9079 AddRangeBasedOptnone(NewFD); 9080 9081 // If this is the first declaration of an extern C variable, update 9082 // the map of such variables. 9083 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9084 isIncompleteDeclExternC(*this, NewFD)) 9085 RegisterLocallyScopedExternCDecl(NewFD, S); 9086 9087 // Set this FunctionDecl's range up to the right paren. 9088 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9089 9090 if (D.isRedeclaration() && !Previous.empty()) { 9091 checkDLLAttributeRedeclaration( 9092 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9093 isMemberSpecialization || isFunctionTemplateSpecialization, 9094 D.isFunctionDefinition()); 9095 } 9096 9097 if (getLangOpts().CUDA) { 9098 IdentifierInfo *II = NewFD->getIdentifier(); 9099 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9100 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9101 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9102 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9103 9104 Context.setcudaConfigureCallDecl(NewFD); 9105 } 9106 9107 // Variadic functions, other than a *declaration* of printf, are not allowed 9108 // in device-side CUDA code, unless someone passed 9109 // -fcuda-allow-variadic-functions. 9110 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9111 (NewFD->hasAttr<CUDADeviceAttr>() || 9112 NewFD->hasAttr<CUDAGlobalAttr>()) && 9113 !(II && II->isStr("printf") && NewFD->isExternC() && 9114 !D.isFunctionDefinition())) { 9115 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9116 } 9117 } 9118 9119 MarkUnusedFileScopedDecl(NewFD); 9120 9121 if (getLangOpts().CPlusPlus) { 9122 if (FunctionTemplate) { 9123 if (NewFD->isInvalidDecl()) 9124 FunctionTemplate->setInvalidDecl(); 9125 return FunctionTemplate; 9126 } 9127 9128 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9129 CompleteMemberSpecialization(NewFD, Previous); 9130 } 9131 9132 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9133 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9134 if ((getLangOpts().OpenCLVersion >= 120) 9135 && (SC == SC_Static)) { 9136 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9137 D.setInvalidType(); 9138 } 9139 9140 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9141 if (!NewFD->getReturnType()->isVoidType()) { 9142 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9143 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9144 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9145 : FixItHint()); 9146 D.setInvalidType(); 9147 } 9148 9149 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9150 for (auto Param : NewFD->parameters()) 9151 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9152 } 9153 for (const ParmVarDecl *Param : NewFD->parameters()) { 9154 QualType PT = Param->getType(); 9155 9156 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9157 // types. 9158 if (getLangOpts().OpenCLVersion >= 200) { 9159 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9160 QualType ElemTy = PipeTy->getElementType(); 9161 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9162 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9163 D.setInvalidType(); 9164 } 9165 } 9166 } 9167 } 9168 9169 // Here we have an function template explicit specialization at class scope. 9170 // The actually specialization will be postponed to template instatiation 9171 // time via the ClassScopeFunctionSpecializationDecl node. 9172 if (isDependentClassScopeExplicitSpecialization) { 9173 ClassScopeFunctionSpecializationDecl *NewSpec = 9174 ClassScopeFunctionSpecializationDecl::Create( 9175 Context, CurContext, SourceLocation(), 9176 cast<CXXMethodDecl>(NewFD), 9177 HasExplicitTemplateArgs, TemplateArgs); 9178 CurContext->addDecl(NewSpec); 9179 AddToScope = false; 9180 } 9181 9182 return NewFD; 9183 } 9184 9185 /// \brief Checks if the new declaration declared in dependent context must be 9186 /// put in the same redeclaration chain as the specified declaration. 9187 /// 9188 /// \param D Declaration that is checked. 9189 /// \param PrevDecl Previous declaration found with proper lookup method for the 9190 /// same declaration name. 9191 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9192 /// belongs to. 9193 /// 9194 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9195 // Any declarations should be put into redeclaration chains except for 9196 // friend declaration in a dependent context that names a function in 9197 // namespace scope. 9198 // 9199 // This allows to compile code like: 9200 // 9201 // void func(); 9202 // template<typename T> class C1 { friend void func() { } }; 9203 // template<typename T> class C2 { friend void func() { } }; 9204 // 9205 // This code snippet is a valid code unless both templates are instantiated. 9206 return !(D->getLexicalDeclContext()->isDependentContext() && 9207 D->getDeclContext()->isFileContext() && 9208 D->getFriendObjectKind() != Decl::FOK_None); 9209 } 9210 9211 /// \brief Perform semantic checking of a new function declaration. 9212 /// 9213 /// Performs semantic analysis of the new function declaration 9214 /// NewFD. This routine performs all semantic checking that does not 9215 /// require the actual declarator involved in the declaration, and is 9216 /// used both for the declaration of functions as they are parsed 9217 /// (called via ActOnDeclarator) and for the declaration of functions 9218 /// that have been instantiated via C++ template instantiation (called 9219 /// via InstantiateDecl). 9220 /// 9221 /// \param IsMemberSpecialization whether this new function declaration is 9222 /// a member specialization (that replaces any definition provided by the 9223 /// previous declaration). 9224 /// 9225 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9226 /// 9227 /// \returns true if the function declaration is a redeclaration. 9228 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9229 LookupResult &Previous, 9230 bool IsMemberSpecialization) { 9231 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9232 "Variably modified return types are not handled here"); 9233 9234 // Determine whether the type of this function should be merged with 9235 // a previous visible declaration. This never happens for functions in C++, 9236 // and always happens in C if the previous declaration was visible. 9237 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9238 !Previous.isShadowed(); 9239 9240 bool Redeclaration = false; 9241 NamedDecl *OldDecl = nullptr; 9242 bool MayNeedOverloadableChecks = false; 9243 9244 // Merge or overload the declaration with an existing declaration of 9245 // the same name, if appropriate. 9246 if (!Previous.empty()) { 9247 // Determine whether NewFD is an overload of PrevDecl or 9248 // a declaration that requires merging. If it's an overload, 9249 // there's no more work to do here; we'll just add the new 9250 // function to the scope. 9251 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9252 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9253 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9254 Redeclaration = true; 9255 OldDecl = Candidate; 9256 } 9257 } else { 9258 MayNeedOverloadableChecks = true; 9259 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9260 /*NewIsUsingDecl*/ false)) { 9261 case Ovl_Match: 9262 Redeclaration = true; 9263 break; 9264 9265 case Ovl_NonFunction: 9266 Redeclaration = true; 9267 break; 9268 9269 case Ovl_Overload: 9270 Redeclaration = false; 9271 break; 9272 } 9273 } 9274 } 9275 9276 // Check for a previous extern "C" declaration with this name. 9277 if (!Redeclaration && 9278 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9279 if (!Previous.empty()) { 9280 // This is an extern "C" declaration with the same name as a previous 9281 // declaration, and thus redeclares that entity... 9282 Redeclaration = true; 9283 OldDecl = Previous.getFoundDecl(); 9284 MergeTypeWithPrevious = false; 9285 9286 // ... except in the presence of __attribute__((overloadable)). 9287 if (OldDecl->hasAttr<OverloadableAttr>() || 9288 NewFD->hasAttr<OverloadableAttr>()) { 9289 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9290 MayNeedOverloadableChecks = true; 9291 Redeclaration = false; 9292 OldDecl = nullptr; 9293 } 9294 } 9295 } 9296 } 9297 9298 // C++11 [dcl.constexpr]p8: 9299 // A constexpr specifier for a non-static member function that is not 9300 // a constructor declares that member function to be const. 9301 // 9302 // This needs to be delayed until we know whether this is an out-of-line 9303 // definition of a static member function. 9304 // 9305 // This rule is not present in C++1y, so we produce a backwards 9306 // compatibility warning whenever it happens in C++11. 9307 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9308 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9309 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9310 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9311 CXXMethodDecl *OldMD = nullptr; 9312 if (OldDecl) 9313 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9314 if (!OldMD || !OldMD->isStatic()) { 9315 const FunctionProtoType *FPT = 9316 MD->getType()->castAs<FunctionProtoType>(); 9317 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9318 EPI.TypeQuals |= Qualifiers::Const; 9319 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9320 FPT->getParamTypes(), EPI)); 9321 9322 // Warn that we did this, if we're not performing template instantiation. 9323 // In that case, we'll have warned already when the template was defined. 9324 if (!inTemplateInstantiation()) { 9325 SourceLocation AddConstLoc; 9326 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9327 .IgnoreParens().getAs<FunctionTypeLoc>()) 9328 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9329 9330 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9331 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9332 } 9333 } 9334 } 9335 9336 if (Redeclaration) { 9337 // NewFD and OldDecl represent declarations that need to be 9338 // merged. 9339 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9340 NewFD->setInvalidDecl(); 9341 return Redeclaration; 9342 } 9343 9344 Previous.clear(); 9345 Previous.addDecl(OldDecl); 9346 9347 if (FunctionTemplateDecl *OldTemplateDecl 9348 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9349 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9350 FunctionTemplateDecl *NewTemplateDecl 9351 = NewFD->getDescribedFunctionTemplate(); 9352 assert(NewTemplateDecl && "Template/non-template mismatch"); 9353 if (CXXMethodDecl *Method 9354 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9355 Method->setAccess(OldTemplateDecl->getAccess()); 9356 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9357 } 9358 9359 // If this is an explicit specialization of a member that is a function 9360 // template, mark it as a member specialization. 9361 if (IsMemberSpecialization && 9362 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9363 NewTemplateDecl->setMemberSpecialization(); 9364 assert(OldTemplateDecl->isMemberSpecialization()); 9365 // Explicit specializations of a member template do not inherit deleted 9366 // status from the parent member template that they are specializing. 9367 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9368 FunctionDecl *const OldTemplatedDecl = 9369 OldTemplateDecl->getTemplatedDecl(); 9370 // FIXME: This assert will not hold in the presence of modules. 9371 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9372 // FIXME: We need an update record for this AST mutation. 9373 OldTemplatedDecl->setDeletedAsWritten(false); 9374 } 9375 } 9376 9377 } else { 9378 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9379 // This needs to happen first so that 'inline' propagates. 9380 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9381 if (isa<CXXMethodDecl>(NewFD)) 9382 NewFD->setAccess(OldDecl->getAccess()); 9383 } 9384 } 9385 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9386 !NewFD->getAttr<OverloadableAttr>()) { 9387 assert((Previous.empty() || 9388 llvm::any_of(Previous, 9389 [](const NamedDecl *ND) { 9390 return ND->hasAttr<OverloadableAttr>(); 9391 })) && 9392 "Non-redecls shouldn't happen without overloadable present"); 9393 9394 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9395 const auto *FD = dyn_cast<FunctionDecl>(ND); 9396 return FD && !FD->hasAttr<OverloadableAttr>(); 9397 }); 9398 9399 if (OtherUnmarkedIter != Previous.end()) { 9400 Diag(NewFD->getLocation(), 9401 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9402 Diag((*OtherUnmarkedIter)->getLocation(), 9403 diag::note_attribute_overloadable_prev_overload) 9404 << false; 9405 9406 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9407 } 9408 } 9409 9410 // Semantic checking for this function declaration (in isolation). 9411 9412 if (getLangOpts().CPlusPlus) { 9413 // C++-specific checks. 9414 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9415 CheckConstructor(Constructor); 9416 } else if (CXXDestructorDecl *Destructor = 9417 dyn_cast<CXXDestructorDecl>(NewFD)) { 9418 CXXRecordDecl *Record = Destructor->getParent(); 9419 QualType ClassType = Context.getTypeDeclType(Record); 9420 9421 // FIXME: Shouldn't we be able to perform this check even when the class 9422 // type is dependent? Both gcc and edg can handle that. 9423 if (!ClassType->isDependentType()) { 9424 DeclarationName Name 9425 = Context.DeclarationNames.getCXXDestructorName( 9426 Context.getCanonicalType(ClassType)); 9427 if (NewFD->getDeclName() != Name) { 9428 Diag(NewFD->getLocation(), diag::err_destructor_name); 9429 NewFD->setInvalidDecl(); 9430 return Redeclaration; 9431 } 9432 } 9433 } else if (CXXConversionDecl *Conversion 9434 = dyn_cast<CXXConversionDecl>(NewFD)) { 9435 ActOnConversionDeclarator(Conversion); 9436 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9437 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9438 CheckDeductionGuideTemplate(TD); 9439 9440 // A deduction guide is not on the list of entities that can be 9441 // explicitly specialized. 9442 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9443 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9444 << /*explicit specialization*/ 1; 9445 } 9446 9447 // Find any virtual functions that this function overrides. 9448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9449 if (!Method->isFunctionTemplateSpecialization() && 9450 !Method->getDescribedFunctionTemplate() && 9451 Method->isCanonicalDecl()) { 9452 if (AddOverriddenMethods(Method->getParent(), Method)) { 9453 // If the function was marked as "static", we have a problem. 9454 if (NewFD->getStorageClass() == SC_Static) { 9455 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9456 } 9457 } 9458 } 9459 9460 if (Method->isStatic()) 9461 checkThisInStaticMemberFunctionType(Method); 9462 } 9463 9464 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9465 if (NewFD->isOverloadedOperator() && 9466 CheckOverloadedOperatorDeclaration(NewFD)) { 9467 NewFD->setInvalidDecl(); 9468 return Redeclaration; 9469 } 9470 9471 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9472 if (NewFD->getLiteralIdentifier() && 9473 CheckLiteralOperatorDeclaration(NewFD)) { 9474 NewFD->setInvalidDecl(); 9475 return Redeclaration; 9476 } 9477 9478 // In C++, check default arguments now that we have merged decls. Unless 9479 // the lexical context is the class, because in this case this is done 9480 // during delayed parsing anyway. 9481 if (!CurContext->isRecord()) 9482 CheckCXXDefaultArguments(NewFD); 9483 9484 // If this function declares a builtin function, check the type of this 9485 // declaration against the expected type for the builtin. 9486 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9487 ASTContext::GetBuiltinTypeError Error; 9488 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9489 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9490 // If the type of the builtin differs only in its exception 9491 // specification, that's OK. 9492 // FIXME: If the types do differ in this way, it would be better to 9493 // retain the 'noexcept' form of the type. 9494 if (!T.isNull() && 9495 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9496 NewFD->getType())) 9497 // The type of this function differs from the type of the builtin, 9498 // so forget about the builtin entirely. 9499 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9500 } 9501 9502 // If this function is declared as being extern "C", then check to see if 9503 // the function returns a UDT (class, struct, or union type) that is not C 9504 // compatible, and if it does, warn the user. 9505 // But, issue any diagnostic on the first declaration only. 9506 if (Previous.empty() && NewFD->isExternC()) { 9507 QualType R = NewFD->getReturnType(); 9508 if (R->isIncompleteType() && !R->isVoidType()) 9509 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9510 << NewFD << R; 9511 else if (!R.isPODType(Context) && !R->isVoidType() && 9512 !R->isObjCObjectPointerType()) 9513 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9514 } 9515 9516 // C++1z [dcl.fct]p6: 9517 // [...] whether the function has a non-throwing exception-specification 9518 // [is] part of the function type 9519 // 9520 // This results in an ABI break between C++14 and C++17 for functions whose 9521 // declared type includes an exception-specification in a parameter or 9522 // return type. (Exception specifications on the function itself are OK in 9523 // most cases, and exception specifications are not permitted in most other 9524 // contexts where they could make it into a mangling.) 9525 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9526 auto HasNoexcept = [&](QualType T) -> bool { 9527 // Strip off declarator chunks that could be between us and a function 9528 // type. We don't need to look far, exception specifications are very 9529 // restricted prior to C++17. 9530 if (auto *RT = T->getAs<ReferenceType>()) 9531 T = RT->getPointeeType(); 9532 else if (T->isAnyPointerType()) 9533 T = T->getPointeeType(); 9534 else if (auto *MPT = T->getAs<MemberPointerType>()) 9535 T = MPT->getPointeeType(); 9536 if (auto *FPT = T->getAs<FunctionProtoType>()) 9537 if (FPT->isNothrow(Context)) 9538 return true; 9539 return false; 9540 }; 9541 9542 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9543 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9544 for (QualType T : FPT->param_types()) 9545 AnyNoexcept |= HasNoexcept(T); 9546 if (AnyNoexcept) 9547 Diag(NewFD->getLocation(), 9548 diag::warn_cxx17_compat_exception_spec_in_signature) 9549 << NewFD; 9550 } 9551 9552 if (!Redeclaration && LangOpts.CUDA) 9553 checkCUDATargetOverload(NewFD, Previous); 9554 } 9555 return Redeclaration; 9556 } 9557 9558 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9559 // C++11 [basic.start.main]p3: 9560 // A program that [...] declares main to be inline, static or 9561 // constexpr is ill-formed. 9562 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9563 // appear in a declaration of main. 9564 // static main is not an error under C99, but we should warn about it. 9565 // We accept _Noreturn main as an extension. 9566 if (FD->getStorageClass() == SC_Static) 9567 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9568 ? diag::err_static_main : diag::warn_static_main) 9569 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9570 if (FD->isInlineSpecified()) 9571 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9572 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9573 if (DS.isNoreturnSpecified()) { 9574 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9575 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9576 Diag(NoreturnLoc, diag::ext_noreturn_main); 9577 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9578 << FixItHint::CreateRemoval(NoreturnRange); 9579 } 9580 if (FD->isConstexpr()) { 9581 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9582 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9583 FD->setConstexpr(false); 9584 } 9585 9586 if (getLangOpts().OpenCL) { 9587 Diag(FD->getLocation(), diag::err_opencl_no_main) 9588 << FD->hasAttr<OpenCLKernelAttr>(); 9589 FD->setInvalidDecl(); 9590 return; 9591 } 9592 9593 QualType T = FD->getType(); 9594 assert(T->isFunctionType() && "function decl is not of function type"); 9595 const FunctionType* FT = T->castAs<FunctionType>(); 9596 9597 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9598 // In C with GNU extensions we allow main() to have non-integer return 9599 // type, but we should warn about the extension, and we disable the 9600 // implicit-return-zero rule. 9601 9602 // GCC in C mode accepts qualified 'int'. 9603 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9604 FD->setHasImplicitReturnZero(true); 9605 else { 9606 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9607 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9608 if (RTRange.isValid()) 9609 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9610 << FixItHint::CreateReplacement(RTRange, "int"); 9611 } 9612 } else { 9613 // In C and C++, main magically returns 0 if you fall off the end; 9614 // set the flag which tells us that. 9615 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9616 9617 // All the standards say that main() should return 'int'. 9618 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9619 FD->setHasImplicitReturnZero(true); 9620 else { 9621 // Otherwise, this is just a flat-out error. 9622 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9623 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9624 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9625 : FixItHint()); 9626 FD->setInvalidDecl(true); 9627 } 9628 } 9629 9630 // Treat protoless main() as nullary. 9631 if (isa<FunctionNoProtoType>(FT)) return; 9632 9633 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9634 unsigned nparams = FTP->getNumParams(); 9635 assert(FD->getNumParams() == nparams); 9636 9637 bool HasExtraParameters = (nparams > 3); 9638 9639 if (FTP->isVariadic()) { 9640 Diag(FD->getLocation(), diag::ext_variadic_main); 9641 // FIXME: if we had information about the location of the ellipsis, we 9642 // could add a FixIt hint to remove it as a parameter. 9643 } 9644 9645 // Darwin passes an undocumented fourth argument of type char**. If 9646 // other platforms start sprouting these, the logic below will start 9647 // getting shifty. 9648 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9649 HasExtraParameters = false; 9650 9651 if (HasExtraParameters) { 9652 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9653 FD->setInvalidDecl(true); 9654 nparams = 3; 9655 } 9656 9657 // FIXME: a lot of the following diagnostics would be improved 9658 // if we had some location information about types. 9659 9660 QualType CharPP = 9661 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9662 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9663 9664 for (unsigned i = 0; i < nparams; ++i) { 9665 QualType AT = FTP->getParamType(i); 9666 9667 bool mismatch = true; 9668 9669 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9670 mismatch = false; 9671 else if (Expected[i] == CharPP) { 9672 // As an extension, the following forms are okay: 9673 // char const ** 9674 // char const * const * 9675 // char * const * 9676 9677 QualifierCollector qs; 9678 const PointerType* PT; 9679 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9680 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9681 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9682 Context.CharTy)) { 9683 qs.removeConst(); 9684 mismatch = !qs.empty(); 9685 } 9686 } 9687 9688 if (mismatch) { 9689 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9690 // TODO: suggest replacing given type with expected type 9691 FD->setInvalidDecl(true); 9692 } 9693 } 9694 9695 if (nparams == 1 && !FD->isInvalidDecl()) { 9696 Diag(FD->getLocation(), diag::warn_main_one_arg); 9697 } 9698 9699 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9700 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9701 FD->setInvalidDecl(); 9702 } 9703 } 9704 9705 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9706 QualType T = FD->getType(); 9707 assert(T->isFunctionType() && "function decl is not of function type"); 9708 const FunctionType *FT = T->castAs<FunctionType>(); 9709 9710 // Set an implicit return of 'zero' if the function can return some integral, 9711 // enumeration, pointer or nullptr type. 9712 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9713 FT->getReturnType()->isAnyPointerType() || 9714 FT->getReturnType()->isNullPtrType()) 9715 // DllMain is exempt because a return value of zero means it failed. 9716 if (FD->getName() != "DllMain") 9717 FD->setHasImplicitReturnZero(true); 9718 9719 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9720 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9721 FD->setInvalidDecl(); 9722 } 9723 } 9724 9725 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9726 // FIXME: Need strict checking. In C89, we need to check for 9727 // any assignment, increment, decrement, function-calls, or 9728 // commas outside of a sizeof. In C99, it's the same list, 9729 // except that the aforementioned are allowed in unevaluated 9730 // expressions. Everything else falls under the 9731 // "may accept other forms of constant expressions" exception. 9732 // (We never end up here for C++, so the constant expression 9733 // rules there don't matter.) 9734 const Expr *Culprit; 9735 if (Init->isConstantInitializer(Context, false, &Culprit)) 9736 return false; 9737 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9738 << Culprit->getSourceRange(); 9739 return true; 9740 } 9741 9742 namespace { 9743 // Visits an initialization expression to see if OrigDecl is evaluated in 9744 // its own initialization and throws a warning if it does. 9745 class SelfReferenceChecker 9746 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9747 Sema &S; 9748 Decl *OrigDecl; 9749 bool isRecordType; 9750 bool isPODType; 9751 bool isReferenceType; 9752 9753 bool isInitList; 9754 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9755 9756 public: 9757 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9758 9759 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9760 S(S), OrigDecl(OrigDecl) { 9761 isPODType = false; 9762 isRecordType = false; 9763 isReferenceType = false; 9764 isInitList = false; 9765 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9766 isPODType = VD->getType().isPODType(S.Context); 9767 isRecordType = VD->getType()->isRecordType(); 9768 isReferenceType = VD->getType()->isReferenceType(); 9769 } 9770 } 9771 9772 // For most expressions, just call the visitor. For initializer lists, 9773 // track the index of the field being initialized since fields are 9774 // initialized in order allowing use of previously initialized fields. 9775 void CheckExpr(Expr *E) { 9776 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9777 if (!InitList) { 9778 Visit(E); 9779 return; 9780 } 9781 9782 // Track and increment the index here. 9783 isInitList = true; 9784 InitFieldIndex.push_back(0); 9785 for (auto Child : InitList->children()) { 9786 CheckExpr(cast<Expr>(Child)); 9787 ++InitFieldIndex.back(); 9788 } 9789 InitFieldIndex.pop_back(); 9790 } 9791 9792 // Returns true if MemberExpr is checked and no further checking is needed. 9793 // Returns false if additional checking is required. 9794 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9795 llvm::SmallVector<FieldDecl*, 4> Fields; 9796 Expr *Base = E; 9797 bool ReferenceField = false; 9798 9799 // Get the field memebers used. 9800 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9801 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9802 if (!FD) 9803 return false; 9804 Fields.push_back(FD); 9805 if (FD->getType()->isReferenceType()) 9806 ReferenceField = true; 9807 Base = ME->getBase()->IgnoreParenImpCasts(); 9808 } 9809 9810 // Keep checking only if the base Decl is the same. 9811 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9812 if (!DRE || DRE->getDecl() != OrigDecl) 9813 return false; 9814 9815 // A reference field can be bound to an unininitialized field. 9816 if (CheckReference && !ReferenceField) 9817 return true; 9818 9819 // Convert FieldDecls to their index number. 9820 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9821 for (const FieldDecl *I : llvm::reverse(Fields)) 9822 UsedFieldIndex.push_back(I->getFieldIndex()); 9823 9824 // See if a warning is needed by checking the first difference in index 9825 // numbers. If field being used has index less than the field being 9826 // initialized, then the use is safe. 9827 for (auto UsedIter = UsedFieldIndex.begin(), 9828 UsedEnd = UsedFieldIndex.end(), 9829 OrigIter = InitFieldIndex.begin(), 9830 OrigEnd = InitFieldIndex.end(); 9831 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9832 if (*UsedIter < *OrigIter) 9833 return true; 9834 if (*UsedIter > *OrigIter) 9835 break; 9836 } 9837 9838 // TODO: Add a different warning which will print the field names. 9839 HandleDeclRefExpr(DRE); 9840 return true; 9841 } 9842 9843 // For most expressions, the cast is directly above the DeclRefExpr. 9844 // For conditional operators, the cast can be outside the conditional 9845 // operator if both expressions are DeclRefExpr's. 9846 void HandleValue(Expr *E) { 9847 E = E->IgnoreParens(); 9848 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9849 HandleDeclRefExpr(DRE); 9850 return; 9851 } 9852 9853 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9854 Visit(CO->getCond()); 9855 HandleValue(CO->getTrueExpr()); 9856 HandleValue(CO->getFalseExpr()); 9857 return; 9858 } 9859 9860 if (BinaryConditionalOperator *BCO = 9861 dyn_cast<BinaryConditionalOperator>(E)) { 9862 Visit(BCO->getCond()); 9863 HandleValue(BCO->getFalseExpr()); 9864 return; 9865 } 9866 9867 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9868 HandleValue(OVE->getSourceExpr()); 9869 return; 9870 } 9871 9872 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9873 if (BO->getOpcode() == BO_Comma) { 9874 Visit(BO->getLHS()); 9875 HandleValue(BO->getRHS()); 9876 return; 9877 } 9878 } 9879 9880 if (isa<MemberExpr>(E)) { 9881 if (isInitList) { 9882 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9883 false /*CheckReference*/)) 9884 return; 9885 } 9886 9887 Expr *Base = E->IgnoreParenImpCasts(); 9888 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9889 // Check for static member variables and don't warn on them. 9890 if (!isa<FieldDecl>(ME->getMemberDecl())) 9891 return; 9892 Base = ME->getBase()->IgnoreParenImpCasts(); 9893 } 9894 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9895 HandleDeclRefExpr(DRE); 9896 return; 9897 } 9898 9899 Visit(E); 9900 } 9901 9902 // Reference types not handled in HandleValue are handled here since all 9903 // uses of references are bad, not just r-value uses. 9904 void VisitDeclRefExpr(DeclRefExpr *E) { 9905 if (isReferenceType) 9906 HandleDeclRefExpr(E); 9907 } 9908 9909 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9910 if (E->getCastKind() == CK_LValueToRValue) { 9911 HandleValue(E->getSubExpr()); 9912 return; 9913 } 9914 9915 Inherited::VisitImplicitCastExpr(E); 9916 } 9917 9918 void VisitMemberExpr(MemberExpr *E) { 9919 if (isInitList) { 9920 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9921 return; 9922 } 9923 9924 // Don't warn on arrays since they can be treated as pointers. 9925 if (E->getType()->canDecayToPointerType()) return; 9926 9927 // Warn when a non-static method call is followed by non-static member 9928 // field accesses, which is followed by a DeclRefExpr. 9929 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9930 bool Warn = (MD && !MD->isStatic()); 9931 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9932 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9933 if (!isa<FieldDecl>(ME->getMemberDecl())) 9934 Warn = false; 9935 Base = ME->getBase()->IgnoreParenImpCasts(); 9936 } 9937 9938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9939 if (Warn) 9940 HandleDeclRefExpr(DRE); 9941 return; 9942 } 9943 9944 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9945 // Visit that expression. 9946 Visit(Base); 9947 } 9948 9949 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9950 Expr *Callee = E->getCallee(); 9951 9952 if (isa<UnresolvedLookupExpr>(Callee)) 9953 return Inherited::VisitCXXOperatorCallExpr(E); 9954 9955 Visit(Callee); 9956 for (auto Arg: E->arguments()) 9957 HandleValue(Arg->IgnoreParenImpCasts()); 9958 } 9959 9960 void VisitUnaryOperator(UnaryOperator *E) { 9961 // For POD record types, addresses of its own members are well-defined. 9962 if (E->getOpcode() == UO_AddrOf && isRecordType && 9963 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9964 if (!isPODType) 9965 HandleValue(E->getSubExpr()); 9966 return; 9967 } 9968 9969 if (E->isIncrementDecrementOp()) { 9970 HandleValue(E->getSubExpr()); 9971 return; 9972 } 9973 9974 Inherited::VisitUnaryOperator(E); 9975 } 9976 9977 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9978 9979 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9980 if (E->getConstructor()->isCopyConstructor()) { 9981 Expr *ArgExpr = E->getArg(0); 9982 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9983 if (ILE->getNumInits() == 1) 9984 ArgExpr = ILE->getInit(0); 9985 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9986 if (ICE->getCastKind() == CK_NoOp) 9987 ArgExpr = ICE->getSubExpr(); 9988 HandleValue(ArgExpr); 9989 return; 9990 } 9991 Inherited::VisitCXXConstructExpr(E); 9992 } 9993 9994 void VisitCallExpr(CallExpr *E) { 9995 // Treat std::move as a use. 9996 if (E->getNumArgs() == 1) { 9997 if (FunctionDecl *FD = E->getDirectCallee()) { 9998 if (FD->isInStdNamespace() && FD->getIdentifier() && 9999 FD->getIdentifier()->isStr("move")) { 10000 HandleValue(E->getArg(0)); 10001 return; 10002 } 10003 } 10004 } 10005 10006 Inherited::VisitCallExpr(E); 10007 } 10008 10009 void VisitBinaryOperator(BinaryOperator *E) { 10010 if (E->isCompoundAssignmentOp()) { 10011 HandleValue(E->getLHS()); 10012 Visit(E->getRHS()); 10013 return; 10014 } 10015 10016 Inherited::VisitBinaryOperator(E); 10017 } 10018 10019 // A custom visitor for BinaryConditionalOperator is needed because the 10020 // regular visitor would check the condition and true expression separately 10021 // but both point to the same place giving duplicate diagnostics. 10022 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10023 Visit(E->getCond()); 10024 Visit(E->getFalseExpr()); 10025 } 10026 10027 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10028 Decl* ReferenceDecl = DRE->getDecl(); 10029 if (OrigDecl != ReferenceDecl) return; 10030 unsigned diag; 10031 if (isReferenceType) { 10032 diag = diag::warn_uninit_self_reference_in_reference_init; 10033 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10034 diag = diag::warn_static_self_reference_in_init; 10035 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10036 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10037 DRE->getDecl()->getType()->isRecordType()) { 10038 diag = diag::warn_uninit_self_reference_in_init; 10039 } else { 10040 // Local variables will be handled by the CFG analysis. 10041 return; 10042 } 10043 10044 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10045 S.PDiag(diag) 10046 << DRE->getNameInfo().getName() 10047 << OrigDecl->getLocation() 10048 << DRE->getSourceRange()); 10049 } 10050 }; 10051 10052 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10053 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10054 bool DirectInit) { 10055 // Parameters arguments are occassionially constructed with itself, 10056 // for instance, in recursive functions. Skip them. 10057 if (isa<ParmVarDecl>(OrigDecl)) 10058 return; 10059 10060 E = E->IgnoreParens(); 10061 10062 // Skip checking T a = a where T is not a record or reference type. 10063 // Doing so is a way to silence uninitialized warnings. 10064 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10065 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10066 if (ICE->getCastKind() == CK_LValueToRValue) 10067 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10068 if (DRE->getDecl() == OrigDecl) 10069 return; 10070 10071 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10072 } 10073 } // end anonymous namespace 10074 10075 namespace { 10076 // Simple wrapper to add the name of a variable or (if no variable is 10077 // available) a DeclarationName into a diagnostic. 10078 struct VarDeclOrName { 10079 VarDecl *VDecl; 10080 DeclarationName Name; 10081 10082 friend const Sema::SemaDiagnosticBuilder & 10083 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10084 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10085 } 10086 }; 10087 } // end anonymous namespace 10088 10089 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10090 DeclarationName Name, QualType Type, 10091 TypeSourceInfo *TSI, 10092 SourceRange Range, bool DirectInit, 10093 Expr *Init) { 10094 bool IsInitCapture = !VDecl; 10095 assert((!VDecl || !VDecl->isInitCapture()) && 10096 "init captures are expected to be deduced prior to initialization"); 10097 10098 VarDeclOrName VN{VDecl, Name}; 10099 10100 DeducedType *Deduced = Type->getContainedDeducedType(); 10101 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10102 10103 // C++11 [dcl.spec.auto]p3 10104 if (!Init) { 10105 assert(VDecl && "no init for init capture deduction?"); 10106 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10107 << VDecl->getDeclName() << Type; 10108 return QualType(); 10109 } 10110 10111 ArrayRef<Expr*> DeduceInits = Init; 10112 if (DirectInit) { 10113 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10114 DeduceInits = PL->exprs(); 10115 } 10116 10117 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10118 assert(VDecl && "non-auto type for init capture deduction?"); 10119 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10120 InitializationKind Kind = InitializationKind::CreateForInit( 10121 VDecl->getLocation(), DirectInit, Init); 10122 // FIXME: Initialization should not be taking a mutable list of inits. 10123 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10124 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10125 InitsCopy); 10126 } 10127 10128 if (DirectInit) { 10129 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10130 DeduceInits = IL->inits(); 10131 } 10132 10133 // Deduction only works if we have exactly one source expression. 10134 if (DeduceInits.empty()) { 10135 // It isn't possible to write this directly, but it is possible to 10136 // end up in this situation with "auto x(some_pack...);" 10137 Diag(Init->getLocStart(), IsInitCapture 10138 ? diag::err_init_capture_no_expression 10139 : diag::err_auto_var_init_no_expression) 10140 << VN << Type << Range; 10141 return QualType(); 10142 } 10143 10144 if (DeduceInits.size() > 1) { 10145 Diag(DeduceInits[1]->getLocStart(), 10146 IsInitCapture ? diag::err_init_capture_multiple_expressions 10147 : diag::err_auto_var_init_multiple_expressions) 10148 << VN << Type << Range; 10149 return QualType(); 10150 } 10151 10152 Expr *DeduceInit = DeduceInits[0]; 10153 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10154 Diag(Init->getLocStart(), IsInitCapture 10155 ? diag::err_init_capture_paren_braces 10156 : diag::err_auto_var_init_paren_braces) 10157 << isa<InitListExpr>(Init) << VN << Type << Range; 10158 return QualType(); 10159 } 10160 10161 // Expressions default to 'id' when we're in a debugger. 10162 bool DefaultedAnyToId = false; 10163 if (getLangOpts().DebuggerCastResultToId && 10164 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10165 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10166 if (Result.isInvalid()) { 10167 return QualType(); 10168 } 10169 Init = Result.get(); 10170 DefaultedAnyToId = true; 10171 } 10172 10173 // C++ [dcl.decomp]p1: 10174 // If the assignment-expression [...] has array type A and no ref-qualifier 10175 // is present, e has type cv A 10176 if (VDecl && isa<DecompositionDecl>(VDecl) && 10177 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10178 DeduceInit->getType()->isConstantArrayType()) 10179 return Context.getQualifiedType(DeduceInit->getType(), 10180 Type.getQualifiers()); 10181 10182 QualType DeducedType; 10183 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10184 if (!IsInitCapture) 10185 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10186 else if (isa<InitListExpr>(Init)) 10187 Diag(Range.getBegin(), 10188 diag::err_init_capture_deduction_failure_from_init_list) 10189 << VN 10190 << (DeduceInit->getType().isNull() ? TSI->getType() 10191 : DeduceInit->getType()) 10192 << DeduceInit->getSourceRange(); 10193 else 10194 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10195 << VN << TSI->getType() 10196 << (DeduceInit->getType().isNull() ? TSI->getType() 10197 : DeduceInit->getType()) 10198 << DeduceInit->getSourceRange(); 10199 } 10200 10201 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10202 // 'id' instead of a specific object type prevents most of our usual 10203 // checks. 10204 // We only want to warn outside of template instantiations, though: 10205 // inside a template, the 'id' could have come from a parameter. 10206 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10207 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10208 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10209 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10210 } 10211 10212 return DeducedType; 10213 } 10214 10215 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10216 Expr *Init) { 10217 QualType DeducedType = deduceVarTypeFromInitializer( 10218 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10219 VDecl->getSourceRange(), DirectInit, Init); 10220 if (DeducedType.isNull()) { 10221 VDecl->setInvalidDecl(); 10222 return true; 10223 } 10224 10225 VDecl->setType(DeducedType); 10226 assert(VDecl->isLinkageValid()); 10227 10228 // In ARC, infer lifetime. 10229 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10230 VDecl->setInvalidDecl(); 10231 10232 // If this is a redeclaration, check that the type we just deduced matches 10233 // the previously declared type. 10234 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10235 // We never need to merge the type, because we cannot form an incomplete 10236 // array of auto, nor deduce such a type. 10237 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10238 } 10239 10240 // Check the deduced type is valid for a variable declaration. 10241 CheckVariableDeclarationType(VDecl); 10242 return VDecl->isInvalidDecl(); 10243 } 10244 10245 /// AddInitializerToDecl - Adds the initializer Init to the 10246 /// declaration dcl. If DirectInit is true, this is C++ direct 10247 /// initialization rather than copy initialization. 10248 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10249 // If there is no declaration, there was an error parsing it. Just ignore 10250 // the initializer. 10251 if (!RealDecl || RealDecl->isInvalidDecl()) { 10252 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10253 return; 10254 } 10255 10256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10257 // Pure-specifiers are handled in ActOnPureSpecifier. 10258 Diag(Method->getLocation(), diag::err_member_function_initialization) 10259 << Method->getDeclName() << Init->getSourceRange(); 10260 Method->setInvalidDecl(); 10261 return; 10262 } 10263 10264 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10265 if (!VDecl) { 10266 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10267 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10268 RealDecl->setInvalidDecl(); 10269 return; 10270 } 10271 10272 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10273 if (VDecl->getType()->isUndeducedType()) { 10274 // Attempt typo correction early so that the type of the init expression can 10275 // be deduced based on the chosen correction if the original init contains a 10276 // TypoExpr. 10277 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10278 if (!Res.isUsable()) { 10279 RealDecl->setInvalidDecl(); 10280 return; 10281 } 10282 Init = Res.get(); 10283 10284 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10285 return; 10286 } 10287 10288 // dllimport cannot be used on variable definitions. 10289 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10290 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10291 VDecl->setInvalidDecl(); 10292 return; 10293 } 10294 10295 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10296 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10297 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10298 VDecl->setInvalidDecl(); 10299 return; 10300 } 10301 10302 if (!VDecl->getType()->isDependentType()) { 10303 // A definition must end up with a complete type, which means it must be 10304 // complete with the restriction that an array type might be completed by 10305 // the initializer; note that later code assumes this restriction. 10306 QualType BaseDeclType = VDecl->getType(); 10307 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10308 BaseDeclType = Array->getElementType(); 10309 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10310 diag::err_typecheck_decl_incomplete_type)) { 10311 RealDecl->setInvalidDecl(); 10312 return; 10313 } 10314 10315 // The variable can not have an abstract class type. 10316 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10317 diag::err_abstract_type_in_decl, 10318 AbstractVariableType)) 10319 VDecl->setInvalidDecl(); 10320 } 10321 10322 // If adding the initializer will turn this declaration into a definition, 10323 // and we already have a definition for this variable, diagnose or otherwise 10324 // handle the situation. 10325 VarDecl *Def; 10326 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10327 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10328 !VDecl->isThisDeclarationADemotedDefinition() && 10329 checkVarDeclRedefinition(Def, VDecl)) 10330 return; 10331 10332 if (getLangOpts().CPlusPlus) { 10333 // C++ [class.static.data]p4 10334 // If a static data member is of const integral or const 10335 // enumeration type, its declaration in the class definition can 10336 // specify a constant-initializer which shall be an integral 10337 // constant expression (5.19). In that case, the member can appear 10338 // in integral constant expressions. The member shall still be 10339 // defined in a namespace scope if it is used in the program and the 10340 // namespace scope definition shall not contain an initializer. 10341 // 10342 // We already performed a redefinition check above, but for static 10343 // data members we also need to check whether there was an in-class 10344 // declaration with an initializer. 10345 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10346 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10347 << VDecl->getDeclName(); 10348 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10349 diag::note_previous_initializer) 10350 << 0; 10351 return; 10352 } 10353 10354 if (VDecl->hasLocalStorage()) 10355 getCurFunction()->setHasBranchProtectedScope(); 10356 10357 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10358 VDecl->setInvalidDecl(); 10359 return; 10360 } 10361 } 10362 10363 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10364 // a kernel function cannot be initialized." 10365 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10366 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10367 VDecl->setInvalidDecl(); 10368 return; 10369 } 10370 10371 // Get the decls type and save a reference for later, since 10372 // CheckInitializerTypes may change it. 10373 QualType DclT = VDecl->getType(), SavT = DclT; 10374 10375 // Expressions default to 'id' when we're in a debugger 10376 // and we are assigning it to a variable of Objective-C pointer type. 10377 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10378 Init->getType() == Context.UnknownAnyTy) { 10379 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10380 if (Result.isInvalid()) { 10381 VDecl->setInvalidDecl(); 10382 return; 10383 } 10384 Init = Result.get(); 10385 } 10386 10387 // Perform the initialization. 10388 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10389 if (!VDecl->isInvalidDecl()) { 10390 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10391 InitializationKind Kind = InitializationKind::CreateForInit( 10392 VDecl->getLocation(), DirectInit, Init); 10393 10394 MultiExprArg Args = Init; 10395 if (CXXDirectInit) 10396 Args = MultiExprArg(CXXDirectInit->getExprs(), 10397 CXXDirectInit->getNumExprs()); 10398 10399 // Try to correct any TypoExprs in the initialization arguments. 10400 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10401 ExprResult Res = CorrectDelayedTyposInExpr( 10402 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10403 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10404 return Init.Failed() ? ExprError() : E; 10405 }); 10406 if (Res.isInvalid()) { 10407 VDecl->setInvalidDecl(); 10408 } else if (Res.get() != Args[Idx]) { 10409 Args[Idx] = Res.get(); 10410 } 10411 } 10412 if (VDecl->isInvalidDecl()) 10413 return; 10414 10415 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10416 /*TopLevelOfInitList=*/false, 10417 /*TreatUnavailableAsInvalid=*/false); 10418 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10419 if (Result.isInvalid()) { 10420 VDecl->setInvalidDecl(); 10421 return; 10422 } 10423 10424 Init = Result.getAs<Expr>(); 10425 } 10426 10427 // Check for self-references within variable initializers. 10428 // Variables declared within a function/method body (except for references) 10429 // are handled by a dataflow analysis. 10430 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10431 VDecl->getType()->isReferenceType()) { 10432 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10433 } 10434 10435 // If the type changed, it means we had an incomplete type that was 10436 // completed by the initializer. For example: 10437 // int ary[] = { 1, 3, 5 }; 10438 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10439 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10440 VDecl->setType(DclT); 10441 10442 if (!VDecl->isInvalidDecl()) { 10443 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10444 10445 if (VDecl->hasAttr<BlocksAttr>()) 10446 checkRetainCycles(VDecl, Init); 10447 10448 // It is safe to assign a weak reference into a strong variable. 10449 // Although this code can still have problems: 10450 // id x = self.weakProp; 10451 // id y = self.weakProp; 10452 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10453 // paths through the function. This should be revisited if 10454 // -Wrepeated-use-of-weak is made flow-sensitive. 10455 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10456 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10457 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10458 Init->getLocStart())) 10459 getCurFunction()->markSafeWeakUse(Init); 10460 } 10461 10462 // The initialization is usually a full-expression. 10463 // 10464 // FIXME: If this is a braced initialization of an aggregate, it is not 10465 // an expression, and each individual field initializer is a separate 10466 // full-expression. For instance, in: 10467 // 10468 // struct Temp { ~Temp(); }; 10469 // struct S { S(Temp); }; 10470 // struct T { S a, b; } t = { Temp(), Temp() } 10471 // 10472 // we should destroy the first Temp before constructing the second. 10473 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10474 false, 10475 VDecl->isConstexpr()); 10476 if (Result.isInvalid()) { 10477 VDecl->setInvalidDecl(); 10478 return; 10479 } 10480 Init = Result.get(); 10481 10482 // Attach the initializer to the decl. 10483 VDecl->setInit(Init); 10484 10485 if (VDecl->isLocalVarDecl()) { 10486 // Don't check the initializer if the declaration is malformed. 10487 if (VDecl->isInvalidDecl()) { 10488 // do nothing 10489 10490 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10491 // This is true even in OpenCL C++. 10492 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10493 CheckForConstantInitializer(Init, DclT); 10494 10495 // Otherwise, C++ does not restrict the initializer. 10496 } else if (getLangOpts().CPlusPlus) { 10497 // do nothing 10498 10499 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10500 // static storage duration shall be constant expressions or string literals. 10501 } else if (VDecl->getStorageClass() == SC_Static) { 10502 CheckForConstantInitializer(Init, DclT); 10503 10504 // C89 is stricter than C99 for aggregate initializers. 10505 // C89 6.5.7p3: All the expressions [...] in an initializer list 10506 // for an object that has aggregate or union type shall be 10507 // constant expressions. 10508 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10509 isa<InitListExpr>(Init)) { 10510 const Expr *Culprit; 10511 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10512 Diag(Culprit->getExprLoc(), 10513 diag::ext_aggregate_init_not_constant) 10514 << Culprit->getSourceRange(); 10515 } 10516 } 10517 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10518 VDecl->getLexicalDeclContext()->isRecord()) { 10519 // This is an in-class initialization for a static data member, e.g., 10520 // 10521 // struct S { 10522 // static const int value = 17; 10523 // }; 10524 10525 // C++ [class.mem]p4: 10526 // A member-declarator can contain a constant-initializer only 10527 // if it declares a static member (9.4) of const integral or 10528 // const enumeration type, see 9.4.2. 10529 // 10530 // C++11 [class.static.data]p3: 10531 // If a non-volatile non-inline const static data member is of integral 10532 // or enumeration type, its declaration in the class definition can 10533 // specify a brace-or-equal-initializer in which every initializer-clause 10534 // that is an assignment-expression is a constant expression. A static 10535 // data member of literal type can be declared in the class definition 10536 // with the constexpr specifier; if so, its declaration shall specify a 10537 // brace-or-equal-initializer in which every initializer-clause that is 10538 // an assignment-expression is a constant expression. 10539 10540 // Do nothing on dependent types. 10541 if (DclT->isDependentType()) { 10542 10543 // Allow any 'static constexpr' members, whether or not they are of literal 10544 // type. We separately check that every constexpr variable is of literal 10545 // type. 10546 } else if (VDecl->isConstexpr()) { 10547 10548 // Require constness. 10549 } else if (!DclT.isConstQualified()) { 10550 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10551 << Init->getSourceRange(); 10552 VDecl->setInvalidDecl(); 10553 10554 // We allow integer constant expressions in all cases. 10555 } else if (DclT->isIntegralOrEnumerationType()) { 10556 // Check whether the expression is a constant expression. 10557 SourceLocation Loc; 10558 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10559 // In C++11, a non-constexpr const static data member with an 10560 // in-class initializer cannot be volatile. 10561 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10562 else if (Init->isValueDependent()) 10563 ; // Nothing to check. 10564 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10565 ; // Ok, it's an ICE! 10566 else if (Init->isEvaluatable(Context)) { 10567 // If we can constant fold the initializer through heroics, accept it, 10568 // but report this as a use of an extension for -pedantic. 10569 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10570 << Init->getSourceRange(); 10571 } else { 10572 // Otherwise, this is some crazy unknown case. Report the issue at the 10573 // location provided by the isIntegerConstantExpr failed check. 10574 Diag(Loc, diag::err_in_class_initializer_non_constant) 10575 << Init->getSourceRange(); 10576 VDecl->setInvalidDecl(); 10577 } 10578 10579 // We allow foldable floating-point constants as an extension. 10580 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10581 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10582 // it anyway and provide a fixit to add the 'constexpr'. 10583 if (getLangOpts().CPlusPlus11) { 10584 Diag(VDecl->getLocation(), 10585 diag::ext_in_class_initializer_float_type_cxx11) 10586 << DclT << Init->getSourceRange(); 10587 Diag(VDecl->getLocStart(), 10588 diag::note_in_class_initializer_float_type_cxx11) 10589 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10590 } else { 10591 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10592 << DclT << Init->getSourceRange(); 10593 10594 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10595 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10596 << Init->getSourceRange(); 10597 VDecl->setInvalidDecl(); 10598 } 10599 } 10600 10601 // Suggest adding 'constexpr' in C++11 for literal types. 10602 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10603 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10604 << DclT << Init->getSourceRange() 10605 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10606 VDecl->setConstexpr(true); 10607 10608 } else { 10609 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10610 << DclT << Init->getSourceRange(); 10611 VDecl->setInvalidDecl(); 10612 } 10613 } else if (VDecl->isFileVarDecl()) { 10614 // In C, extern is typically used to avoid tentative definitions when 10615 // declaring variables in headers, but adding an intializer makes it a 10616 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10617 // In C++, extern is often used to give implictly static const variables 10618 // external linkage, so don't warn in that case. If selectany is present, 10619 // this might be header code intended for C and C++ inclusion, so apply the 10620 // C++ rules. 10621 if (VDecl->getStorageClass() == SC_Extern && 10622 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10623 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10624 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10625 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10626 Diag(VDecl->getLocation(), diag::warn_extern_init); 10627 10628 // C99 6.7.8p4. All file scoped initializers need to be constant. 10629 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10630 CheckForConstantInitializer(Init, DclT); 10631 } 10632 10633 // We will represent direct-initialization similarly to copy-initialization: 10634 // int x(1); -as-> int x = 1; 10635 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10636 // 10637 // Clients that want to distinguish between the two forms, can check for 10638 // direct initializer using VarDecl::getInitStyle(). 10639 // A major benefit is that clients that don't particularly care about which 10640 // exactly form was it (like the CodeGen) can handle both cases without 10641 // special case code. 10642 10643 // C++ 8.5p11: 10644 // The form of initialization (using parentheses or '=') is generally 10645 // insignificant, but does matter when the entity being initialized has a 10646 // class type. 10647 if (CXXDirectInit) { 10648 assert(DirectInit && "Call-style initializer must be direct init."); 10649 VDecl->setInitStyle(VarDecl::CallInit); 10650 } else if (DirectInit) { 10651 // This must be list-initialization. No other way is direct-initialization. 10652 VDecl->setInitStyle(VarDecl::ListInit); 10653 } 10654 10655 CheckCompleteVariableDeclaration(VDecl); 10656 } 10657 10658 /// ActOnInitializerError - Given that there was an error parsing an 10659 /// initializer for the given declaration, try to return to some form 10660 /// of sanity. 10661 void Sema::ActOnInitializerError(Decl *D) { 10662 // Our main concern here is re-establishing invariants like "a 10663 // variable's type is either dependent or complete". 10664 if (!D || D->isInvalidDecl()) return; 10665 10666 VarDecl *VD = dyn_cast<VarDecl>(D); 10667 if (!VD) return; 10668 10669 // Bindings are not usable if we can't make sense of the initializer. 10670 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10671 for (auto *BD : DD->bindings()) 10672 BD->setInvalidDecl(); 10673 10674 // Auto types are meaningless if we can't make sense of the initializer. 10675 if (ParsingInitForAutoVars.count(D)) { 10676 D->setInvalidDecl(); 10677 return; 10678 } 10679 10680 QualType Ty = VD->getType(); 10681 if (Ty->isDependentType()) return; 10682 10683 // Require a complete type. 10684 if (RequireCompleteType(VD->getLocation(), 10685 Context.getBaseElementType(Ty), 10686 diag::err_typecheck_decl_incomplete_type)) { 10687 VD->setInvalidDecl(); 10688 return; 10689 } 10690 10691 // Require a non-abstract type. 10692 if (RequireNonAbstractType(VD->getLocation(), Ty, 10693 diag::err_abstract_type_in_decl, 10694 AbstractVariableType)) { 10695 VD->setInvalidDecl(); 10696 return; 10697 } 10698 10699 // Don't bother complaining about constructors or destructors, 10700 // though. 10701 } 10702 10703 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10704 // If there is no declaration, there was an error parsing it. Just ignore it. 10705 if (!RealDecl) 10706 return; 10707 10708 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10709 QualType Type = Var->getType(); 10710 10711 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10712 if (isa<DecompositionDecl>(RealDecl)) { 10713 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10714 Var->setInvalidDecl(); 10715 return; 10716 } 10717 10718 if (Type->isUndeducedType() && 10719 DeduceVariableDeclarationType(Var, false, nullptr)) 10720 return; 10721 10722 // C++11 [class.static.data]p3: A static data member can be declared with 10723 // the constexpr specifier; if so, its declaration shall specify 10724 // a brace-or-equal-initializer. 10725 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10726 // the definition of a variable [...] or the declaration of a static data 10727 // member. 10728 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10729 !Var->isThisDeclarationADemotedDefinition()) { 10730 if (Var->isStaticDataMember()) { 10731 // C++1z removes the relevant rule; the in-class declaration is always 10732 // a definition there. 10733 if (!getLangOpts().CPlusPlus1z) { 10734 Diag(Var->getLocation(), 10735 diag::err_constexpr_static_mem_var_requires_init) 10736 << Var->getDeclName(); 10737 Var->setInvalidDecl(); 10738 return; 10739 } 10740 } else { 10741 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10742 Var->setInvalidDecl(); 10743 return; 10744 } 10745 } 10746 10747 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10748 // definition having the concept specifier is called a variable concept. A 10749 // concept definition refers to [...] a variable concept and its initializer. 10750 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10751 if (VTD->isConcept()) { 10752 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10753 Var->setInvalidDecl(); 10754 return; 10755 } 10756 } 10757 10758 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10759 // be initialized. 10760 if (!Var->isInvalidDecl() && 10761 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10762 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10763 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10764 Var->setInvalidDecl(); 10765 return; 10766 } 10767 10768 switch (Var->isThisDeclarationADefinition()) { 10769 case VarDecl::Definition: 10770 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10771 break; 10772 10773 // We have an out-of-line definition of a static data member 10774 // that has an in-class initializer, so we type-check this like 10775 // a declaration. 10776 // 10777 // Fall through 10778 10779 case VarDecl::DeclarationOnly: 10780 // It's only a declaration. 10781 10782 // Block scope. C99 6.7p7: If an identifier for an object is 10783 // declared with no linkage (C99 6.2.2p6), the type for the 10784 // object shall be complete. 10785 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10786 !Var->hasLinkage() && !Var->isInvalidDecl() && 10787 RequireCompleteType(Var->getLocation(), Type, 10788 diag::err_typecheck_decl_incomplete_type)) 10789 Var->setInvalidDecl(); 10790 10791 // Make sure that the type is not abstract. 10792 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10793 RequireNonAbstractType(Var->getLocation(), Type, 10794 diag::err_abstract_type_in_decl, 10795 AbstractVariableType)) 10796 Var->setInvalidDecl(); 10797 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10798 Var->getStorageClass() == SC_PrivateExtern) { 10799 Diag(Var->getLocation(), diag::warn_private_extern); 10800 Diag(Var->getLocation(), diag::note_private_extern); 10801 } 10802 10803 return; 10804 10805 case VarDecl::TentativeDefinition: 10806 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10807 // object that has file scope without an initializer, and without a 10808 // storage-class specifier or with the storage-class specifier "static", 10809 // constitutes a tentative definition. Note: A tentative definition with 10810 // external linkage is valid (C99 6.2.2p5). 10811 if (!Var->isInvalidDecl()) { 10812 if (const IncompleteArrayType *ArrayT 10813 = Context.getAsIncompleteArrayType(Type)) { 10814 if (RequireCompleteType(Var->getLocation(), 10815 ArrayT->getElementType(), 10816 diag::err_illegal_decl_array_incomplete_type)) 10817 Var->setInvalidDecl(); 10818 } else if (Var->getStorageClass() == SC_Static) { 10819 // C99 6.9.2p3: If the declaration of an identifier for an object is 10820 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10821 // declared type shall not be an incomplete type. 10822 // NOTE: code such as the following 10823 // static struct s; 10824 // struct s { int a; }; 10825 // is accepted by gcc. Hence here we issue a warning instead of 10826 // an error and we do not invalidate the static declaration. 10827 // NOTE: to avoid multiple warnings, only check the first declaration. 10828 if (Var->isFirstDecl()) 10829 RequireCompleteType(Var->getLocation(), Type, 10830 diag::ext_typecheck_decl_incomplete_type); 10831 } 10832 } 10833 10834 // Record the tentative definition; we're done. 10835 if (!Var->isInvalidDecl()) 10836 TentativeDefinitions.push_back(Var); 10837 return; 10838 } 10839 10840 // Provide a specific diagnostic for uninitialized variable 10841 // definitions with incomplete array type. 10842 if (Type->isIncompleteArrayType()) { 10843 Diag(Var->getLocation(), 10844 diag::err_typecheck_incomplete_array_needs_initializer); 10845 Var->setInvalidDecl(); 10846 return; 10847 } 10848 10849 // Provide a specific diagnostic for uninitialized variable 10850 // definitions with reference type. 10851 if (Type->isReferenceType()) { 10852 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10853 << Var->getDeclName() 10854 << SourceRange(Var->getLocation(), Var->getLocation()); 10855 Var->setInvalidDecl(); 10856 return; 10857 } 10858 10859 // Do not attempt to type-check the default initializer for a 10860 // variable with dependent type. 10861 if (Type->isDependentType()) 10862 return; 10863 10864 if (Var->isInvalidDecl()) 10865 return; 10866 10867 if (!Var->hasAttr<AliasAttr>()) { 10868 if (RequireCompleteType(Var->getLocation(), 10869 Context.getBaseElementType(Type), 10870 diag::err_typecheck_decl_incomplete_type)) { 10871 Var->setInvalidDecl(); 10872 return; 10873 } 10874 } else { 10875 return; 10876 } 10877 10878 // The variable can not have an abstract class type. 10879 if (RequireNonAbstractType(Var->getLocation(), Type, 10880 diag::err_abstract_type_in_decl, 10881 AbstractVariableType)) { 10882 Var->setInvalidDecl(); 10883 return; 10884 } 10885 10886 // Check for jumps past the implicit initializer. C++0x 10887 // clarifies that this applies to a "variable with automatic 10888 // storage duration", not a "local variable". 10889 // C++11 [stmt.dcl]p3 10890 // A program that jumps from a point where a variable with automatic 10891 // storage duration is not in scope to a point where it is in scope is 10892 // ill-formed unless the variable has scalar type, class type with a 10893 // trivial default constructor and a trivial destructor, a cv-qualified 10894 // version of one of these types, or an array of one of the preceding 10895 // types and is declared without an initializer. 10896 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10897 if (const RecordType *Record 10898 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10899 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10900 // Mark the function for further checking even if the looser rules of 10901 // C++11 do not require such checks, so that we can diagnose 10902 // incompatibilities with C++98. 10903 if (!CXXRecord->isPOD()) 10904 getCurFunction()->setHasBranchProtectedScope(); 10905 } 10906 } 10907 10908 // C++03 [dcl.init]p9: 10909 // If no initializer is specified for an object, and the 10910 // object is of (possibly cv-qualified) non-POD class type (or 10911 // array thereof), the object shall be default-initialized; if 10912 // the object is of const-qualified type, the underlying class 10913 // type shall have a user-declared default 10914 // constructor. Otherwise, if no initializer is specified for 10915 // a non- static object, the object and its subobjects, if 10916 // any, have an indeterminate initial value); if the object 10917 // or any of its subobjects are of const-qualified type, the 10918 // program is ill-formed. 10919 // C++0x [dcl.init]p11: 10920 // If no initializer is specified for an object, the object is 10921 // default-initialized; [...]. 10922 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10923 InitializationKind Kind 10924 = InitializationKind::CreateDefault(Var->getLocation()); 10925 10926 InitializationSequence InitSeq(*this, Entity, Kind, None); 10927 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10928 if (Init.isInvalid()) 10929 Var->setInvalidDecl(); 10930 else if (Init.get()) { 10931 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10932 // This is important for template substitution. 10933 Var->setInitStyle(VarDecl::CallInit); 10934 } 10935 10936 CheckCompleteVariableDeclaration(Var); 10937 } 10938 } 10939 10940 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10941 // If there is no declaration, there was an error parsing it. Ignore it. 10942 if (!D) 10943 return; 10944 10945 VarDecl *VD = dyn_cast<VarDecl>(D); 10946 if (!VD) { 10947 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10948 D->setInvalidDecl(); 10949 return; 10950 } 10951 10952 VD->setCXXForRangeDecl(true); 10953 10954 // for-range-declaration cannot be given a storage class specifier. 10955 int Error = -1; 10956 switch (VD->getStorageClass()) { 10957 case SC_None: 10958 break; 10959 case SC_Extern: 10960 Error = 0; 10961 break; 10962 case SC_Static: 10963 Error = 1; 10964 break; 10965 case SC_PrivateExtern: 10966 Error = 2; 10967 break; 10968 case SC_Auto: 10969 Error = 3; 10970 break; 10971 case SC_Register: 10972 Error = 4; 10973 break; 10974 } 10975 if (Error != -1) { 10976 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10977 << VD->getDeclName() << Error; 10978 D->setInvalidDecl(); 10979 } 10980 } 10981 10982 StmtResult 10983 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10984 IdentifierInfo *Ident, 10985 ParsedAttributes &Attrs, 10986 SourceLocation AttrEnd) { 10987 // C++1y [stmt.iter]p1: 10988 // A range-based for statement of the form 10989 // for ( for-range-identifier : for-range-initializer ) statement 10990 // is equivalent to 10991 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10992 DeclSpec DS(Attrs.getPool().getFactory()); 10993 10994 const char *PrevSpec; 10995 unsigned DiagID; 10996 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10997 getPrintingPolicy()); 10998 10999 Declarator D(DS, Declarator::ForContext); 11000 D.SetIdentifier(Ident, IdentLoc); 11001 D.takeAttributes(Attrs, AttrEnd); 11002 11003 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11004 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11005 EmptyAttrs, IdentLoc); 11006 Decl *Var = ActOnDeclarator(S, D); 11007 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11008 FinalizeDeclaration(Var); 11009 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11010 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11011 } 11012 11013 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11014 if (var->isInvalidDecl()) return; 11015 11016 if (getLangOpts().OpenCL) { 11017 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11018 // initialiser 11019 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11020 !var->hasInit()) { 11021 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11022 << 1 /*Init*/; 11023 var->setInvalidDecl(); 11024 return; 11025 } 11026 } 11027 11028 // In Objective-C, don't allow jumps past the implicit initialization of a 11029 // local retaining variable. 11030 if (getLangOpts().ObjC1 && 11031 var->hasLocalStorage()) { 11032 switch (var->getType().getObjCLifetime()) { 11033 case Qualifiers::OCL_None: 11034 case Qualifiers::OCL_ExplicitNone: 11035 case Qualifiers::OCL_Autoreleasing: 11036 break; 11037 11038 case Qualifiers::OCL_Weak: 11039 case Qualifiers::OCL_Strong: 11040 getCurFunction()->setHasBranchProtectedScope(); 11041 break; 11042 } 11043 } 11044 11045 // Warn about externally-visible variables being defined without a 11046 // prior declaration. We only want to do this for global 11047 // declarations, but we also specifically need to avoid doing it for 11048 // class members because the linkage of an anonymous class can 11049 // change if it's later given a typedef name. 11050 if (var->isThisDeclarationADefinition() && 11051 var->getDeclContext()->getRedeclContext()->isFileContext() && 11052 var->isExternallyVisible() && var->hasLinkage() && 11053 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11054 var->getLocation())) { 11055 // Find a previous declaration that's not a definition. 11056 VarDecl *prev = var->getPreviousDecl(); 11057 while (prev && prev->isThisDeclarationADefinition()) 11058 prev = prev->getPreviousDecl(); 11059 11060 if (!prev) 11061 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11062 } 11063 11064 // Cache the result of checking for constant initialization. 11065 Optional<bool> CacheHasConstInit; 11066 const Expr *CacheCulprit; 11067 auto checkConstInit = [&]() mutable { 11068 if (!CacheHasConstInit) 11069 CacheHasConstInit = var->getInit()->isConstantInitializer( 11070 Context, var->getType()->isReferenceType(), &CacheCulprit); 11071 return *CacheHasConstInit; 11072 }; 11073 11074 if (var->getTLSKind() == VarDecl::TLS_Static) { 11075 if (var->getType().isDestructedType()) { 11076 // GNU C++98 edits for __thread, [basic.start.term]p3: 11077 // The type of an object with thread storage duration shall not 11078 // have a non-trivial destructor. 11079 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11080 if (getLangOpts().CPlusPlus11) 11081 Diag(var->getLocation(), diag::note_use_thread_local); 11082 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11083 if (!checkConstInit()) { 11084 // GNU C++98 edits for __thread, [basic.start.init]p4: 11085 // An object of thread storage duration shall not require dynamic 11086 // initialization. 11087 // FIXME: Need strict checking here. 11088 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11089 << CacheCulprit->getSourceRange(); 11090 if (getLangOpts().CPlusPlus11) 11091 Diag(var->getLocation(), diag::note_use_thread_local); 11092 } 11093 } 11094 } 11095 11096 // Apply section attributes and pragmas to global variables. 11097 bool GlobalStorage = var->hasGlobalStorage(); 11098 if (GlobalStorage && var->isThisDeclarationADefinition() && 11099 !inTemplateInstantiation()) { 11100 PragmaStack<StringLiteral *> *Stack = nullptr; 11101 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11102 if (var->getType().isConstQualified()) 11103 Stack = &ConstSegStack; 11104 else if (!var->getInit()) { 11105 Stack = &BSSSegStack; 11106 SectionFlags |= ASTContext::PSF_Write; 11107 } else { 11108 Stack = &DataSegStack; 11109 SectionFlags |= ASTContext::PSF_Write; 11110 } 11111 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11112 var->addAttr(SectionAttr::CreateImplicit( 11113 Context, SectionAttr::Declspec_allocate, 11114 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11115 } 11116 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11117 if (UnifySection(SA->getName(), SectionFlags, var)) 11118 var->dropAttr<SectionAttr>(); 11119 11120 // Apply the init_seg attribute if this has an initializer. If the 11121 // initializer turns out to not be dynamic, we'll end up ignoring this 11122 // attribute. 11123 if (CurInitSeg && var->getInit()) 11124 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11125 CurInitSegLoc)); 11126 } 11127 11128 // All the following checks are C++ only. 11129 if (!getLangOpts().CPlusPlus) { 11130 // If this variable must be emitted, add it as an initializer for the 11131 // current module. 11132 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11133 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11134 return; 11135 } 11136 11137 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11138 CheckCompleteDecompositionDeclaration(DD); 11139 11140 QualType type = var->getType(); 11141 if (type->isDependentType()) return; 11142 11143 // __block variables might require us to capture a copy-initializer. 11144 if (var->hasAttr<BlocksAttr>()) { 11145 // It's currently invalid to ever have a __block variable with an 11146 // array type; should we diagnose that here? 11147 11148 // Regardless, we don't want to ignore array nesting when 11149 // constructing this copy. 11150 if (type->isStructureOrClassType()) { 11151 EnterExpressionEvaluationContext scope( 11152 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11153 SourceLocation poi = var->getLocation(); 11154 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11155 ExprResult result 11156 = PerformMoveOrCopyInitialization( 11157 InitializedEntity::InitializeBlock(poi, type, false), 11158 var, var->getType(), varRef, /*AllowNRVO=*/true); 11159 if (!result.isInvalid()) { 11160 result = MaybeCreateExprWithCleanups(result); 11161 Expr *init = result.getAs<Expr>(); 11162 Context.setBlockVarCopyInits(var, init); 11163 } 11164 } 11165 } 11166 11167 Expr *Init = var->getInit(); 11168 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11169 QualType baseType = Context.getBaseElementType(type); 11170 11171 if (Init && !Init->isValueDependent()) { 11172 if (var->isConstexpr()) { 11173 SmallVector<PartialDiagnosticAt, 8> Notes; 11174 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11175 SourceLocation DiagLoc = var->getLocation(); 11176 // If the note doesn't add any useful information other than a source 11177 // location, fold it into the primary diagnostic. 11178 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11179 diag::note_invalid_subexpr_in_const_expr) { 11180 DiagLoc = Notes[0].first; 11181 Notes.clear(); 11182 } 11183 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11184 << var << Init->getSourceRange(); 11185 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11186 Diag(Notes[I].first, Notes[I].second); 11187 } 11188 } else if (var->isUsableInConstantExpressions(Context)) { 11189 // Check whether the initializer of a const variable of integral or 11190 // enumeration type is an ICE now, since we can't tell whether it was 11191 // initialized by a constant expression if we check later. 11192 var->checkInitIsICE(); 11193 } 11194 11195 // Don't emit further diagnostics about constexpr globals since they 11196 // were just diagnosed. 11197 if (!var->isConstexpr() && GlobalStorage && 11198 var->hasAttr<RequireConstantInitAttr>()) { 11199 // FIXME: Need strict checking in C++03 here. 11200 bool DiagErr = getLangOpts().CPlusPlus11 11201 ? !var->checkInitIsICE() : !checkConstInit(); 11202 if (DiagErr) { 11203 auto attr = var->getAttr<RequireConstantInitAttr>(); 11204 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11205 << Init->getSourceRange(); 11206 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11207 << attr->getRange(); 11208 if (getLangOpts().CPlusPlus11) { 11209 APValue Value; 11210 SmallVector<PartialDiagnosticAt, 8> Notes; 11211 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11212 for (auto &it : Notes) 11213 Diag(it.first, it.second); 11214 } else { 11215 Diag(CacheCulprit->getExprLoc(), 11216 diag::note_invalid_subexpr_in_const_expr) 11217 << CacheCulprit->getSourceRange(); 11218 } 11219 } 11220 } 11221 else if (!var->isConstexpr() && IsGlobal && 11222 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11223 var->getLocation())) { 11224 // Warn about globals which don't have a constant initializer. Don't 11225 // warn about globals with a non-trivial destructor because we already 11226 // warned about them. 11227 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11228 if (!(RD && !RD->hasTrivialDestructor())) { 11229 if (!checkConstInit()) 11230 Diag(var->getLocation(), diag::warn_global_constructor) 11231 << Init->getSourceRange(); 11232 } 11233 } 11234 } 11235 11236 // Require the destructor. 11237 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11238 FinalizeVarWithDestructor(var, recordType); 11239 11240 // If this variable must be emitted, add it as an initializer for the current 11241 // module. 11242 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11243 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11244 } 11245 11246 /// \brief Determines if a variable's alignment is dependent. 11247 static bool hasDependentAlignment(VarDecl *VD) { 11248 if (VD->getType()->isDependentType()) 11249 return true; 11250 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11251 if (I->isAlignmentDependent()) 11252 return true; 11253 return false; 11254 } 11255 11256 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11257 /// any semantic actions necessary after any initializer has been attached. 11258 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11259 // Note that we are no longer parsing the initializer for this declaration. 11260 ParsingInitForAutoVars.erase(ThisDecl); 11261 11262 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11263 if (!VD) 11264 return; 11265 11266 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11267 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11268 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11269 if (PragmaClangBSSSection.Valid) 11270 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11271 PragmaClangBSSSection.SectionName, 11272 PragmaClangBSSSection.PragmaLocation)); 11273 if (PragmaClangDataSection.Valid) 11274 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11275 PragmaClangDataSection.SectionName, 11276 PragmaClangDataSection.PragmaLocation)); 11277 if (PragmaClangRodataSection.Valid) 11278 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11279 PragmaClangRodataSection.SectionName, 11280 PragmaClangRodataSection.PragmaLocation)); 11281 } 11282 11283 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11284 for (auto *BD : DD->bindings()) { 11285 FinalizeDeclaration(BD); 11286 } 11287 } 11288 11289 checkAttributesAfterMerging(*this, *VD); 11290 11291 // Perform TLS alignment check here after attributes attached to the variable 11292 // which may affect the alignment have been processed. Only perform the check 11293 // if the target has a maximum TLS alignment (zero means no constraints). 11294 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11295 // Protect the check so that it's not performed on dependent types and 11296 // dependent alignments (we can't determine the alignment in that case). 11297 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11298 !VD->isInvalidDecl()) { 11299 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11300 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11301 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11302 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11303 << (unsigned)MaxAlignChars.getQuantity(); 11304 } 11305 } 11306 } 11307 11308 if (VD->isStaticLocal()) { 11309 if (FunctionDecl *FD = 11310 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11311 // Static locals inherit dll attributes from their function. 11312 if (Attr *A = getDLLAttr(FD)) { 11313 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11314 NewAttr->setInherited(true); 11315 VD->addAttr(NewAttr); 11316 } 11317 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11318 // function, only __shared__ variables may be declared with 11319 // static storage class. 11320 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11321 CUDADiagIfDeviceCode(VD->getLocation(), 11322 diag::err_device_static_local_var) 11323 << CurrentCUDATarget()) 11324 VD->setInvalidDecl(); 11325 } 11326 } 11327 11328 // Perform check for initializers of device-side global variables. 11329 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11330 // 7.5). We must also apply the same checks to all __shared__ 11331 // variables whether they are local or not. CUDA also allows 11332 // constant initializers for __constant__ and __device__ variables. 11333 if (getLangOpts().CUDA) { 11334 const Expr *Init = VD->getInit(); 11335 if (Init && VD->hasGlobalStorage()) { 11336 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11337 VD->hasAttr<CUDASharedAttr>()) { 11338 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11339 bool AllowedInit = false; 11340 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11341 AllowedInit = 11342 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11343 // We'll allow constant initializers even if it's a non-empty 11344 // constructor according to CUDA rules. This deviates from NVCC, 11345 // but allows us to handle things like constexpr constructors. 11346 if (!AllowedInit && 11347 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11348 AllowedInit = VD->getInit()->isConstantInitializer( 11349 Context, VD->getType()->isReferenceType()); 11350 11351 // Also make sure that destructor, if there is one, is empty. 11352 if (AllowedInit) 11353 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11354 AllowedInit = 11355 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11356 11357 if (!AllowedInit) { 11358 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11359 ? diag::err_shared_var_init 11360 : diag::err_dynamic_var_init) 11361 << Init->getSourceRange(); 11362 VD->setInvalidDecl(); 11363 } 11364 } else { 11365 // This is a host-side global variable. Check that the initializer is 11366 // callable from the host side. 11367 const FunctionDecl *InitFn = nullptr; 11368 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11369 InitFn = CE->getConstructor(); 11370 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11371 InitFn = CE->getDirectCallee(); 11372 } 11373 if (InitFn) { 11374 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11375 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11376 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11377 << InitFnTarget << InitFn; 11378 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11379 VD->setInvalidDecl(); 11380 } 11381 } 11382 } 11383 } 11384 } 11385 11386 // Grab the dllimport or dllexport attribute off of the VarDecl. 11387 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11388 11389 // Imported static data members cannot be defined out-of-line. 11390 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11391 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11392 VD->isThisDeclarationADefinition()) { 11393 // We allow definitions of dllimport class template static data members 11394 // with a warning. 11395 CXXRecordDecl *Context = 11396 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11397 bool IsClassTemplateMember = 11398 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11399 Context->getDescribedClassTemplate(); 11400 11401 Diag(VD->getLocation(), 11402 IsClassTemplateMember 11403 ? diag::warn_attribute_dllimport_static_field_definition 11404 : diag::err_attribute_dllimport_static_field_definition); 11405 Diag(IA->getLocation(), diag::note_attribute); 11406 if (!IsClassTemplateMember) 11407 VD->setInvalidDecl(); 11408 } 11409 } 11410 11411 // dllimport/dllexport variables cannot be thread local, their TLS index 11412 // isn't exported with the variable. 11413 if (DLLAttr && VD->getTLSKind()) { 11414 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11415 if (F && getDLLAttr(F)) { 11416 assert(VD->isStaticLocal()); 11417 // But if this is a static local in a dlimport/dllexport function, the 11418 // function will never be inlined, which means the var would never be 11419 // imported, so having it marked import/export is safe. 11420 } else { 11421 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11422 << DLLAttr; 11423 VD->setInvalidDecl(); 11424 } 11425 } 11426 11427 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11428 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11429 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11430 VD->dropAttr<UsedAttr>(); 11431 } 11432 } 11433 11434 const DeclContext *DC = VD->getDeclContext(); 11435 // If there's a #pragma GCC visibility in scope, and this isn't a class 11436 // member, set the visibility of this variable. 11437 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11438 AddPushedVisibilityAttribute(VD); 11439 11440 // FIXME: Warn on unused var template partial specializations. 11441 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11442 MarkUnusedFileScopedDecl(VD); 11443 11444 // Now we have parsed the initializer and can update the table of magic 11445 // tag values. 11446 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11447 !VD->getType()->isIntegralOrEnumerationType()) 11448 return; 11449 11450 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11451 const Expr *MagicValueExpr = VD->getInit(); 11452 if (!MagicValueExpr) { 11453 continue; 11454 } 11455 llvm::APSInt MagicValueInt; 11456 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11457 Diag(I->getRange().getBegin(), 11458 diag::err_type_tag_for_datatype_not_ice) 11459 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11460 continue; 11461 } 11462 if (MagicValueInt.getActiveBits() > 64) { 11463 Diag(I->getRange().getBegin(), 11464 diag::err_type_tag_for_datatype_too_large) 11465 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11466 continue; 11467 } 11468 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11469 RegisterTypeTagForDatatype(I->getArgumentKind(), 11470 MagicValue, 11471 I->getMatchingCType(), 11472 I->getLayoutCompatible(), 11473 I->getMustBeNull()); 11474 } 11475 } 11476 11477 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11478 auto *VD = dyn_cast<VarDecl>(DD); 11479 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11480 } 11481 11482 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11483 ArrayRef<Decl *> Group) { 11484 SmallVector<Decl*, 8> Decls; 11485 11486 if (DS.isTypeSpecOwned()) 11487 Decls.push_back(DS.getRepAsDecl()); 11488 11489 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11490 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11491 bool DiagnosedMultipleDecomps = false; 11492 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11493 bool DiagnosedNonDeducedAuto = false; 11494 11495 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11496 if (Decl *D = Group[i]) { 11497 // For declarators, there are some additional syntactic-ish checks we need 11498 // to perform. 11499 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11500 if (!FirstDeclaratorInGroup) 11501 FirstDeclaratorInGroup = DD; 11502 if (!FirstDecompDeclaratorInGroup) 11503 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11504 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11505 !hasDeducedAuto(DD)) 11506 FirstNonDeducedAutoInGroup = DD; 11507 11508 if (FirstDeclaratorInGroup != DD) { 11509 // A decomposition declaration cannot be combined with any other 11510 // declaration in the same group. 11511 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11512 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11513 diag::err_decomp_decl_not_alone) 11514 << FirstDeclaratorInGroup->getSourceRange() 11515 << DD->getSourceRange(); 11516 DiagnosedMultipleDecomps = true; 11517 } 11518 11519 // A declarator that uses 'auto' in any way other than to declare a 11520 // variable with a deduced type cannot be combined with any other 11521 // declarator in the same group. 11522 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11523 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11524 diag::err_auto_non_deduced_not_alone) 11525 << FirstNonDeducedAutoInGroup->getType() 11526 ->hasAutoForTrailingReturnType() 11527 << FirstDeclaratorInGroup->getSourceRange() 11528 << DD->getSourceRange(); 11529 DiagnosedNonDeducedAuto = true; 11530 } 11531 } 11532 } 11533 11534 Decls.push_back(D); 11535 } 11536 } 11537 11538 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11539 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11540 handleTagNumbering(Tag, S); 11541 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11542 getLangOpts().CPlusPlus) 11543 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11544 } 11545 } 11546 11547 return BuildDeclaratorGroup(Decls); 11548 } 11549 11550 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11551 /// group, performing any necessary semantic checking. 11552 Sema::DeclGroupPtrTy 11553 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11554 // C++14 [dcl.spec.auto]p7: (DR1347) 11555 // If the type that replaces the placeholder type is not the same in each 11556 // deduction, the program is ill-formed. 11557 if (Group.size() > 1) { 11558 QualType Deduced; 11559 VarDecl *DeducedDecl = nullptr; 11560 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11561 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11562 if (!D || D->isInvalidDecl()) 11563 break; 11564 DeducedType *DT = D->getType()->getContainedDeducedType(); 11565 if (!DT || DT->getDeducedType().isNull()) 11566 continue; 11567 if (Deduced.isNull()) { 11568 Deduced = DT->getDeducedType(); 11569 DeducedDecl = D; 11570 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11571 auto *AT = dyn_cast<AutoType>(DT); 11572 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11573 diag::err_auto_different_deductions) 11574 << (AT ? (unsigned)AT->getKeyword() : 3) 11575 << Deduced << DeducedDecl->getDeclName() 11576 << DT->getDeducedType() << D->getDeclName() 11577 << DeducedDecl->getInit()->getSourceRange() 11578 << D->getInit()->getSourceRange(); 11579 D->setInvalidDecl(); 11580 break; 11581 } 11582 } 11583 } 11584 11585 ActOnDocumentableDecls(Group); 11586 11587 return DeclGroupPtrTy::make( 11588 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11589 } 11590 11591 void Sema::ActOnDocumentableDecl(Decl *D) { 11592 ActOnDocumentableDecls(D); 11593 } 11594 11595 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11596 // Don't parse the comment if Doxygen diagnostics are ignored. 11597 if (Group.empty() || !Group[0]) 11598 return; 11599 11600 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11601 Group[0]->getLocation()) && 11602 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11603 Group[0]->getLocation())) 11604 return; 11605 11606 if (Group.size() >= 2) { 11607 // This is a decl group. Normally it will contain only declarations 11608 // produced from declarator list. But in case we have any definitions or 11609 // additional declaration references: 11610 // 'typedef struct S {} S;' 11611 // 'typedef struct S *S;' 11612 // 'struct S *pS;' 11613 // FinalizeDeclaratorGroup adds these as separate declarations. 11614 Decl *MaybeTagDecl = Group[0]; 11615 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11616 Group = Group.slice(1); 11617 } 11618 } 11619 11620 // See if there are any new comments that are not attached to a decl. 11621 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11622 if (!Comments.empty() && 11623 !Comments.back()->isAttached()) { 11624 // There is at least one comment that not attached to a decl. 11625 // Maybe it should be attached to one of these decls? 11626 // 11627 // Note that this way we pick up not only comments that precede the 11628 // declaration, but also comments that *follow* the declaration -- thanks to 11629 // the lookahead in the lexer: we've consumed the semicolon and looked 11630 // ahead through comments. 11631 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11632 Context.getCommentForDecl(Group[i], &PP); 11633 } 11634 } 11635 11636 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11637 /// to introduce parameters into function prototype scope. 11638 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11639 const DeclSpec &DS = D.getDeclSpec(); 11640 11641 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11642 11643 // C++03 [dcl.stc]p2 also permits 'auto'. 11644 StorageClass SC = SC_None; 11645 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11646 SC = SC_Register; 11647 } else if (getLangOpts().CPlusPlus && 11648 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11649 SC = SC_Auto; 11650 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11651 Diag(DS.getStorageClassSpecLoc(), 11652 diag::err_invalid_storage_class_in_func_decl); 11653 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11654 } 11655 11656 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11657 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11658 << DeclSpec::getSpecifierName(TSCS); 11659 if (DS.isInlineSpecified()) 11660 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11661 << getLangOpts().CPlusPlus1z; 11662 if (DS.isConstexprSpecified()) 11663 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11664 << 0; 11665 if (DS.isConceptSpecified()) 11666 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11667 11668 DiagnoseFunctionSpecifiers(DS); 11669 11670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11671 QualType parmDeclType = TInfo->getType(); 11672 11673 if (getLangOpts().CPlusPlus) { 11674 // Check that there are no default arguments inside the type of this 11675 // parameter. 11676 CheckExtraCXXDefaultArguments(D); 11677 11678 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11679 if (D.getCXXScopeSpec().isSet()) { 11680 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11681 << D.getCXXScopeSpec().getRange(); 11682 D.getCXXScopeSpec().clear(); 11683 } 11684 } 11685 11686 // Ensure we have a valid name 11687 IdentifierInfo *II = nullptr; 11688 if (D.hasName()) { 11689 II = D.getIdentifier(); 11690 if (!II) { 11691 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11692 << GetNameForDeclarator(D).getName(); 11693 D.setInvalidType(true); 11694 } 11695 } 11696 11697 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11698 if (II) { 11699 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11700 ForRedeclaration); 11701 LookupName(R, S); 11702 if (R.isSingleResult()) { 11703 NamedDecl *PrevDecl = R.getFoundDecl(); 11704 if (PrevDecl->isTemplateParameter()) { 11705 // Maybe we will complain about the shadowed template parameter. 11706 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11707 // Just pretend that we didn't see the previous declaration. 11708 PrevDecl = nullptr; 11709 } else if (S->isDeclScope(PrevDecl)) { 11710 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11711 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11712 11713 // Recover by removing the name 11714 II = nullptr; 11715 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11716 D.setInvalidType(true); 11717 } 11718 } 11719 } 11720 11721 // Temporarily put parameter variables in the translation unit, not 11722 // the enclosing context. This prevents them from accidentally 11723 // looking like class members in C++. 11724 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11725 D.getLocStart(), 11726 D.getIdentifierLoc(), II, 11727 parmDeclType, TInfo, 11728 SC); 11729 11730 if (D.isInvalidType()) 11731 New->setInvalidDecl(); 11732 11733 assert(S->isFunctionPrototypeScope()); 11734 assert(S->getFunctionPrototypeDepth() >= 1); 11735 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11736 S->getNextFunctionPrototypeIndex()); 11737 11738 // Add the parameter declaration into this scope. 11739 S->AddDecl(New); 11740 if (II) 11741 IdResolver.AddDecl(New); 11742 11743 ProcessDeclAttributes(S, New, D); 11744 11745 if (D.getDeclSpec().isModulePrivateSpecified()) 11746 Diag(New->getLocation(), diag::err_module_private_local) 11747 << 1 << New->getDeclName() 11748 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11749 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11750 11751 if (New->hasAttr<BlocksAttr>()) { 11752 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11753 } 11754 return New; 11755 } 11756 11757 /// \brief Synthesizes a variable for a parameter arising from a 11758 /// typedef. 11759 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11760 SourceLocation Loc, 11761 QualType T) { 11762 /* FIXME: setting StartLoc == Loc. 11763 Would it be worth to modify callers so as to provide proper source 11764 location for the unnamed parameters, embedding the parameter's type? */ 11765 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11766 T, Context.getTrivialTypeSourceInfo(T, Loc), 11767 SC_None, nullptr); 11768 Param->setImplicit(); 11769 return Param; 11770 } 11771 11772 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11773 // Don't diagnose unused-parameter errors in template instantiations; we 11774 // will already have done so in the template itself. 11775 if (inTemplateInstantiation()) 11776 return; 11777 11778 for (const ParmVarDecl *Parameter : Parameters) { 11779 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11780 !Parameter->hasAttr<UnusedAttr>()) { 11781 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11782 << Parameter->getDeclName(); 11783 } 11784 } 11785 } 11786 11787 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11788 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11789 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11790 return; 11791 11792 // Warn if the return value is pass-by-value and larger than the specified 11793 // threshold. 11794 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11795 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11796 if (Size > LangOpts.NumLargeByValueCopy) 11797 Diag(D->getLocation(), diag::warn_return_value_size) 11798 << D->getDeclName() << Size; 11799 } 11800 11801 // Warn if any parameter is pass-by-value and larger than the specified 11802 // threshold. 11803 for (const ParmVarDecl *Parameter : Parameters) { 11804 QualType T = Parameter->getType(); 11805 if (T->isDependentType() || !T.isPODType(Context)) 11806 continue; 11807 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11808 if (Size > LangOpts.NumLargeByValueCopy) 11809 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11810 << Parameter->getDeclName() << Size; 11811 } 11812 } 11813 11814 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11815 SourceLocation NameLoc, IdentifierInfo *Name, 11816 QualType T, TypeSourceInfo *TSInfo, 11817 StorageClass SC) { 11818 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11819 if (getLangOpts().ObjCAutoRefCount && 11820 T.getObjCLifetime() == Qualifiers::OCL_None && 11821 T->isObjCLifetimeType()) { 11822 11823 Qualifiers::ObjCLifetime lifetime; 11824 11825 // Special cases for arrays: 11826 // - if it's const, use __unsafe_unretained 11827 // - otherwise, it's an error 11828 if (T->isArrayType()) { 11829 if (!T.isConstQualified()) { 11830 DelayedDiagnostics.add( 11831 sema::DelayedDiagnostic::makeForbiddenType( 11832 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11833 } 11834 lifetime = Qualifiers::OCL_ExplicitNone; 11835 } else { 11836 lifetime = T->getObjCARCImplicitLifetime(); 11837 } 11838 T = Context.getLifetimeQualifiedType(T, lifetime); 11839 } 11840 11841 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11842 Context.getAdjustedParameterType(T), 11843 TSInfo, SC, nullptr); 11844 11845 // Parameters can not be abstract class types. 11846 // For record types, this is done by the AbstractClassUsageDiagnoser once 11847 // the class has been completely parsed. 11848 if (!CurContext->isRecord() && 11849 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11850 AbstractParamType)) 11851 New->setInvalidDecl(); 11852 11853 // Parameter declarators cannot be interface types. All ObjC objects are 11854 // passed by reference. 11855 if (T->isObjCObjectType()) { 11856 SourceLocation TypeEndLoc = 11857 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11858 Diag(NameLoc, 11859 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11860 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11861 T = Context.getObjCObjectPointerType(T); 11862 New->setType(T); 11863 } 11864 11865 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11866 // duration shall not be qualified by an address-space qualifier." 11867 // Since all parameters have automatic store duration, they can not have 11868 // an address space. 11869 if (T.getAddressSpace() != 0) { 11870 // OpenCL allows function arguments declared to be an array of a type 11871 // to be qualified with an address space. 11872 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11873 Diag(NameLoc, diag::err_arg_with_address_space); 11874 New->setInvalidDecl(); 11875 } 11876 } 11877 11878 return New; 11879 } 11880 11881 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11882 SourceLocation LocAfterDecls) { 11883 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11884 11885 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11886 // for a K&R function. 11887 if (!FTI.hasPrototype) { 11888 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11889 --i; 11890 if (FTI.Params[i].Param == nullptr) { 11891 SmallString<256> Code; 11892 llvm::raw_svector_ostream(Code) 11893 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11894 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11895 << FTI.Params[i].Ident 11896 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11897 11898 // Implicitly declare the argument as type 'int' for lack of a better 11899 // type. 11900 AttributeFactory attrs; 11901 DeclSpec DS(attrs); 11902 const char* PrevSpec; // unused 11903 unsigned DiagID; // unused 11904 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11905 DiagID, Context.getPrintingPolicy()); 11906 // Use the identifier location for the type source range. 11907 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11908 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11909 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11910 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11911 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11912 } 11913 } 11914 } 11915 } 11916 11917 Decl * 11918 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11919 MultiTemplateParamsArg TemplateParameterLists, 11920 SkipBodyInfo *SkipBody) { 11921 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11922 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11923 Scope *ParentScope = FnBodyScope->getParent(); 11924 11925 D.setFunctionDefinitionKind(FDK_Definition); 11926 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11927 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11928 } 11929 11930 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11931 Consumer.HandleInlineFunctionDefinition(D); 11932 } 11933 11934 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11935 const FunctionDecl*& PossibleZeroParamPrototype) { 11936 // Don't warn about invalid declarations. 11937 if (FD->isInvalidDecl()) 11938 return false; 11939 11940 // Or declarations that aren't global. 11941 if (!FD->isGlobal()) 11942 return false; 11943 11944 // Don't warn about C++ member functions. 11945 if (isa<CXXMethodDecl>(FD)) 11946 return false; 11947 11948 // Don't warn about 'main'. 11949 if (FD->isMain()) 11950 return false; 11951 11952 // Don't warn about inline functions. 11953 if (FD->isInlined()) 11954 return false; 11955 11956 // Don't warn about function templates. 11957 if (FD->getDescribedFunctionTemplate()) 11958 return false; 11959 11960 // Don't warn about function template specializations. 11961 if (FD->isFunctionTemplateSpecialization()) 11962 return false; 11963 11964 // Don't warn for OpenCL kernels. 11965 if (FD->hasAttr<OpenCLKernelAttr>()) 11966 return false; 11967 11968 // Don't warn on explicitly deleted functions. 11969 if (FD->isDeleted()) 11970 return false; 11971 11972 bool MissingPrototype = true; 11973 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11974 Prev; Prev = Prev->getPreviousDecl()) { 11975 // Ignore any declarations that occur in function or method 11976 // scope, because they aren't visible from the header. 11977 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11978 continue; 11979 11980 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11981 if (FD->getNumParams() == 0) 11982 PossibleZeroParamPrototype = Prev; 11983 break; 11984 } 11985 11986 return MissingPrototype; 11987 } 11988 11989 void 11990 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11991 const FunctionDecl *EffectiveDefinition, 11992 SkipBodyInfo *SkipBody) { 11993 const FunctionDecl *Definition = EffectiveDefinition; 11994 if (!Definition) 11995 if (!FD->isDefined(Definition)) 11996 return; 11997 11998 if (canRedefineFunction(Definition, getLangOpts())) 11999 return; 12000 12001 // Don't emit an error when this is redefinition of a typo-corrected 12002 // definition. 12003 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12004 return; 12005 12006 // If we don't have a visible definition of the function, and it's inline or 12007 // a template, skip the new definition. 12008 if (SkipBody && !hasVisibleDefinition(Definition) && 12009 (Definition->getFormalLinkage() == InternalLinkage || 12010 Definition->isInlined() || 12011 Definition->getDescribedFunctionTemplate() || 12012 Definition->getNumTemplateParameterLists())) { 12013 SkipBody->ShouldSkip = true; 12014 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12015 makeMergedDefinitionVisible(TD); 12016 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12017 return; 12018 } 12019 12020 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12021 Definition->getStorageClass() == SC_Extern) 12022 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12023 << FD->getDeclName() << getLangOpts().CPlusPlus; 12024 else 12025 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12026 12027 Diag(Definition->getLocation(), diag::note_previous_definition); 12028 FD->setInvalidDecl(); 12029 } 12030 12031 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12032 Sema &S) { 12033 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12034 12035 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12036 LSI->CallOperator = CallOperator; 12037 LSI->Lambda = LambdaClass; 12038 LSI->ReturnType = CallOperator->getReturnType(); 12039 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12040 12041 if (LCD == LCD_None) 12042 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12043 else if (LCD == LCD_ByCopy) 12044 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12045 else if (LCD == LCD_ByRef) 12046 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12047 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12048 12049 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12050 LSI->Mutable = !CallOperator->isConst(); 12051 12052 // Add the captures to the LSI so they can be noted as already 12053 // captured within tryCaptureVar. 12054 auto I = LambdaClass->field_begin(); 12055 for (const auto &C : LambdaClass->captures()) { 12056 if (C.capturesVariable()) { 12057 VarDecl *VD = C.getCapturedVar(); 12058 if (VD->isInitCapture()) 12059 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12060 QualType CaptureType = VD->getType(); 12061 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12062 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12063 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12064 /*EllipsisLoc*/C.isPackExpansion() 12065 ? C.getEllipsisLoc() : SourceLocation(), 12066 CaptureType, /*Expr*/ nullptr); 12067 12068 } else if (C.capturesThis()) { 12069 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12070 /*Expr*/ nullptr, 12071 C.getCaptureKind() == LCK_StarThis); 12072 } else { 12073 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12074 } 12075 ++I; 12076 } 12077 } 12078 12079 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12080 SkipBodyInfo *SkipBody) { 12081 if (!D) 12082 return D; 12083 FunctionDecl *FD = nullptr; 12084 12085 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12086 FD = FunTmpl->getTemplatedDecl(); 12087 else 12088 FD = cast<FunctionDecl>(D); 12089 12090 // Check for defining attributes before the check for redefinition. 12091 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12092 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12093 FD->dropAttr<AliasAttr>(); 12094 FD->setInvalidDecl(); 12095 } 12096 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12097 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12098 FD->dropAttr<IFuncAttr>(); 12099 FD->setInvalidDecl(); 12100 } 12101 12102 // See if this is a redefinition. If 'will have body' is already set, then 12103 // these checks were already performed when it was set. 12104 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12105 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12106 12107 // If we're skipping the body, we're done. Don't enter the scope. 12108 if (SkipBody && SkipBody->ShouldSkip) 12109 return D; 12110 } 12111 12112 // Mark this function as "will have a body eventually". This lets users to 12113 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12114 // this function. 12115 FD->setWillHaveBody(); 12116 12117 // If we are instantiating a generic lambda call operator, push 12118 // a LambdaScopeInfo onto the function stack. But use the information 12119 // that's already been calculated (ActOnLambdaExpr) to prime the current 12120 // LambdaScopeInfo. 12121 // When the template operator is being specialized, the LambdaScopeInfo, 12122 // has to be properly restored so that tryCaptureVariable doesn't try 12123 // and capture any new variables. In addition when calculating potential 12124 // captures during transformation of nested lambdas, it is necessary to 12125 // have the LSI properly restored. 12126 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12127 assert(inTemplateInstantiation() && 12128 "There should be an active template instantiation on the stack " 12129 "when instantiating a generic lambda!"); 12130 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12131 } else { 12132 // Enter a new function scope 12133 PushFunctionScope(); 12134 } 12135 12136 // Builtin functions cannot be defined. 12137 if (unsigned BuiltinID = FD->getBuiltinID()) { 12138 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12139 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12140 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12141 FD->setInvalidDecl(); 12142 } 12143 } 12144 12145 // The return type of a function definition must be complete 12146 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12147 QualType ResultType = FD->getReturnType(); 12148 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12149 !FD->isInvalidDecl() && 12150 RequireCompleteType(FD->getLocation(), ResultType, 12151 diag::err_func_def_incomplete_result)) 12152 FD->setInvalidDecl(); 12153 12154 if (FnBodyScope) 12155 PushDeclContext(FnBodyScope, FD); 12156 12157 // Check the validity of our function parameters 12158 CheckParmsForFunctionDef(FD->parameters(), 12159 /*CheckParameterNames=*/true); 12160 12161 // Add non-parameter declarations already in the function to the current 12162 // scope. 12163 if (FnBodyScope) { 12164 for (Decl *NPD : FD->decls()) { 12165 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12166 if (!NonParmDecl) 12167 continue; 12168 assert(!isa<ParmVarDecl>(NonParmDecl) && 12169 "parameters should not be in newly created FD yet"); 12170 12171 // If the decl has a name, make it accessible in the current scope. 12172 if (NonParmDecl->getDeclName()) 12173 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12174 12175 // Similarly, dive into enums and fish their constants out, making them 12176 // accessible in this scope. 12177 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12178 for (auto *EI : ED->enumerators()) 12179 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12180 } 12181 } 12182 } 12183 12184 // Introduce our parameters into the function scope 12185 for (auto Param : FD->parameters()) { 12186 Param->setOwningFunction(FD); 12187 12188 // If this has an identifier, add it to the scope stack. 12189 if (Param->getIdentifier() && FnBodyScope) { 12190 CheckShadow(FnBodyScope, Param); 12191 12192 PushOnScopeChains(Param, FnBodyScope); 12193 } 12194 } 12195 12196 // Ensure that the function's exception specification is instantiated. 12197 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12198 ResolveExceptionSpec(D->getLocation(), FPT); 12199 12200 // dllimport cannot be applied to non-inline function definitions. 12201 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12202 !FD->isTemplateInstantiation()) { 12203 assert(!FD->hasAttr<DLLExportAttr>()); 12204 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12205 FD->setInvalidDecl(); 12206 return D; 12207 } 12208 // We want to attach documentation to original Decl (which might be 12209 // a function template). 12210 ActOnDocumentableDecl(D); 12211 if (getCurLexicalContext()->isObjCContainer() && 12212 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12213 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12214 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12215 12216 return D; 12217 } 12218 12219 /// \brief Given the set of return statements within a function body, 12220 /// compute the variables that are subject to the named return value 12221 /// optimization. 12222 /// 12223 /// Each of the variables that is subject to the named return value 12224 /// optimization will be marked as NRVO variables in the AST, and any 12225 /// return statement that has a marked NRVO variable as its NRVO candidate can 12226 /// use the named return value optimization. 12227 /// 12228 /// This function applies a very simplistic algorithm for NRVO: if every return 12229 /// statement in the scope of a variable has the same NRVO candidate, that 12230 /// candidate is an NRVO variable. 12231 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12232 ReturnStmt **Returns = Scope->Returns.data(); 12233 12234 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12235 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12236 if (!NRVOCandidate->isNRVOVariable()) 12237 Returns[I]->setNRVOCandidate(nullptr); 12238 } 12239 } 12240 } 12241 12242 bool Sema::canDelayFunctionBody(const Declarator &D) { 12243 // We can't delay parsing the body of a constexpr function template (yet). 12244 if (D.getDeclSpec().isConstexprSpecified()) 12245 return false; 12246 12247 // We can't delay parsing the body of a function template with a deduced 12248 // return type (yet). 12249 if (D.getDeclSpec().hasAutoTypeSpec()) { 12250 // If the placeholder introduces a non-deduced trailing return type, 12251 // we can still delay parsing it. 12252 if (D.getNumTypeObjects()) { 12253 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12254 if (Outer.Kind == DeclaratorChunk::Function && 12255 Outer.Fun.hasTrailingReturnType()) { 12256 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12257 return Ty.isNull() || !Ty->isUndeducedType(); 12258 } 12259 } 12260 return false; 12261 } 12262 12263 return true; 12264 } 12265 12266 bool Sema::canSkipFunctionBody(Decl *D) { 12267 // We cannot skip the body of a function (or function template) which is 12268 // constexpr, since we may need to evaluate its body in order to parse the 12269 // rest of the file. 12270 // We cannot skip the body of a function with an undeduced return type, 12271 // because any callers of that function need to know the type. 12272 if (const FunctionDecl *FD = D->getAsFunction()) 12273 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12274 return false; 12275 return Consumer.shouldSkipFunctionBody(D); 12276 } 12277 12278 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12279 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12280 FD->setHasSkippedBody(); 12281 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12282 MD->setHasSkippedBody(); 12283 return Decl; 12284 } 12285 12286 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12287 return ActOnFinishFunctionBody(D, BodyArg, false); 12288 } 12289 12290 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12291 bool IsInstantiation) { 12292 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12293 12294 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12295 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12296 12297 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12298 CheckCompletedCoroutineBody(FD, Body); 12299 12300 if (FD) { 12301 FD->setBody(Body); 12302 FD->setWillHaveBody(false); 12303 12304 if (getLangOpts().CPlusPlus14) { 12305 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12306 FD->getReturnType()->isUndeducedType()) { 12307 // If the function has a deduced result type but contains no 'return' 12308 // statements, the result type as written must be exactly 'auto', and 12309 // the deduced result type is 'void'. 12310 if (!FD->getReturnType()->getAs<AutoType>()) { 12311 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12312 << FD->getReturnType(); 12313 FD->setInvalidDecl(); 12314 } else { 12315 // Substitute 'void' for the 'auto' in the type. 12316 TypeLoc ResultType = getReturnTypeLoc(FD); 12317 Context.adjustDeducedFunctionResultType( 12318 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12319 } 12320 } 12321 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12322 // In C++11, we don't use 'auto' deduction rules for lambda call 12323 // operators because we don't support return type deduction. 12324 auto *LSI = getCurLambda(); 12325 if (LSI->HasImplicitReturnType) { 12326 deduceClosureReturnType(*LSI); 12327 12328 // C++11 [expr.prim.lambda]p4: 12329 // [...] if there are no return statements in the compound-statement 12330 // [the deduced type is] the type void 12331 QualType RetType = 12332 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12333 12334 // Update the return type to the deduced type. 12335 const FunctionProtoType *Proto = 12336 FD->getType()->getAs<FunctionProtoType>(); 12337 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12338 Proto->getExtProtoInfo())); 12339 } 12340 } 12341 12342 // If the function implicitly returns zero (like 'main') or is naked, 12343 // don't complain about missing return statements. 12344 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12345 WP.disableCheckFallThrough(); 12346 12347 // MSVC permits the use of pure specifier (=0) on function definition, 12348 // defined at class scope, warn about this non-standard construct. 12349 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12350 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12351 12352 if (!FD->isInvalidDecl()) { 12353 // Don't diagnose unused parameters of defaulted or deleted functions. 12354 if (!FD->isDeleted() && !FD->isDefaulted()) 12355 DiagnoseUnusedParameters(FD->parameters()); 12356 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12357 FD->getReturnType(), FD); 12358 12359 // If this is a structor, we need a vtable. 12360 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12361 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12362 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12363 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12364 12365 // Try to apply the named return value optimization. We have to check 12366 // if we can do this here because lambdas keep return statements around 12367 // to deduce an implicit return type. 12368 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12369 !FD->isDependentContext()) 12370 computeNRVO(Body, getCurFunction()); 12371 } 12372 12373 // GNU warning -Wmissing-prototypes: 12374 // Warn if a global function is defined without a previous 12375 // prototype declaration. This warning is issued even if the 12376 // definition itself provides a prototype. The aim is to detect 12377 // global functions that fail to be declared in header files. 12378 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12379 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12380 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12381 12382 if (PossibleZeroParamPrototype) { 12383 // We found a declaration that is not a prototype, 12384 // but that could be a zero-parameter prototype 12385 if (TypeSourceInfo *TI = 12386 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12387 TypeLoc TL = TI->getTypeLoc(); 12388 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12389 Diag(PossibleZeroParamPrototype->getLocation(), 12390 diag::note_declaration_not_a_prototype) 12391 << PossibleZeroParamPrototype 12392 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12393 } 12394 } 12395 12396 // GNU warning -Wstrict-prototypes 12397 // Warn if K&R function is defined without a previous declaration. 12398 // This warning is issued only if the definition itself does not provide 12399 // a prototype. Only K&R definitions do not provide a prototype. 12400 // An empty list in a function declarator that is part of a definition 12401 // of that function specifies that the function has no parameters 12402 // (C99 6.7.5.3p14) 12403 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12404 !LangOpts.CPlusPlus) { 12405 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12406 TypeLoc TL = TI->getTypeLoc(); 12407 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12408 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12409 } 12410 } 12411 12412 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12413 const CXXMethodDecl *KeyFunction; 12414 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12415 MD->isVirtual() && 12416 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12417 MD == KeyFunction->getCanonicalDecl()) { 12418 // Update the key-function state if necessary for this ABI. 12419 if (FD->isInlined() && 12420 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12421 Context.setNonKeyFunction(MD); 12422 12423 // If the newly-chosen key function is already defined, then we 12424 // need to mark the vtable as used retroactively. 12425 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12426 const FunctionDecl *Definition; 12427 if (KeyFunction && KeyFunction->isDefined(Definition)) 12428 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12429 } else { 12430 // We just defined they key function; mark the vtable as used. 12431 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12432 } 12433 } 12434 } 12435 12436 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12437 "Function parsing confused"); 12438 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12439 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12440 MD->setBody(Body); 12441 if (!MD->isInvalidDecl()) { 12442 DiagnoseUnusedParameters(MD->parameters()); 12443 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12444 MD->getReturnType(), MD); 12445 12446 if (Body) 12447 computeNRVO(Body, getCurFunction()); 12448 } 12449 if (getCurFunction()->ObjCShouldCallSuper) { 12450 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12451 << MD->getSelector().getAsString(); 12452 getCurFunction()->ObjCShouldCallSuper = false; 12453 } 12454 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12455 const ObjCMethodDecl *InitMethod = nullptr; 12456 bool isDesignated = 12457 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12458 assert(isDesignated && InitMethod); 12459 (void)isDesignated; 12460 12461 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12462 auto IFace = MD->getClassInterface(); 12463 if (!IFace) 12464 return false; 12465 auto SuperD = IFace->getSuperClass(); 12466 if (!SuperD) 12467 return false; 12468 return SuperD->getIdentifier() == 12469 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12470 }; 12471 // Don't issue this warning for unavailable inits or direct subclasses 12472 // of NSObject. 12473 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12474 Diag(MD->getLocation(), 12475 diag::warn_objc_designated_init_missing_super_call); 12476 Diag(InitMethod->getLocation(), 12477 diag::note_objc_designated_init_marked_here); 12478 } 12479 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12480 } 12481 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12482 // Don't issue this warning for unavaialable inits. 12483 if (!MD->isUnavailable()) 12484 Diag(MD->getLocation(), 12485 diag::warn_objc_secondary_init_missing_init_call); 12486 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12487 } 12488 } else { 12489 return nullptr; 12490 } 12491 12492 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12493 DiagnoseUnguardedAvailabilityViolations(dcl); 12494 12495 assert(!getCurFunction()->ObjCShouldCallSuper && 12496 "This should only be set for ObjC methods, which should have been " 12497 "handled in the block above."); 12498 12499 // Verify and clean out per-function state. 12500 if (Body && (!FD || !FD->isDefaulted())) { 12501 // C++ constructors that have function-try-blocks can't have return 12502 // statements in the handlers of that block. (C++ [except.handle]p14) 12503 // Verify this. 12504 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12505 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12506 12507 // Verify that gotos and switch cases don't jump into scopes illegally. 12508 if (getCurFunction()->NeedsScopeChecking() && 12509 !PP.isCodeCompletionEnabled()) 12510 DiagnoseInvalidJumps(Body); 12511 12512 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12513 if (!Destructor->getParent()->isDependentType()) 12514 CheckDestructor(Destructor); 12515 12516 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12517 Destructor->getParent()); 12518 } 12519 12520 // If any errors have occurred, clear out any temporaries that may have 12521 // been leftover. This ensures that these temporaries won't be picked up for 12522 // deletion in some later function. 12523 if (getDiagnostics().hasErrorOccurred() || 12524 getDiagnostics().getSuppressAllDiagnostics()) { 12525 DiscardCleanupsInEvaluationContext(); 12526 } 12527 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12528 !isa<FunctionTemplateDecl>(dcl)) { 12529 // Since the body is valid, issue any analysis-based warnings that are 12530 // enabled. 12531 ActivePolicy = &WP; 12532 } 12533 12534 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12535 (!CheckConstexprFunctionDecl(FD) || 12536 !CheckConstexprFunctionBody(FD, Body))) 12537 FD->setInvalidDecl(); 12538 12539 if (FD && FD->hasAttr<NakedAttr>()) { 12540 for (const Stmt *S : Body->children()) { 12541 // Allow local register variables without initializer as they don't 12542 // require prologue. 12543 bool RegisterVariables = false; 12544 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12545 for (const auto *Decl : DS->decls()) { 12546 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12547 RegisterVariables = 12548 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12549 if (!RegisterVariables) 12550 break; 12551 } 12552 } 12553 } 12554 if (RegisterVariables) 12555 continue; 12556 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12557 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12558 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12559 FD->setInvalidDecl(); 12560 break; 12561 } 12562 } 12563 } 12564 12565 assert(ExprCleanupObjects.size() == 12566 ExprEvalContexts.back().NumCleanupObjects && 12567 "Leftover temporaries in function"); 12568 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12569 assert(MaybeODRUseExprs.empty() && 12570 "Leftover expressions for odr-use checking"); 12571 } 12572 12573 if (!IsInstantiation) 12574 PopDeclContext(); 12575 12576 PopFunctionScopeInfo(ActivePolicy, dcl); 12577 // If any errors have occurred, clear out any temporaries that may have 12578 // been leftover. This ensures that these temporaries won't be picked up for 12579 // deletion in some later function. 12580 if (getDiagnostics().hasErrorOccurred()) { 12581 DiscardCleanupsInEvaluationContext(); 12582 } 12583 12584 return dcl; 12585 } 12586 12587 /// When we finish delayed parsing of an attribute, we must attach it to the 12588 /// relevant Decl. 12589 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12590 ParsedAttributes &Attrs) { 12591 // Always attach attributes to the underlying decl. 12592 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12593 D = TD->getTemplatedDecl(); 12594 ProcessDeclAttributeList(S, D, Attrs.getList()); 12595 12596 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12597 if (Method->isStatic()) 12598 checkThisInStaticMemberFunctionAttributes(Method); 12599 } 12600 12601 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12602 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12603 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12604 IdentifierInfo &II, Scope *S) { 12605 // Before we produce a declaration for an implicitly defined 12606 // function, see whether there was a locally-scoped declaration of 12607 // this name as a function or variable. If so, use that 12608 // (non-visible) declaration, and complain about it. 12609 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12610 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12611 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12612 return ExternCPrev; 12613 } 12614 12615 // Extension in C99. Legal in C90, but warn about it. 12616 unsigned diag_id; 12617 if (II.getName().startswith("__builtin_")) 12618 diag_id = diag::warn_builtin_unknown; 12619 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 12620 else if (getLangOpts().OpenCL) 12621 diag_id = diag::err_opencl_implicit_function_decl; 12622 else if (getLangOpts().C99) 12623 diag_id = diag::ext_implicit_function_decl; 12624 else 12625 diag_id = diag::warn_implicit_function_decl; 12626 Diag(Loc, diag_id) << &II; 12627 12628 // Because typo correction is expensive, only do it if the implicit 12629 // function declaration is going to be treated as an error. 12630 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12631 TypoCorrection Corrected; 12632 if (S && 12633 (Corrected = CorrectTypo( 12634 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12635 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12636 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12637 /*ErrorRecovery*/false); 12638 } 12639 12640 // Set a Declarator for the implicit definition: int foo(); 12641 const char *Dummy; 12642 AttributeFactory attrFactory; 12643 DeclSpec DS(attrFactory); 12644 unsigned DiagID; 12645 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12646 Context.getPrintingPolicy()); 12647 (void)Error; // Silence warning. 12648 assert(!Error && "Error setting up implicit decl!"); 12649 SourceLocation NoLoc; 12650 Declarator D(DS, Declarator::BlockContext); 12651 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12652 /*IsAmbiguous=*/false, 12653 /*LParenLoc=*/NoLoc, 12654 /*Params=*/nullptr, 12655 /*NumParams=*/0, 12656 /*EllipsisLoc=*/NoLoc, 12657 /*RParenLoc=*/NoLoc, 12658 /*TypeQuals=*/0, 12659 /*RefQualifierIsLvalueRef=*/true, 12660 /*RefQualifierLoc=*/NoLoc, 12661 /*ConstQualifierLoc=*/NoLoc, 12662 /*VolatileQualifierLoc=*/NoLoc, 12663 /*RestrictQualifierLoc=*/NoLoc, 12664 /*MutableLoc=*/NoLoc, 12665 EST_None, 12666 /*ESpecRange=*/SourceRange(), 12667 /*Exceptions=*/nullptr, 12668 /*ExceptionRanges=*/nullptr, 12669 /*NumExceptions=*/0, 12670 /*NoexceptExpr=*/nullptr, 12671 /*ExceptionSpecTokens=*/nullptr, 12672 /*DeclsInPrototype=*/None, 12673 Loc, Loc, D), 12674 DS.getAttributes(), 12675 SourceLocation()); 12676 D.SetIdentifier(&II, Loc); 12677 12678 // Insert this function into the enclosing block scope. 12679 while (S && !S->isCompoundStmtScope()) 12680 S = S->getParent(); 12681 if (S == nullptr) 12682 S = TUScope; 12683 12684 DeclContext *PrevDC = CurContext; 12685 CurContext = Context.getTranslationUnitDecl(); 12686 12687 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(S, D)); 12688 FD->setImplicit(); 12689 12690 CurContext = PrevDC; 12691 12692 AddKnownFunctionAttributes(FD); 12693 12694 return FD; 12695 } 12696 12697 /// \brief Adds any function attributes that we know a priori based on 12698 /// the declaration of this function. 12699 /// 12700 /// These attributes can apply both to implicitly-declared builtins 12701 /// (like __builtin___printf_chk) or to library-declared functions 12702 /// like NSLog or printf. 12703 /// 12704 /// We need to check for duplicate attributes both here and where user-written 12705 /// attributes are applied to declarations. 12706 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12707 if (FD->isInvalidDecl()) 12708 return; 12709 12710 // If this is a built-in function, map its builtin attributes to 12711 // actual attributes. 12712 if (unsigned BuiltinID = FD->getBuiltinID()) { 12713 // Handle printf-formatting attributes. 12714 unsigned FormatIdx; 12715 bool HasVAListArg; 12716 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12717 if (!FD->hasAttr<FormatAttr>()) { 12718 const char *fmt = "printf"; 12719 unsigned int NumParams = FD->getNumParams(); 12720 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12721 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12722 fmt = "NSString"; 12723 FD->addAttr(FormatAttr::CreateImplicit(Context, 12724 &Context.Idents.get(fmt), 12725 FormatIdx+1, 12726 HasVAListArg ? 0 : FormatIdx+2, 12727 FD->getLocation())); 12728 } 12729 } 12730 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12731 HasVAListArg)) { 12732 if (!FD->hasAttr<FormatAttr>()) 12733 FD->addAttr(FormatAttr::CreateImplicit(Context, 12734 &Context.Idents.get("scanf"), 12735 FormatIdx+1, 12736 HasVAListArg ? 0 : FormatIdx+2, 12737 FD->getLocation())); 12738 } 12739 12740 // Mark const if we don't care about errno and that is the only 12741 // thing preventing the function from being const. This allows 12742 // IRgen to use LLVM intrinsics for such functions. 12743 if (!getLangOpts().MathErrno && 12744 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12745 if (!FD->hasAttr<ConstAttr>()) 12746 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12747 } 12748 12749 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12750 !FD->hasAttr<ReturnsTwiceAttr>()) 12751 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12752 FD->getLocation())); 12753 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12754 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12755 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12756 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12757 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12758 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12759 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12760 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12761 // Add the appropriate attribute, depending on the CUDA compilation mode 12762 // and which target the builtin belongs to. For example, during host 12763 // compilation, aux builtins are __device__, while the rest are __host__. 12764 if (getLangOpts().CUDAIsDevice != 12765 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12766 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12767 else 12768 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12769 } 12770 } 12771 12772 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12773 // throw, add an implicit nothrow attribute to any extern "C" function we come 12774 // across. 12775 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12776 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12777 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12778 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12779 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12780 } 12781 12782 IdentifierInfo *Name = FD->getIdentifier(); 12783 if (!Name) 12784 return; 12785 if ((!getLangOpts().CPlusPlus && 12786 FD->getDeclContext()->isTranslationUnit()) || 12787 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12788 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12789 LinkageSpecDecl::lang_c)) { 12790 // Okay: this could be a libc/libm/Objective-C function we know 12791 // about. 12792 } else 12793 return; 12794 12795 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12796 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12797 // target-specific builtins, perhaps? 12798 if (!FD->hasAttr<FormatAttr>()) 12799 FD->addAttr(FormatAttr::CreateImplicit(Context, 12800 &Context.Idents.get("printf"), 2, 12801 Name->isStr("vasprintf") ? 0 : 3, 12802 FD->getLocation())); 12803 } 12804 12805 if (Name->isStr("__CFStringMakeConstantString")) { 12806 // We already have a __builtin___CFStringMakeConstantString, 12807 // but builds that use -fno-constant-cfstrings don't go through that. 12808 if (!FD->hasAttr<FormatArgAttr>()) 12809 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12810 FD->getLocation())); 12811 } 12812 } 12813 12814 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12815 TypeSourceInfo *TInfo) { 12816 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12817 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12818 12819 if (!TInfo) { 12820 assert(D.isInvalidType() && "no declarator info for valid type"); 12821 TInfo = Context.getTrivialTypeSourceInfo(T); 12822 } 12823 12824 // Scope manipulation handled by caller. 12825 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12826 D.getLocStart(), 12827 D.getIdentifierLoc(), 12828 D.getIdentifier(), 12829 TInfo); 12830 12831 // Bail out immediately if we have an invalid declaration. 12832 if (D.isInvalidType()) { 12833 NewTD->setInvalidDecl(); 12834 return NewTD; 12835 } 12836 12837 if (D.getDeclSpec().isModulePrivateSpecified()) { 12838 if (CurContext->isFunctionOrMethod()) 12839 Diag(NewTD->getLocation(), diag::err_module_private_local) 12840 << 2 << NewTD->getDeclName() 12841 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12842 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12843 else 12844 NewTD->setModulePrivate(); 12845 } 12846 12847 // C++ [dcl.typedef]p8: 12848 // If the typedef declaration defines an unnamed class (or 12849 // enum), the first typedef-name declared by the declaration 12850 // to be that class type (or enum type) is used to denote the 12851 // class type (or enum type) for linkage purposes only. 12852 // We need to check whether the type was declared in the declaration. 12853 switch (D.getDeclSpec().getTypeSpecType()) { 12854 case TST_enum: 12855 case TST_struct: 12856 case TST_interface: 12857 case TST_union: 12858 case TST_class: { 12859 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12860 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12861 break; 12862 } 12863 12864 default: 12865 break; 12866 } 12867 12868 return NewTD; 12869 } 12870 12871 /// \brief Check that this is a valid underlying type for an enum declaration. 12872 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12873 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12874 QualType T = TI->getType(); 12875 12876 if (T->isDependentType()) 12877 return false; 12878 12879 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12880 if (BT->isInteger()) 12881 return false; 12882 12883 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12884 return true; 12885 } 12886 12887 /// Check whether this is a valid redeclaration of a previous enumeration. 12888 /// \return true if the redeclaration was invalid. 12889 bool Sema::CheckEnumRedeclaration( 12890 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12891 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12892 bool IsFixed = !EnumUnderlyingTy.isNull(); 12893 12894 if (IsScoped != Prev->isScoped()) { 12895 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12896 << Prev->isScoped(); 12897 Diag(Prev->getLocation(), diag::note_previous_declaration); 12898 return true; 12899 } 12900 12901 if (IsFixed && Prev->isFixed()) { 12902 if (!EnumUnderlyingTy->isDependentType() && 12903 !Prev->getIntegerType()->isDependentType() && 12904 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12905 Prev->getIntegerType())) { 12906 // TODO: Highlight the underlying type of the redeclaration. 12907 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12908 << EnumUnderlyingTy << Prev->getIntegerType(); 12909 Diag(Prev->getLocation(), diag::note_previous_declaration) 12910 << Prev->getIntegerTypeRange(); 12911 return true; 12912 } 12913 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12914 ; 12915 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12916 ; 12917 } else if (IsFixed != Prev->isFixed()) { 12918 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12919 << Prev->isFixed(); 12920 Diag(Prev->getLocation(), diag::note_previous_declaration); 12921 return true; 12922 } 12923 12924 return false; 12925 } 12926 12927 /// \brief Get diagnostic %select index for tag kind for 12928 /// redeclaration diagnostic message. 12929 /// WARNING: Indexes apply to particular diagnostics only! 12930 /// 12931 /// \returns diagnostic %select index. 12932 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12933 switch (Tag) { 12934 case TTK_Struct: return 0; 12935 case TTK_Interface: return 1; 12936 case TTK_Class: return 2; 12937 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12938 } 12939 } 12940 12941 /// \brief Determine if tag kind is a class-key compatible with 12942 /// class for redeclaration (class, struct, or __interface). 12943 /// 12944 /// \returns true iff the tag kind is compatible. 12945 static bool isClassCompatTagKind(TagTypeKind Tag) 12946 { 12947 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12948 } 12949 12950 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12951 TagTypeKind TTK) { 12952 if (isa<TypedefDecl>(PrevDecl)) 12953 return NTK_Typedef; 12954 else if (isa<TypeAliasDecl>(PrevDecl)) 12955 return NTK_TypeAlias; 12956 else if (isa<ClassTemplateDecl>(PrevDecl)) 12957 return NTK_Template; 12958 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12959 return NTK_TypeAliasTemplate; 12960 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12961 return NTK_TemplateTemplateArgument; 12962 switch (TTK) { 12963 case TTK_Struct: 12964 case TTK_Interface: 12965 case TTK_Class: 12966 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12967 case TTK_Union: 12968 return NTK_NonUnion; 12969 case TTK_Enum: 12970 return NTK_NonEnum; 12971 } 12972 llvm_unreachable("invalid TTK"); 12973 } 12974 12975 /// \brief Determine whether a tag with a given kind is acceptable 12976 /// as a redeclaration of the given tag declaration. 12977 /// 12978 /// \returns true if the new tag kind is acceptable, false otherwise. 12979 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12980 TagTypeKind NewTag, bool isDefinition, 12981 SourceLocation NewTagLoc, 12982 const IdentifierInfo *Name) { 12983 // C++ [dcl.type.elab]p3: 12984 // The class-key or enum keyword present in the 12985 // elaborated-type-specifier shall agree in kind with the 12986 // declaration to which the name in the elaborated-type-specifier 12987 // refers. This rule also applies to the form of 12988 // elaborated-type-specifier that declares a class-name or 12989 // friend class since it can be construed as referring to the 12990 // definition of the class. Thus, in any 12991 // elaborated-type-specifier, the enum keyword shall be used to 12992 // refer to an enumeration (7.2), the union class-key shall be 12993 // used to refer to a union (clause 9), and either the class or 12994 // struct class-key shall be used to refer to a class (clause 9) 12995 // declared using the class or struct class-key. 12996 TagTypeKind OldTag = Previous->getTagKind(); 12997 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12998 if (OldTag == NewTag) 12999 return true; 13000 13001 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13002 // Warn about the struct/class tag mismatch. 13003 bool isTemplate = false; 13004 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13005 isTemplate = Record->getDescribedClassTemplate(); 13006 13007 if (inTemplateInstantiation()) { 13008 // In a template instantiation, do not offer fix-its for tag mismatches 13009 // since they usually mess up the template instead of fixing the problem. 13010 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13011 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13012 << getRedeclDiagFromTagKind(OldTag); 13013 return true; 13014 } 13015 13016 if (isDefinition) { 13017 // On definitions, check previous tags and issue a fix-it for each 13018 // one that doesn't match the current tag. 13019 if (Previous->getDefinition()) { 13020 // Don't suggest fix-its for redefinitions. 13021 return true; 13022 } 13023 13024 bool previousMismatch = false; 13025 for (auto I : Previous->redecls()) { 13026 if (I->getTagKind() != NewTag) { 13027 if (!previousMismatch) { 13028 previousMismatch = true; 13029 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13030 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13031 << getRedeclDiagFromTagKind(I->getTagKind()); 13032 } 13033 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13034 << getRedeclDiagFromTagKind(NewTag) 13035 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13036 TypeWithKeyword::getTagTypeKindName(NewTag)); 13037 } 13038 } 13039 return true; 13040 } 13041 13042 // Check for a previous definition. If current tag and definition 13043 // are same type, do nothing. If no definition, but disagree with 13044 // with previous tag type, give a warning, but no fix-it. 13045 const TagDecl *Redecl = Previous->getDefinition() ? 13046 Previous->getDefinition() : Previous; 13047 if (Redecl->getTagKind() == NewTag) { 13048 return true; 13049 } 13050 13051 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13052 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13053 << getRedeclDiagFromTagKind(OldTag); 13054 Diag(Redecl->getLocation(), diag::note_previous_use); 13055 13056 // If there is a previous definition, suggest a fix-it. 13057 if (Previous->getDefinition()) { 13058 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13059 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13060 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13061 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13062 } 13063 13064 return true; 13065 } 13066 return false; 13067 } 13068 13069 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13070 /// from an outer enclosing namespace or file scope inside a friend declaration. 13071 /// This should provide the commented out code in the following snippet: 13072 /// namespace N { 13073 /// struct X; 13074 /// namespace M { 13075 /// struct Y { friend struct /*N::*/ X; }; 13076 /// } 13077 /// } 13078 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13079 SourceLocation NameLoc) { 13080 // While the decl is in a namespace, do repeated lookup of that name and see 13081 // if we get the same namespace back. If we do not, continue until 13082 // translation unit scope, at which point we have a fully qualified NNS. 13083 SmallVector<IdentifierInfo *, 4> Namespaces; 13084 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13085 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13086 // This tag should be declared in a namespace, which can only be enclosed by 13087 // other namespaces. Bail if there's an anonymous namespace in the chain. 13088 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13089 if (!Namespace || Namespace->isAnonymousNamespace()) 13090 return FixItHint(); 13091 IdentifierInfo *II = Namespace->getIdentifier(); 13092 Namespaces.push_back(II); 13093 NamedDecl *Lookup = SemaRef.LookupSingleName( 13094 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13095 if (Lookup == Namespace) 13096 break; 13097 } 13098 13099 // Once we have all the namespaces, reverse them to go outermost first, and 13100 // build an NNS. 13101 SmallString<64> Insertion; 13102 llvm::raw_svector_ostream OS(Insertion); 13103 if (DC->isTranslationUnit()) 13104 OS << "::"; 13105 std::reverse(Namespaces.begin(), Namespaces.end()); 13106 for (auto *II : Namespaces) 13107 OS << II->getName() << "::"; 13108 return FixItHint::CreateInsertion(NameLoc, Insertion); 13109 } 13110 13111 /// \brief Determine whether a tag originally declared in context \p OldDC can 13112 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13113 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13114 /// using-declaration). 13115 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13116 DeclContext *NewDC) { 13117 OldDC = OldDC->getRedeclContext(); 13118 NewDC = NewDC->getRedeclContext(); 13119 13120 if (OldDC->Equals(NewDC)) 13121 return true; 13122 13123 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13124 // encloses the other). 13125 if (S.getLangOpts().MSVCCompat && 13126 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13127 return true; 13128 13129 return false; 13130 } 13131 13132 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13133 /// former case, Name will be non-null. In the later case, Name will be null. 13134 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13135 /// reference/declaration/definition of a tag. 13136 /// 13137 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13138 /// trailing-type-specifier) other than one in an alias-declaration. 13139 /// 13140 /// \param SkipBody If non-null, will be set to indicate if the caller should 13141 /// skip the definition of this tag and treat it as if it were a declaration. 13142 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13143 SourceLocation KWLoc, CXXScopeSpec &SS, 13144 IdentifierInfo *Name, SourceLocation NameLoc, 13145 AttributeList *Attr, AccessSpecifier AS, 13146 SourceLocation ModulePrivateLoc, 13147 MultiTemplateParamsArg TemplateParameterLists, 13148 bool &OwnedDecl, bool &IsDependent, 13149 SourceLocation ScopedEnumKWLoc, 13150 bool ScopedEnumUsesClassTag, 13151 TypeResult UnderlyingType, 13152 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13153 SkipBodyInfo *SkipBody) { 13154 // If this is not a definition, it must have a name. 13155 IdentifierInfo *OrigName = Name; 13156 assert((Name != nullptr || TUK == TUK_Definition) && 13157 "Nameless record must be a definition!"); 13158 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13159 13160 OwnedDecl = false; 13161 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13162 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13163 13164 // FIXME: Check member specializations more carefully. 13165 bool isMemberSpecialization = false; 13166 bool Invalid = false; 13167 13168 // We only need to do this matching if we have template parameters 13169 // or a scope specifier, which also conveniently avoids this work 13170 // for non-C++ cases. 13171 if (TemplateParameterLists.size() > 0 || 13172 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13173 if (TemplateParameterList *TemplateParams = 13174 MatchTemplateParametersToScopeSpecifier( 13175 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13176 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13177 if (Kind == TTK_Enum) { 13178 Diag(KWLoc, diag::err_enum_template); 13179 return nullptr; 13180 } 13181 13182 if (TemplateParams->size() > 0) { 13183 // This is a declaration or definition of a class template (which may 13184 // be a member of another template). 13185 13186 if (Invalid) 13187 return nullptr; 13188 13189 OwnedDecl = false; 13190 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13191 SS, Name, NameLoc, Attr, 13192 TemplateParams, AS, 13193 ModulePrivateLoc, 13194 /*FriendLoc*/SourceLocation(), 13195 TemplateParameterLists.size()-1, 13196 TemplateParameterLists.data(), 13197 SkipBody); 13198 return Result.get(); 13199 } else { 13200 // The "template<>" header is extraneous. 13201 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13202 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13203 isMemberSpecialization = true; 13204 } 13205 } 13206 } 13207 13208 // Figure out the underlying type if this a enum declaration. We need to do 13209 // this early, because it's needed to detect if this is an incompatible 13210 // redeclaration. 13211 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13212 bool EnumUnderlyingIsImplicit = false; 13213 13214 if (Kind == TTK_Enum) { 13215 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13216 // No underlying type explicitly specified, or we failed to parse the 13217 // type, default to int. 13218 EnumUnderlying = Context.IntTy.getTypePtr(); 13219 else if (UnderlyingType.get()) { 13220 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13221 // integral type; any cv-qualification is ignored. 13222 TypeSourceInfo *TI = nullptr; 13223 GetTypeFromParser(UnderlyingType.get(), &TI); 13224 EnumUnderlying = TI; 13225 13226 if (CheckEnumUnderlyingType(TI)) 13227 // Recover by falling back to int. 13228 EnumUnderlying = Context.IntTy.getTypePtr(); 13229 13230 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13231 UPPC_FixedUnderlyingType)) 13232 EnumUnderlying = Context.IntTy.getTypePtr(); 13233 13234 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13235 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13236 // Microsoft enums are always of int type. 13237 EnumUnderlying = Context.IntTy.getTypePtr(); 13238 EnumUnderlyingIsImplicit = true; 13239 } 13240 } 13241 } 13242 13243 DeclContext *SearchDC = CurContext; 13244 DeclContext *DC = CurContext; 13245 bool isStdBadAlloc = false; 13246 bool isStdAlignValT = false; 13247 13248 RedeclarationKind Redecl = ForRedeclaration; 13249 if (TUK == TUK_Friend || TUK == TUK_Reference) 13250 Redecl = NotForRedeclaration; 13251 13252 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13253 /// implemented asks for structural equivalence checking, the returned decl 13254 /// here is passed back to the parser, allowing the tag body to be parsed. 13255 auto createTagFromNewDecl = [&]() -> TagDecl * { 13256 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13257 // If there is an identifier, use the location of the identifier as the 13258 // location of the decl, otherwise use the location of the struct/union 13259 // keyword. 13260 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13261 TagDecl *New = nullptr; 13262 13263 if (Kind == TTK_Enum) { 13264 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13265 ScopedEnum, ScopedEnumUsesClassTag, 13266 !EnumUnderlying.isNull()); 13267 // If this is an undefined enum, bail. 13268 if (TUK != TUK_Definition && !Invalid) 13269 return nullptr; 13270 if (EnumUnderlying) { 13271 EnumDecl *ED = cast<EnumDecl>(New); 13272 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13273 ED->setIntegerTypeSourceInfo(TI); 13274 else 13275 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13276 ED->setPromotionType(ED->getIntegerType()); 13277 } 13278 } else { // struct/union 13279 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13280 nullptr); 13281 } 13282 13283 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13284 // Add alignment attributes if necessary; these attributes are checked 13285 // when the ASTContext lays out the structure. 13286 // 13287 // It is important for implementing the correct semantics that this 13288 // happen here (in ActOnTag). The #pragma pack stack is 13289 // maintained as a result of parser callbacks which can occur at 13290 // many points during the parsing of a struct declaration (because 13291 // the #pragma tokens are effectively skipped over during the 13292 // parsing of the struct). 13293 if (TUK == TUK_Definition) { 13294 AddAlignmentAttributesForRecord(RD); 13295 AddMsStructLayoutForRecord(RD); 13296 } 13297 } 13298 New->setLexicalDeclContext(CurContext); 13299 return New; 13300 }; 13301 13302 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13303 if (Name && SS.isNotEmpty()) { 13304 // We have a nested-name tag ('struct foo::bar'). 13305 13306 // Check for invalid 'foo::'. 13307 if (SS.isInvalid()) { 13308 Name = nullptr; 13309 goto CreateNewDecl; 13310 } 13311 13312 // If this is a friend or a reference to a class in a dependent 13313 // context, don't try to make a decl for it. 13314 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13315 DC = computeDeclContext(SS, false); 13316 if (!DC) { 13317 IsDependent = true; 13318 return nullptr; 13319 } 13320 } else { 13321 DC = computeDeclContext(SS, true); 13322 if (!DC) { 13323 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13324 << SS.getRange(); 13325 return nullptr; 13326 } 13327 } 13328 13329 if (RequireCompleteDeclContext(SS, DC)) 13330 return nullptr; 13331 13332 SearchDC = DC; 13333 // Look-up name inside 'foo::'. 13334 LookupQualifiedName(Previous, DC); 13335 13336 if (Previous.isAmbiguous()) 13337 return nullptr; 13338 13339 if (Previous.empty()) { 13340 // Name lookup did not find anything. However, if the 13341 // nested-name-specifier refers to the current instantiation, 13342 // and that current instantiation has any dependent base 13343 // classes, we might find something at instantiation time: treat 13344 // this as a dependent elaborated-type-specifier. 13345 // But this only makes any sense for reference-like lookups. 13346 if (Previous.wasNotFoundInCurrentInstantiation() && 13347 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13348 IsDependent = true; 13349 return nullptr; 13350 } 13351 13352 // A tag 'foo::bar' must already exist. 13353 Diag(NameLoc, diag::err_not_tag_in_scope) 13354 << Kind << Name << DC << SS.getRange(); 13355 Name = nullptr; 13356 Invalid = true; 13357 goto CreateNewDecl; 13358 } 13359 } else if (Name) { 13360 // C++14 [class.mem]p14: 13361 // If T is the name of a class, then each of the following shall have a 13362 // name different from T: 13363 // -- every member of class T that is itself a type 13364 if (TUK != TUK_Reference && TUK != TUK_Friend && 13365 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13366 return nullptr; 13367 13368 // If this is a named struct, check to see if there was a previous forward 13369 // declaration or definition. 13370 // FIXME: We're looking into outer scopes here, even when we 13371 // shouldn't be. Doing so can result in ambiguities that we 13372 // shouldn't be diagnosing. 13373 LookupName(Previous, S); 13374 13375 // When declaring or defining a tag, ignore ambiguities introduced 13376 // by types using'ed into this scope. 13377 if (Previous.isAmbiguous() && 13378 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13379 LookupResult::Filter F = Previous.makeFilter(); 13380 while (F.hasNext()) { 13381 NamedDecl *ND = F.next(); 13382 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13383 SearchDC->getRedeclContext())) 13384 F.erase(); 13385 } 13386 F.done(); 13387 } 13388 13389 // C++11 [namespace.memdef]p3: 13390 // If the name in a friend declaration is neither qualified nor 13391 // a template-id and the declaration is a function or an 13392 // elaborated-type-specifier, the lookup to determine whether 13393 // the entity has been previously declared shall not consider 13394 // any scopes outside the innermost enclosing namespace. 13395 // 13396 // MSVC doesn't implement the above rule for types, so a friend tag 13397 // declaration may be a redeclaration of a type declared in an enclosing 13398 // scope. They do implement this rule for friend functions. 13399 // 13400 // Does it matter that this should be by scope instead of by 13401 // semantic context? 13402 if (!Previous.empty() && TUK == TUK_Friend) { 13403 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13404 LookupResult::Filter F = Previous.makeFilter(); 13405 bool FriendSawTagOutsideEnclosingNamespace = false; 13406 while (F.hasNext()) { 13407 NamedDecl *ND = F.next(); 13408 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13409 if (DC->isFileContext() && 13410 !EnclosingNS->Encloses(ND->getDeclContext())) { 13411 if (getLangOpts().MSVCCompat) 13412 FriendSawTagOutsideEnclosingNamespace = true; 13413 else 13414 F.erase(); 13415 } 13416 } 13417 F.done(); 13418 13419 // Diagnose this MSVC extension in the easy case where lookup would have 13420 // unambiguously found something outside the enclosing namespace. 13421 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13422 NamedDecl *ND = Previous.getFoundDecl(); 13423 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13424 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13425 } 13426 } 13427 13428 // Note: there used to be some attempt at recovery here. 13429 if (Previous.isAmbiguous()) 13430 return nullptr; 13431 13432 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13433 // FIXME: This makes sure that we ignore the contexts associated 13434 // with C structs, unions, and enums when looking for a matching 13435 // tag declaration or definition. See the similar lookup tweak 13436 // in Sema::LookupName; is there a better way to deal with this? 13437 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13438 SearchDC = SearchDC->getParent(); 13439 } 13440 } 13441 13442 if (Previous.isSingleResult() && 13443 Previous.getFoundDecl()->isTemplateParameter()) { 13444 // Maybe we will complain about the shadowed template parameter. 13445 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13446 // Just pretend that we didn't see the previous declaration. 13447 Previous.clear(); 13448 } 13449 13450 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13451 DC->Equals(getStdNamespace())) { 13452 if (Name->isStr("bad_alloc")) { 13453 // This is a declaration of or a reference to "std::bad_alloc". 13454 isStdBadAlloc = true; 13455 13456 // If std::bad_alloc has been implicitly declared (but made invisible to 13457 // name lookup), fill in this implicit declaration as the previous 13458 // declaration, so that the declarations get chained appropriately. 13459 if (Previous.empty() && StdBadAlloc) 13460 Previous.addDecl(getStdBadAlloc()); 13461 } else if (Name->isStr("align_val_t")) { 13462 isStdAlignValT = true; 13463 if (Previous.empty() && StdAlignValT) 13464 Previous.addDecl(getStdAlignValT()); 13465 } 13466 } 13467 13468 // If we didn't find a previous declaration, and this is a reference 13469 // (or friend reference), move to the correct scope. In C++, we 13470 // also need to do a redeclaration lookup there, just in case 13471 // there's a shadow friend decl. 13472 if (Name && Previous.empty() && 13473 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13474 if (Invalid) goto CreateNewDecl; 13475 assert(SS.isEmpty()); 13476 13477 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13478 // C++ [basic.scope.pdecl]p5: 13479 // -- for an elaborated-type-specifier of the form 13480 // 13481 // class-key identifier 13482 // 13483 // if the elaborated-type-specifier is used in the 13484 // decl-specifier-seq or parameter-declaration-clause of a 13485 // function defined in namespace scope, the identifier is 13486 // declared as a class-name in the namespace that contains 13487 // the declaration; otherwise, except as a friend 13488 // declaration, the identifier is declared in the smallest 13489 // non-class, non-function-prototype scope that contains the 13490 // declaration. 13491 // 13492 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13493 // C structs and unions. 13494 // 13495 // It is an error in C++ to declare (rather than define) an enum 13496 // type, including via an elaborated type specifier. We'll 13497 // diagnose that later; for now, declare the enum in the same 13498 // scope as we would have picked for any other tag type. 13499 // 13500 // GNU C also supports this behavior as part of its incomplete 13501 // enum types extension, while GNU C++ does not. 13502 // 13503 // Find the context where we'll be declaring the tag. 13504 // FIXME: We would like to maintain the current DeclContext as the 13505 // lexical context, 13506 SearchDC = getTagInjectionContext(SearchDC); 13507 13508 // Find the scope where we'll be declaring the tag. 13509 S = getTagInjectionScope(S, getLangOpts()); 13510 } else { 13511 assert(TUK == TUK_Friend); 13512 // C++ [namespace.memdef]p3: 13513 // If a friend declaration in a non-local class first declares a 13514 // class or function, the friend class or function is a member of 13515 // the innermost enclosing namespace. 13516 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13517 } 13518 13519 // In C++, we need to do a redeclaration lookup to properly 13520 // diagnose some problems. 13521 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13522 // hidden declaration so that we don't get ambiguity errors when using a 13523 // type declared by an elaborated-type-specifier. In C that is not correct 13524 // and we should instead merge compatible types found by lookup. 13525 if (getLangOpts().CPlusPlus) { 13526 Previous.setRedeclarationKind(ForRedeclaration); 13527 LookupQualifiedName(Previous, SearchDC); 13528 } else { 13529 Previous.setRedeclarationKind(ForRedeclaration); 13530 LookupName(Previous, S); 13531 } 13532 } 13533 13534 // If we have a known previous declaration to use, then use it. 13535 if (Previous.empty() && SkipBody && SkipBody->Previous) 13536 Previous.addDecl(SkipBody->Previous); 13537 13538 if (!Previous.empty()) { 13539 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13540 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13541 13542 // It's okay to have a tag decl in the same scope as a typedef 13543 // which hides a tag decl in the same scope. Finding this 13544 // insanity with a redeclaration lookup can only actually happen 13545 // in C++. 13546 // 13547 // This is also okay for elaborated-type-specifiers, which is 13548 // technically forbidden by the current standard but which is 13549 // okay according to the likely resolution of an open issue; 13550 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13551 if (getLangOpts().CPlusPlus) { 13552 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13553 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13554 TagDecl *Tag = TT->getDecl(); 13555 if (Tag->getDeclName() == Name && 13556 Tag->getDeclContext()->getRedeclContext() 13557 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13558 PrevDecl = Tag; 13559 Previous.clear(); 13560 Previous.addDecl(Tag); 13561 Previous.resolveKind(); 13562 } 13563 } 13564 } 13565 } 13566 13567 // If this is a redeclaration of a using shadow declaration, it must 13568 // declare a tag in the same context. In MSVC mode, we allow a 13569 // redefinition if either context is within the other. 13570 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13571 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13572 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13573 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13574 !(OldTag && isAcceptableTagRedeclContext( 13575 *this, OldTag->getDeclContext(), SearchDC))) { 13576 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13577 Diag(Shadow->getTargetDecl()->getLocation(), 13578 diag::note_using_decl_target); 13579 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13580 << 0; 13581 // Recover by ignoring the old declaration. 13582 Previous.clear(); 13583 goto CreateNewDecl; 13584 } 13585 } 13586 13587 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13588 // If this is a use of a previous tag, or if the tag is already declared 13589 // in the same scope (so that the definition/declaration completes or 13590 // rementions the tag), reuse the decl. 13591 if (TUK == TUK_Reference || TUK == TUK_Friend || 13592 isDeclInScope(DirectPrevDecl, SearchDC, S, 13593 SS.isNotEmpty() || isMemberSpecialization)) { 13594 // Make sure that this wasn't declared as an enum and now used as a 13595 // struct or something similar. 13596 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13597 TUK == TUK_Definition, KWLoc, 13598 Name)) { 13599 bool SafeToContinue 13600 = (PrevTagDecl->getTagKind() != TTK_Enum && 13601 Kind != TTK_Enum); 13602 if (SafeToContinue) 13603 Diag(KWLoc, diag::err_use_with_wrong_tag) 13604 << Name 13605 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13606 PrevTagDecl->getKindName()); 13607 else 13608 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13609 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13610 13611 if (SafeToContinue) 13612 Kind = PrevTagDecl->getTagKind(); 13613 else { 13614 // Recover by making this an anonymous redefinition. 13615 Name = nullptr; 13616 Previous.clear(); 13617 Invalid = true; 13618 } 13619 } 13620 13621 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13622 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13623 13624 // If this is an elaborated-type-specifier for a scoped enumeration, 13625 // the 'class' keyword is not necessary and not permitted. 13626 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13627 if (ScopedEnum) 13628 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13629 << PrevEnum->isScoped() 13630 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13631 return PrevTagDecl; 13632 } 13633 13634 QualType EnumUnderlyingTy; 13635 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13636 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13637 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13638 EnumUnderlyingTy = QualType(T, 0); 13639 13640 // All conflicts with previous declarations are recovered by 13641 // returning the previous declaration, unless this is a definition, 13642 // in which case we want the caller to bail out. 13643 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13644 ScopedEnum, EnumUnderlyingTy, 13645 EnumUnderlyingIsImplicit, PrevEnum)) 13646 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13647 } 13648 13649 // C++11 [class.mem]p1: 13650 // A member shall not be declared twice in the member-specification, 13651 // except that a nested class or member class template can be declared 13652 // and then later defined. 13653 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13654 S->isDeclScope(PrevDecl)) { 13655 Diag(NameLoc, diag::ext_member_redeclared); 13656 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13657 } 13658 13659 if (!Invalid) { 13660 // If this is a use, just return the declaration we found, unless 13661 // we have attributes. 13662 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13663 if (Attr) { 13664 // FIXME: Diagnose these attributes. For now, we create a new 13665 // declaration to hold them. 13666 } else if (TUK == TUK_Reference && 13667 (PrevTagDecl->getFriendObjectKind() == 13668 Decl::FOK_Undeclared || 13669 PrevDecl->getOwningModule() != getCurrentModule()) && 13670 SS.isEmpty()) { 13671 // This declaration is a reference to an existing entity, but 13672 // has different visibility from that entity: it either makes 13673 // a friend visible or it makes a type visible in a new module. 13674 // In either case, create a new declaration. We only do this if 13675 // the declaration would have meant the same thing if no prior 13676 // declaration were found, that is, if it was found in the same 13677 // scope where we would have injected a declaration. 13678 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13679 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13680 return PrevTagDecl; 13681 // This is in the injected scope, create a new declaration in 13682 // that scope. 13683 S = getTagInjectionScope(S, getLangOpts()); 13684 } else { 13685 return PrevTagDecl; 13686 } 13687 } 13688 13689 // Diagnose attempts to redefine a tag. 13690 if (TUK == TUK_Definition) { 13691 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13692 // If we're defining a specialization and the previous definition 13693 // is from an implicit instantiation, don't emit an error 13694 // here; we'll catch this in the general case below. 13695 bool IsExplicitSpecializationAfterInstantiation = false; 13696 if (isMemberSpecialization) { 13697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13698 IsExplicitSpecializationAfterInstantiation = 13699 RD->getTemplateSpecializationKind() != 13700 TSK_ExplicitSpecialization; 13701 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13702 IsExplicitSpecializationAfterInstantiation = 13703 ED->getTemplateSpecializationKind() != 13704 TSK_ExplicitSpecialization; 13705 } 13706 13707 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 13708 // not keep more that one definition around (merge them). However, 13709 // ensure the decl passes the structural compatibility check in 13710 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 13711 NamedDecl *Hidden = nullptr; 13712 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 13713 // There is a definition of this tag, but it is not visible. We 13714 // explicitly make use of C++'s one definition rule here, and 13715 // assume that this definition is identical to the hidden one 13716 // we already have. Make the existing definition visible and 13717 // use it in place of this one. 13718 if (!getLangOpts().CPlusPlus) { 13719 // Postpone making the old definition visible until after we 13720 // complete parsing the new one and do the structural 13721 // comparison. 13722 SkipBody->CheckSameAsPrevious = true; 13723 SkipBody->New = createTagFromNewDecl(); 13724 SkipBody->Previous = Hidden; 13725 } else { 13726 SkipBody->ShouldSkip = true; 13727 makeMergedDefinitionVisible(Hidden); 13728 } 13729 return Def; 13730 } else if (!IsExplicitSpecializationAfterInstantiation) { 13731 // A redeclaration in function prototype scope in C isn't 13732 // visible elsewhere, so merely issue a warning. 13733 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13734 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13735 else 13736 Diag(NameLoc, diag::err_redefinition) << Name; 13737 notePreviousDefinition(Def, 13738 NameLoc.isValid() ? NameLoc : KWLoc); 13739 // If this is a redefinition, recover by making this 13740 // struct be anonymous, which will make any later 13741 // references get the previous definition. 13742 Name = nullptr; 13743 Previous.clear(); 13744 Invalid = true; 13745 } 13746 } else { 13747 // If the type is currently being defined, complain 13748 // about a nested redefinition. 13749 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13750 if (TD->isBeingDefined()) { 13751 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13752 Diag(PrevTagDecl->getLocation(), 13753 diag::note_previous_definition); 13754 Name = nullptr; 13755 Previous.clear(); 13756 Invalid = true; 13757 } 13758 } 13759 13760 // Okay, this is definition of a previously declared or referenced 13761 // tag. We're going to create a new Decl for it. 13762 } 13763 13764 // Okay, we're going to make a redeclaration. If this is some kind 13765 // of reference, make sure we build the redeclaration in the same DC 13766 // as the original, and ignore the current access specifier. 13767 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13768 SearchDC = PrevTagDecl->getDeclContext(); 13769 AS = AS_none; 13770 } 13771 } 13772 // If we get here we have (another) forward declaration or we 13773 // have a definition. Just create a new decl. 13774 13775 } else { 13776 // If we get here, this is a definition of a new tag type in a nested 13777 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13778 // new decl/type. We set PrevDecl to NULL so that the entities 13779 // have distinct types. 13780 Previous.clear(); 13781 } 13782 // If we get here, we're going to create a new Decl. If PrevDecl 13783 // is non-NULL, it's a definition of the tag declared by 13784 // PrevDecl. If it's NULL, we have a new definition. 13785 13786 // Otherwise, PrevDecl is not a tag, but was found with tag 13787 // lookup. This is only actually possible in C++, where a few 13788 // things like templates still live in the tag namespace. 13789 } else { 13790 // Use a better diagnostic if an elaborated-type-specifier 13791 // found the wrong kind of type on the first 13792 // (non-redeclaration) lookup. 13793 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13794 !Previous.isForRedeclaration()) { 13795 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13796 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13797 << Kind; 13798 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13799 Invalid = true; 13800 13801 // Otherwise, only diagnose if the declaration is in scope. 13802 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13803 SS.isNotEmpty() || isMemberSpecialization)) { 13804 // do nothing 13805 13806 // Diagnose implicit declarations introduced by elaborated types. 13807 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13808 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13809 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13810 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13811 Invalid = true; 13812 13813 // Otherwise it's a declaration. Call out a particularly common 13814 // case here. 13815 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13816 unsigned Kind = 0; 13817 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13818 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13819 << Name << Kind << TND->getUnderlyingType(); 13820 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13821 Invalid = true; 13822 13823 // Otherwise, diagnose. 13824 } else { 13825 // The tag name clashes with something else in the target scope, 13826 // issue an error and recover by making this tag be anonymous. 13827 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13828 notePreviousDefinition(PrevDecl, NameLoc); 13829 Name = nullptr; 13830 Invalid = true; 13831 } 13832 13833 // The existing declaration isn't relevant to us; we're in a 13834 // new scope, so clear out the previous declaration. 13835 Previous.clear(); 13836 } 13837 } 13838 13839 CreateNewDecl: 13840 13841 TagDecl *PrevDecl = nullptr; 13842 if (Previous.isSingleResult()) 13843 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13844 13845 // If there is an identifier, use the location of the identifier as the 13846 // location of the decl, otherwise use the location of the struct/union 13847 // keyword. 13848 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13849 13850 // Otherwise, create a new declaration. If there is a previous 13851 // declaration of the same entity, the two will be linked via 13852 // PrevDecl. 13853 TagDecl *New; 13854 13855 bool IsForwardReference = false; 13856 if (Kind == TTK_Enum) { 13857 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13858 // enum X { A, B, C } D; D should chain to X. 13859 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13860 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13861 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13862 13863 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13864 StdAlignValT = cast<EnumDecl>(New); 13865 13866 // If this is an undefined enum, warn. 13867 if (TUK != TUK_Definition && !Invalid) { 13868 TagDecl *Def; 13869 if (!EnumUnderlyingIsImplicit && 13870 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13871 cast<EnumDecl>(New)->isFixed()) { 13872 // C++0x: 7.2p2: opaque-enum-declaration. 13873 // Conflicts are diagnosed above. Do nothing. 13874 } 13875 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13876 Diag(Loc, diag::ext_forward_ref_enum_def) 13877 << New; 13878 Diag(Def->getLocation(), diag::note_previous_definition); 13879 } else { 13880 unsigned DiagID = diag::ext_forward_ref_enum; 13881 if (getLangOpts().MSVCCompat) 13882 DiagID = diag::ext_ms_forward_ref_enum; 13883 else if (getLangOpts().CPlusPlus) 13884 DiagID = diag::err_forward_ref_enum; 13885 Diag(Loc, DiagID); 13886 13887 // If this is a forward-declared reference to an enumeration, make a 13888 // note of it; we won't actually be introducing the declaration into 13889 // the declaration context. 13890 if (TUK == TUK_Reference) 13891 IsForwardReference = true; 13892 } 13893 } 13894 13895 if (EnumUnderlying) { 13896 EnumDecl *ED = cast<EnumDecl>(New); 13897 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13898 ED->setIntegerTypeSourceInfo(TI); 13899 else 13900 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13901 ED->setPromotionType(ED->getIntegerType()); 13902 } 13903 } else { 13904 // struct/union/class 13905 13906 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13907 // struct X { int A; } D; D should chain to X. 13908 if (getLangOpts().CPlusPlus) { 13909 // FIXME: Look for a way to use RecordDecl for simple structs. 13910 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13911 cast_or_null<CXXRecordDecl>(PrevDecl)); 13912 13913 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13914 StdBadAlloc = cast<CXXRecordDecl>(New); 13915 } else 13916 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13917 cast_or_null<RecordDecl>(PrevDecl)); 13918 } 13919 13920 // C++11 [dcl.type]p3: 13921 // A type-specifier-seq shall not define a class or enumeration [...]. 13922 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 13923 TUK == TUK_Definition) { 13924 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13925 << Context.getTagDeclType(New); 13926 Invalid = true; 13927 } 13928 13929 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 13930 DC->getDeclKind() == Decl::Enum) { 13931 Diag(New->getLocation(), diag::err_type_defined_in_enum) 13932 << Context.getTagDeclType(New); 13933 Invalid = true; 13934 } 13935 13936 // Maybe add qualifier info. 13937 if (SS.isNotEmpty()) { 13938 if (SS.isSet()) { 13939 // If this is either a declaration or a definition, check the 13940 // nested-name-specifier against the current context. We don't do this 13941 // for explicit specializations, because they have similar checking 13942 // (with more specific diagnostics) in the call to 13943 // CheckMemberSpecialization, below. 13944 if (!isMemberSpecialization && 13945 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13946 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13947 Invalid = true; 13948 13949 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13950 if (TemplateParameterLists.size() > 0) { 13951 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13952 } 13953 } 13954 else 13955 Invalid = true; 13956 } 13957 13958 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13959 // Add alignment attributes if necessary; these attributes are checked when 13960 // the ASTContext lays out the structure. 13961 // 13962 // It is important for implementing the correct semantics that this 13963 // happen here (in ActOnTag). The #pragma pack stack is 13964 // maintained as a result of parser callbacks which can occur at 13965 // many points during the parsing of a struct declaration (because 13966 // the #pragma tokens are effectively skipped over during the 13967 // parsing of the struct). 13968 if (TUK == TUK_Definition) { 13969 AddAlignmentAttributesForRecord(RD); 13970 AddMsStructLayoutForRecord(RD); 13971 } 13972 } 13973 13974 if (ModulePrivateLoc.isValid()) { 13975 if (isMemberSpecialization) 13976 Diag(New->getLocation(), diag::err_module_private_specialization) 13977 << 2 13978 << FixItHint::CreateRemoval(ModulePrivateLoc); 13979 // __module_private__ does not apply to local classes. However, we only 13980 // diagnose this as an error when the declaration specifiers are 13981 // freestanding. Here, we just ignore the __module_private__. 13982 else if (!SearchDC->isFunctionOrMethod()) 13983 New->setModulePrivate(); 13984 } 13985 13986 // If this is a specialization of a member class (of a class template), 13987 // check the specialization. 13988 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13989 Invalid = true; 13990 13991 // If we're declaring or defining a tag in function prototype scope in C, 13992 // note that this type can only be used within the function and add it to 13993 // the list of decls to inject into the function definition scope. 13994 if ((Name || Kind == TTK_Enum) && 13995 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13996 if (getLangOpts().CPlusPlus) { 13997 // C++ [dcl.fct]p6: 13998 // Types shall not be defined in return or parameter types. 13999 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14000 Diag(Loc, diag::err_type_defined_in_param_type) 14001 << Name; 14002 Invalid = true; 14003 } 14004 } else if (!PrevDecl) { 14005 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14006 } 14007 } 14008 14009 if (Invalid) 14010 New->setInvalidDecl(); 14011 14012 // Set the lexical context. If the tag has a C++ scope specifier, the 14013 // lexical context will be different from the semantic context. 14014 New->setLexicalDeclContext(CurContext); 14015 14016 // Mark this as a friend decl if applicable. 14017 // In Microsoft mode, a friend declaration also acts as a forward 14018 // declaration so we always pass true to setObjectOfFriendDecl to make 14019 // the tag name visible. 14020 if (TUK == TUK_Friend) 14021 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14022 14023 // Set the access specifier. 14024 if (!Invalid && SearchDC->isRecord()) 14025 SetMemberAccessSpecifier(New, PrevDecl, AS); 14026 14027 if (TUK == TUK_Definition) 14028 New->startDefinition(); 14029 14030 if (Attr) 14031 ProcessDeclAttributeList(S, New, Attr); 14032 AddPragmaAttributes(S, New); 14033 14034 // If this has an identifier, add it to the scope stack. 14035 if (TUK == TUK_Friend) { 14036 // We might be replacing an existing declaration in the lookup tables; 14037 // if so, borrow its access specifier. 14038 if (PrevDecl) 14039 New->setAccess(PrevDecl->getAccess()); 14040 14041 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14042 DC->makeDeclVisibleInContext(New); 14043 if (Name) // can be null along some error paths 14044 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14045 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14046 } else if (Name) { 14047 S = getNonFieldDeclScope(S); 14048 PushOnScopeChains(New, S, !IsForwardReference); 14049 if (IsForwardReference) 14050 SearchDC->makeDeclVisibleInContext(New); 14051 } else { 14052 CurContext->addDecl(New); 14053 } 14054 14055 // If this is the C FILE type, notify the AST context. 14056 if (IdentifierInfo *II = New->getIdentifier()) 14057 if (!New->isInvalidDecl() && 14058 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14059 II->isStr("FILE")) 14060 Context.setFILEDecl(New); 14061 14062 if (PrevDecl) 14063 mergeDeclAttributes(New, PrevDecl); 14064 14065 // If there's a #pragma GCC visibility in scope, set the visibility of this 14066 // record. 14067 AddPushedVisibilityAttribute(New); 14068 14069 if (isMemberSpecialization && !New->isInvalidDecl()) 14070 CompleteMemberSpecialization(New, Previous); 14071 14072 OwnedDecl = true; 14073 // In C++, don't return an invalid declaration. We can't recover well from 14074 // the cases where we make the type anonymous. 14075 if (Invalid && getLangOpts().CPlusPlus) { 14076 if (New->isBeingDefined()) 14077 if (auto RD = dyn_cast<RecordDecl>(New)) 14078 RD->completeDefinition(); 14079 return nullptr; 14080 } else { 14081 return New; 14082 } 14083 } 14084 14085 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14086 AdjustDeclIfTemplate(TagD); 14087 TagDecl *Tag = cast<TagDecl>(TagD); 14088 14089 // Enter the tag context. 14090 PushDeclContext(S, Tag); 14091 14092 ActOnDocumentableDecl(TagD); 14093 14094 // If there's a #pragma GCC visibility in scope, set the visibility of this 14095 // record. 14096 AddPushedVisibilityAttribute(Tag); 14097 } 14098 14099 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14100 SkipBodyInfo &SkipBody) { 14101 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14102 return false; 14103 14104 // Make the previous decl visible. 14105 makeMergedDefinitionVisible(SkipBody.Previous); 14106 return true; 14107 } 14108 14109 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14110 assert(isa<ObjCContainerDecl>(IDecl) && 14111 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14112 DeclContext *OCD = cast<DeclContext>(IDecl); 14113 assert(getContainingDC(OCD) == CurContext && 14114 "The next DeclContext should be lexically contained in the current one."); 14115 CurContext = OCD; 14116 return IDecl; 14117 } 14118 14119 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14120 SourceLocation FinalLoc, 14121 bool IsFinalSpelledSealed, 14122 SourceLocation LBraceLoc) { 14123 AdjustDeclIfTemplate(TagD); 14124 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14125 14126 FieldCollector->StartClass(); 14127 14128 if (!Record->getIdentifier()) 14129 return; 14130 14131 if (FinalLoc.isValid()) 14132 Record->addAttr(new (Context) 14133 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14134 14135 // C++ [class]p2: 14136 // [...] The class-name is also inserted into the scope of the 14137 // class itself; this is known as the injected-class-name. For 14138 // purposes of access checking, the injected-class-name is treated 14139 // as if it were a public member name. 14140 CXXRecordDecl *InjectedClassName 14141 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14142 Record->getLocStart(), Record->getLocation(), 14143 Record->getIdentifier(), 14144 /*PrevDecl=*/nullptr, 14145 /*DelayTypeCreation=*/true); 14146 Context.getTypeDeclType(InjectedClassName, Record); 14147 InjectedClassName->setImplicit(); 14148 InjectedClassName->setAccess(AS_public); 14149 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14150 InjectedClassName->setDescribedClassTemplate(Template); 14151 PushOnScopeChains(InjectedClassName, S); 14152 assert(InjectedClassName->isInjectedClassName() && 14153 "Broken injected-class-name"); 14154 } 14155 14156 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14157 SourceRange BraceRange) { 14158 AdjustDeclIfTemplate(TagD); 14159 TagDecl *Tag = cast<TagDecl>(TagD); 14160 Tag->setBraceRange(BraceRange); 14161 14162 // Make sure we "complete" the definition even it is invalid. 14163 if (Tag->isBeingDefined()) { 14164 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14165 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14166 RD->completeDefinition(); 14167 } 14168 14169 if (isa<CXXRecordDecl>(Tag)) { 14170 FieldCollector->FinishClass(); 14171 } 14172 14173 // Exit this scope of this tag's definition. 14174 PopDeclContext(); 14175 14176 if (getCurLexicalContext()->isObjCContainer() && 14177 Tag->getDeclContext()->isFileContext()) 14178 Tag->setTopLevelDeclInObjCContainer(); 14179 14180 // Notify the consumer that we've defined a tag. 14181 if (!Tag->isInvalidDecl()) 14182 Consumer.HandleTagDeclDefinition(Tag); 14183 } 14184 14185 void Sema::ActOnObjCContainerFinishDefinition() { 14186 // Exit this scope of this interface definition. 14187 PopDeclContext(); 14188 } 14189 14190 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14191 assert(DC == CurContext && "Mismatch of container contexts"); 14192 OriginalLexicalContext = DC; 14193 ActOnObjCContainerFinishDefinition(); 14194 } 14195 14196 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14197 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14198 OriginalLexicalContext = nullptr; 14199 } 14200 14201 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14202 AdjustDeclIfTemplate(TagD); 14203 TagDecl *Tag = cast<TagDecl>(TagD); 14204 Tag->setInvalidDecl(); 14205 14206 // Make sure we "complete" the definition even it is invalid. 14207 if (Tag->isBeingDefined()) { 14208 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14209 RD->completeDefinition(); 14210 } 14211 14212 // We're undoing ActOnTagStartDefinition here, not 14213 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14214 // the FieldCollector. 14215 14216 PopDeclContext(); 14217 } 14218 14219 // Note that FieldName may be null for anonymous bitfields. 14220 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14221 IdentifierInfo *FieldName, 14222 QualType FieldTy, bool IsMsStruct, 14223 Expr *BitWidth, bool *ZeroWidth) { 14224 // Default to true; that shouldn't confuse checks for emptiness 14225 if (ZeroWidth) 14226 *ZeroWidth = true; 14227 14228 // C99 6.7.2.1p4 - verify the field type. 14229 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14230 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14231 // Handle incomplete types with specific error. 14232 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14233 return ExprError(); 14234 if (FieldName) 14235 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14236 << FieldName << FieldTy << BitWidth->getSourceRange(); 14237 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14238 << FieldTy << BitWidth->getSourceRange(); 14239 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14240 UPPC_BitFieldWidth)) 14241 return ExprError(); 14242 14243 // If the bit-width is type- or value-dependent, don't try to check 14244 // it now. 14245 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14246 return BitWidth; 14247 14248 llvm::APSInt Value; 14249 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14250 if (ICE.isInvalid()) 14251 return ICE; 14252 BitWidth = ICE.get(); 14253 14254 if (Value != 0 && ZeroWidth) 14255 *ZeroWidth = false; 14256 14257 // Zero-width bitfield is ok for anonymous field. 14258 if (Value == 0 && FieldName) 14259 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14260 14261 if (Value.isSigned() && Value.isNegative()) { 14262 if (FieldName) 14263 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14264 << FieldName << Value.toString(10); 14265 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14266 << Value.toString(10); 14267 } 14268 14269 if (!FieldTy->isDependentType()) { 14270 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14271 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14272 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14273 14274 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14275 // ABI. 14276 bool CStdConstraintViolation = 14277 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14278 bool MSBitfieldViolation = 14279 Value.ugt(TypeStorageSize) && 14280 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14281 if (CStdConstraintViolation || MSBitfieldViolation) { 14282 unsigned DiagWidth = 14283 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14284 if (FieldName) 14285 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14286 << FieldName << (unsigned)Value.getZExtValue() 14287 << !CStdConstraintViolation << DiagWidth; 14288 14289 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14290 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14291 << DiagWidth; 14292 } 14293 14294 // Warn on types where the user might conceivably expect to get all 14295 // specified bits as value bits: that's all integral types other than 14296 // 'bool'. 14297 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14298 if (FieldName) 14299 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14300 << FieldName << (unsigned)Value.getZExtValue() 14301 << (unsigned)TypeWidth; 14302 else 14303 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14304 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14305 } 14306 } 14307 14308 return BitWidth; 14309 } 14310 14311 /// ActOnField - Each field of a C struct/union is passed into this in order 14312 /// to create a FieldDecl object for it. 14313 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14314 Declarator &D, Expr *BitfieldWidth) { 14315 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14316 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14317 /*InitStyle=*/ICIS_NoInit, AS_public); 14318 return Res; 14319 } 14320 14321 /// HandleField - Analyze a field of a C struct or a C++ data member. 14322 /// 14323 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14324 SourceLocation DeclStart, 14325 Declarator &D, Expr *BitWidth, 14326 InClassInitStyle InitStyle, 14327 AccessSpecifier AS) { 14328 if (D.isDecompositionDeclarator()) { 14329 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14330 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14331 << Decomp.getSourceRange(); 14332 return nullptr; 14333 } 14334 14335 IdentifierInfo *II = D.getIdentifier(); 14336 SourceLocation Loc = DeclStart; 14337 if (II) Loc = D.getIdentifierLoc(); 14338 14339 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14340 QualType T = TInfo->getType(); 14341 if (getLangOpts().CPlusPlus) { 14342 CheckExtraCXXDefaultArguments(D); 14343 14344 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14345 UPPC_DataMemberType)) { 14346 D.setInvalidType(); 14347 T = Context.IntTy; 14348 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14349 } 14350 } 14351 14352 // TR 18037 does not allow fields to be declared with address spaces. 14353 if (T.getQualifiers().hasAddressSpace()) { 14354 Diag(Loc, diag::err_field_with_address_space); 14355 D.setInvalidType(); 14356 } 14357 14358 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14359 // used as structure or union field: image, sampler, event or block types. 14360 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14361 T->isSamplerT() || T->isBlockPointerType())) { 14362 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14363 D.setInvalidType(); 14364 } 14365 14366 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14367 14368 if (D.getDeclSpec().isInlineSpecified()) 14369 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14370 << getLangOpts().CPlusPlus1z; 14371 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14372 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14373 diag::err_invalid_thread) 14374 << DeclSpec::getSpecifierName(TSCS); 14375 14376 // Check to see if this name was declared as a member previously 14377 NamedDecl *PrevDecl = nullptr; 14378 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14379 LookupName(Previous, S); 14380 switch (Previous.getResultKind()) { 14381 case LookupResult::Found: 14382 case LookupResult::FoundUnresolvedValue: 14383 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14384 break; 14385 14386 case LookupResult::FoundOverloaded: 14387 PrevDecl = Previous.getRepresentativeDecl(); 14388 break; 14389 14390 case LookupResult::NotFound: 14391 case LookupResult::NotFoundInCurrentInstantiation: 14392 case LookupResult::Ambiguous: 14393 break; 14394 } 14395 Previous.suppressDiagnostics(); 14396 14397 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14398 // Maybe we will complain about the shadowed template parameter. 14399 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14400 // Just pretend that we didn't see the previous declaration. 14401 PrevDecl = nullptr; 14402 } 14403 14404 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14405 PrevDecl = nullptr; 14406 14407 bool Mutable 14408 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14409 SourceLocation TSSL = D.getLocStart(); 14410 FieldDecl *NewFD 14411 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14412 TSSL, AS, PrevDecl, &D); 14413 14414 if (NewFD->isInvalidDecl()) 14415 Record->setInvalidDecl(); 14416 14417 if (D.getDeclSpec().isModulePrivateSpecified()) 14418 NewFD->setModulePrivate(); 14419 14420 if (NewFD->isInvalidDecl() && PrevDecl) { 14421 // Don't introduce NewFD into scope; there's already something 14422 // with the same name in the same scope. 14423 } else if (II) { 14424 PushOnScopeChains(NewFD, S); 14425 } else 14426 Record->addDecl(NewFD); 14427 14428 return NewFD; 14429 } 14430 14431 /// \brief Build a new FieldDecl and check its well-formedness. 14432 /// 14433 /// This routine builds a new FieldDecl given the fields name, type, 14434 /// record, etc. \p PrevDecl should refer to any previous declaration 14435 /// with the same name and in the same scope as the field to be 14436 /// created. 14437 /// 14438 /// \returns a new FieldDecl. 14439 /// 14440 /// \todo The Declarator argument is a hack. It will be removed once 14441 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14442 TypeSourceInfo *TInfo, 14443 RecordDecl *Record, SourceLocation Loc, 14444 bool Mutable, Expr *BitWidth, 14445 InClassInitStyle InitStyle, 14446 SourceLocation TSSL, 14447 AccessSpecifier AS, NamedDecl *PrevDecl, 14448 Declarator *D) { 14449 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14450 bool InvalidDecl = false; 14451 if (D) InvalidDecl = D->isInvalidType(); 14452 14453 // If we receive a broken type, recover by assuming 'int' and 14454 // marking this declaration as invalid. 14455 if (T.isNull()) { 14456 InvalidDecl = true; 14457 T = Context.IntTy; 14458 } 14459 14460 QualType EltTy = Context.getBaseElementType(T); 14461 if (!EltTy->isDependentType()) { 14462 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14463 // Fields of incomplete type force their record to be invalid. 14464 Record->setInvalidDecl(); 14465 InvalidDecl = true; 14466 } else { 14467 NamedDecl *Def; 14468 EltTy->isIncompleteType(&Def); 14469 if (Def && Def->isInvalidDecl()) { 14470 Record->setInvalidDecl(); 14471 InvalidDecl = true; 14472 } 14473 } 14474 } 14475 14476 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14477 if (BitWidth && getLangOpts().OpenCL) { 14478 Diag(Loc, diag::err_opencl_bitfields); 14479 InvalidDecl = true; 14480 } 14481 14482 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14483 // than a variably modified type. 14484 if (!InvalidDecl && T->isVariablyModifiedType()) { 14485 bool SizeIsNegative; 14486 llvm::APSInt Oversized; 14487 14488 TypeSourceInfo *FixedTInfo = 14489 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14490 SizeIsNegative, 14491 Oversized); 14492 if (FixedTInfo) { 14493 Diag(Loc, diag::warn_illegal_constant_array_size); 14494 TInfo = FixedTInfo; 14495 T = FixedTInfo->getType(); 14496 } else { 14497 if (SizeIsNegative) 14498 Diag(Loc, diag::err_typecheck_negative_array_size); 14499 else if (Oversized.getBoolValue()) 14500 Diag(Loc, diag::err_array_too_large) 14501 << Oversized.toString(10); 14502 else 14503 Diag(Loc, diag::err_typecheck_field_variable_size); 14504 InvalidDecl = true; 14505 } 14506 } 14507 14508 // Fields can not have abstract class types 14509 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14510 diag::err_abstract_type_in_decl, 14511 AbstractFieldType)) 14512 InvalidDecl = true; 14513 14514 bool ZeroWidth = false; 14515 if (InvalidDecl) 14516 BitWidth = nullptr; 14517 // If this is declared as a bit-field, check the bit-field. 14518 if (BitWidth) { 14519 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14520 &ZeroWidth).get(); 14521 if (!BitWidth) { 14522 InvalidDecl = true; 14523 BitWidth = nullptr; 14524 ZeroWidth = false; 14525 } 14526 } 14527 14528 // Check that 'mutable' is consistent with the type of the declaration. 14529 if (!InvalidDecl && Mutable) { 14530 unsigned DiagID = 0; 14531 if (T->isReferenceType()) 14532 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14533 : diag::err_mutable_reference; 14534 else if (T.isConstQualified()) 14535 DiagID = diag::err_mutable_const; 14536 14537 if (DiagID) { 14538 SourceLocation ErrLoc = Loc; 14539 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14540 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14541 Diag(ErrLoc, DiagID); 14542 if (DiagID != diag::ext_mutable_reference) { 14543 Mutable = false; 14544 InvalidDecl = true; 14545 } 14546 } 14547 } 14548 14549 // C++11 [class.union]p8 (DR1460): 14550 // At most one variant member of a union may have a 14551 // brace-or-equal-initializer. 14552 if (InitStyle != ICIS_NoInit) 14553 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14554 14555 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14556 BitWidth, Mutable, InitStyle); 14557 if (InvalidDecl) 14558 NewFD->setInvalidDecl(); 14559 14560 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14561 Diag(Loc, diag::err_duplicate_member) << II; 14562 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14563 NewFD->setInvalidDecl(); 14564 } 14565 14566 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14567 if (Record->isUnion()) { 14568 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14569 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14570 if (RDecl->getDefinition()) { 14571 // C++ [class.union]p1: An object of a class with a non-trivial 14572 // constructor, a non-trivial copy constructor, a non-trivial 14573 // destructor, or a non-trivial copy assignment operator 14574 // cannot be a member of a union, nor can an array of such 14575 // objects. 14576 if (CheckNontrivialField(NewFD)) 14577 NewFD->setInvalidDecl(); 14578 } 14579 } 14580 14581 // C++ [class.union]p1: If a union contains a member of reference type, 14582 // the program is ill-formed, except when compiling with MSVC extensions 14583 // enabled. 14584 if (EltTy->isReferenceType()) { 14585 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14586 diag::ext_union_member_of_reference_type : 14587 diag::err_union_member_of_reference_type) 14588 << NewFD->getDeclName() << EltTy; 14589 if (!getLangOpts().MicrosoftExt) 14590 NewFD->setInvalidDecl(); 14591 } 14592 } 14593 } 14594 14595 // FIXME: We need to pass in the attributes given an AST 14596 // representation, not a parser representation. 14597 if (D) { 14598 // FIXME: The current scope is almost... but not entirely... correct here. 14599 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14600 14601 if (NewFD->hasAttrs()) 14602 CheckAlignasUnderalignment(NewFD); 14603 } 14604 14605 // In auto-retain/release, infer strong retension for fields of 14606 // retainable type. 14607 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14608 NewFD->setInvalidDecl(); 14609 14610 if (T.isObjCGCWeak()) 14611 Diag(Loc, diag::warn_attribute_weak_on_field); 14612 14613 NewFD->setAccess(AS); 14614 return NewFD; 14615 } 14616 14617 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14618 assert(FD); 14619 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14620 14621 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14622 return false; 14623 14624 QualType EltTy = Context.getBaseElementType(FD->getType()); 14625 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14626 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14627 if (RDecl->getDefinition()) { 14628 // We check for copy constructors before constructors 14629 // because otherwise we'll never get complaints about 14630 // copy constructors. 14631 14632 CXXSpecialMember member = CXXInvalid; 14633 // We're required to check for any non-trivial constructors. Since the 14634 // implicit default constructor is suppressed if there are any 14635 // user-declared constructors, we just need to check that there is a 14636 // trivial default constructor and a trivial copy constructor. (We don't 14637 // worry about move constructors here, since this is a C++98 check.) 14638 if (RDecl->hasNonTrivialCopyConstructor()) 14639 member = CXXCopyConstructor; 14640 else if (!RDecl->hasTrivialDefaultConstructor()) 14641 member = CXXDefaultConstructor; 14642 else if (RDecl->hasNonTrivialCopyAssignment()) 14643 member = CXXCopyAssignment; 14644 else if (RDecl->hasNonTrivialDestructor()) 14645 member = CXXDestructor; 14646 14647 if (member != CXXInvalid) { 14648 if (!getLangOpts().CPlusPlus11 && 14649 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14650 // Objective-C++ ARC: it is an error to have a non-trivial field of 14651 // a union. However, system headers in Objective-C programs 14652 // occasionally have Objective-C lifetime objects within unions, 14653 // and rather than cause the program to fail, we make those 14654 // members unavailable. 14655 SourceLocation Loc = FD->getLocation(); 14656 if (getSourceManager().isInSystemHeader(Loc)) { 14657 if (!FD->hasAttr<UnavailableAttr>()) 14658 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14659 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14660 return false; 14661 } 14662 } 14663 14664 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14665 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14666 diag::err_illegal_union_or_anon_struct_member) 14667 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14668 DiagnoseNontrivial(RDecl, member); 14669 return !getLangOpts().CPlusPlus11; 14670 } 14671 } 14672 } 14673 14674 return false; 14675 } 14676 14677 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14678 /// AST enum value. 14679 static ObjCIvarDecl::AccessControl 14680 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14681 switch (ivarVisibility) { 14682 default: llvm_unreachable("Unknown visitibility kind"); 14683 case tok::objc_private: return ObjCIvarDecl::Private; 14684 case tok::objc_public: return ObjCIvarDecl::Public; 14685 case tok::objc_protected: return ObjCIvarDecl::Protected; 14686 case tok::objc_package: return ObjCIvarDecl::Package; 14687 } 14688 } 14689 14690 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14691 /// in order to create an IvarDecl object for it. 14692 Decl *Sema::ActOnIvar(Scope *S, 14693 SourceLocation DeclStart, 14694 Declarator &D, Expr *BitfieldWidth, 14695 tok::ObjCKeywordKind Visibility) { 14696 14697 IdentifierInfo *II = D.getIdentifier(); 14698 Expr *BitWidth = (Expr*)BitfieldWidth; 14699 SourceLocation Loc = DeclStart; 14700 if (II) Loc = D.getIdentifierLoc(); 14701 14702 // FIXME: Unnamed fields can be handled in various different ways, for 14703 // example, unnamed unions inject all members into the struct namespace! 14704 14705 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14706 QualType T = TInfo->getType(); 14707 14708 if (BitWidth) { 14709 // 6.7.2.1p3, 6.7.2.1p4 14710 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14711 if (!BitWidth) 14712 D.setInvalidType(); 14713 } else { 14714 // Not a bitfield. 14715 14716 // validate II. 14717 14718 } 14719 if (T->isReferenceType()) { 14720 Diag(Loc, diag::err_ivar_reference_type); 14721 D.setInvalidType(); 14722 } 14723 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14724 // than a variably modified type. 14725 else if (T->isVariablyModifiedType()) { 14726 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14727 D.setInvalidType(); 14728 } 14729 14730 // Get the visibility (access control) for this ivar. 14731 ObjCIvarDecl::AccessControl ac = 14732 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14733 : ObjCIvarDecl::None; 14734 // Must set ivar's DeclContext to its enclosing interface. 14735 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14736 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14737 return nullptr; 14738 ObjCContainerDecl *EnclosingContext; 14739 if (ObjCImplementationDecl *IMPDecl = 14740 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14741 if (LangOpts.ObjCRuntime.isFragile()) { 14742 // Case of ivar declared in an implementation. Context is that of its class. 14743 EnclosingContext = IMPDecl->getClassInterface(); 14744 assert(EnclosingContext && "Implementation has no class interface!"); 14745 } 14746 else 14747 EnclosingContext = EnclosingDecl; 14748 } else { 14749 if (ObjCCategoryDecl *CDecl = 14750 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14751 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14752 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14753 return nullptr; 14754 } 14755 } 14756 EnclosingContext = EnclosingDecl; 14757 } 14758 14759 // Construct the decl. 14760 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14761 DeclStart, Loc, II, T, 14762 TInfo, ac, (Expr *)BitfieldWidth); 14763 14764 if (II) { 14765 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14766 ForRedeclaration); 14767 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14768 && !isa<TagDecl>(PrevDecl)) { 14769 Diag(Loc, diag::err_duplicate_member) << II; 14770 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14771 NewID->setInvalidDecl(); 14772 } 14773 } 14774 14775 // Process attributes attached to the ivar. 14776 ProcessDeclAttributes(S, NewID, D); 14777 14778 if (D.isInvalidType()) 14779 NewID->setInvalidDecl(); 14780 14781 // In ARC, infer 'retaining' for ivars of retainable type. 14782 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14783 NewID->setInvalidDecl(); 14784 14785 if (D.getDeclSpec().isModulePrivateSpecified()) 14786 NewID->setModulePrivate(); 14787 14788 if (II) { 14789 // FIXME: When interfaces are DeclContexts, we'll need to add 14790 // these to the interface. 14791 S->AddDecl(NewID); 14792 IdResolver.AddDecl(NewID); 14793 } 14794 14795 if (LangOpts.ObjCRuntime.isNonFragile() && 14796 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14797 Diag(Loc, diag::warn_ivars_in_interface); 14798 14799 return NewID; 14800 } 14801 14802 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14803 /// class and class extensions. For every class \@interface and class 14804 /// extension \@interface, if the last ivar is a bitfield of any type, 14805 /// then add an implicit `char :0` ivar to the end of that interface. 14806 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14807 SmallVectorImpl<Decl *> &AllIvarDecls) { 14808 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14809 return; 14810 14811 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14812 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14813 14814 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14815 return; 14816 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14817 if (!ID) { 14818 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14819 if (!CD->IsClassExtension()) 14820 return; 14821 } 14822 // No need to add this to end of @implementation. 14823 else 14824 return; 14825 } 14826 // All conditions are met. Add a new bitfield to the tail end of ivars. 14827 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14828 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14829 14830 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14831 DeclLoc, DeclLoc, nullptr, 14832 Context.CharTy, 14833 Context.getTrivialTypeSourceInfo(Context.CharTy, 14834 DeclLoc), 14835 ObjCIvarDecl::Private, BW, 14836 true); 14837 AllIvarDecls.push_back(Ivar); 14838 } 14839 14840 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14841 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14842 SourceLocation RBrac, AttributeList *Attr) { 14843 assert(EnclosingDecl && "missing record or interface decl"); 14844 14845 // If this is an Objective-C @implementation or category and we have 14846 // new fields here we should reset the layout of the interface since 14847 // it will now change. 14848 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14849 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14850 switch (DC->getKind()) { 14851 default: break; 14852 case Decl::ObjCCategory: 14853 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14854 break; 14855 case Decl::ObjCImplementation: 14856 Context. 14857 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14858 break; 14859 } 14860 } 14861 14862 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14863 14864 // Start counting up the number of named members; make sure to include 14865 // members of anonymous structs and unions in the total. 14866 unsigned NumNamedMembers = 0; 14867 if (Record) { 14868 for (const auto *I : Record->decls()) { 14869 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14870 if (IFD->getDeclName()) 14871 ++NumNamedMembers; 14872 } 14873 } 14874 14875 // Verify that all the fields are okay. 14876 SmallVector<FieldDecl*, 32> RecFields; 14877 14878 bool ObjCFieldLifetimeErrReported = false; 14879 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14880 i != end; ++i) { 14881 FieldDecl *FD = cast<FieldDecl>(*i); 14882 14883 // Get the type for the field. 14884 const Type *FDTy = FD->getType().getTypePtr(); 14885 14886 if (!FD->isAnonymousStructOrUnion()) { 14887 // Remember all fields written by the user. 14888 RecFields.push_back(FD); 14889 } 14890 14891 // If the field is already invalid for some reason, don't emit more 14892 // diagnostics about it. 14893 if (FD->isInvalidDecl()) { 14894 EnclosingDecl->setInvalidDecl(); 14895 continue; 14896 } 14897 14898 // C99 6.7.2.1p2: 14899 // A structure or union shall not contain a member with 14900 // incomplete or function type (hence, a structure shall not 14901 // contain an instance of itself, but may contain a pointer to 14902 // an instance of itself), except that the last member of a 14903 // structure with more than one named member may have incomplete 14904 // array type; such a structure (and any union containing, 14905 // possibly recursively, a member that is such a structure) 14906 // shall not be a member of a structure or an element of an 14907 // array. 14908 if (FDTy->isFunctionType()) { 14909 // Field declared as a function. 14910 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14911 << FD->getDeclName(); 14912 FD->setInvalidDecl(); 14913 EnclosingDecl->setInvalidDecl(); 14914 continue; 14915 } else if (FDTy->isIncompleteArrayType() && Record && 14916 ((i + 1 == Fields.end() && !Record->isUnion()) || 14917 ((getLangOpts().MicrosoftExt || 14918 getLangOpts().CPlusPlus) && 14919 (i + 1 == Fields.end() || Record->isUnion())))) { 14920 // Flexible array member. 14921 // Microsoft and g++ is more permissive regarding flexible array. 14922 // It will accept flexible array in union and also 14923 // as the sole element of a struct/class. 14924 unsigned DiagID = 0; 14925 if (Record->isUnion()) 14926 DiagID = getLangOpts().MicrosoftExt 14927 ? diag::ext_flexible_array_union_ms 14928 : getLangOpts().CPlusPlus 14929 ? diag::ext_flexible_array_union_gnu 14930 : diag::err_flexible_array_union; 14931 else if (NumNamedMembers < 1) 14932 DiagID = getLangOpts().MicrosoftExt 14933 ? diag::ext_flexible_array_empty_aggregate_ms 14934 : getLangOpts().CPlusPlus 14935 ? diag::ext_flexible_array_empty_aggregate_gnu 14936 : diag::err_flexible_array_empty_aggregate; 14937 14938 if (DiagID) 14939 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14940 << Record->getTagKind(); 14941 // While the layout of types that contain virtual bases is not specified 14942 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14943 // virtual bases after the derived members. This would make a flexible 14944 // array member declared at the end of an object not adjacent to the end 14945 // of the type. 14946 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14947 if (RD->getNumVBases() != 0) 14948 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14949 << FD->getDeclName() << Record->getTagKind(); 14950 if (!getLangOpts().C99) 14951 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14952 << FD->getDeclName() << Record->getTagKind(); 14953 14954 // If the element type has a non-trivial destructor, we would not 14955 // implicitly destroy the elements, so disallow it for now. 14956 // 14957 // FIXME: GCC allows this. We should probably either implicitly delete 14958 // the destructor of the containing class, or just allow this. 14959 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14960 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14961 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14962 << FD->getDeclName() << FD->getType(); 14963 FD->setInvalidDecl(); 14964 EnclosingDecl->setInvalidDecl(); 14965 continue; 14966 } 14967 // Okay, we have a legal flexible array member at the end of the struct. 14968 Record->setHasFlexibleArrayMember(true); 14969 } else if (!FDTy->isDependentType() && 14970 RequireCompleteType(FD->getLocation(), FD->getType(), 14971 diag::err_field_incomplete)) { 14972 // Incomplete type 14973 FD->setInvalidDecl(); 14974 EnclosingDecl->setInvalidDecl(); 14975 continue; 14976 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14977 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14978 // A type which contains a flexible array member is considered to be a 14979 // flexible array member. 14980 Record->setHasFlexibleArrayMember(true); 14981 if (!Record->isUnion()) { 14982 // If this is a struct/class and this is not the last element, reject 14983 // it. Note that GCC supports variable sized arrays in the middle of 14984 // structures. 14985 if (i + 1 != Fields.end()) 14986 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14987 << FD->getDeclName() << FD->getType(); 14988 else { 14989 // We support flexible arrays at the end of structs in 14990 // other structs as an extension. 14991 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14992 << FD->getDeclName(); 14993 } 14994 } 14995 } 14996 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14997 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14998 diag::err_abstract_type_in_decl, 14999 AbstractIvarType)) { 15000 // Ivars can not have abstract class types 15001 FD->setInvalidDecl(); 15002 } 15003 if (Record && FDTTy->getDecl()->hasObjectMember()) 15004 Record->setHasObjectMember(true); 15005 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15006 Record->setHasVolatileMember(true); 15007 } else if (FDTy->isObjCObjectType()) { 15008 /// A field cannot be an Objective-c object 15009 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15010 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15011 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15012 FD->setType(T); 15013 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15014 Record && !ObjCFieldLifetimeErrReported && 15015 (!getLangOpts().CPlusPlus || Record->isUnion())) { 15016 // It's an error in ARC or Weak if a field has lifetime. 15017 // We don't want to report this in a system header, though, 15018 // so we just make the field unavailable. 15019 // FIXME: that's really not sufficient; we need to make the type 15020 // itself invalid to, say, initialize or copy. 15021 QualType T = FD->getType(); 15022 if (T.hasNonTrivialObjCLifetime()) { 15023 SourceLocation loc = FD->getLocation(); 15024 if (getSourceManager().isInSystemHeader(loc)) { 15025 if (!FD->hasAttr<UnavailableAttr>()) { 15026 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15027 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15028 } 15029 } else { 15030 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15031 << T->isBlockPointerType() << Record->getTagKind(); 15032 } 15033 ObjCFieldLifetimeErrReported = true; 15034 } 15035 } else if (getLangOpts().ObjC1 && 15036 getLangOpts().getGC() != LangOptions::NonGC && 15037 Record && !Record->hasObjectMember()) { 15038 if (FD->getType()->isObjCObjectPointerType() || 15039 FD->getType().isObjCGCStrong()) 15040 Record->setHasObjectMember(true); 15041 else if (Context.getAsArrayType(FD->getType())) { 15042 QualType BaseType = Context.getBaseElementType(FD->getType()); 15043 if (BaseType->isRecordType() && 15044 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15045 Record->setHasObjectMember(true); 15046 else if (BaseType->isObjCObjectPointerType() || 15047 BaseType.isObjCGCStrong()) 15048 Record->setHasObjectMember(true); 15049 } 15050 } 15051 if (Record && FD->getType().isVolatileQualified()) 15052 Record->setHasVolatileMember(true); 15053 // Keep track of the number of named members. 15054 if (FD->getIdentifier()) 15055 ++NumNamedMembers; 15056 } 15057 15058 // Okay, we successfully defined 'Record'. 15059 if (Record) { 15060 bool Completed = false; 15061 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15062 if (!CXXRecord->isInvalidDecl()) { 15063 // Set access bits correctly on the directly-declared conversions. 15064 for (CXXRecordDecl::conversion_iterator 15065 I = CXXRecord->conversion_begin(), 15066 E = CXXRecord->conversion_end(); I != E; ++I) 15067 I.setAccess((*I)->getAccess()); 15068 } 15069 15070 if (!CXXRecord->isDependentType()) { 15071 if (CXXRecord->hasUserDeclaredDestructor()) { 15072 // Adjust user-defined destructor exception spec. 15073 if (getLangOpts().CPlusPlus11) 15074 AdjustDestructorExceptionSpec(CXXRecord, 15075 CXXRecord->getDestructor()); 15076 } 15077 15078 if (!CXXRecord->isInvalidDecl()) { 15079 // Add any implicitly-declared members to this class. 15080 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15081 15082 // If we have virtual base classes, we may end up finding multiple 15083 // final overriders for a given virtual function. Check for this 15084 // problem now. 15085 if (CXXRecord->getNumVBases()) { 15086 CXXFinalOverriderMap FinalOverriders; 15087 CXXRecord->getFinalOverriders(FinalOverriders); 15088 15089 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15090 MEnd = FinalOverriders.end(); 15091 M != MEnd; ++M) { 15092 for (OverridingMethods::iterator SO = M->second.begin(), 15093 SOEnd = M->second.end(); 15094 SO != SOEnd; ++SO) { 15095 assert(SO->second.size() > 0 && 15096 "Virtual function without overridding functions?"); 15097 if (SO->second.size() == 1) 15098 continue; 15099 15100 // C++ [class.virtual]p2: 15101 // In a derived class, if a virtual member function of a base 15102 // class subobject has more than one final overrider the 15103 // program is ill-formed. 15104 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15105 << (const NamedDecl *)M->first << Record; 15106 Diag(M->first->getLocation(), 15107 diag::note_overridden_virtual_function); 15108 for (OverridingMethods::overriding_iterator 15109 OM = SO->second.begin(), 15110 OMEnd = SO->second.end(); 15111 OM != OMEnd; ++OM) 15112 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15113 << (const NamedDecl *)M->first << OM->Method->getParent(); 15114 15115 Record->setInvalidDecl(); 15116 } 15117 } 15118 CXXRecord->completeDefinition(&FinalOverriders); 15119 Completed = true; 15120 } 15121 } 15122 } 15123 } 15124 15125 if (!Completed) 15126 Record->completeDefinition(); 15127 15128 // We may have deferred checking for a deleted destructor. Check now. 15129 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15130 auto *Dtor = CXXRecord->getDestructor(); 15131 if (Dtor && Dtor->isImplicit() && 15132 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15133 CXXRecord->setImplicitDestructorIsDeleted(); 15134 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15135 } 15136 } 15137 15138 if (Record->hasAttrs()) { 15139 CheckAlignasUnderalignment(Record); 15140 15141 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15142 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15143 IA->getRange(), IA->getBestCase(), 15144 IA->getSemanticSpelling()); 15145 } 15146 15147 // Check if the structure/union declaration is a type that can have zero 15148 // size in C. For C this is a language extension, for C++ it may cause 15149 // compatibility problems. 15150 bool CheckForZeroSize; 15151 if (!getLangOpts().CPlusPlus) { 15152 CheckForZeroSize = true; 15153 } else { 15154 // For C++ filter out types that cannot be referenced in C code. 15155 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15156 CheckForZeroSize = 15157 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15158 !CXXRecord->isDependentType() && 15159 CXXRecord->isCLike(); 15160 } 15161 if (CheckForZeroSize) { 15162 bool ZeroSize = true; 15163 bool IsEmpty = true; 15164 unsigned NonBitFields = 0; 15165 for (RecordDecl::field_iterator I = Record->field_begin(), 15166 E = Record->field_end(); 15167 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15168 IsEmpty = false; 15169 if (I->isUnnamedBitfield()) { 15170 if (I->getBitWidthValue(Context) > 0) 15171 ZeroSize = false; 15172 } else { 15173 ++NonBitFields; 15174 QualType FieldType = I->getType(); 15175 if (FieldType->isIncompleteType() || 15176 !Context.getTypeSizeInChars(FieldType).isZero()) 15177 ZeroSize = false; 15178 } 15179 } 15180 15181 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15182 // allowed in C++, but warn if its declaration is inside 15183 // extern "C" block. 15184 if (ZeroSize) { 15185 Diag(RecLoc, getLangOpts().CPlusPlus ? 15186 diag::warn_zero_size_struct_union_in_extern_c : 15187 diag::warn_zero_size_struct_union_compat) 15188 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15189 } 15190 15191 // Structs without named members are extension in C (C99 6.7.2.1p7), 15192 // but are accepted by GCC. 15193 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15194 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15195 diag::ext_no_named_members_in_struct_union) 15196 << Record->isUnion(); 15197 } 15198 } 15199 } else { 15200 ObjCIvarDecl **ClsFields = 15201 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15202 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15203 ID->setEndOfDefinitionLoc(RBrac); 15204 // Add ivar's to class's DeclContext. 15205 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15206 ClsFields[i]->setLexicalDeclContext(ID); 15207 ID->addDecl(ClsFields[i]); 15208 } 15209 // Must enforce the rule that ivars in the base classes may not be 15210 // duplicates. 15211 if (ID->getSuperClass()) 15212 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15213 } else if (ObjCImplementationDecl *IMPDecl = 15214 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15215 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15216 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15217 // Ivar declared in @implementation never belongs to the implementation. 15218 // Only it is in implementation's lexical context. 15219 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15220 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15221 IMPDecl->setIvarLBraceLoc(LBrac); 15222 IMPDecl->setIvarRBraceLoc(RBrac); 15223 } else if (ObjCCategoryDecl *CDecl = 15224 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15225 // case of ivars in class extension; all other cases have been 15226 // reported as errors elsewhere. 15227 // FIXME. Class extension does not have a LocEnd field. 15228 // CDecl->setLocEnd(RBrac); 15229 // Add ivar's to class extension's DeclContext. 15230 // Diagnose redeclaration of private ivars. 15231 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15232 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15233 if (IDecl) { 15234 if (const ObjCIvarDecl *ClsIvar = 15235 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15236 Diag(ClsFields[i]->getLocation(), 15237 diag::err_duplicate_ivar_declaration); 15238 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15239 continue; 15240 } 15241 for (const auto *Ext : IDecl->known_extensions()) { 15242 if (const ObjCIvarDecl *ClsExtIvar 15243 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15244 Diag(ClsFields[i]->getLocation(), 15245 diag::err_duplicate_ivar_declaration); 15246 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15247 continue; 15248 } 15249 } 15250 } 15251 ClsFields[i]->setLexicalDeclContext(CDecl); 15252 CDecl->addDecl(ClsFields[i]); 15253 } 15254 CDecl->setIvarLBraceLoc(LBrac); 15255 CDecl->setIvarRBraceLoc(RBrac); 15256 } 15257 } 15258 15259 if (Attr) 15260 ProcessDeclAttributeList(S, Record, Attr); 15261 } 15262 15263 /// \brief Determine whether the given integral value is representable within 15264 /// the given type T. 15265 static bool isRepresentableIntegerValue(ASTContext &Context, 15266 llvm::APSInt &Value, 15267 QualType T) { 15268 assert(T->isIntegralType(Context) && "Integral type required!"); 15269 unsigned BitWidth = Context.getIntWidth(T); 15270 15271 if (Value.isUnsigned() || Value.isNonNegative()) { 15272 if (T->isSignedIntegerOrEnumerationType()) 15273 --BitWidth; 15274 return Value.getActiveBits() <= BitWidth; 15275 } 15276 return Value.getMinSignedBits() <= BitWidth; 15277 } 15278 15279 // \brief Given an integral type, return the next larger integral type 15280 // (or a NULL type of no such type exists). 15281 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15282 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15283 // enum checking below. 15284 assert(T->isIntegralType(Context) && "Integral type required!"); 15285 const unsigned NumTypes = 4; 15286 QualType SignedIntegralTypes[NumTypes] = { 15287 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15288 }; 15289 QualType UnsignedIntegralTypes[NumTypes] = { 15290 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15291 Context.UnsignedLongLongTy 15292 }; 15293 15294 unsigned BitWidth = Context.getTypeSize(T); 15295 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15296 : UnsignedIntegralTypes; 15297 for (unsigned I = 0; I != NumTypes; ++I) 15298 if (Context.getTypeSize(Types[I]) > BitWidth) 15299 return Types[I]; 15300 15301 return QualType(); 15302 } 15303 15304 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15305 EnumConstantDecl *LastEnumConst, 15306 SourceLocation IdLoc, 15307 IdentifierInfo *Id, 15308 Expr *Val) { 15309 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15310 llvm::APSInt EnumVal(IntWidth); 15311 QualType EltTy; 15312 15313 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15314 Val = nullptr; 15315 15316 if (Val) 15317 Val = DefaultLvalueConversion(Val).get(); 15318 15319 if (Val) { 15320 if (Enum->isDependentType() || Val->isTypeDependent()) 15321 EltTy = Context.DependentTy; 15322 else { 15323 SourceLocation ExpLoc; 15324 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15325 !getLangOpts().MSVCCompat) { 15326 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15327 // constant-expression in the enumerator-definition shall be a converted 15328 // constant expression of the underlying type. 15329 EltTy = Enum->getIntegerType(); 15330 ExprResult Converted = 15331 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15332 CCEK_Enumerator); 15333 if (Converted.isInvalid()) 15334 Val = nullptr; 15335 else 15336 Val = Converted.get(); 15337 } else if (!Val->isValueDependent() && 15338 !(Val = VerifyIntegerConstantExpression(Val, 15339 &EnumVal).get())) { 15340 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15341 } else { 15342 if (Enum->isFixed()) { 15343 EltTy = Enum->getIntegerType(); 15344 15345 // In Obj-C and Microsoft mode, require the enumeration value to be 15346 // representable in the underlying type of the enumeration. In C++11, 15347 // we perform a non-narrowing conversion as part of converted constant 15348 // expression checking. 15349 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15350 if (getLangOpts().MSVCCompat) { 15351 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15352 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15353 } else 15354 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15355 } else 15356 Val = ImpCastExprToType(Val, EltTy, 15357 EltTy->isBooleanType() ? 15358 CK_IntegralToBoolean : CK_IntegralCast) 15359 .get(); 15360 } else if (getLangOpts().CPlusPlus) { 15361 // C++11 [dcl.enum]p5: 15362 // If the underlying type is not fixed, the type of each enumerator 15363 // is the type of its initializing value: 15364 // - If an initializer is specified for an enumerator, the 15365 // initializing value has the same type as the expression. 15366 EltTy = Val->getType(); 15367 } else { 15368 // C99 6.7.2.2p2: 15369 // The expression that defines the value of an enumeration constant 15370 // shall be an integer constant expression that has a value 15371 // representable as an int. 15372 15373 // Complain if the value is not representable in an int. 15374 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15375 Diag(IdLoc, diag::ext_enum_value_not_int) 15376 << EnumVal.toString(10) << Val->getSourceRange() 15377 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15378 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15379 // Force the type of the expression to 'int'. 15380 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15381 } 15382 EltTy = Val->getType(); 15383 } 15384 } 15385 } 15386 } 15387 15388 if (!Val) { 15389 if (Enum->isDependentType()) 15390 EltTy = Context.DependentTy; 15391 else if (!LastEnumConst) { 15392 // C++0x [dcl.enum]p5: 15393 // If the underlying type is not fixed, the type of each enumerator 15394 // is the type of its initializing value: 15395 // - If no initializer is specified for the first enumerator, the 15396 // initializing value has an unspecified integral type. 15397 // 15398 // GCC uses 'int' for its unspecified integral type, as does 15399 // C99 6.7.2.2p3. 15400 if (Enum->isFixed()) { 15401 EltTy = Enum->getIntegerType(); 15402 } 15403 else { 15404 EltTy = Context.IntTy; 15405 } 15406 } else { 15407 // Assign the last value + 1. 15408 EnumVal = LastEnumConst->getInitVal(); 15409 ++EnumVal; 15410 EltTy = LastEnumConst->getType(); 15411 15412 // Check for overflow on increment. 15413 if (EnumVal < LastEnumConst->getInitVal()) { 15414 // C++0x [dcl.enum]p5: 15415 // If the underlying type is not fixed, the type of each enumerator 15416 // is the type of its initializing value: 15417 // 15418 // - Otherwise the type of the initializing value is the same as 15419 // the type of the initializing value of the preceding enumerator 15420 // unless the incremented value is not representable in that type, 15421 // in which case the type is an unspecified integral type 15422 // sufficient to contain the incremented value. If no such type 15423 // exists, the program is ill-formed. 15424 QualType T = getNextLargerIntegralType(Context, EltTy); 15425 if (T.isNull() || Enum->isFixed()) { 15426 // There is no integral type larger enough to represent this 15427 // value. Complain, then allow the value to wrap around. 15428 EnumVal = LastEnumConst->getInitVal(); 15429 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15430 ++EnumVal; 15431 if (Enum->isFixed()) 15432 // When the underlying type is fixed, this is ill-formed. 15433 Diag(IdLoc, diag::err_enumerator_wrapped) 15434 << EnumVal.toString(10) 15435 << EltTy; 15436 else 15437 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15438 << EnumVal.toString(10); 15439 } else { 15440 EltTy = T; 15441 } 15442 15443 // Retrieve the last enumerator's value, extent that type to the 15444 // type that is supposed to be large enough to represent the incremented 15445 // value, then increment. 15446 EnumVal = LastEnumConst->getInitVal(); 15447 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15448 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15449 ++EnumVal; 15450 15451 // If we're not in C++, diagnose the overflow of enumerator values, 15452 // which in C99 means that the enumerator value is not representable in 15453 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15454 // permits enumerator values that are representable in some larger 15455 // integral type. 15456 if (!getLangOpts().CPlusPlus && !T.isNull()) 15457 Diag(IdLoc, diag::warn_enum_value_overflow); 15458 } else if (!getLangOpts().CPlusPlus && 15459 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15460 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15461 Diag(IdLoc, diag::ext_enum_value_not_int) 15462 << EnumVal.toString(10) << 1; 15463 } 15464 } 15465 } 15466 15467 if (!EltTy->isDependentType()) { 15468 // Make the enumerator value match the signedness and size of the 15469 // enumerator's type. 15470 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15471 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15472 } 15473 15474 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15475 Val, EnumVal); 15476 } 15477 15478 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15479 SourceLocation IILoc) { 15480 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15481 !getLangOpts().CPlusPlus) 15482 return SkipBodyInfo(); 15483 15484 // We have an anonymous enum definition. Look up the first enumerator to 15485 // determine if we should merge the definition with an existing one and 15486 // skip the body. 15487 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15488 ForRedeclaration); 15489 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15490 if (!PrevECD) 15491 return SkipBodyInfo(); 15492 15493 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15494 NamedDecl *Hidden; 15495 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15496 SkipBodyInfo Skip; 15497 Skip.Previous = Hidden; 15498 return Skip; 15499 } 15500 15501 return SkipBodyInfo(); 15502 } 15503 15504 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15505 SourceLocation IdLoc, IdentifierInfo *Id, 15506 AttributeList *Attr, 15507 SourceLocation EqualLoc, Expr *Val) { 15508 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15509 EnumConstantDecl *LastEnumConst = 15510 cast_or_null<EnumConstantDecl>(lastEnumConst); 15511 15512 // The scope passed in may not be a decl scope. Zip up the scope tree until 15513 // we find one that is. 15514 S = getNonFieldDeclScope(S); 15515 15516 // Verify that there isn't already something declared with this name in this 15517 // scope. 15518 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15519 ForRedeclaration); 15520 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15521 // Maybe we will complain about the shadowed template parameter. 15522 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15523 // Just pretend that we didn't see the previous declaration. 15524 PrevDecl = nullptr; 15525 } 15526 15527 // C++ [class.mem]p15: 15528 // If T is the name of a class, then each of the following shall have a name 15529 // different from T: 15530 // - every enumerator of every member of class T that is an unscoped 15531 // enumerated type 15532 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15533 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15534 DeclarationNameInfo(Id, IdLoc)); 15535 15536 EnumConstantDecl *New = 15537 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15538 if (!New) 15539 return nullptr; 15540 15541 if (PrevDecl) { 15542 // When in C++, we may get a TagDecl with the same name; in this case the 15543 // enum constant will 'hide' the tag. 15544 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15545 "Received TagDecl when not in C++!"); 15546 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15547 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15548 if (isa<EnumConstantDecl>(PrevDecl)) 15549 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15550 else 15551 Diag(IdLoc, diag::err_redefinition) << Id; 15552 notePreviousDefinition(PrevDecl, IdLoc); 15553 return nullptr; 15554 } 15555 } 15556 15557 // Process attributes. 15558 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15559 AddPragmaAttributes(S, New); 15560 15561 // Register this decl in the current scope stack. 15562 New->setAccess(TheEnumDecl->getAccess()); 15563 PushOnScopeChains(New, S); 15564 15565 ActOnDocumentableDecl(New); 15566 15567 return New; 15568 } 15569 15570 // Returns true when the enum initial expression does not trigger the 15571 // duplicate enum warning. A few common cases are exempted as follows: 15572 // Element2 = Element1 15573 // Element2 = Element1 + 1 15574 // Element2 = Element1 - 1 15575 // Where Element2 and Element1 are from the same enum. 15576 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15577 Expr *InitExpr = ECD->getInitExpr(); 15578 if (!InitExpr) 15579 return true; 15580 InitExpr = InitExpr->IgnoreImpCasts(); 15581 15582 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15583 if (!BO->isAdditiveOp()) 15584 return true; 15585 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15586 if (!IL) 15587 return true; 15588 if (IL->getValue() != 1) 15589 return true; 15590 15591 InitExpr = BO->getLHS(); 15592 } 15593 15594 // This checks if the elements are from the same enum. 15595 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15596 if (!DRE) 15597 return true; 15598 15599 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15600 if (!EnumConstant) 15601 return true; 15602 15603 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15604 Enum) 15605 return true; 15606 15607 return false; 15608 } 15609 15610 namespace { 15611 struct DupKey { 15612 int64_t val; 15613 bool isTombstoneOrEmptyKey; 15614 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15615 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15616 }; 15617 15618 static DupKey GetDupKey(const llvm::APSInt& Val) { 15619 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15620 false); 15621 } 15622 15623 struct DenseMapInfoDupKey { 15624 static DupKey getEmptyKey() { return DupKey(0, true); } 15625 static DupKey getTombstoneKey() { return DupKey(1, true); } 15626 static unsigned getHashValue(const DupKey Key) { 15627 return (unsigned)(Key.val * 37); 15628 } 15629 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15630 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15631 LHS.val == RHS.val; 15632 } 15633 }; 15634 } // end anonymous namespace 15635 15636 // Emits a warning when an element is implicitly set a value that 15637 // a previous element has already been set to. 15638 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15639 EnumDecl *Enum, 15640 QualType EnumType) { 15641 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15642 return; 15643 // Avoid anonymous enums 15644 if (!Enum->getIdentifier()) 15645 return; 15646 15647 // Only check for small enums. 15648 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15649 return; 15650 15651 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15652 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15653 15654 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15655 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15656 ValueToVectorMap; 15657 15658 DuplicatesVector DupVector; 15659 ValueToVectorMap EnumMap; 15660 15661 // Populate the EnumMap with all values represented by enum constants without 15662 // an initialier. 15663 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15664 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15665 15666 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15667 // this constant. Skip this enum since it may be ill-formed. 15668 if (!ECD) { 15669 return; 15670 } 15671 15672 if (ECD->getInitExpr()) 15673 continue; 15674 15675 DupKey Key = GetDupKey(ECD->getInitVal()); 15676 DeclOrVector &Entry = EnumMap[Key]; 15677 15678 // First time encountering this value. 15679 if (Entry.isNull()) 15680 Entry = ECD; 15681 } 15682 15683 // Create vectors for any values that has duplicates. 15684 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15685 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15686 if (!ValidDuplicateEnum(ECD, Enum)) 15687 continue; 15688 15689 DupKey Key = GetDupKey(ECD->getInitVal()); 15690 15691 DeclOrVector& Entry = EnumMap[Key]; 15692 if (Entry.isNull()) 15693 continue; 15694 15695 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15696 // Ensure constants are different. 15697 if (D == ECD) 15698 continue; 15699 15700 // Create new vector and push values onto it. 15701 ECDVector *Vec = new ECDVector(); 15702 Vec->push_back(D); 15703 Vec->push_back(ECD); 15704 15705 // Update entry to point to the duplicates vector. 15706 Entry = Vec; 15707 15708 // Store the vector somewhere we can consult later for quick emission of 15709 // diagnostics. 15710 DupVector.push_back(Vec); 15711 continue; 15712 } 15713 15714 ECDVector *Vec = Entry.get<ECDVector*>(); 15715 // Make sure constants are not added more than once. 15716 if (*Vec->begin() == ECD) 15717 continue; 15718 15719 Vec->push_back(ECD); 15720 } 15721 15722 // Emit diagnostics. 15723 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15724 DupVectorEnd = DupVector.end(); 15725 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15726 ECDVector *Vec = *DupVectorIter; 15727 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15728 15729 // Emit warning for one enum constant. 15730 ECDVector::iterator I = Vec->begin(); 15731 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15732 << (*I)->getName() << (*I)->getInitVal().toString(10) 15733 << (*I)->getSourceRange(); 15734 ++I; 15735 15736 // Emit one note for each of the remaining enum constants with 15737 // the same value. 15738 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15739 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15740 << (*I)->getName() << (*I)->getInitVal().toString(10) 15741 << (*I)->getSourceRange(); 15742 delete Vec; 15743 } 15744 } 15745 15746 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15747 bool AllowMask) const { 15748 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15749 assert(ED->isCompleteDefinition() && "expected enum definition"); 15750 15751 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15752 llvm::APInt &FlagBits = R.first->second; 15753 15754 if (R.second) { 15755 for (auto *E : ED->enumerators()) { 15756 const auto &EVal = E->getInitVal(); 15757 // Only single-bit enumerators introduce new flag values. 15758 if (EVal.isPowerOf2()) 15759 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15760 } 15761 } 15762 15763 // A value is in a flag enum if either its bits are a subset of the enum's 15764 // flag bits (the first condition) or we are allowing masks and the same is 15765 // true of its complement (the second condition). When masks are allowed, we 15766 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15767 // 15768 // While it's true that any value could be used as a mask, the assumption is 15769 // that a mask will have all of the insignificant bits set. Anything else is 15770 // likely a logic error. 15771 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15772 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15773 } 15774 15775 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15776 Decl *EnumDeclX, 15777 ArrayRef<Decl *> Elements, 15778 Scope *S, AttributeList *Attr) { 15779 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15780 QualType EnumType = Context.getTypeDeclType(Enum); 15781 15782 if (Attr) 15783 ProcessDeclAttributeList(S, Enum, Attr); 15784 15785 if (Enum->isDependentType()) { 15786 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15787 EnumConstantDecl *ECD = 15788 cast_or_null<EnumConstantDecl>(Elements[i]); 15789 if (!ECD) continue; 15790 15791 ECD->setType(EnumType); 15792 } 15793 15794 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15795 return; 15796 } 15797 15798 // TODO: If the result value doesn't fit in an int, it must be a long or long 15799 // long value. ISO C does not support this, but GCC does as an extension, 15800 // emit a warning. 15801 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15802 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15803 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15804 15805 // Verify that all the values are okay, compute the size of the values, and 15806 // reverse the list. 15807 unsigned NumNegativeBits = 0; 15808 unsigned NumPositiveBits = 0; 15809 15810 // Keep track of whether all elements have type int. 15811 bool AllElementsInt = true; 15812 15813 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15814 EnumConstantDecl *ECD = 15815 cast_or_null<EnumConstantDecl>(Elements[i]); 15816 if (!ECD) continue; // Already issued a diagnostic. 15817 15818 const llvm::APSInt &InitVal = ECD->getInitVal(); 15819 15820 // Keep track of the size of positive and negative values. 15821 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15822 NumPositiveBits = std::max(NumPositiveBits, 15823 (unsigned)InitVal.getActiveBits()); 15824 else 15825 NumNegativeBits = std::max(NumNegativeBits, 15826 (unsigned)InitVal.getMinSignedBits()); 15827 15828 // Keep track of whether every enum element has type int (very commmon). 15829 if (AllElementsInt) 15830 AllElementsInt = ECD->getType() == Context.IntTy; 15831 } 15832 15833 // Figure out the type that should be used for this enum. 15834 QualType BestType; 15835 unsigned BestWidth; 15836 15837 // C++0x N3000 [conv.prom]p3: 15838 // An rvalue of an unscoped enumeration type whose underlying 15839 // type is not fixed can be converted to an rvalue of the first 15840 // of the following types that can represent all the values of 15841 // the enumeration: int, unsigned int, long int, unsigned long 15842 // int, long long int, or unsigned long long int. 15843 // C99 6.4.4.3p2: 15844 // An identifier declared as an enumeration constant has type int. 15845 // The C99 rule is modified by a gcc extension 15846 QualType BestPromotionType; 15847 15848 bool Packed = Enum->hasAttr<PackedAttr>(); 15849 // -fshort-enums is the equivalent to specifying the packed attribute on all 15850 // enum definitions. 15851 if (LangOpts.ShortEnums) 15852 Packed = true; 15853 15854 if (Enum->isFixed()) { 15855 BestType = Enum->getIntegerType(); 15856 if (BestType->isPromotableIntegerType()) 15857 BestPromotionType = Context.getPromotedIntegerType(BestType); 15858 else 15859 BestPromotionType = BestType; 15860 15861 BestWidth = Context.getIntWidth(BestType); 15862 } 15863 else if (NumNegativeBits) { 15864 // If there is a negative value, figure out the smallest integer type (of 15865 // int/long/longlong) that fits. 15866 // If it's packed, check also if it fits a char or a short. 15867 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15868 BestType = Context.SignedCharTy; 15869 BestWidth = CharWidth; 15870 } else if (Packed && NumNegativeBits <= ShortWidth && 15871 NumPositiveBits < ShortWidth) { 15872 BestType = Context.ShortTy; 15873 BestWidth = ShortWidth; 15874 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15875 BestType = Context.IntTy; 15876 BestWidth = IntWidth; 15877 } else { 15878 BestWidth = Context.getTargetInfo().getLongWidth(); 15879 15880 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15881 BestType = Context.LongTy; 15882 } else { 15883 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15884 15885 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15886 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15887 BestType = Context.LongLongTy; 15888 } 15889 } 15890 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15891 } else { 15892 // If there is no negative value, figure out the smallest type that fits 15893 // all of the enumerator values. 15894 // If it's packed, check also if it fits a char or a short. 15895 if (Packed && NumPositiveBits <= CharWidth) { 15896 BestType = Context.UnsignedCharTy; 15897 BestPromotionType = Context.IntTy; 15898 BestWidth = CharWidth; 15899 } else if (Packed && NumPositiveBits <= ShortWidth) { 15900 BestType = Context.UnsignedShortTy; 15901 BestPromotionType = Context.IntTy; 15902 BestWidth = ShortWidth; 15903 } else if (NumPositiveBits <= IntWidth) { 15904 BestType = Context.UnsignedIntTy; 15905 BestWidth = IntWidth; 15906 BestPromotionType 15907 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15908 ? Context.UnsignedIntTy : Context.IntTy; 15909 } else if (NumPositiveBits <= 15910 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15911 BestType = Context.UnsignedLongTy; 15912 BestPromotionType 15913 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15914 ? Context.UnsignedLongTy : Context.LongTy; 15915 } else { 15916 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15917 assert(NumPositiveBits <= BestWidth && 15918 "How could an initializer get larger than ULL?"); 15919 BestType = Context.UnsignedLongLongTy; 15920 BestPromotionType 15921 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15922 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15923 } 15924 } 15925 15926 // Loop over all of the enumerator constants, changing their types to match 15927 // the type of the enum if needed. 15928 for (auto *D : Elements) { 15929 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15930 if (!ECD) continue; // Already issued a diagnostic. 15931 15932 // Standard C says the enumerators have int type, but we allow, as an 15933 // extension, the enumerators to be larger than int size. If each 15934 // enumerator value fits in an int, type it as an int, otherwise type it the 15935 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15936 // that X has type 'int', not 'unsigned'. 15937 15938 // Determine whether the value fits into an int. 15939 llvm::APSInt InitVal = ECD->getInitVal(); 15940 15941 // If it fits into an integer type, force it. Otherwise force it to match 15942 // the enum decl type. 15943 QualType NewTy; 15944 unsigned NewWidth; 15945 bool NewSign; 15946 if (!getLangOpts().CPlusPlus && 15947 !Enum->isFixed() && 15948 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15949 NewTy = Context.IntTy; 15950 NewWidth = IntWidth; 15951 NewSign = true; 15952 } else if (ECD->getType() == BestType) { 15953 // Already the right type! 15954 if (getLangOpts().CPlusPlus) 15955 // C++ [dcl.enum]p4: Following the closing brace of an 15956 // enum-specifier, each enumerator has the type of its 15957 // enumeration. 15958 ECD->setType(EnumType); 15959 continue; 15960 } else { 15961 NewTy = BestType; 15962 NewWidth = BestWidth; 15963 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15964 } 15965 15966 // Adjust the APSInt value. 15967 InitVal = InitVal.extOrTrunc(NewWidth); 15968 InitVal.setIsSigned(NewSign); 15969 ECD->setInitVal(InitVal); 15970 15971 // Adjust the Expr initializer and type. 15972 if (ECD->getInitExpr() && 15973 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15974 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15975 CK_IntegralCast, 15976 ECD->getInitExpr(), 15977 /*base paths*/ nullptr, 15978 VK_RValue)); 15979 if (getLangOpts().CPlusPlus) 15980 // C++ [dcl.enum]p4: Following the closing brace of an 15981 // enum-specifier, each enumerator has the type of its 15982 // enumeration. 15983 ECD->setType(EnumType); 15984 else 15985 ECD->setType(NewTy); 15986 } 15987 15988 Enum->completeDefinition(BestType, BestPromotionType, 15989 NumPositiveBits, NumNegativeBits); 15990 15991 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15992 15993 if (Enum->isClosedFlag()) { 15994 for (Decl *D : Elements) { 15995 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15996 if (!ECD) continue; // Already issued a diagnostic. 15997 15998 llvm::APSInt InitVal = ECD->getInitVal(); 15999 if (InitVal != 0 && !InitVal.isPowerOf2() && 16000 !IsValueInFlagEnum(Enum, InitVal, true)) 16001 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16002 << ECD << Enum; 16003 } 16004 } 16005 16006 // Now that the enum type is defined, ensure it's not been underaligned. 16007 if (Enum->hasAttrs()) 16008 CheckAlignasUnderalignment(Enum); 16009 } 16010 16011 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16012 SourceLocation StartLoc, 16013 SourceLocation EndLoc) { 16014 StringLiteral *AsmString = cast<StringLiteral>(expr); 16015 16016 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16017 AsmString, StartLoc, 16018 EndLoc); 16019 CurContext->addDecl(New); 16020 return New; 16021 } 16022 16023 static void checkModuleImportContext(Sema &S, Module *M, 16024 SourceLocation ImportLoc, DeclContext *DC, 16025 bool FromInclude = false) { 16026 SourceLocation ExternCLoc; 16027 16028 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16029 switch (LSD->getLanguage()) { 16030 case LinkageSpecDecl::lang_c: 16031 if (ExternCLoc.isInvalid()) 16032 ExternCLoc = LSD->getLocStart(); 16033 break; 16034 case LinkageSpecDecl::lang_cxx: 16035 break; 16036 } 16037 DC = LSD->getParent(); 16038 } 16039 16040 while (isa<LinkageSpecDecl>(DC)) 16041 DC = DC->getParent(); 16042 16043 if (!isa<TranslationUnitDecl>(DC)) { 16044 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16045 ? diag::ext_module_import_not_at_top_level_noop 16046 : diag::err_module_import_not_at_top_level_fatal) 16047 << M->getFullModuleName() << DC; 16048 S.Diag(cast<Decl>(DC)->getLocStart(), 16049 diag::note_module_import_not_at_top_level) << DC; 16050 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16051 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16052 << M->getFullModuleName(); 16053 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16054 } 16055 } 16056 16057 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16058 SourceLocation ModuleLoc, 16059 ModuleDeclKind MDK, 16060 ModuleIdPath Path) { 16061 assert(getLangOpts().ModulesTS && 16062 "should only have module decl in modules TS"); 16063 16064 // A module implementation unit requires that we are not compiling a module 16065 // of any kind. A module interface unit requires that we are not compiling a 16066 // module map. 16067 switch (getLangOpts().getCompilingModule()) { 16068 case LangOptions::CMK_None: 16069 // It's OK to compile a module interface as a normal translation unit. 16070 break; 16071 16072 case LangOptions::CMK_ModuleInterface: 16073 if (MDK != ModuleDeclKind::Implementation) 16074 break; 16075 16076 // We were asked to compile a module interface unit but this is a module 16077 // implementation unit. That indicates the 'export' is missing. 16078 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16079 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16080 break; 16081 16082 case LangOptions::CMK_ModuleMap: 16083 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16084 return nullptr; 16085 } 16086 16087 // FIXME: Most of this work should be done by the preprocessor rather than 16088 // here, in order to support macro import. 16089 16090 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16091 // modules, the dots here are just another character that can appear in a 16092 // module name. 16093 std::string ModuleName; 16094 for (auto &Piece : Path) { 16095 if (!ModuleName.empty()) 16096 ModuleName += "."; 16097 ModuleName += Piece.first->getName(); 16098 } 16099 16100 // FIXME: If we've already seen a module-declaration, report an error. 16101 16102 // If a module name was explicitly specified on the command line, it must be 16103 // correct. 16104 if (!getLangOpts().CurrentModule.empty() && 16105 getLangOpts().CurrentModule != ModuleName) { 16106 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16107 << SourceRange(Path.front().second, Path.back().second) 16108 << getLangOpts().CurrentModule; 16109 return nullptr; 16110 } 16111 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16112 16113 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16114 Module *Mod; 16115 16116 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16117 16118 switch (MDK) { 16119 case ModuleDeclKind::Module: { 16120 // We can't have parsed or imported a definition of this module or parsed a 16121 // module map defining it already. 16122 if (auto *M = Map.findModule(ModuleName)) { 16123 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16124 if (M->DefinitionLoc.isValid()) 16125 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16126 else if (const auto *FE = M->getASTFile()) 16127 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16128 << FE->getName(); 16129 return nullptr; 16130 } 16131 16132 // Create a Module for the module that we're defining. 16133 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16134 ModuleScopes.front().Module); 16135 assert(Mod && "module creation should not fail"); 16136 break; 16137 } 16138 16139 case ModuleDeclKind::Partition: 16140 // FIXME: Check we are in a submodule of the named module. 16141 return nullptr; 16142 16143 case ModuleDeclKind::Implementation: 16144 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16145 PP.getIdentifierInfo(ModuleName), Path[0].second); 16146 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16147 /*IsIncludeDirective=*/false); 16148 if (!Mod) 16149 return nullptr; 16150 break; 16151 } 16152 16153 // Switch from the global module to the named module. 16154 ModuleScopes.back().Module = Mod; 16155 VisibleModules.setVisible(Mod, ModuleLoc); 16156 16157 // From now on, we have an owning module for all declarations we see. 16158 // However, those declarations are module-private unless explicitly 16159 // exported. 16160 auto *TU = Context.getTranslationUnitDecl(); 16161 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16162 TU->setLocalOwningModule(Mod); 16163 16164 // FIXME: Create a ModuleDecl. 16165 return nullptr; 16166 } 16167 16168 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16169 SourceLocation ImportLoc, 16170 ModuleIdPath Path) { 16171 Module *Mod = 16172 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16173 /*IsIncludeDirective=*/false); 16174 if (!Mod) 16175 return true; 16176 16177 VisibleModules.setVisible(Mod, ImportLoc); 16178 16179 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16180 16181 // FIXME: we should support importing a submodule within a different submodule 16182 // of the same top-level module. Until we do, make it an error rather than 16183 // silently ignoring the import. 16184 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16185 // warn on a redundant import of the current module? 16186 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16187 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16188 Diag(ImportLoc, getLangOpts().isCompilingModule() 16189 ? diag::err_module_self_import 16190 : diag::err_module_import_in_implementation) 16191 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16192 16193 SmallVector<SourceLocation, 2> IdentifierLocs; 16194 Module *ModCheck = Mod; 16195 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16196 // If we've run out of module parents, just drop the remaining identifiers. 16197 // We need the length to be consistent. 16198 if (!ModCheck) 16199 break; 16200 ModCheck = ModCheck->Parent; 16201 16202 IdentifierLocs.push_back(Path[I].second); 16203 } 16204 16205 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16206 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 16207 Mod, IdentifierLocs); 16208 if (!ModuleScopes.empty()) 16209 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16210 TU->addDecl(Import); 16211 return Import; 16212 } 16213 16214 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16215 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16216 BuildModuleInclude(DirectiveLoc, Mod); 16217 } 16218 16219 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16220 // Determine whether we're in the #include buffer for a module. The #includes 16221 // in that buffer do not qualify as module imports; they're just an 16222 // implementation detail of us building the module. 16223 // 16224 // FIXME: Should we even get ActOnModuleInclude calls for those? 16225 bool IsInModuleIncludes = 16226 TUKind == TU_Module && 16227 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16228 16229 bool ShouldAddImport = !IsInModuleIncludes; 16230 16231 // If this module import was due to an inclusion directive, create an 16232 // implicit import declaration to capture it in the AST. 16233 if (ShouldAddImport) { 16234 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16235 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16236 DirectiveLoc, Mod, 16237 DirectiveLoc); 16238 if (!ModuleScopes.empty()) 16239 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16240 TU->addDecl(ImportD); 16241 Consumer.HandleImplicitImportDecl(ImportD); 16242 } 16243 16244 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16245 VisibleModules.setVisible(Mod, DirectiveLoc); 16246 } 16247 16248 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16249 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16250 16251 ModuleScopes.push_back({}); 16252 ModuleScopes.back().Module = Mod; 16253 if (getLangOpts().ModulesLocalVisibility) 16254 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16255 16256 VisibleModules.setVisible(Mod, DirectiveLoc); 16257 16258 // The enclosing context is now part of this module. 16259 // FIXME: Consider creating a child DeclContext to hold the entities 16260 // lexically within the module. 16261 if (getLangOpts().trackLocalOwningModule()) { 16262 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16263 cast<Decl>(DC)->setModuleOwnershipKind( 16264 getLangOpts().ModulesLocalVisibility 16265 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16266 : Decl::ModuleOwnershipKind::Visible); 16267 cast<Decl>(DC)->setLocalOwningModule(Mod); 16268 } 16269 } 16270 } 16271 16272 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16273 if (getLangOpts().ModulesLocalVisibility) { 16274 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16275 // Leaving a module hides namespace names, so our visible namespace cache 16276 // is now out of date. 16277 VisibleNamespaceCache.clear(); 16278 } 16279 16280 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16281 "left the wrong module scope"); 16282 ModuleScopes.pop_back(); 16283 16284 // We got to the end of processing a local module. Create an 16285 // ImportDecl as we would for an imported module. 16286 FileID File = getSourceManager().getFileID(EomLoc); 16287 SourceLocation DirectiveLoc; 16288 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16289 // We reached the end of a #included module header. Use the #include loc. 16290 assert(File != getSourceManager().getMainFileID() && 16291 "end of submodule in main source file"); 16292 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16293 } else { 16294 // We reached an EOM pragma. Use the pragma location. 16295 DirectiveLoc = EomLoc; 16296 } 16297 BuildModuleInclude(DirectiveLoc, Mod); 16298 16299 // Any further declarations are in whatever module we returned to. 16300 if (getLangOpts().trackLocalOwningModule()) { 16301 // The parser guarantees that this is the same context that we entered 16302 // the module within. 16303 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16304 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16305 if (!getCurrentModule()) 16306 cast<Decl>(DC)->setModuleOwnershipKind( 16307 Decl::ModuleOwnershipKind::Unowned); 16308 } 16309 } 16310 } 16311 16312 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16313 Module *Mod) { 16314 // Bail if we're not allowed to implicitly import a module here. 16315 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16316 VisibleModules.isVisible(Mod)) 16317 return; 16318 16319 // Create the implicit import declaration. 16320 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16321 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16322 Loc, Mod, Loc); 16323 TU->addDecl(ImportD); 16324 Consumer.HandleImplicitImportDecl(ImportD); 16325 16326 // Make the module visible. 16327 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16328 VisibleModules.setVisible(Mod, Loc); 16329 } 16330 16331 /// We have parsed the start of an export declaration, including the '{' 16332 /// (if present). 16333 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16334 SourceLocation LBraceLoc) { 16335 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16336 16337 // C++ Modules TS draft: 16338 // An export-declaration shall appear in the purview of a module other than 16339 // the global module. 16340 if (ModuleScopes.empty() || 16341 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16342 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16343 16344 // An export-declaration [...] shall not contain more than one 16345 // export keyword. 16346 // 16347 // The intent here is that an export-declaration cannot appear within another 16348 // export-declaration. 16349 if (D->isExported()) 16350 Diag(ExportLoc, diag::err_export_within_export); 16351 16352 CurContext->addDecl(D); 16353 PushDeclContext(S, D); 16354 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16355 return D; 16356 } 16357 16358 /// Complete the definition of an export declaration. 16359 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16360 auto *ED = cast<ExportDecl>(D); 16361 if (RBraceLoc.isValid()) 16362 ED->setRBraceLoc(RBraceLoc); 16363 16364 // FIXME: Diagnose export of internal-linkage declaration (including 16365 // anonymous namespace). 16366 16367 PopDeclContext(); 16368 return D; 16369 } 16370 16371 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16372 IdentifierInfo* AliasName, 16373 SourceLocation PragmaLoc, 16374 SourceLocation NameLoc, 16375 SourceLocation AliasNameLoc) { 16376 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16377 LookupOrdinaryName); 16378 AsmLabelAttr *Attr = 16379 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16380 16381 // If a declaration that: 16382 // 1) declares a function or a variable 16383 // 2) has external linkage 16384 // already exists, add a label attribute to it. 16385 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16386 if (isDeclExternC(PrevDecl)) 16387 PrevDecl->addAttr(Attr); 16388 else 16389 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16390 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16391 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16392 } else 16393 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16394 } 16395 16396 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16397 SourceLocation PragmaLoc, 16398 SourceLocation NameLoc) { 16399 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16400 16401 if (PrevDecl) { 16402 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16403 } else { 16404 (void)WeakUndeclaredIdentifiers.insert( 16405 std::pair<IdentifierInfo*,WeakInfo> 16406 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16407 } 16408 } 16409 16410 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16411 IdentifierInfo* AliasName, 16412 SourceLocation PragmaLoc, 16413 SourceLocation NameLoc, 16414 SourceLocation AliasNameLoc) { 16415 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16416 LookupOrdinaryName); 16417 WeakInfo W = WeakInfo(Name, NameLoc); 16418 16419 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16420 if (!PrevDecl->hasAttr<AliasAttr>()) 16421 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16422 DeclApplyPragmaWeak(TUScope, ND, W); 16423 } else { 16424 (void)WeakUndeclaredIdentifiers.insert( 16425 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16426 } 16427 } 16428 16429 Decl *Sema::getObjCDeclContext() const { 16430 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16431 } 16432