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___float128: 136 case tok::kw_wchar_t: 137 case tok::kw_bool: 138 case tok::kw___underlying_type: 139 case tok::kw___auto_type: 140 return true; 141 142 case tok::annot_typename: 143 case tok::kw_char16_t: 144 case tok::kw_char32_t: 145 case tok::kw_typeof: 146 case tok::annot_decltype: 147 case tok::kw_decltype: 148 return getLangOpts().CPlusPlus; 149 150 default: 151 break; 152 } 153 154 return false; 155 } 156 157 namespace { 158 enum class UnqualifiedTypeNameLookupResult { 159 NotFound, 160 FoundNonType, 161 FoundType 162 }; 163 } // end anonymous namespace 164 165 /// \brief Tries to perform unqualified lookup of the type decls in bases for 166 /// dependent class. 167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 168 /// type decl, \a FoundType if only type decls are found. 169 static UnqualifiedTypeNameLookupResult 170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 171 SourceLocation NameLoc, 172 const CXXRecordDecl *RD) { 173 if (!RD->hasDefinition()) 174 return UnqualifiedTypeNameLookupResult::NotFound; 175 // Look for type decls in base classes. 176 UnqualifiedTypeNameLookupResult FoundTypeDecl = 177 UnqualifiedTypeNameLookupResult::NotFound; 178 for (const auto &Base : RD->bases()) { 179 const CXXRecordDecl *BaseRD = nullptr; 180 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 181 BaseRD = BaseTT->getAsCXXRecordDecl(); 182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 183 // Look for type decls in dependent base classes that have known primary 184 // templates. 185 if (!TST || !TST->isDependentType()) 186 continue; 187 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 188 if (!TD) 189 continue; 190 if (auto *BasePrimaryTemplate = 191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 193 BaseRD = BasePrimaryTemplate; 194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 195 if (const ClassTemplatePartialSpecializationDecl *PS = 196 CTD->findPartialSpecialization(Base.getType())) 197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 198 BaseRD = PS; 199 } 200 } 201 } 202 if (BaseRD) { 203 for (NamedDecl *ND : BaseRD->lookup(&II)) { 204 if (!isa<TypeDecl>(ND)) 205 return UnqualifiedTypeNameLookupResult::FoundNonType; 206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 207 } 208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 210 case UnqualifiedTypeNameLookupResult::FoundNonType: 211 return UnqualifiedTypeNameLookupResult::FoundNonType; 212 case UnqualifiedTypeNameLookupResult::FoundType: 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 break; 215 case UnqualifiedTypeNameLookupResult::NotFound: 216 break; 217 } 218 } 219 } 220 } 221 222 return FoundTypeDecl; 223 } 224 225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 226 const IdentifierInfo &II, 227 SourceLocation NameLoc) { 228 // Lookup in the parent class template context, if any. 229 const CXXRecordDecl *RD = nullptr; 230 UnqualifiedTypeNameLookupResult FoundTypeDecl = 231 UnqualifiedTypeNameLookupResult::NotFound; 232 for (DeclContext *DC = S.CurContext; 233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 234 DC = DC->getParent()) { 235 // Look for type decls in dependent base classes that have known primary 236 // templates. 237 RD = dyn_cast<CXXRecordDecl>(DC); 238 if (RD && RD->getDescribedClassTemplate()) 239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 240 } 241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 242 return nullptr; 243 244 // We found some types in dependent base classes. Recover as if the user 245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 246 // lookup during template instantiation. 247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 248 249 ASTContext &Context = S.Context; 250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 251 cast<Type>(Context.getRecordType(RD))); 252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 253 254 CXXScopeSpec SS; 255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 256 257 TypeLocBuilder Builder; 258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 259 DepTL.setNameLoc(NameLoc); 260 DepTL.setElaboratedKeywordLoc(SourceLocation()); 261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263 } 264 265 /// \brief If the identifier refers to a type name within this scope, 266 /// return the declaration of that type. 267 /// 268 /// This routine performs ordinary name lookup of the identifier II 269 /// within the given scope, with optional C++ scope specifier SS, to 270 /// determine whether the name refers to a type. If so, returns an 271 /// opaque pointer (actually a QualType) corresponding to that 272 /// type. Otherwise, returns NULL. 273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 274 Scope *S, CXXScopeSpec *SS, 275 bool isClassName, bool HasTrailingDot, 276 ParsedType ObjectTypePtr, 277 bool IsCtorOrDtorName, 278 bool WantNontrivialTypeSourceInfo, 279 bool IsClassTemplateDeductionContext, 280 IdentifierInfo **CorrectedII) { 281 // FIXME: Consider allowing this outside C++1z mode as an extension. 282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 284 !isClassName && !HasTrailingDot; 285 286 // Determine where we will perform name lookup. 287 DeclContext *LookupCtx = nullptr; 288 if (ObjectTypePtr) { 289 QualType ObjectType = ObjectTypePtr.get(); 290 if (ObjectType->isRecordType()) 291 LookupCtx = computeDeclContext(ObjectType); 292 } else if (SS && SS->isNotEmpty()) { 293 LookupCtx = computeDeclContext(*SS, false); 294 295 if (!LookupCtx) { 296 if (isDependentScopeSpecifier(*SS)) { 297 // C++ [temp.res]p3: 298 // A qualified-id that refers to a type and in which the 299 // nested-name-specifier depends on a template-parameter (14.6.2) 300 // shall be prefixed by the keyword typename to indicate that the 301 // qualified-id denotes a type, forming an 302 // elaborated-type-specifier (7.1.5.3). 303 // 304 // We therefore do not perform any name lookup if the result would 305 // refer to a member of an unknown specialization. 306 if (!isClassName && !IsCtorOrDtorName) 307 return nullptr; 308 309 // We know from the grammar that this name refers to a type, 310 // so build a dependent node to describe the type. 311 if (WantNontrivialTypeSourceInfo) 312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 313 314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 316 II, NameLoc); 317 return ParsedType::make(T); 318 } 319 320 return nullptr; 321 } 322 323 if (!LookupCtx->isDependentContext() && 324 RequireCompleteDeclContext(*SS, LookupCtx)) 325 return nullptr; 326 } 327 328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 329 // lookup for class-names. 330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 331 LookupOrdinaryName; 332 LookupResult Result(*this, &II, NameLoc, Kind); 333 if (LookupCtx) { 334 // Perform "qualified" name lookup into the declaration context we 335 // computed, which is either the type of the base of a member access 336 // expression or the declaration context associated with a prior 337 // nested-name-specifier. 338 LookupQualifiedName(Result, LookupCtx); 339 340 if (ObjectTypePtr && Result.empty()) { 341 // C++ [basic.lookup.classref]p3: 342 // If the unqualified-id is ~type-name, the type-name is looked up 343 // in the context of the entire postfix-expression. If the type T of 344 // the object expression is of a class type C, the type-name is also 345 // looked up in the scope of class C. At least one of the lookups shall 346 // find a name that refers to (possibly cv-qualified) T. 347 LookupName(Result, S); 348 } 349 } else { 350 // Perform unqualified name lookup. 351 LookupName(Result, S); 352 353 // For unqualified lookup in a class template in MSVC mode, look into 354 // dependent base classes where the primary class template is known. 355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 356 if (ParsedType TypeInBase = 357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 358 return TypeInBase; 359 } 360 } 361 362 NamedDecl *IIDecl = nullptr; 363 switch (Result.getResultKind()) { 364 case LookupResult::NotFound: 365 case LookupResult::NotFoundInCurrentInstantiation: 366 if (CorrectedII) { 367 TypoCorrection Correction = 368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 369 llvm::make_unique<TypeNameValidatorCCC>( 370 true, isClassName, AllowDeducedTemplate), 371 CTK_ErrorRecovery); 372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 373 TemplateTy Template; 374 bool MemberOfUnknownSpecialization; 375 UnqualifiedId TemplateName; 376 TemplateName.setIdentifier(NewII, NameLoc); 377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 378 CXXScopeSpec NewSS, *NewSSPtr = SS; 379 if (SS && NNS) { 380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 381 NewSSPtr = &NewSS; 382 } 383 if (Correction && (NNS || NewII != &II) && 384 // Ignore a correction to a template type as the to-be-corrected 385 // identifier is not a template (typo correction for template names 386 // is handled elsewhere). 387 !(getLangOpts().CPlusPlus && NewSSPtr && 388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 389 Template, MemberOfUnknownSpecialization))) { 390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 391 isClassName, HasTrailingDot, ObjectTypePtr, 392 IsCtorOrDtorName, 393 WantNontrivialTypeSourceInfo, 394 IsClassTemplateDeductionContext); 395 if (Ty) { 396 diagnoseTypo(Correction, 397 PDiag(diag::err_unknown_type_or_class_name_suggest) 398 << Result.getLookupName() << isClassName); 399 if (SS && NNS) 400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 401 *CorrectedII = NewII; 402 return Ty; 403 } 404 } 405 } 406 // If typo correction failed or was not performed, fall through 407 LLVM_FALLTHROUGH; 408 case LookupResult::FoundOverloaded: 409 case LookupResult::FoundUnresolvedValue: 410 Result.suppressDiagnostics(); 411 return nullptr; 412 413 case LookupResult::Ambiguous: 414 // Recover from type-hiding ambiguities by hiding the type. We'll 415 // do the lookup again when looking for an object, and we can 416 // diagnose the error then. If we don't do this, then the error 417 // about hiding the type will be immediately followed by an error 418 // that only makes sense if the identifier was treated like a type. 419 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 420 Result.suppressDiagnostics(); 421 return nullptr; 422 } 423 424 // Look to see if we have a type anywhere in the list of results. 425 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 426 Res != ResEnd; ++Res) { 427 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 428 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 429 if (!IIDecl || 430 (*Res)->getLocation().getRawEncoding() < 431 IIDecl->getLocation().getRawEncoding()) 432 IIDecl = *Res; 433 } 434 } 435 436 if (!IIDecl) { 437 // None of the entities we found is a type, so there is no way 438 // to even assume that the result is a type. In this case, don't 439 // complain about the ambiguity. The parser will either try to 440 // perform this lookup again (e.g., as an object name), which 441 // will produce the ambiguity, or will complain that it expected 442 // a type name. 443 Result.suppressDiagnostics(); 444 return nullptr; 445 } 446 447 // We found a type within the ambiguous lookup; diagnose the 448 // ambiguity and then return that type. This might be the right 449 // answer, or it might not be, but it suppresses any attempt to 450 // perform the name lookup again. 451 break; 452 453 case LookupResult::Found: 454 IIDecl = Result.getFoundDecl(); 455 break; 456 } 457 458 assert(IIDecl && "Didn't find decl"); 459 460 QualType T; 461 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 462 // C++ [class.qual]p2: A lookup that would find the injected-class-name 463 // instead names the constructors of the class, except when naming a class. 464 // This is ill-formed when we're not actually forming a ctor or dtor name. 465 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 466 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 467 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 468 FoundRD->isInjectedClassName() && 469 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 470 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 471 << &II << /*Type*/1; 472 473 DiagnoseUseOfDecl(IIDecl, NameLoc); 474 475 T = Context.getTypeDeclType(TD); 476 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 477 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 478 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 479 if (!HasTrailingDot) 480 T = Context.getObjCInterfaceType(IDecl); 481 } else if (AllowDeducedTemplate) { 482 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 483 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 484 QualType(), false); 485 } 486 487 if (T.isNull()) { 488 // If it's not plausibly a type, suppress diagnostics. 489 Result.suppressDiagnostics(); 490 return nullptr; 491 } 492 493 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 494 // constructor or destructor name (in such a case, the scope specifier 495 // will be attached to the enclosing Expr or Decl node). 496 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 497 !isa<ObjCInterfaceDecl>(IIDecl)) { 498 if (WantNontrivialTypeSourceInfo) { 499 // Construct a type with type-source information. 500 TypeLocBuilder Builder; 501 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 502 503 T = getElaboratedType(ETK_None, *SS, T); 504 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 505 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 506 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 507 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 508 } else { 509 T = getElaboratedType(ETK_None, *SS, T); 510 } 511 } 512 513 return ParsedType::make(T); 514 } 515 516 // Builds a fake NNS for the given decl context. 517 static NestedNameSpecifier * 518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 519 for (;; DC = DC->getLookupParent()) { 520 DC = DC->getPrimaryContext(); 521 auto *ND = dyn_cast<NamespaceDecl>(DC); 522 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 523 return NestedNameSpecifier::Create(Context, nullptr, ND); 524 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 525 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 526 RD->getTypeForDecl()); 527 else if (isa<TranslationUnitDecl>(DC)) 528 return NestedNameSpecifier::GlobalSpecifier(Context); 529 } 530 llvm_unreachable("something isn't in TU scope?"); 531 } 532 533 /// Find the parent class with dependent bases of the innermost enclosing method 534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 535 /// up allowing unqualified dependent type names at class-level, which MSVC 536 /// correctly rejects. 537 static const CXXRecordDecl * 538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 539 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 540 DC = DC->getPrimaryContext(); 541 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 542 if (MD->getParent()->hasAnyDependentBases()) 543 return MD->getParent(); 544 } 545 return nullptr; 546 } 547 548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 549 SourceLocation NameLoc, 550 bool IsTemplateTypeArg) { 551 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 552 553 NestedNameSpecifier *NNS = nullptr; 554 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 555 // If we weren't able to parse a default template argument, delay lookup 556 // until instantiation time by making a non-dependent DependentTypeName. We 557 // pretend we saw a NestedNameSpecifier referring to the current scope, and 558 // lookup is retried. 559 // FIXME: This hurts our diagnostic quality, since we get errors like "no 560 // type named 'Foo' in 'current_namespace'" when the user didn't write any 561 // name specifiers. 562 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 563 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 564 } else if (const CXXRecordDecl *RD = 565 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 566 // Build a DependentNameType that will perform lookup into RD at 567 // instantiation time. 568 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 569 RD->getTypeForDecl()); 570 571 // Diagnose that this identifier was undeclared, and retry the lookup during 572 // template instantiation. 573 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 574 << RD; 575 } else { 576 // This is not a situation that we should recover from. 577 return ParsedType(); 578 } 579 580 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 581 582 // Build type location information. We synthesized the qualifier, so we have 583 // to build a fake NestedNameSpecifierLoc. 584 NestedNameSpecifierLocBuilder NNSLocBuilder; 585 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 586 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 587 588 TypeLocBuilder Builder; 589 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 590 DepTL.setNameLoc(NameLoc); 591 DepTL.setElaboratedKeywordLoc(SourceLocation()); 592 DepTL.setQualifierLoc(QualifierLoc); 593 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 594 } 595 596 /// isTagName() - This method is called *for error recovery purposes only* 597 /// to determine if the specified name is a valid tag name ("struct foo"). If 598 /// so, this returns the TST for the tag corresponding to it (TST_enum, 599 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 600 /// cases in C where the user forgot to specify the tag. 601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 602 // Do a tag name lookup in this scope. 603 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 604 LookupName(R, S, false); 605 R.suppressDiagnostics(); 606 if (R.getResultKind() == LookupResult::Found) 607 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 608 switch (TD->getTagKind()) { 609 case TTK_Struct: return DeclSpec::TST_struct; 610 case TTK_Interface: return DeclSpec::TST_interface; 611 case TTK_Union: return DeclSpec::TST_union; 612 case TTK_Class: return DeclSpec::TST_class; 613 case TTK_Enum: return DeclSpec::TST_enum; 614 } 615 } 616 617 return DeclSpec::TST_unspecified; 618 } 619 620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 622 /// then downgrade the missing typename error to a warning. 623 /// This is needed for MSVC compatibility; Example: 624 /// @code 625 /// template<class T> class A { 626 /// public: 627 /// typedef int TYPE; 628 /// }; 629 /// template<class T> class B : public A<T> { 630 /// public: 631 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 632 /// }; 633 /// @endcode 634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 635 if (CurContext->isRecord()) { 636 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 637 return true; 638 639 const Type *Ty = SS->getScopeRep()->getAsType(); 640 641 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 642 for (const auto &Base : RD->bases()) 643 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 644 return true; 645 return S->isFunctionPrototypeScope(); 646 } 647 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 648 } 649 650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 651 SourceLocation IILoc, 652 Scope *S, 653 CXXScopeSpec *SS, 654 ParsedType &SuggestedType, 655 bool IsTemplateName) { 656 // Don't report typename errors for editor placeholders. 657 if (II->isEditorPlaceholder()) 658 return; 659 // We don't have anything to suggest (yet). 660 SuggestedType = nullptr; 661 662 // There may have been a typo in the name of the type. Look up typo 663 // results, in case we have something that we can suggest. 664 if (TypoCorrection Corrected = 665 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 666 llvm::make_unique<TypeNameValidatorCCC>( 667 false, false, IsTemplateName, !IsTemplateName), 668 CTK_ErrorRecovery)) { 669 // FIXME: Support error recovery for the template-name case. 670 bool CanRecover = !IsTemplateName; 671 if (Corrected.isKeyword()) { 672 // We corrected to a keyword. 673 diagnoseTypo(Corrected, 674 PDiag(IsTemplateName ? diag::err_no_template_suggest 675 : diag::err_unknown_typename_suggest) 676 << II); 677 II = Corrected.getCorrectionAsIdentifierInfo(); 678 } else { 679 // We found a similarly-named type or interface; suggest that. 680 if (!SS || !SS->isSet()) { 681 diagnoseTypo(Corrected, 682 PDiag(IsTemplateName ? diag::err_no_template_suggest 683 : diag::err_unknown_typename_suggest) 684 << II, CanRecover); 685 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 686 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 687 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 688 II->getName().equals(CorrectedStr); 689 diagnoseTypo(Corrected, 690 PDiag(IsTemplateName 691 ? diag::err_no_member_template_suggest 692 : diag::err_unknown_nested_typename_suggest) 693 << II << DC << DroppedSpecifier << SS->getRange(), 694 CanRecover); 695 } else { 696 llvm_unreachable("could not have corrected a typo here"); 697 } 698 699 if (!CanRecover) 700 return; 701 702 CXXScopeSpec tmpSS; 703 if (Corrected.getCorrectionSpecifier()) 704 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 705 SourceRange(IILoc)); 706 // FIXME: Support class template argument deduction here. 707 SuggestedType = 708 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 709 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 710 /*IsCtorOrDtorName=*/false, 711 /*NonTrivialTypeSourceInfo=*/true); 712 } 713 return; 714 } 715 716 if (getLangOpts().CPlusPlus && !IsTemplateName) { 717 // See if II is a class template that the user forgot to pass arguments to. 718 UnqualifiedId Name; 719 Name.setIdentifier(II, IILoc); 720 CXXScopeSpec EmptySS; 721 TemplateTy TemplateResult; 722 bool MemberOfUnknownSpecialization; 723 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 724 Name, nullptr, true, TemplateResult, 725 MemberOfUnknownSpecialization) == TNK_Type_template) { 726 TemplateName TplName = TemplateResult.get(); 727 Diag(IILoc, diag::err_template_missing_args) 728 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 729 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 730 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 731 << TplDecl->getTemplateParameters()->getSourceRange(); 732 } 733 return; 734 } 735 } 736 737 // FIXME: Should we move the logic that tries to recover from a missing tag 738 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 739 740 if (!SS || (!SS->isSet() && !SS->isInvalid())) 741 Diag(IILoc, IsTemplateName ? diag::err_no_template 742 : diag::err_unknown_typename) 743 << II; 744 else if (DeclContext *DC = computeDeclContext(*SS, false)) 745 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 746 : diag::err_typename_nested_not_found) 747 << II << DC << SS->getRange(); 748 else if (isDependentScopeSpecifier(*SS)) { 749 unsigned DiagID = diag::err_typename_missing; 750 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 751 DiagID = diag::ext_typename_missing; 752 753 Diag(SS->getRange().getBegin(), DiagID) 754 << SS->getScopeRep() << II->getName() 755 << SourceRange(SS->getRange().getBegin(), IILoc) 756 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 757 SuggestedType = ActOnTypenameType(S, SourceLocation(), 758 *SS, *II, IILoc).get(); 759 } else { 760 assert(SS && SS->isInvalid() && 761 "Invalid scope specifier has already been diagnosed"); 762 } 763 } 764 765 /// \brief Determine whether the given result set contains either a type name 766 /// or 767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 768 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 769 NextToken.is(tok::less); 770 771 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 772 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 773 return true; 774 775 if (CheckTemplate && isa<TemplateDecl>(*I)) 776 return true; 777 } 778 779 return false; 780 } 781 782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 783 Scope *S, CXXScopeSpec &SS, 784 IdentifierInfo *&Name, 785 SourceLocation NameLoc) { 786 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 787 SemaRef.LookupParsedName(R, S, &SS); 788 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 789 StringRef FixItTagName; 790 switch (Tag->getTagKind()) { 791 case TTK_Class: 792 FixItTagName = "class "; 793 break; 794 795 case TTK_Enum: 796 FixItTagName = "enum "; 797 break; 798 799 case TTK_Struct: 800 FixItTagName = "struct "; 801 break; 802 803 case TTK_Interface: 804 FixItTagName = "__interface "; 805 break; 806 807 case TTK_Union: 808 FixItTagName = "union "; 809 break; 810 } 811 812 StringRef TagName = FixItTagName.drop_back(); 813 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 814 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 815 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 816 817 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 818 I != IEnd; ++I) 819 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 820 << Name << TagName; 821 822 // Replace lookup results with just the tag decl. 823 Result.clear(Sema::LookupTagName); 824 SemaRef.LookupParsedName(Result, S, &SS); 825 return true; 826 } 827 828 return false; 829 } 830 831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 833 QualType T, SourceLocation NameLoc) { 834 ASTContext &Context = S.Context; 835 836 TypeLocBuilder Builder; 837 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 838 839 T = S.getElaboratedType(ETK_None, SS, T); 840 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 841 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 842 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 843 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 844 } 845 846 Sema::NameClassification 847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 848 SourceLocation NameLoc, const Token &NextToken, 849 bool IsAddressOfOperand, 850 std::unique_ptr<CorrectionCandidateCallback> CCC) { 851 DeclarationNameInfo NameInfo(Name, NameLoc); 852 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 853 854 if (NextToken.is(tok::coloncolon)) { 855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 857 } else if (getLangOpts().CPlusPlus && SS.isSet() && 858 isCurrentClassName(*Name, S, &SS)) { 859 // Per [class.qual]p2, this names the constructors of SS, not the 860 // injected-class-name. We don't have a classification for that. 861 // There's not much point caching this result, since the parser 862 // will reject it later. 863 return NameClassification::Unknown(); 864 } 865 866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 867 LookupParsedName(Result, S, &SS, !CurMethod); 868 869 // For unqualified lookup in a class template in MSVC mode, look into 870 // dependent base classes where the primary class template is known. 871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 872 if (ParsedType TypeInBase = 873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 874 return TypeInBase; 875 } 876 877 // Perform lookup for Objective-C instance variables (including automatically 878 // synthesized instance variables), if we're in an Objective-C method. 879 // FIXME: This lookup really, really needs to be folded in to the normal 880 // unqualified lookup mechanism. 881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 882 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 883 if (E.get() || E.isInvalid()) 884 return E; 885 } 886 887 bool SecondTry = false; 888 bool IsFilteredTemplateName = false; 889 890 Corrected: 891 switch (Result.getResultKind()) { 892 case LookupResult::NotFound: 893 // If an unqualified-id is followed by a '(', then we have a function 894 // call. 895 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 896 // In C++, this is an ADL-only call. 897 // FIXME: Reference? 898 if (getLangOpts().CPlusPlus) 899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 900 901 // C90 6.3.2.2: 902 // If the expression that precedes the parenthesized argument list in a 903 // function call consists solely of an identifier, and if no 904 // declaration is visible for this identifier, the identifier is 905 // implicitly declared exactly as if, in the innermost block containing 906 // the function call, the declaration 907 // 908 // extern int identifier (); 909 // 910 // appeared. 911 // 912 // We also allow this in C99 as an extension. 913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 914 Result.addDecl(D); 915 Result.resolveKind(); 916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 917 } 918 } 919 920 // In C, we first see whether there is a tag type by the same name, in 921 // which case it's likely that the user just forgot to write "enum", 922 // "struct", or "union". 923 if (!getLangOpts().CPlusPlus && !SecondTry && 924 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 925 break; 926 } 927 928 // Perform typo correction to determine if there is another name that is 929 // close to this name. 930 if (!SecondTry && CCC) { 931 SecondTry = true; 932 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 933 Result.getLookupKind(), S, 934 &SS, std::move(CCC), 935 CTK_ErrorRecovery)) { 936 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 937 unsigned QualifiedDiag = diag::err_no_member_suggest; 938 939 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 940 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 941 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 942 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 943 UnqualifiedDiag = diag::err_no_template_suggest; 944 QualifiedDiag = diag::err_no_member_template_suggest; 945 } else if (UnderlyingFirstDecl && 946 (isa<TypeDecl>(UnderlyingFirstDecl) || 947 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 948 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 949 UnqualifiedDiag = diag::err_unknown_typename_suggest; 950 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 951 } 952 953 if (SS.isEmpty()) { 954 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 955 } else {// FIXME: is this even reachable? Test it. 956 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 957 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 958 Name->getName().equals(CorrectedStr); 959 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 960 << Name << computeDeclContext(SS, false) 961 << DroppedSpecifier << SS.getRange()); 962 } 963 964 // Update the name, so that the caller has the new name. 965 Name = Corrected.getCorrectionAsIdentifierInfo(); 966 967 // Typo correction corrected to a keyword. 968 if (Corrected.isKeyword()) 969 return Name; 970 971 // Also update the LookupResult... 972 // FIXME: This should probably go away at some point 973 Result.clear(); 974 Result.setLookupName(Corrected.getCorrection()); 975 if (FirstDecl) 976 Result.addDecl(FirstDecl); 977 978 // If we found an Objective-C instance variable, let 979 // LookupInObjCMethod build the appropriate expression to 980 // reference the ivar. 981 // FIXME: This is a gross hack. 982 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 983 Result.clear(); 984 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 985 return E; 986 } 987 988 goto Corrected; 989 } 990 } 991 992 // We failed to correct; just fall through and let the parser deal with it. 993 Result.suppressDiagnostics(); 994 return NameClassification::Unknown(); 995 996 case LookupResult::NotFoundInCurrentInstantiation: { 997 // We performed name lookup into the current instantiation, and there were 998 // dependent bases, so we treat this result the same way as any other 999 // dependent nested-name-specifier. 1000 1001 // C++ [temp.res]p2: 1002 // A name used in a template declaration or definition and that is 1003 // dependent on a template-parameter is assumed not to name a type 1004 // unless the applicable name lookup finds a type name or the name is 1005 // qualified by the keyword typename. 1006 // 1007 // FIXME: If the next token is '<', we might want to ask the parser to 1008 // perform some heroics to see if we actually have a 1009 // template-argument-list, which would indicate a missing 'template' 1010 // keyword here. 1011 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1012 NameInfo, IsAddressOfOperand, 1013 /*TemplateArgs=*/nullptr); 1014 } 1015 1016 case LookupResult::Found: 1017 case LookupResult::FoundOverloaded: 1018 case LookupResult::FoundUnresolvedValue: 1019 break; 1020 1021 case LookupResult::Ambiguous: 1022 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1023 hasAnyAcceptableTemplateNames(Result)) { 1024 // C++ [temp.local]p3: 1025 // A lookup that finds an injected-class-name (10.2) can result in an 1026 // ambiguity in certain cases (for example, if it is found in more than 1027 // one base class). If all of the injected-class-names that are found 1028 // refer to specializations of the same class template, and if the name 1029 // is followed by a template-argument-list, the reference refers to the 1030 // class template itself and not a specialization thereof, and is not 1031 // ambiguous. 1032 // 1033 // This filtering can make an ambiguous result into an unambiguous one, 1034 // so try again after filtering out template names. 1035 FilterAcceptableTemplateNames(Result); 1036 if (!Result.isAmbiguous()) { 1037 IsFilteredTemplateName = true; 1038 break; 1039 } 1040 } 1041 1042 // Diagnose the ambiguity and return an error. 1043 return NameClassification::Error(); 1044 } 1045 1046 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1047 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1048 // C++ [temp.names]p3: 1049 // After name lookup (3.4) finds that a name is a template-name or that 1050 // an operator-function-id or a literal- operator-id refers to a set of 1051 // overloaded functions any member of which is a function template if 1052 // this is followed by a <, the < is always taken as the delimiter of a 1053 // template-argument-list and never as the less-than operator. 1054 if (!IsFilteredTemplateName) 1055 FilterAcceptableTemplateNames(Result); 1056 1057 if (!Result.empty()) { 1058 bool IsFunctionTemplate; 1059 bool IsVarTemplate; 1060 TemplateName Template; 1061 if (Result.end() - Result.begin() > 1) { 1062 IsFunctionTemplate = true; 1063 Template = Context.getOverloadedTemplateName(Result.begin(), 1064 Result.end()); 1065 } else { 1066 TemplateDecl *TD 1067 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1068 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1069 IsVarTemplate = isa<VarTemplateDecl>(TD); 1070 1071 if (SS.isSet() && !SS.isInvalid()) 1072 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1073 /*TemplateKeyword=*/false, 1074 TD); 1075 else 1076 Template = TemplateName(TD); 1077 } 1078 1079 if (IsFunctionTemplate) { 1080 // Function templates always go through overload resolution, at which 1081 // point we'll perform the various checks (e.g., accessibility) we need 1082 // to based on which function we selected. 1083 Result.suppressDiagnostics(); 1084 1085 return NameClassification::FunctionTemplate(Template); 1086 } 1087 1088 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1089 : NameClassification::TypeTemplate(Template); 1090 } 1091 } 1092 1093 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1094 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1095 DiagnoseUseOfDecl(Type, NameLoc); 1096 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1097 QualType T = Context.getTypeDeclType(Type); 1098 if (SS.isNotEmpty()) 1099 return buildNestedType(*this, SS, T, NameLoc); 1100 return ParsedType::make(T); 1101 } 1102 1103 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1104 if (!Class) { 1105 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1106 if (ObjCCompatibleAliasDecl *Alias = 1107 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1108 Class = Alias->getClassInterface(); 1109 } 1110 1111 if (Class) { 1112 DiagnoseUseOfDecl(Class, NameLoc); 1113 1114 if (NextToken.is(tok::period)) { 1115 // Interface. <something> is parsed as a property reference expression. 1116 // Just return "unknown" as a fall-through for now. 1117 Result.suppressDiagnostics(); 1118 return NameClassification::Unknown(); 1119 } 1120 1121 QualType T = Context.getObjCInterfaceType(Class); 1122 return ParsedType::make(T); 1123 } 1124 1125 // We can have a type template here if we're classifying a template argument. 1126 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1127 !isa<VarTemplateDecl>(FirstDecl)) 1128 return NameClassification::TypeTemplate( 1129 TemplateName(cast<TemplateDecl>(FirstDecl))); 1130 1131 // Check for a tag type hidden by a non-type decl in a few cases where it 1132 // seems likely a type is wanted instead of the non-type that was found. 1133 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1134 if ((NextToken.is(tok::identifier) || 1135 (NextIsOp && 1136 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1137 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1138 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1139 DiagnoseUseOfDecl(Type, NameLoc); 1140 QualType T = Context.getTypeDeclType(Type); 1141 if (SS.isNotEmpty()) 1142 return buildNestedType(*this, SS, T, NameLoc); 1143 return ParsedType::make(T); 1144 } 1145 1146 if (FirstDecl->isCXXClassMember()) 1147 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1148 nullptr, S); 1149 1150 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1151 return BuildDeclarationNameExpr(SS, Result, ADL); 1152 } 1153 1154 Sema::TemplateNameKindForDiagnostics 1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1156 auto *TD = Name.getAsTemplateDecl(); 1157 if (!TD) 1158 return TemplateNameKindForDiagnostics::DependentTemplate; 1159 if (isa<ClassTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::ClassTemplate; 1161 if (isa<FunctionTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::FunctionTemplate; 1163 if (isa<VarTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::VarTemplate; 1165 if (isa<TypeAliasTemplateDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::AliasTemplate; 1167 if (isa<TemplateTemplateParmDecl>(TD)) 1168 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1169 return TemplateNameKindForDiagnostics::DependentTemplate; 1170 } 1171 1172 // Determines the context to return to after temporarily entering a 1173 // context. This depends in an unnecessarily complicated way on the 1174 // exact ordering of callbacks from the parser. 1175 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1176 1177 // Functions defined inline within classes aren't parsed until we've 1178 // finished parsing the top-level class, so the top-level class is 1179 // the context we'll need to return to. 1180 // A Lambda call operator whose parent is a class must not be treated 1181 // as an inline member function. A Lambda can be used legally 1182 // either as an in-class member initializer or a default argument. These 1183 // are parsed once the class has been marked complete and so the containing 1184 // context would be the nested class (when the lambda is defined in one); 1185 // If the class is not complete, then the lambda is being used in an 1186 // ill-formed fashion (such as to specify the width of a bit-field, or 1187 // in an array-bound) - in which case we still want to return the 1188 // lexically containing DC (which could be a nested class). 1189 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1190 DC = DC->getLexicalParent(); 1191 1192 // A function not defined within a class will always return to its 1193 // lexical context. 1194 if (!isa<CXXRecordDecl>(DC)) 1195 return DC; 1196 1197 // A C++ inline method/friend is parsed *after* the topmost class 1198 // it was declared in is fully parsed ("complete"); the topmost 1199 // class is the context we need to return to. 1200 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1201 DC = RD; 1202 1203 // Return the declaration context of the topmost class the inline method is 1204 // declared in. 1205 return DC; 1206 } 1207 1208 return DC->getLexicalParent(); 1209 } 1210 1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1212 assert(getContainingDC(DC) == CurContext && 1213 "The next DeclContext should be lexically contained in the current one."); 1214 CurContext = DC; 1215 S->setEntity(DC); 1216 } 1217 1218 void Sema::PopDeclContext() { 1219 assert(CurContext && "DeclContext imbalance!"); 1220 1221 CurContext = getContainingDC(CurContext); 1222 assert(CurContext && "Popped translation unit!"); 1223 } 1224 1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1226 Decl *D) { 1227 // Unlike PushDeclContext, the context to which we return is not necessarily 1228 // the containing DC of TD, because the new context will be some pre-existing 1229 // TagDecl definition instead of a fresh one. 1230 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1231 CurContext = cast<TagDecl>(D)->getDefinition(); 1232 assert(CurContext && "skipping definition of undefined tag"); 1233 // Start lookups from the parent of the current context; we don't want to look 1234 // into the pre-existing complete definition. 1235 S->setEntity(CurContext->getLookupParent()); 1236 return Result; 1237 } 1238 1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1240 CurContext = static_cast<decltype(CurContext)>(Context); 1241 } 1242 1243 /// EnterDeclaratorContext - Used when we must lookup names in the context 1244 /// of a declarator's nested name specifier. 1245 /// 1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1247 // C++0x [basic.lookup.unqual]p13: 1248 // A name used in the definition of a static data member of class 1249 // X (after the qualified-id of the static member) is looked up as 1250 // if the name was used in a member function of X. 1251 // C++0x [basic.lookup.unqual]p14: 1252 // If a variable member of a namespace is defined outside of the 1253 // scope of its namespace then any name used in the definition of 1254 // the variable member (after the declarator-id) is looked up as 1255 // if the definition of the variable member occurred in its 1256 // namespace. 1257 // Both of these imply that we should push a scope whose context 1258 // is the semantic context of the declaration. We can't use 1259 // PushDeclContext here because that context is not necessarily 1260 // lexically contained in the current context. Fortunately, 1261 // the containing scope should have the appropriate information. 1262 1263 assert(!S->getEntity() && "scope already has entity"); 1264 1265 #ifndef NDEBUG 1266 Scope *Ancestor = S->getParent(); 1267 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1268 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1269 #endif 1270 1271 CurContext = DC; 1272 S->setEntity(DC); 1273 } 1274 1275 void Sema::ExitDeclaratorContext(Scope *S) { 1276 assert(S->getEntity() == CurContext && "Context imbalance!"); 1277 1278 // Switch back to the lexical context. The safety of this is 1279 // enforced by an assert in EnterDeclaratorContext. 1280 Scope *Ancestor = S->getParent(); 1281 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1282 CurContext = Ancestor->getEntity(); 1283 1284 // We don't need to do anything with the scope, which is going to 1285 // disappear. 1286 } 1287 1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1289 // We assume that the caller has already called 1290 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1291 FunctionDecl *FD = D->getAsFunction(); 1292 if (!FD) 1293 return; 1294 1295 // Same implementation as PushDeclContext, but enters the context 1296 // from the lexical parent, rather than the top-level class. 1297 assert(CurContext == FD->getLexicalParent() && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = FD; 1300 S->setEntity(CurContext); 1301 1302 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1303 ParmVarDecl *Param = FD->getParamDecl(P); 1304 // If the parameter has an identifier, then add it to the scope 1305 if (Param->getIdentifier()) { 1306 S->AddDecl(Param); 1307 IdResolver.AddDecl(Param); 1308 } 1309 } 1310 } 1311 1312 void Sema::ActOnExitFunctionContext() { 1313 // Same implementation as PopDeclContext, but returns to the lexical parent, 1314 // rather than the top-level class. 1315 assert(CurContext && "DeclContext imbalance!"); 1316 CurContext = CurContext->getLexicalParent(); 1317 assert(CurContext && "Popped translation unit!"); 1318 } 1319 1320 /// \brief Determine whether we allow overloading of the function 1321 /// PrevDecl with another declaration. 1322 /// 1323 /// This routine determines whether overloading is possible, not 1324 /// whether some new function is actually an overload. It will return 1325 /// true in C++ (where we can always provide overloads) or, as an 1326 /// extension, in C when the previous function is already an 1327 /// overloaded function declaration or has the "overloadable" 1328 /// attribute. 1329 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1330 ASTContext &Context, 1331 const FunctionDecl *New) { 1332 if (Context.getLangOpts().CPlusPlus) 1333 return true; 1334 1335 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1336 return true; 1337 1338 return Previous.getResultKind() == LookupResult::Found && 1339 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1340 New->hasAttr<OverloadableAttr>()); 1341 } 1342 1343 /// Add this decl to the scope shadowed decl chains. 1344 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1345 // Move up the scope chain until we find the nearest enclosing 1346 // non-transparent context. The declaration will be introduced into this 1347 // scope. 1348 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1349 S = S->getParent(); 1350 1351 // Add scoped declarations into their context, so that they can be 1352 // found later. Declarations without a context won't be inserted 1353 // into any context. 1354 if (AddToContext) 1355 CurContext->addDecl(D); 1356 1357 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1358 // are function-local declarations. 1359 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1360 !D->getDeclContext()->getRedeclContext()->Equals( 1361 D->getLexicalDeclContext()->getRedeclContext()) && 1362 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1363 return; 1364 1365 // Template instantiations should also not be pushed into scope. 1366 if (isa<FunctionDecl>(D) && 1367 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1368 return; 1369 1370 // If this replaces anything in the current scope, 1371 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1372 IEnd = IdResolver.end(); 1373 for (; I != IEnd; ++I) { 1374 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1375 S->RemoveDecl(*I); 1376 IdResolver.RemoveDecl(*I); 1377 1378 // Should only need to replace one decl. 1379 break; 1380 } 1381 } 1382 1383 S->AddDecl(D); 1384 1385 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1386 // Implicitly-generated labels may end up getting generated in an order that 1387 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1388 // the label at the appropriate place in the identifier chain. 1389 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1390 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1391 if (IDC == CurContext) { 1392 if (!S->isDeclScope(*I)) 1393 continue; 1394 } else if (IDC->Encloses(CurContext)) 1395 break; 1396 } 1397 1398 IdResolver.InsertDeclAfter(I, D); 1399 } else { 1400 IdResolver.AddDecl(D); 1401 } 1402 } 1403 1404 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1405 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1406 TUScope->AddDecl(D); 1407 } 1408 1409 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1410 bool AllowInlineNamespace) { 1411 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1412 } 1413 1414 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1415 DeclContext *TargetDC = DC->getPrimaryContext(); 1416 do { 1417 if (DeclContext *ScopeDC = S->getEntity()) 1418 if (ScopeDC->getPrimaryContext() == TargetDC) 1419 return S; 1420 } while ((S = S->getParent())); 1421 1422 return nullptr; 1423 } 1424 1425 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1426 DeclContext*, 1427 ASTContext&); 1428 1429 /// Filters out lookup results that don't fall within the given scope 1430 /// as determined by isDeclInScope. 1431 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1432 bool ConsiderLinkage, 1433 bool AllowInlineNamespace) { 1434 LookupResult::Filter F = R.makeFilter(); 1435 while (F.hasNext()) { 1436 NamedDecl *D = F.next(); 1437 1438 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1439 continue; 1440 1441 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1442 continue; 1443 1444 F.erase(); 1445 } 1446 1447 F.done(); 1448 } 1449 1450 static bool isUsingDecl(NamedDecl *D) { 1451 return isa<UsingShadowDecl>(D) || 1452 isa<UnresolvedUsingTypenameDecl>(D) || 1453 isa<UnresolvedUsingValueDecl>(D); 1454 } 1455 1456 /// Removes using shadow declarations from the lookup results. 1457 static void RemoveUsingDecls(LookupResult &R) { 1458 LookupResult::Filter F = R.makeFilter(); 1459 while (F.hasNext()) 1460 if (isUsingDecl(F.next())) 1461 F.erase(); 1462 1463 F.done(); 1464 } 1465 1466 /// \brief Check for this common pattern: 1467 /// @code 1468 /// class S { 1469 /// S(const S&); // DO NOT IMPLEMENT 1470 /// void operator=(const S&); // DO NOT IMPLEMENT 1471 /// }; 1472 /// @endcode 1473 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1474 // FIXME: Should check for private access too but access is set after we get 1475 // the decl here. 1476 if (D->doesThisDeclarationHaveABody()) 1477 return false; 1478 1479 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1480 return CD->isCopyConstructor(); 1481 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1482 return Method->isCopyAssignmentOperator(); 1483 return false; 1484 } 1485 1486 // We need this to handle 1487 // 1488 // typedef struct { 1489 // void *foo() { return 0; } 1490 // } A; 1491 // 1492 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1493 // for example. If 'A', foo will have external linkage. If we have '*A', 1494 // foo will have no linkage. Since we can't know until we get to the end 1495 // of the typedef, this function finds out if D might have non-external linkage. 1496 // Callers should verify at the end of the TU if it D has external linkage or 1497 // not. 1498 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1499 const DeclContext *DC = D->getDeclContext(); 1500 while (!DC->isTranslationUnit()) { 1501 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1502 if (!RD->hasNameForLinkage()) 1503 return true; 1504 } 1505 DC = DC->getParent(); 1506 } 1507 1508 return !D->isExternallyVisible(); 1509 } 1510 1511 // FIXME: This needs to be refactored; some other isInMainFile users want 1512 // these semantics. 1513 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1514 if (S.TUKind != TU_Complete) 1515 return false; 1516 return S.SourceMgr.isInMainFile(Loc); 1517 } 1518 1519 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1520 assert(D); 1521 1522 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1523 return false; 1524 1525 // Ignore all entities declared within templates, and out-of-line definitions 1526 // of members of class templates. 1527 if (D->getDeclContext()->isDependentContext() || 1528 D->getLexicalDeclContext()->isDependentContext()) 1529 return false; 1530 1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1532 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1533 return false; 1534 // A non-out-of-line declaration of a member specialization was implicitly 1535 // instantiated; it's the out-of-line declaration that we're interested in. 1536 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1537 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1538 return false; 1539 1540 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1541 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1542 return false; 1543 } else { 1544 // 'static inline' functions are defined in headers; don't warn. 1545 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1546 return false; 1547 } 1548 1549 if (FD->doesThisDeclarationHaveABody() && 1550 Context.DeclMustBeEmitted(FD)) 1551 return false; 1552 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1553 // Constants and utility variables are defined in headers with internal 1554 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1555 // like "inline".) 1556 if (!isMainFileLoc(*this, VD->getLocation())) 1557 return false; 1558 1559 if (Context.DeclMustBeEmitted(VD)) 1560 return false; 1561 1562 if (VD->isStaticDataMember() && 1563 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1564 return false; 1565 if (VD->isStaticDataMember() && 1566 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1567 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1568 return false; 1569 1570 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1571 return false; 1572 } else { 1573 return false; 1574 } 1575 1576 // Only warn for unused decls internal to the translation unit. 1577 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1578 // for inline functions defined in the main source file, for instance. 1579 return mightHaveNonExternalLinkage(D); 1580 } 1581 1582 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1583 if (!D) 1584 return; 1585 1586 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1587 const FunctionDecl *First = FD->getFirstDecl(); 1588 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1589 return; // First should already be in the vector. 1590 } 1591 1592 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1593 const VarDecl *First = VD->getFirstDecl(); 1594 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1595 return; // First should already be in the vector. 1596 } 1597 1598 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1599 UnusedFileScopedDecls.push_back(D); 1600 } 1601 1602 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1603 if (D->isInvalidDecl()) 1604 return false; 1605 1606 bool Referenced = false; 1607 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1608 // For a decomposition declaration, warn if none of the bindings are 1609 // referenced, instead of if the variable itself is referenced (which 1610 // it is, by the bindings' expressions). 1611 for (auto *BD : DD->bindings()) { 1612 if (BD->isReferenced()) { 1613 Referenced = true; 1614 break; 1615 } 1616 } 1617 } else if (!D->getDeclName()) { 1618 return false; 1619 } else if (D->isReferenced() || D->isUsed()) { 1620 Referenced = true; 1621 } 1622 1623 if (Referenced || D->hasAttr<UnusedAttr>() || 1624 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1625 return false; 1626 1627 if (isa<LabelDecl>(D)) 1628 return true; 1629 1630 // Except for labels, we only care about unused decls that are local to 1631 // functions. 1632 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1633 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1634 // For dependent types, the diagnostic is deferred. 1635 WithinFunction = 1636 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1637 if (!WithinFunction) 1638 return false; 1639 1640 if (isa<TypedefNameDecl>(D)) 1641 return true; 1642 1643 // White-list anything that isn't a local variable. 1644 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1645 return false; 1646 1647 // Types of valid local variables should be complete, so this should succeed. 1648 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1649 1650 // White-list anything with an __attribute__((unused)) type. 1651 const auto *Ty = VD->getType().getTypePtr(); 1652 1653 // Only look at the outermost level of typedef. 1654 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1655 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1656 return false; 1657 } 1658 1659 // If we failed to complete the type for some reason, or if the type is 1660 // dependent, don't diagnose the variable. 1661 if (Ty->isIncompleteType() || Ty->isDependentType()) 1662 return false; 1663 1664 // Look at the element type to ensure that the warning behaviour is 1665 // consistent for both scalars and arrays. 1666 Ty = Ty->getBaseElementTypeUnsafe(); 1667 1668 if (const TagType *TT = Ty->getAs<TagType>()) { 1669 const TagDecl *Tag = TT->getDecl(); 1670 if (Tag->hasAttr<UnusedAttr>()) 1671 return false; 1672 1673 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1674 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1675 return false; 1676 1677 if (const Expr *Init = VD->getInit()) { 1678 if (const ExprWithCleanups *Cleanups = 1679 dyn_cast<ExprWithCleanups>(Init)) 1680 Init = Cleanups->getSubExpr(); 1681 const CXXConstructExpr *Construct = 1682 dyn_cast<CXXConstructExpr>(Init); 1683 if (Construct && !Construct->isElidable()) { 1684 CXXConstructorDecl *CD = Construct->getConstructor(); 1685 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1686 return false; 1687 } 1688 } 1689 } 1690 } 1691 1692 // TODO: __attribute__((unused)) templates? 1693 } 1694 1695 return true; 1696 } 1697 1698 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1699 FixItHint &Hint) { 1700 if (isa<LabelDecl>(D)) { 1701 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1702 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1703 if (AfterColon.isInvalid()) 1704 return; 1705 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1706 getCharRange(D->getLocStart(), AfterColon)); 1707 } 1708 } 1709 1710 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1711 if (D->getTypeForDecl()->isDependentType()) 1712 return; 1713 1714 for (auto *TmpD : D->decls()) { 1715 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1716 DiagnoseUnusedDecl(T); 1717 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1718 DiagnoseUnusedNestedTypedefs(R); 1719 } 1720 } 1721 1722 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1723 /// unless they are marked attr(unused). 1724 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1725 if (!ShouldDiagnoseUnusedDecl(D)) 1726 return; 1727 1728 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1729 // typedefs can be referenced later on, so the diagnostics are emitted 1730 // at end-of-translation-unit. 1731 UnusedLocalTypedefNameCandidates.insert(TD); 1732 return; 1733 } 1734 1735 FixItHint Hint; 1736 GenerateFixForUnusedDecl(D, Context, Hint); 1737 1738 unsigned DiagID; 1739 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1740 DiagID = diag::warn_unused_exception_param; 1741 else if (isa<LabelDecl>(D)) 1742 DiagID = diag::warn_unused_label; 1743 else 1744 DiagID = diag::warn_unused_variable; 1745 1746 Diag(D->getLocation(), DiagID) << D << Hint; 1747 } 1748 1749 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1750 // Verify that we have no forward references left. If so, there was a goto 1751 // or address of a label taken, but no definition of it. Label fwd 1752 // definitions are indicated with a null substmt which is also not a resolved 1753 // MS inline assembly label name. 1754 bool Diagnose = false; 1755 if (L->isMSAsmLabel()) 1756 Diagnose = !L->isResolvedMSAsmLabel(); 1757 else 1758 Diagnose = L->getStmt() == nullptr; 1759 if (Diagnose) 1760 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1761 } 1762 1763 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1764 S->mergeNRVOIntoParent(); 1765 1766 if (S->decl_empty()) return; 1767 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1768 "Scope shouldn't contain decls!"); 1769 1770 for (auto *TmpD : S->decls()) { 1771 assert(TmpD && "This decl didn't get pushed??"); 1772 1773 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1774 NamedDecl *D = cast<NamedDecl>(TmpD); 1775 1776 // Diagnose unused variables in this scope. 1777 if (!S->hasUnrecoverableErrorOccurred()) { 1778 DiagnoseUnusedDecl(D); 1779 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1780 DiagnoseUnusedNestedTypedefs(RD); 1781 } 1782 1783 if (!D->getDeclName()) continue; 1784 1785 // If this was a forward reference to a label, verify it was defined. 1786 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1787 CheckPoppedLabel(LD, *this); 1788 1789 // Remove this name from our lexical scope, and warn on it if we haven't 1790 // already. 1791 IdResolver.RemoveDecl(D); 1792 auto ShadowI = ShadowingDecls.find(D); 1793 if (ShadowI != ShadowingDecls.end()) { 1794 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1795 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1796 << D << FD << FD->getParent(); 1797 Diag(FD->getLocation(), diag::note_previous_declaration); 1798 } 1799 ShadowingDecls.erase(ShadowI); 1800 } 1801 } 1802 } 1803 1804 /// \brief Look for an Objective-C class in the translation unit. 1805 /// 1806 /// \param Id The name of the Objective-C class we're looking for. If 1807 /// typo-correction fixes this name, the Id will be updated 1808 /// to the fixed name. 1809 /// 1810 /// \param IdLoc The location of the name in the translation unit. 1811 /// 1812 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1813 /// if there is no class with the given name. 1814 /// 1815 /// \returns The declaration of the named Objective-C class, or NULL if the 1816 /// class could not be found. 1817 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1818 SourceLocation IdLoc, 1819 bool DoTypoCorrection) { 1820 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1821 // creation from this context. 1822 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1823 1824 if (!IDecl && DoTypoCorrection) { 1825 // Perform typo correction at the given location, but only if we 1826 // find an Objective-C class name. 1827 if (TypoCorrection C = CorrectTypo( 1828 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1829 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1830 CTK_ErrorRecovery)) { 1831 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1832 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1833 Id = IDecl->getIdentifier(); 1834 } 1835 } 1836 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1837 // This routine must always return a class definition, if any. 1838 if (Def && Def->getDefinition()) 1839 Def = Def->getDefinition(); 1840 return Def; 1841 } 1842 1843 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1844 /// from S, where a non-field would be declared. This routine copes 1845 /// with the difference between C and C++ scoping rules in structs and 1846 /// unions. For example, the following code is well-formed in C but 1847 /// ill-formed in C++: 1848 /// @code 1849 /// struct S6 { 1850 /// enum { BAR } e; 1851 /// }; 1852 /// 1853 /// void test_S6() { 1854 /// struct S6 a; 1855 /// a.e = BAR; 1856 /// } 1857 /// @endcode 1858 /// For the declaration of BAR, this routine will return a different 1859 /// scope. The scope S will be the scope of the unnamed enumeration 1860 /// within S6. In C++, this routine will return the scope associated 1861 /// with S6, because the enumeration's scope is a transparent 1862 /// context but structures can contain non-field names. In C, this 1863 /// routine will return the translation unit scope, since the 1864 /// enumeration's scope is a transparent context and structures cannot 1865 /// contain non-field names. 1866 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1867 while (((S->getFlags() & Scope::DeclScope) == 0) || 1868 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1869 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1870 S = S->getParent(); 1871 return S; 1872 } 1873 1874 /// \brief Looks up the declaration of "struct objc_super" and 1875 /// saves it for later use in building builtin declaration of 1876 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1877 /// pre-existing declaration exists no action takes place. 1878 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1879 IdentifierInfo *II) { 1880 if (!II->isStr("objc_msgSendSuper")) 1881 return; 1882 ASTContext &Context = ThisSema.Context; 1883 1884 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1885 SourceLocation(), Sema::LookupTagName); 1886 ThisSema.LookupName(Result, S); 1887 if (Result.getResultKind() == LookupResult::Found) 1888 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1889 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1890 } 1891 1892 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1893 switch (Error) { 1894 case ASTContext::GE_None: 1895 return ""; 1896 case ASTContext::GE_Missing_stdio: 1897 return "stdio.h"; 1898 case ASTContext::GE_Missing_setjmp: 1899 return "setjmp.h"; 1900 case ASTContext::GE_Missing_ucontext: 1901 return "ucontext.h"; 1902 } 1903 llvm_unreachable("unhandled error kind"); 1904 } 1905 1906 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1907 /// file scope. lazily create a decl for it. ForRedeclaration is true 1908 /// if we're creating this built-in in anticipation of redeclaring the 1909 /// built-in. 1910 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1911 Scope *S, bool ForRedeclaration, 1912 SourceLocation Loc) { 1913 LookupPredefedObjCSuperType(*this, S, II); 1914 1915 ASTContext::GetBuiltinTypeError Error; 1916 QualType R = Context.GetBuiltinType(ID, Error); 1917 if (Error) { 1918 if (ForRedeclaration) 1919 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1920 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1921 return nullptr; 1922 } 1923 1924 if (!ForRedeclaration && 1925 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1926 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1927 Diag(Loc, diag::ext_implicit_lib_function_decl) 1928 << Context.BuiltinInfo.getName(ID) << R; 1929 if (Context.BuiltinInfo.getHeaderName(ID) && 1930 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1931 Diag(Loc, diag::note_include_header_or_declare) 1932 << Context.BuiltinInfo.getHeaderName(ID) 1933 << Context.BuiltinInfo.getName(ID); 1934 } 1935 1936 if (R.isNull()) 1937 return nullptr; 1938 1939 DeclContext *Parent = Context.getTranslationUnitDecl(); 1940 if (getLangOpts().CPlusPlus) { 1941 LinkageSpecDecl *CLinkageDecl = 1942 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1943 LinkageSpecDecl::lang_c, false); 1944 CLinkageDecl->setImplicit(); 1945 Parent->addDecl(CLinkageDecl); 1946 Parent = CLinkageDecl; 1947 } 1948 1949 FunctionDecl *New = FunctionDecl::Create(Context, 1950 Parent, 1951 Loc, Loc, II, R, /*TInfo=*/nullptr, 1952 SC_Extern, 1953 false, 1954 R->isFunctionProtoType()); 1955 New->setImplicit(); 1956 1957 // Create Decl objects for each parameter, adding them to the 1958 // FunctionDecl. 1959 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1960 SmallVector<ParmVarDecl*, 16> Params; 1961 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1962 ParmVarDecl *parm = 1963 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1964 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1965 SC_None, nullptr); 1966 parm->setScopeInfo(0, i); 1967 Params.push_back(parm); 1968 } 1969 New->setParams(Params); 1970 } 1971 1972 AddKnownFunctionAttributes(New); 1973 RegisterLocallyScopedExternCDecl(New, S); 1974 1975 // TUScope is the translation-unit scope to insert this function into. 1976 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1977 // relate Scopes to DeclContexts, and probably eliminate CurContext 1978 // entirely, but we're not there yet. 1979 DeclContext *SavedContext = CurContext; 1980 CurContext = Parent; 1981 PushOnScopeChains(New, TUScope); 1982 CurContext = SavedContext; 1983 return New; 1984 } 1985 1986 /// Typedef declarations don't have linkage, but they still denote the same 1987 /// entity if their types are the same. 1988 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1989 /// isSameEntity. 1990 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1991 TypedefNameDecl *Decl, 1992 LookupResult &Previous) { 1993 // This is only interesting when modules are enabled. 1994 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1995 return; 1996 1997 // Empty sets are uninteresting. 1998 if (Previous.empty()) 1999 return; 2000 2001 LookupResult::Filter Filter = Previous.makeFilter(); 2002 while (Filter.hasNext()) { 2003 NamedDecl *Old = Filter.next(); 2004 2005 // Non-hidden declarations are never ignored. 2006 if (S.isVisible(Old)) 2007 continue; 2008 2009 // Declarations of the same entity are not ignored, even if they have 2010 // different linkages. 2011 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2012 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2013 Decl->getUnderlyingType())) 2014 continue; 2015 2016 // If both declarations give a tag declaration a typedef name for linkage 2017 // purposes, then they declare the same entity. 2018 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2019 Decl->getAnonDeclWithTypedefName()) 2020 continue; 2021 } 2022 2023 Filter.erase(); 2024 } 2025 2026 Filter.done(); 2027 } 2028 2029 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2030 QualType OldType; 2031 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2032 OldType = OldTypedef->getUnderlyingType(); 2033 else 2034 OldType = Context.getTypeDeclType(Old); 2035 QualType NewType = New->getUnderlyingType(); 2036 2037 if (NewType->isVariablyModifiedType()) { 2038 // Must not redefine a typedef with a variably-modified type. 2039 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2040 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2041 << Kind << NewType; 2042 if (Old->getLocation().isValid()) 2043 notePreviousDefinition(Old, New->getLocation()); 2044 New->setInvalidDecl(); 2045 return true; 2046 } 2047 2048 if (OldType != NewType && 2049 !OldType->isDependentType() && 2050 !NewType->isDependentType() && 2051 !Context.hasSameType(OldType, NewType)) { 2052 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2053 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2054 << Kind << NewType << OldType; 2055 if (Old->getLocation().isValid()) 2056 notePreviousDefinition(Old, New->getLocation()); 2057 New->setInvalidDecl(); 2058 return true; 2059 } 2060 return false; 2061 } 2062 2063 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2064 /// same name and scope as a previous declaration 'Old'. Figure out 2065 /// how to resolve this situation, merging decls or emitting 2066 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2067 /// 2068 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2069 LookupResult &OldDecls) { 2070 // If the new decl is known invalid already, don't bother doing any 2071 // merging checks. 2072 if (New->isInvalidDecl()) return; 2073 2074 // Allow multiple definitions for ObjC built-in typedefs. 2075 // FIXME: Verify the underlying types are equivalent! 2076 if (getLangOpts().ObjC1) { 2077 const IdentifierInfo *TypeID = New->getIdentifier(); 2078 switch (TypeID->getLength()) { 2079 default: break; 2080 case 2: 2081 { 2082 if (!TypeID->isStr("id")) 2083 break; 2084 QualType T = New->getUnderlyingType(); 2085 if (!T->isPointerType()) 2086 break; 2087 if (!T->isVoidPointerType()) { 2088 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2089 if (!PT->isStructureType()) 2090 break; 2091 } 2092 Context.setObjCIdRedefinitionType(T); 2093 // Install the built-in type for 'id', ignoring the current definition. 2094 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2095 return; 2096 } 2097 case 5: 2098 if (!TypeID->isStr("Class")) 2099 break; 2100 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2101 // Install the built-in type for 'Class', ignoring the current definition. 2102 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2103 return; 2104 case 3: 2105 if (!TypeID->isStr("SEL")) 2106 break; 2107 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2108 // Install the built-in type for 'SEL', ignoring the current definition. 2109 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2110 return; 2111 } 2112 // Fall through - the typedef name was not a builtin type. 2113 } 2114 2115 // Verify the old decl was also a type. 2116 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2117 if (!Old) { 2118 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2119 << New->getDeclName(); 2120 2121 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2122 if (OldD->getLocation().isValid()) 2123 notePreviousDefinition(OldD, New->getLocation()); 2124 2125 return New->setInvalidDecl(); 2126 } 2127 2128 // If the old declaration is invalid, just give up here. 2129 if (Old->isInvalidDecl()) 2130 return New->setInvalidDecl(); 2131 2132 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2133 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2134 auto *NewTag = New->getAnonDeclWithTypedefName(); 2135 NamedDecl *Hidden = nullptr; 2136 if (OldTag && NewTag && 2137 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2138 !hasVisibleDefinition(OldTag, &Hidden)) { 2139 // There is a definition of this tag, but it is not visible. Use it 2140 // instead of our tag. 2141 New->setTypeForDecl(OldTD->getTypeForDecl()); 2142 if (OldTD->isModed()) 2143 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2144 OldTD->getUnderlyingType()); 2145 else 2146 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2147 2148 // Make the old tag definition visible. 2149 makeMergedDefinitionVisible(Hidden); 2150 2151 // If this was an unscoped enumeration, yank all of its enumerators 2152 // out of the scope. 2153 if (isa<EnumDecl>(NewTag)) { 2154 Scope *EnumScope = getNonFieldDeclScope(S); 2155 for (auto *D : NewTag->decls()) { 2156 auto *ED = cast<EnumConstantDecl>(D); 2157 assert(EnumScope->isDeclScope(ED)); 2158 EnumScope->RemoveDecl(ED); 2159 IdResolver.RemoveDecl(ED); 2160 ED->getLexicalDeclContext()->removeDecl(ED); 2161 } 2162 } 2163 } 2164 } 2165 2166 // If the typedef types are not identical, reject them in all languages and 2167 // with any extensions enabled. 2168 if (isIncompatibleTypedef(Old, New)) 2169 return; 2170 2171 // The types match. Link up the redeclaration chain and merge attributes if 2172 // the old declaration was a typedef. 2173 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2174 New->setPreviousDecl(Typedef); 2175 mergeDeclAttributes(New, Old); 2176 } 2177 2178 if (getLangOpts().MicrosoftExt) 2179 return; 2180 2181 if (getLangOpts().CPlusPlus) { 2182 // C++ [dcl.typedef]p2: 2183 // In a given non-class scope, a typedef specifier can be used to 2184 // redefine the name of any type declared in that scope to refer 2185 // to the type to which it already refers. 2186 if (!isa<CXXRecordDecl>(CurContext)) 2187 return; 2188 2189 // C++0x [dcl.typedef]p4: 2190 // In a given class scope, a typedef specifier can be used to redefine 2191 // any class-name declared in that scope that is not also a typedef-name 2192 // to refer to the type to which it already refers. 2193 // 2194 // This wording came in via DR424, which was a correction to the 2195 // wording in DR56, which accidentally banned code like: 2196 // 2197 // struct S { 2198 // typedef struct A { } A; 2199 // }; 2200 // 2201 // in the C++03 standard. We implement the C++0x semantics, which 2202 // allow the above but disallow 2203 // 2204 // struct S { 2205 // typedef int I; 2206 // typedef int I; 2207 // }; 2208 // 2209 // since that was the intent of DR56. 2210 if (!isa<TypedefNameDecl>(Old)) 2211 return; 2212 2213 Diag(New->getLocation(), diag::err_redefinition) 2214 << New->getDeclName(); 2215 notePreviousDefinition(Old, New->getLocation()); 2216 return New->setInvalidDecl(); 2217 } 2218 2219 // Modules always permit redefinition of typedefs, as does C11. 2220 if (getLangOpts().Modules || getLangOpts().C11) 2221 return; 2222 2223 // If we have a redefinition of a typedef in C, emit a warning. This warning 2224 // is normally mapped to an error, but can be controlled with 2225 // -Wtypedef-redefinition. If either the original or the redefinition is 2226 // in a system header, don't emit this for compatibility with GCC. 2227 if (getDiagnostics().getSuppressSystemWarnings() && 2228 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2229 (Old->isImplicit() || 2230 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2231 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2232 return; 2233 2234 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2235 << New->getDeclName(); 2236 notePreviousDefinition(Old, New->getLocation()); 2237 } 2238 2239 /// DeclhasAttr - returns true if decl Declaration already has the target 2240 /// attribute. 2241 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2242 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2243 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2244 for (const auto *i : D->attrs()) 2245 if (i->getKind() == A->getKind()) { 2246 if (Ann) { 2247 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2248 return true; 2249 continue; 2250 } 2251 // FIXME: Don't hardcode this check 2252 if (OA && isa<OwnershipAttr>(i)) 2253 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2254 return true; 2255 } 2256 2257 return false; 2258 } 2259 2260 static bool isAttributeTargetADefinition(Decl *D) { 2261 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2262 return VD->isThisDeclarationADefinition(); 2263 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2264 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2265 return true; 2266 } 2267 2268 /// Merge alignment attributes from \p Old to \p New, taking into account the 2269 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2270 /// 2271 /// \return \c true if any attributes were added to \p New. 2272 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2273 // Look for alignas attributes on Old, and pick out whichever attribute 2274 // specifies the strictest alignment requirement. 2275 AlignedAttr *OldAlignasAttr = nullptr; 2276 AlignedAttr *OldStrictestAlignAttr = nullptr; 2277 unsigned OldAlign = 0; 2278 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2279 // FIXME: We have no way of representing inherited dependent alignments 2280 // in a case like: 2281 // template<int A, int B> struct alignas(A) X; 2282 // template<int A, int B> struct alignas(B) X {}; 2283 // For now, we just ignore any alignas attributes which are not on the 2284 // definition in such a case. 2285 if (I->isAlignmentDependent()) 2286 return false; 2287 2288 if (I->isAlignas()) 2289 OldAlignasAttr = I; 2290 2291 unsigned Align = I->getAlignment(S.Context); 2292 if (Align > OldAlign) { 2293 OldAlign = Align; 2294 OldStrictestAlignAttr = I; 2295 } 2296 } 2297 2298 // Look for alignas attributes on New. 2299 AlignedAttr *NewAlignasAttr = nullptr; 2300 unsigned NewAlign = 0; 2301 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2302 if (I->isAlignmentDependent()) 2303 return false; 2304 2305 if (I->isAlignas()) 2306 NewAlignasAttr = I; 2307 2308 unsigned Align = I->getAlignment(S.Context); 2309 if (Align > NewAlign) 2310 NewAlign = Align; 2311 } 2312 2313 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2314 // Both declarations have 'alignas' attributes. We require them to match. 2315 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2316 // fall short. (If two declarations both have alignas, they must both match 2317 // every definition, and so must match each other if there is a definition.) 2318 2319 // If either declaration only contains 'alignas(0)' specifiers, then it 2320 // specifies the natural alignment for the type. 2321 if (OldAlign == 0 || NewAlign == 0) { 2322 QualType Ty; 2323 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2324 Ty = VD->getType(); 2325 else 2326 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2327 2328 if (OldAlign == 0) 2329 OldAlign = S.Context.getTypeAlign(Ty); 2330 if (NewAlign == 0) 2331 NewAlign = S.Context.getTypeAlign(Ty); 2332 } 2333 2334 if (OldAlign != NewAlign) { 2335 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2336 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2337 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2338 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2339 } 2340 } 2341 2342 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2343 // C++11 [dcl.align]p6: 2344 // if any declaration of an entity has an alignment-specifier, 2345 // every defining declaration of that entity shall specify an 2346 // equivalent alignment. 2347 // C11 6.7.5/7: 2348 // If the definition of an object does not have an alignment 2349 // specifier, any other declaration of that object shall also 2350 // have no alignment specifier. 2351 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2352 << OldAlignasAttr; 2353 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2354 << OldAlignasAttr; 2355 } 2356 2357 bool AnyAdded = false; 2358 2359 // Ensure we have an attribute representing the strictest alignment. 2360 if (OldAlign > NewAlign) { 2361 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2362 Clone->setInherited(true); 2363 New->addAttr(Clone); 2364 AnyAdded = true; 2365 } 2366 2367 // Ensure we have an alignas attribute if the old declaration had one. 2368 if (OldAlignasAttr && !NewAlignasAttr && 2369 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2370 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2371 Clone->setInherited(true); 2372 New->addAttr(Clone); 2373 AnyAdded = true; 2374 } 2375 2376 return AnyAdded; 2377 } 2378 2379 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2380 const InheritableAttr *Attr, 2381 Sema::AvailabilityMergeKind AMK) { 2382 // This function copies an attribute Attr from a previous declaration to the 2383 // new declaration D if the new declaration doesn't itself have that attribute 2384 // yet or if that attribute allows duplicates. 2385 // If you're adding a new attribute that requires logic different from 2386 // "use explicit attribute on decl if present, else use attribute from 2387 // previous decl", for example if the attribute needs to be consistent 2388 // between redeclarations, you need to call a custom merge function here. 2389 InheritableAttr *NewAttr = nullptr; 2390 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2391 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2392 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2393 AA->isImplicit(), AA->getIntroduced(), 2394 AA->getDeprecated(), 2395 AA->getObsoleted(), AA->getUnavailable(), 2396 AA->getMessage(), AA->getStrict(), 2397 AA->getReplacement(), AMK, 2398 AttrSpellingListIndex); 2399 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2400 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2401 AttrSpellingListIndex); 2402 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2403 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2404 AttrSpellingListIndex); 2405 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2406 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2407 AttrSpellingListIndex); 2408 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2409 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2410 AttrSpellingListIndex); 2411 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2412 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2413 FA->getFormatIdx(), FA->getFirstArg(), 2414 AttrSpellingListIndex); 2415 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2416 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2417 AttrSpellingListIndex); 2418 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2419 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2420 AttrSpellingListIndex, 2421 IA->getSemanticSpelling()); 2422 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2423 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2424 &S.Context.Idents.get(AA->getSpelling()), 2425 AttrSpellingListIndex); 2426 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2427 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2428 isa<CUDAGlobalAttr>(Attr))) { 2429 // CUDA target attributes are part of function signature for 2430 // overloading purposes and must not be merged. 2431 return false; 2432 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2433 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2434 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2435 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2436 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2437 NewAttr = S.mergeInternalLinkageAttr( 2438 D, InternalLinkageA->getRange(), 2439 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2440 AttrSpellingListIndex); 2441 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2442 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2443 &S.Context.Idents.get(CommonA->getSpelling()), 2444 AttrSpellingListIndex); 2445 else if (isa<AlignedAttr>(Attr)) 2446 // AlignedAttrs are handled separately, because we need to handle all 2447 // such attributes on a declaration at the same time. 2448 NewAttr = nullptr; 2449 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2450 (AMK == Sema::AMK_Override || 2451 AMK == Sema::AMK_ProtocolImplementation)) 2452 NewAttr = nullptr; 2453 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2454 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2455 UA->getGuid()); 2456 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2457 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2458 2459 if (NewAttr) { 2460 NewAttr->setInherited(true); 2461 D->addAttr(NewAttr); 2462 if (isa<MSInheritanceAttr>(NewAttr)) 2463 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2464 return true; 2465 } 2466 2467 return false; 2468 } 2469 2470 static const NamedDecl *getDefinition(const Decl *D) { 2471 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2472 return TD->getDefinition(); 2473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2474 const VarDecl *Def = VD->getDefinition(); 2475 if (Def) 2476 return Def; 2477 return VD->getActingDefinition(); 2478 } 2479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2480 return FD->getDefinition(); 2481 return nullptr; 2482 } 2483 2484 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2485 for (const auto *Attribute : D->attrs()) 2486 if (Attribute->getKind() == Kind) 2487 return true; 2488 return false; 2489 } 2490 2491 /// checkNewAttributesAfterDef - If we already have a definition, check that 2492 /// there are no new attributes in this declaration. 2493 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2494 if (!New->hasAttrs()) 2495 return; 2496 2497 const NamedDecl *Def = getDefinition(Old); 2498 if (!Def || Def == New) 2499 return; 2500 2501 AttrVec &NewAttributes = New->getAttrs(); 2502 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2503 const Attr *NewAttribute = NewAttributes[I]; 2504 2505 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2506 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2507 Sema::SkipBodyInfo SkipBody; 2508 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2509 2510 // If we're skipping this definition, drop the "alias" attribute. 2511 if (SkipBody.ShouldSkip) { 2512 NewAttributes.erase(NewAttributes.begin() + I); 2513 --E; 2514 continue; 2515 } 2516 } else { 2517 VarDecl *VD = cast<VarDecl>(New); 2518 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2519 VarDecl::TentativeDefinition 2520 ? diag::err_alias_after_tentative 2521 : diag::err_redefinition; 2522 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2523 if (Diag == diag::err_redefinition) 2524 S.notePreviousDefinition(Def, VD->getLocation()); 2525 else 2526 S.Diag(Def->getLocation(), diag::note_previous_definition); 2527 VD->setInvalidDecl(); 2528 } 2529 ++I; 2530 continue; 2531 } 2532 2533 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2534 // Tentative definitions are only interesting for the alias check above. 2535 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2536 ++I; 2537 continue; 2538 } 2539 } 2540 2541 if (hasAttribute(Def, NewAttribute->getKind())) { 2542 ++I; 2543 continue; // regular attr merging will take care of validating this. 2544 } 2545 2546 if (isa<C11NoReturnAttr>(NewAttribute)) { 2547 // C's _Noreturn is allowed to be added to a function after it is defined. 2548 ++I; 2549 continue; 2550 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2551 if (AA->isAlignas()) { 2552 // C++11 [dcl.align]p6: 2553 // if any declaration of an entity has an alignment-specifier, 2554 // every defining declaration of that entity shall specify an 2555 // equivalent alignment. 2556 // C11 6.7.5/7: 2557 // If the definition of an object does not have an alignment 2558 // specifier, any other declaration of that object shall also 2559 // have no alignment specifier. 2560 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2561 << AA; 2562 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2563 << AA; 2564 NewAttributes.erase(NewAttributes.begin() + I); 2565 --E; 2566 continue; 2567 } 2568 } 2569 2570 S.Diag(NewAttribute->getLocation(), 2571 diag::warn_attribute_precede_definition); 2572 S.Diag(Def->getLocation(), diag::note_previous_definition); 2573 NewAttributes.erase(NewAttributes.begin() + I); 2574 --E; 2575 } 2576 } 2577 2578 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2579 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2580 AvailabilityMergeKind AMK) { 2581 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2582 UsedAttr *NewAttr = OldAttr->clone(Context); 2583 NewAttr->setInherited(true); 2584 New->addAttr(NewAttr); 2585 } 2586 2587 if (!Old->hasAttrs() && !New->hasAttrs()) 2588 return; 2589 2590 // Attributes declared post-definition are currently ignored. 2591 checkNewAttributesAfterDef(*this, New, Old); 2592 2593 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2594 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2595 if (OldA->getLabel() != NewA->getLabel()) { 2596 // This redeclaration changes __asm__ label. 2597 Diag(New->getLocation(), diag::err_different_asm_label); 2598 Diag(OldA->getLocation(), diag::note_previous_declaration); 2599 } 2600 } else if (Old->isUsed()) { 2601 // This redeclaration adds an __asm__ label to a declaration that has 2602 // already been ODR-used. 2603 Diag(New->getLocation(), diag::err_late_asm_label_name) 2604 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2605 } 2606 } 2607 2608 // Re-declaration cannot add abi_tag's. 2609 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2610 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2611 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2612 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2613 NewTag) == OldAbiTagAttr->tags_end()) { 2614 Diag(NewAbiTagAttr->getLocation(), 2615 diag::err_new_abi_tag_on_redeclaration) 2616 << NewTag; 2617 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2618 } 2619 } 2620 } else { 2621 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2622 Diag(Old->getLocation(), diag::note_previous_declaration); 2623 } 2624 } 2625 2626 if (!Old->hasAttrs()) 2627 return; 2628 2629 bool foundAny = New->hasAttrs(); 2630 2631 // Ensure that any moving of objects within the allocated map is done before 2632 // we process them. 2633 if (!foundAny) New->setAttrs(AttrVec()); 2634 2635 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2636 // Ignore deprecated/unavailable/availability attributes if requested. 2637 AvailabilityMergeKind LocalAMK = AMK_None; 2638 if (isa<DeprecatedAttr>(I) || 2639 isa<UnavailableAttr>(I) || 2640 isa<AvailabilityAttr>(I)) { 2641 switch (AMK) { 2642 case AMK_None: 2643 continue; 2644 2645 case AMK_Redeclaration: 2646 case AMK_Override: 2647 case AMK_ProtocolImplementation: 2648 LocalAMK = AMK; 2649 break; 2650 } 2651 } 2652 2653 // Already handled. 2654 if (isa<UsedAttr>(I)) 2655 continue; 2656 2657 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2658 foundAny = true; 2659 } 2660 2661 if (mergeAlignedAttrs(*this, New, Old)) 2662 foundAny = true; 2663 2664 if (!foundAny) New->dropAttrs(); 2665 } 2666 2667 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2668 /// to the new one. 2669 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2670 const ParmVarDecl *oldDecl, 2671 Sema &S) { 2672 // C++11 [dcl.attr.depend]p2: 2673 // The first declaration of a function shall specify the 2674 // carries_dependency attribute for its declarator-id if any declaration 2675 // of the function specifies the carries_dependency attribute. 2676 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2677 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2678 S.Diag(CDA->getLocation(), 2679 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2680 // Find the first declaration of the parameter. 2681 // FIXME: Should we build redeclaration chains for function parameters? 2682 const FunctionDecl *FirstFD = 2683 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2684 const ParmVarDecl *FirstVD = 2685 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2686 S.Diag(FirstVD->getLocation(), 2687 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2688 } 2689 2690 if (!oldDecl->hasAttrs()) 2691 return; 2692 2693 bool foundAny = newDecl->hasAttrs(); 2694 2695 // Ensure that any moving of objects within the allocated map is 2696 // done before we process them. 2697 if (!foundAny) newDecl->setAttrs(AttrVec()); 2698 2699 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2700 if (!DeclHasAttr(newDecl, I)) { 2701 InheritableAttr *newAttr = 2702 cast<InheritableParamAttr>(I->clone(S.Context)); 2703 newAttr->setInherited(true); 2704 newDecl->addAttr(newAttr); 2705 foundAny = true; 2706 } 2707 } 2708 2709 if (!foundAny) newDecl->dropAttrs(); 2710 } 2711 2712 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2713 const ParmVarDecl *OldParam, 2714 Sema &S) { 2715 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2716 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2717 if (*Oldnullability != *Newnullability) { 2718 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2719 << DiagNullabilityKind( 2720 *Newnullability, 2721 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2722 != 0)) 2723 << DiagNullabilityKind( 2724 *Oldnullability, 2725 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2726 != 0)); 2727 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2728 } 2729 } else { 2730 QualType NewT = NewParam->getType(); 2731 NewT = S.Context.getAttributedType( 2732 AttributedType::getNullabilityAttrKind(*Oldnullability), 2733 NewT, NewT); 2734 NewParam->setType(NewT); 2735 } 2736 } 2737 } 2738 2739 namespace { 2740 2741 /// Used in MergeFunctionDecl to keep track of function parameters in 2742 /// C. 2743 struct GNUCompatibleParamWarning { 2744 ParmVarDecl *OldParm; 2745 ParmVarDecl *NewParm; 2746 QualType PromotedType; 2747 }; 2748 2749 } // end anonymous namespace 2750 2751 /// getSpecialMember - get the special member enum for a method. 2752 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2753 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2754 if (Ctor->isDefaultConstructor()) 2755 return Sema::CXXDefaultConstructor; 2756 2757 if (Ctor->isCopyConstructor()) 2758 return Sema::CXXCopyConstructor; 2759 2760 if (Ctor->isMoveConstructor()) 2761 return Sema::CXXMoveConstructor; 2762 } else if (isa<CXXDestructorDecl>(MD)) { 2763 return Sema::CXXDestructor; 2764 } else if (MD->isCopyAssignmentOperator()) { 2765 return Sema::CXXCopyAssignment; 2766 } else if (MD->isMoveAssignmentOperator()) { 2767 return Sema::CXXMoveAssignment; 2768 } 2769 2770 return Sema::CXXInvalid; 2771 } 2772 2773 // Determine whether the previous declaration was a definition, implicit 2774 // declaration, or a declaration. 2775 template <typename T> 2776 static std::pair<diag::kind, SourceLocation> 2777 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2778 diag::kind PrevDiag; 2779 SourceLocation OldLocation = Old->getLocation(); 2780 if (Old->isThisDeclarationADefinition()) 2781 PrevDiag = diag::note_previous_definition; 2782 else if (Old->isImplicit()) { 2783 PrevDiag = diag::note_previous_implicit_declaration; 2784 if (OldLocation.isInvalid()) 2785 OldLocation = New->getLocation(); 2786 } else 2787 PrevDiag = diag::note_previous_declaration; 2788 return std::make_pair(PrevDiag, OldLocation); 2789 } 2790 2791 /// canRedefineFunction - checks if a function can be redefined. Currently, 2792 /// only extern inline functions can be redefined, and even then only in 2793 /// GNU89 mode. 2794 static bool canRedefineFunction(const FunctionDecl *FD, 2795 const LangOptions& LangOpts) { 2796 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2797 !LangOpts.CPlusPlus && 2798 FD->isInlineSpecified() && 2799 FD->getStorageClass() == SC_Extern); 2800 } 2801 2802 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2803 const AttributedType *AT = T->getAs<AttributedType>(); 2804 while (AT && !AT->isCallingConv()) 2805 AT = AT->getModifiedType()->getAs<AttributedType>(); 2806 return AT; 2807 } 2808 2809 template <typename T> 2810 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2811 const DeclContext *DC = Old->getDeclContext(); 2812 if (DC->isRecord()) 2813 return false; 2814 2815 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2816 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2817 return true; 2818 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2819 return true; 2820 return false; 2821 } 2822 2823 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2824 static bool isExternC(VarTemplateDecl *) { return false; } 2825 2826 /// \brief Check whether a redeclaration of an entity introduced by a 2827 /// using-declaration is valid, given that we know it's not an overload 2828 /// (nor a hidden tag declaration). 2829 template<typename ExpectedDecl> 2830 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2831 ExpectedDecl *New) { 2832 // C++11 [basic.scope.declarative]p4: 2833 // Given a set of declarations in a single declarative region, each of 2834 // which specifies the same unqualified name, 2835 // -- they shall all refer to the same entity, or all refer to functions 2836 // and function templates; or 2837 // -- exactly one declaration shall declare a class name or enumeration 2838 // name that is not a typedef name and the other declarations shall all 2839 // refer to the same variable or enumerator, or all refer to functions 2840 // and function templates; in this case the class name or enumeration 2841 // name is hidden (3.3.10). 2842 2843 // C++11 [namespace.udecl]p14: 2844 // If a function declaration in namespace scope or block scope has the 2845 // same name and the same parameter-type-list as a function introduced 2846 // by a using-declaration, and the declarations do not declare the same 2847 // function, the program is ill-formed. 2848 2849 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2850 if (Old && 2851 !Old->getDeclContext()->getRedeclContext()->Equals( 2852 New->getDeclContext()->getRedeclContext()) && 2853 !(isExternC(Old) && isExternC(New))) 2854 Old = nullptr; 2855 2856 if (!Old) { 2857 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2858 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2859 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2860 return true; 2861 } 2862 return false; 2863 } 2864 2865 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2866 const FunctionDecl *B) { 2867 assert(A->getNumParams() == B->getNumParams()); 2868 2869 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2870 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2871 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2872 if (AttrA == AttrB) 2873 return true; 2874 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2875 }; 2876 2877 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2878 } 2879 2880 /// MergeFunctionDecl - We just parsed a function 'New' from 2881 /// declarator D which has the same name and scope as a previous 2882 /// declaration 'Old'. Figure out how to resolve this situation, 2883 /// merging decls or emitting diagnostics as appropriate. 2884 /// 2885 /// In C++, New and Old must be declarations that are not 2886 /// overloaded. Use IsOverload to determine whether New and Old are 2887 /// overloaded, and to select the Old declaration that New should be 2888 /// merged with. 2889 /// 2890 /// Returns true if there was an error, false otherwise. 2891 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2892 Scope *S, bool MergeTypeWithOld) { 2893 // Verify the old decl was also a function. 2894 FunctionDecl *Old = OldD->getAsFunction(); 2895 if (!Old) { 2896 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2897 if (New->getFriendObjectKind()) { 2898 Diag(New->getLocation(), diag::err_using_decl_friend); 2899 Diag(Shadow->getTargetDecl()->getLocation(), 2900 diag::note_using_decl_target); 2901 Diag(Shadow->getUsingDecl()->getLocation(), 2902 diag::note_using_decl) << 0; 2903 return true; 2904 } 2905 2906 // Check whether the two declarations might declare the same function. 2907 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2908 return true; 2909 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2910 } else { 2911 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2912 << New->getDeclName(); 2913 notePreviousDefinition(OldD, New->getLocation()); 2914 return true; 2915 } 2916 } 2917 2918 // If the old declaration is invalid, just give up here. 2919 if (Old->isInvalidDecl()) 2920 return true; 2921 2922 diag::kind PrevDiag; 2923 SourceLocation OldLocation; 2924 std::tie(PrevDiag, OldLocation) = 2925 getNoteDiagForInvalidRedeclaration(Old, New); 2926 2927 // Don't complain about this if we're in GNU89 mode and the old function 2928 // is an extern inline function. 2929 // Don't complain about specializations. They are not supposed to have 2930 // storage classes. 2931 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2932 New->getStorageClass() == SC_Static && 2933 Old->hasExternalFormalLinkage() && 2934 !New->getTemplateSpecializationInfo() && 2935 !canRedefineFunction(Old, getLangOpts())) { 2936 if (getLangOpts().MicrosoftExt) { 2937 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2938 Diag(OldLocation, PrevDiag); 2939 } else { 2940 Diag(New->getLocation(), diag::err_static_non_static) << New; 2941 Diag(OldLocation, PrevDiag); 2942 return true; 2943 } 2944 } 2945 2946 if (New->hasAttr<InternalLinkageAttr>() && 2947 !Old->hasAttr<InternalLinkageAttr>()) { 2948 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2949 << New->getDeclName(); 2950 notePreviousDefinition(Old, New->getLocation()); 2951 New->dropAttr<InternalLinkageAttr>(); 2952 } 2953 2954 if (!getLangOpts().CPlusPlus) { 2955 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 2956 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 2957 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 2958 << New << OldOvl; 2959 2960 // Try our best to find a decl that actually has the overloadable 2961 // attribute for the note. In most cases (e.g. programs with only one 2962 // broken declaration/definition), this won't matter. 2963 // 2964 // FIXME: We could do this if we juggled some extra state in 2965 // OverloadableAttr, rather than just removing it. 2966 const Decl *DiagOld = Old; 2967 if (OldOvl) { 2968 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 2969 const auto *A = D->getAttr<OverloadableAttr>(); 2970 return A && !A->isImplicit(); 2971 }); 2972 // If we've implicitly added *all* of the overloadable attrs to this 2973 // chain, emitting a "previous redecl" note is pointless. 2974 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 2975 } 2976 2977 if (DiagOld) 2978 Diag(DiagOld->getLocation(), 2979 diag::note_attribute_overloadable_prev_overload) 2980 << OldOvl; 2981 2982 if (OldOvl) 2983 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 2984 else 2985 New->dropAttr<OverloadableAttr>(); 2986 } 2987 } 2988 2989 // If a function is first declared with a calling convention, but is later 2990 // declared or defined without one, all following decls assume the calling 2991 // convention of the first. 2992 // 2993 // It's OK if a function is first declared without a calling convention, 2994 // but is later declared or defined with the default calling convention. 2995 // 2996 // To test if either decl has an explicit calling convention, we look for 2997 // AttributedType sugar nodes on the type as written. If they are missing or 2998 // were canonicalized away, we assume the calling convention was implicit. 2999 // 3000 // Note also that we DO NOT return at this point, because we still have 3001 // other tests to run. 3002 QualType OldQType = Context.getCanonicalType(Old->getType()); 3003 QualType NewQType = Context.getCanonicalType(New->getType()); 3004 const FunctionType *OldType = cast<FunctionType>(OldQType); 3005 const FunctionType *NewType = cast<FunctionType>(NewQType); 3006 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3007 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3008 bool RequiresAdjustment = false; 3009 3010 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3011 FunctionDecl *First = Old->getFirstDecl(); 3012 const FunctionType *FT = 3013 First->getType().getCanonicalType()->castAs<FunctionType>(); 3014 FunctionType::ExtInfo FI = FT->getExtInfo(); 3015 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3016 if (!NewCCExplicit) { 3017 // Inherit the CC from the previous declaration if it was specified 3018 // there but not here. 3019 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3020 RequiresAdjustment = true; 3021 } else { 3022 // Calling conventions aren't compatible, so complain. 3023 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3024 Diag(New->getLocation(), diag::err_cconv_change) 3025 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3026 << !FirstCCExplicit 3027 << (!FirstCCExplicit ? "" : 3028 FunctionType::getNameForCallConv(FI.getCC())); 3029 3030 // Put the note on the first decl, since it is the one that matters. 3031 Diag(First->getLocation(), diag::note_previous_declaration); 3032 return true; 3033 } 3034 } 3035 3036 // FIXME: diagnose the other way around? 3037 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3038 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3039 RequiresAdjustment = true; 3040 } 3041 3042 // Merge regparm attribute. 3043 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3044 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3045 if (NewTypeInfo.getHasRegParm()) { 3046 Diag(New->getLocation(), diag::err_regparm_mismatch) 3047 << NewType->getRegParmType() 3048 << OldType->getRegParmType(); 3049 Diag(OldLocation, diag::note_previous_declaration); 3050 return true; 3051 } 3052 3053 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3054 RequiresAdjustment = true; 3055 } 3056 3057 // Merge ns_returns_retained attribute. 3058 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3059 if (NewTypeInfo.getProducesResult()) { 3060 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3061 << "'ns_returns_retained'"; 3062 Diag(OldLocation, diag::note_previous_declaration); 3063 return true; 3064 } 3065 3066 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3067 RequiresAdjustment = true; 3068 } 3069 3070 if (OldTypeInfo.getNoCallerSavedRegs() != 3071 NewTypeInfo.getNoCallerSavedRegs()) { 3072 if (NewTypeInfo.getNoCallerSavedRegs()) { 3073 AnyX86NoCallerSavedRegistersAttr *Attr = 3074 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3075 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3076 Diag(OldLocation, diag::note_previous_declaration); 3077 return true; 3078 } 3079 3080 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3081 RequiresAdjustment = true; 3082 } 3083 3084 if (RequiresAdjustment) { 3085 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3086 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3087 New->setType(QualType(AdjustedType, 0)); 3088 NewQType = Context.getCanonicalType(New->getType()); 3089 NewType = cast<FunctionType>(NewQType); 3090 } 3091 3092 // If this redeclaration makes the function inline, we may need to add it to 3093 // UndefinedButUsed. 3094 if (!Old->isInlined() && New->isInlined() && 3095 !New->hasAttr<GNUInlineAttr>() && 3096 !getLangOpts().GNUInline && 3097 Old->isUsed(false) && 3098 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3099 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3100 SourceLocation())); 3101 3102 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3103 // about it. 3104 if (New->hasAttr<GNUInlineAttr>() && 3105 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3106 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3107 } 3108 3109 // If pass_object_size params don't match up perfectly, this isn't a valid 3110 // redeclaration. 3111 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3112 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3113 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3114 << New->getDeclName(); 3115 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3116 return true; 3117 } 3118 3119 if (getLangOpts().CPlusPlus) { 3120 // C++1z [over.load]p2 3121 // Certain function declarations cannot be overloaded: 3122 // -- Function declarations that differ only in the return type, 3123 // the exception specification, or both cannot be overloaded. 3124 3125 // Check the exception specifications match. This may recompute the type of 3126 // both Old and New if it resolved exception specifications, so grab the 3127 // types again after this. Because this updates the type, we do this before 3128 // any of the other checks below, which may update the "de facto" NewQType 3129 // but do not necessarily update the type of New. 3130 if (CheckEquivalentExceptionSpec(Old, New)) 3131 return true; 3132 OldQType = Context.getCanonicalType(Old->getType()); 3133 NewQType = Context.getCanonicalType(New->getType()); 3134 3135 // Go back to the type source info to compare the declared return types, 3136 // per C++1y [dcl.type.auto]p13: 3137 // Redeclarations or specializations of a function or function template 3138 // with a declared return type that uses a placeholder type shall also 3139 // use that placeholder, not a deduced type. 3140 QualType OldDeclaredReturnType = 3141 (Old->getTypeSourceInfo() 3142 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3143 : OldType)->getReturnType(); 3144 QualType NewDeclaredReturnType = 3145 (New->getTypeSourceInfo() 3146 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3147 : NewType)->getReturnType(); 3148 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3149 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3150 New->isLocalExternDecl())) { 3151 QualType ResQT; 3152 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3153 OldDeclaredReturnType->isObjCObjectPointerType()) 3154 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3155 if (ResQT.isNull()) { 3156 if (New->isCXXClassMember() && New->isOutOfLine()) 3157 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3158 << New << New->getReturnTypeSourceRange(); 3159 else 3160 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3161 << New->getReturnTypeSourceRange(); 3162 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3163 << Old->getReturnTypeSourceRange(); 3164 return true; 3165 } 3166 else 3167 NewQType = ResQT; 3168 } 3169 3170 QualType OldReturnType = OldType->getReturnType(); 3171 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3172 if (OldReturnType != NewReturnType) { 3173 // If this function has a deduced return type and has already been 3174 // defined, copy the deduced value from the old declaration. 3175 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3176 if (OldAT && OldAT->isDeduced()) { 3177 New->setType( 3178 SubstAutoType(New->getType(), 3179 OldAT->isDependentType() ? Context.DependentTy 3180 : OldAT->getDeducedType())); 3181 NewQType = Context.getCanonicalType( 3182 SubstAutoType(NewQType, 3183 OldAT->isDependentType() ? Context.DependentTy 3184 : OldAT->getDeducedType())); 3185 } 3186 } 3187 3188 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3189 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3190 if (OldMethod && NewMethod) { 3191 // Preserve triviality. 3192 NewMethod->setTrivial(OldMethod->isTrivial()); 3193 3194 // MSVC allows explicit template specialization at class scope: 3195 // 2 CXXMethodDecls referring to the same function will be injected. 3196 // We don't want a redeclaration error. 3197 bool IsClassScopeExplicitSpecialization = 3198 OldMethod->isFunctionTemplateSpecialization() && 3199 NewMethod->isFunctionTemplateSpecialization(); 3200 bool isFriend = NewMethod->getFriendObjectKind(); 3201 3202 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3203 !IsClassScopeExplicitSpecialization) { 3204 // -- Member function declarations with the same name and the 3205 // same parameter types cannot be overloaded if any of them 3206 // is a static member function declaration. 3207 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3208 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3209 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3210 return true; 3211 } 3212 3213 // C++ [class.mem]p1: 3214 // [...] A member shall not be declared twice in the 3215 // member-specification, except that a nested class or member 3216 // class template can be declared and then later defined. 3217 if (!inTemplateInstantiation()) { 3218 unsigned NewDiag; 3219 if (isa<CXXConstructorDecl>(OldMethod)) 3220 NewDiag = diag::err_constructor_redeclared; 3221 else if (isa<CXXDestructorDecl>(NewMethod)) 3222 NewDiag = diag::err_destructor_redeclared; 3223 else if (isa<CXXConversionDecl>(NewMethod)) 3224 NewDiag = diag::err_conv_function_redeclared; 3225 else 3226 NewDiag = diag::err_member_redeclared; 3227 3228 Diag(New->getLocation(), NewDiag); 3229 } else { 3230 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3231 << New << New->getType(); 3232 } 3233 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3234 return true; 3235 3236 // Complain if this is an explicit declaration of a special 3237 // member that was initially declared implicitly. 3238 // 3239 // As an exception, it's okay to befriend such methods in order 3240 // to permit the implicit constructor/destructor/operator calls. 3241 } else if (OldMethod->isImplicit()) { 3242 if (isFriend) { 3243 NewMethod->setImplicit(); 3244 } else { 3245 Diag(NewMethod->getLocation(), 3246 diag::err_definition_of_implicitly_declared_member) 3247 << New << getSpecialMember(OldMethod); 3248 return true; 3249 } 3250 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3251 Diag(NewMethod->getLocation(), 3252 diag::err_definition_of_explicitly_defaulted_member) 3253 << getSpecialMember(OldMethod); 3254 return true; 3255 } 3256 } 3257 3258 // C++11 [dcl.attr.noreturn]p1: 3259 // The first declaration of a function shall specify the noreturn 3260 // attribute if any declaration of that function specifies the noreturn 3261 // attribute. 3262 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3263 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3264 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3265 Diag(Old->getFirstDecl()->getLocation(), 3266 diag::note_noreturn_missing_first_decl); 3267 } 3268 3269 // C++11 [dcl.attr.depend]p2: 3270 // The first declaration of a function shall specify the 3271 // carries_dependency attribute for its declarator-id if any declaration 3272 // of the function specifies the carries_dependency attribute. 3273 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3274 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3275 Diag(CDA->getLocation(), 3276 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3277 Diag(Old->getFirstDecl()->getLocation(), 3278 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3279 } 3280 3281 // (C++98 8.3.5p3): 3282 // All declarations for a function shall agree exactly in both the 3283 // return type and the parameter-type-list. 3284 // We also want to respect all the extended bits except noreturn. 3285 3286 // noreturn should now match unless the old type info didn't have it. 3287 QualType OldQTypeForComparison = OldQType; 3288 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3289 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3290 const FunctionType *OldTypeForComparison 3291 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3292 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3293 assert(OldQTypeForComparison.isCanonical()); 3294 } 3295 3296 if (haveIncompatibleLanguageLinkages(Old, New)) { 3297 // As a special case, retain the language linkage from previous 3298 // declarations of a friend function as an extension. 3299 // 3300 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3301 // and is useful because there's otherwise no way to specify language 3302 // linkage within class scope. 3303 // 3304 // Check cautiously as the friend object kind isn't yet complete. 3305 if (New->getFriendObjectKind() != Decl::FOK_None) { 3306 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3307 Diag(OldLocation, PrevDiag); 3308 } else { 3309 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3310 Diag(OldLocation, PrevDiag); 3311 return true; 3312 } 3313 } 3314 3315 if (OldQTypeForComparison == NewQType) 3316 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3317 3318 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3319 New->isLocalExternDecl()) { 3320 // It's OK if we couldn't merge types for a local function declaraton 3321 // if either the old or new type is dependent. We'll merge the types 3322 // when we instantiate the function. 3323 return false; 3324 } 3325 3326 // Fall through for conflicting redeclarations and redefinitions. 3327 } 3328 3329 // C: Function types need to be compatible, not identical. This handles 3330 // duplicate function decls like "void f(int); void f(enum X);" properly. 3331 if (!getLangOpts().CPlusPlus && 3332 Context.typesAreCompatible(OldQType, NewQType)) { 3333 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3334 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3335 const FunctionProtoType *OldProto = nullptr; 3336 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3337 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3338 // The old declaration provided a function prototype, but the 3339 // new declaration does not. Merge in the prototype. 3340 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3341 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3342 NewQType = 3343 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3344 OldProto->getExtProtoInfo()); 3345 New->setType(NewQType); 3346 New->setHasInheritedPrototype(); 3347 3348 // Synthesize parameters with the same types. 3349 SmallVector<ParmVarDecl*, 16> Params; 3350 for (const auto &ParamType : OldProto->param_types()) { 3351 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3352 SourceLocation(), nullptr, 3353 ParamType, /*TInfo=*/nullptr, 3354 SC_None, nullptr); 3355 Param->setScopeInfo(0, Params.size()); 3356 Param->setImplicit(); 3357 Params.push_back(Param); 3358 } 3359 3360 New->setParams(Params); 3361 } 3362 3363 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3364 } 3365 3366 // GNU C permits a K&R definition to follow a prototype declaration 3367 // if the declared types of the parameters in the K&R definition 3368 // match the types in the prototype declaration, even when the 3369 // promoted types of the parameters from the K&R definition differ 3370 // from the types in the prototype. GCC then keeps the types from 3371 // the prototype. 3372 // 3373 // If a variadic prototype is followed by a non-variadic K&R definition, 3374 // the K&R definition becomes variadic. This is sort of an edge case, but 3375 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3376 // C99 6.9.1p8. 3377 if (!getLangOpts().CPlusPlus && 3378 Old->hasPrototype() && !New->hasPrototype() && 3379 New->getType()->getAs<FunctionProtoType>() && 3380 Old->getNumParams() == New->getNumParams()) { 3381 SmallVector<QualType, 16> ArgTypes; 3382 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3383 const FunctionProtoType *OldProto 3384 = Old->getType()->getAs<FunctionProtoType>(); 3385 const FunctionProtoType *NewProto 3386 = New->getType()->getAs<FunctionProtoType>(); 3387 3388 // Determine whether this is the GNU C extension. 3389 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3390 NewProto->getReturnType()); 3391 bool LooseCompatible = !MergedReturn.isNull(); 3392 for (unsigned Idx = 0, End = Old->getNumParams(); 3393 LooseCompatible && Idx != End; ++Idx) { 3394 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3395 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3396 if (Context.typesAreCompatible(OldParm->getType(), 3397 NewProto->getParamType(Idx))) { 3398 ArgTypes.push_back(NewParm->getType()); 3399 } else if (Context.typesAreCompatible(OldParm->getType(), 3400 NewParm->getType(), 3401 /*CompareUnqualified=*/true)) { 3402 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3403 NewProto->getParamType(Idx) }; 3404 Warnings.push_back(Warn); 3405 ArgTypes.push_back(NewParm->getType()); 3406 } else 3407 LooseCompatible = false; 3408 } 3409 3410 if (LooseCompatible) { 3411 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3412 Diag(Warnings[Warn].NewParm->getLocation(), 3413 diag::ext_param_promoted_not_compatible_with_prototype) 3414 << Warnings[Warn].PromotedType 3415 << Warnings[Warn].OldParm->getType(); 3416 if (Warnings[Warn].OldParm->getLocation().isValid()) 3417 Diag(Warnings[Warn].OldParm->getLocation(), 3418 diag::note_previous_declaration); 3419 } 3420 3421 if (MergeTypeWithOld) 3422 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3423 OldProto->getExtProtoInfo())); 3424 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3425 } 3426 3427 // Fall through to diagnose conflicting types. 3428 } 3429 3430 // A function that has already been declared has been redeclared or 3431 // defined with a different type; show an appropriate diagnostic. 3432 3433 // If the previous declaration was an implicitly-generated builtin 3434 // declaration, then at the very least we should use a specialized note. 3435 unsigned BuiltinID; 3436 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3437 // If it's actually a library-defined builtin function like 'malloc' 3438 // or 'printf', just warn about the incompatible redeclaration. 3439 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3440 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3441 Diag(OldLocation, diag::note_previous_builtin_declaration) 3442 << Old << Old->getType(); 3443 3444 // If this is a global redeclaration, just forget hereafter 3445 // about the "builtin-ness" of the function. 3446 // 3447 // Doing this for local extern declarations is problematic. If 3448 // the builtin declaration remains visible, a second invalid 3449 // local declaration will produce a hard error; if it doesn't 3450 // remain visible, a single bogus local redeclaration (which is 3451 // actually only a warning) could break all the downstream code. 3452 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3453 New->getIdentifier()->revertBuiltin(); 3454 3455 return false; 3456 } 3457 3458 PrevDiag = diag::note_previous_builtin_declaration; 3459 } 3460 3461 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3462 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3463 return true; 3464 } 3465 3466 /// \brief Completes the merge of two function declarations that are 3467 /// known to be compatible. 3468 /// 3469 /// This routine handles the merging of attributes and other 3470 /// properties of function declarations from the old declaration to 3471 /// the new declaration, once we know that New is in fact a 3472 /// redeclaration of Old. 3473 /// 3474 /// \returns false 3475 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3476 Scope *S, bool MergeTypeWithOld) { 3477 // Merge the attributes 3478 mergeDeclAttributes(New, Old); 3479 3480 // Merge "pure" flag. 3481 if (Old->isPure()) 3482 New->setPure(); 3483 3484 // Merge "used" flag. 3485 if (Old->getMostRecentDecl()->isUsed(false)) 3486 New->setIsUsed(); 3487 3488 // Merge attributes from the parameters. These can mismatch with K&R 3489 // declarations. 3490 if (New->getNumParams() == Old->getNumParams()) 3491 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3492 ParmVarDecl *NewParam = New->getParamDecl(i); 3493 ParmVarDecl *OldParam = Old->getParamDecl(i); 3494 mergeParamDeclAttributes(NewParam, OldParam, *this); 3495 mergeParamDeclTypes(NewParam, OldParam, *this); 3496 } 3497 3498 if (getLangOpts().CPlusPlus) 3499 return MergeCXXFunctionDecl(New, Old, S); 3500 3501 // Merge the function types so the we get the composite types for the return 3502 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3503 // was visible. 3504 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3505 if (!Merged.isNull() && MergeTypeWithOld) 3506 New->setType(Merged); 3507 3508 return false; 3509 } 3510 3511 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3512 ObjCMethodDecl *oldMethod) { 3513 // Merge the attributes, including deprecated/unavailable 3514 AvailabilityMergeKind MergeKind = 3515 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3516 ? AMK_ProtocolImplementation 3517 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3518 : AMK_Override; 3519 3520 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3521 3522 // Merge attributes from the parameters. 3523 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3524 oe = oldMethod->param_end(); 3525 for (ObjCMethodDecl::param_iterator 3526 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3527 ni != ne && oi != oe; ++ni, ++oi) 3528 mergeParamDeclAttributes(*ni, *oi, *this); 3529 3530 CheckObjCMethodOverride(newMethod, oldMethod); 3531 } 3532 3533 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3534 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3535 3536 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3537 ? diag::err_redefinition_different_type 3538 : diag::err_redeclaration_different_type) 3539 << New->getDeclName() << New->getType() << Old->getType(); 3540 3541 diag::kind PrevDiag; 3542 SourceLocation OldLocation; 3543 std::tie(PrevDiag, OldLocation) 3544 = getNoteDiagForInvalidRedeclaration(Old, New); 3545 S.Diag(OldLocation, PrevDiag); 3546 New->setInvalidDecl(); 3547 } 3548 3549 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3550 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3551 /// emitting diagnostics as appropriate. 3552 /// 3553 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3554 /// to here in AddInitializerToDecl. We can't check them before the initializer 3555 /// is attached. 3556 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3557 bool MergeTypeWithOld) { 3558 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3559 return; 3560 3561 QualType MergedT; 3562 if (getLangOpts().CPlusPlus) { 3563 if (New->getType()->isUndeducedType()) { 3564 // We don't know what the new type is until the initializer is attached. 3565 return; 3566 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3567 // These could still be something that needs exception specs checked. 3568 return MergeVarDeclExceptionSpecs(New, Old); 3569 } 3570 // C++ [basic.link]p10: 3571 // [...] the types specified by all declarations referring to a given 3572 // object or function shall be identical, except that declarations for an 3573 // array object can specify array types that differ by the presence or 3574 // absence of a major array bound (8.3.4). 3575 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3576 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3577 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3578 3579 // We are merging a variable declaration New into Old. If it has an array 3580 // bound, and that bound differs from Old's bound, we should diagnose the 3581 // mismatch. 3582 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3583 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3584 PrevVD = PrevVD->getPreviousDecl()) { 3585 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3586 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3587 continue; 3588 3589 if (!Context.hasSameType(NewArray, PrevVDTy)) 3590 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3591 } 3592 } 3593 3594 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3595 if (Context.hasSameType(OldArray->getElementType(), 3596 NewArray->getElementType())) 3597 MergedT = New->getType(); 3598 } 3599 // FIXME: Check visibility. New is hidden but has a complete type. If New 3600 // has no array bound, it should not inherit one from Old, if Old is not 3601 // visible. 3602 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3603 if (Context.hasSameType(OldArray->getElementType(), 3604 NewArray->getElementType())) 3605 MergedT = Old->getType(); 3606 } 3607 } 3608 else if (New->getType()->isObjCObjectPointerType() && 3609 Old->getType()->isObjCObjectPointerType()) { 3610 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3611 Old->getType()); 3612 } 3613 } else { 3614 // C 6.2.7p2: 3615 // All declarations that refer to the same object or function shall have 3616 // compatible type. 3617 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3618 } 3619 if (MergedT.isNull()) { 3620 // It's OK if we couldn't merge types if either type is dependent, for a 3621 // block-scope variable. In other cases (static data members of class 3622 // templates, variable templates, ...), we require the types to be 3623 // equivalent. 3624 // FIXME: The C++ standard doesn't say anything about this. 3625 if ((New->getType()->isDependentType() || 3626 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3627 // If the old type was dependent, we can't merge with it, so the new type 3628 // becomes dependent for now. We'll reproduce the original type when we 3629 // instantiate the TypeSourceInfo for the variable. 3630 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3631 New->setType(Context.DependentTy); 3632 return; 3633 } 3634 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3635 } 3636 3637 // Don't actually update the type on the new declaration if the old 3638 // declaration was an extern declaration in a different scope. 3639 if (MergeTypeWithOld) 3640 New->setType(MergedT); 3641 } 3642 3643 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3644 LookupResult &Previous) { 3645 // C11 6.2.7p4: 3646 // For an identifier with internal or external linkage declared 3647 // in a scope in which a prior declaration of that identifier is 3648 // visible, if the prior declaration specifies internal or 3649 // external linkage, the type of the identifier at the later 3650 // declaration becomes the composite type. 3651 // 3652 // If the variable isn't visible, we do not merge with its type. 3653 if (Previous.isShadowed()) 3654 return false; 3655 3656 if (S.getLangOpts().CPlusPlus) { 3657 // C++11 [dcl.array]p3: 3658 // If there is a preceding declaration of the entity in the same 3659 // scope in which the bound was specified, an omitted array bound 3660 // is taken to be the same as in that earlier declaration. 3661 return NewVD->isPreviousDeclInSameBlockScope() || 3662 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3663 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3664 } else { 3665 // If the old declaration was function-local, don't merge with its 3666 // type unless we're in the same function. 3667 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3668 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3669 } 3670 } 3671 3672 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3673 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3674 /// situation, merging decls or emitting diagnostics as appropriate. 3675 /// 3676 /// Tentative definition rules (C99 6.9.2p2) are checked by 3677 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3678 /// definitions here, since the initializer hasn't been attached. 3679 /// 3680 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3681 // If the new decl is already invalid, don't do any other checking. 3682 if (New->isInvalidDecl()) 3683 return; 3684 3685 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3686 return; 3687 3688 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3689 3690 // Verify the old decl was also a variable or variable template. 3691 VarDecl *Old = nullptr; 3692 VarTemplateDecl *OldTemplate = nullptr; 3693 if (Previous.isSingleResult()) { 3694 if (NewTemplate) { 3695 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3696 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3697 3698 if (auto *Shadow = 3699 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3700 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3701 return New->setInvalidDecl(); 3702 } else { 3703 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3704 3705 if (auto *Shadow = 3706 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3707 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3708 return New->setInvalidDecl(); 3709 } 3710 } 3711 if (!Old) { 3712 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3713 << New->getDeclName(); 3714 notePreviousDefinition(Previous.getRepresentativeDecl(), 3715 New->getLocation()); 3716 return New->setInvalidDecl(); 3717 } 3718 3719 // Ensure the template parameters are compatible. 3720 if (NewTemplate && 3721 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3722 OldTemplate->getTemplateParameters(), 3723 /*Complain=*/true, TPL_TemplateMatch)) 3724 return New->setInvalidDecl(); 3725 3726 // C++ [class.mem]p1: 3727 // A member shall not be declared twice in the member-specification [...] 3728 // 3729 // Here, we need only consider static data members. 3730 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3731 Diag(New->getLocation(), diag::err_duplicate_member) 3732 << New->getIdentifier(); 3733 Diag(Old->getLocation(), diag::note_previous_declaration); 3734 New->setInvalidDecl(); 3735 } 3736 3737 mergeDeclAttributes(New, Old); 3738 // Warn if an already-declared variable is made a weak_import in a subsequent 3739 // declaration 3740 if (New->hasAttr<WeakImportAttr>() && 3741 Old->getStorageClass() == SC_None && 3742 !Old->hasAttr<WeakImportAttr>()) { 3743 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3744 notePreviousDefinition(Old, New->getLocation()); 3745 // Remove weak_import attribute on new declaration. 3746 New->dropAttr<WeakImportAttr>(); 3747 } 3748 3749 if (New->hasAttr<InternalLinkageAttr>() && 3750 !Old->hasAttr<InternalLinkageAttr>()) { 3751 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3752 << New->getDeclName(); 3753 notePreviousDefinition(Old, New->getLocation()); 3754 New->dropAttr<InternalLinkageAttr>(); 3755 } 3756 3757 // Merge the types. 3758 VarDecl *MostRecent = Old->getMostRecentDecl(); 3759 if (MostRecent != Old) { 3760 MergeVarDeclTypes(New, MostRecent, 3761 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3762 if (New->isInvalidDecl()) 3763 return; 3764 } 3765 3766 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3767 if (New->isInvalidDecl()) 3768 return; 3769 3770 diag::kind PrevDiag; 3771 SourceLocation OldLocation; 3772 std::tie(PrevDiag, OldLocation) = 3773 getNoteDiagForInvalidRedeclaration(Old, New); 3774 3775 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3776 if (New->getStorageClass() == SC_Static && 3777 !New->isStaticDataMember() && 3778 Old->hasExternalFormalLinkage()) { 3779 if (getLangOpts().MicrosoftExt) { 3780 Diag(New->getLocation(), diag::ext_static_non_static) 3781 << New->getDeclName(); 3782 Diag(OldLocation, PrevDiag); 3783 } else { 3784 Diag(New->getLocation(), diag::err_static_non_static) 3785 << New->getDeclName(); 3786 Diag(OldLocation, PrevDiag); 3787 return New->setInvalidDecl(); 3788 } 3789 } 3790 // C99 6.2.2p4: 3791 // For an identifier declared with the storage-class specifier 3792 // extern in a scope in which a prior declaration of that 3793 // identifier is visible,23) if the prior declaration specifies 3794 // internal or external linkage, the linkage of the identifier at 3795 // the later declaration is the same as the linkage specified at 3796 // the prior declaration. If no prior declaration is visible, or 3797 // if the prior declaration specifies no linkage, then the 3798 // identifier has external linkage. 3799 if (New->hasExternalStorage() && Old->hasLinkage()) 3800 /* Okay */; 3801 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3802 !New->isStaticDataMember() && 3803 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3804 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3805 Diag(OldLocation, PrevDiag); 3806 return New->setInvalidDecl(); 3807 } 3808 3809 // Check if extern is followed by non-extern and vice-versa. 3810 if (New->hasExternalStorage() && 3811 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3812 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3813 Diag(OldLocation, PrevDiag); 3814 return New->setInvalidDecl(); 3815 } 3816 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3817 !New->hasExternalStorage()) { 3818 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3819 Diag(OldLocation, PrevDiag); 3820 return New->setInvalidDecl(); 3821 } 3822 3823 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3824 3825 // FIXME: The test for external storage here seems wrong? We still 3826 // need to check for mismatches. 3827 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3828 // Don't complain about out-of-line definitions of static members. 3829 !(Old->getLexicalDeclContext()->isRecord() && 3830 !New->getLexicalDeclContext()->isRecord())) { 3831 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3832 Diag(OldLocation, PrevDiag); 3833 return New->setInvalidDecl(); 3834 } 3835 3836 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3837 if (VarDecl *Def = Old->getDefinition()) { 3838 // C++1z [dcl.fcn.spec]p4: 3839 // If the definition of a variable appears in a translation unit before 3840 // its first declaration as inline, the program is ill-formed. 3841 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3842 Diag(Def->getLocation(), diag::note_previous_definition); 3843 } 3844 } 3845 3846 // If this redeclaration makes the function inline, we may need to add it to 3847 // UndefinedButUsed. 3848 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3849 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3850 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3851 SourceLocation())); 3852 3853 if (New->getTLSKind() != Old->getTLSKind()) { 3854 if (!Old->getTLSKind()) { 3855 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3856 Diag(OldLocation, PrevDiag); 3857 } else if (!New->getTLSKind()) { 3858 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3859 Diag(OldLocation, PrevDiag); 3860 } else { 3861 // Do not allow redeclaration to change the variable between requiring 3862 // static and dynamic initialization. 3863 // FIXME: GCC allows this, but uses the TLS keyword on the first 3864 // declaration to determine the kind. Do we need to be compatible here? 3865 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3866 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3867 Diag(OldLocation, PrevDiag); 3868 } 3869 } 3870 3871 // C++ doesn't have tentative definitions, so go right ahead and check here. 3872 if (getLangOpts().CPlusPlus && 3873 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3874 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3875 Old->getCanonicalDecl()->isConstexpr()) { 3876 // This definition won't be a definition any more once it's been merged. 3877 Diag(New->getLocation(), 3878 diag::warn_deprecated_redundant_constexpr_static_def); 3879 } else if (VarDecl *Def = Old->getDefinition()) { 3880 if (checkVarDeclRedefinition(Def, New)) 3881 return; 3882 } 3883 } 3884 3885 if (haveIncompatibleLanguageLinkages(Old, New)) { 3886 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3887 Diag(OldLocation, PrevDiag); 3888 New->setInvalidDecl(); 3889 return; 3890 } 3891 3892 // Merge "used" flag. 3893 if (Old->getMostRecentDecl()->isUsed(false)) 3894 New->setIsUsed(); 3895 3896 // Keep a chain of previous declarations. 3897 New->setPreviousDecl(Old); 3898 if (NewTemplate) 3899 NewTemplate->setPreviousDecl(OldTemplate); 3900 3901 // Inherit access appropriately. 3902 New->setAccess(Old->getAccess()); 3903 if (NewTemplate) 3904 NewTemplate->setAccess(New->getAccess()); 3905 3906 if (Old->isInline()) 3907 New->setImplicitlyInline(); 3908 } 3909 3910 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 3911 SourceManager &SrcMgr = getSourceManager(); 3912 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3913 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3914 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3915 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3916 auto &HSI = PP.getHeaderSearchInfo(); 3917 StringRef HdrFilename = 3918 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3919 3920 auto noteFromModuleOrInclude = [&](Module *Mod, 3921 SourceLocation IncLoc) -> bool { 3922 // Redefinition errors with modules are common with non modular mapped 3923 // headers, example: a non-modular header H in module A that also gets 3924 // included directly in a TU. Pointing twice to the same header/definition 3925 // is confusing, try to get better diagnostics when modules is on. 3926 if (IncLoc.isValid()) { 3927 if (Mod) { 3928 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3929 << HdrFilename.str() << Mod->getFullModuleName(); 3930 if (!Mod->DefinitionLoc.isInvalid()) 3931 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3932 << Mod->getFullModuleName(); 3933 } else { 3934 Diag(IncLoc, diag::note_redefinition_include_same_file) 3935 << HdrFilename.str(); 3936 } 3937 return true; 3938 } 3939 3940 return false; 3941 }; 3942 3943 // Is it the same file and same offset? Provide more information on why 3944 // this leads to a redefinition error. 3945 bool EmittedDiag = false; 3946 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3947 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3948 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3949 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 3950 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 3951 3952 // If the header has no guards, emit a note suggesting one. 3953 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3954 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 3955 3956 if (EmittedDiag) 3957 return; 3958 } 3959 3960 // Redefinition coming from different files or couldn't do better above. 3961 Diag(Old->getLocation(), diag::note_previous_definition); 3962 } 3963 3964 /// We've just determined that \p Old and \p New both appear to be definitions 3965 /// of the same variable. Either diagnose or fix the problem. 3966 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3967 if (!hasVisibleDefinition(Old) && 3968 (New->getFormalLinkage() == InternalLinkage || 3969 New->isInline() || 3970 New->getDescribedVarTemplate() || 3971 New->getNumTemplateParameterLists() || 3972 New->getDeclContext()->isDependentContext())) { 3973 // The previous definition is hidden, and multiple definitions are 3974 // permitted (in separate TUs). Demote this to a declaration. 3975 New->demoteThisDefinitionToDeclaration(); 3976 3977 // Make the canonical definition visible. 3978 if (auto *OldTD = Old->getDescribedVarTemplate()) 3979 makeMergedDefinitionVisible(OldTD); 3980 makeMergedDefinitionVisible(Old); 3981 return false; 3982 } else { 3983 Diag(New->getLocation(), diag::err_redefinition) << New; 3984 notePreviousDefinition(Old, New->getLocation()); 3985 New->setInvalidDecl(); 3986 return true; 3987 } 3988 } 3989 3990 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3991 /// no declarator (e.g. "struct foo;") is parsed. 3992 Decl * 3993 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3994 RecordDecl *&AnonRecord) { 3995 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3996 AnonRecord); 3997 } 3998 3999 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4000 // disambiguate entities defined in different scopes. 4001 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4002 // compatibility. 4003 // We will pick our mangling number depending on which version of MSVC is being 4004 // targeted. 4005 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4006 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4007 ? S->getMSCurManglingNumber() 4008 : S->getMSLastManglingNumber(); 4009 } 4010 4011 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4012 if (!Context.getLangOpts().CPlusPlus) 4013 return; 4014 4015 if (isa<CXXRecordDecl>(Tag->getParent())) { 4016 // If this tag is the direct child of a class, number it if 4017 // it is anonymous. 4018 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4019 return; 4020 MangleNumberingContext &MCtx = 4021 Context.getManglingNumberContext(Tag->getParent()); 4022 Context.setManglingNumber( 4023 Tag, MCtx.getManglingNumber( 4024 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4025 return; 4026 } 4027 4028 // If this tag isn't a direct child of a class, number it if it is local. 4029 Decl *ManglingContextDecl; 4030 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4031 Tag->getDeclContext(), ManglingContextDecl)) { 4032 Context.setManglingNumber( 4033 Tag, MCtx->getManglingNumber( 4034 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4035 } 4036 } 4037 4038 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4039 TypedefNameDecl *NewTD) { 4040 if (TagFromDeclSpec->isInvalidDecl()) 4041 return; 4042 4043 // Do nothing if the tag already has a name for linkage purposes. 4044 if (TagFromDeclSpec->hasNameForLinkage()) 4045 return; 4046 4047 // A well-formed anonymous tag must always be a TUK_Definition. 4048 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4049 4050 // The type must match the tag exactly; no qualifiers allowed. 4051 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4052 Context.getTagDeclType(TagFromDeclSpec))) { 4053 if (getLangOpts().CPlusPlus) 4054 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4055 return; 4056 } 4057 4058 // If we've already computed linkage for the anonymous tag, then 4059 // adding a typedef name for the anonymous decl can change that 4060 // linkage, which might be a serious problem. Diagnose this as 4061 // unsupported and ignore the typedef name. TODO: we should 4062 // pursue this as a language defect and establish a formal rule 4063 // for how to handle it. 4064 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4065 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4066 4067 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4068 tagLoc = getLocForEndOfToken(tagLoc); 4069 4070 llvm::SmallString<40> textToInsert; 4071 textToInsert += ' '; 4072 textToInsert += NewTD->getIdentifier()->getName(); 4073 Diag(tagLoc, diag::note_typedef_changes_linkage) 4074 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4075 return; 4076 } 4077 4078 // Otherwise, set this is the anon-decl typedef for the tag. 4079 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4080 } 4081 4082 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4083 switch (T) { 4084 case DeclSpec::TST_class: 4085 return 0; 4086 case DeclSpec::TST_struct: 4087 return 1; 4088 case DeclSpec::TST_interface: 4089 return 2; 4090 case DeclSpec::TST_union: 4091 return 3; 4092 case DeclSpec::TST_enum: 4093 return 4; 4094 default: 4095 llvm_unreachable("unexpected type specifier"); 4096 } 4097 } 4098 4099 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4100 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4101 /// parameters to cope with template friend declarations. 4102 Decl * 4103 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4104 MultiTemplateParamsArg TemplateParams, 4105 bool IsExplicitInstantiation, 4106 RecordDecl *&AnonRecord) { 4107 Decl *TagD = nullptr; 4108 TagDecl *Tag = nullptr; 4109 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4110 DS.getTypeSpecType() == DeclSpec::TST_struct || 4111 DS.getTypeSpecType() == DeclSpec::TST_interface || 4112 DS.getTypeSpecType() == DeclSpec::TST_union || 4113 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4114 TagD = DS.getRepAsDecl(); 4115 4116 if (!TagD) // We probably had an error 4117 return nullptr; 4118 4119 // Note that the above type specs guarantee that the 4120 // type rep is a Decl, whereas in many of the others 4121 // it's a Type. 4122 if (isa<TagDecl>(TagD)) 4123 Tag = cast<TagDecl>(TagD); 4124 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4125 Tag = CTD->getTemplatedDecl(); 4126 } 4127 4128 if (Tag) { 4129 handleTagNumbering(Tag, S); 4130 Tag->setFreeStanding(); 4131 if (Tag->isInvalidDecl()) 4132 return Tag; 4133 } 4134 4135 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4136 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4137 // or incomplete types shall not be restrict-qualified." 4138 if (TypeQuals & DeclSpec::TQ_restrict) 4139 Diag(DS.getRestrictSpecLoc(), 4140 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4141 << DS.getSourceRange(); 4142 } 4143 4144 if (DS.isInlineSpecified()) 4145 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4146 << getLangOpts().CPlusPlus1z; 4147 4148 if (DS.isConstexprSpecified()) { 4149 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4150 // and definitions of functions and variables. 4151 if (Tag) 4152 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4153 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4154 else 4155 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4156 // Don't emit warnings after this error. 4157 return TagD; 4158 } 4159 4160 if (DS.isConceptSpecified()) { 4161 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4162 // either a function concept and its definition or a variable concept and 4163 // its initializer. 4164 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4165 return TagD; 4166 } 4167 4168 DiagnoseFunctionSpecifiers(DS); 4169 4170 if (DS.isFriendSpecified()) { 4171 // If we're dealing with a decl but not a TagDecl, assume that 4172 // whatever routines created it handled the friendship aspect. 4173 if (TagD && !Tag) 4174 return nullptr; 4175 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4176 } 4177 4178 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4179 bool IsExplicitSpecialization = 4180 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4181 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4182 !IsExplicitInstantiation && !IsExplicitSpecialization && 4183 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4184 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4185 // nested-name-specifier unless it is an explicit instantiation 4186 // or an explicit specialization. 4187 // 4188 // FIXME: We allow class template partial specializations here too, per the 4189 // obvious intent of DR1819. 4190 // 4191 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4192 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4193 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4194 return nullptr; 4195 } 4196 4197 // Track whether this decl-specifier declares anything. 4198 bool DeclaresAnything = true; 4199 4200 // Handle anonymous struct definitions. 4201 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4202 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4203 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4204 if (getLangOpts().CPlusPlus || 4205 Record->getDeclContext()->isRecord()) { 4206 // If CurContext is a DeclContext that can contain statements, 4207 // RecursiveASTVisitor won't visit the decls that 4208 // BuildAnonymousStructOrUnion() will put into CurContext. 4209 // Also store them here so that they can be part of the 4210 // DeclStmt that gets created in this case. 4211 // FIXME: Also return the IndirectFieldDecls created by 4212 // BuildAnonymousStructOr union, for the same reason? 4213 if (CurContext->isFunctionOrMethod()) 4214 AnonRecord = Record; 4215 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4216 Context.getPrintingPolicy()); 4217 } 4218 4219 DeclaresAnything = false; 4220 } 4221 } 4222 4223 // C11 6.7.2.1p2: 4224 // A struct-declaration that does not declare an anonymous structure or 4225 // anonymous union shall contain a struct-declarator-list. 4226 // 4227 // This rule also existed in C89 and C99; the grammar for struct-declaration 4228 // did not permit a struct-declaration without a struct-declarator-list. 4229 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4230 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4231 // Check for Microsoft C extension: anonymous struct/union member. 4232 // Handle 2 kinds of anonymous struct/union: 4233 // struct STRUCT; 4234 // union UNION; 4235 // and 4236 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4237 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4238 if ((Tag && Tag->getDeclName()) || 4239 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4240 RecordDecl *Record = nullptr; 4241 if (Tag) 4242 Record = dyn_cast<RecordDecl>(Tag); 4243 else if (const RecordType *RT = 4244 DS.getRepAsType().get()->getAsStructureType()) 4245 Record = RT->getDecl(); 4246 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4247 Record = UT->getDecl(); 4248 4249 if (Record && getLangOpts().MicrosoftExt) { 4250 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4251 << Record->isUnion() << DS.getSourceRange(); 4252 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4253 } 4254 4255 DeclaresAnything = false; 4256 } 4257 } 4258 4259 // Skip all the checks below if we have a type error. 4260 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4261 (TagD && TagD->isInvalidDecl())) 4262 return TagD; 4263 4264 if (getLangOpts().CPlusPlus && 4265 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4266 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4267 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4268 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4269 DeclaresAnything = false; 4270 4271 if (!DS.isMissingDeclaratorOk()) { 4272 // Customize diagnostic for a typedef missing a name. 4273 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4274 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4275 << DS.getSourceRange(); 4276 else 4277 DeclaresAnything = false; 4278 } 4279 4280 if (DS.isModulePrivateSpecified() && 4281 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4282 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4283 << Tag->getTagKind() 4284 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4285 4286 ActOnDocumentableDecl(TagD); 4287 4288 // C 6.7/2: 4289 // A declaration [...] shall declare at least a declarator [...], a tag, 4290 // or the members of an enumeration. 4291 // C++ [dcl.dcl]p3: 4292 // [If there are no declarators], and except for the declaration of an 4293 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4294 // names into the program, or shall redeclare a name introduced by a 4295 // previous declaration. 4296 if (!DeclaresAnything) { 4297 // In C, we allow this as a (popular) extension / bug. Don't bother 4298 // producing further diagnostics for redundant qualifiers after this. 4299 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4300 return TagD; 4301 } 4302 4303 // C++ [dcl.stc]p1: 4304 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4305 // init-declarator-list of the declaration shall not be empty. 4306 // C++ [dcl.fct.spec]p1: 4307 // If a cv-qualifier appears in a decl-specifier-seq, the 4308 // init-declarator-list of the declaration shall not be empty. 4309 // 4310 // Spurious qualifiers here appear to be valid in C. 4311 unsigned DiagID = diag::warn_standalone_specifier; 4312 if (getLangOpts().CPlusPlus) 4313 DiagID = diag::ext_standalone_specifier; 4314 4315 // Note that a linkage-specification sets a storage class, but 4316 // 'extern "C" struct foo;' is actually valid and not theoretically 4317 // useless. 4318 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4319 if (SCS == DeclSpec::SCS_mutable) 4320 // Since mutable is not a viable storage class specifier in C, there is 4321 // no reason to treat it as an extension. Instead, diagnose as an error. 4322 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4323 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4324 Diag(DS.getStorageClassSpecLoc(), DiagID) 4325 << DeclSpec::getSpecifierName(SCS); 4326 } 4327 4328 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4329 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4330 << DeclSpec::getSpecifierName(TSCS); 4331 if (DS.getTypeQualifiers()) { 4332 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4333 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4334 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4335 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4336 // Restrict is covered above. 4337 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4338 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4339 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4340 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4341 } 4342 4343 // Warn about ignored type attributes, for example: 4344 // __attribute__((aligned)) struct A; 4345 // Attributes should be placed after tag to apply to type declaration. 4346 if (!DS.getAttributes().empty()) { 4347 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4348 if (TypeSpecType == DeclSpec::TST_class || 4349 TypeSpecType == DeclSpec::TST_struct || 4350 TypeSpecType == DeclSpec::TST_interface || 4351 TypeSpecType == DeclSpec::TST_union || 4352 TypeSpecType == DeclSpec::TST_enum) { 4353 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4354 attrs = attrs->getNext()) 4355 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4356 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4357 } 4358 } 4359 4360 return TagD; 4361 } 4362 4363 /// We are trying to inject an anonymous member into the given scope; 4364 /// check if there's an existing declaration that can't be overloaded. 4365 /// 4366 /// \return true if this is a forbidden redeclaration 4367 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4368 Scope *S, 4369 DeclContext *Owner, 4370 DeclarationName Name, 4371 SourceLocation NameLoc, 4372 bool IsUnion) { 4373 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4374 Sema::ForRedeclaration); 4375 if (!SemaRef.LookupName(R, S)) return false; 4376 4377 // Pick a representative declaration. 4378 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4379 assert(PrevDecl && "Expected a non-null Decl"); 4380 4381 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4382 return false; 4383 4384 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4385 << IsUnion << Name; 4386 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4387 4388 return true; 4389 } 4390 4391 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4392 /// anonymous struct or union AnonRecord into the owning context Owner 4393 /// and scope S. This routine will be invoked just after we realize 4394 /// that an unnamed union or struct is actually an anonymous union or 4395 /// struct, e.g., 4396 /// 4397 /// @code 4398 /// union { 4399 /// int i; 4400 /// float f; 4401 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4402 /// // f into the surrounding scope.x 4403 /// @endcode 4404 /// 4405 /// This routine is recursive, injecting the names of nested anonymous 4406 /// structs/unions into the owning context and scope as well. 4407 static bool 4408 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4409 RecordDecl *AnonRecord, AccessSpecifier AS, 4410 SmallVectorImpl<NamedDecl *> &Chaining) { 4411 bool Invalid = false; 4412 4413 // Look every FieldDecl and IndirectFieldDecl with a name. 4414 for (auto *D : AnonRecord->decls()) { 4415 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4416 cast<NamedDecl>(D)->getDeclName()) { 4417 ValueDecl *VD = cast<ValueDecl>(D); 4418 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4419 VD->getLocation(), 4420 AnonRecord->isUnion())) { 4421 // C++ [class.union]p2: 4422 // The names of the members of an anonymous union shall be 4423 // distinct from the names of any other entity in the 4424 // scope in which the anonymous union is declared. 4425 Invalid = true; 4426 } else { 4427 // C++ [class.union]p2: 4428 // For the purpose of name lookup, after the anonymous union 4429 // definition, the members of the anonymous union are 4430 // considered to have been defined in the scope in which the 4431 // anonymous union is declared. 4432 unsigned OldChainingSize = Chaining.size(); 4433 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4434 Chaining.append(IF->chain_begin(), IF->chain_end()); 4435 else 4436 Chaining.push_back(VD); 4437 4438 assert(Chaining.size() >= 2); 4439 NamedDecl **NamedChain = 4440 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4441 for (unsigned i = 0; i < Chaining.size(); i++) 4442 NamedChain[i] = Chaining[i]; 4443 4444 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4445 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4446 VD->getType(), {NamedChain, Chaining.size()}); 4447 4448 for (const auto *Attr : VD->attrs()) 4449 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4450 4451 IndirectField->setAccess(AS); 4452 IndirectField->setImplicit(); 4453 SemaRef.PushOnScopeChains(IndirectField, S); 4454 4455 // That includes picking up the appropriate access specifier. 4456 if (AS != AS_none) IndirectField->setAccess(AS); 4457 4458 Chaining.resize(OldChainingSize); 4459 } 4460 } 4461 } 4462 4463 return Invalid; 4464 } 4465 4466 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4467 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4468 /// illegal input values are mapped to SC_None. 4469 static StorageClass 4470 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4471 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4472 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4473 "Parser allowed 'typedef' as storage class VarDecl."); 4474 switch (StorageClassSpec) { 4475 case DeclSpec::SCS_unspecified: return SC_None; 4476 case DeclSpec::SCS_extern: 4477 if (DS.isExternInLinkageSpec()) 4478 return SC_None; 4479 return SC_Extern; 4480 case DeclSpec::SCS_static: return SC_Static; 4481 case DeclSpec::SCS_auto: return SC_Auto; 4482 case DeclSpec::SCS_register: return SC_Register; 4483 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4484 // Illegal SCSs map to None: error reporting is up to the caller. 4485 case DeclSpec::SCS_mutable: // Fall through. 4486 case DeclSpec::SCS_typedef: return SC_None; 4487 } 4488 llvm_unreachable("unknown storage class specifier"); 4489 } 4490 4491 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4492 assert(Record->hasInClassInitializer()); 4493 4494 for (const auto *I : Record->decls()) { 4495 const auto *FD = dyn_cast<FieldDecl>(I); 4496 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4497 FD = IFD->getAnonField(); 4498 if (FD && FD->hasInClassInitializer()) 4499 return FD->getLocation(); 4500 } 4501 4502 llvm_unreachable("couldn't find in-class initializer"); 4503 } 4504 4505 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4506 SourceLocation DefaultInitLoc) { 4507 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4508 return; 4509 4510 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4511 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4512 } 4513 4514 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4515 CXXRecordDecl *AnonUnion) { 4516 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4517 return; 4518 4519 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4520 } 4521 4522 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4523 /// anonymous structure or union. Anonymous unions are a C++ feature 4524 /// (C++ [class.union]) and a C11 feature; anonymous structures 4525 /// are a C11 feature and GNU C++ extension. 4526 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4527 AccessSpecifier AS, 4528 RecordDecl *Record, 4529 const PrintingPolicy &Policy) { 4530 DeclContext *Owner = Record->getDeclContext(); 4531 4532 // Diagnose whether this anonymous struct/union is an extension. 4533 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4534 Diag(Record->getLocation(), diag::ext_anonymous_union); 4535 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4536 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4537 else if (!Record->isUnion() && !getLangOpts().C11) 4538 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4539 4540 // C and C++ require different kinds of checks for anonymous 4541 // structs/unions. 4542 bool Invalid = false; 4543 if (getLangOpts().CPlusPlus) { 4544 const char *PrevSpec = nullptr; 4545 unsigned DiagID; 4546 if (Record->isUnion()) { 4547 // C++ [class.union]p6: 4548 // Anonymous unions declared in a named namespace or in the 4549 // global namespace shall be declared static. 4550 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4551 (isa<TranslationUnitDecl>(Owner) || 4552 (isa<NamespaceDecl>(Owner) && 4553 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4554 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4555 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4556 4557 // Recover by adding 'static'. 4558 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4559 PrevSpec, DiagID, Policy); 4560 } 4561 // C++ [class.union]p6: 4562 // A storage class is not allowed in a declaration of an 4563 // anonymous union in a class scope. 4564 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4565 isa<RecordDecl>(Owner)) { 4566 Diag(DS.getStorageClassSpecLoc(), 4567 diag::err_anonymous_union_with_storage_spec) 4568 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4569 4570 // Recover by removing the storage specifier. 4571 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4572 SourceLocation(), 4573 PrevSpec, DiagID, Context.getPrintingPolicy()); 4574 } 4575 } 4576 4577 // Ignore const/volatile/restrict qualifiers. 4578 if (DS.getTypeQualifiers()) { 4579 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4580 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4581 << Record->isUnion() << "const" 4582 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4583 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4584 Diag(DS.getVolatileSpecLoc(), 4585 diag::ext_anonymous_struct_union_qualified) 4586 << Record->isUnion() << "volatile" 4587 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4588 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4589 Diag(DS.getRestrictSpecLoc(), 4590 diag::ext_anonymous_struct_union_qualified) 4591 << Record->isUnion() << "restrict" 4592 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4593 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4594 Diag(DS.getAtomicSpecLoc(), 4595 diag::ext_anonymous_struct_union_qualified) 4596 << Record->isUnion() << "_Atomic" 4597 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4598 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4599 Diag(DS.getUnalignedSpecLoc(), 4600 diag::ext_anonymous_struct_union_qualified) 4601 << Record->isUnion() << "__unaligned" 4602 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4603 4604 DS.ClearTypeQualifiers(); 4605 } 4606 4607 // C++ [class.union]p2: 4608 // The member-specification of an anonymous union shall only 4609 // define non-static data members. [Note: nested types and 4610 // functions cannot be declared within an anonymous union. ] 4611 for (auto *Mem : Record->decls()) { 4612 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4613 // C++ [class.union]p3: 4614 // An anonymous union shall not have private or protected 4615 // members (clause 11). 4616 assert(FD->getAccess() != AS_none); 4617 if (FD->getAccess() != AS_public) { 4618 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4619 << Record->isUnion() << (FD->getAccess() == AS_protected); 4620 Invalid = true; 4621 } 4622 4623 // C++ [class.union]p1 4624 // An object of a class with a non-trivial constructor, a non-trivial 4625 // copy constructor, a non-trivial destructor, or a non-trivial copy 4626 // assignment operator cannot be a member of a union, nor can an 4627 // array of such objects. 4628 if (CheckNontrivialField(FD)) 4629 Invalid = true; 4630 } else if (Mem->isImplicit()) { 4631 // Any implicit members are fine. 4632 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4633 // This is a type that showed up in an 4634 // elaborated-type-specifier inside the anonymous struct or 4635 // union, but which actually declares a type outside of the 4636 // anonymous struct or union. It's okay. 4637 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4638 if (!MemRecord->isAnonymousStructOrUnion() && 4639 MemRecord->getDeclName()) { 4640 // Visual C++ allows type definition in anonymous struct or union. 4641 if (getLangOpts().MicrosoftExt) 4642 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4643 << Record->isUnion(); 4644 else { 4645 // This is a nested type declaration. 4646 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4647 << Record->isUnion(); 4648 Invalid = true; 4649 } 4650 } else { 4651 // This is an anonymous type definition within another anonymous type. 4652 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4653 // not part of standard C++. 4654 Diag(MemRecord->getLocation(), 4655 diag::ext_anonymous_record_with_anonymous_type) 4656 << Record->isUnion(); 4657 } 4658 } else if (isa<AccessSpecDecl>(Mem)) { 4659 // Any access specifier is fine. 4660 } else if (isa<StaticAssertDecl>(Mem)) { 4661 // In C++1z, static_assert declarations are also fine. 4662 } else { 4663 // We have something that isn't a non-static data 4664 // member. Complain about it. 4665 unsigned DK = diag::err_anonymous_record_bad_member; 4666 if (isa<TypeDecl>(Mem)) 4667 DK = diag::err_anonymous_record_with_type; 4668 else if (isa<FunctionDecl>(Mem)) 4669 DK = diag::err_anonymous_record_with_function; 4670 else if (isa<VarDecl>(Mem)) 4671 DK = diag::err_anonymous_record_with_static; 4672 4673 // Visual C++ allows type definition in anonymous struct or union. 4674 if (getLangOpts().MicrosoftExt && 4675 DK == diag::err_anonymous_record_with_type) 4676 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4677 << Record->isUnion(); 4678 else { 4679 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4680 Invalid = true; 4681 } 4682 } 4683 } 4684 4685 // C++11 [class.union]p8 (DR1460): 4686 // At most one variant member of a union may have a 4687 // brace-or-equal-initializer. 4688 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4689 Owner->isRecord()) 4690 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4691 cast<CXXRecordDecl>(Record)); 4692 } 4693 4694 if (!Record->isUnion() && !Owner->isRecord()) { 4695 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4696 << getLangOpts().CPlusPlus; 4697 Invalid = true; 4698 } 4699 4700 // Mock up a declarator. 4701 Declarator Dc(DS, Declarator::MemberContext); 4702 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4703 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4704 4705 // Create a declaration for this anonymous struct/union. 4706 NamedDecl *Anon = nullptr; 4707 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4708 Anon = FieldDecl::Create(Context, OwningClass, 4709 DS.getLocStart(), 4710 Record->getLocation(), 4711 /*IdentifierInfo=*/nullptr, 4712 Context.getTypeDeclType(Record), 4713 TInfo, 4714 /*BitWidth=*/nullptr, /*Mutable=*/false, 4715 /*InitStyle=*/ICIS_NoInit); 4716 Anon->setAccess(AS); 4717 if (getLangOpts().CPlusPlus) 4718 FieldCollector->Add(cast<FieldDecl>(Anon)); 4719 } else { 4720 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4721 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4722 if (SCSpec == DeclSpec::SCS_mutable) { 4723 // mutable can only appear on non-static class members, so it's always 4724 // an error here 4725 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4726 Invalid = true; 4727 SC = SC_None; 4728 } 4729 4730 Anon = VarDecl::Create(Context, Owner, 4731 DS.getLocStart(), 4732 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4733 Context.getTypeDeclType(Record), 4734 TInfo, SC); 4735 4736 // Default-initialize the implicit variable. This initialization will be 4737 // trivial in almost all cases, except if a union member has an in-class 4738 // initializer: 4739 // union { int n = 0; }; 4740 ActOnUninitializedDecl(Anon); 4741 } 4742 Anon->setImplicit(); 4743 4744 // Mark this as an anonymous struct/union type. 4745 Record->setAnonymousStructOrUnion(true); 4746 4747 // Add the anonymous struct/union object to the current 4748 // context. We'll be referencing this object when we refer to one of 4749 // its members. 4750 Owner->addDecl(Anon); 4751 4752 // Inject the members of the anonymous struct/union into the owning 4753 // context and into the identifier resolver chain for name lookup 4754 // purposes. 4755 SmallVector<NamedDecl*, 2> Chain; 4756 Chain.push_back(Anon); 4757 4758 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4759 Invalid = true; 4760 4761 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4762 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4763 Decl *ManglingContextDecl; 4764 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4765 NewVD->getDeclContext(), ManglingContextDecl)) { 4766 Context.setManglingNumber( 4767 NewVD, MCtx->getManglingNumber( 4768 NewVD, getMSManglingNumber(getLangOpts(), S))); 4769 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4770 } 4771 } 4772 } 4773 4774 if (Invalid) 4775 Anon->setInvalidDecl(); 4776 4777 return Anon; 4778 } 4779 4780 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4781 /// Microsoft C anonymous structure. 4782 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4783 /// Example: 4784 /// 4785 /// struct A { int a; }; 4786 /// struct B { struct A; int b; }; 4787 /// 4788 /// void foo() { 4789 /// B var; 4790 /// var.a = 3; 4791 /// } 4792 /// 4793 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4794 RecordDecl *Record) { 4795 assert(Record && "expected a record!"); 4796 4797 // Mock up a declarator. 4798 Declarator Dc(DS, Declarator::TypeNameContext); 4799 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4800 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4801 4802 auto *ParentDecl = cast<RecordDecl>(CurContext); 4803 QualType RecTy = Context.getTypeDeclType(Record); 4804 4805 // Create a declaration for this anonymous struct. 4806 NamedDecl *Anon = FieldDecl::Create(Context, 4807 ParentDecl, 4808 DS.getLocStart(), 4809 DS.getLocStart(), 4810 /*IdentifierInfo=*/nullptr, 4811 RecTy, 4812 TInfo, 4813 /*BitWidth=*/nullptr, /*Mutable=*/false, 4814 /*InitStyle=*/ICIS_NoInit); 4815 Anon->setImplicit(); 4816 4817 // Add the anonymous struct object to the current context. 4818 CurContext->addDecl(Anon); 4819 4820 // Inject the members of the anonymous struct into the current 4821 // context and into the identifier resolver chain for name lookup 4822 // purposes. 4823 SmallVector<NamedDecl*, 2> Chain; 4824 Chain.push_back(Anon); 4825 4826 RecordDecl *RecordDef = Record->getDefinition(); 4827 if (RequireCompleteType(Anon->getLocation(), RecTy, 4828 diag::err_field_incomplete) || 4829 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4830 AS_none, Chain)) { 4831 Anon->setInvalidDecl(); 4832 ParentDecl->setInvalidDecl(); 4833 } 4834 4835 return Anon; 4836 } 4837 4838 /// GetNameForDeclarator - Determine the full declaration name for the 4839 /// given Declarator. 4840 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4841 return GetNameFromUnqualifiedId(D.getName()); 4842 } 4843 4844 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4845 DeclarationNameInfo 4846 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4847 DeclarationNameInfo NameInfo; 4848 NameInfo.setLoc(Name.StartLocation); 4849 4850 switch (Name.getKind()) { 4851 4852 case UnqualifiedId::IK_ImplicitSelfParam: 4853 case UnqualifiedId::IK_Identifier: 4854 NameInfo.setName(Name.Identifier); 4855 NameInfo.setLoc(Name.StartLocation); 4856 return NameInfo; 4857 4858 case UnqualifiedId::IK_DeductionGuideName: { 4859 // C++ [temp.deduct.guide]p3: 4860 // The simple-template-id shall name a class template specialization. 4861 // The template-name shall be the same identifier as the template-name 4862 // of the simple-template-id. 4863 // These together intend to imply that the template-name shall name a 4864 // class template. 4865 // FIXME: template<typename T> struct X {}; 4866 // template<typename T> using Y = X<T>; 4867 // Y(int) -> Y<int>; 4868 // satisfies these rules but does not name a class template. 4869 TemplateName TN = Name.TemplateName.get().get(); 4870 auto *Template = TN.getAsTemplateDecl(); 4871 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4872 Diag(Name.StartLocation, 4873 diag::err_deduction_guide_name_not_class_template) 4874 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4875 if (Template) 4876 Diag(Template->getLocation(), diag::note_template_decl_here); 4877 return DeclarationNameInfo(); 4878 } 4879 4880 NameInfo.setName( 4881 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4882 NameInfo.setLoc(Name.StartLocation); 4883 return NameInfo; 4884 } 4885 4886 case UnqualifiedId::IK_OperatorFunctionId: 4887 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4888 Name.OperatorFunctionId.Operator)); 4889 NameInfo.setLoc(Name.StartLocation); 4890 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4891 = Name.OperatorFunctionId.SymbolLocations[0]; 4892 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4893 = Name.EndLocation.getRawEncoding(); 4894 return NameInfo; 4895 4896 case UnqualifiedId::IK_LiteralOperatorId: 4897 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4898 Name.Identifier)); 4899 NameInfo.setLoc(Name.StartLocation); 4900 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4901 return NameInfo; 4902 4903 case UnqualifiedId::IK_ConversionFunctionId: { 4904 TypeSourceInfo *TInfo; 4905 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4906 if (Ty.isNull()) 4907 return DeclarationNameInfo(); 4908 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4909 Context.getCanonicalType(Ty))); 4910 NameInfo.setLoc(Name.StartLocation); 4911 NameInfo.setNamedTypeInfo(TInfo); 4912 return NameInfo; 4913 } 4914 4915 case UnqualifiedId::IK_ConstructorName: { 4916 TypeSourceInfo *TInfo; 4917 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4918 if (Ty.isNull()) 4919 return DeclarationNameInfo(); 4920 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4921 Context.getCanonicalType(Ty))); 4922 NameInfo.setLoc(Name.StartLocation); 4923 NameInfo.setNamedTypeInfo(TInfo); 4924 return NameInfo; 4925 } 4926 4927 case UnqualifiedId::IK_ConstructorTemplateId: { 4928 // In well-formed code, we can only have a constructor 4929 // template-id that refers to the current context, so go there 4930 // to find the actual type being constructed. 4931 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4932 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4933 return DeclarationNameInfo(); 4934 4935 // Determine the type of the class being constructed. 4936 QualType CurClassType = Context.getTypeDeclType(CurClass); 4937 4938 // FIXME: Check two things: that the template-id names the same type as 4939 // CurClassType, and that the template-id does not occur when the name 4940 // was qualified. 4941 4942 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4943 Context.getCanonicalType(CurClassType))); 4944 NameInfo.setLoc(Name.StartLocation); 4945 // FIXME: should we retrieve TypeSourceInfo? 4946 NameInfo.setNamedTypeInfo(nullptr); 4947 return NameInfo; 4948 } 4949 4950 case UnqualifiedId::IK_DestructorName: { 4951 TypeSourceInfo *TInfo; 4952 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4953 if (Ty.isNull()) 4954 return DeclarationNameInfo(); 4955 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4956 Context.getCanonicalType(Ty))); 4957 NameInfo.setLoc(Name.StartLocation); 4958 NameInfo.setNamedTypeInfo(TInfo); 4959 return NameInfo; 4960 } 4961 4962 case UnqualifiedId::IK_TemplateId: { 4963 TemplateName TName = Name.TemplateId->Template.get(); 4964 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4965 return Context.getNameForTemplate(TName, TNameLoc); 4966 } 4967 4968 } // switch (Name.getKind()) 4969 4970 llvm_unreachable("Unknown name kind"); 4971 } 4972 4973 static QualType getCoreType(QualType Ty) { 4974 do { 4975 if (Ty->isPointerType() || Ty->isReferenceType()) 4976 Ty = Ty->getPointeeType(); 4977 else if (Ty->isArrayType()) 4978 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4979 else 4980 return Ty.withoutLocalFastQualifiers(); 4981 } while (true); 4982 } 4983 4984 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4985 /// and Definition have "nearly" matching parameters. This heuristic is 4986 /// used to improve diagnostics in the case where an out-of-line function 4987 /// definition doesn't match any declaration within the class or namespace. 4988 /// Also sets Params to the list of indices to the parameters that differ 4989 /// between the declaration and the definition. If hasSimilarParameters 4990 /// returns true and Params is empty, then all of the parameters match. 4991 static bool hasSimilarParameters(ASTContext &Context, 4992 FunctionDecl *Declaration, 4993 FunctionDecl *Definition, 4994 SmallVectorImpl<unsigned> &Params) { 4995 Params.clear(); 4996 if (Declaration->param_size() != Definition->param_size()) 4997 return false; 4998 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4999 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5000 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5001 5002 // The parameter types are identical 5003 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5004 continue; 5005 5006 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5007 QualType DefParamBaseTy = getCoreType(DefParamTy); 5008 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5009 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5010 5011 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5012 (DeclTyName && DeclTyName == DefTyName)) 5013 Params.push_back(Idx); 5014 else // The two parameters aren't even close 5015 return false; 5016 } 5017 5018 return true; 5019 } 5020 5021 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5022 /// declarator needs to be rebuilt in the current instantiation. 5023 /// Any bits of declarator which appear before the name are valid for 5024 /// consideration here. That's specifically the type in the decl spec 5025 /// and the base type in any member-pointer chunks. 5026 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5027 DeclarationName Name) { 5028 // The types we specifically need to rebuild are: 5029 // - typenames, typeofs, and decltypes 5030 // - types which will become injected class names 5031 // Of course, we also need to rebuild any type referencing such a 5032 // type. It's safest to just say "dependent", but we call out a 5033 // few cases here. 5034 5035 DeclSpec &DS = D.getMutableDeclSpec(); 5036 switch (DS.getTypeSpecType()) { 5037 case DeclSpec::TST_typename: 5038 case DeclSpec::TST_typeofType: 5039 case DeclSpec::TST_underlyingType: 5040 case DeclSpec::TST_atomic: { 5041 // Grab the type from the parser. 5042 TypeSourceInfo *TSI = nullptr; 5043 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5044 if (T.isNull() || !T->isDependentType()) break; 5045 5046 // Make sure there's a type source info. This isn't really much 5047 // of a waste; most dependent types should have type source info 5048 // attached already. 5049 if (!TSI) 5050 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5051 5052 // Rebuild the type in the current instantiation. 5053 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5054 if (!TSI) return true; 5055 5056 // Store the new type back in the decl spec. 5057 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5058 DS.UpdateTypeRep(LocType); 5059 break; 5060 } 5061 5062 case DeclSpec::TST_decltype: 5063 case DeclSpec::TST_typeofExpr: { 5064 Expr *E = DS.getRepAsExpr(); 5065 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5066 if (Result.isInvalid()) return true; 5067 DS.UpdateExprRep(Result.get()); 5068 break; 5069 } 5070 5071 default: 5072 // Nothing to do for these decl specs. 5073 break; 5074 } 5075 5076 // It doesn't matter what order we do this in. 5077 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5078 DeclaratorChunk &Chunk = D.getTypeObject(I); 5079 5080 // The only type information in the declarator which can come 5081 // before the declaration name is the base type of a member 5082 // pointer. 5083 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5084 continue; 5085 5086 // Rebuild the scope specifier in-place. 5087 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5088 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5089 return true; 5090 } 5091 5092 return false; 5093 } 5094 5095 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5096 D.setFunctionDefinitionKind(FDK_Declaration); 5097 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5098 5099 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5100 Dcl && Dcl->getDeclContext()->isFileContext()) 5101 Dcl->setTopLevelDeclInObjCContainer(); 5102 5103 if (getLangOpts().OpenCL) 5104 setCurrentOpenCLExtensionForDecl(Dcl); 5105 5106 return Dcl; 5107 } 5108 5109 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5110 /// If T is the name of a class, then each of the following shall have a 5111 /// name different from T: 5112 /// - every static data member of class T; 5113 /// - every member function of class T 5114 /// - every member of class T that is itself a type; 5115 /// \returns true if the declaration name violates these rules. 5116 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5117 DeclarationNameInfo NameInfo) { 5118 DeclarationName Name = NameInfo.getName(); 5119 5120 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5121 while (Record && Record->isAnonymousStructOrUnion()) 5122 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5123 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5124 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5125 return true; 5126 } 5127 5128 return false; 5129 } 5130 5131 /// \brief Diagnose a declaration whose declarator-id has the given 5132 /// nested-name-specifier. 5133 /// 5134 /// \param SS The nested-name-specifier of the declarator-id. 5135 /// 5136 /// \param DC The declaration context to which the nested-name-specifier 5137 /// resolves. 5138 /// 5139 /// \param Name The name of the entity being declared. 5140 /// 5141 /// \param Loc The location of the name of the entity being declared. 5142 /// 5143 /// \returns true if we cannot safely recover from this error, false otherwise. 5144 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5145 DeclarationName Name, 5146 SourceLocation Loc) { 5147 DeclContext *Cur = CurContext; 5148 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5149 Cur = Cur->getParent(); 5150 5151 // If the user provided a superfluous scope specifier that refers back to the 5152 // class in which the entity is already declared, diagnose and ignore it. 5153 // 5154 // class X { 5155 // void X::f(); 5156 // }; 5157 // 5158 // Note, it was once ill-formed to give redundant qualification in all 5159 // contexts, but that rule was removed by DR482. 5160 if (Cur->Equals(DC)) { 5161 if (Cur->isRecord()) { 5162 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5163 : diag::err_member_extra_qualification) 5164 << Name << FixItHint::CreateRemoval(SS.getRange()); 5165 SS.clear(); 5166 } else { 5167 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5168 } 5169 return false; 5170 } 5171 5172 // Check whether the qualifying scope encloses the scope of the original 5173 // declaration. 5174 if (!Cur->Encloses(DC)) { 5175 if (Cur->isRecord()) 5176 Diag(Loc, diag::err_member_qualification) 5177 << Name << SS.getRange(); 5178 else if (isa<TranslationUnitDecl>(DC)) 5179 Diag(Loc, diag::err_invalid_declarator_global_scope) 5180 << Name << SS.getRange(); 5181 else if (isa<FunctionDecl>(Cur)) 5182 Diag(Loc, diag::err_invalid_declarator_in_function) 5183 << Name << SS.getRange(); 5184 else if (isa<BlockDecl>(Cur)) 5185 Diag(Loc, diag::err_invalid_declarator_in_block) 5186 << Name << SS.getRange(); 5187 else 5188 Diag(Loc, diag::err_invalid_declarator_scope) 5189 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5190 5191 return true; 5192 } 5193 5194 if (Cur->isRecord()) { 5195 // Cannot qualify members within a class. 5196 Diag(Loc, diag::err_member_qualification) 5197 << Name << SS.getRange(); 5198 SS.clear(); 5199 5200 // C++ constructors and destructors with incorrect scopes can break 5201 // our AST invariants by having the wrong underlying types. If 5202 // that's the case, then drop this declaration entirely. 5203 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5204 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5205 !Context.hasSameType(Name.getCXXNameType(), 5206 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5207 return true; 5208 5209 return false; 5210 } 5211 5212 // C++11 [dcl.meaning]p1: 5213 // [...] "The nested-name-specifier of the qualified declarator-id shall 5214 // not begin with a decltype-specifer" 5215 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5216 while (SpecLoc.getPrefix()) 5217 SpecLoc = SpecLoc.getPrefix(); 5218 if (dyn_cast_or_null<DecltypeType>( 5219 SpecLoc.getNestedNameSpecifier()->getAsType())) 5220 Diag(Loc, diag::err_decltype_in_declarator) 5221 << SpecLoc.getTypeLoc().getSourceRange(); 5222 5223 return false; 5224 } 5225 5226 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5227 MultiTemplateParamsArg TemplateParamLists) { 5228 // TODO: consider using NameInfo for diagnostic. 5229 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5230 DeclarationName Name = NameInfo.getName(); 5231 5232 // All of these full declarators require an identifier. If it doesn't have 5233 // one, the ParsedFreeStandingDeclSpec action should be used. 5234 if (D.isDecompositionDeclarator()) { 5235 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5236 } else if (!Name) { 5237 if (!D.isInvalidType()) // Reject this if we think it is valid. 5238 Diag(D.getDeclSpec().getLocStart(), 5239 diag::err_declarator_need_ident) 5240 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5241 return nullptr; 5242 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5243 return nullptr; 5244 5245 // The scope passed in may not be a decl scope. Zip up the scope tree until 5246 // we find one that is. 5247 while ((S->getFlags() & Scope::DeclScope) == 0 || 5248 (S->getFlags() & Scope::TemplateParamScope) != 0) 5249 S = S->getParent(); 5250 5251 DeclContext *DC = CurContext; 5252 if (D.getCXXScopeSpec().isInvalid()) 5253 D.setInvalidType(); 5254 else if (D.getCXXScopeSpec().isSet()) { 5255 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5256 UPPC_DeclarationQualifier)) 5257 return nullptr; 5258 5259 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5260 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5261 if (!DC || isa<EnumDecl>(DC)) { 5262 // If we could not compute the declaration context, it's because the 5263 // declaration context is dependent but does not refer to a class, 5264 // class template, or class template partial specialization. Complain 5265 // and return early, to avoid the coming semantic disaster. 5266 Diag(D.getIdentifierLoc(), 5267 diag::err_template_qualified_declarator_no_match) 5268 << D.getCXXScopeSpec().getScopeRep() 5269 << D.getCXXScopeSpec().getRange(); 5270 return nullptr; 5271 } 5272 bool IsDependentContext = DC->isDependentContext(); 5273 5274 if (!IsDependentContext && 5275 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5276 return nullptr; 5277 5278 // If a class is incomplete, do not parse entities inside it. 5279 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5280 Diag(D.getIdentifierLoc(), 5281 diag::err_member_def_undefined_record) 5282 << Name << DC << D.getCXXScopeSpec().getRange(); 5283 return nullptr; 5284 } 5285 if (!D.getDeclSpec().isFriendSpecified()) { 5286 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5287 Name, D.getIdentifierLoc())) { 5288 if (DC->isRecord()) 5289 return nullptr; 5290 5291 D.setInvalidType(); 5292 } 5293 } 5294 5295 // Check whether we need to rebuild the type of the given 5296 // declaration in the current instantiation. 5297 if (EnteringContext && IsDependentContext && 5298 TemplateParamLists.size() != 0) { 5299 ContextRAII SavedContext(*this, DC); 5300 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5301 D.setInvalidType(); 5302 } 5303 } 5304 5305 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5306 QualType R = TInfo->getType(); 5307 5308 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5309 // If this is a typedef, we'll end up spewing multiple diagnostics. 5310 // Just return early; it's safer. If this is a function, let the 5311 // "constructor cannot have a return type" diagnostic handle it. 5312 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5313 return nullptr; 5314 5315 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5316 UPPC_DeclarationType)) 5317 D.setInvalidType(); 5318 5319 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5320 ForRedeclaration); 5321 5322 // See if this is a redefinition of a variable in the same scope. 5323 if (!D.getCXXScopeSpec().isSet()) { 5324 bool IsLinkageLookup = false; 5325 bool CreateBuiltins = false; 5326 5327 // If the declaration we're planning to build will be a function 5328 // or object with linkage, then look for another declaration with 5329 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5330 // 5331 // If the declaration we're planning to build will be declared with 5332 // external linkage in the translation unit, create any builtin with 5333 // the same name. 5334 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5335 /* Do nothing*/; 5336 else if (CurContext->isFunctionOrMethod() && 5337 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5338 R->isFunctionType())) { 5339 IsLinkageLookup = true; 5340 CreateBuiltins = 5341 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5342 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5343 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5344 CreateBuiltins = true; 5345 5346 if (IsLinkageLookup) 5347 Previous.clear(LookupRedeclarationWithLinkage); 5348 5349 LookupName(Previous, S, CreateBuiltins); 5350 } else { // Something like "int foo::x;" 5351 LookupQualifiedName(Previous, DC); 5352 5353 // C++ [dcl.meaning]p1: 5354 // When the declarator-id is qualified, the declaration shall refer to a 5355 // previously declared member of the class or namespace to which the 5356 // qualifier refers (or, in the case of a namespace, of an element of the 5357 // inline namespace set of that namespace (7.3.1)) or to a specialization 5358 // thereof; [...] 5359 // 5360 // Note that we already checked the context above, and that we do not have 5361 // enough information to make sure that Previous contains the declaration 5362 // we want to match. For example, given: 5363 // 5364 // class X { 5365 // void f(); 5366 // void f(float); 5367 // }; 5368 // 5369 // void X::f(int) { } // ill-formed 5370 // 5371 // In this case, Previous will point to the overload set 5372 // containing the two f's declared in X, but neither of them 5373 // matches. 5374 5375 // C++ [dcl.meaning]p1: 5376 // [...] the member shall not merely have been introduced by a 5377 // using-declaration in the scope of the class or namespace nominated by 5378 // the nested-name-specifier of the declarator-id. 5379 RemoveUsingDecls(Previous); 5380 } 5381 5382 if (Previous.isSingleResult() && 5383 Previous.getFoundDecl()->isTemplateParameter()) { 5384 // Maybe we will complain about the shadowed template parameter. 5385 if (!D.isInvalidType()) 5386 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5387 Previous.getFoundDecl()); 5388 5389 // Just pretend that we didn't see the previous declaration. 5390 Previous.clear(); 5391 } 5392 5393 // In C++, the previous declaration we find might be a tag type 5394 // (class or enum). In this case, the new declaration will hide the 5395 // tag type. Note that this does does not apply if we're declaring a 5396 // typedef (C++ [dcl.typedef]p4). 5397 if (Previous.isSingleTagDecl() && 5398 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5399 Previous.clear(); 5400 5401 // Check that there are no default arguments other than in the parameters 5402 // of a function declaration (C++ only). 5403 if (getLangOpts().CPlusPlus) 5404 CheckExtraCXXDefaultArguments(D); 5405 5406 if (D.getDeclSpec().isConceptSpecified()) { 5407 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5408 // applied only to the definition of a function template or variable 5409 // template, declared in namespace scope 5410 if (!TemplateParamLists.size()) { 5411 Diag(D.getDeclSpec().getConceptSpecLoc(), 5412 diag:: err_concept_wrong_decl_kind); 5413 return nullptr; 5414 } 5415 5416 if (!DC->getRedeclContext()->isFileContext()) { 5417 Diag(D.getIdentifierLoc(), 5418 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5419 return nullptr; 5420 } 5421 } 5422 5423 NamedDecl *New; 5424 5425 bool AddToScope = true; 5426 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5427 if (TemplateParamLists.size()) { 5428 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5429 return nullptr; 5430 } 5431 5432 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5433 } else if (R->isFunctionType()) { 5434 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5435 TemplateParamLists, 5436 AddToScope); 5437 } else { 5438 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5439 AddToScope); 5440 } 5441 5442 if (!New) 5443 return nullptr; 5444 5445 // If this has an identifier and is not a function template specialization, 5446 // add it to the scope stack. 5447 if (New->getDeclName() && AddToScope) { 5448 // Only make a locally-scoped extern declaration visible if it is the first 5449 // declaration of this entity. Qualified lookup for such an entity should 5450 // only find this declaration if there is no visible declaration of it. 5451 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5452 PushOnScopeChains(New, S, AddToContext); 5453 if (!AddToContext) 5454 CurContext->addHiddenDecl(New); 5455 } 5456 5457 if (isInOpenMPDeclareTargetContext()) 5458 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5459 5460 return New; 5461 } 5462 5463 /// Helper method to turn variable array types into constant array 5464 /// types in certain situations which would otherwise be errors (for 5465 /// GCC compatibility). 5466 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5467 ASTContext &Context, 5468 bool &SizeIsNegative, 5469 llvm::APSInt &Oversized) { 5470 // This method tries to turn a variable array into a constant 5471 // array even when the size isn't an ICE. This is necessary 5472 // for compatibility with code that depends on gcc's buggy 5473 // constant expression folding, like struct {char x[(int)(char*)2];} 5474 SizeIsNegative = false; 5475 Oversized = 0; 5476 5477 if (T->isDependentType()) 5478 return QualType(); 5479 5480 QualifierCollector Qs; 5481 const Type *Ty = Qs.strip(T); 5482 5483 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5484 QualType Pointee = PTy->getPointeeType(); 5485 QualType FixedType = 5486 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5487 Oversized); 5488 if (FixedType.isNull()) return FixedType; 5489 FixedType = Context.getPointerType(FixedType); 5490 return Qs.apply(Context, FixedType); 5491 } 5492 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5493 QualType Inner = PTy->getInnerType(); 5494 QualType FixedType = 5495 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5496 Oversized); 5497 if (FixedType.isNull()) return FixedType; 5498 FixedType = Context.getParenType(FixedType); 5499 return Qs.apply(Context, FixedType); 5500 } 5501 5502 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5503 if (!VLATy) 5504 return QualType(); 5505 // FIXME: We should probably handle this case 5506 if (VLATy->getElementType()->isVariablyModifiedType()) 5507 return QualType(); 5508 5509 llvm::APSInt Res; 5510 if (!VLATy->getSizeExpr() || 5511 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5512 return QualType(); 5513 5514 // Check whether the array size is negative. 5515 if (Res.isSigned() && Res.isNegative()) { 5516 SizeIsNegative = true; 5517 return QualType(); 5518 } 5519 5520 // Check whether the array is too large to be addressed. 5521 unsigned ActiveSizeBits 5522 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5523 Res); 5524 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5525 Oversized = Res; 5526 return QualType(); 5527 } 5528 5529 return Context.getConstantArrayType(VLATy->getElementType(), 5530 Res, ArrayType::Normal, 0); 5531 } 5532 5533 static void 5534 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5535 SrcTL = SrcTL.getUnqualifiedLoc(); 5536 DstTL = DstTL.getUnqualifiedLoc(); 5537 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5538 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5539 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5540 DstPTL.getPointeeLoc()); 5541 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5542 return; 5543 } 5544 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5545 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5546 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5547 DstPTL.getInnerLoc()); 5548 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5549 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5550 return; 5551 } 5552 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5553 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5554 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5555 TypeLoc DstElemTL = DstATL.getElementLoc(); 5556 DstElemTL.initializeFullCopy(SrcElemTL); 5557 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5558 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5559 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5560 } 5561 5562 /// Helper method to turn variable array types into constant array 5563 /// types in certain situations which would otherwise be errors (for 5564 /// GCC compatibility). 5565 static TypeSourceInfo* 5566 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5567 ASTContext &Context, 5568 bool &SizeIsNegative, 5569 llvm::APSInt &Oversized) { 5570 QualType FixedTy 5571 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5572 SizeIsNegative, Oversized); 5573 if (FixedTy.isNull()) 5574 return nullptr; 5575 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5576 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5577 FixedTInfo->getTypeLoc()); 5578 return FixedTInfo; 5579 } 5580 5581 /// \brief Register the given locally-scoped extern "C" declaration so 5582 /// that it can be found later for redeclarations. We include any extern "C" 5583 /// declaration that is not visible in the translation unit here, not just 5584 /// function-scope declarations. 5585 void 5586 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5587 if (!getLangOpts().CPlusPlus && 5588 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5589 // Don't need to track declarations in the TU in C. 5590 return; 5591 5592 // Note that we have a locally-scoped external with this name. 5593 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5594 } 5595 5596 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5597 // FIXME: We can have multiple results via __attribute__((overloadable)). 5598 auto Result = Context.getExternCContextDecl()->lookup(Name); 5599 return Result.empty() ? nullptr : *Result.begin(); 5600 } 5601 5602 /// \brief Diagnose function specifiers on a declaration of an identifier that 5603 /// does not identify a function. 5604 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5605 // FIXME: We should probably indicate the identifier in question to avoid 5606 // confusion for constructs like "virtual int a(), b;" 5607 if (DS.isVirtualSpecified()) 5608 Diag(DS.getVirtualSpecLoc(), 5609 diag::err_virtual_non_function); 5610 5611 if (DS.isExplicitSpecified()) 5612 Diag(DS.getExplicitSpecLoc(), 5613 diag::err_explicit_non_function); 5614 5615 if (DS.isNoreturnSpecified()) 5616 Diag(DS.getNoreturnSpecLoc(), 5617 diag::err_noreturn_non_function); 5618 } 5619 5620 NamedDecl* 5621 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5622 TypeSourceInfo *TInfo, LookupResult &Previous) { 5623 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5624 if (D.getCXXScopeSpec().isSet()) { 5625 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5626 << D.getCXXScopeSpec().getRange(); 5627 D.setInvalidType(); 5628 // Pretend we didn't see the scope specifier. 5629 DC = CurContext; 5630 Previous.clear(); 5631 } 5632 5633 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5634 5635 if (D.getDeclSpec().isInlineSpecified()) 5636 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5637 << getLangOpts().CPlusPlus1z; 5638 if (D.getDeclSpec().isConstexprSpecified()) 5639 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5640 << 1; 5641 if (D.getDeclSpec().isConceptSpecified()) 5642 Diag(D.getDeclSpec().getConceptSpecLoc(), 5643 diag::err_concept_wrong_decl_kind); 5644 5645 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5646 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5647 Diag(D.getName().StartLocation, 5648 diag::err_deduction_guide_invalid_specifier) 5649 << "typedef"; 5650 else 5651 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5652 << D.getName().getSourceRange(); 5653 return nullptr; 5654 } 5655 5656 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5657 if (!NewTD) return nullptr; 5658 5659 // Handle attributes prior to checking for duplicates in MergeVarDecl 5660 ProcessDeclAttributes(S, NewTD, D); 5661 5662 CheckTypedefForVariablyModifiedType(S, NewTD); 5663 5664 bool Redeclaration = D.isRedeclaration(); 5665 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5666 D.setRedeclaration(Redeclaration); 5667 return ND; 5668 } 5669 5670 void 5671 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5672 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5673 // then it shall have block scope. 5674 // Note that variably modified types must be fixed before merging the decl so 5675 // that redeclarations will match. 5676 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5677 QualType T = TInfo->getType(); 5678 if (T->isVariablyModifiedType()) { 5679 getCurFunction()->setHasBranchProtectedScope(); 5680 5681 if (S->getFnParent() == nullptr) { 5682 bool SizeIsNegative; 5683 llvm::APSInt Oversized; 5684 TypeSourceInfo *FixedTInfo = 5685 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5686 SizeIsNegative, 5687 Oversized); 5688 if (FixedTInfo) { 5689 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5690 NewTD->setTypeSourceInfo(FixedTInfo); 5691 } else { 5692 if (SizeIsNegative) 5693 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5694 else if (T->isVariableArrayType()) 5695 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5696 else if (Oversized.getBoolValue()) 5697 Diag(NewTD->getLocation(), diag::err_array_too_large) 5698 << Oversized.toString(10); 5699 else 5700 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5701 NewTD->setInvalidDecl(); 5702 } 5703 } 5704 } 5705 } 5706 5707 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5708 /// declares a typedef-name, either using the 'typedef' type specifier or via 5709 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5710 NamedDecl* 5711 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5712 LookupResult &Previous, bool &Redeclaration) { 5713 5714 // Find the shadowed declaration before filtering for scope. 5715 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5716 5717 // Merge the decl with the existing one if appropriate. If the decl is 5718 // in an outer scope, it isn't the same thing. 5719 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5720 /*AllowInlineNamespace*/false); 5721 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5722 if (!Previous.empty()) { 5723 Redeclaration = true; 5724 MergeTypedefNameDecl(S, NewTD, Previous); 5725 } 5726 5727 if (ShadowedDecl && !Redeclaration) 5728 CheckShadow(NewTD, ShadowedDecl, Previous); 5729 5730 // If this is the C FILE type, notify the AST context. 5731 if (IdentifierInfo *II = NewTD->getIdentifier()) 5732 if (!NewTD->isInvalidDecl() && 5733 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5734 if (II->isStr("FILE")) 5735 Context.setFILEDecl(NewTD); 5736 else if (II->isStr("jmp_buf")) 5737 Context.setjmp_bufDecl(NewTD); 5738 else if (II->isStr("sigjmp_buf")) 5739 Context.setsigjmp_bufDecl(NewTD); 5740 else if (II->isStr("ucontext_t")) 5741 Context.setucontext_tDecl(NewTD); 5742 } 5743 5744 return NewTD; 5745 } 5746 5747 /// \brief Determines whether the given declaration is an out-of-scope 5748 /// previous declaration. 5749 /// 5750 /// This routine should be invoked when name lookup has found a 5751 /// previous declaration (PrevDecl) that is not in the scope where a 5752 /// new declaration by the same name is being introduced. If the new 5753 /// declaration occurs in a local scope, previous declarations with 5754 /// linkage may still be considered previous declarations (C99 5755 /// 6.2.2p4-5, C++ [basic.link]p6). 5756 /// 5757 /// \param PrevDecl the previous declaration found by name 5758 /// lookup 5759 /// 5760 /// \param DC the context in which the new declaration is being 5761 /// declared. 5762 /// 5763 /// \returns true if PrevDecl is an out-of-scope previous declaration 5764 /// for a new delcaration with the same name. 5765 static bool 5766 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5767 ASTContext &Context) { 5768 if (!PrevDecl) 5769 return false; 5770 5771 if (!PrevDecl->hasLinkage()) 5772 return false; 5773 5774 if (Context.getLangOpts().CPlusPlus) { 5775 // C++ [basic.link]p6: 5776 // If there is a visible declaration of an entity with linkage 5777 // having the same name and type, ignoring entities declared 5778 // outside the innermost enclosing namespace scope, the block 5779 // scope declaration declares that same entity and receives the 5780 // linkage of the previous declaration. 5781 DeclContext *OuterContext = DC->getRedeclContext(); 5782 if (!OuterContext->isFunctionOrMethod()) 5783 // This rule only applies to block-scope declarations. 5784 return false; 5785 5786 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5787 if (PrevOuterContext->isRecord()) 5788 // We found a member function: ignore it. 5789 return false; 5790 5791 // Find the innermost enclosing namespace for the new and 5792 // previous declarations. 5793 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5794 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5795 5796 // The previous declaration is in a different namespace, so it 5797 // isn't the same function. 5798 if (!OuterContext->Equals(PrevOuterContext)) 5799 return false; 5800 } 5801 5802 return true; 5803 } 5804 5805 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5806 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5807 if (!SS.isSet()) return; 5808 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5809 } 5810 5811 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5812 QualType type = decl->getType(); 5813 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5814 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5815 // Various kinds of declaration aren't allowed to be __autoreleasing. 5816 unsigned kind = -1U; 5817 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5818 if (var->hasAttr<BlocksAttr>()) 5819 kind = 0; // __block 5820 else if (!var->hasLocalStorage()) 5821 kind = 1; // global 5822 } else if (isa<ObjCIvarDecl>(decl)) { 5823 kind = 3; // ivar 5824 } else if (isa<FieldDecl>(decl)) { 5825 kind = 2; // field 5826 } 5827 5828 if (kind != -1U) { 5829 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5830 << kind; 5831 } 5832 } else if (lifetime == Qualifiers::OCL_None) { 5833 // Try to infer lifetime. 5834 if (!type->isObjCLifetimeType()) 5835 return false; 5836 5837 lifetime = type->getObjCARCImplicitLifetime(); 5838 type = Context.getLifetimeQualifiedType(type, lifetime); 5839 decl->setType(type); 5840 } 5841 5842 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5843 // Thread-local variables cannot have lifetime. 5844 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5845 var->getTLSKind()) { 5846 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5847 << var->getType(); 5848 return true; 5849 } 5850 } 5851 5852 return false; 5853 } 5854 5855 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5856 // Ensure that an auto decl is deduced otherwise the checks below might cache 5857 // the wrong linkage. 5858 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5859 5860 // 'weak' only applies to declarations with external linkage. 5861 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5862 if (!ND.isExternallyVisible()) { 5863 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5864 ND.dropAttr<WeakAttr>(); 5865 } 5866 } 5867 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5868 if (ND.isExternallyVisible()) { 5869 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5870 ND.dropAttr<WeakRefAttr>(); 5871 ND.dropAttr<AliasAttr>(); 5872 } 5873 } 5874 5875 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5876 if (VD->hasInit()) { 5877 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5878 assert(VD->isThisDeclarationADefinition() && 5879 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5880 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5881 VD->dropAttr<AliasAttr>(); 5882 } 5883 } 5884 } 5885 5886 // 'selectany' only applies to externally visible variable declarations. 5887 // It does not apply to functions. 5888 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5889 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5890 S.Diag(Attr->getLocation(), 5891 diag::err_attribute_selectany_non_extern_data); 5892 ND.dropAttr<SelectAnyAttr>(); 5893 } 5894 } 5895 5896 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5897 // dll attributes require external linkage. Static locals may have external 5898 // linkage but still cannot be explicitly imported or exported. 5899 auto *VD = dyn_cast<VarDecl>(&ND); 5900 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5901 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5902 << &ND << Attr; 5903 ND.setInvalidDecl(); 5904 } 5905 } 5906 5907 // Virtual functions cannot be marked as 'notail'. 5908 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5909 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5910 if (MD->isVirtual()) { 5911 S.Diag(ND.getLocation(), 5912 diag::err_invalid_attribute_on_virtual_function) 5913 << Attr; 5914 ND.dropAttr<NotTailCalledAttr>(); 5915 } 5916 } 5917 5918 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5919 NamedDecl *NewDecl, 5920 bool IsSpecialization, 5921 bool IsDefinition) { 5922 if (OldDecl->isInvalidDecl()) 5923 return; 5924 5925 bool IsTemplate = false; 5926 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5927 OldDecl = OldTD->getTemplatedDecl(); 5928 IsTemplate = true; 5929 if (!IsSpecialization) 5930 IsDefinition = false; 5931 } 5932 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5933 NewDecl = NewTD->getTemplatedDecl(); 5934 IsTemplate = true; 5935 } 5936 5937 if (!OldDecl || !NewDecl) 5938 return; 5939 5940 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5941 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5942 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5943 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5944 5945 // dllimport and dllexport are inheritable attributes so we have to exclude 5946 // inherited attribute instances. 5947 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5948 (NewExportAttr && !NewExportAttr->isInherited()); 5949 5950 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5951 // the only exception being explicit specializations. 5952 // Implicitly generated declarations are also excluded for now because there 5953 // is no other way to switch these to use dllimport or dllexport. 5954 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5955 5956 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5957 // Allow with a warning for free functions and global variables. 5958 bool JustWarn = false; 5959 if (!OldDecl->isCXXClassMember()) { 5960 auto *VD = dyn_cast<VarDecl>(OldDecl); 5961 if (VD && !VD->getDescribedVarTemplate()) 5962 JustWarn = true; 5963 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5964 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5965 JustWarn = true; 5966 } 5967 5968 // We cannot change a declaration that's been used because IR has already 5969 // been emitted. Dllimported functions will still work though (modulo 5970 // address equality) as they can use the thunk. 5971 if (OldDecl->isUsed()) 5972 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5973 JustWarn = false; 5974 5975 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5976 : diag::err_attribute_dll_redeclaration; 5977 S.Diag(NewDecl->getLocation(), DiagID) 5978 << NewDecl 5979 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5980 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5981 if (!JustWarn) { 5982 NewDecl->setInvalidDecl(); 5983 return; 5984 } 5985 } 5986 5987 // A redeclaration is not allowed to drop a dllimport attribute, the only 5988 // exceptions being inline function definitions (except for function 5989 // templates), local extern declarations, qualified friend declarations or 5990 // special MSVC extension: in the last case, the declaration is treated as if 5991 // it were marked dllexport. 5992 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5993 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5994 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5995 // Ignore static data because out-of-line definitions are diagnosed 5996 // separately. 5997 IsStaticDataMember = VD->isStaticDataMember(); 5998 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5999 VarDecl::DeclarationOnly; 6000 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6001 IsInline = FD->isInlined(); 6002 IsQualifiedFriend = FD->getQualifier() && 6003 FD->getFriendObjectKind() == Decl::FOK_Declared; 6004 } 6005 6006 if (OldImportAttr && !HasNewAttr && 6007 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6008 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6009 if (IsMicrosoft && IsDefinition) { 6010 S.Diag(NewDecl->getLocation(), 6011 diag::warn_redeclaration_without_import_attribute) 6012 << NewDecl; 6013 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6014 NewDecl->dropAttr<DLLImportAttr>(); 6015 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6016 NewImportAttr->getRange(), S.Context, 6017 NewImportAttr->getSpellingListIndex())); 6018 } else { 6019 S.Diag(NewDecl->getLocation(), 6020 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6021 << NewDecl << OldImportAttr; 6022 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6023 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6024 OldDecl->dropAttr<DLLImportAttr>(); 6025 NewDecl->dropAttr<DLLImportAttr>(); 6026 } 6027 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6028 // In MinGW, seeing a function declared inline drops the dllimport attribute. 6029 OldDecl->dropAttr<DLLImportAttr>(); 6030 NewDecl->dropAttr<DLLImportAttr>(); 6031 S.Diag(NewDecl->getLocation(), 6032 diag::warn_dllimport_dropped_from_inline_function) 6033 << NewDecl << OldImportAttr; 6034 } 6035 } 6036 6037 /// Given that we are within the definition of the given function, 6038 /// will that definition behave like C99's 'inline', where the 6039 /// definition is discarded except for optimization purposes? 6040 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6041 // Try to avoid calling GetGVALinkageForFunction. 6042 6043 // All cases of this require the 'inline' keyword. 6044 if (!FD->isInlined()) return false; 6045 6046 // This is only possible in C++ with the gnu_inline attribute. 6047 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6048 return false; 6049 6050 // Okay, go ahead and call the relatively-more-expensive function. 6051 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6052 } 6053 6054 /// Determine whether a variable is extern "C" prior to attaching 6055 /// an initializer. We can't just call isExternC() here, because that 6056 /// will also compute and cache whether the declaration is externally 6057 /// visible, which might change when we attach the initializer. 6058 /// 6059 /// This can only be used if the declaration is known to not be a 6060 /// redeclaration of an internal linkage declaration. 6061 /// 6062 /// For instance: 6063 /// 6064 /// auto x = []{}; 6065 /// 6066 /// Attaching the initializer here makes this declaration not externally 6067 /// visible, because its type has internal linkage. 6068 /// 6069 /// FIXME: This is a hack. 6070 template<typename T> 6071 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6072 if (S.getLangOpts().CPlusPlus) { 6073 // In C++, the overloadable attribute negates the effects of extern "C". 6074 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6075 return false; 6076 6077 // So do CUDA's host/device attributes. 6078 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6079 D->template hasAttr<CUDAHostAttr>())) 6080 return false; 6081 } 6082 return D->isExternC(); 6083 } 6084 6085 static bool shouldConsiderLinkage(const VarDecl *VD) { 6086 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6087 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6088 return VD->hasExternalStorage(); 6089 if (DC->isFileContext()) 6090 return true; 6091 if (DC->isRecord()) 6092 return false; 6093 llvm_unreachable("Unexpected context"); 6094 } 6095 6096 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6097 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6098 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6099 isa<OMPDeclareReductionDecl>(DC)) 6100 return true; 6101 if (DC->isRecord()) 6102 return false; 6103 llvm_unreachable("Unexpected context"); 6104 } 6105 6106 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6107 AttributeList::Kind Kind) { 6108 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6109 if (L->getKind() == Kind) 6110 return true; 6111 return false; 6112 } 6113 6114 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6115 AttributeList::Kind Kind) { 6116 // Check decl attributes on the DeclSpec. 6117 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6118 return true; 6119 6120 // Walk the declarator structure, checking decl attributes that were in a type 6121 // position to the decl itself. 6122 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6123 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6124 return true; 6125 } 6126 6127 // Finally, check attributes on the decl itself. 6128 return hasParsedAttr(S, PD.getAttributes(), Kind); 6129 } 6130 6131 /// Adjust the \c DeclContext for a function or variable that might be a 6132 /// function-local external declaration. 6133 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6134 if (!DC->isFunctionOrMethod()) 6135 return false; 6136 6137 // If this is a local extern function or variable declared within a function 6138 // template, don't add it into the enclosing namespace scope until it is 6139 // instantiated; it might have a dependent type right now. 6140 if (DC->isDependentContext()) 6141 return true; 6142 6143 // C++11 [basic.link]p7: 6144 // When a block scope declaration of an entity with linkage is not found to 6145 // refer to some other declaration, then that entity is a member of the 6146 // innermost enclosing namespace. 6147 // 6148 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6149 // semantically-enclosing namespace, not a lexically-enclosing one. 6150 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6151 DC = DC->getParent(); 6152 return true; 6153 } 6154 6155 /// \brief Returns true if given declaration has external C language linkage. 6156 static bool isDeclExternC(const Decl *D) { 6157 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6158 return FD->isExternC(); 6159 if (const auto *VD = dyn_cast<VarDecl>(D)) 6160 return VD->isExternC(); 6161 6162 llvm_unreachable("Unknown type of decl!"); 6163 } 6164 6165 NamedDecl *Sema::ActOnVariableDeclarator( 6166 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6167 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6168 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6169 QualType R = TInfo->getType(); 6170 DeclarationName Name = GetNameForDeclarator(D).getName(); 6171 6172 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6173 6174 if (D.isDecompositionDeclarator()) { 6175 // Take the name of the first declarator as our name for diagnostic 6176 // purposes. 6177 auto &Decomp = D.getDecompositionDeclarator(); 6178 if (!Decomp.bindings().empty()) { 6179 II = Decomp.bindings()[0].Name; 6180 Name = II; 6181 } 6182 } else if (!II) { 6183 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6184 return nullptr; 6185 } 6186 6187 if (getLangOpts().OpenCL) { 6188 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6189 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6190 // argument. 6191 if (R->isImageType() || R->isPipeType()) { 6192 Diag(D.getIdentifierLoc(), 6193 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6194 << R; 6195 D.setInvalidType(); 6196 return nullptr; 6197 } 6198 6199 // OpenCL v1.2 s6.9.r: 6200 // The event type cannot be used to declare a program scope variable. 6201 // OpenCL v2.0 s6.9.q: 6202 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6203 if (NULL == S->getParent()) { 6204 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6205 Diag(D.getIdentifierLoc(), 6206 diag::err_invalid_type_for_program_scope_var) << R; 6207 D.setInvalidType(); 6208 return nullptr; 6209 } 6210 } 6211 6212 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6213 QualType NR = R; 6214 while (NR->isPointerType()) { 6215 if (NR->isFunctionPointerType()) { 6216 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6217 D.setInvalidType(); 6218 break; 6219 } 6220 NR = NR->getPointeeType(); 6221 } 6222 6223 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6224 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6225 // half array type (unless the cl_khr_fp16 extension is enabled). 6226 if (Context.getBaseElementType(R)->isHalfType()) { 6227 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6228 D.setInvalidType(); 6229 } 6230 } 6231 6232 if (R->isSamplerT()) { 6233 // OpenCL v1.2 s6.9.b p4: 6234 // The sampler type cannot be used with the __local and __global address 6235 // space qualifiers. 6236 if (R.getAddressSpace() == LangAS::opencl_local || 6237 R.getAddressSpace() == LangAS::opencl_global) { 6238 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6239 } 6240 6241 // OpenCL v1.2 s6.12.14.1: 6242 // A global sampler must be declared with either the constant address 6243 // space qualifier or with the const qualifier. 6244 if (DC->isTranslationUnit() && 6245 !(R.getAddressSpace() == LangAS::opencl_constant || 6246 R.isConstQualified())) { 6247 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6248 D.setInvalidType(); 6249 } 6250 } 6251 6252 // OpenCL v1.2 s6.9.r: 6253 // The event type cannot be used with the __local, __constant and __global 6254 // address space qualifiers. 6255 if (R->isEventT()) { 6256 if (R.getAddressSpace()) { 6257 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6258 D.setInvalidType(); 6259 } 6260 } 6261 } 6262 6263 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6264 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6265 6266 // dllimport globals without explicit storage class are treated as extern. We 6267 // have to change the storage class this early to get the right DeclContext. 6268 if (SC == SC_None && !DC->isRecord() && 6269 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6270 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6271 SC = SC_Extern; 6272 6273 DeclContext *OriginalDC = DC; 6274 bool IsLocalExternDecl = SC == SC_Extern && 6275 adjustContextForLocalExternDecl(DC); 6276 6277 if (SCSpec == DeclSpec::SCS_mutable) { 6278 // mutable can only appear on non-static class members, so it's always 6279 // an error here 6280 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6281 D.setInvalidType(); 6282 SC = SC_None; 6283 } 6284 6285 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6286 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6287 D.getDeclSpec().getStorageClassSpecLoc())) { 6288 // In C++11, the 'register' storage class specifier is deprecated. 6289 // Suppress the warning in system macros, it's used in macros in some 6290 // popular C system headers, such as in glibc's htonl() macro. 6291 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6292 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6293 : diag::warn_deprecated_register) 6294 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6295 } 6296 6297 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6298 6299 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6300 // C99 6.9p2: The storage-class specifiers auto and register shall not 6301 // appear in the declaration specifiers in an external declaration. 6302 // Global Register+Asm is a GNU extension we support. 6303 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6304 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6305 D.setInvalidType(); 6306 } 6307 } 6308 6309 bool IsMemberSpecialization = false; 6310 bool IsVariableTemplateSpecialization = false; 6311 bool IsPartialSpecialization = false; 6312 bool IsVariableTemplate = false; 6313 VarDecl *NewVD = nullptr; 6314 VarTemplateDecl *NewTemplate = nullptr; 6315 TemplateParameterList *TemplateParams = nullptr; 6316 if (!getLangOpts().CPlusPlus) { 6317 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6318 D.getIdentifierLoc(), II, 6319 R, TInfo, SC); 6320 6321 if (R->getContainedDeducedType()) 6322 ParsingInitForAutoVars.insert(NewVD); 6323 6324 if (D.isInvalidType()) 6325 NewVD->setInvalidDecl(); 6326 } else { 6327 bool Invalid = false; 6328 6329 if (DC->isRecord() && !CurContext->isRecord()) { 6330 // This is an out-of-line definition of a static data member. 6331 switch (SC) { 6332 case SC_None: 6333 break; 6334 case SC_Static: 6335 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6336 diag::err_static_out_of_line) 6337 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6338 break; 6339 case SC_Auto: 6340 case SC_Register: 6341 case SC_Extern: 6342 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6343 // to names of variables declared in a block or to function parameters. 6344 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6345 // of class members 6346 6347 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6348 diag::err_storage_class_for_static_member) 6349 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6350 break; 6351 case SC_PrivateExtern: 6352 llvm_unreachable("C storage class in c++!"); 6353 } 6354 } 6355 6356 if (SC == SC_Static && CurContext->isRecord()) { 6357 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6358 if (RD->isLocalClass()) 6359 Diag(D.getIdentifierLoc(), 6360 diag::err_static_data_member_not_allowed_in_local_class) 6361 << Name << RD->getDeclName(); 6362 6363 // C++98 [class.union]p1: If a union contains a static data member, 6364 // the program is ill-formed. C++11 drops this restriction. 6365 if (RD->isUnion()) 6366 Diag(D.getIdentifierLoc(), 6367 getLangOpts().CPlusPlus11 6368 ? diag::warn_cxx98_compat_static_data_member_in_union 6369 : diag::ext_static_data_member_in_union) << Name; 6370 // We conservatively disallow static data members in anonymous structs. 6371 else if (!RD->getDeclName()) 6372 Diag(D.getIdentifierLoc(), 6373 diag::err_static_data_member_not_allowed_in_anon_struct) 6374 << Name << RD->isUnion(); 6375 } 6376 } 6377 6378 // Match up the template parameter lists with the scope specifier, then 6379 // determine whether we have a template or a template specialization. 6380 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6381 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6382 D.getCXXScopeSpec(), 6383 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6384 ? D.getName().TemplateId 6385 : nullptr, 6386 TemplateParamLists, 6387 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6388 6389 if (TemplateParams) { 6390 if (!TemplateParams->size() && 6391 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6392 // There is an extraneous 'template<>' for this variable. Complain 6393 // about it, but allow the declaration of the variable. 6394 Diag(TemplateParams->getTemplateLoc(), 6395 diag::err_template_variable_noparams) 6396 << II 6397 << SourceRange(TemplateParams->getTemplateLoc(), 6398 TemplateParams->getRAngleLoc()); 6399 TemplateParams = nullptr; 6400 } else { 6401 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6402 // This is an explicit specialization or a partial specialization. 6403 // FIXME: Check that we can declare a specialization here. 6404 IsVariableTemplateSpecialization = true; 6405 IsPartialSpecialization = TemplateParams->size() > 0; 6406 } else { // if (TemplateParams->size() > 0) 6407 // This is a template declaration. 6408 IsVariableTemplate = true; 6409 6410 // Check that we can declare a template here. 6411 if (CheckTemplateDeclScope(S, TemplateParams)) 6412 return nullptr; 6413 6414 // Only C++1y supports variable templates (N3651). 6415 Diag(D.getIdentifierLoc(), 6416 getLangOpts().CPlusPlus14 6417 ? diag::warn_cxx11_compat_variable_template 6418 : diag::ext_variable_template); 6419 } 6420 } 6421 } else { 6422 assert( 6423 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6424 "should have a 'template<>' for this decl"); 6425 } 6426 6427 if (IsVariableTemplateSpecialization) { 6428 SourceLocation TemplateKWLoc = 6429 TemplateParamLists.size() > 0 6430 ? TemplateParamLists[0]->getTemplateLoc() 6431 : SourceLocation(); 6432 DeclResult Res = ActOnVarTemplateSpecialization( 6433 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6434 IsPartialSpecialization); 6435 if (Res.isInvalid()) 6436 return nullptr; 6437 NewVD = cast<VarDecl>(Res.get()); 6438 AddToScope = false; 6439 } else if (D.isDecompositionDeclarator()) { 6440 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6441 D.getIdentifierLoc(), R, TInfo, SC, 6442 Bindings); 6443 } else 6444 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6445 D.getIdentifierLoc(), II, R, TInfo, SC); 6446 6447 // If this is supposed to be a variable template, create it as such. 6448 if (IsVariableTemplate) { 6449 NewTemplate = 6450 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6451 TemplateParams, NewVD); 6452 NewVD->setDescribedVarTemplate(NewTemplate); 6453 } 6454 6455 // If this decl has an auto type in need of deduction, make a note of the 6456 // Decl so we can diagnose uses of it in its own initializer. 6457 if (R->getContainedDeducedType()) 6458 ParsingInitForAutoVars.insert(NewVD); 6459 6460 if (D.isInvalidType() || Invalid) { 6461 NewVD->setInvalidDecl(); 6462 if (NewTemplate) 6463 NewTemplate->setInvalidDecl(); 6464 } 6465 6466 SetNestedNameSpecifier(NewVD, D); 6467 6468 // If we have any template parameter lists that don't directly belong to 6469 // the variable (matching the scope specifier), store them. 6470 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6471 if (TemplateParamLists.size() > VDTemplateParamLists) 6472 NewVD->setTemplateParameterListsInfo( 6473 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6474 6475 if (D.getDeclSpec().isConstexprSpecified()) { 6476 NewVD->setConstexpr(true); 6477 // C++1z [dcl.spec.constexpr]p1: 6478 // A static data member declared with the constexpr specifier is 6479 // implicitly an inline variable. 6480 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6481 NewVD->setImplicitlyInline(); 6482 } 6483 6484 if (D.getDeclSpec().isConceptSpecified()) { 6485 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6486 VTD->setConcept(); 6487 6488 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6489 // be declared with the thread_local, inline, friend, or constexpr 6490 // specifiers, [...] 6491 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6492 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6493 diag::err_concept_decl_invalid_specifiers) 6494 << 0 << 0; 6495 NewVD->setInvalidDecl(true); 6496 } 6497 6498 if (D.getDeclSpec().isConstexprSpecified()) { 6499 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6500 diag::err_concept_decl_invalid_specifiers) 6501 << 0 << 3; 6502 NewVD->setInvalidDecl(true); 6503 } 6504 6505 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6506 // applied only to the definition of a function template or variable 6507 // template, declared in namespace scope. 6508 if (IsVariableTemplateSpecialization) { 6509 Diag(D.getDeclSpec().getConceptSpecLoc(), 6510 diag::err_concept_specified_specialization) 6511 << (IsPartialSpecialization ? 2 : 1); 6512 } 6513 6514 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6515 // following restrictions: 6516 // - The declared type shall have the type bool. 6517 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6518 !NewVD->isInvalidDecl()) { 6519 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6520 NewVD->setInvalidDecl(true); 6521 } 6522 } 6523 } 6524 6525 if (D.getDeclSpec().isInlineSpecified()) { 6526 if (!getLangOpts().CPlusPlus) { 6527 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6528 << 0; 6529 } else if (CurContext->isFunctionOrMethod()) { 6530 // 'inline' is not allowed on block scope variable declaration. 6531 Diag(D.getDeclSpec().getInlineSpecLoc(), 6532 diag::err_inline_declaration_block_scope) << Name 6533 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6534 } else { 6535 Diag(D.getDeclSpec().getInlineSpecLoc(), 6536 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6537 : diag::ext_inline_variable); 6538 NewVD->setInlineSpecified(); 6539 } 6540 } 6541 6542 // Set the lexical context. If the declarator has a C++ scope specifier, the 6543 // lexical context will be different from the semantic context. 6544 NewVD->setLexicalDeclContext(CurContext); 6545 if (NewTemplate) 6546 NewTemplate->setLexicalDeclContext(CurContext); 6547 6548 if (IsLocalExternDecl) { 6549 if (D.isDecompositionDeclarator()) 6550 for (auto *B : Bindings) 6551 B->setLocalExternDecl(); 6552 else 6553 NewVD->setLocalExternDecl(); 6554 } 6555 6556 bool EmitTLSUnsupportedError = false; 6557 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6558 // C++11 [dcl.stc]p4: 6559 // When thread_local is applied to a variable of block scope the 6560 // storage-class-specifier static is implied if it does not appear 6561 // explicitly. 6562 // Core issue: 'static' is not implied if the variable is declared 6563 // 'extern'. 6564 if (NewVD->hasLocalStorage() && 6565 (SCSpec != DeclSpec::SCS_unspecified || 6566 TSCS != DeclSpec::TSCS_thread_local || 6567 !DC->isFunctionOrMethod())) 6568 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6569 diag::err_thread_non_global) 6570 << DeclSpec::getSpecifierName(TSCS); 6571 else if (!Context.getTargetInfo().isTLSSupported()) { 6572 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6573 // Postpone error emission until we've collected attributes required to 6574 // figure out whether it's a host or device variable and whether the 6575 // error should be ignored. 6576 EmitTLSUnsupportedError = true; 6577 // We still need to mark the variable as TLS so it shows up in AST with 6578 // proper storage class for other tools to use even if we're not going 6579 // to emit any code for it. 6580 NewVD->setTSCSpec(TSCS); 6581 } else 6582 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6583 diag::err_thread_unsupported); 6584 } else 6585 NewVD->setTSCSpec(TSCS); 6586 } 6587 6588 // C99 6.7.4p3 6589 // An inline definition of a function with external linkage shall 6590 // not contain a definition of a modifiable object with static or 6591 // thread storage duration... 6592 // We only apply this when the function is required to be defined 6593 // elsewhere, i.e. when the function is not 'extern inline'. Note 6594 // that a local variable with thread storage duration still has to 6595 // be marked 'static'. Also note that it's possible to get these 6596 // semantics in C++ using __attribute__((gnu_inline)). 6597 if (SC == SC_Static && S->getFnParent() != nullptr && 6598 !NewVD->getType().isConstQualified()) { 6599 FunctionDecl *CurFD = getCurFunctionDecl(); 6600 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6601 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6602 diag::warn_static_local_in_extern_inline); 6603 MaybeSuggestAddingStaticToDecl(CurFD); 6604 } 6605 } 6606 6607 if (D.getDeclSpec().isModulePrivateSpecified()) { 6608 if (IsVariableTemplateSpecialization) 6609 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6610 << (IsPartialSpecialization ? 1 : 0) 6611 << FixItHint::CreateRemoval( 6612 D.getDeclSpec().getModulePrivateSpecLoc()); 6613 else if (IsMemberSpecialization) 6614 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6615 << 2 6616 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6617 else if (NewVD->hasLocalStorage()) 6618 Diag(NewVD->getLocation(), diag::err_module_private_local) 6619 << 0 << NewVD->getDeclName() 6620 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6621 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6622 else { 6623 NewVD->setModulePrivate(); 6624 if (NewTemplate) 6625 NewTemplate->setModulePrivate(); 6626 for (auto *B : Bindings) 6627 B->setModulePrivate(); 6628 } 6629 } 6630 6631 // Handle attributes prior to checking for duplicates in MergeVarDecl 6632 ProcessDeclAttributes(S, NewVD, D); 6633 6634 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6635 if (EmitTLSUnsupportedError && 6636 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6637 (getLangOpts().OpenMPIsDevice && 6638 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6639 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6640 diag::err_thread_unsupported); 6641 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6642 // storage [duration]." 6643 if (SC == SC_None && S->getFnParent() != nullptr && 6644 (NewVD->hasAttr<CUDASharedAttr>() || 6645 NewVD->hasAttr<CUDAConstantAttr>())) { 6646 NewVD->setStorageClass(SC_Static); 6647 } 6648 } 6649 6650 // Ensure that dllimport globals without explicit storage class are treated as 6651 // extern. The storage class is set above using parsed attributes. Now we can 6652 // check the VarDecl itself. 6653 assert(!NewVD->hasAttr<DLLImportAttr>() || 6654 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6655 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6656 6657 // In auto-retain/release, infer strong retension for variables of 6658 // retainable type. 6659 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6660 NewVD->setInvalidDecl(); 6661 6662 // Handle GNU asm-label extension (encoded as an attribute). 6663 if (Expr *E = (Expr*)D.getAsmLabel()) { 6664 // The parser guarantees this is a string. 6665 StringLiteral *SE = cast<StringLiteral>(E); 6666 StringRef Label = SE->getString(); 6667 if (S->getFnParent() != nullptr) { 6668 switch (SC) { 6669 case SC_None: 6670 case SC_Auto: 6671 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6672 break; 6673 case SC_Register: 6674 // Local Named register 6675 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6676 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6677 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6678 break; 6679 case SC_Static: 6680 case SC_Extern: 6681 case SC_PrivateExtern: 6682 break; 6683 } 6684 } else if (SC == SC_Register) { 6685 // Global Named register 6686 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6687 const auto &TI = Context.getTargetInfo(); 6688 bool HasSizeMismatch; 6689 6690 if (!TI.isValidGCCRegisterName(Label)) 6691 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6692 else if (!TI.validateGlobalRegisterVariable(Label, 6693 Context.getTypeSize(R), 6694 HasSizeMismatch)) 6695 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6696 else if (HasSizeMismatch) 6697 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6698 } 6699 6700 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6701 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6702 NewVD->setInvalidDecl(true); 6703 } 6704 } 6705 6706 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6707 Context, Label, 0)); 6708 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6709 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6710 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6711 if (I != ExtnameUndeclaredIdentifiers.end()) { 6712 if (isDeclExternC(NewVD)) { 6713 NewVD->addAttr(I->second); 6714 ExtnameUndeclaredIdentifiers.erase(I); 6715 } else 6716 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6717 << /*Variable*/1 << NewVD; 6718 } 6719 } 6720 6721 // Find the shadowed declaration before filtering for scope. 6722 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6723 ? getShadowedDeclaration(NewVD, Previous) 6724 : nullptr; 6725 6726 // Don't consider existing declarations that are in a different 6727 // scope and are out-of-semantic-context declarations (if the new 6728 // declaration has linkage). 6729 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6730 D.getCXXScopeSpec().isNotEmpty() || 6731 IsMemberSpecialization || 6732 IsVariableTemplateSpecialization); 6733 6734 // Check whether the previous declaration is in the same block scope. This 6735 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6736 if (getLangOpts().CPlusPlus && 6737 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6738 NewVD->setPreviousDeclInSameBlockScope( 6739 Previous.isSingleResult() && !Previous.isShadowed() && 6740 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6741 6742 if (!getLangOpts().CPlusPlus) { 6743 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6744 } else { 6745 // If this is an explicit specialization of a static data member, check it. 6746 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6747 CheckMemberSpecialization(NewVD, Previous)) 6748 NewVD->setInvalidDecl(); 6749 6750 // Merge the decl with the existing one if appropriate. 6751 if (!Previous.empty()) { 6752 if (Previous.isSingleResult() && 6753 isa<FieldDecl>(Previous.getFoundDecl()) && 6754 D.getCXXScopeSpec().isSet()) { 6755 // The user tried to define a non-static data member 6756 // out-of-line (C++ [dcl.meaning]p1). 6757 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6758 << D.getCXXScopeSpec().getRange(); 6759 Previous.clear(); 6760 NewVD->setInvalidDecl(); 6761 } 6762 } else if (D.getCXXScopeSpec().isSet()) { 6763 // No previous declaration in the qualifying scope. 6764 Diag(D.getIdentifierLoc(), diag::err_no_member) 6765 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6766 << D.getCXXScopeSpec().getRange(); 6767 NewVD->setInvalidDecl(); 6768 } 6769 6770 if (!IsVariableTemplateSpecialization) 6771 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6772 6773 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6774 // an explicit specialization (14.8.3) or a partial specialization of a 6775 // concept definition. 6776 if (IsVariableTemplateSpecialization && 6777 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6778 Previous.isSingleResult()) { 6779 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6780 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6781 if (VarTmpl->isConcept()) { 6782 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6783 << 1 /*variable*/ 6784 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6785 : 1 /*explicitly specialized*/); 6786 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6787 NewVD->setInvalidDecl(); 6788 } 6789 } 6790 } 6791 6792 if (NewTemplate) { 6793 VarTemplateDecl *PrevVarTemplate = 6794 NewVD->getPreviousDecl() 6795 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6796 : nullptr; 6797 6798 // Check the template parameter list of this declaration, possibly 6799 // merging in the template parameter list from the previous variable 6800 // template declaration. 6801 if (CheckTemplateParameterList( 6802 TemplateParams, 6803 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6804 : nullptr, 6805 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6806 DC->isDependentContext()) 6807 ? TPC_ClassTemplateMember 6808 : TPC_VarTemplate)) 6809 NewVD->setInvalidDecl(); 6810 6811 // If we are providing an explicit specialization of a static variable 6812 // template, make a note of that. 6813 if (PrevVarTemplate && 6814 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6815 PrevVarTemplate->setMemberSpecialization(); 6816 } 6817 } 6818 6819 // Diagnose shadowed variables iff this isn't a redeclaration. 6820 if (ShadowedDecl && !D.isRedeclaration()) 6821 CheckShadow(NewVD, ShadowedDecl, Previous); 6822 6823 ProcessPragmaWeak(S, NewVD); 6824 6825 // If this is the first declaration of an extern C variable, update 6826 // the map of such variables. 6827 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6828 isIncompleteDeclExternC(*this, NewVD)) 6829 RegisterLocallyScopedExternCDecl(NewVD, S); 6830 6831 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6832 Decl *ManglingContextDecl; 6833 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6834 NewVD->getDeclContext(), ManglingContextDecl)) { 6835 Context.setManglingNumber( 6836 NewVD, MCtx->getManglingNumber( 6837 NewVD, getMSManglingNumber(getLangOpts(), S))); 6838 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6839 } 6840 } 6841 6842 // Special handling of variable named 'main'. 6843 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6844 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6845 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6846 6847 // C++ [basic.start.main]p3 6848 // A program that declares a variable main at global scope is ill-formed. 6849 if (getLangOpts().CPlusPlus) 6850 Diag(D.getLocStart(), diag::err_main_global_variable); 6851 6852 // In C, and external-linkage variable named main results in undefined 6853 // behavior. 6854 else if (NewVD->hasExternalFormalLinkage()) 6855 Diag(D.getLocStart(), diag::warn_main_redefined); 6856 } 6857 6858 if (D.isRedeclaration() && !Previous.empty()) { 6859 checkDLLAttributeRedeclaration( 6860 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6861 IsMemberSpecialization, D.isFunctionDefinition()); 6862 } 6863 6864 if (NewTemplate) { 6865 if (NewVD->isInvalidDecl()) 6866 NewTemplate->setInvalidDecl(); 6867 ActOnDocumentableDecl(NewTemplate); 6868 return NewTemplate; 6869 } 6870 6871 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6872 CompleteMemberSpecialization(NewVD, Previous); 6873 6874 return NewVD; 6875 } 6876 6877 /// Enum describing the %select options in diag::warn_decl_shadow. 6878 enum ShadowedDeclKind { 6879 SDK_Local, 6880 SDK_Global, 6881 SDK_StaticMember, 6882 SDK_Field, 6883 SDK_Typedef, 6884 SDK_Using 6885 }; 6886 6887 /// Determine what kind of declaration we're shadowing. 6888 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6889 const DeclContext *OldDC) { 6890 if (isa<TypeAliasDecl>(ShadowedDecl)) 6891 return SDK_Using; 6892 else if (isa<TypedefDecl>(ShadowedDecl)) 6893 return SDK_Typedef; 6894 else if (isa<RecordDecl>(OldDC)) 6895 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6896 6897 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6898 } 6899 6900 /// Return the location of the capture if the given lambda captures the given 6901 /// variable \p VD, or an invalid source location otherwise. 6902 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6903 const VarDecl *VD) { 6904 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6905 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6906 return Capture.getLocation(); 6907 } 6908 return SourceLocation(); 6909 } 6910 6911 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6912 const LookupResult &R) { 6913 // Only diagnose if we're shadowing an unambiguous field or variable. 6914 if (R.getResultKind() != LookupResult::Found) 6915 return false; 6916 6917 // Return false if warning is ignored. 6918 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6919 } 6920 6921 /// \brief Return the declaration shadowed by the given variable \p D, or null 6922 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6923 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6924 const LookupResult &R) { 6925 if (!shouldWarnIfShadowedDecl(Diags, R)) 6926 return nullptr; 6927 6928 // Don't diagnose declarations at file scope. 6929 if (D->hasGlobalStorage()) 6930 return nullptr; 6931 6932 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6933 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6934 ? ShadowedDecl 6935 : nullptr; 6936 } 6937 6938 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6939 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6940 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6941 const LookupResult &R) { 6942 // Don't warn if typedef declaration is part of a class 6943 if (D->getDeclContext()->isRecord()) 6944 return nullptr; 6945 6946 if (!shouldWarnIfShadowedDecl(Diags, R)) 6947 return nullptr; 6948 6949 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6950 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6951 } 6952 6953 /// \brief Diagnose variable or built-in function shadowing. Implements 6954 /// -Wshadow. 6955 /// 6956 /// This method is called whenever a VarDecl is added to a "useful" 6957 /// scope. 6958 /// 6959 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6960 /// \param R the lookup of the name 6961 /// 6962 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6963 const LookupResult &R) { 6964 DeclContext *NewDC = D->getDeclContext(); 6965 6966 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6967 // Fields are not shadowed by variables in C++ static methods. 6968 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6969 if (MD->isStatic()) 6970 return; 6971 6972 // Fields shadowed by constructor parameters are a special case. Usually 6973 // the constructor initializes the field with the parameter. 6974 if (isa<CXXConstructorDecl>(NewDC)) 6975 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6976 // Remember that this was shadowed so we can either warn about its 6977 // modification or its existence depending on warning settings. 6978 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6979 return; 6980 } 6981 } 6982 6983 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6984 if (shadowedVar->isExternC()) { 6985 // For shadowing external vars, make sure that we point to the global 6986 // declaration, not a locally scoped extern declaration. 6987 for (auto I : shadowedVar->redecls()) 6988 if (I->isFileVarDecl()) { 6989 ShadowedDecl = I; 6990 break; 6991 } 6992 } 6993 6994 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 6995 6996 unsigned WarningDiag = diag::warn_decl_shadow; 6997 SourceLocation CaptureLoc; 6998 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6999 isa<CXXMethodDecl>(NewDC)) { 7000 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7001 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7002 if (RD->getLambdaCaptureDefault() == LCD_None) { 7003 // Try to avoid warnings for lambdas with an explicit capture list. 7004 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7005 // Warn only when the lambda captures the shadowed decl explicitly. 7006 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7007 if (CaptureLoc.isInvalid()) 7008 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7009 } else { 7010 // Remember that this was shadowed so we can avoid the warning if the 7011 // shadowed decl isn't captured and the warning settings allow it. 7012 cast<LambdaScopeInfo>(getCurFunction()) 7013 ->ShadowingDecls.push_back( 7014 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7015 return; 7016 } 7017 } 7018 7019 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7020 // A variable can't shadow a local variable in an enclosing scope, if 7021 // they are separated by a non-capturing declaration context. 7022 for (DeclContext *ParentDC = NewDC; 7023 ParentDC && !ParentDC->Equals(OldDC); 7024 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7025 // Only block literals, captured statements, and lambda expressions 7026 // can capture; other scopes don't. 7027 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7028 !isLambdaCallOperator(ParentDC)) { 7029 return; 7030 } 7031 } 7032 } 7033 } 7034 } 7035 7036 // Only warn about certain kinds of shadowing for class members. 7037 if (NewDC && NewDC->isRecord()) { 7038 // In particular, don't warn about shadowing non-class members. 7039 if (!OldDC->isRecord()) 7040 return; 7041 7042 // TODO: should we warn about static data members shadowing 7043 // static data members from base classes? 7044 7045 // TODO: don't diagnose for inaccessible shadowed members. 7046 // This is hard to do perfectly because we might friend the 7047 // shadowing context, but that's just a false negative. 7048 } 7049 7050 7051 DeclarationName Name = R.getLookupName(); 7052 7053 // Emit warning and note. 7054 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7055 return; 7056 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7057 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7058 if (!CaptureLoc.isInvalid()) 7059 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7060 << Name << /*explicitly*/ 1; 7061 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7062 } 7063 7064 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7065 /// when these variables are captured by the lambda. 7066 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7067 for (const auto &Shadow : LSI->ShadowingDecls) { 7068 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7069 // Try to avoid the warning when the shadowed decl isn't captured. 7070 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7071 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7072 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7073 ? diag::warn_decl_shadow_uncaptured_local 7074 : diag::warn_decl_shadow) 7075 << Shadow.VD->getDeclName() 7076 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7077 if (!CaptureLoc.isInvalid()) 7078 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7079 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7080 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7081 } 7082 } 7083 7084 /// \brief Check -Wshadow without the advantage of a previous lookup. 7085 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7086 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7087 return; 7088 7089 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7090 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7091 LookupName(R, S); 7092 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7093 CheckShadow(D, ShadowedDecl, R); 7094 } 7095 7096 /// Check if 'E', which is an expression that is about to be modified, refers 7097 /// to a constructor parameter that shadows a field. 7098 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7099 // Quickly ignore expressions that can't be shadowing ctor parameters. 7100 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7101 return; 7102 E = E->IgnoreParenImpCasts(); 7103 auto *DRE = dyn_cast<DeclRefExpr>(E); 7104 if (!DRE) 7105 return; 7106 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7107 auto I = ShadowingDecls.find(D); 7108 if (I == ShadowingDecls.end()) 7109 return; 7110 const NamedDecl *ShadowedDecl = I->second; 7111 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7112 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7113 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7114 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7115 7116 // Avoid issuing multiple warnings about the same decl. 7117 ShadowingDecls.erase(I); 7118 } 7119 7120 /// Check for conflict between this global or extern "C" declaration and 7121 /// previous global or extern "C" declarations. This is only used in C++. 7122 template<typename T> 7123 static bool checkGlobalOrExternCConflict( 7124 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7125 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7126 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7127 7128 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7129 // The common case: this global doesn't conflict with any extern "C" 7130 // declaration. 7131 return false; 7132 } 7133 7134 if (Prev) { 7135 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7136 // Both the old and new declarations have C language linkage. This is a 7137 // redeclaration. 7138 Previous.clear(); 7139 Previous.addDecl(Prev); 7140 return true; 7141 } 7142 7143 // This is a global, non-extern "C" declaration, and there is a previous 7144 // non-global extern "C" declaration. Diagnose if this is a variable 7145 // declaration. 7146 if (!isa<VarDecl>(ND)) 7147 return false; 7148 } else { 7149 // The declaration is extern "C". Check for any declaration in the 7150 // translation unit which might conflict. 7151 if (IsGlobal) { 7152 // We have already performed the lookup into the translation unit. 7153 IsGlobal = false; 7154 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7155 I != E; ++I) { 7156 if (isa<VarDecl>(*I)) { 7157 Prev = *I; 7158 break; 7159 } 7160 } 7161 } else { 7162 DeclContext::lookup_result R = 7163 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7164 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7165 I != E; ++I) { 7166 if (isa<VarDecl>(*I)) { 7167 Prev = *I; 7168 break; 7169 } 7170 // FIXME: If we have any other entity with this name in global scope, 7171 // the declaration is ill-formed, but that is a defect: it breaks the 7172 // 'stat' hack, for instance. Only variables can have mangled name 7173 // clashes with extern "C" declarations, so only they deserve a 7174 // diagnostic. 7175 } 7176 } 7177 7178 if (!Prev) 7179 return false; 7180 } 7181 7182 // Use the first declaration's location to ensure we point at something which 7183 // is lexically inside an extern "C" linkage-spec. 7184 assert(Prev && "should have found a previous declaration to diagnose"); 7185 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7186 Prev = FD->getFirstDecl(); 7187 else 7188 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7189 7190 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7191 << IsGlobal << ND; 7192 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7193 << IsGlobal; 7194 return false; 7195 } 7196 7197 /// Apply special rules for handling extern "C" declarations. Returns \c true 7198 /// if we have found that this is a redeclaration of some prior entity. 7199 /// 7200 /// Per C++ [dcl.link]p6: 7201 /// Two declarations [for a function or variable] with C language linkage 7202 /// with the same name that appear in different scopes refer to the same 7203 /// [entity]. An entity with C language linkage shall not be declared with 7204 /// the same name as an entity in global scope. 7205 template<typename T> 7206 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7207 LookupResult &Previous) { 7208 if (!S.getLangOpts().CPlusPlus) { 7209 // In C, when declaring a global variable, look for a corresponding 'extern' 7210 // variable declared in function scope. We don't need this in C++, because 7211 // we find local extern decls in the surrounding file-scope DeclContext. 7212 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7213 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7214 Previous.clear(); 7215 Previous.addDecl(Prev); 7216 return true; 7217 } 7218 } 7219 return false; 7220 } 7221 7222 // A declaration in the translation unit can conflict with an extern "C" 7223 // declaration. 7224 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7225 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7226 7227 // An extern "C" declaration can conflict with a declaration in the 7228 // translation unit or can be a redeclaration of an extern "C" declaration 7229 // in another scope. 7230 if (isIncompleteDeclExternC(S,ND)) 7231 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7232 7233 // Neither global nor extern "C": nothing to do. 7234 return false; 7235 } 7236 7237 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7238 // If the decl is already known invalid, don't check it. 7239 if (NewVD->isInvalidDecl()) 7240 return; 7241 7242 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7243 QualType T = TInfo->getType(); 7244 7245 // Defer checking an 'auto' type until its initializer is attached. 7246 if (T->isUndeducedType()) 7247 return; 7248 7249 if (NewVD->hasAttrs()) 7250 CheckAlignasUnderalignment(NewVD); 7251 7252 if (T->isObjCObjectType()) { 7253 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7254 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7255 T = Context.getObjCObjectPointerType(T); 7256 NewVD->setType(T); 7257 } 7258 7259 // Emit an error if an address space was applied to decl with local storage. 7260 // This includes arrays of objects with address space qualifiers, but not 7261 // automatic variables that point to other address spaces. 7262 // ISO/IEC TR 18037 S5.1.2 7263 if (!getLangOpts().OpenCL 7264 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7265 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7266 NewVD->setInvalidDecl(); 7267 return; 7268 } 7269 7270 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7271 // scope. 7272 if (getLangOpts().OpenCLVersion == 120 && 7273 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7274 NewVD->isStaticLocal()) { 7275 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7276 NewVD->setInvalidDecl(); 7277 return; 7278 } 7279 7280 if (getLangOpts().OpenCL) { 7281 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7282 if (NewVD->hasAttr<BlocksAttr>()) { 7283 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7284 return; 7285 } 7286 7287 if (T->isBlockPointerType()) { 7288 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7289 // can't use 'extern' storage class. 7290 if (!T.isConstQualified()) { 7291 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7292 << 0 /*const*/; 7293 NewVD->setInvalidDecl(); 7294 return; 7295 } 7296 if (NewVD->hasExternalStorage()) { 7297 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7298 NewVD->setInvalidDecl(); 7299 return; 7300 } 7301 } 7302 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7303 // __constant address space. 7304 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7305 // variables inside a function can also be declared in the global 7306 // address space. 7307 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7308 NewVD->hasExternalStorage()) { 7309 if (!T->isSamplerT() && 7310 !(T.getAddressSpace() == LangAS::opencl_constant || 7311 (T.getAddressSpace() == LangAS::opencl_global && 7312 getLangOpts().OpenCLVersion == 200))) { 7313 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7314 if (getLangOpts().OpenCLVersion == 200) 7315 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7316 << Scope << "global or constant"; 7317 else 7318 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7319 << Scope << "constant"; 7320 NewVD->setInvalidDecl(); 7321 return; 7322 } 7323 } else { 7324 if (T.getAddressSpace() == LangAS::opencl_global) { 7325 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7326 << 1 /*is any function*/ << "global"; 7327 NewVD->setInvalidDecl(); 7328 return; 7329 } 7330 if (T.getAddressSpace() == LangAS::opencl_constant || 7331 T.getAddressSpace() == LangAS::opencl_local) { 7332 FunctionDecl *FD = getCurFunctionDecl(); 7333 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7334 // in functions. 7335 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7336 if (T.getAddressSpace() == LangAS::opencl_constant) 7337 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7338 << 0 /*non-kernel only*/ << "constant"; 7339 else 7340 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7341 << 0 /*non-kernel only*/ << "local"; 7342 NewVD->setInvalidDecl(); 7343 return; 7344 } 7345 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7346 // in the outermost scope of a kernel function. 7347 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7348 if (!getCurScope()->isFunctionScope()) { 7349 if (T.getAddressSpace() == LangAS::opencl_constant) 7350 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7351 << "constant"; 7352 else 7353 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7354 << "local"; 7355 NewVD->setInvalidDecl(); 7356 return; 7357 } 7358 } 7359 } else if (T.getAddressSpace() != LangAS::Default) { 7360 // Do not allow other address spaces on automatic variable. 7361 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7362 NewVD->setInvalidDecl(); 7363 return; 7364 } 7365 } 7366 } 7367 7368 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7369 && !NewVD->hasAttr<BlocksAttr>()) { 7370 if (getLangOpts().getGC() != LangOptions::NonGC) 7371 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7372 else { 7373 assert(!getLangOpts().ObjCAutoRefCount); 7374 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7375 } 7376 } 7377 7378 bool isVM = T->isVariablyModifiedType(); 7379 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7380 NewVD->hasAttr<BlocksAttr>()) 7381 getCurFunction()->setHasBranchProtectedScope(); 7382 7383 if ((isVM && NewVD->hasLinkage()) || 7384 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7385 bool SizeIsNegative; 7386 llvm::APSInt Oversized; 7387 TypeSourceInfo *FixedTInfo = 7388 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7389 SizeIsNegative, Oversized); 7390 if (!FixedTInfo && T->isVariableArrayType()) { 7391 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7392 // FIXME: This won't give the correct result for 7393 // int a[10][n]; 7394 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7395 7396 if (NewVD->isFileVarDecl()) 7397 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7398 << SizeRange; 7399 else if (NewVD->isStaticLocal()) 7400 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7401 << SizeRange; 7402 else 7403 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7404 << SizeRange; 7405 NewVD->setInvalidDecl(); 7406 return; 7407 } 7408 7409 if (!FixedTInfo) { 7410 if (NewVD->isFileVarDecl()) 7411 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7412 else 7413 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7414 NewVD->setInvalidDecl(); 7415 return; 7416 } 7417 7418 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7419 NewVD->setType(FixedTInfo->getType()); 7420 NewVD->setTypeSourceInfo(FixedTInfo); 7421 } 7422 7423 if (T->isVoidType()) { 7424 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7425 // of objects and functions. 7426 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7427 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7428 << T; 7429 NewVD->setInvalidDecl(); 7430 return; 7431 } 7432 } 7433 7434 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7435 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7436 NewVD->setInvalidDecl(); 7437 return; 7438 } 7439 7440 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7441 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7442 NewVD->setInvalidDecl(); 7443 return; 7444 } 7445 7446 if (NewVD->isConstexpr() && !T->isDependentType() && 7447 RequireLiteralType(NewVD->getLocation(), T, 7448 diag::err_constexpr_var_non_literal)) { 7449 NewVD->setInvalidDecl(); 7450 return; 7451 } 7452 } 7453 7454 /// \brief Perform semantic checking on a newly-created variable 7455 /// declaration. 7456 /// 7457 /// This routine performs all of the type-checking required for a 7458 /// variable declaration once it has been built. It is used both to 7459 /// check variables after they have been parsed and their declarators 7460 /// have been translated into a declaration, and to check variables 7461 /// that have been instantiated from a template. 7462 /// 7463 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7464 /// 7465 /// Returns true if the variable declaration is a redeclaration. 7466 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7467 CheckVariableDeclarationType(NewVD); 7468 7469 // If the decl is already known invalid, don't check it. 7470 if (NewVD->isInvalidDecl()) 7471 return false; 7472 7473 // If we did not find anything by this name, look for a non-visible 7474 // extern "C" declaration with the same name. 7475 if (Previous.empty() && 7476 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7477 Previous.setShadowed(); 7478 7479 if (!Previous.empty()) { 7480 MergeVarDecl(NewVD, Previous); 7481 return true; 7482 } 7483 return false; 7484 } 7485 7486 namespace { 7487 struct FindOverriddenMethod { 7488 Sema *S; 7489 CXXMethodDecl *Method; 7490 7491 /// Member lookup function that determines whether a given C++ 7492 /// method overrides a method in a base class, to be used with 7493 /// CXXRecordDecl::lookupInBases(). 7494 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7495 RecordDecl *BaseRecord = 7496 Specifier->getType()->getAs<RecordType>()->getDecl(); 7497 7498 DeclarationName Name = Method->getDeclName(); 7499 7500 // FIXME: Do we care about other names here too? 7501 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7502 // We really want to find the base class destructor here. 7503 QualType T = S->Context.getTypeDeclType(BaseRecord); 7504 CanQualType CT = S->Context.getCanonicalType(T); 7505 7506 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7507 } 7508 7509 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7510 Path.Decls = Path.Decls.slice(1)) { 7511 NamedDecl *D = Path.Decls.front(); 7512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7513 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7514 return true; 7515 } 7516 } 7517 7518 return false; 7519 } 7520 }; 7521 7522 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7523 } // end anonymous namespace 7524 7525 /// \brief Report an error regarding overriding, along with any relevant 7526 /// overriden methods. 7527 /// 7528 /// \param DiagID the primary error to report. 7529 /// \param MD the overriding method. 7530 /// \param OEK which overrides to include as notes. 7531 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7532 OverrideErrorKind OEK = OEK_All) { 7533 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7534 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7535 E = MD->end_overridden_methods(); 7536 I != E; ++I) { 7537 // This check (& the OEK parameter) could be replaced by a predicate, but 7538 // without lambdas that would be overkill. This is still nicer than writing 7539 // out the diag loop 3 times. 7540 if ((OEK == OEK_All) || 7541 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7542 (OEK == OEK_Deleted && (*I)->isDeleted())) 7543 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7544 } 7545 } 7546 7547 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7548 /// and if so, check that it's a valid override and remember it. 7549 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7550 // Look for methods in base classes that this method might override. 7551 CXXBasePaths Paths; 7552 FindOverriddenMethod FOM; 7553 FOM.Method = MD; 7554 FOM.S = this; 7555 bool hasDeletedOverridenMethods = false; 7556 bool hasNonDeletedOverridenMethods = false; 7557 bool AddedAny = false; 7558 if (DC->lookupInBases(FOM, Paths)) { 7559 for (auto *I : Paths.found_decls()) { 7560 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7561 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7562 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7563 !CheckOverridingFunctionAttributes(MD, OldMD) && 7564 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7565 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7566 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7567 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7568 AddedAny = true; 7569 } 7570 } 7571 } 7572 } 7573 7574 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7575 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7576 } 7577 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7578 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7579 } 7580 7581 return AddedAny; 7582 } 7583 7584 namespace { 7585 // Struct for holding all of the extra arguments needed by 7586 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7587 struct ActOnFDArgs { 7588 Scope *S; 7589 Declarator &D; 7590 MultiTemplateParamsArg TemplateParamLists; 7591 bool AddToScope; 7592 }; 7593 } // end anonymous namespace 7594 7595 namespace { 7596 7597 // Callback to only accept typo corrections that have a non-zero edit distance. 7598 // Also only accept corrections that have the same parent decl. 7599 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7600 public: 7601 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7602 CXXRecordDecl *Parent) 7603 : Context(Context), OriginalFD(TypoFD), 7604 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7605 7606 bool ValidateCandidate(const TypoCorrection &candidate) override { 7607 if (candidate.getEditDistance() == 0) 7608 return false; 7609 7610 SmallVector<unsigned, 1> MismatchedParams; 7611 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7612 CDeclEnd = candidate.end(); 7613 CDecl != CDeclEnd; ++CDecl) { 7614 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7615 7616 if (FD && !FD->hasBody() && 7617 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7619 CXXRecordDecl *Parent = MD->getParent(); 7620 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7621 return true; 7622 } else if (!ExpectedParent) { 7623 return true; 7624 } 7625 } 7626 } 7627 7628 return false; 7629 } 7630 7631 private: 7632 ASTContext &Context; 7633 FunctionDecl *OriginalFD; 7634 CXXRecordDecl *ExpectedParent; 7635 }; 7636 7637 } // end anonymous namespace 7638 7639 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7640 TypoCorrectedFunctionDefinitions.insert(F); 7641 } 7642 7643 /// \brief Generate diagnostics for an invalid function redeclaration. 7644 /// 7645 /// This routine handles generating the diagnostic messages for an invalid 7646 /// function redeclaration, including finding possible similar declarations 7647 /// or performing typo correction if there are no previous declarations with 7648 /// the same name. 7649 /// 7650 /// Returns a NamedDecl iff typo correction was performed and substituting in 7651 /// the new declaration name does not cause new errors. 7652 static NamedDecl *DiagnoseInvalidRedeclaration( 7653 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7654 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7655 DeclarationName Name = NewFD->getDeclName(); 7656 DeclContext *NewDC = NewFD->getDeclContext(); 7657 SmallVector<unsigned, 1> MismatchedParams; 7658 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7659 TypoCorrection Correction; 7660 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7661 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7662 : diag::err_member_decl_does_not_match; 7663 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7664 IsLocalFriend ? Sema::LookupLocalFriendName 7665 : Sema::LookupOrdinaryName, 7666 Sema::ForRedeclaration); 7667 7668 NewFD->setInvalidDecl(); 7669 if (IsLocalFriend) 7670 SemaRef.LookupName(Prev, S); 7671 else 7672 SemaRef.LookupQualifiedName(Prev, NewDC); 7673 assert(!Prev.isAmbiguous() && 7674 "Cannot have an ambiguity in previous-declaration lookup"); 7675 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7676 if (!Prev.empty()) { 7677 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7678 Func != FuncEnd; ++Func) { 7679 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7680 if (FD && 7681 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7682 // Add 1 to the index so that 0 can mean the mismatch didn't 7683 // involve a parameter 7684 unsigned ParamNum = 7685 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7686 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7687 } 7688 } 7689 // If the qualified name lookup yielded nothing, try typo correction 7690 } else if ((Correction = SemaRef.CorrectTypo( 7691 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7692 &ExtraArgs.D.getCXXScopeSpec(), 7693 llvm::make_unique<DifferentNameValidatorCCC>( 7694 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7695 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7696 // Set up everything for the call to ActOnFunctionDeclarator 7697 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7698 ExtraArgs.D.getIdentifierLoc()); 7699 Previous.clear(); 7700 Previous.setLookupName(Correction.getCorrection()); 7701 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7702 CDeclEnd = Correction.end(); 7703 CDecl != CDeclEnd; ++CDecl) { 7704 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7705 if (FD && !FD->hasBody() && 7706 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7707 Previous.addDecl(FD); 7708 } 7709 } 7710 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7711 7712 NamedDecl *Result; 7713 // Retry building the function declaration with the new previous 7714 // declarations, and with errors suppressed. 7715 { 7716 // Trap errors. 7717 Sema::SFINAETrap Trap(SemaRef); 7718 7719 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7720 // pieces need to verify the typo-corrected C++ declaration and hopefully 7721 // eliminate the need for the parameter pack ExtraArgs. 7722 Result = SemaRef.ActOnFunctionDeclarator( 7723 ExtraArgs.S, ExtraArgs.D, 7724 Correction.getCorrectionDecl()->getDeclContext(), 7725 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7726 ExtraArgs.AddToScope); 7727 7728 if (Trap.hasErrorOccurred()) 7729 Result = nullptr; 7730 } 7731 7732 if (Result) { 7733 // Determine which correction we picked. 7734 Decl *Canonical = Result->getCanonicalDecl(); 7735 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7736 I != E; ++I) 7737 if ((*I)->getCanonicalDecl() == Canonical) 7738 Correction.setCorrectionDecl(*I); 7739 7740 // Let Sema know about the correction. 7741 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7742 SemaRef.diagnoseTypo( 7743 Correction, 7744 SemaRef.PDiag(IsLocalFriend 7745 ? diag::err_no_matching_local_friend_suggest 7746 : diag::err_member_decl_does_not_match_suggest) 7747 << Name << NewDC << IsDefinition); 7748 return Result; 7749 } 7750 7751 // Pretend the typo correction never occurred 7752 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7753 ExtraArgs.D.getIdentifierLoc()); 7754 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7755 Previous.clear(); 7756 Previous.setLookupName(Name); 7757 } 7758 7759 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7760 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7761 7762 bool NewFDisConst = false; 7763 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7764 NewFDisConst = NewMD->isConst(); 7765 7766 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7767 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7768 NearMatch != NearMatchEnd; ++NearMatch) { 7769 FunctionDecl *FD = NearMatch->first; 7770 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7771 bool FDisConst = MD && MD->isConst(); 7772 bool IsMember = MD || !IsLocalFriend; 7773 7774 // FIXME: These notes are poorly worded for the local friend case. 7775 if (unsigned Idx = NearMatch->second) { 7776 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7777 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7778 if (Loc.isInvalid()) Loc = FD->getLocation(); 7779 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7780 : diag::note_local_decl_close_param_match) 7781 << Idx << FDParam->getType() 7782 << NewFD->getParamDecl(Idx - 1)->getType(); 7783 } else if (FDisConst != NewFDisConst) { 7784 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7785 << NewFDisConst << FD->getSourceRange().getEnd(); 7786 } else 7787 SemaRef.Diag(FD->getLocation(), 7788 IsMember ? diag::note_member_def_close_match 7789 : diag::note_local_decl_close_match); 7790 } 7791 return nullptr; 7792 } 7793 7794 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7795 switch (D.getDeclSpec().getStorageClassSpec()) { 7796 default: llvm_unreachable("Unknown storage class!"); 7797 case DeclSpec::SCS_auto: 7798 case DeclSpec::SCS_register: 7799 case DeclSpec::SCS_mutable: 7800 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7801 diag::err_typecheck_sclass_func); 7802 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7803 D.setInvalidType(); 7804 break; 7805 case DeclSpec::SCS_unspecified: break; 7806 case DeclSpec::SCS_extern: 7807 if (D.getDeclSpec().isExternInLinkageSpec()) 7808 return SC_None; 7809 return SC_Extern; 7810 case DeclSpec::SCS_static: { 7811 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7812 // C99 6.7.1p5: 7813 // The declaration of an identifier for a function that has 7814 // block scope shall have no explicit storage-class specifier 7815 // other than extern 7816 // See also (C++ [dcl.stc]p4). 7817 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7818 diag::err_static_block_func); 7819 break; 7820 } else 7821 return SC_Static; 7822 } 7823 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7824 } 7825 7826 // No explicit storage class has already been returned 7827 return SC_None; 7828 } 7829 7830 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7831 DeclContext *DC, QualType &R, 7832 TypeSourceInfo *TInfo, 7833 StorageClass SC, 7834 bool &IsVirtualOkay) { 7835 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7836 DeclarationName Name = NameInfo.getName(); 7837 7838 FunctionDecl *NewFD = nullptr; 7839 bool isInline = D.getDeclSpec().isInlineSpecified(); 7840 7841 if (!SemaRef.getLangOpts().CPlusPlus) { 7842 // Determine whether the function was written with a 7843 // prototype. This true when: 7844 // - there is a prototype in the declarator, or 7845 // - the type R of the function is some kind of typedef or other non- 7846 // attributed reference to a type name (which eventually refers to a 7847 // function type). 7848 bool HasPrototype = 7849 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7850 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7851 7852 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7853 D.getLocStart(), NameInfo, R, 7854 TInfo, SC, isInline, 7855 HasPrototype, false); 7856 if (D.isInvalidType()) 7857 NewFD->setInvalidDecl(); 7858 7859 return NewFD; 7860 } 7861 7862 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7863 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7864 7865 // Check that the return type is not an abstract class type. 7866 // For record types, this is done by the AbstractClassUsageDiagnoser once 7867 // the class has been completely parsed. 7868 if (!DC->isRecord() && 7869 SemaRef.RequireNonAbstractType( 7870 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7871 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7872 D.setInvalidType(); 7873 7874 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7875 // This is a C++ constructor declaration. 7876 assert(DC->isRecord() && 7877 "Constructors can only be declared in a member context"); 7878 7879 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7880 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7881 D.getLocStart(), NameInfo, 7882 R, TInfo, isExplicit, isInline, 7883 /*isImplicitlyDeclared=*/false, 7884 isConstexpr); 7885 7886 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7887 // This is a C++ destructor declaration. 7888 if (DC->isRecord()) { 7889 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7890 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7891 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7892 SemaRef.Context, Record, 7893 D.getLocStart(), 7894 NameInfo, R, TInfo, isInline, 7895 /*isImplicitlyDeclared=*/false); 7896 7897 // If the class is complete, then we now create the implicit exception 7898 // specification. If the class is incomplete or dependent, we can't do 7899 // it yet. 7900 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7901 Record->getDefinition() && !Record->isBeingDefined() && 7902 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7903 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7904 } 7905 7906 IsVirtualOkay = true; 7907 return NewDD; 7908 7909 } else { 7910 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7911 D.setInvalidType(); 7912 7913 // Create a FunctionDecl to satisfy the function definition parsing 7914 // code path. 7915 return FunctionDecl::Create(SemaRef.Context, DC, 7916 D.getLocStart(), 7917 D.getIdentifierLoc(), Name, R, TInfo, 7918 SC, isInline, 7919 /*hasPrototype=*/true, isConstexpr); 7920 } 7921 7922 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7923 if (!DC->isRecord()) { 7924 SemaRef.Diag(D.getIdentifierLoc(), 7925 diag::err_conv_function_not_member); 7926 return nullptr; 7927 } 7928 7929 SemaRef.CheckConversionDeclarator(D, R, SC); 7930 IsVirtualOkay = true; 7931 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7932 D.getLocStart(), NameInfo, 7933 R, TInfo, isInline, isExplicit, 7934 isConstexpr, SourceLocation()); 7935 7936 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7937 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7938 7939 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7940 isExplicit, NameInfo, R, TInfo, 7941 D.getLocEnd()); 7942 } else if (DC->isRecord()) { 7943 // If the name of the function is the same as the name of the record, 7944 // then this must be an invalid constructor that has a return type. 7945 // (The parser checks for a return type and makes the declarator a 7946 // constructor if it has no return type). 7947 if (Name.getAsIdentifierInfo() && 7948 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7949 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7950 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7951 << SourceRange(D.getIdentifierLoc()); 7952 return nullptr; 7953 } 7954 7955 // This is a C++ method declaration. 7956 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7957 cast<CXXRecordDecl>(DC), 7958 D.getLocStart(), NameInfo, R, 7959 TInfo, SC, isInline, 7960 isConstexpr, SourceLocation()); 7961 IsVirtualOkay = !Ret->isStatic(); 7962 return Ret; 7963 } else { 7964 bool isFriend = 7965 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7966 if (!isFriend && SemaRef.CurContext->isRecord()) 7967 return nullptr; 7968 7969 // Determine whether the function was written with a 7970 // prototype. This true when: 7971 // - we're in C++ (where every function has a prototype), 7972 return FunctionDecl::Create(SemaRef.Context, DC, 7973 D.getLocStart(), 7974 NameInfo, R, TInfo, SC, isInline, 7975 true/*HasPrototype*/, isConstexpr); 7976 } 7977 } 7978 7979 enum OpenCLParamType { 7980 ValidKernelParam, 7981 PtrPtrKernelParam, 7982 PtrKernelParam, 7983 InvalidAddrSpacePtrKernelParam, 7984 InvalidKernelParam, 7985 RecordKernelParam 7986 }; 7987 7988 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7989 if (PT->isPointerType()) { 7990 QualType PointeeType = PT->getPointeeType(); 7991 if (PointeeType->isPointerType()) 7992 return PtrPtrKernelParam; 7993 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7994 PointeeType.getAddressSpace() == 0) 7995 return InvalidAddrSpacePtrKernelParam; 7996 return PtrKernelParam; 7997 } 7998 7999 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8000 // be used as builtin types. 8001 8002 if (PT->isImageType()) 8003 return PtrKernelParam; 8004 8005 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8006 return InvalidKernelParam; 8007 8008 // OpenCL extension spec v1.2 s9.5: 8009 // This extension adds support for half scalar and vector types as built-in 8010 // types that can be used for arithmetic operations, conversions etc. 8011 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8012 return InvalidKernelParam; 8013 8014 if (PT->isRecordType()) 8015 return RecordKernelParam; 8016 8017 return ValidKernelParam; 8018 } 8019 8020 static void checkIsValidOpenCLKernelParameter( 8021 Sema &S, 8022 Declarator &D, 8023 ParmVarDecl *Param, 8024 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8025 QualType PT = Param->getType(); 8026 8027 // Cache the valid types we encounter to avoid rechecking structs that are 8028 // used again 8029 if (ValidTypes.count(PT.getTypePtr())) 8030 return; 8031 8032 switch (getOpenCLKernelParameterType(S, PT)) { 8033 case PtrPtrKernelParam: 8034 // OpenCL v1.2 s6.9.a: 8035 // A kernel function argument cannot be declared as a 8036 // pointer to a pointer type. 8037 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8038 D.setInvalidType(); 8039 return; 8040 8041 case InvalidAddrSpacePtrKernelParam: 8042 // OpenCL v1.0 s6.5: 8043 // __kernel function arguments declared to be a pointer of a type can point 8044 // to one of the following address spaces only : __global, __local or 8045 // __constant. 8046 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8047 D.setInvalidType(); 8048 return; 8049 8050 // OpenCL v1.2 s6.9.k: 8051 // Arguments to kernel functions in a program cannot be declared with the 8052 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8053 // uintptr_t or a struct and/or union that contain fields declared to be 8054 // one of these built-in scalar types. 8055 8056 case InvalidKernelParam: 8057 // OpenCL v1.2 s6.8 n: 8058 // A kernel function argument cannot be declared 8059 // of event_t type. 8060 // Do not diagnose half type since it is diagnosed as invalid argument 8061 // type for any function elsewhere. 8062 if (!PT->isHalfType()) 8063 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8064 D.setInvalidType(); 8065 return; 8066 8067 case PtrKernelParam: 8068 case ValidKernelParam: 8069 ValidTypes.insert(PT.getTypePtr()); 8070 return; 8071 8072 case RecordKernelParam: 8073 break; 8074 } 8075 8076 // Track nested structs we will inspect 8077 SmallVector<const Decl *, 4> VisitStack; 8078 8079 // Track where we are in the nested structs. Items will migrate from 8080 // VisitStack to HistoryStack as we do the DFS for bad field. 8081 SmallVector<const FieldDecl *, 4> HistoryStack; 8082 HistoryStack.push_back(nullptr); 8083 8084 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8085 VisitStack.push_back(PD); 8086 8087 assert(VisitStack.back() && "First decl null?"); 8088 8089 do { 8090 const Decl *Next = VisitStack.pop_back_val(); 8091 if (!Next) { 8092 assert(!HistoryStack.empty()); 8093 // Found a marker, we have gone up a level 8094 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8095 ValidTypes.insert(Hist->getType().getTypePtr()); 8096 8097 continue; 8098 } 8099 8100 // Adds everything except the original parameter declaration (which is not a 8101 // field itself) to the history stack. 8102 const RecordDecl *RD; 8103 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8104 HistoryStack.push_back(Field); 8105 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8106 } else { 8107 RD = cast<RecordDecl>(Next); 8108 } 8109 8110 // Add a null marker so we know when we've gone back up a level 8111 VisitStack.push_back(nullptr); 8112 8113 for (const auto *FD : RD->fields()) { 8114 QualType QT = FD->getType(); 8115 8116 if (ValidTypes.count(QT.getTypePtr())) 8117 continue; 8118 8119 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8120 if (ParamType == ValidKernelParam) 8121 continue; 8122 8123 if (ParamType == RecordKernelParam) { 8124 VisitStack.push_back(FD); 8125 continue; 8126 } 8127 8128 // OpenCL v1.2 s6.9.p: 8129 // Arguments to kernel functions that are declared to be a struct or union 8130 // do not allow OpenCL objects to be passed as elements of the struct or 8131 // union. 8132 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8133 ParamType == InvalidAddrSpacePtrKernelParam) { 8134 S.Diag(Param->getLocation(), 8135 diag::err_record_with_pointers_kernel_param) 8136 << PT->isUnionType() 8137 << PT; 8138 } else { 8139 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8140 } 8141 8142 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8143 << PD->getDeclName(); 8144 8145 // We have an error, now let's go back up through history and show where 8146 // the offending field came from 8147 for (ArrayRef<const FieldDecl *>::const_iterator 8148 I = HistoryStack.begin() + 1, 8149 E = HistoryStack.end(); 8150 I != E; ++I) { 8151 const FieldDecl *OuterField = *I; 8152 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8153 << OuterField->getType(); 8154 } 8155 8156 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8157 << QT->isPointerType() 8158 << QT; 8159 D.setInvalidType(); 8160 return; 8161 } 8162 } while (!VisitStack.empty()); 8163 } 8164 8165 /// Find the DeclContext in which a tag is implicitly declared if we see an 8166 /// elaborated type specifier in the specified context, and lookup finds 8167 /// nothing. 8168 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8169 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8170 DC = DC->getParent(); 8171 return DC; 8172 } 8173 8174 /// Find the Scope in which a tag is implicitly declared if we see an 8175 /// elaborated type specifier in the specified context, and lookup finds 8176 /// nothing. 8177 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8178 while (S->isClassScope() || 8179 (LangOpts.CPlusPlus && 8180 S->isFunctionPrototypeScope()) || 8181 ((S->getFlags() & Scope::DeclScope) == 0) || 8182 (S->getEntity() && S->getEntity()->isTransparentContext())) 8183 S = S->getParent(); 8184 return S; 8185 } 8186 8187 NamedDecl* 8188 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8189 TypeSourceInfo *TInfo, LookupResult &Previous, 8190 MultiTemplateParamsArg TemplateParamLists, 8191 bool &AddToScope) { 8192 QualType R = TInfo->getType(); 8193 8194 assert(R.getTypePtr()->isFunctionType()); 8195 8196 // TODO: consider using NameInfo for diagnostic. 8197 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8198 DeclarationName Name = NameInfo.getName(); 8199 StorageClass SC = getFunctionStorageClass(*this, D); 8200 8201 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8202 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8203 diag::err_invalid_thread) 8204 << DeclSpec::getSpecifierName(TSCS); 8205 8206 if (D.isFirstDeclarationOfMember()) 8207 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8208 D.getIdentifierLoc()); 8209 8210 bool isFriend = false; 8211 FunctionTemplateDecl *FunctionTemplate = nullptr; 8212 bool isMemberSpecialization = false; 8213 bool isFunctionTemplateSpecialization = false; 8214 8215 bool isDependentClassScopeExplicitSpecialization = false; 8216 bool HasExplicitTemplateArgs = false; 8217 TemplateArgumentListInfo TemplateArgs; 8218 8219 bool isVirtualOkay = false; 8220 8221 DeclContext *OriginalDC = DC; 8222 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8223 8224 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8225 isVirtualOkay); 8226 if (!NewFD) return nullptr; 8227 8228 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8229 NewFD->setTopLevelDeclInObjCContainer(); 8230 8231 // Set the lexical context. If this is a function-scope declaration, or has a 8232 // C++ scope specifier, or is the object of a friend declaration, the lexical 8233 // context will be different from the semantic context. 8234 NewFD->setLexicalDeclContext(CurContext); 8235 8236 if (IsLocalExternDecl) 8237 NewFD->setLocalExternDecl(); 8238 8239 if (getLangOpts().CPlusPlus) { 8240 bool isInline = D.getDeclSpec().isInlineSpecified(); 8241 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8242 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8243 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8244 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8245 isFriend = D.getDeclSpec().isFriendSpecified(); 8246 if (isFriend && !isInline && D.isFunctionDefinition()) { 8247 // C++ [class.friend]p5 8248 // A function can be defined in a friend declaration of a 8249 // class . . . . Such a function is implicitly inline. 8250 NewFD->setImplicitlyInline(); 8251 } 8252 8253 // If this is a method defined in an __interface, and is not a constructor 8254 // or an overloaded operator, then set the pure flag (isVirtual will already 8255 // return true). 8256 if (const CXXRecordDecl *Parent = 8257 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8258 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8259 NewFD->setPure(true); 8260 8261 // C++ [class.union]p2 8262 // A union can have member functions, but not virtual functions. 8263 if (isVirtual && Parent->isUnion()) 8264 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8265 } 8266 8267 SetNestedNameSpecifier(NewFD, D); 8268 isMemberSpecialization = false; 8269 isFunctionTemplateSpecialization = false; 8270 if (D.isInvalidType()) 8271 NewFD->setInvalidDecl(); 8272 8273 // Match up the template parameter lists with the scope specifier, then 8274 // determine whether we have a template or a template specialization. 8275 bool Invalid = false; 8276 if (TemplateParameterList *TemplateParams = 8277 MatchTemplateParametersToScopeSpecifier( 8278 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8279 D.getCXXScopeSpec(), 8280 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8281 ? D.getName().TemplateId 8282 : nullptr, 8283 TemplateParamLists, isFriend, isMemberSpecialization, 8284 Invalid)) { 8285 if (TemplateParams->size() > 0) { 8286 // This is a function template 8287 8288 // Check that we can declare a template here. 8289 if (CheckTemplateDeclScope(S, TemplateParams)) 8290 NewFD->setInvalidDecl(); 8291 8292 // A destructor cannot be a template. 8293 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8294 Diag(NewFD->getLocation(), diag::err_destructor_template); 8295 NewFD->setInvalidDecl(); 8296 } 8297 8298 // If we're adding a template to a dependent context, we may need to 8299 // rebuilding some of the types used within the template parameter list, 8300 // now that we know what the current instantiation is. 8301 if (DC->isDependentContext()) { 8302 ContextRAII SavedContext(*this, DC); 8303 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8304 Invalid = true; 8305 } 8306 8307 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8308 NewFD->getLocation(), 8309 Name, TemplateParams, 8310 NewFD); 8311 FunctionTemplate->setLexicalDeclContext(CurContext); 8312 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8313 8314 // For source fidelity, store the other template param lists. 8315 if (TemplateParamLists.size() > 1) { 8316 NewFD->setTemplateParameterListsInfo(Context, 8317 TemplateParamLists.drop_back(1)); 8318 } 8319 } else { 8320 // This is a function template specialization. 8321 isFunctionTemplateSpecialization = true; 8322 // For source fidelity, store all the template param lists. 8323 if (TemplateParamLists.size() > 0) 8324 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8325 8326 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8327 if (isFriend) { 8328 // We want to remove the "template<>", found here. 8329 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8330 8331 // If we remove the template<> and the name is not a 8332 // template-id, we're actually silently creating a problem: 8333 // the friend declaration will refer to an untemplated decl, 8334 // and clearly the user wants a template specialization. So 8335 // we need to insert '<>' after the name. 8336 SourceLocation InsertLoc; 8337 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8338 InsertLoc = D.getName().getSourceRange().getEnd(); 8339 InsertLoc = getLocForEndOfToken(InsertLoc); 8340 } 8341 8342 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8343 << Name << RemoveRange 8344 << FixItHint::CreateRemoval(RemoveRange) 8345 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8346 } 8347 } 8348 } 8349 else { 8350 // All template param lists were matched against the scope specifier: 8351 // this is NOT (an explicit specialization of) a template. 8352 if (TemplateParamLists.size() > 0) 8353 // For source fidelity, store all the template param lists. 8354 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8355 } 8356 8357 if (Invalid) { 8358 NewFD->setInvalidDecl(); 8359 if (FunctionTemplate) 8360 FunctionTemplate->setInvalidDecl(); 8361 } 8362 8363 // C++ [dcl.fct.spec]p5: 8364 // The virtual specifier shall only be used in declarations of 8365 // nonstatic class member functions that appear within a 8366 // member-specification of a class declaration; see 10.3. 8367 // 8368 if (isVirtual && !NewFD->isInvalidDecl()) { 8369 if (!isVirtualOkay) { 8370 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8371 diag::err_virtual_non_function); 8372 } else if (!CurContext->isRecord()) { 8373 // 'virtual' was specified outside of the class. 8374 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8375 diag::err_virtual_out_of_class) 8376 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8377 } else if (NewFD->getDescribedFunctionTemplate()) { 8378 // C++ [temp.mem]p3: 8379 // A member function template shall not be virtual. 8380 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8381 diag::err_virtual_member_function_template) 8382 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8383 } else { 8384 // Okay: Add virtual to the method. 8385 NewFD->setVirtualAsWritten(true); 8386 } 8387 8388 if (getLangOpts().CPlusPlus14 && 8389 NewFD->getReturnType()->isUndeducedType()) 8390 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8391 } 8392 8393 if (getLangOpts().CPlusPlus14 && 8394 (NewFD->isDependentContext() || 8395 (isFriend && CurContext->isDependentContext())) && 8396 NewFD->getReturnType()->isUndeducedType()) { 8397 // If the function template is referenced directly (for instance, as a 8398 // member of the current instantiation), pretend it has a dependent type. 8399 // This is not really justified by the standard, but is the only sane 8400 // thing to do. 8401 // FIXME: For a friend function, we have not marked the function as being 8402 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8403 const FunctionProtoType *FPT = 8404 NewFD->getType()->castAs<FunctionProtoType>(); 8405 QualType Result = 8406 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8407 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8408 FPT->getExtProtoInfo())); 8409 } 8410 8411 // C++ [dcl.fct.spec]p3: 8412 // The inline specifier shall not appear on a block scope function 8413 // declaration. 8414 if (isInline && !NewFD->isInvalidDecl()) { 8415 if (CurContext->isFunctionOrMethod()) { 8416 // 'inline' is not allowed on block scope function declaration. 8417 Diag(D.getDeclSpec().getInlineSpecLoc(), 8418 diag::err_inline_declaration_block_scope) << Name 8419 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8420 } 8421 } 8422 8423 // C++ [dcl.fct.spec]p6: 8424 // The explicit specifier shall be used only in the declaration of a 8425 // constructor or conversion function within its class definition; 8426 // see 12.3.1 and 12.3.2. 8427 if (isExplicit && !NewFD->isInvalidDecl() && 8428 !isa<CXXDeductionGuideDecl>(NewFD)) { 8429 if (!CurContext->isRecord()) { 8430 // 'explicit' was specified outside of the class. 8431 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8432 diag::err_explicit_out_of_class) 8433 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8434 } else if (!isa<CXXConstructorDecl>(NewFD) && 8435 !isa<CXXConversionDecl>(NewFD)) { 8436 // 'explicit' was specified on a function that wasn't a constructor 8437 // or conversion function. 8438 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8439 diag::err_explicit_non_ctor_or_conv_function) 8440 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8441 } 8442 } 8443 8444 if (isConstexpr) { 8445 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8446 // are implicitly inline. 8447 NewFD->setImplicitlyInline(); 8448 8449 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8450 // be either constructors or to return a literal type. Therefore, 8451 // destructors cannot be declared constexpr. 8452 if (isa<CXXDestructorDecl>(NewFD)) 8453 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8454 } 8455 8456 if (isConcept) { 8457 // This is a function concept. 8458 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8459 FTD->setConcept(); 8460 8461 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8462 // applied only to the definition of a function template [...] 8463 if (!D.isFunctionDefinition()) { 8464 Diag(D.getDeclSpec().getConceptSpecLoc(), 8465 diag::err_function_concept_not_defined); 8466 NewFD->setInvalidDecl(); 8467 } 8468 8469 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8470 // have no exception-specification and is treated as if it were specified 8471 // with noexcept(true) (15.4). [...] 8472 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8473 if (FPT->hasExceptionSpec()) { 8474 SourceRange Range; 8475 if (D.isFunctionDeclarator()) 8476 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8477 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8478 << FixItHint::CreateRemoval(Range); 8479 NewFD->setInvalidDecl(); 8480 } else { 8481 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8482 } 8483 8484 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8485 // following restrictions: 8486 // - The declared return type shall have the type bool. 8487 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8488 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8489 NewFD->setInvalidDecl(); 8490 } 8491 8492 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8493 // following restrictions: 8494 // - The declaration's parameter list shall be equivalent to an empty 8495 // parameter list. 8496 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8497 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8498 } 8499 8500 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8501 // implicity defined to be a constexpr declaration (implicitly inline) 8502 NewFD->setImplicitlyInline(); 8503 8504 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8505 // be declared with the thread_local, inline, friend, or constexpr 8506 // specifiers, [...] 8507 if (isInline) { 8508 Diag(D.getDeclSpec().getInlineSpecLoc(), 8509 diag::err_concept_decl_invalid_specifiers) 8510 << 1 << 1; 8511 NewFD->setInvalidDecl(true); 8512 } 8513 8514 if (isFriend) { 8515 Diag(D.getDeclSpec().getFriendSpecLoc(), 8516 diag::err_concept_decl_invalid_specifiers) 8517 << 1 << 2; 8518 NewFD->setInvalidDecl(true); 8519 } 8520 8521 if (isConstexpr) { 8522 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8523 diag::err_concept_decl_invalid_specifiers) 8524 << 1 << 3; 8525 NewFD->setInvalidDecl(true); 8526 } 8527 8528 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8529 // applied only to the definition of a function template or variable 8530 // template, declared in namespace scope. 8531 if (isFunctionTemplateSpecialization) { 8532 Diag(D.getDeclSpec().getConceptSpecLoc(), 8533 diag::err_concept_specified_specialization) << 1; 8534 NewFD->setInvalidDecl(true); 8535 return NewFD; 8536 } 8537 } 8538 8539 // If __module_private__ was specified, mark the function accordingly. 8540 if (D.getDeclSpec().isModulePrivateSpecified()) { 8541 if (isFunctionTemplateSpecialization) { 8542 SourceLocation ModulePrivateLoc 8543 = D.getDeclSpec().getModulePrivateSpecLoc(); 8544 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8545 << 0 8546 << FixItHint::CreateRemoval(ModulePrivateLoc); 8547 } else { 8548 NewFD->setModulePrivate(); 8549 if (FunctionTemplate) 8550 FunctionTemplate->setModulePrivate(); 8551 } 8552 } 8553 8554 if (isFriend) { 8555 if (FunctionTemplate) { 8556 FunctionTemplate->setObjectOfFriendDecl(); 8557 FunctionTemplate->setAccess(AS_public); 8558 } 8559 NewFD->setObjectOfFriendDecl(); 8560 NewFD->setAccess(AS_public); 8561 } 8562 8563 // If a function is defined as defaulted or deleted, mark it as such now. 8564 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8565 // definition kind to FDK_Definition. 8566 switch (D.getFunctionDefinitionKind()) { 8567 case FDK_Declaration: 8568 case FDK_Definition: 8569 break; 8570 8571 case FDK_Defaulted: 8572 NewFD->setDefaulted(); 8573 break; 8574 8575 case FDK_Deleted: 8576 NewFD->setDeletedAsWritten(); 8577 break; 8578 } 8579 8580 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8581 D.isFunctionDefinition()) { 8582 // C++ [class.mfct]p2: 8583 // A member function may be defined (8.4) in its class definition, in 8584 // which case it is an inline member function (7.1.2) 8585 NewFD->setImplicitlyInline(); 8586 } 8587 8588 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8589 !CurContext->isRecord()) { 8590 // C++ [class.static]p1: 8591 // A data or function member of a class may be declared static 8592 // in a class definition, in which case it is a static member of 8593 // the class. 8594 8595 // Complain about the 'static' specifier if it's on an out-of-line 8596 // member function definition. 8597 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8598 diag::err_static_out_of_line) 8599 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8600 } 8601 8602 // C++11 [except.spec]p15: 8603 // A deallocation function with no exception-specification is treated 8604 // as if it were specified with noexcept(true). 8605 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8606 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8607 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8608 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8609 NewFD->setType(Context.getFunctionType( 8610 FPT->getReturnType(), FPT->getParamTypes(), 8611 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8612 } 8613 8614 // Filter out previous declarations that don't match the scope. 8615 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8616 D.getCXXScopeSpec().isNotEmpty() || 8617 isMemberSpecialization || 8618 isFunctionTemplateSpecialization); 8619 8620 // Handle GNU asm-label extension (encoded as an attribute). 8621 if (Expr *E = (Expr*) D.getAsmLabel()) { 8622 // The parser guarantees this is a string. 8623 StringLiteral *SE = cast<StringLiteral>(E); 8624 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8625 SE->getString(), 0)); 8626 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8627 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8628 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8629 if (I != ExtnameUndeclaredIdentifiers.end()) { 8630 if (isDeclExternC(NewFD)) { 8631 NewFD->addAttr(I->second); 8632 ExtnameUndeclaredIdentifiers.erase(I); 8633 } else 8634 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8635 << /*Variable*/0 << NewFD; 8636 } 8637 } 8638 8639 // Copy the parameter declarations from the declarator D to the function 8640 // declaration NewFD, if they are available. First scavenge them into Params. 8641 SmallVector<ParmVarDecl*, 16> Params; 8642 unsigned FTIIdx; 8643 if (D.isFunctionDeclarator(FTIIdx)) { 8644 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8645 8646 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8647 // function that takes no arguments, not a function that takes a 8648 // single void argument. 8649 // We let through "const void" here because Sema::GetTypeForDeclarator 8650 // already checks for that case. 8651 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8652 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8653 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8654 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8655 Param->setDeclContext(NewFD); 8656 Params.push_back(Param); 8657 8658 if (Param->isInvalidDecl()) 8659 NewFD->setInvalidDecl(); 8660 } 8661 } 8662 8663 if (!getLangOpts().CPlusPlus) { 8664 // In C, find all the tag declarations from the prototype and move them 8665 // into the function DeclContext. Remove them from the surrounding tag 8666 // injection context of the function, which is typically but not always 8667 // the TU. 8668 DeclContext *PrototypeTagContext = 8669 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8670 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8671 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8672 8673 // We don't want to reparent enumerators. Look at their parent enum 8674 // instead. 8675 if (!TD) { 8676 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8677 TD = cast<EnumDecl>(ECD->getDeclContext()); 8678 } 8679 if (!TD) 8680 continue; 8681 DeclContext *TagDC = TD->getLexicalDeclContext(); 8682 if (!TagDC->containsDecl(TD)) 8683 continue; 8684 TagDC->removeDecl(TD); 8685 TD->setDeclContext(NewFD); 8686 NewFD->addDecl(TD); 8687 8688 // Preserve the lexical DeclContext if it is not the surrounding tag 8689 // injection context of the FD. In this example, the semantic context of 8690 // E will be f and the lexical context will be S, while both the 8691 // semantic and lexical contexts of S will be f: 8692 // void f(struct S { enum E { a } f; } s); 8693 if (TagDC != PrototypeTagContext) 8694 TD->setLexicalDeclContext(TagDC); 8695 } 8696 } 8697 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8698 // When we're declaring a function with a typedef, typeof, etc as in the 8699 // following example, we'll need to synthesize (unnamed) 8700 // parameters for use in the declaration. 8701 // 8702 // @code 8703 // typedef void fn(int); 8704 // fn f; 8705 // @endcode 8706 8707 // Synthesize a parameter for each argument type. 8708 for (const auto &AI : FT->param_types()) { 8709 ParmVarDecl *Param = 8710 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8711 Param->setScopeInfo(0, Params.size()); 8712 Params.push_back(Param); 8713 } 8714 } else { 8715 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8716 "Should not need args for typedef of non-prototype fn"); 8717 } 8718 8719 // Finally, we know we have the right number of parameters, install them. 8720 NewFD->setParams(Params); 8721 8722 if (D.getDeclSpec().isNoreturnSpecified()) 8723 NewFD->addAttr( 8724 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8725 Context, 0)); 8726 8727 // Functions returning a variably modified type violate C99 6.7.5.2p2 8728 // because all functions have linkage. 8729 if (!NewFD->isInvalidDecl() && 8730 NewFD->getReturnType()->isVariablyModifiedType()) { 8731 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8732 NewFD->setInvalidDecl(); 8733 } 8734 8735 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8736 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8737 !NewFD->hasAttr<SectionAttr>()) { 8738 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8739 PragmaClangTextSection.SectionName, 8740 PragmaClangTextSection.PragmaLocation)); 8741 } 8742 8743 // Apply an implicit SectionAttr if #pragma code_seg is active. 8744 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8745 !NewFD->hasAttr<SectionAttr>()) { 8746 NewFD->addAttr( 8747 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8748 CodeSegStack.CurrentValue->getString(), 8749 CodeSegStack.CurrentPragmaLocation)); 8750 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8751 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8752 ASTContext::PSF_Read, 8753 NewFD)) 8754 NewFD->dropAttr<SectionAttr>(); 8755 } 8756 8757 // Handle attributes. 8758 ProcessDeclAttributes(S, NewFD, D); 8759 8760 if (getLangOpts().OpenCL) { 8761 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8762 // type declaration will generate a compilation error. 8763 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8764 if (AddressSpace == LangAS::opencl_local || 8765 AddressSpace == LangAS::opencl_global || 8766 AddressSpace == LangAS::opencl_constant) { 8767 Diag(NewFD->getLocation(), 8768 diag::err_opencl_return_value_with_address_space); 8769 NewFD->setInvalidDecl(); 8770 } 8771 } 8772 8773 if (!getLangOpts().CPlusPlus) { 8774 // Perform semantic checking on the function declaration. 8775 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8776 CheckMain(NewFD, D.getDeclSpec()); 8777 8778 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8779 CheckMSVCRTEntryPoint(NewFD); 8780 8781 if (!NewFD->isInvalidDecl()) 8782 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8783 isMemberSpecialization)); 8784 else if (!Previous.empty()) 8785 // Recover gracefully from an invalid redeclaration. 8786 D.setRedeclaration(true); 8787 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8788 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8789 "previous declaration set still overloaded"); 8790 8791 // Diagnose no-prototype function declarations with calling conventions that 8792 // don't support variadic calls. Only do this in C and do it after merging 8793 // possibly prototyped redeclarations. 8794 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8795 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8796 CallingConv CC = FT->getExtInfo().getCC(); 8797 if (!supportsVariadicCall(CC)) { 8798 // Windows system headers sometimes accidentally use stdcall without 8799 // (void) parameters, so we relax this to a warning. 8800 int DiagID = 8801 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8802 Diag(NewFD->getLocation(), DiagID) 8803 << FunctionType::getNameForCallConv(CC); 8804 } 8805 } 8806 } else { 8807 // C++11 [replacement.functions]p3: 8808 // The program's definitions shall not be specified as inline. 8809 // 8810 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8811 // 8812 // Suppress the diagnostic if the function is __attribute__((used)), since 8813 // that forces an external definition to be emitted. 8814 if (D.getDeclSpec().isInlineSpecified() && 8815 NewFD->isReplaceableGlobalAllocationFunction() && 8816 !NewFD->hasAttr<UsedAttr>()) 8817 Diag(D.getDeclSpec().getInlineSpecLoc(), 8818 diag::ext_operator_new_delete_declared_inline) 8819 << NewFD->getDeclName(); 8820 8821 // If the declarator is a template-id, translate the parser's template 8822 // argument list into our AST format. 8823 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8824 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8825 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8826 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8827 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8828 TemplateId->NumArgs); 8829 translateTemplateArguments(TemplateArgsPtr, 8830 TemplateArgs); 8831 8832 HasExplicitTemplateArgs = true; 8833 8834 if (NewFD->isInvalidDecl()) { 8835 HasExplicitTemplateArgs = false; 8836 } else if (FunctionTemplate) { 8837 // Function template with explicit template arguments. 8838 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8839 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8840 8841 HasExplicitTemplateArgs = false; 8842 } else { 8843 assert((isFunctionTemplateSpecialization || 8844 D.getDeclSpec().isFriendSpecified()) && 8845 "should have a 'template<>' for this decl"); 8846 // "friend void foo<>(int);" is an implicit specialization decl. 8847 isFunctionTemplateSpecialization = true; 8848 } 8849 } else if (isFriend && isFunctionTemplateSpecialization) { 8850 // This combination is only possible in a recovery case; the user 8851 // wrote something like: 8852 // template <> friend void foo(int); 8853 // which we're recovering from as if the user had written: 8854 // friend void foo<>(int); 8855 // Go ahead and fake up a template id. 8856 HasExplicitTemplateArgs = true; 8857 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8858 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8859 } 8860 8861 // We do not add HD attributes to specializations here because 8862 // they may have different constexpr-ness compared to their 8863 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8864 // may end up with different effective targets. Instead, a 8865 // specialization inherits its target attributes from its template 8866 // in the CheckFunctionTemplateSpecialization() call below. 8867 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8868 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8869 8870 // If it's a friend (and only if it's a friend), it's possible 8871 // that either the specialized function type or the specialized 8872 // template is dependent, and therefore matching will fail. In 8873 // this case, don't check the specialization yet. 8874 bool InstantiationDependent = false; 8875 if (isFunctionTemplateSpecialization && isFriend && 8876 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8877 TemplateSpecializationType::anyDependentTemplateArguments( 8878 TemplateArgs, 8879 InstantiationDependent))) { 8880 assert(HasExplicitTemplateArgs && 8881 "friend function specialization without template args"); 8882 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8883 Previous)) 8884 NewFD->setInvalidDecl(); 8885 } else if (isFunctionTemplateSpecialization) { 8886 if (CurContext->isDependentContext() && CurContext->isRecord() 8887 && !isFriend) { 8888 isDependentClassScopeExplicitSpecialization = true; 8889 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8890 diag::ext_function_specialization_in_class : 8891 diag::err_function_specialization_in_class) 8892 << NewFD->getDeclName(); 8893 } else if (CheckFunctionTemplateSpecialization(NewFD, 8894 (HasExplicitTemplateArgs ? &TemplateArgs 8895 : nullptr), 8896 Previous)) 8897 NewFD->setInvalidDecl(); 8898 8899 // C++ [dcl.stc]p1: 8900 // A storage-class-specifier shall not be specified in an explicit 8901 // specialization (14.7.3) 8902 FunctionTemplateSpecializationInfo *Info = 8903 NewFD->getTemplateSpecializationInfo(); 8904 if (Info && SC != SC_None) { 8905 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8906 Diag(NewFD->getLocation(), 8907 diag::err_explicit_specialization_inconsistent_storage_class) 8908 << SC 8909 << FixItHint::CreateRemoval( 8910 D.getDeclSpec().getStorageClassSpecLoc()); 8911 8912 else 8913 Diag(NewFD->getLocation(), 8914 diag::ext_explicit_specialization_storage_class) 8915 << FixItHint::CreateRemoval( 8916 D.getDeclSpec().getStorageClassSpecLoc()); 8917 } 8918 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8919 if (CheckMemberSpecialization(NewFD, Previous)) 8920 NewFD->setInvalidDecl(); 8921 } 8922 8923 // Perform semantic checking on the function declaration. 8924 if (!isDependentClassScopeExplicitSpecialization) { 8925 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8926 CheckMain(NewFD, D.getDeclSpec()); 8927 8928 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8929 CheckMSVCRTEntryPoint(NewFD); 8930 8931 if (!NewFD->isInvalidDecl()) 8932 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8933 isMemberSpecialization)); 8934 else if (!Previous.empty()) 8935 // Recover gracefully from an invalid redeclaration. 8936 D.setRedeclaration(true); 8937 } 8938 8939 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8940 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8941 "previous declaration set still overloaded"); 8942 8943 NamedDecl *PrincipalDecl = (FunctionTemplate 8944 ? cast<NamedDecl>(FunctionTemplate) 8945 : NewFD); 8946 8947 if (isFriend && NewFD->getPreviousDecl()) { 8948 AccessSpecifier Access = AS_public; 8949 if (!NewFD->isInvalidDecl()) 8950 Access = NewFD->getPreviousDecl()->getAccess(); 8951 8952 NewFD->setAccess(Access); 8953 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8954 } 8955 8956 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8957 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8958 PrincipalDecl->setNonMemberOperator(); 8959 8960 // If we have a function template, check the template parameter 8961 // list. This will check and merge default template arguments. 8962 if (FunctionTemplate) { 8963 FunctionTemplateDecl *PrevTemplate = 8964 FunctionTemplate->getPreviousDecl(); 8965 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8966 PrevTemplate ? PrevTemplate->getTemplateParameters() 8967 : nullptr, 8968 D.getDeclSpec().isFriendSpecified() 8969 ? (D.isFunctionDefinition() 8970 ? TPC_FriendFunctionTemplateDefinition 8971 : TPC_FriendFunctionTemplate) 8972 : (D.getCXXScopeSpec().isSet() && 8973 DC && DC->isRecord() && 8974 DC->isDependentContext()) 8975 ? TPC_ClassTemplateMember 8976 : TPC_FunctionTemplate); 8977 } 8978 8979 if (NewFD->isInvalidDecl()) { 8980 // Ignore all the rest of this. 8981 } else if (!D.isRedeclaration()) { 8982 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8983 AddToScope }; 8984 // Fake up an access specifier if it's supposed to be a class member. 8985 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8986 NewFD->setAccess(AS_public); 8987 8988 // Qualified decls generally require a previous declaration. 8989 if (D.getCXXScopeSpec().isSet()) { 8990 // ...with the major exception of templated-scope or 8991 // dependent-scope friend declarations. 8992 8993 // TODO: we currently also suppress this check in dependent 8994 // contexts because (1) the parameter depth will be off when 8995 // matching friend templates and (2) we might actually be 8996 // selecting a friend based on a dependent factor. But there 8997 // are situations where these conditions don't apply and we 8998 // can actually do this check immediately. 8999 if (isFriend && 9000 (TemplateParamLists.size() || 9001 D.getCXXScopeSpec().getScopeRep()->isDependent() || 9002 CurContext->isDependentContext())) { 9003 // ignore these 9004 } else { 9005 // The user tried to provide an out-of-line definition for a 9006 // function that is a member of a class or namespace, but there 9007 // was no such member function declared (C++ [class.mfct]p2, 9008 // C++ [namespace.memdef]p2). For example: 9009 // 9010 // class X { 9011 // void f() const; 9012 // }; 9013 // 9014 // void X::f() { } // ill-formed 9015 // 9016 // Complain about this problem, and attempt to suggest close 9017 // matches (e.g., those that differ only in cv-qualifiers and 9018 // whether the parameter types are references). 9019 9020 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9021 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9022 AddToScope = ExtraArgs.AddToScope; 9023 return Result; 9024 } 9025 } 9026 9027 // Unqualified local friend declarations are required to resolve 9028 // to something. 9029 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9030 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9031 *this, Previous, NewFD, ExtraArgs, true, S)) { 9032 AddToScope = ExtraArgs.AddToScope; 9033 return Result; 9034 } 9035 } 9036 } else if (!D.isFunctionDefinition() && 9037 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9038 !isFriend && !isFunctionTemplateSpecialization && 9039 !isMemberSpecialization) { 9040 // An out-of-line member function declaration must also be a 9041 // definition (C++ [class.mfct]p2). 9042 // Note that this is not the case for explicit specializations of 9043 // function templates or member functions of class templates, per 9044 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9045 // extension for compatibility with old SWIG code which likes to 9046 // generate them. 9047 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9048 << D.getCXXScopeSpec().getRange(); 9049 } 9050 } 9051 9052 ProcessPragmaWeak(S, NewFD); 9053 checkAttributesAfterMerging(*this, *NewFD); 9054 9055 AddKnownFunctionAttributes(NewFD); 9056 9057 if (NewFD->hasAttr<OverloadableAttr>() && 9058 !NewFD->getType()->getAs<FunctionProtoType>()) { 9059 Diag(NewFD->getLocation(), 9060 diag::err_attribute_overloadable_no_prototype) 9061 << NewFD; 9062 9063 // Turn this into a variadic function with no parameters. 9064 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9065 FunctionProtoType::ExtProtoInfo EPI( 9066 Context.getDefaultCallingConvention(true, false)); 9067 EPI.Variadic = true; 9068 EPI.ExtInfo = FT->getExtInfo(); 9069 9070 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9071 NewFD->setType(R); 9072 } 9073 9074 // If there's a #pragma GCC visibility in scope, and this isn't a class 9075 // member, set the visibility of this function. 9076 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9077 AddPushedVisibilityAttribute(NewFD); 9078 9079 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9080 // marking the function. 9081 AddCFAuditedAttribute(NewFD); 9082 9083 // If this is a function definition, check if we have to apply optnone due to 9084 // a pragma. 9085 if(D.isFunctionDefinition()) 9086 AddRangeBasedOptnone(NewFD); 9087 9088 // If this is the first declaration of an extern C variable, update 9089 // the map of such variables. 9090 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9091 isIncompleteDeclExternC(*this, NewFD)) 9092 RegisterLocallyScopedExternCDecl(NewFD, S); 9093 9094 // Set this FunctionDecl's range up to the right paren. 9095 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9096 9097 if (D.isRedeclaration() && !Previous.empty()) { 9098 checkDLLAttributeRedeclaration( 9099 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9100 isMemberSpecialization || isFunctionTemplateSpecialization, 9101 D.isFunctionDefinition()); 9102 } 9103 9104 if (getLangOpts().CUDA) { 9105 IdentifierInfo *II = NewFD->getIdentifier(); 9106 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9107 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9108 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9109 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9110 9111 Context.setcudaConfigureCallDecl(NewFD); 9112 } 9113 9114 // Variadic functions, other than a *declaration* of printf, are not allowed 9115 // in device-side CUDA code, unless someone passed 9116 // -fcuda-allow-variadic-functions. 9117 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9118 (NewFD->hasAttr<CUDADeviceAttr>() || 9119 NewFD->hasAttr<CUDAGlobalAttr>()) && 9120 !(II && II->isStr("printf") && NewFD->isExternC() && 9121 !D.isFunctionDefinition())) { 9122 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9123 } 9124 } 9125 9126 MarkUnusedFileScopedDecl(NewFD); 9127 9128 if (getLangOpts().CPlusPlus) { 9129 if (FunctionTemplate) { 9130 if (NewFD->isInvalidDecl()) 9131 FunctionTemplate->setInvalidDecl(); 9132 return FunctionTemplate; 9133 } 9134 9135 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9136 CompleteMemberSpecialization(NewFD, Previous); 9137 } 9138 9139 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9140 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9141 if ((getLangOpts().OpenCLVersion >= 120) 9142 && (SC == SC_Static)) { 9143 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9144 D.setInvalidType(); 9145 } 9146 9147 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9148 if (!NewFD->getReturnType()->isVoidType()) { 9149 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9150 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9151 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9152 : FixItHint()); 9153 D.setInvalidType(); 9154 } 9155 9156 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9157 for (auto Param : NewFD->parameters()) 9158 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9159 } 9160 for (const ParmVarDecl *Param : NewFD->parameters()) { 9161 QualType PT = Param->getType(); 9162 9163 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9164 // types. 9165 if (getLangOpts().OpenCLVersion >= 200) { 9166 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9167 QualType ElemTy = PipeTy->getElementType(); 9168 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9169 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9170 D.setInvalidType(); 9171 } 9172 } 9173 } 9174 } 9175 9176 // Here we have an function template explicit specialization at class scope. 9177 // The actually specialization will be postponed to template instatiation 9178 // time via the ClassScopeFunctionSpecializationDecl node. 9179 if (isDependentClassScopeExplicitSpecialization) { 9180 ClassScopeFunctionSpecializationDecl *NewSpec = 9181 ClassScopeFunctionSpecializationDecl::Create( 9182 Context, CurContext, SourceLocation(), 9183 cast<CXXMethodDecl>(NewFD), 9184 HasExplicitTemplateArgs, TemplateArgs); 9185 CurContext->addDecl(NewSpec); 9186 AddToScope = false; 9187 } 9188 9189 return NewFD; 9190 } 9191 9192 /// \brief Checks if the new declaration declared in dependent context must be 9193 /// put in the same redeclaration chain as the specified declaration. 9194 /// 9195 /// \param D Declaration that is checked. 9196 /// \param PrevDecl Previous declaration found with proper lookup method for the 9197 /// same declaration name. 9198 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9199 /// belongs to. 9200 /// 9201 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9202 // Any declarations should be put into redeclaration chains except for 9203 // friend declaration in a dependent context that names a function in 9204 // namespace scope. 9205 // 9206 // This allows to compile code like: 9207 // 9208 // void func(); 9209 // template<typename T> class C1 { friend void func() { } }; 9210 // template<typename T> class C2 { friend void func() { } }; 9211 // 9212 // This code snippet is a valid code unless both templates are instantiated. 9213 return !(D->getLexicalDeclContext()->isDependentContext() && 9214 D->getDeclContext()->isFileContext() && 9215 D->getFriendObjectKind() != Decl::FOK_None); 9216 } 9217 9218 /// \brief Perform semantic checking of a new function declaration. 9219 /// 9220 /// Performs semantic analysis of the new function declaration 9221 /// NewFD. This routine performs all semantic checking that does not 9222 /// require the actual declarator involved in the declaration, and is 9223 /// used both for the declaration of functions as they are parsed 9224 /// (called via ActOnDeclarator) and for the declaration of functions 9225 /// that have been instantiated via C++ template instantiation (called 9226 /// via InstantiateDecl). 9227 /// 9228 /// \param IsMemberSpecialization whether this new function declaration is 9229 /// a member specialization (that replaces any definition provided by the 9230 /// previous declaration). 9231 /// 9232 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9233 /// 9234 /// \returns true if the function declaration is a redeclaration. 9235 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9236 LookupResult &Previous, 9237 bool IsMemberSpecialization) { 9238 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9239 "Variably modified return types are not handled here"); 9240 9241 // Determine whether the type of this function should be merged with 9242 // a previous visible declaration. This never happens for functions in C++, 9243 // and always happens in C if the previous declaration was visible. 9244 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9245 !Previous.isShadowed(); 9246 9247 bool Redeclaration = false; 9248 NamedDecl *OldDecl = nullptr; 9249 bool MayNeedOverloadableChecks = false; 9250 9251 // Merge or overload the declaration with an existing declaration of 9252 // the same name, if appropriate. 9253 if (!Previous.empty()) { 9254 // Determine whether NewFD is an overload of PrevDecl or 9255 // a declaration that requires merging. If it's an overload, 9256 // there's no more work to do here; we'll just add the new 9257 // function to the scope. 9258 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9259 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9260 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9261 Redeclaration = true; 9262 OldDecl = Candidate; 9263 } 9264 } else { 9265 MayNeedOverloadableChecks = true; 9266 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9267 /*NewIsUsingDecl*/ false)) { 9268 case Ovl_Match: 9269 Redeclaration = true; 9270 break; 9271 9272 case Ovl_NonFunction: 9273 Redeclaration = true; 9274 break; 9275 9276 case Ovl_Overload: 9277 Redeclaration = false; 9278 break; 9279 } 9280 } 9281 } 9282 9283 // Check for a previous extern "C" declaration with this name. 9284 if (!Redeclaration && 9285 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9286 if (!Previous.empty()) { 9287 // This is an extern "C" declaration with the same name as a previous 9288 // declaration, and thus redeclares that entity... 9289 Redeclaration = true; 9290 OldDecl = Previous.getFoundDecl(); 9291 MergeTypeWithPrevious = false; 9292 9293 // ... except in the presence of __attribute__((overloadable)). 9294 if (OldDecl->hasAttr<OverloadableAttr>() || 9295 NewFD->hasAttr<OverloadableAttr>()) { 9296 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9297 MayNeedOverloadableChecks = true; 9298 Redeclaration = false; 9299 OldDecl = nullptr; 9300 } 9301 } 9302 } 9303 } 9304 9305 // C++11 [dcl.constexpr]p8: 9306 // A constexpr specifier for a non-static member function that is not 9307 // a constructor declares that member function to be const. 9308 // 9309 // This needs to be delayed until we know whether this is an out-of-line 9310 // definition of a static member function. 9311 // 9312 // This rule is not present in C++1y, so we produce a backwards 9313 // compatibility warning whenever it happens in C++11. 9314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9315 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9316 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9317 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9318 CXXMethodDecl *OldMD = nullptr; 9319 if (OldDecl) 9320 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9321 if (!OldMD || !OldMD->isStatic()) { 9322 const FunctionProtoType *FPT = 9323 MD->getType()->castAs<FunctionProtoType>(); 9324 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9325 EPI.TypeQuals |= Qualifiers::Const; 9326 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9327 FPT->getParamTypes(), EPI)); 9328 9329 // Warn that we did this, if we're not performing template instantiation. 9330 // In that case, we'll have warned already when the template was defined. 9331 if (!inTemplateInstantiation()) { 9332 SourceLocation AddConstLoc; 9333 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9334 .IgnoreParens().getAs<FunctionTypeLoc>()) 9335 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9336 9337 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9338 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9339 } 9340 } 9341 } 9342 9343 if (Redeclaration) { 9344 // NewFD and OldDecl represent declarations that need to be 9345 // merged. 9346 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9347 NewFD->setInvalidDecl(); 9348 return Redeclaration; 9349 } 9350 9351 Previous.clear(); 9352 Previous.addDecl(OldDecl); 9353 9354 if (FunctionTemplateDecl *OldTemplateDecl 9355 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9356 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9357 FunctionTemplateDecl *NewTemplateDecl 9358 = NewFD->getDescribedFunctionTemplate(); 9359 assert(NewTemplateDecl && "Template/non-template mismatch"); 9360 if (CXXMethodDecl *Method 9361 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9362 Method->setAccess(OldTemplateDecl->getAccess()); 9363 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9364 } 9365 9366 // If this is an explicit specialization of a member that is a function 9367 // template, mark it as a member specialization. 9368 if (IsMemberSpecialization && 9369 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9370 NewTemplateDecl->setMemberSpecialization(); 9371 assert(OldTemplateDecl->isMemberSpecialization()); 9372 // Explicit specializations of a member template do not inherit deleted 9373 // status from the parent member template that they are specializing. 9374 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9375 FunctionDecl *const OldTemplatedDecl = 9376 OldTemplateDecl->getTemplatedDecl(); 9377 // FIXME: This assert will not hold in the presence of modules. 9378 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9379 // FIXME: We need an update record for this AST mutation. 9380 OldTemplatedDecl->setDeletedAsWritten(false); 9381 } 9382 } 9383 9384 } else { 9385 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9386 // This needs to happen first so that 'inline' propagates. 9387 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9388 if (isa<CXXMethodDecl>(NewFD)) 9389 NewFD->setAccess(OldDecl->getAccess()); 9390 } 9391 } 9392 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9393 !NewFD->getAttr<OverloadableAttr>()) { 9394 assert((Previous.empty() || 9395 llvm::any_of(Previous, 9396 [](const NamedDecl *ND) { 9397 return ND->hasAttr<OverloadableAttr>(); 9398 })) && 9399 "Non-redecls shouldn't happen without overloadable present"); 9400 9401 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9402 const auto *FD = dyn_cast<FunctionDecl>(ND); 9403 return FD && !FD->hasAttr<OverloadableAttr>(); 9404 }); 9405 9406 if (OtherUnmarkedIter != Previous.end()) { 9407 Diag(NewFD->getLocation(), 9408 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9409 Diag((*OtherUnmarkedIter)->getLocation(), 9410 diag::note_attribute_overloadable_prev_overload) 9411 << false; 9412 9413 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9414 } 9415 } 9416 9417 // Semantic checking for this function declaration (in isolation). 9418 9419 if (getLangOpts().CPlusPlus) { 9420 // C++-specific checks. 9421 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9422 CheckConstructor(Constructor); 9423 } else if (CXXDestructorDecl *Destructor = 9424 dyn_cast<CXXDestructorDecl>(NewFD)) { 9425 CXXRecordDecl *Record = Destructor->getParent(); 9426 QualType ClassType = Context.getTypeDeclType(Record); 9427 9428 // FIXME: Shouldn't we be able to perform this check even when the class 9429 // type is dependent? Both gcc and edg can handle that. 9430 if (!ClassType->isDependentType()) { 9431 DeclarationName Name 9432 = Context.DeclarationNames.getCXXDestructorName( 9433 Context.getCanonicalType(ClassType)); 9434 if (NewFD->getDeclName() != Name) { 9435 Diag(NewFD->getLocation(), diag::err_destructor_name); 9436 NewFD->setInvalidDecl(); 9437 return Redeclaration; 9438 } 9439 } 9440 } else if (CXXConversionDecl *Conversion 9441 = dyn_cast<CXXConversionDecl>(NewFD)) { 9442 ActOnConversionDeclarator(Conversion); 9443 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9444 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9445 CheckDeductionGuideTemplate(TD); 9446 9447 // A deduction guide is not on the list of entities that can be 9448 // explicitly specialized. 9449 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9450 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9451 << /*explicit specialization*/ 1; 9452 } 9453 9454 // Find any virtual functions that this function overrides. 9455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9456 if (!Method->isFunctionTemplateSpecialization() && 9457 !Method->getDescribedFunctionTemplate() && 9458 Method->isCanonicalDecl()) { 9459 if (AddOverriddenMethods(Method->getParent(), Method)) { 9460 // If the function was marked as "static", we have a problem. 9461 if (NewFD->getStorageClass() == SC_Static) { 9462 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9463 } 9464 } 9465 } 9466 9467 if (Method->isStatic()) 9468 checkThisInStaticMemberFunctionType(Method); 9469 } 9470 9471 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9472 if (NewFD->isOverloadedOperator() && 9473 CheckOverloadedOperatorDeclaration(NewFD)) { 9474 NewFD->setInvalidDecl(); 9475 return Redeclaration; 9476 } 9477 9478 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9479 if (NewFD->getLiteralIdentifier() && 9480 CheckLiteralOperatorDeclaration(NewFD)) { 9481 NewFD->setInvalidDecl(); 9482 return Redeclaration; 9483 } 9484 9485 // In C++, check default arguments now that we have merged decls. Unless 9486 // the lexical context is the class, because in this case this is done 9487 // during delayed parsing anyway. 9488 if (!CurContext->isRecord()) 9489 CheckCXXDefaultArguments(NewFD); 9490 9491 // If this function declares a builtin function, check the type of this 9492 // declaration against the expected type for the builtin. 9493 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9494 ASTContext::GetBuiltinTypeError Error; 9495 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9496 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9497 // If the type of the builtin differs only in its exception 9498 // specification, that's OK. 9499 // FIXME: If the types do differ in this way, it would be better to 9500 // retain the 'noexcept' form of the type. 9501 if (!T.isNull() && 9502 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9503 NewFD->getType())) 9504 // The type of this function differs from the type of the builtin, 9505 // so forget about the builtin entirely. 9506 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9507 } 9508 9509 // If this function is declared as being extern "C", then check to see if 9510 // the function returns a UDT (class, struct, or union type) that is not C 9511 // compatible, and if it does, warn the user. 9512 // But, issue any diagnostic on the first declaration only. 9513 if (Previous.empty() && NewFD->isExternC()) { 9514 QualType R = NewFD->getReturnType(); 9515 if (R->isIncompleteType() && !R->isVoidType()) 9516 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9517 << NewFD << R; 9518 else if (!R.isPODType(Context) && !R->isVoidType() && 9519 !R->isObjCObjectPointerType()) 9520 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9521 } 9522 9523 // C++1z [dcl.fct]p6: 9524 // [...] whether the function has a non-throwing exception-specification 9525 // [is] part of the function type 9526 // 9527 // This results in an ABI break between C++14 and C++17 for functions whose 9528 // declared type includes an exception-specification in a parameter or 9529 // return type. (Exception specifications on the function itself are OK in 9530 // most cases, and exception specifications are not permitted in most other 9531 // contexts where they could make it into a mangling.) 9532 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9533 auto HasNoexcept = [&](QualType T) -> bool { 9534 // Strip off declarator chunks that could be between us and a function 9535 // type. We don't need to look far, exception specifications are very 9536 // restricted prior to C++17. 9537 if (auto *RT = T->getAs<ReferenceType>()) 9538 T = RT->getPointeeType(); 9539 else if (T->isAnyPointerType()) 9540 T = T->getPointeeType(); 9541 else if (auto *MPT = T->getAs<MemberPointerType>()) 9542 T = MPT->getPointeeType(); 9543 if (auto *FPT = T->getAs<FunctionProtoType>()) 9544 if (FPT->isNothrow(Context)) 9545 return true; 9546 return false; 9547 }; 9548 9549 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9550 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9551 for (QualType T : FPT->param_types()) 9552 AnyNoexcept |= HasNoexcept(T); 9553 if (AnyNoexcept) 9554 Diag(NewFD->getLocation(), 9555 diag::warn_cxx1z_compat_exception_spec_in_signature) 9556 << NewFD; 9557 } 9558 9559 if (!Redeclaration && LangOpts.CUDA) 9560 checkCUDATargetOverload(NewFD, Previous); 9561 } 9562 return Redeclaration; 9563 } 9564 9565 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9566 // C++11 [basic.start.main]p3: 9567 // A program that [...] declares main to be inline, static or 9568 // constexpr is ill-formed. 9569 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9570 // appear in a declaration of main. 9571 // static main is not an error under C99, but we should warn about it. 9572 // We accept _Noreturn main as an extension. 9573 if (FD->getStorageClass() == SC_Static) 9574 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9575 ? diag::err_static_main : diag::warn_static_main) 9576 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9577 if (FD->isInlineSpecified()) 9578 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9579 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9580 if (DS.isNoreturnSpecified()) { 9581 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9582 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9583 Diag(NoreturnLoc, diag::ext_noreturn_main); 9584 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9585 << FixItHint::CreateRemoval(NoreturnRange); 9586 } 9587 if (FD->isConstexpr()) { 9588 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9589 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9590 FD->setConstexpr(false); 9591 } 9592 9593 if (getLangOpts().OpenCL) { 9594 Diag(FD->getLocation(), diag::err_opencl_no_main) 9595 << FD->hasAttr<OpenCLKernelAttr>(); 9596 FD->setInvalidDecl(); 9597 return; 9598 } 9599 9600 QualType T = FD->getType(); 9601 assert(T->isFunctionType() && "function decl is not of function type"); 9602 const FunctionType* FT = T->castAs<FunctionType>(); 9603 9604 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9605 // In C with GNU extensions we allow main() to have non-integer return 9606 // type, but we should warn about the extension, and we disable the 9607 // implicit-return-zero rule. 9608 9609 // GCC in C mode accepts qualified 'int'. 9610 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9611 FD->setHasImplicitReturnZero(true); 9612 else { 9613 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9614 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9615 if (RTRange.isValid()) 9616 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9617 << FixItHint::CreateReplacement(RTRange, "int"); 9618 } 9619 } else { 9620 // In C and C++, main magically returns 0 if you fall off the end; 9621 // set the flag which tells us that. 9622 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9623 9624 // All the standards say that main() should return 'int'. 9625 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9626 FD->setHasImplicitReturnZero(true); 9627 else { 9628 // Otherwise, this is just a flat-out error. 9629 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9630 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9631 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9632 : FixItHint()); 9633 FD->setInvalidDecl(true); 9634 } 9635 } 9636 9637 // Treat protoless main() as nullary. 9638 if (isa<FunctionNoProtoType>(FT)) return; 9639 9640 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9641 unsigned nparams = FTP->getNumParams(); 9642 assert(FD->getNumParams() == nparams); 9643 9644 bool HasExtraParameters = (nparams > 3); 9645 9646 if (FTP->isVariadic()) { 9647 Diag(FD->getLocation(), diag::ext_variadic_main); 9648 // FIXME: if we had information about the location of the ellipsis, we 9649 // could add a FixIt hint to remove it as a parameter. 9650 } 9651 9652 // Darwin passes an undocumented fourth argument of type char**. If 9653 // other platforms start sprouting these, the logic below will start 9654 // getting shifty. 9655 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9656 HasExtraParameters = false; 9657 9658 if (HasExtraParameters) { 9659 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9660 FD->setInvalidDecl(true); 9661 nparams = 3; 9662 } 9663 9664 // FIXME: a lot of the following diagnostics would be improved 9665 // if we had some location information about types. 9666 9667 QualType CharPP = 9668 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9669 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9670 9671 for (unsigned i = 0; i < nparams; ++i) { 9672 QualType AT = FTP->getParamType(i); 9673 9674 bool mismatch = true; 9675 9676 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9677 mismatch = false; 9678 else if (Expected[i] == CharPP) { 9679 // As an extension, the following forms are okay: 9680 // char const ** 9681 // char const * const * 9682 // char * const * 9683 9684 QualifierCollector qs; 9685 const PointerType* PT; 9686 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9687 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9688 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9689 Context.CharTy)) { 9690 qs.removeConst(); 9691 mismatch = !qs.empty(); 9692 } 9693 } 9694 9695 if (mismatch) { 9696 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9697 // TODO: suggest replacing given type with expected type 9698 FD->setInvalidDecl(true); 9699 } 9700 } 9701 9702 if (nparams == 1 && !FD->isInvalidDecl()) { 9703 Diag(FD->getLocation(), diag::warn_main_one_arg); 9704 } 9705 9706 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9707 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9708 FD->setInvalidDecl(); 9709 } 9710 } 9711 9712 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9713 QualType T = FD->getType(); 9714 assert(T->isFunctionType() && "function decl is not of function type"); 9715 const FunctionType *FT = T->castAs<FunctionType>(); 9716 9717 // Set an implicit return of 'zero' if the function can return some integral, 9718 // enumeration, pointer or nullptr type. 9719 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9720 FT->getReturnType()->isAnyPointerType() || 9721 FT->getReturnType()->isNullPtrType()) 9722 // DllMain is exempt because a return value of zero means it failed. 9723 if (FD->getName() != "DllMain") 9724 FD->setHasImplicitReturnZero(true); 9725 9726 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9727 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9728 FD->setInvalidDecl(); 9729 } 9730 } 9731 9732 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9733 // FIXME: Need strict checking. In C89, we need to check for 9734 // any assignment, increment, decrement, function-calls, or 9735 // commas outside of a sizeof. In C99, it's the same list, 9736 // except that the aforementioned are allowed in unevaluated 9737 // expressions. Everything else falls under the 9738 // "may accept other forms of constant expressions" exception. 9739 // (We never end up here for C++, so the constant expression 9740 // rules there don't matter.) 9741 const Expr *Culprit; 9742 if (Init->isConstantInitializer(Context, false, &Culprit)) 9743 return false; 9744 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9745 << Culprit->getSourceRange(); 9746 return true; 9747 } 9748 9749 namespace { 9750 // Visits an initialization expression to see if OrigDecl is evaluated in 9751 // its own initialization and throws a warning if it does. 9752 class SelfReferenceChecker 9753 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9754 Sema &S; 9755 Decl *OrigDecl; 9756 bool isRecordType; 9757 bool isPODType; 9758 bool isReferenceType; 9759 9760 bool isInitList; 9761 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9762 9763 public: 9764 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9765 9766 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9767 S(S), OrigDecl(OrigDecl) { 9768 isPODType = false; 9769 isRecordType = false; 9770 isReferenceType = false; 9771 isInitList = false; 9772 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9773 isPODType = VD->getType().isPODType(S.Context); 9774 isRecordType = VD->getType()->isRecordType(); 9775 isReferenceType = VD->getType()->isReferenceType(); 9776 } 9777 } 9778 9779 // For most expressions, just call the visitor. For initializer lists, 9780 // track the index of the field being initialized since fields are 9781 // initialized in order allowing use of previously initialized fields. 9782 void CheckExpr(Expr *E) { 9783 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9784 if (!InitList) { 9785 Visit(E); 9786 return; 9787 } 9788 9789 // Track and increment the index here. 9790 isInitList = true; 9791 InitFieldIndex.push_back(0); 9792 for (auto Child : InitList->children()) { 9793 CheckExpr(cast<Expr>(Child)); 9794 ++InitFieldIndex.back(); 9795 } 9796 InitFieldIndex.pop_back(); 9797 } 9798 9799 // Returns true if MemberExpr is checked and no further checking is needed. 9800 // Returns false if additional checking is required. 9801 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9802 llvm::SmallVector<FieldDecl*, 4> Fields; 9803 Expr *Base = E; 9804 bool ReferenceField = false; 9805 9806 // Get the field memebers used. 9807 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9808 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9809 if (!FD) 9810 return false; 9811 Fields.push_back(FD); 9812 if (FD->getType()->isReferenceType()) 9813 ReferenceField = true; 9814 Base = ME->getBase()->IgnoreParenImpCasts(); 9815 } 9816 9817 // Keep checking only if the base Decl is the same. 9818 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9819 if (!DRE || DRE->getDecl() != OrigDecl) 9820 return false; 9821 9822 // A reference field can be bound to an unininitialized field. 9823 if (CheckReference && !ReferenceField) 9824 return true; 9825 9826 // Convert FieldDecls to their index number. 9827 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9828 for (const FieldDecl *I : llvm::reverse(Fields)) 9829 UsedFieldIndex.push_back(I->getFieldIndex()); 9830 9831 // See if a warning is needed by checking the first difference in index 9832 // numbers. If field being used has index less than the field being 9833 // initialized, then the use is safe. 9834 for (auto UsedIter = UsedFieldIndex.begin(), 9835 UsedEnd = UsedFieldIndex.end(), 9836 OrigIter = InitFieldIndex.begin(), 9837 OrigEnd = InitFieldIndex.end(); 9838 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9839 if (*UsedIter < *OrigIter) 9840 return true; 9841 if (*UsedIter > *OrigIter) 9842 break; 9843 } 9844 9845 // TODO: Add a different warning which will print the field names. 9846 HandleDeclRefExpr(DRE); 9847 return true; 9848 } 9849 9850 // For most expressions, the cast is directly above the DeclRefExpr. 9851 // For conditional operators, the cast can be outside the conditional 9852 // operator if both expressions are DeclRefExpr's. 9853 void HandleValue(Expr *E) { 9854 E = E->IgnoreParens(); 9855 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9856 HandleDeclRefExpr(DRE); 9857 return; 9858 } 9859 9860 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9861 Visit(CO->getCond()); 9862 HandleValue(CO->getTrueExpr()); 9863 HandleValue(CO->getFalseExpr()); 9864 return; 9865 } 9866 9867 if (BinaryConditionalOperator *BCO = 9868 dyn_cast<BinaryConditionalOperator>(E)) { 9869 Visit(BCO->getCond()); 9870 HandleValue(BCO->getFalseExpr()); 9871 return; 9872 } 9873 9874 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9875 HandleValue(OVE->getSourceExpr()); 9876 return; 9877 } 9878 9879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9880 if (BO->getOpcode() == BO_Comma) { 9881 Visit(BO->getLHS()); 9882 HandleValue(BO->getRHS()); 9883 return; 9884 } 9885 } 9886 9887 if (isa<MemberExpr>(E)) { 9888 if (isInitList) { 9889 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9890 false /*CheckReference*/)) 9891 return; 9892 } 9893 9894 Expr *Base = E->IgnoreParenImpCasts(); 9895 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9896 // Check for static member variables and don't warn on them. 9897 if (!isa<FieldDecl>(ME->getMemberDecl())) 9898 return; 9899 Base = ME->getBase()->IgnoreParenImpCasts(); 9900 } 9901 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9902 HandleDeclRefExpr(DRE); 9903 return; 9904 } 9905 9906 Visit(E); 9907 } 9908 9909 // Reference types not handled in HandleValue are handled here since all 9910 // uses of references are bad, not just r-value uses. 9911 void VisitDeclRefExpr(DeclRefExpr *E) { 9912 if (isReferenceType) 9913 HandleDeclRefExpr(E); 9914 } 9915 9916 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9917 if (E->getCastKind() == CK_LValueToRValue) { 9918 HandleValue(E->getSubExpr()); 9919 return; 9920 } 9921 9922 Inherited::VisitImplicitCastExpr(E); 9923 } 9924 9925 void VisitMemberExpr(MemberExpr *E) { 9926 if (isInitList) { 9927 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9928 return; 9929 } 9930 9931 // Don't warn on arrays since they can be treated as pointers. 9932 if (E->getType()->canDecayToPointerType()) return; 9933 9934 // Warn when a non-static method call is followed by non-static member 9935 // field accesses, which is followed by a DeclRefExpr. 9936 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9937 bool Warn = (MD && !MD->isStatic()); 9938 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9939 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9940 if (!isa<FieldDecl>(ME->getMemberDecl())) 9941 Warn = false; 9942 Base = ME->getBase()->IgnoreParenImpCasts(); 9943 } 9944 9945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9946 if (Warn) 9947 HandleDeclRefExpr(DRE); 9948 return; 9949 } 9950 9951 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9952 // Visit that expression. 9953 Visit(Base); 9954 } 9955 9956 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9957 Expr *Callee = E->getCallee(); 9958 9959 if (isa<UnresolvedLookupExpr>(Callee)) 9960 return Inherited::VisitCXXOperatorCallExpr(E); 9961 9962 Visit(Callee); 9963 for (auto Arg: E->arguments()) 9964 HandleValue(Arg->IgnoreParenImpCasts()); 9965 } 9966 9967 void VisitUnaryOperator(UnaryOperator *E) { 9968 // For POD record types, addresses of its own members are well-defined. 9969 if (E->getOpcode() == UO_AddrOf && isRecordType && 9970 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9971 if (!isPODType) 9972 HandleValue(E->getSubExpr()); 9973 return; 9974 } 9975 9976 if (E->isIncrementDecrementOp()) { 9977 HandleValue(E->getSubExpr()); 9978 return; 9979 } 9980 9981 Inherited::VisitUnaryOperator(E); 9982 } 9983 9984 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9985 9986 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9987 if (E->getConstructor()->isCopyConstructor()) { 9988 Expr *ArgExpr = E->getArg(0); 9989 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9990 if (ILE->getNumInits() == 1) 9991 ArgExpr = ILE->getInit(0); 9992 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9993 if (ICE->getCastKind() == CK_NoOp) 9994 ArgExpr = ICE->getSubExpr(); 9995 HandleValue(ArgExpr); 9996 return; 9997 } 9998 Inherited::VisitCXXConstructExpr(E); 9999 } 10000 10001 void VisitCallExpr(CallExpr *E) { 10002 // Treat std::move as a use. 10003 if (E->getNumArgs() == 1) { 10004 if (FunctionDecl *FD = E->getDirectCallee()) { 10005 if (FD->isInStdNamespace() && FD->getIdentifier() && 10006 FD->getIdentifier()->isStr("move")) { 10007 HandleValue(E->getArg(0)); 10008 return; 10009 } 10010 } 10011 } 10012 10013 Inherited::VisitCallExpr(E); 10014 } 10015 10016 void VisitBinaryOperator(BinaryOperator *E) { 10017 if (E->isCompoundAssignmentOp()) { 10018 HandleValue(E->getLHS()); 10019 Visit(E->getRHS()); 10020 return; 10021 } 10022 10023 Inherited::VisitBinaryOperator(E); 10024 } 10025 10026 // A custom visitor for BinaryConditionalOperator is needed because the 10027 // regular visitor would check the condition and true expression separately 10028 // but both point to the same place giving duplicate diagnostics. 10029 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10030 Visit(E->getCond()); 10031 Visit(E->getFalseExpr()); 10032 } 10033 10034 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10035 Decl* ReferenceDecl = DRE->getDecl(); 10036 if (OrigDecl != ReferenceDecl) return; 10037 unsigned diag; 10038 if (isReferenceType) { 10039 diag = diag::warn_uninit_self_reference_in_reference_init; 10040 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10041 diag = diag::warn_static_self_reference_in_init; 10042 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10043 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10044 DRE->getDecl()->getType()->isRecordType()) { 10045 diag = diag::warn_uninit_self_reference_in_init; 10046 } else { 10047 // Local variables will be handled by the CFG analysis. 10048 return; 10049 } 10050 10051 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10052 S.PDiag(diag) 10053 << DRE->getNameInfo().getName() 10054 << OrigDecl->getLocation() 10055 << DRE->getSourceRange()); 10056 } 10057 }; 10058 10059 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10060 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10061 bool DirectInit) { 10062 // Parameters arguments are occassionially constructed with itself, 10063 // for instance, in recursive functions. Skip them. 10064 if (isa<ParmVarDecl>(OrigDecl)) 10065 return; 10066 10067 E = E->IgnoreParens(); 10068 10069 // Skip checking T a = a where T is not a record or reference type. 10070 // Doing so is a way to silence uninitialized warnings. 10071 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10072 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10073 if (ICE->getCastKind() == CK_LValueToRValue) 10074 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10075 if (DRE->getDecl() == OrigDecl) 10076 return; 10077 10078 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10079 } 10080 } // end anonymous namespace 10081 10082 namespace { 10083 // Simple wrapper to add the name of a variable or (if no variable is 10084 // available) a DeclarationName into a diagnostic. 10085 struct VarDeclOrName { 10086 VarDecl *VDecl; 10087 DeclarationName Name; 10088 10089 friend const Sema::SemaDiagnosticBuilder & 10090 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10091 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10092 } 10093 }; 10094 } // end anonymous namespace 10095 10096 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10097 DeclarationName Name, QualType Type, 10098 TypeSourceInfo *TSI, 10099 SourceRange Range, bool DirectInit, 10100 Expr *Init) { 10101 bool IsInitCapture = !VDecl; 10102 assert((!VDecl || !VDecl->isInitCapture()) && 10103 "init captures are expected to be deduced prior to initialization"); 10104 10105 VarDeclOrName VN{VDecl, Name}; 10106 10107 DeducedType *Deduced = Type->getContainedDeducedType(); 10108 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10109 10110 // C++11 [dcl.spec.auto]p3 10111 if (!Init) { 10112 assert(VDecl && "no init for init capture deduction?"); 10113 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10114 << VDecl->getDeclName() << Type; 10115 return QualType(); 10116 } 10117 10118 ArrayRef<Expr*> DeduceInits = Init; 10119 if (DirectInit) { 10120 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10121 DeduceInits = PL->exprs(); 10122 } 10123 10124 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10125 assert(VDecl && "non-auto type for init capture deduction?"); 10126 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10127 InitializationKind Kind = InitializationKind::CreateForInit( 10128 VDecl->getLocation(), DirectInit, Init); 10129 // FIXME: Initialization should not be taking a mutable list of inits. 10130 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10131 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10132 InitsCopy); 10133 } 10134 10135 if (DirectInit) { 10136 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10137 DeduceInits = IL->inits(); 10138 } 10139 10140 // Deduction only works if we have exactly one source expression. 10141 if (DeduceInits.empty()) { 10142 // It isn't possible to write this directly, but it is possible to 10143 // end up in this situation with "auto x(some_pack...);" 10144 Diag(Init->getLocStart(), IsInitCapture 10145 ? diag::err_init_capture_no_expression 10146 : diag::err_auto_var_init_no_expression) 10147 << VN << Type << Range; 10148 return QualType(); 10149 } 10150 10151 if (DeduceInits.size() > 1) { 10152 Diag(DeduceInits[1]->getLocStart(), 10153 IsInitCapture ? diag::err_init_capture_multiple_expressions 10154 : diag::err_auto_var_init_multiple_expressions) 10155 << VN << Type << Range; 10156 return QualType(); 10157 } 10158 10159 Expr *DeduceInit = DeduceInits[0]; 10160 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10161 Diag(Init->getLocStart(), IsInitCapture 10162 ? diag::err_init_capture_paren_braces 10163 : diag::err_auto_var_init_paren_braces) 10164 << isa<InitListExpr>(Init) << VN << Type << Range; 10165 return QualType(); 10166 } 10167 10168 // Expressions default to 'id' when we're in a debugger. 10169 bool DefaultedAnyToId = false; 10170 if (getLangOpts().DebuggerCastResultToId && 10171 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10172 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10173 if (Result.isInvalid()) { 10174 return QualType(); 10175 } 10176 Init = Result.get(); 10177 DefaultedAnyToId = true; 10178 } 10179 10180 // C++ [dcl.decomp]p1: 10181 // If the assignment-expression [...] has array type A and no ref-qualifier 10182 // is present, e has type cv A 10183 if (VDecl && isa<DecompositionDecl>(VDecl) && 10184 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10185 DeduceInit->getType()->isConstantArrayType()) 10186 return Context.getQualifiedType(DeduceInit->getType(), 10187 Type.getQualifiers()); 10188 10189 QualType DeducedType; 10190 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10191 if (!IsInitCapture) 10192 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10193 else if (isa<InitListExpr>(Init)) 10194 Diag(Range.getBegin(), 10195 diag::err_init_capture_deduction_failure_from_init_list) 10196 << VN 10197 << (DeduceInit->getType().isNull() ? TSI->getType() 10198 : DeduceInit->getType()) 10199 << DeduceInit->getSourceRange(); 10200 else 10201 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10202 << VN << TSI->getType() 10203 << (DeduceInit->getType().isNull() ? TSI->getType() 10204 : DeduceInit->getType()) 10205 << DeduceInit->getSourceRange(); 10206 } 10207 10208 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10209 // 'id' instead of a specific object type prevents most of our usual 10210 // checks. 10211 // We only want to warn outside of template instantiations, though: 10212 // inside a template, the 'id' could have come from a parameter. 10213 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10214 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10215 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10216 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10217 } 10218 10219 return DeducedType; 10220 } 10221 10222 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10223 Expr *Init) { 10224 QualType DeducedType = deduceVarTypeFromInitializer( 10225 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10226 VDecl->getSourceRange(), DirectInit, Init); 10227 if (DeducedType.isNull()) { 10228 VDecl->setInvalidDecl(); 10229 return true; 10230 } 10231 10232 VDecl->setType(DeducedType); 10233 assert(VDecl->isLinkageValid()); 10234 10235 // In ARC, infer lifetime. 10236 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10237 VDecl->setInvalidDecl(); 10238 10239 // If this is a redeclaration, check that the type we just deduced matches 10240 // the previously declared type. 10241 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10242 // We never need to merge the type, because we cannot form an incomplete 10243 // array of auto, nor deduce such a type. 10244 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10245 } 10246 10247 // Check the deduced type is valid for a variable declaration. 10248 CheckVariableDeclarationType(VDecl); 10249 return VDecl->isInvalidDecl(); 10250 } 10251 10252 /// AddInitializerToDecl - Adds the initializer Init to the 10253 /// declaration dcl. If DirectInit is true, this is C++ direct 10254 /// initialization rather than copy initialization. 10255 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10256 // If there is no declaration, there was an error parsing it. Just ignore 10257 // the initializer. 10258 if (!RealDecl || RealDecl->isInvalidDecl()) { 10259 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10260 return; 10261 } 10262 10263 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10264 // Pure-specifiers are handled in ActOnPureSpecifier. 10265 Diag(Method->getLocation(), diag::err_member_function_initialization) 10266 << Method->getDeclName() << Init->getSourceRange(); 10267 Method->setInvalidDecl(); 10268 return; 10269 } 10270 10271 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10272 if (!VDecl) { 10273 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10274 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10275 RealDecl->setInvalidDecl(); 10276 return; 10277 } 10278 10279 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10280 if (VDecl->getType()->isUndeducedType()) { 10281 // Attempt typo correction early so that the type of the init expression can 10282 // be deduced based on the chosen correction if the original init contains a 10283 // TypoExpr. 10284 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10285 if (!Res.isUsable()) { 10286 RealDecl->setInvalidDecl(); 10287 return; 10288 } 10289 Init = Res.get(); 10290 10291 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10292 return; 10293 } 10294 10295 // dllimport cannot be used on variable definitions. 10296 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10297 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10298 VDecl->setInvalidDecl(); 10299 return; 10300 } 10301 10302 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10303 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10304 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10305 VDecl->setInvalidDecl(); 10306 return; 10307 } 10308 10309 if (!VDecl->getType()->isDependentType()) { 10310 // A definition must end up with a complete type, which means it must be 10311 // complete with the restriction that an array type might be completed by 10312 // the initializer; note that later code assumes this restriction. 10313 QualType BaseDeclType = VDecl->getType(); 10314 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10315 BaseDeclType = Array->getElementType(); 10316 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10317 diag::err_typecheck_decl_incomplete_type)) { 10318 RealDecl->setInvalidDecl(); 10319 return; 10320 } 10321 10322 // The variable can not have an abstract class type. 10323 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10324 diag::err_abstract_type_in_decl, 10325 AbstractVariableType)) 10326 VDecl->setInvalidDecl(); 10327 } 10328 10329 // If adding the initializer will turn this declaration into a definition, 10330 // and we already have a definition for this variable, diagnose or otherwise 10331 // handle the situation. 10332 VarDecl *Def; 10333 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10334 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10335 !VDecl->isThisDeclarationADemotedDefinition() && 10336 checkVarDeclRedefinition(Def, VDecl)) 10337 return; 10338 10339 if (getLangOpts().CPlusPlus) { 10340 // C++ [class.static.data]p4 10341 // If a static data member is of const integral or const 10342 // enumeration type, its declaration in the class definition can 10343 // specify a constant-initializer which shall be an integral 10344 // constant expression (5.19). In that case, the member can appear 10345 // in integral constant expressions. The member shall still be 10346 // defined in a namespace scope if it is used in the program and the 10347 // namespace scope definition shall not contain an initializer. 10348 // 10349 // We already performed a redefinition check above, but for static 10350 // data members we also need to check whether there was an in-class 10351 // declaration with an initializer. 10352 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10353 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10354 << VDecl->getDeclName(); 10355 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10356 diag::note_previous_initializer) 10357 << 0; 10358 return; 10359 } 10360 10361 if (VDecl->hasLocalStorage()) 10362 getCurFunction()->setHasBranchProtectedScope(); 10363 10364 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10365 VDecl->setInvalidDecl(); 10366 return; 10367 } 10368 } 10369 10370 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10371 // a kernel function cannot be initialized." 10372 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10373 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10374 VDecl->setInvalidDecl(); 10375 return; 10376 } 10377 10378 // Get the decls type and save a reference for later, since 10379 // CheckInitializerTypes may change it. 10380 QualType DclT = VDecl->getType(), SavT = DclT; 10381 10382 // Expressions default to 'id' when we're in a debugger 10383 // and we are assigning it to a variable of Objective-C pointer type. 10384 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10385 Init->getType() == Context.UnknownAnyTy) { 10386 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10387 if (Result.isInvalid()) { 10388 VDecl->setInvalidDecl(); 10389 return; 10390 } 10391 Init = Result.get(); 10392 } 10393 10394 // Perform the initialization. 10395 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10396 if (!VDecl->isInvalidDecl()) { 10397 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10398 InitializationKind Kind = InitializationKind::CreateForInit( 10399 VDecl->getLocation(), DirectInit, Init); 10400 10401 MultiExprArg Args = Init; 10402 if (CXXDirectInit) 10403 Args = MultiExprArg(CXXDirectInit->getExprs(), 10404 CXXDirectInit->getNumExprs()); 10405 10406 // Try to correct any TypoExprs in the initialization arguments. 10407 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10408 ExprResult Res = CorrectDelayedTyposInExpr( 10409 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10410 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10411 return Init.Failed() ? ExprError() : E; 10412 }); 10413 if (Res.isInvalid()) { 10414 VDecl->setInvalidDecl(); 10415 } else if (Res.get() != Args[Idx]) { 10416 Args[Idx] = Res.get(); 10417 } 10418 } 10419 if (VDecl->isInvalidDecl()) 10420 return; 10421 10422 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10423 /*TopLevelOfInitList=*/false, 10424 /*TreatUnavailableAsInvalid=*/false); 10425 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10426 if (Result.isInvalid()) { 10427 VDecl->setInvalidDecl(); 10428 return; 10429 } 10430 10431 Init = Result.getAs<Expr>(); 10432 } 10433 10434 // Check for self-references within variable initializers. 10435 // Variables declared within a function/method body (except for references) 10436 // are handled by a dataflow analysis. 10437 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10438 VDecl->getType()->isReferenceType()) { 10439 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10440 } 10441 10442 // If the type changed, it means we had an incomplete type that was 10443 // completed by the initializer. For example: 10444 // int ary[] = { 1, 3, 5 }; 10445 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10446 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10447 VDecl->setType(DclT); 10448 10449 if (!VDecl->isInvalidDecl()) { 10450 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10451 10452 if (VDecl->hasAttr<BlocksAttr>()) 10453 checkRetainCycles(VDecl, Init); 10454 10455 // It is safe to assign a weak reference into a strong variable. 10456 // Although this code can still have problems: 10457 // id x = self.weakProp; 10458 // id y = self.weakProp; 10459 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10460 // paths through the function. This should be revisited if 10461 // -Wrepeated-use-of-weak is made flow-sensitive. 10462 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10463 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10464 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10465 Init->getLocStart())) 10466 getCurFunction()->markSafeWeakUse(Init); 10467 } 10468 10469 // The initialization is usually a full-expression. 10470 // 10471 // FIXME: If this is a braced initialization of an aggregate, it is not 10472 // an expression, and each individual field initializer is a separate 10473 // full-expression. For instance, in: 10474 // 10475 // struct Temp { ~Temp(); }; 10476 // struct S { S(Temp); }; 10477 // struct T { S a, b; } t = { Temp(), Temp() } 10478 // 10479 // we should destroy the first Temp before constructing the second. 10480 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10481 false, 10482 VDecl->isConstexpr()); 10483 if (Result.isInvalid()) { 10484 VDecl->setInvalidDecl(); 10485 return; 10486 } 10487 Init = Result.get(); 10488 10489 // Attach the initializer to the decl. 10490 VDecl->setInit(Init); 10491 10492 if (VDecl->isLocalVarDecl()) { 10493 // Don't check the initializer if the declaration is malformed. 10494 if (VDecl->isInvalidDecl()) { 10495 // do nothing 10496 10497 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10498 // This is true even in OpenCL C++. 10499 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10500 CheckForConstantInitializer(Init, DclT); 10501 10502 // Otherwise, C++ does not restrict the initializer. 10503 } else if (getLangOpts().CPlusPlus) { 10504 // do nothing 10505 10506 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10507 // static storage duration shall be constant expressions or string literals. 10508 } else if (VDecl->getStorageClass() == SC_Static) { 10509 CheckForConstantInitializer(Init, DclT); 10510 10511 // C89 is stricter than C99 for aggregate initializers. 10512 // C89 6.5.7p3: All the expressions [...] in an initializer list 10513 // for an object that has aggregate or union type shall be 10514 // constant expressions. 10515 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10516 isa<InitListExpr>(Init)) { 10517 const Expr *Culprit; 10518 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10519 Diag(Culprit->getExprLoc(), 10520 diag::ext_aggregate_init_not_constant) 10521 << Culprit->getSourceRange(); 10522 } 10523 } 10524 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10525 VDecl->getLexicalDeclContext()->isRecord()) { 10526 // This is an in-class initialization for a static data member, e.g., 10527 // 10528 // struct S { 10529 // static const int value = 17; 10530 // }; 10531 10532 // C++ [class.mem]p4: 10533 // A member-declarator can contain a constant-initializer only 10534 // if it declares a static member (9.4) of const integral or 10535 // const enumeration type, see 9.4.2. 10536 // 10537 // C++11 [class.static.data]p3: 10538 // If a non-volatile non-inline const static data member is of integral 10539 // or enumeration type, its declaration in the class definition can 10540 // specify a brace-or-equal-initializer in which every initializer-clause 10541 // that is an assignment-expression is a constant expression. A static 10542 // data member of literal type can be declared in the class definition 10543 // with the constexpr specifier; if so, its declaration shall specify a 10544 // brace-or-equal-initializer in which every initializer-clause that is 10545 // an assignment-expression is a constant expression. 10546 10547 // Do nothing on dependent types. 10548 if (DclT->isDependentType()) { 10549 10550 // Allow any 'static constexpr' members, whether or not they are of literal 10551 // type. We separately check that every constexpr variable is of literal 10552 // type. 10553 } else if (VDecl->isConstexpr()) { 10554 10555 // Require constness. 10556 } else if (!DclT.isConstQualified()) { 10557 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10558 << Init->getSourceRange(); 10559 VDecl->setInvalidDecl(); 10560 10561 // We allow integer constant expressions in all cases. 10562 } else if (DclT->isIntegralOrEnumerationType()) { 10563 // Check whether the expression is a constant expression. 10564 SourceLocation Loc; 10565 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10566 // In C++11, a non-constexpr const static data member with an 10567 // in-class initializer cannot be volatile. 10568 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10569 else if (Init->isValueDependent()) 10570 ; // Nothing to check. 10571 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10572 ; // Ok, it's an ICE! 10573 else if (Init->isEvaluatable(Context)) { 10574 // If we can constant fold the initializer through heroics, accept it, 10575 // but report this as a use of an extension for -pedantic. 10576 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10577 << Init->getSourceRange(); 10578 } else { 10579 // Otherwise, this is some crazy unknown case. Report the issue at the 10580 // location provided by the isIntegerConstantExpr failed check. 10581 Diag(Loc, diag::err_in_class_initializer_non_constant) 10582 << Init->getSourceRange(); 10583 VDecl->setInvalidDecl(); 10584 } 10585 10586 // We allow foldable floating-point constants as an extension. 10587 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10588 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10589 // it anyway and provide a fixit to add the 'constexpr'. 10590 if (getLangOpts().CPlusPlus11) { 10591 Diag(VDecl->getLocation(), 10592 diag::ext_in_class_initializer_float_type_cxx11) 10593 << DclT << Init->getSourceRange(); 10594 Diag(VDecl->getLocStart(), 10595 diag::note_in_class_initializer_float_type_cxx11) 10596 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10597 } else { 10598 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10599 << DclT << Init->getSourceRange(); 10600 10601 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10602 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10603 << Init->getSourceRange(); 10604 VDecl->setInvalidDecl(); 10605 } 10606 } 10607 10608 // Suggest adding 'constexpr' in C++11 for literal types. 10609 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10610 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10611 << DclT << Init->getSourceRange() 10612 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10613 VDecl->setConstexpr(true); 10614 10615 } else { 10616 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10617 << DclT << Init->getSourceRange(); 10618 VDecl->setInvalidDecl(); 10619 } 10620 } else if (VDecl->isFileVarDecl()) { 10621 // In C, extern is typically used to avoid tentative definitions when 10622 // declaring variables in headers, but adding an intializer makes it a 10623 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10624 // In C++, extern is often used to give implictly static const variables 10625 // external linkage, so don't warn in that case. If selectany is present, 10626 // this might be header code intended for C and C++ inclusion, so apply the 10627 // C++ rules. 10628 if (VDecl->getStorageClass() == SC_Extern && 10629 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10630 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10631 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10632 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10633 Diag(VDecl->getLocation(), diag::warn_extern_init); 10634 10635 // C99 6.7.8p4. All file scoped initializers need to be constant. 10636 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10637 CheckForConstantInitializer(Init, DclT); 10638 } 10639 10640 // We will represent direct-initialization similarly to copy-initialization: 10641 // int x(1); -as-> int x = 1; 10642 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10643 // 10644 // Clients that want to distinguish between the two forms, can check for 10645 // direct initializer using VarDecl::getInitStyle(). 10646 // A major benefit is that clients that don't particularly care about which 10647 // exactly form was it (like the CodeGen) can handle both cases without 10648 // special case code. 10649 10650 // C++ 8.5p11: 10651 // The form of initialization (using parentheses or '=') is generally 10652 // insignificant, but does matter when the entity being initialized has a 10653 // class type. 10654 if (CXXDirectInit) { 10655 assert(DirectInit && "Call-style initializer must be direct init."); 10656 VDecl->setInitStyle(VarDecl::CallInit); 10657 } else if (DirectInit) { 10658 // This must be list-initialization. No other way is direct-initialization. 10659 VDecl->setInitStyle(VarDecl::ListInit); 10660 } 10661 10662 CheckCompleteVariableDeclaration(VDecl); 10663 } 10664 10665 /// ActOnInitializerError - Given that there was an error parsing an 10666 /// initializer for the given declaration, try to return to some form 10667 /// of sanity. 10668 void Sema::ActOnInitializerError(Decl *D) { 10669 // Our main concern here is re-establishing invariants like "a 10670 // variable's type is either dependent or complete". 10671 if (!D || D->isInvalidDecl()) return; 10672 10673 VarDecl *VD = dyn_cast<VarDecl>(D); 10674 if (!VD) return; 10675 10676 // Bindings are not usable if we can't make sense of the initializer. 10677 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10678 for (auto *BD : DD->bindings()) 10679 BD->setInvalidDecl(); 10680 10681 // Auto types are meaningless if we can't make sense of the initializer. 10682 if (ParsingInitForAutoVars.count(D)) { 10683 D->setInvalidDecl(); 10684 return; 10685 } 10686 10687 QualType Ty = VD->getType(); 10688 if (Ty->isDependentType()) return; 10689 10690 // Require a complete type. 10691 if (RequireCompleteType(VD->getLocation(), 10692 Context.getBaseElementType(Ty), 10693 diag::err_typecheck_decl_incomplete_type)) { 10694 VD->setInvalidDecl(); 10695 return; 10696 } 10697 10698 // Require a non-abstract type. 10699 if (RequireNonAbstractType(VD->getLocation(), Ty, 10700 diag::err_abstract_type_in_decl, 10701 AbstractVariableType)) { 10702 VD->setInvalidDecl(); 10703 return; 10704 } 10705 10706 // Don't bother complaining about constructors or destructors, 10707 // though. 10708 } 10709 10710 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10711 // If there is no declaration, there was an error parsing it. Just ignore it. 10712 if (!RealDecl) 10713 return; 10714 10715 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10716 QualType Type = Var->getType(); 10717 10718 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10719 if (isa<DecompositionDecl>(RealDecl)) { 10720 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10721 Var->setInvalidDecl(); 10722 return; 10723 } 10724 10725 if (Type->isUndeducedType() && 10726 DeduceVariableDeclarationType(Var, false, nullptr)) 10727 return; 10728 10729 // C++11 [class.static.data]p3: A static data member can be declared with 10730 // the constexpr specifier; if so, its declaration shall specify 10731 // a brace-or-equal-initializer. 10732 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10733 // the definition of a variable [...] or the declaration of a static data 10734 // member. 10735 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10736 !Var->isThisDeclarationADemotedDefinition()) { 10737 if (Var->isStaticDataMember()) { 10738 // C++1z removes the relevant rule; the in-class declaration is always 10739 // a definition there. 10740 if (!getLangOpts().CPlusPlus1z) { 10741 Diag(Var->getLocation(), 10742 diag::err_constexpr_static_mem_var_requires_init) 10743 << Var->getDeclName(); 10744 Var->setInvalidDecl(); 10745 return; 10746 } 10747 } else { 10748 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10749 Var->setInvalidDecl(); 10750 return; 10751 } 10752 } 10753 10754 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10755 // definition having the concept specifier is called a variable concept. A 10756 // concept definition refers to [...] a variable concept and its initializer. 10757 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10758 if (VTD->isConcept()) { 10759 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10760 Var->setInvalidDecl(); 10761 return; 10762 } 10763 } 10764 10765 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10766 // be initialized. 10767 if (!Var->isInvalidDecl() && 10768 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10769 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10770 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10771 Var->setInvalidDecl(); 10772 return; 10773 } 10774 10775 switch (Var->isThisDeclarationADefinition()) { 10776 case VarDecl::Definition: 10777 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10778 break; 10779 10780 // We have an out-of-line definition of a static data member 10781 // that has an in-class initializer, so we type-check this like 10782 // a declaration. 10783 // 10784 // Fall through 10785 10786 case VarDecl::DeclarationOnly: 10787 // It's only a declaration. 10788 10789 // Block scope. C99 6.7p7: If an identifier for an object is 10790 // declared with no linkage (C99 6.2.2p6), the type for the 10791 // object shall be complete. 10792 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10793 !Var->hasLinkage() && !Var->isInvalidDecl() && 10794 RequireCompleteType(Var->getLocation(), Type, 10795 diag::err_typecheck_decl_incomplete_type)) 10796 Var->setInvalidDecl(); 10797 10798 // Make sure that the type is not abstract. 10799 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10800 RequireNonAbstractType(Var->getLocation(), Type, 10801 diag::err_abstract_type_in_decl, 10802 AbstractVariableType)) 10803 Var->setInvalidDecl(); 10804 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10805 Var->getStorageClass() == SC_PrivateExtern) { 10806 Diag(Var->getLocation(), diag::warn_private_extern); 10807 Diag(Var->getLocation(), diag::note_private_extern); 10808 } 10809 10810 return; 10811 10812 case VarDecl::TentativeDefinition: 10813 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10814 // object that has file scope without an initializer, and without a 10815 // storage-class specifier or with the storage-class specifier "static", 10816 // constitutes a tentative definition. Note: A tentative definition with 10817 // external linkage is valid (C99 6.2.2p5). 10818 if (!Var->isInvalidDecl()) { 10819 if (const IncompleteArrayType *ArrayT 10820 = Context.getAsIncompleteArrayType(Type)) { 10821 if (RequireCompleteType(Var->getLocation(), 10822 ArrayT->getElementType(), 10823 diag::err_illegal_decl_array_incomplete_type)) 10824 Var->setInvalidDecl(); 10825 } else if (Var->getStorageClass() == SC_Static) { 10826 // C99 6.9.2p3: If the declaration of an identifier for an object is 10827 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10828 // declared type shall not be an incomplete type. 10829 // NOTE: code such as the following 10830 // static struct s; 10831 // struct s { int a; }; 10832 // is accepted by gcc. Hence here we issue a warning instead of 10833 // an error and we do not invalidate the static declaration. 10834 // NOTE: to avoid multiple warnings, only check the first declaration. 10835 if (Var->isFirstDecl()) 10836 RequireCompleteType(Var->getLocation(), Type, 10837 diag::ext_typecheck_decl_incomplete_type); 10838 } 10839 } 10840 10841 // Record the tentative definition; we're done. 10842 if (!Var->isInvalidDecl()) 10843 TentativeDefinitions.push_back(Var); 10844 return; 10845 } 10846 10847 // Provide a specific diagnostic for uninitialized variable 10848 // definitions with incomplete array type. 10849 if (Type->isIncompleteArrayType()) { 10850 Diag(Var->getLocation(), 10851 diag::err_typecheck_incomplete_array_needs_initializer); 10852 Var->setInvalidDecl(); 10853 return; 10854 } 10855 10856 // Provide a specific diagnostic for uninitialized variable 10857 // definitions with reference type. 10858 if (Type->isReferenceType()) { 10859 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10860 << Var->getDeclName() 10861 << SourceRange(Var->getLocation(), Var->getLocation()); 10862 Var->setInvalidDecl(); 10863 return; 10864 } 10865 10866 // Do not attempt to type-check the default initializer for a 10867 // variable with dependent type. 10868 if (Type->isDependentType()) 10869 return; 10870 10871 if (Var->isInvalidDecl()) 10872 return; 10873 10874 if (!Var->hasAttr<AliasAttr>()) { 10875 if (RequireCompleteType(Var->getLocation(), 10876 Context.getBaseElementType(Type), 10877 diag::err_typecheck_decl_incomplete_type)) { 10878 Var->setInvalidDecl(); 10879 return; 10880 } 10881 } else { 10882 return; 10883 } 10884 10885 // The variable can not have an abstract class type. 10886 if (RequireNonAbstractType(Var->getLocation(), Type, 10887 diag::err_abstract_type_in_decl, 10888 AbstractVariableType)) { 10889 Var->setInvalidDecl(); 10890 return; 10891 } 10892 10893 // Check for jumps past the implicit initializer. C++0x 10894 // clarifies that this applies to a "variable with automatic 10895 // storage duration", not a "local variable". 10896 // C++11 [stmt.dcl]p3 10897 // A program that jumps from a point where a variable with automatic 10898 // storage duration is not in scope to a point where it is in scope is 10899 // ill-formed unless the variable has scalar type, class type with a 10900 // trivial default constructor and a trivial destructor, a cv-qualified 10901 // version of one of these types, or an array of one of the preceding 10902 // types and is declared without an initializer. 10903 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10904 if (const RecordType *Record 10905 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10906 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10907 // Mark the function for further checking even if the looser rules of 10908 // C++11 do not require such checks, so that we can diagnose 10909 // incompatibilities with C++98. 10910 if (!CXXRecord->isPOD()) 10911 getCurFunction()->setHasBranchProtectedScope(); 10912 } 10913 } 10914 10915 // C++03 [dcl.init]p9: 10916 // If no initializer is specified for an object, and the 10917 // object is of (possibly cv-qualified) non-POD class type (or 10918 // array thereof), the object shall be default-initialized; if 10919 // the object is of const-qualified type, the underlying class 10920 // type shall have a user-declared default 10921 // constructor. Otherwise, if no initializer is specified for 10922 // a non- static object, the object and its subobjects, if 10923 // any, have an indeterminate initial value); if the object 10924 // or any of its subobjects are of const-qualified type, the 10925 // program is ill-formed. 10926 // C++0x [dcl.init]p11: 10927 // If no initializer is specified for an object, the object is 10928 // default-initialized; [...]. 10929 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10930 InitializationKind Kind 10931 = InitializationKind::CreateDefault(Var->getLocation()); 10932 10933 InitializationSequence InitSeq(*this, Entity, Kind, None); 10934 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10935 if (Init.isInvalid()) 10936 Var->setInvalidDecl(); 10937 else if (Init.get()) { 10938 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10939 // This is important for template substitution. 10940 Var->setInitStyle(VarDecl::CallInit); 10941 } 10942 10943 CheckCompleteVariableDeclaration(Var); 10944 } 10945 } 10946 10947 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10948 // If there is no declaration, there was an error parsing it. Ignore it. 10949 if (!D) 10950 return; 10951 10952 VarDecl *VD = dyn_cast<VarDecl>(D); 10953 if (!VD) { 10954 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10955 D->setInvalidDecl(); 10956 return; 10957 } 10958 10959 VD->setCXXForRangeDecl(true); 10960 10961 // for-range-declaration cannot be given a storage class specifier. 10962 int Error = -1; 10963 switch (VD->getStorageClass()) { 10964 case SC_None: 10965 break; 10966 case SC_Extern: 10967 Error = 0; 10968 break; 10969 case SC_Static: 10970 Error = 1; 10971 break; 10972 case SC_PrivateExtern: 10973 Error = 2; 10974 break; 10975 case SC_Auto: 10976 Error = 3; 10977 break; 10978 case SC_Register: 10979 Error = 4; 10980 break; 10981 } 10982 if (Error != -1) { 10983 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10984 << VD->getDeclName() << Error; 10985 D->setInvalidDecl(); 10986 } 10987 } 10988 10989 StmtResult 10990 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10991 IdentifierInfo *Ident, 10992 ParsedAttributes &Attrs, 10993 SourceLocation AttrEnd) { 10994 // C++1y [stmt.iter]p1: 10995 // A range-based for statement of the form 10996 // for ( for-range-identifier : for-range-initializer ) statement 10997 // is equivalent to 10998 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10999 DeclSpec DS(Attrs.getPool().getFactory()); 11000 11001 const char *PrevSpec; 11002 unsigned DiagID; 11003 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11004 getPrintingPolicy()); 11005 11006 Declarator D(DS, Declarator::ForContext); 11007 D.SetIdentifier(Ident, IdentLoc); 11008 D.takeAttributes(Attrs, AttrEnd); 11009 11010 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11011 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11012 EmptyAttrs, IdentLoc); 11013 Decl *Var = ActOnDeclarator(S, D); 11014 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11015 FinalizeDeclaration(Var); 11016 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11017 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11018 } 11019 11020 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11021 if (var->isInvalidDecl()) return; 11022 11023 if (getLangOpts().OpenCL) { 11024 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11025 // initialiser 11026 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11027 !var->hasInit()) { 11028 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11029 << 1 /*Init*/; 11030 var->setInvalidDecl(); 11031 return; 11032 } 11033 } 11034 11035 // In Objective-C, don't allow jumps past the implicit initialization of a 11036 // local retaining variable. 11037 if (getLangOpts().ObjC1 && 11038 var->hasLocalStorage()) { 11039 switch (var->getType().getObjCLifetime()) { 11040 case Qualifiers::OCL_None: 11041 case Qualifiers::OCL_ExplicitNone: 11042 case Qualifiers::OCL_Autoreleasing: 11043 break; 11044 11045 case Qualifiers::OCL_Weak: 11046 case Qualifiers::OCL_Strong: 11047 getCurFunction()->setHasBranchProtectedScope(); 11048 break; 11049 } 11050 } 11051 11052 // Warn about externally-visible variables being defined without a 11053 // prior declaration. We only want to do this for global 11054 // declarations, but we also specifically need to avoid doing it for 11055 // class members because the linkage of an anonymous class can 11056 // change if it's later given a typedef name. 11057 if (var->isThisDeclarationADefinition() && 11058 var->getDeclContext()->getRedeclContext()->isFileContext() && 11059 var->isExternallyVisible() && var->hasLinkage() && 11060 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11061 var->getLocation())) { 11062 // Find a previous declaration that's not a definition. 11063 VarDecl *prev = var->getPreviousDecl(); 11064 while (prev && prev->isThisDeclarationADefinition()) 11065 prev = prev->getPreviousDecl(); 11066 11067 if (!prev) 11068 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11069 } 11070 11071 // Cache the result of checking for constant initialization. 11072 Optional<bool> CacheHasConstInit; 11073 const Expr *CacheCulprit; 11074 auto checkConstInit = [&]() mutable { 11075 if (!CacheHasConstInit) 11076 CacheHasConstInit = var->getInit()->isConstantInitializer( 11077 Context, var->getType()->isReferenceType(), &CacheCulprit); 11078 return *CacheHasConstInit; 11079 }; 11080 11081 if (var->getTLSKind() == VarDecl::TLS_Static) { 11082 if (var->getType().isDestructedType()) { 11083 // GNU C++98 edits for __thread, [basic.start.term]p3: 11084 // The type of an object with thread storage duration shall not 11085 // have a non-trivial destructor. 11086 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11087 if (getLangOpts().CPlusPlus11) 11088 Diag(var->getLocation(), diag::note_use_thread_local); 11089 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11090 if (!checkConstInit()) { 11091 // GNU C++98 edits for __thread, [basic.start.init]p4: 11092 // An object of thread storage duration shall not require dynamic 11093 // initialization. 11094 // FIXME: Need strict checking here. 11095 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11096 << CacheCulprit->getSourceRange(); 11097 if (getLangOpts().CPlusPlus11) 11098 Diag(var->getLocation(), diag::note_use_thread_local); 11099 } 11100 } 11101 } 11102 11103 // Apply section attributes and pragmas to global variables. 11104 bool GlobalStorage = var->hasGlobalStorage(); 11105 if (GlobalStorage && var->isThisDeclarationADefinition() && 11106 !inTemplateInstantiation()) { 11107 PragmaStack<StringLiteral *> *Stack = nullptr; 11108 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11109 if (var->getType().isConstQualified()) 11110 Stack = &ConstSegStack; 11111 else if (!var->getInit()) { 11112 Stack = &BSSSegStack; 11113 SectionFlags |= ASTContext::PSF_Write; 11114 } else { 11115 Stack = &DataSegStack; 11116 SectionFlags |= ASTContext::PSF_Write; 11117 } 11118 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11119 var->addAttr(SectionAttr::CreateImplicit( 11120 Context, SectionAttr::Declspec_allocate, 11121 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11122 } 11123 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11124 if (UnifySection(SA->getName(), SectionFlags, var)) 11125 var->dropAttr<SectionAttr>(); 11126 11127 // Apply the init_seg attribute if this has an initializer. If the 11128 // initializer turns out to not be dynamic, we'll end up ignoring this 11129 // attribute. 11130 if (CurInitSeg && var->getInit()) 11131 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11132 CurInitSegLoc)); 11133 } 11134 11135 // All the following checks are C++ only. 11136 if (!getLangOpts().CPlusPlus) { 11137 // If this variable must be emitted, add it as an initializer for the 11138 // current module. 11139 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11140 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11141 return; 11142 } 11143 11144 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11145 CheckCompleteDecompositionDeclaration(DD); 11146 11147 QualType type = var->getType(); 11148 if (type->isDependentType()) return; 11149 11150 // __block variables might require us to capture a copy-initializer. 11151 if (var->hasAttr<BlocksAttr>()) { 11152 // It's currently invalid to ever have a __block variable with an 11153 // array type; should we diagnose that here? 11154 11155 // Regardless, we don't want to ignore array nesting when 11156 // constructing this copy. 11157 if (type->isStructureOrClassType()) { 11158 EnterExpressionEvaluationContext scope( 11159 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11160 SourceLocation poi = var->getLocation(); 11161 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11162 ExprResult result 11163 = PerformMoveOrCopyInitialization( 11164 InitializedEntity::InitializeBlock(poi, type, false), 11165 var, var->getType(), varRef, /*AllowNRVO=*/true); 11166 if (!result.isInvalid()) { 11167 result = MaybeCreateExprWithCleanups(result); 11168 Expr *init = result.getAs<Expr>(); 11169 Context.setBlockVarCopyInits(var, init); 11170 } 11171 } 11172 } 11173 11174 Expr *Init = var->getInit(); 11175 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11176 QualType baseType = Context.getBaseElementType(type); 11177 11178 if (Init && !Init->isValueDependent()) { 11179 if (var->isConstexpr()) { 11180 SmallVector<PartialDiagnosticAt, 8> Notes; 11181 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11182 SourceLocation DiagLoc = var->getLocation(); 11183 // If the note doesn't add any useful information other than a source 11184 // location, fold it into the primary diagnostic. 11185 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11186 diag::note_invalid_subexpr_in_const_expr) { 11187 DiagLoc = Notes[0].first; 11188 Notes.clear(); 11189 } 11190 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11191 << var << Init->getSourceRange(); 11192 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11193 Diag(Notes[I].first, Notes[I].second); 11194 } 11195 } else if (var->isUsableInConstantExpressions(Context)) { 11196 // Check whether the initializer of a const variable of integral or 11197 // enumeration type is an ICE now, since we can't tell whether it was 11198 // initialized by a constant expression if we check later. 11199 var->checkInitIsICE(); 11200 } 11201 11202 // Don't emit further diagnostics about constexpr globals since they 11203 // were just diagnosed. 11204 if (!var->isConstexpr() && GlobalStorage && 11205 var->hasAttr<RequireConstantInitAttr>()) { 11206 // FIXME: Need strict checking in C++03 here. 11207 bool DiagErr = getLangOpts().CPlusPlus11 11208 ? !var->checkInitIsICE() : !checkConstInit(); 11209 if (DiagErr) { 11210 auto attr = var->getAttr<RequireConstantInitAttr>(); 11211 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11212 << Init->getSourceRange(); 11213 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11214 << attr->getRange(); 11215 if (getLangOpts().CPlusPlus11) { 11216 APValue Value; 11217 SmallVector<PartialDiagnosticAt, 8> Notes; 11218 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11219 for (auto &it : Notes) 11220 Diag(it.first, it.second); 11221 } else { 11222 Diag(CacheCulprit->getExprLoc(), 11223 diag::note_invalid_subexpr_in_const_expr) 11224 << CacheCulprit->getSourceRange(); 11225 } 11226 } 11227 } 11228 else if (!var->isConstexpr() && IsGlobal && 11229 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11230 var->getLocation())) { 11231 // Warn about globals which don't have a constant initializer. Don't 11232 // warn about globals with a non-trivial destructor because we already 11233 // warned about them. 11234 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11235 if (!(RD && !RD->hasTrivialDestructor())) { 11236 if (!checkConstInit()) 11237 Diag(var->getLocation(), diag::warn_global_constructor) 11238 << Init->getSourceRange(); 11239 } 11240 } 11241 } 11242 11243 // Require the destructor. 11244 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11245 FinalizeVarWithDestructor(var, recordType); 11246 11247 // If this variable must be emitted, add it as an initializer for the current 11248 // module. 11249 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11250 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11251 } 11252 11253 /// \brief Determines if a variable's alignment is dependent. 11254 static bool hasDependentAlignment(VarDecl *VD) { 11255 if (VD->getType()->isDependentType()) 11256 return true; 11257 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11258 if (I->isAlignmentDependent()) 11259 return true; 11260 return false; 11261 } 11262 11263 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11264 /// any semantic actions necessary after any initializer has been attached. 11265 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11266 // Note that we are no longer parsing the initializer for this declaration. 11267 ParsingInitForAutoVars.erase(ThisDecl); 11268 11269 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11270 if (!VD) 11271 return; 11272 11273 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11274 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11275 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11276 if (PragmaClangBSSSection.Valid) 11277 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11278 PragmaClangBSSSection.SectionName, 11279 PragmaClangBSSSection.PragmaLocation)); 11280 if (PragmaClangDataSection.Valid) 11281 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11282 PragmaClangDataSection.SectionName, 11283 PragmaClangDataSection.PragmaLocation)); 11284 if (PragmaClangRodataSection.Valid) 11285 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11286 PragmaClangRodataSection.SectionName, 11287 PragmaClangRodataSection.PragmaLocation)); 11288 } 11289 11290 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11291 for (auto *BD : DD->bindings()) { 11292 FinalizeDeclaration(BD); 11293 } 11294 } 11295 11296 checkAttributesAfterMerging(*this, *VD); 11297 11298 // Perform TLS alignment check here after attributes attached to the variable 11299 // which may affect the alignment have been processed. Only perform the check 11300 // if the target has a maximum TLS alignment (zero means no constraints). 11301 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11302 // Protect the check so that it's not performed on dependent types and 11303 // dependent alignments (we can't determine the alignment in that case). 11304 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11305 !VD->isInvalidDecl()) { 11306 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11307 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11308 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11309 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11310 << (unsigned)MaxAlignChars.getQuantity(); 11311 } 11312 } 11313 } 11314 11315 if (VD->isStaticLocal()) { 11316 if (FunctionDecl *FD = 11317 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11318 // Static locals inherit dll attributes from their function. 11319 if (Attr *A = getDLLAttr(FD)) { 11320 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11321 NewAttr->setInherited(true); 11322 VD->addAttr(NewAttr); 11323 } 11324 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11325 // function, only __shared__ variables may be declared with 11326 // static storage class. 11327 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11328 CUDADiagIfDeviceCode(VD->getLocation(), 11329 diag::err_device_static_local_var) 11330 << CurrentCUDATarget()) 11331 VD->setInvalidDecl(); 11332 } 11333 } 11334 11335 // Perform check for initializers of device-side global variables. 11336 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11337 // 7.5). We must also apply the same checks to all __shared__ 11338 // variables whether they are local or not. CUDA also allows 11339 // constant initializers for __constant__ and __device__ variables. 11340 if (getLangOpts().CUDA) { 11341 const Expr *Init = VD->getInit(); 11342 if (Init && VD->hasGlobalStorage()) { 11343 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11344 VD->hasAttr<CUDASharedAttr>()) { 11345 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11346 bool AllowedInit = false; 11347 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11348 AllowedInit = 11349 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11350 // We'll allow constant initializers even if it's a non-empty 11351 // constructor according to CUDA rules. This deviates from NVCC, 11352 // but allows us to handle things like constexpr constructors. 11353 if (!AllowedInit && 11354 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11355 AllowedInit = VD->getInit()->isConstantInitializer( 11356 Context, VD->getType()->isReferenceType()); 11357 11358 // Also make sure that destructor, if there is one, is empty. 11359 if (AllowedInit) 11360 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11361 AllowedInit = 11362 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11363 11364 if (!AllowedInit) { 11365 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11366 ? diag::err_shared_var_init 11367 : diag::err_dynamic_var_init) 11368 << Init->getSourceRange(); 11369 VD->setInvalidDecl(); 11370 } 11371 } else { 11372 // This is a host-side global variable. Check that the initializer is 11373 // callable from the host side. 11374 const FunctionDecl *InitFn = nullptr; 11375 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11376 InitFn = CE->getConstructor(); 11377 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11378 InitFn = CE->getDirectCallee(); 11379 } 11380 if (InitFn) { 11381 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11382 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11383 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11384 << InitFnTarget << InitFn; 11385 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11386 VD->setInvalidDecl(); 11387 } 11388 } 11389 } 11390 } 11391 } 11392 11393 // Grab the dllimport or dllexport attribute off of the VarDecl. 11394 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11395 11396 // Imported static data members cannot be defined out-of-line. 11397 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11398 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11399 VD->isThisDeclarationADefinition()) { 11400 // We allow definitions of dllimport class template static data members 11401 // with a warning. 11402 CXXRecordDecl *Context = 11403 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11404 bool IsClassTemplateMember = 11405 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11406 Context->getDescribedClassTemplate(); 11407 11408 Diag(VD->getLocation(), 11409 IsClassTemplateMember 11410 ? diag::warn_attribute_dllimport_static_field_definition 11411 : diag::err_attribute_dllimport_static_field_definition); 11412 Diag(IA->getLocation(), diag::note_attribute); 11413 if (!IsClassTemplateMember) 11414 VD->setInvalidDecl(); 11415 } 11416 } 11417 11418 // dllimport/dllexport variables cannot be thread local, their TLS index 11419 // isn't exported with the variable. 11420 if (DLLAttr && VD->getTLSKind()) { 11421 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11422 if (F && getDLLAttr(F)) { 11423 assert(VD->isStaticLocal()); 11424 // But if this is a static local in a dlimport/dllexport function, the 11425 // function will never be inlined, which means the var would never be 11426 // imported, so having it marked import/export is safe. 11427 } else { 11428 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11429 << DLLAttr; 11430 VD->setInvalidDecl(); 11431 } 11432 } 11433 11434 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11435 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11436 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11437 VD->dropAttr<UsedAttr>(); 11438 } 11439 } 11440 11441 const DeclContext *DC = VD->getDeclContext(); 11442 // If there's a #pragma GCC visibility in scope, and this isn't a class 11443 // member, set the visibility of this variable. 11444 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11445 AddPushedVisibilityAttribute(VD); 11446 11447 // FIXME: Warn on unused var template partial specializations. 11448 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11449 MarkUnusedFileScopedDecl(VD); 11450 11451 // Now we have parsed the initializer and can update the table of magic 11452 // tag values. 11453 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11454 !VD->getType()->isIntegralOrEnumerationType()) 11455 return; 11456 11457 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11458 const Expr *MagicValueExpr = VD->getInit(); 11459 if (!MagicValueExpr) { 11460 continue; 11461 } 11462 llvm::APSInt MagicValueInt; 11463 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11464 Diag(I->getRange().getBegin(), 11465 diag::err_type_tag_for_datatype_not_ice) 11466 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11467 continue; 11468 } 11469 if (MagicValueInt.getActiveBits() > 64) { 11470 Diag(I->getRange().getBegin(), 11471 diag::err_type_tag_for_datatype_too_large) 11472 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11473 continue; 11474 } 11475 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11476 RegisterTypeTagForDatatype(I->getArgumentKind(), 11477 MagicValue, 11478 I->getMatchingCType(), 11479 I->getLayoutCompatible(), 11480 I->getMustBeNull()); 11481 } 11482 } 11483 11484 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11485 auto *VD = dyn_cast<VarDecl>(DD); 11486 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11487 } 11488 11489 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11490 ArrayRef<Decl *> Group) { 11491 SmallVector<Decl*, 8> Decls; 11492 11493 if (DS.isTypeSpecOwned()) 11494 Decls.push_back(DS.getRepAsDecl()); 11495 11496 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11497 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11498 bool DiagnosedMultipleDecomps = false; 11499 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11500 bool DiagnosedNonDeducedAuto = false; 11501 11502 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11503 if (Decl *D = Group[i]) { 11504 // For declarators, there are some additional syntactic-ish checks we need 11505 // to perform. 11506 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11507 if (!FirstDeclaratorInGroup) 11508 FirstDeclaratorInGroup = DD; 11509 if (!FirstDecompDeclaratorInGroup) 11510 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11511 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11512 !hasDeducedAuto(DD)) 11513 FirstNonDeducedAutoInGroup = DD; 11514 11515 if (FirstDeclaratorInGroup != DD) { 11516 // A decomposition declaration cannot be combined with any other 11517 // declaration in the same group. 11518 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11519 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11520 diag::err_decomp_decl_not_alone) 11521 << FirstDeclaratorInGroup->getSourceRange() 11522 << DD->getSourceRange(); 11523 DiagnosedMultipleDecomps = true; 11524 } 11525 11526 // A declarator that uses 'auto' in any way other than to declare a 11527 // variable with a deduced type cannot be combined with any other 11528 // declarator in the same group. 11529 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11530 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11531 diag::err_auto_non_deduced_not_alone) 11532 << FirstNonDeducedAutoInGroup->getType() 11533 ->hasAutoForTrailingReturnType() 11534 << FirstDeclaratorInGroup->getSourceRange() 11535 << DD->getSourceRange(); 11536 DiagnosedNonDeducedAuto = true; 11537 } 11538 } 11539 } 11540 11541 Decls.push_back(D); 11542 } 11543 } 11544 11545 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11546 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11547 handleTagNumbering(Tag, S); 11548 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11549 getLangOpts().CPlusPlus) 11550 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11551 } 11552 } 11553 11554 return BuildDeclaratorGroup(Decls); 11555 } 11556 11557 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11558 /// group, performing any necessary semantic checking. 11559 Sema::DeclGroupPtrTy 11560 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11561 // C++14 [dcl.spec.auto]p7: (DR1347) 11562 // If the type that replaces the placeholder type is not the same in each 11563 // deduction, the program is ill-formed. 11564 if (Group.size() > 1) { 11565 QualType Deduced; 11566 VarDecl *DeducedDecl = nullptr; 11567 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11568 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11569 if (!D || D->isInvalidDecl()) 11570 break; 11571 DeducedType *DT = D->getType()->getContainedDeducedType(); 11572 if (!DT || DT->getDeducedType().isNull()) 11573 continue; 11574 if (Deduced.isNull()) { 11575 Deduced = DT->getDeducedType(); 11576 DeducedDecl = D; 11577 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11578 auto *AT = dyn_cast<AutoType>(DT); 11579 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11580 diag::err_auto_different_deductions) 11581 << (AT ? (unsigned)AT->getKeyword() : 3) 11582 << Deduced << DeducedDecl->getDeclName() 11583 << DT->getDeducedType() << D->getDeclName() 11584 << DeducedDecl->getInit()->getSourceRange() 11585 << D->getInit()->getSourceRange(); 11586 D->setInvalidDecl(); 11587 break; 11588 } 11589 } 11590 } 11591 11592 ActOnDocumentableDecls(Group); 11593 11594 return DeclGroupPtrTy::make( 11595 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11596 } 11597 11598 void Sema::ActOnDocumentableDecl(Decl *D) { 11599 ActOnDocumentableDecls(D); 11600 } 11601 11602 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11603 // Don't parse the comment if Doxygen diagnostics are ignored. 11604 if (Group.empty() || !Group[0]) 11605 return; 11606 11607 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11608 Group[0]->getLocation()) && 11609 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11610 Group[0]->getLocation())) 11611 return; 11612 11613 if (Group.size() >= 2) { 11614 // This is a decl group. Normally it will contain only declarations 11615 // produced from declarator list. But in case we have any definitions or 11616 // additional declaration references: 11617 // 'typedef struct S {} S;' 11618 // 'typedef struct S *S;' 11619 // 'struct S *pS;' 11620 // FinalizeDeclaratorGroup adds these as separate declarations. 11621 Decl *MaybeTagDecl = Group[0]; 11622 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11623 Group = Group.slice(1); 11624 } 11625 } 11626 11627 // See if there are any new comments that are not attached to a decl. 11628 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11629 if (!Comments.empty() && 11630 !Comments.back()->isAttached()) { 11631 // There is at least one comment that not attached to a decl. 11632 // Maybe it should be attached to one of these decls? 11633 // 11634 // Note that this way we pick up not only comments that precede the 11635 // declaration, but also comments that *follow* the declaration -- thanks to 11636 // the lookahead in the lexer: we've consumed the semicolon and looked 11637 // ahead through comments. 11638 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11639 Context.getCommentForDecl(Group[i], &PP); 11640 } 11641 } 11642 11643 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11644 /// to introduce parameters into function prototype scope. 11645 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11646 const DeclSpec &DS = D.getDeclSpec(); 11647 11648 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11649 11650 // C++03 [dcl.stc]p2 also permits 'auto'. 11651 StorageClass SC = SC_None; 11652 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11653 SC = SC_Register; 11654 } else if (getLangOpts().CPlusPlus && 11655 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11656 SC = SC_Auto; 11657 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11658 Diag(DS.getStorageClassSpecLoc(), 11659 diag::err_invalid_storage_class_in_func_decl); 11660 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11661 } 11662 11663 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11664 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11665 << DeclSpec::getSpecifierName(TSCS); 11666 if (DS.isInlineSpecified()) 11667 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11668 << getLangOpts().CPlusPlus1z; 11669 if (DS.isConstexprSpecified()) 11670 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11671 << 0; 11672 if (DS.isConceptSpecified()) 11673 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11674 11675 DiagnoseFunctionSpecifiers(DS); 11676 11677 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11678 QualType parmDeclType = TInfo->getType(); 11679 11680 if (getLangOpts().CPlusPlus) { 11681 // Check that there are no default arguments inside the type of this 11682 // parameter. 11683 CheckExtraCXXDefaultArguments(D); 11684 11685 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11686 if (D.getCXXScopeSpec().isSet()) { 11687 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11688 << D.getCXXScopeSpec().getRange(); 11689 D.getCXXScopeSpec().clear(); 11690 } 11691 } 11692 11693 // Ensure we have a valid name 11694 IdentifierInfo *II = nullptr; 11695 if (D.hasName()) { 11696 II = D.getIdentifier(); 11697 if (!II) { 11698 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11699 << GetNameForDeclarator(D).getName(); 11700 D.setInvalidType(true); 11701 } 11702 } 11703 11704 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11705 if (II) { 11706 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11707 ForRedeclaration); 11708 LookupName(R, S); 11709 if (R.isSingleResult()) { 11710 NamedDecl *PrevDecl = R.getFoundDecl(); 11711 if (PrevDecl->isTemplateParameter()) { 11712 // Maybe we will complain about the shadowed template parameter. 11713 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11714 // Just pretend that we didn't see the previous declaration. 11715 PrevDecl = nullptr; 11716 } else if (S->isDeclScope(PrevDecl)) { 11717 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11718 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11719 11720 // Recover by removing the name 11721 II = nullptr; 11722 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11723 D.setInvalidType(true); 11724 } 11725 } 11726 } 11727 11728 // Temporarily put parameter variables in the translation unit, not 11729 // the enclosing context. This prevents them from accidentally 11730 // looking like class members in C++. 11731 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11732 D.getLocStart(), 11733 D.getIdentifierLoc(), II, 11734 parmDeclType, TInfo, 11735 SC); 11736 11737 if (D.isInvalidType()) 11738 New->setInvalidDecl(); 11739 11740 assert(S->isFunctionPrototypeScope()); 11741 assert(S->getFunctionPrototypeDepth() >= 1); 11742 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11743 S->getNextFunctionPrototypeIndex()); 11744 11745 // Add the parameter declaration into this scope. 11746 S->AddDecl(New); 11747 if (II) 11748 IdResolver.AddDecl(New); 11749 11750 ProcessDeclAttributes(S, New, D); 11751 11752 if (D.getDeclSpec().isModulePrivateSpecified()) 11753 Diag(New->getLocation(), diag::err_module_private_local) 11754 << 1 << New->getDeclName() 11755 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11756 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11757 11758 if (New->hasAttr<BlocksAttr>()) { 11759 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11760 } 11761 return New; 11762 } 11763 11764 /// \brief Synthesizes a variable for a parameter arising from a 11765 /// typedef. 11766 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11767 SourceLocation Loc, 11768 QualType T) { 11769 /* FIXME: setting StartLoc == Loc. 11770 Would it be worth to modify callers so as to provide proper source 11771 location for the unnamed parameters, embedding the parameter's type? */ 11772 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11773 T, Context.getTrivialTypeSourceInfo(T, Loc), 11774 SC_None, nullptr); 11775 Param->setImplicit(); 11776 return Param; 11777 } 11778 11779 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11780 // Don't diagnose unused-parameter errors in template instantiations; we 11781 // will already have done so in the template itself. 11782 if (inTemplateInstantiation()) 11783 return; 11784 11785 for (const ParmVarDecl *Parameter : Parameters) { 11786 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11787 !Parameter->hasAttr<UnusedAttr>()) { 11788 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11789 << Parameter->getDeclName(); 11790 } 11791 } 11792 } 11793 11794 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11795 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11796 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11797 return; 11798 11799 // Warn if the return value is pass-by-value and larger than the specified 11800 // threshold. 11801 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11802 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11803 if (Size > LangOpts.NumLargeByValueCopy) 11804 Diag(D->getLocation(), diag::warn_return_value_size) 11805 << D->getDeclName() << Size; 11806 } 11807 11808 // Warn if any parameter is pass-by-value and larger than the specified 11809 // threshold. 11810 for (const ParmVarDecl *Parameter : Parameters) { 11811 QualType T = Parameter->getType(); 11812 if (T->isDependentType() || !T.isPODType(Context)) 11813 continue; 11814 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11815 if (Size > LangOpts.NumLargeByValueCopy) 11816 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11817 << Parameter->getDeclName() << Size; 11818 } 11819 } 11820 11821 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11822 SourceLocation NameLoc, IdentifierInfo *Name, 11823 QualType T, TypeSourceInfo *TSInfo, 11824 StorageClass SC) { 11825 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11826 if (getLangOpts().ObjCAutoRefCount && 11827 T.getObjCLifetime() == Qualifiers::OCL_None && 11828 T->isObjCLifetimeType()) { 11829 11830 Qualifiers::ObjCLifetime lifetime; 11831 11832 // Special cases for arrays: 11833 // - if it's const, use __unsafe_unretained 11834 // - otherwise, it's an error 11835 if (T->isArrayType()) { 11836 if (!T.isConstQualified()) { 11837 DelayedDiagnostics.add( 11838 sema::DelayedDiagnostic::makeForbiddenType( 11839 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11840 } 11841 lifetime = Qualifiers::OCL_ExplicitNone; 11842 } else { 11843 lifetime = T->getObjCARCImplicitLifetime(); 11844 } 11845 T = Context.getLifetimeQualifiedType(T, lifetime); 11846 } 11847 11848 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11849 Context.getAdjustedParameterType(T), 11850 TSInfo, SC, nullptr); 11851 11852 // Parameters can not be abstract class types. 11853 // For record types, this is done by the AbstractClassUsageDiagnoser once 11854 // the class has been completely parsed. 11855 if (!CurContext->isRecord() && 11856 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11857 AbstractParamType)) 11858 New->setInvalidDecl(); 11859 11860 // Parameter declarators cannot be interface types. All ObjC objects are 11861 // passed by reference. 11862 if (T->isObjCObjectType()) { 11863 SourceLocation TypeEndLoc = 11864 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11865 Diag(NameLoc, 11866 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11867 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11868 T = Context.getObjCObjectPointerType(T); 11869 New->setType(T); 11870 } 11871 11872 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11873 // duration shall not be qualified by an address-space qualifier." 11874 // Since all parameters have automatic store duration, they can not have 11875 // an address space. 11876 if (T.getAddressSpace() != 0) { 11877 // OpenCL allows function arguments declared to be an array of a type 11878 // to be qualified with an address space. 11879 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11880 Diag(NameLoc, diag::err_arg_with_address_space); 11881 New->setInvalidDecl(); 11882 } 11883 } 11884 11885 return New; 11886 } 11887 11888 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11889 SourceLocation LocAfterDecls) { 11890 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11891 11892 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11893 // for a K&R function. 11894 if (!FTI.hasPrototype) { 11895 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11896 --i; 11897 if (FTI.Params[i].Param == nullptr) { 11898 SmallString<256> Code; 11899 llvm::raw_svector_ostream(Code) 11900 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11901 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11902 << FTI.Params[i].Ident 11903 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11904 11905 // Implicitly declare the argument as type 'int' for lack of a better 11906 // type. 11907 AttributeFactory attrs; 11908 DeclSpec DS(attrs); 11909 const char* PrevSpec; // unused 11910 unsigned DiagID; // unused 11911 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11912 DiagID, Context.getPrintingPolicy()); 11913 // Use the identifier location for the type source range. 11914 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11915 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11916 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11917 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11918 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11919 } 11920 } 11921 } 11922 } 11923 11924 Decl * 11925 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11926 MultiTemplateParamsArg TemplateParameterLists, 11927 SkipBodyInfo *SkipBody) { 11928 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11929 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11930 Scope *ParentScope = FnBodyScope->getParent(); 11931 11932 D.setFunctionDefinitionKind(FDK_Definition); 11933 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11934 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11935 } 11936 11937 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11938 Consumer.HandleInlineFunctionDefinition(D); 11939 } 11940 11941 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11942 const FunctionDecl*& PossibleZeroParamPrototype) { 11943 // Don't warn about invalid declarations. 11944 if (FD->isInvalidDecl()) 11945 return false; 11946 11947 // Or declarations that aren't global. 11948 if (!FD->isGlobal()) 11949 return false; 11950 11951 // Don't warn about C++ member functions. 11952 if (isa<CXXMethodDecl>(FD)) 11953 return false; 11954 11955 // Don't warn about 'main'. 11956 if (FD->isMain()) 11957 return false; 11958 11959 // Don't warn about inline functions. 11960 if (FD->isInlined()) 11961 return false; 11962 11963 // Don't warn about function templates. 11964 if (FD->getDescribedFunctionTemplate()) 11965 return false; 11966 11967 // Don't warn about function template specializations. 11968 if (FD->isFunctionTemplateSpecialization()) 11969 return false; 11970 11971 // Don't warn for OpenCL kernels. 11972 if (FD->hasAttr<OpenCLKernelAttr>()) 11973 return false; 11974 11975 // Don't warn on explicitly deleted functions. 11976 if (FD->isDeleted()) 11977 return false; 11978 11979 bool MissingPrototype = true; 11980 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11981 Prev; Prev = Prev->getPreviousDecl()) { 11982 // Ignore any declarations that occur in function or method 11983 // scope, because they aren't visible from the header. 11984 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11985 continue; 11986 11987 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11988 if (FD->getNumParams() == 0) 11989 PossibleZeroParamPrototype = Prev; 11990 break; 11991 } 11992 11993 return MissingPrototype; 11994 } 11995 11996 void 11997 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11998 const FunctionDecl *EffectiveDefinition, 11999 SkipBodyInfo *SkipBody) { 12000 const FunctionDecl *Definition = EffectiveDefinition; 12001 if (!Definition) 12002 if (!FD->isDefined(Definition)) 12003 return; 12004 12005 if (canRedefineFunction(Definition, getLangOpts())) 12006 return; 12007 12008 // Don't emit an error when this is redefinition of a typo-corrected 12009 // definition. 12010 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12011 return; 12012 12013 // If we don't have a visible definition of the function, and it's inline or 12014 // a template, skip the new definition. 12015 if (SkipBody && !hasVisibleDefinition(Definition) && 12016 (Definition->getFormalLinkage() == InternalLinkage || 12017 Definition->isInlined() || 12018 Definition->getDescribedFunctionTemplate() || 12019 Definition->getNumTemplateParameterLists())) { 12020 SkipBody->ShouldSkip = true; 12021 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12022 makeMergedDefinitionVisible(TD); 12023 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12024 return; 12025 } 12026 12027 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12028 Definition->getStorageClass() == SC_Extern) 12029 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12030 << FD->getDeclName() << getLangOpts().CPlusPlus; 12031 else 12032 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12033 12034 Diag(Definition->getLocation(), diag::note_previous_definition); 12035 FD->setInvalidDecl(); 12036 } 12037 12038 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12039 Sema &S) { 12040 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12041 12042 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12043 LSI->CallOperator = CallOperator; 12044 LSI->Lambda = LambdaClass; 12045 LSI->ReturnType = CallOperator->getReturnType(); 12046 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12047 12048 if (LCD == LCD_None) 12049 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12050 else if (LCD == LCD_ByCopy) 12051 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12052 else if (LCD == LCD_ByRef) 12053 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12054 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12055 12056 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12057 LSI->Mutable = !CallOperator->isConst(); 12058 12059 // Add the captures to the LSI so they can be noted as already 12060 // captured within tryCaptureVar. 12061 auto I = LambdaClass->field_begin(); 12062 for (const auto &C : LambdaClass->captures()) { 12063 if (C.capturesVariable()) { 12064 VarDecl *VD = C.getCapturedVar(); 12065 if (VD->isInitCapture()) 12066 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12067 QualType CaptureType = VD->getType(); 12068 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12069 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12070 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12071 /*EllipsisLoc*/C.isPackExpansion() 12072 ? C.getEllipsisLoc() : SourceLocation(), 12073 CaptureType, /*Expr*/ nullptr); 12074 12075 } else if (C.capturesThis()) { 12076 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12077 /*Expr*/ nullptr, 12078 C.getCaptureKind() == LCK_StarThis); 12079 } else { 12080 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12081 } 12082 ++I; 12083 } 12084 } 12085 12086 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12087 SkipBodyInfo *SkipBody) { 12088 if (!D) 12089 return D; 12090 FunctionDecl *FD = nullptr; 12091 12092 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12093 FD = FunTmpl->getTemplatedDecl(); 12094 else 12095 FD = cast<FunctionDecl>(D); 12096 12097 // Check for defining attributes before the check for redefinition. 12098 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12099 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12100 FD->dropAttr<AliasAttr>(); 12101 FD->setInvalidDecl(); 12102 } 12103 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12104 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12105 FD->dropAttr<IFuncAttr>(); 12106 FD->setInvalidDecl(); 12107 } 12108 12109 // See if this is a redefinition. If 'will have body' is already set, then 12110 // these checks were already performed when it was set. 12111 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12112 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12113 12114 // If we're skipping the body, we're done. Don't enter the scope. 12115 if (SkipBody && SkipBody->ShouldSkip) 12116 return D; 12117 } 12118 12119 // Mark this function as "will have a body eventually". This lets users to 12120 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12121 // this function. 12122 FD->setWillHaveBody(); 12123 12124 // If we are instantiating a generic lambda call operator, push 12125 // a LambdaScopeInfo onto the function stack. But use the information 12126 // that's already been calculated (ActOnLambdaExpr) to prime the current 12127 // LambdaScopeInfo. 12128 // When the template operator is being specialized, the LambdaScopeInfo, 12129 // has to be properly restored so that tryCaptureVariable doesn't try 12130 // and capture any new variables. In addition when calculating potential 12131 // captures during transformation of nested lambdas, it is necessary to 12132 // have the LSI properly restored. 12133 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12134 assert(inTemplateInstantiation() && 12135 "There should be an active template instantiation on the stack " 12136 "when instantiating a generic lambda!"); 12137 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12138 } else { 12139 // Enter a new function scope 12140 PushFunctionScope(); 12141 } 12142 12143 // Builtin functions cannot be defined. 12144 if (unsigned BuiltinID = FD->getBuiltinID()) { 12145 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12146 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12147 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12148 FD->setInvalidDecl(); 12149 } 12150 } 12151 12152 // The return type of a function definition must be complete 12153 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12154 QualType ResultType = FD->getReturnType(); 12155 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12156 !FD->isInvalidDecl() && 12157 RequireCompleteType(FD->getLocation(), ResultType, 12158 diag::err_func_def_incomplete_result)) 12159 FD->setInvalidDecl(); 12160 12161 if (FnBodyScope) 12162 PushDeclContext(FnBodyScope, FD); 12163 12164 // Check the validity of our function parameters 12165 CheckParmsForFunctionDef(FD->parameters(), 12166 /*CheckParameterNames=*/true); 12167 12168 // Add non-parameter declarations already in the function to the current 12169 // scope. 12170 if (FnBodyScope) { 12171 for (Decl *NPD : FD->decls()) { 12172 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12173 if (!NonParmDecl) 12174 continue; 12175 assert(!isa<ParmVarDecl>(NonParmDecl) && 12176 "parameters should not be in newly created FD yet"); 12177 12178 // If the decl has a name, make it accessible in the current scope. 12179 if (NonParmDecl->getDeclName()) 12180 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12181 12182 // Similarly, dive into enums and fish their constants out, making them 12183 // accessible in this scope. 12184 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12185 for (auto *EI : ED->enumerators()) 12186 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12187 } 12188 } 12189 } 12190 12191 // Introduce our parameters into the function scope 12192 for (auto Param : FD->parameters()) { 12193 Param->setOwningFunction(FD); 12194 12195 // If this has an identifier, add it to the scope stack. 12196 if (Param->getIdentifier() && FnBodyScope) { 12197 CheckShadow(FnBodyScope, Param); 12198 12199 PushOnScopeChains(Param, FnBodyScope); 12200 } 12201 } 12202 12203 // Ensure that the function's exception specification is instantiated. 12204 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12205 ResolveExceptionSpec(D->getLocation(), FPT); 12206 12207 // dllimport cannot be applied to non-inline function definitions. 12208 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12209 !FD->isTemplateInstantiation()) { 12210 assert(!FD->hasAttr<DLLExportAttr>()); 12211 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12212 FD->setInvalidDecl(); 12213 return D; 12214 } 12215 // We want to attach documentation to original Decl (which might be 12216 // a function template). 12217 ActOnDocumentableDecl(D); 12218 if (getCurLexicalContext()->isObjCContainer() && 12219 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12220 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12221 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12222 12223 return D; 12224 } 12225 12226 /// \brief Given the set of return statements within a function body, 12227 /// compute the variables that are subject to the named return value 12228 /// optimization. 12229 /// 12230 /// Each of the variables that is subject to the named return value 12231 /// optimization will be marked as NRVO variables in the AST, and any 12232 /// return statement that has a marked NRVO variable as its NRVO candidate can 12233 /// use the named return value optimization. 12234 /// 12235 /// This function applies a very simplistic algorithm for NRVO: if every return 12236 /// statement in the scope of a variable has the same NRVO candidate, that 12237 /// candidate is an NRVO variable. 12238 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12239 ReturnStmt **Returns = Scope->Returns.data(); 12240 12241 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12242 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12243 if (!NRVOCandidate->isNRVOVariable()) 12244 Returns[I]->setNRVOCandidate(nullptr); 12245 } 12246 } 12247 } 12248 12249 bool Sema::canDelayFunctionBody(const Declarator &D) { 12250 // We can't delay parsing the body of a constexpr function template (yet). 12251 if (D.getDeclSpec().isConstexprSpecified()) 12252 return false; 12253 12254 // We can't delay parsing the body of a function template with a deduced 12255 // return type (yet). 12256 if (D.getDeclSpec().hasAutoTypeSpec()) { 12257 // If the placeholder introduces a non-deduced trailing return type, 12258 // we can still delay parsing it. 12259 if (D.getNumTypeObjects()) { 12260 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12261 if (Outer.Kind == DeclaratorChunk::Function && 12262 Outer.Fun.hasTrailingReturnType()) { 12263 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12264 return Ty.isNull() || !Ty->isUndeducedType(); 12265 } 12266 } 12267 return false; 12268 } 12269 12270 return true; 12271 } 12272 12273 bool Sema::canSkipFunctionBody(Decl *D) { 12274 // We cannot skip the body of a function (or function template) which is 12275 // constexpr, since we may need to evaluate its body in order to parse the 12276 // rest of the file. 12277 // We cannot skip the body of a function with an undeduced return type, 12278 // because any callers of that function need to know the type. 12279 if (const FunctionDecl *FD = D->getAsFunction()) 12280 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12281 return false; 12282 return Consumer.shouldSkipFunctionBody(D); 12283 } 12284 12285 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12286 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12287 FD->setHasSkippedBody(); 12288 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12289 MD->setHasSkippedBody(); 12290 return Decl; 12291 } 12292 12293 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12294 return ActOnFinishFunctionBody(D, BodyArg, false); 12295 } 12296 12297 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12298 bool IsInstantiation) { 12299 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12300 12301 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12302 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12303 12304 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12305 CheckCompletedCoroutineBody(FD, Body); 12306 12307 if (FD) { 12308 FD->setBody(Body); 12309 FD->setWillHaveBody(false); 12310 12311 if (getLangOpts().CPlusPlus14) { 12312 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12313 FD->getReturnType()->isUndeducedType()) { 12314 // If the function has a deduced result type but contains no 'return' 12315 // statements, the result type as written must be exactly 'auto', and 12316 // the deduced result type is 'void'. 12317 if (!FD->getReturnType()->getAs<AutoType>()) { 12318 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12319 << FD->getReturnType(); 12320 FD->setInvalidDecl(); 12321 } else { 12322 // Substitute 'void' for the 'auto' in the type. 12323 TypeLoc ResultType = getReturnTypeLoc(FD); 12324 Context.adjustDeducedFunctionResultType( 12325 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12326 } 12327 } 12328 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12329 // In C++11, we don't use 'auto' deduction rules for lambda call 12330 // operators because we don't support return type deduction. 12331 auto *LSI = getCurLambda(); 12332 if (LSI->HasImplicitReturnType) { 12333 deduceClosureReturnType(*LSI); 12334 12335 // C++11 [expr.prim.lambda]p4: 12336 // [...] if there are no return statements in the compound-statement 12337 // [the deduced type is] the type void 12338 QualType RetType = 12339 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12340 12341 // Update the return type to the deduced type. 12342 const FunctionProtoType *Proto = 12343 FD->getType()->getAs<FunctionProtoType>(); 12344 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12345 Proto->getExtProtoInfo())); 12346 } 12347 } 12348 12349 // The only way to be included in UndefinedButUsed is if there is an 12350 // ODR use before the definition. Avoid the expensive map lookup if this 12351 // is the first declaration. 12352 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12353 if (!FD->isExternallyVisible()) 12354 UndefinedButUsed.erase(FD); 12355 else if (FD->isInlined() && 12356 !LangOpts.GNUInline && 12357 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12358 UndefinedButUsed.erase(FD); 12359 } 12360 12361 // If the function implicitly returns zero (like 'main') or is naked, 12362 // don't complain about missing return statements. 12363 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12364 WP.disableCheckFallThrough(); 12365 12366 // MSVC permits the use of pure specifier (=0) on function definition, 12367 // defined at class scope, warn about this non-standard construct. 12368 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12369 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12370 12371 if (!FD->isInvalidDecl()) { 12372 // Don't diagnose unused parameters of defaulted or deleted functions. 12373 if (!FD->isDeleted() && !FD->isDefaulted()) 12374 DiagnoseUnusedParameters(FD->parameters()); 12375 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12376 FD->getReturnType(), FD); 12377 12378 // If this is a structor, we need a vtable. 12379 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12380 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12381 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12382 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12383 12384 // Try to apply the named return value optimization. We have to check 12385 // if we can do this here because lambdas keep return statements around 12386 // to deduce an implicit return type. 12387 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12388 !FD->isDependentContext()) 12389 computeNRVO(Body, getCurFunction()); 12390 } 12391 12392 // GNU warning -Wmissing-prototypes: 12393 // Warn if a global function is defined without a previous 12394 // prototype declaration. This warning is issued even if the 12395 // definition itself provides a prototype. The aim is to detect 12396 // global functions that fail to be declared in header files. 12397 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12398 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12399 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12400 12401 if (PossibleZeroParamPrototype) { 12402 // We found a declaration that is not a prototype, 12403 // but that could be a zero-parameter prototype 12404 if (TypeSourceInfo *TI = 12405 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12406 TypeLoc TL = TI->getTypeLoc(); 12407 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12408 Diag(PossibleZeroParamPrototype->getLocation(), 12409 diag::note_declaration_not_a_prototype) 12410 << PossibleZeroParamPrototype 12411 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12412 } 12413 } 12414 12415 // GNU warning -Wstrict-prototypes 12416 // Warn if K&R function is defined without a previous declaration. 12417 // This warning is issued only if the definition itself does not provide 12418 // a prototype. Only K&R definitions do not provide a prototype. 12419 // An empty list in a function declarator that is part of a definition 12420 // of that function specifies that the function has no parameters 12421 // (C99 6.7.5.3p14) 12422 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12423 !LangOpts.CPlusPlus) { 12424 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12425 TypeLoc TL = TI->getTypeLoc(); 12426 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12427 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12428 } 12429 } 12430 12431 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12432 const CXXMethodDecl *KeyFunction; 12433 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12434 MD->isVirtual() && 12435 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12436 MD == KeyFunction->getCanonicalDecl()) { 12437 // Update the key-function state if necessary for this ABI. 12438 if (FD->isInlined() && 12439 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12440 Context.setNonKeyFunction(MD); 12441 12442 // If the newly-chosen key function is already defined, then we 12443 // need to mark the vtable as used retroactively. 12444 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12445 const FunctionDecl *Definition; 12446 if (KeyFunction && KeyFunction->isDefined(Definition)) 12447 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12448 } else { 12449 // We just defined they key function; mark the vtable as used. 12450 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12451 } 12452 } 12453 } 12454 12455 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12456 "Function parsing confused"); 12457 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12458 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12459 MD->setBody(Body); 12460 if (!MD->isInvalidDecl()) { 12461 DiagnoseUnusedParameters(MD->parameters()); 12462 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12463 MD->getReturnType(), MD); 12464 12465 if (Body) 12466 computeNRVO(Body, getCurFunction()); 12467 } 12468 if (getCurFunction()->ObjCShouldCallSuper) { 12469 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12470 << MD->getSelector().getAsString(); 12471 getCurFunction()->ObjCShouldCallSuper = false; 12472 } 12473 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12474 const ObjCMethodDecl *InitMethod = nullptr; 12475 bool isDesignated = 12476 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12477 assert(isDesignated && InitMethod); 12478 (void)isDesignated; 12479 12480 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12481 auto IFace = MD->getClassInterface(); 12482 if (!IFace) 12483 return false; 12484 auto SuperD = IFace->getSuperClass(); 12485 if (!SuperD) 12486 return false; 12487 return SuperD->getIdentifier() == 12488 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12489 }; 12490 // Don't issue this warning for unavailable inits or direct subclasses 12491 // of NSObject. 12492 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12493 Diag(MD->getLocation(), 12494 diag::warn_objc_designated_init_missing_super_call); 12495 Diag(InitMethod->getLocation(), 12496 diag::note_objc_designated_init_marked_here); 12497 } 12498 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12499 } 12500 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12501 // Don't issue this warning for unavaialable inits. 12502 if (!MD->isUnavailable()) 12503 Diag(MD->getLocation(), 12504 diag::warn_objc_secondary_init_missing_init_call); 12505 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12506 } 12507 } else { 12508 return nullptr; 12509 } 12510 12511 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12512 DiagnoseUnguardedAvailabilityViolations(dcl); 12513 12514 assert(!getCurFunction()->ObjCShouldCallSuper && 12515 "This should only be set for ObjC methods, which should have been " 12516 "handled in the block above."); 12517 12518 // Verify and clean out per-function state. 12519 if (Body && (!FD || !FD->isDefaulted())) { 12520 // C++ constructors that have function-try-blocks can't have return 12521 // statements in the handlers of that block. (C++ [except.handle]p14) 12522 // Verify this. 12523 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12524 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12525 12526 // Verify that gotos and switch cases don't jump into scopes illegally. 12527 if (getCurFunction()->NeedsScopeChecking() && 12528 !PP.isCodeCompletionEnabled()) 12529 DiagnoseInvalidJumps(Body); 12530 12531 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12532 if (!Destructor->getParent()->isDependentType()) 12533 CheckDestructor(Destructor); 12534 12535 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12536 Destructor->getParent()); 12537 } 12538 12539 // If any errors have occurred, clear out any temporaries that may have 12540 // been leftover. This ensures that these temporaries won't be picked up for 12541 // deletion in some later function. 12542 if (getDiagnostics().hasErrorOccurred() || 12543 getDiagnostics().getSuppressAllDiagnostics()) { 12544 DiscardCleanupsInEvaluationContext(); 12545 } 12546 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12547 !isa<FunctionTemplateDecl>(dcl)) { 12548 // Since the body is valid, issue any analysis-based warnings that are 12549 // enabled. 12550 ActivePolicy = &WP; 12551 } 12552 12553 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12554 (!CheckConstexprFunctionDecl(FD) || 12555 !CheckConstexprFunctionBody(FD, Body))) 12556 FD->setInvalidDecl(); 12557 12558 if (FD && FD->hasAttr<NakedAttr>()) { 12559 for (const Stmt *S : Body->children()) { 12560 // Allow local register variables without initializer as they don't 12561 // require prologue. 12562 bool RegisterVariables = false; 12563 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12564 for (const auto *Decl : DS->decls()) { 12565 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12566 RegisterVariables = 12567 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12568 if (!RegisterVariables) 12569 break; 12570 } 12571 } 12572 } 12573 if (RegisterVariables) 12574 continue; 12575 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12576 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12577 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12578 FD->setInvalidDecl(); 12579 break; 12580 } 12581 } 12582 } 12583 12584 assert(ExprCleanupObjects.size() == 12585 ExprEvalContexts.back().NumCleanupObjects && 12586 "Leftover temporaries in function"); 12587 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12588 assert(MaybeODRUseExprs.empty() && 12589 "Leftover expressions for odr-use checking"); 12590 } 12591 12592 if (!IsInstantiation) 12593 PopDeclContext(); 12594 12595 PopFunctionScopeInfo(ActivePolicy, dcl); 12596 // If any errors have occurred, clear out any temporaries that may have 12597 // been leftover. This ensures that these temporaries won't be picked up for 12598 // deletion in some later function. 12599 if (getDiagnostics().hasErrorOccurred()) { 12600 DiscardCleanupsInEvaluationContext(); 12601 } 12602 12603 return dcl; 12604 } 12605 12606 /// When we finish delayed parsing of an attribute, we must attach it to the 12607 /// relevant Decl. 12608 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12609 ParsedAttributes &Attrs) { 12610 // Always attach attributes to the underlying decl. 12611 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12612 D = TD->getTemplatedDecl(); 12613 ProcessDeclAttributeList(S, D, Attrs.getList()); 12614 12615 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12616 if (Method->isStatic()) 12617 checkThisInStaticMemberFunctionAttributes(Method); 12618 } 12619 12620 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12621 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12622 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12623 IdentifierInfo &II, Scope *S) { 12624 // Before we produce a declaration for an implicitly defined 12625 // function, see whether there was a locally-scoped declaration of 12626 // this name as a function or variable. If so, use that 12627 // (non-visible) declaration, and complain about it. 12628 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12629 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12630 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12631 return ExternCPrev; 12632 } 12633 12634 // Extension in C99. Legal in C90, but warn about it. 12635 unsigned diag_id; 12636 if (II.getName().startswith("__builtin_")) 12637 diag_id = diag::warn_builtin_unknown; 12638 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 12639 else if (getLangOpts().OpenCL) 12640 diag_id = diag::err_opencl_implicit_function_decl; 12641 else if (getLangOpts().C99) 12642 diag_id = diag::ext_implicit_function_decl; 12643 else 12644 diag_id = diag::warn_implicit_function_decl; 12645 Diag(Loc, diag_id) << &II; 12646 12647 // Because typo correction is expensive, only do it if the implicit 12648 // function declaration is going to be treated as an error. 12649 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12650 TypoCorrection Corrected; 12651 if (S && 12652 (Corrected = CorrectTypo( 12653 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12654 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12655 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12656 /*ErrorRecovery*/false); 12657 } 12658 12659 // Set a Declarator for the implicit definition: int foo(); 12660 const char *Dummy; 12661 AttributeFactory attrFactory; 12662 DeclSpec DS(attrFactory); 12663 unsigned DiagID; 12664 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12665 Context.getPrintingPolicy()); 12666 (void)Error; // Silence warning. 12667 assert(!Error && "Error setting up implicit decl!"); 12668 SourceLocation NoLoc; 12669 Declarator D(DS, Declarator::BlockContext); 12670 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12671 /*IsAmbiguous=*/false, 12672 /*LParenLoc=*/NoLoc, 12673 /*Params=*/nullptr, 12674 /*NumParams=*/0, 12675 /*EllipsisLoc=*/NoLoc, 12676 /*RParenLoc=*/NoLoc, 12677 /*TypeQuals=*/0, 12678 /*RefQualifierIsLvalueRef=*/true, 12679 /*RefQualifierLoc=*/NoLoc, 12680 /*ConstQualifierLoc=*/NoLoc, 12681 /*VolatileQualifierLoc=*/NoLoc, 12682 /*RestrictQualifierLoc=*/NoLoc, 12683 /*MutableLoc=*/NoLoc, 12684 EST_None, 12685 /*ESpecRange=*/SourceRange(), 12686 /*Exceptions=*/nullptr, 12687 /*ExceptionRanges=*/nullptr, 12688 /*NumExceptions=*/0, 12689 /*NoexceptExpr=*/nullptr, 12690 /*ExceptionSpecTokens=*/nullptr, 12691 /*DeclsInPrototype=*/None, 12692 Loc, Loc, D), 12693 DS.getAttributes(), 12694 SourceLocation()); 12695 D.SetIdentifier(&II, Loc); 12696 12697 // Insert this function into translation-unit scope. 12698 12699 DeclContext *PrevDC = CurContext; 12700 CurContext = Context.getTranslationUnitDecl(); 12701 12702 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12703 FD->setImplicit(); 12704 12705 CurContext = PrevDC; 12706 12707 AddKnownFunctionAttributes(FD); 12708 12709 return FD; 12710 } 12711 12712 /// \brief Adds any function attributes that we know a priori based on 12713 /// the declaration of this function. 12714 /// 12715 /// These attributes can apply both to implicitly-declared builtins 12716 /// (like __builtin___printf_chk) or to library-declared functions 12717 /// like NSLog or printf. 12718 /// 12719 /// We need to check for duplicate attributes both here and where user-written 12720 /// attributes are applied to declarations. 12721 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12722 if (FD->isInvalidDecl()) 12723 return; 12724 12725 // If this is a built-in function, map its builtin attributes to 12726 // actual attributes. 12727 if (unsigned BuiltinID = FD->getBuiltinID()) { 12728 // Handle printf-formatting attributes. 12729 unsigned FormatIdx; 12730 bool HasVAListArg; 12731 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12732 if (!FD->hasAttr<FormatAttr>()) { 12733 const char *fmt = "printf"; 12734 unsigned int NumParams = FD->getNumParams(); 12735 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12736 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12737 fmt = "NSString"; 12738 FD->addAttr(FormatAttr::CreateImplicit(Context, 12739 &Context.Idents.get(fmt), 12740 FormatIdx+1, 12741 HasVAListArg ? 0 : FormatIdx+2, 12742 FD->getLocation())); 12743 } 12744 } 12745 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12746 HasVAListArg)) { 12747 if (!FD->hasAttr<FormatAttr>()) 12748 FD->addAttr(FormatAttr::CreateImplicit(Context, 12749 &Context.Idents.get("scanf"), 12750 FormatIdx+1, 12751 HasVAListArg ? 0 : FormatIdx+2, 12752 FD->getLocation())); 12753 } 12754 12755 // Mark const if we don't care about errno and that is the only 12756 // thing preventing the function from being const. This allows 12757 // IRgen to use LLVM intrinsics for such functions. 12758 if (!getLangOpts().MathErrno && 12759 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12760 if (!FD->hasAttr<ConstAttr>()) 12761 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12762 } 12763 12764 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12765 !FD->hasAttr<ReturnsTwiceAttr>()) 12766 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12767 FD->getLocation())); 12768 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12769 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12770 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12771 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12772 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12773 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12774 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12775 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12776 // Add the appropriate attribute, depending on the CUDA compilation mode 12777 // and which target the builtin belongs to. For example, during host 12778 // compilation, aux builtins are __device__, while the rest are __host__. 12779 if (getLangOpts().CUDAIsDevice != 12780 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12781 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12782 else 12783 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12784 } 12785 } 12786 12787 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12788 // throw, add an implicit nothrow attribute to any extern "C" function we come 12789 // across. 12790 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12791 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12792 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12793 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12794 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12795 } 12796 12797 IdentifierInfo *Name = FD->getIdentifier(); 12798 if (!Name) 12799 return; 12800 if ((!getLangOpts().CPlusPlus && 12801 FD->getDeclContext()->isTranslationUnit()) || 12802 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12803 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12804 LinkageSpecDecl::lang_c)) { 12805 // Okay: this could be a libc/libm/Objective-C function we know 12806 // about. 12807 } else 12808 return; 12809 12810 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12811 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12812 // target-specific builtins, perhaps? 12813 if (!FD->hasAttr<FormatAttr>()) 12814 FD->addAttr(FormatAttr::CreateImplicit(Context, 12815 &Context.Idents.get("printf"), 2, 12816 Name->isStr("vasprintf") ? 0 : 3, 12817 FD->getLocation())); 12818 } 12819 12820 if (Name->isStr("__CFStringMakeConstantString")) { 12821 // We already have a __builtin___CFStringMakeConstantString, 12822 // but builds that use -fno-constant-cfstrings don't go through that. 12823 if (!FD->hasAttr<FormatArgAttr>()) 12824 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12825 FD->getLocation())); 12826 } 12827 } 12828 12829 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12830 TypeSourceInfo *TInfo) { 12831 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12832 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12833 12834 if (!TInfo) { 12835 assert(D.isInvalidType() && "no declarator info for valid type"); 12836 TInfo = Context.getTrivialTypeSourceInfo(T); 12837 } 12838 12839 // Scope manipulation handled by caller. 12840 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12841 D.getLocStart(), 12842 D.getIdentifierLoc(), 12843 D.getIdentifier(), 12844 TInfo); 12845 12846 // Bail out immediately if we have an invalid declaration. 12847 if (D.isInvalidType()) { 12848 NewTD->setInvalidDecl(); 12849 return NewTD; 12850 } 12851 12852 if (D.getDeclSpec().isModulePrivateSpecified()) { 12853 if (CurContext->isFunctionOrMethod()) 12854 Diag(NewTD->getLocation(), diag::err_module_private_local) 12855 << 2 << NewTD->getDeclName() 12856 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12857 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12858 else 12859 NewTD->setModulePrivate(); 12860 } 12861 12862 // C++ [dcl.typedef]p8: 12863 // If the typedef declaration defines an unnamed class (or 12864 // enum), the first typedef-name declared by the declaration 12865 // to be that class type (or enum type) is used to denote the 12866 // class type (or enum type) for linkage purposes only. 12867 // We need to check whether the type was declared in the declaration. 12868 switch (D.getDeclSpec().getTypeSpecType()) { 12869 case TST_enum: 12870 case TST_struct: 12871 case TST_interface: 12872 case TST_union: 12873 case TST_class: { 12874 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12875 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12876 break; 12877 } 12878 12879 default: 12880 break; 12881 } 12882 12883 return NewTD; 12884 } 12885 12886 /// \brief Check that this is a valid underlying type for an enum declaration. 12887 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12888 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12889 QualType T = TI->getType(); 12890 12891 if (T->isDependentType()) 12892 return false; 12893 12894 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12895 if (BT->isInteger()) 12896 return false; 12897 12898 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12899 return true; 12900 } 12901 12902 /// Check whether this is a valid redeclaration of a previous enumeration. 12903 /// \return true if the redeclaration was invalid. 12904 bool Sema::CheckEnumRedeclaration( 12905 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12906 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12907 bool IsFixed = !EnumUnderlyingTy.isNull(); 12908 12909 if (IsScoped != Prev->isScoped()) { 12910 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12911 << Prev->isScoped(); 12912 Diag(Prev->getLocation(), diag::note_previous_declaration); 12913 return true; 12914 } 12915 12916 if (IsFixed && Prev->isFixed()) { 12917 if (!EnumUnderlyingTy->isDependentType() && 12918 !Prev->getIntegerType()->isDependentType() && 12919 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12920 Prev->getIntegerType())) { 12921 // TODO: Highlight the underlying type of the redeclaration. 12922 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12923 << EnumUnderlyingTy << Prev->getIntegerType(); 12924 Diag(Prev->getLocation(), diag::note_previous_declaration) 12925 << Prev->getIntegerTypeRange(); 12926 return true; 12927 } 12928 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12929 ; 12930 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12931 ; 12932 } else if (IsFixed != Prev->isFixed()) { 12933 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12934 << Prev->isFixed(); 12935 Diag(Prev->getLocation(), diag::note_previous_declaration); 12936 return true; 12937 } 12938 12939 return false; 12940 } 12941 12942 /// \brief Get diagnostic %select index for tag kind for 12943 /// redeclaration diagnostic message. 12944 /// WARNING: Indexes apply to particular diagnostics only! 12945 /// 12946 /// \returns diagnostic %select index. 12947 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12948 switch (Tag) { 12949 case TTK_Struct: return 0; 12950 case TTK_Interface: return 1; 12951 case TTK_Class: return 2; 12952 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12953 } 12954 } 12955 12956 /// \brief Determine if tag kind is a class-key compatible with 12957 /// class for redeclaration (class, struct, or __interface). 12958 /// 12959 /// \returns true iff the tag kind is compatible. 12960 static bool isClassCompatTagKind(TagTypeKind Tag) 12961 { 12962 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12963 } 12964 12965 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12966 TagTypeKind TTK) { 12967 if (isa<TypedefDecl>(PrevDecl)) 12968 return NTK_Typedef; 12969 else if (isa<TypeAliasDecl>(PrevDecl)) 12970 return NTK_TypeAlias; 12971 else if (isa<ClassTemplateDecl>(PrevDecl)) 12972 return NTK_Template; 12973 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12974 return NTK_TypeAliasTemplate; 12975 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12976 return NTK_TemplateTemplateArgument; 12977 switch (TTK) { 12978 case TTK_Struct: 12979 case TTK_Interface: 12980 case TTK_Class: 12981 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12982 case TTK_Union: 12983 return NTK_NonUnion; 12984 case TTK_Enum: 12985 return NTK_NonEnum; 12986 } 12987 llvm_unreachable("invalid TTK"); 12988 } 12989 12990 /// \brief Determine whether a tag with a given kind is acceptable 12991 /// as a redeclaration of the given tag declaration. 12992 /// 12993 /// \returns true if the new tag kind is acceptable, false otherwise. 12994 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12995 TagTypeKind NewTag, bool isDefinition, 12996 SourceLocation NewTagLoc, 12997 const IdentifierInfo *Name) { 12998 // C++ [dcl.type.elab]p3: 12999 // The class-key or enum keyword present in the 13000 // elaborated-type-specifier shall agree in kind with the 13001 // declaration to which the name in the elaborated-type-specifier 13002 // refers. This rule also applies to the form of 13003 // elaborated-type-specifier that declares a class-name or 13004 // friend class since it can be construed as referring to the 13005 // definition of the class. Thus, in any 13006 // elaborated-type-specifier, the enum keyword shall be used to 13007 // refer to an enumeration (7.2), the union class-key shall be 13008 // used to refer to a union (clause 9), and either the class or 13009 // struct class-key shall be used to refer to a class (clause 9) 13010 // declared using the class or struct class-key. 13011 TagTypeKind OldTag = Previous->getTagKind(); 13012 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13013 if (OldTag == NewTag) 13014 return true; 13015 13016 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13017 // Warn about the struct/class tag mismatch. 13018 bool isTemplate = false; 13019 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13020 isTemplate = Record->getDescribedClassTemplate(); 13021 13022 if (inTemplateInstantiation()) { 13023 // In a template instantiation, do not offer fix-its for tag mismatches 13024 // since they usually mess up the template instead of fixing the problem. 13025 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13026 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13027 << getRedeclDiagFromTagKind(OldTag); 13028 return true; 13029 } 13030 13031 if (isDefinition) { 13032 // On definitions, check previous tags and issue a fix-it for each 13033 // one that doesn't match the current tag. 13034 if (Previous->getDefinition()) { 13035 // Don't suggest fix-its for redefinitions. 13036 return true; 13037 } 13038 13039 bool previousMismatch = false; 13040 for (auto I : Previous->redecls()) { 13041 if (I->getTagKind() != NewTag) { 13042 if (!previousMismatch) { 13043 previousMismatch = true; 13044 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13045 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13046 << getRedeclDiagFromTagKind(I->getTagKind()); 13047 } 13048 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13049 << getRedeclDiagFromTagKind(NewTag) 13050 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13051 TypeWithKeyword::getTagTypeKindName(NewTag)); 13052 } 13053 } 13054 return true; 13055 } 13056 13057 // Check for a previous definition. If current tag and definition 13058 // are same type, do nothing. If no definition, but disagree with 13059 // with previous tag type, give a warning, but no fix-it. 13060 const TagDecl *Redecl = Previous->getDefinition() ? 13061 Previous->getDefinition() : Previous; 13062 if (Redecl->getTagKind() == NewTag) { 13063 return true; 13064 } 13065 13066 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13067 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13068 << getRedeclDiagFromTagKind(OldTag); 13069 Diag(Redecl->getLocation(), diag::note_previous_use); 13070 13071 // If there is a previous definition, suggest a fix-it. 13072 if (Previous->getDefinition()) { 13073 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13074 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13075 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13076 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13077 } 13078 13079 return true; 13080 } 13081 return false; 13082 } 13083 13084 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13085 /// from an outer enclosing namespace or file scope inside a friend declaration. 13086 /// This should provide the commented out code in the following snippet: 13087 /// namespace N { 13088 /// struct X; 13089 /// namespace M { 13090 /// struct Y { friend struct /*N::*/ X; }; 13091 /// } 13092 /// } 13093 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13094 SourceLocation NameLoc) { 13095 // While the decl is in a namespace, do repeated lookup of that name and see 13096 // if we get the same namespace back. If we do not, continue until 13097 // translation unit scope, at which point we have a fully qualified NNS. 13098 SmallVector<IdentifierInfo *, 4> Namespaces; 13099 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13100 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13101 // This tag should be declared in a namespace, which can only be enclosed by 13102 // other namespaces. Bail if there's an anonymous namespace in the chain. 13103 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13104 if (!Namespace || Namespace->isAnonymousNamespace()) 13105 return FixItHint(); 13106 IdentifierInfo *II = Namespace->getIdentifier(); 13107 Namespaces.push_back(II); 13108 NamedDecl *Lookup = SemaRef.LookupSingleName( 13109 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13110 if (Lookup == Namespace) 13111 break; 13112 } 13113 13114 // Once we have all the namespaces, reverse them to go outermost first, and 13115 // build an NNS. 13116 SmallString<64> Insertion; 13117 llvm::raw_svector_ostream OS(Insertion); 13118 if (DC->isTranslationUnit()) 13119 OS << "::"; 13120 std::reverse(Namespaces.begin(), Namespaces.end()); 13121 for (auto *II : Namespaces) 13122 OS << II->getName() << "::"; 13123 return FixItHint::CreateInsertion(NameLoc, Insertion); 13124 } 13125 13126 /// \brief Determine whether a tag originally declared in context \p OldDC can 13127 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13128 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13129 /// using-declaration). 13130 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13131 DeclContext *NewDC) { 13132 OldDC = OldDC->getRedeclContext(); 13133 NewDC = NewDC->getRedeclContext(); 13134 13135 if (OldDC->Equals(NewDC)) 13136 return true; 13137 13138 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13139 // encloses the other). 13140 if (S.getLangOpts().MSVCCompat && 13141 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13142 return true; 13143 13144 return false; 13145 } 13146 13147 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13148 /// former case, Name will be non-null. In the later case, Name will be null. 13149 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13150 /// reference/declaration/definition of a tag. 13151 /// 13152 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13153 /// trailing-type-specifier) other than one in an alias-declaration. 13154 /// 13155 /// \param SkipBody If non-null, will be set to indicate if the caller should 13156 /// skip the definition of this tag and treat it as if it were a declaration. 13157 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13158 SourceLocation KWLoc, CXXScopeSpec &SS, 13159 IdentifierInfo *Name, SourceLocation NameLoc, 13160 AttributeList *Attr, AccessSpecifier AS, 13161 SourceLocation ModulePrivateLoc, 13162 MultiTemplateParamsArg TemplateParameterLists, 13163 bool &OwnedDecl, bool &IsDependent, 13164 SourceLocation ScopedEnumKWLoc, 13165 bool ScopedEnumUsesClassTag, 13166 TypeResult UnderlyingType, 13167 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13168 SkipBodyInfo *SkipBody) { 13169 // If this is not a definition, it must have a name. 13170 IdentifierInfo *OrigName = Name; 13171 assert((Name != nullptr || TUK == TUK_Definition) && 13172 "Nameless record must be a definition!"); 13173 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13174 13175 OwnedDecl = false; 13176 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13177 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13178 13179 // FIXME: Check member specializations more carefully. 13180 bool isMemberSpecialization = false; 13181 bool Invalid = false; 13182 13183 // We only need to do this matching if we have template parameters 13184 // or a scope specifier, which also conveniently avoids this work 13185 // for non-C++ cases. 13186 if (TemplateParameterLists.size() > 0 || 13187 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13188 if (TemplateParameterList *TemplateParams = 13189 MatchTemplateParametersToScopeSpecifier( 13190 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13191 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13192 if (Kind == TTK_Enum) { 13193 Diag(KWLoc, diag::err_enum_template); 13194 return nullptr; 13195 } 13196 13197 if (TemplateParams->size() > 0) { 13198 // This is a declaration or definition of a class template (which may 13199 // be a member of another template). 13200 13201 if (Invalid) 13202 return nullptr; 13203 13204 OwnedDecl = false; 13205 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13206 SS, Name, NameLoc, Attr, 13207 TemplateParams, AS, 13208 ModulePrivateLoc, 13209 /*FriendLoc*/SourceLocation(), 13210 TemplateParameterLists.size()-1, 13211 TemplateParameterLists.data(), 13212 SkipBody); 13213 return Result.get(); 13214 } else { 13215 // The "template<>" header is extraneous. 13216 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13217 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13218 isMemberSpecialization = true; 13219 } 13220 } 13221 } 13222 13223 // Figure out the underlying type if this a enum declaration. We need to do 13224 // this early, because it's needed to detect if this is an incompatible 13225 // redeclaration. 13226 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13227 bool EnumUnderlyingIsImplicit = false; 13228 13229 if (Kind == TTK_Enum) { 13230 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13231 // No underlying type explicitly specified, or we failed to parse the 13232 // type, default to int. 13233 EnumUnderlying = Context.IntTy.getTypePtr(); 13234 else if (UnderlyingType.get()) { 13235 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13236 // integral type; any cv-qualification is ignored. 13237 TypeSourceInfo *TI = nullptr; 13238 GetTypeFromParser(UnderlyingType.get(), &TI); 13239 EnumUnderlying = TI; 13240 13241 if (CheckEnumUnderlyingType(TI)) 13242 // Recover by falling back to int. 13243 EnumUnderlying = Context.IntTy.getTypePtr(); 13244 13245 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13246 UPPC_FixedUnderlyingType)) 13247 EnumUnderlying = Context.IntTy.getTypePtr(); 13248 13249 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13250 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13251 // Microsoft enums are always of int type. 13252 EnumUnderlying = Context.IntTy.getTypePtr(); 13253 EnumUnderlyingIsImplicit = true; 13254 } 13255 } 13256 } 13257 13258 DeclContext *SearchDC = CurContext; 13259 DeclContext *DC = CurContext; 13260 bool isStdBadAlloc = false; 13261 bool isStdAlignValT = false; 13262 13263 RedeclarationKind Redecl = ForRedeclaration; 13264 if (TUK == TUK_Friend || TUK == TUK_Reference) 13265 Redecl = NotForRedeclaration; 13266 13267 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13268 /// implemented asks for structural equivalence checking, the returned decl 13269 /// here is passed back to the parser, allowing the tag body to be parsed. 13270 auto createTagFromNewDecl = [&]() -> TagDecl * { 13271 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13272 // If there is an identifier, use the location of the identifier as the 13273 // location of the decl, otherwise use the location of the struct/union 13274 // keyword. 13275 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13276 TagDecl *New = nullptr; 13277 13278 if (Kind == TTK_Enum) { 13279 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13280 ScopedEnum, ScopedEnumUsesClassTag, 13281 !EnumUnderlying.isNull()); 13282 // If this is an undefined enum, bail. 13283 if (TUK != TUK_Definition && !Invalid) 13284 return nullptr; 13285 if (EnumUnderlying) { 13286 EnumDecl *ED = cast<EnumDecl>(New); 13287 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13288 ED->setIntegerTypeSourceInfo(TI); 13289 else 13290 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13291 ED->setPromotionType(ED->getIntegerType()); 13292 } 13293 } else { // struct/union 13294 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13295 nullptr); 13296 } 13297 13298 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13299 // Add alignment attributes if necessary; these attributes are checked 13300 // when the ASTContext lays out the structure. 13301 // 13302 // It is important for implementing the correct semantics that this 13303 // happen here (in ActOnTag). The #pragma pack stack is 13304 // maintained as a result of parser callbacks which can occur at 13305 // many points during the parsing of a struct declaration (because 13306 // the #pragma tokens are effectively skipped over during the 13307 // parsing of the struct). 13308 if (TUK == TUK_Definition) { 13309 AddAlignmentAttributesForRecord(RD); 13310 AddMsStructLayoutForRecord(RD); 13311 } 13312 } 13313 New->setLexicalDeclContext(CurContext); 13314 return New; 13315 }; 13316 13317 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13318 if (Name && SS.isNotEmpty()) { 13319 // We have a nested-name tag ('struct foo::bar'). 13320 13321 // Check for invalid 'foo::'. 13322 if (SS.isInvalid()) { 13323 Name = nullptr; 13324 goto CreateNewDecl; 13325 } 13326 13327 // If this is a friend or a reference to a class in a dependent 13328 // context, don't try to make a decl for it. 13329 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13330 DC = computeDeclContext(SS, false); 13331 if (!DC) { 13332 IsDependent = true; 13333 return nullptr; 13334 } 13335 } else { 13336 DC = computeDeclContext(SS, true); 13337 if (!DC) { 13338 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13339 << SS.getRange(); 13340 return nullptr; 13341 } 13342 } 13343 13344 if (RequireCompleteDeclContext(SS, DC)) 13345 return nullptr; 13346 13347 SearchDC = DC; 13348 // Look-up name inside 'foo::'. 13349 LookupQualifiedName(Previous, DC); 13350 13351 if (Previous.isAmbiguous()) 13352 return nullptr; 13353 13354 if (Previous.empty()) { 13355 // Name lookup did not find anything. However, if the 13356 // nested-name-specifier refers to the current instantiation, 13357 // and that current instantiation has any dependent base 13358 // classes, we might find something at instantiation time: treat 13359 // this as a dependent elaborated-type-specifier. 13360 // But this only makes any sense for reference-like lookups. 13361 if (Previous.wasNotFoundInCurrentInstantiation() && 13362 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13363 IsDependent = true; 13364 return nullptr; 13365 } 13366 13367 // A tag 'foo::bar' must already exist. 13368 Diag(NameLoc, diag::err_not_tag_in_scope) 13369 << Kind << Name << DC << SS.getRange(); 13370 Name = nullptr; 13371 Invalid = true; 13372 goto CreateNewDecl; 13373 } 13374 } else if (Name) { 13375 // C++14 [class.mem]p14: 13376 // If T is the name of a class, then each of the following shall have a 13377 // name different from T: 13378 // -- every member of class T that is itself a type 13379 if (TUK != TUK_Reference && TUK != TUK_Friend && 13380 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13381 return nullptr; 13382 13383 // If this is a named struct, check to see if there was a previous forward 13384 // declaration or definition. 13385 // FIXME: We're looking into outer scopes here, even when we 13386 // shouldn't be. Doing so can result in ambiguities that we 13387 // shouldn't be diagnosing. 13388 LookupName(Previous, S); 13389 13390 // When declaring or defining a tag, ignore ambiguities introduced 13391 // by types using'ed into this scope. 13392 if (Previous.isAmbiguous() && 13393 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13394 LookupResult::Filter F = Previous.makeFilter(); 13395 while (F.hasNext()) { 13396 NamedDecl *ND = F.next(); 13397 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13398 SearchDC->getRedeclContext())) 13399 F.erase(); 13400 } 13401 F.done(); 13402 } 13403 13404 // C++11 [namespace.memdef]p3: 13405 // If the name in a friend declaration is neither qualified nor 13406 // a template-id and the declaration is a function or an 13407 // elaborated-type-specifier, the lookup to determine whether 13408 // the entity has been previously declared shall not consider 13409 // any scopes outside the innermost enclosing namespace. 13410 // 13411 // MSVC doesn't implement the above rule for types, so a friend tag 13412 // declaration may be a redeclaration of a type declared in an enclosing 13413 // scope. They do implement this rule for friend functions. 13414 // 13415 // Does it matter that this should be by scope instead of by 13416 // semantic context? 13417 if (!Previous.empty() && TUK == TUK_Friend) { 13418 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13419 LookupResult::Filter F = Previous.makeFilter(); 13420 bool FriendSawTagOutsideEnclosingNamespace = false; 13421 while (F.hasNext()) { 13422 NamedDecl *ND = F.next(); 13423 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13424 if (DC->isFileContext() && 13425 !EnclosingNS->Encloses(ND->getDeclContext())) { 13426 if (getLangOpts().MSVCCompat) 13427 FriendSawTagOutsideEnclosingNamespace = true; 13428 else 13429 F.erase(); 13430 } 13431 } 13432 F.done(); 13433 13434 // Diagnose this MSVC extension in the easy case where lookup would have 13435 // unambiguously found something outside the enclosing namespace. 13436 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13437 NamedDecl *ND = Previous.getFoundDecl(); 13438 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13439 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13440 } 13441 } 13442 13443 // Note: there used to be some attempt at recovery here. 13444 if (Previous.isAmbiguous()) 13445 return nullptr; 13446 13447 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13448 // FIXME: This makes sure that we ignore the contexts associated 13449 // with C structs, unions, and enums when looking for a matching 13450 // tag declaration or definition. See the similar lookup tweak 13451 // in Sema::LookupName; is there a better way to deal with this? 13452 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13453 SearchDC = SearchDC->getParent(); 13454 } 13455 } 13456 13457 if (Previous.isSingleResult() && 13458 Previous.getFoundDecl()->isTemplateParameter()) { 13459 // Maybe we will complain about the shadowed template parameter. 13460 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13461 // Just pretend that we didn't see the previous declaration. 13462 Previous.clear(); 13463 } 13464 13465 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13466 DC->Equals(getStdNamespace())) { 13467 if (Name->isStr("bad_alloc")) { 13468 // This is a declaration of or a reference to "std::bad_alloc". 13469 isStdBadAlloc = true; 13470 13471 // If std::bad_alloc has been implicitly declared (but made invisible to 13472 // name lookup), fill in this implicit declaration as the previous 13473 // declaration, so that the declarations get chained appropriately. 13474 if (Previous.empty() && StdBadAlloc) 13475 Previous.addDecl(getStdBadAlloc()); 13476 } else if (Name->isStr("align_val_t")) { 13477 isStdAlignValT = true; 13478 if (Previous.empty() && StdAlignValT) 13479 Previous.addDecl(getStdAlignValT()); 13480 } 13481 } 13482 13483 // If we didn't find a previous declaration, and this is a reference 13484 // (or friend reference), move to the correct scope. In C++, we 13485 // also need to do a redeclaration lookup there, just in case 13486 // there's a shadow friend decl. 13487 if (Name && Previous.empty() && 13488 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13489 if (Invalid) goto CreateNewDecl; 13490 assert(SS.isEmpty()); 13491 13492 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13493 // C++ [basic.scope.pdecl]p5: 13494 // -- for an elaborated-type-specifier of the form 13495 // 13496 // class-key identifier 13497 // 13498 // if the elaborated-type-specifier is used in the 13499 // decl-specifier-seq or parameter-declaration-clause of a 13500 // function defined in namespace scope, the identifier is 13501 // declared as a class-name in the namespace that contains 13502 // the declaration; otherwise, except as a friend 13503 // declaration, the identifier is declared in the smallest 13504 // non-class, non-function-prototype scope that contains the 13505 // declaration. 13506 // 13507 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13508 // C structs and unions. 13509 // 13510 // It is an error in C++ to declare (rather than define) an enum 13511 // type, including via an elaborated type specifier. We'll 13512 // diagnose that later; for now, declare the enum in the same 13513 // scope as we would have picked for any other tag type. 13514 // 13515 // GNU C also supports this behavior as part of its incomplete 13516 // enum types extension, while GNU C++ does not. 13517 // 13518 // Find the context where we'll be declaring the tag. 13519 // FIXME: We would like to maintain the current DeclContext as the 13520 // lexical context, 13521 SearchDC = getTagInjectionContext(SearchDC); 13522 13523 // Find the scope where we'll be declaring the tag. 13524 S = getTagInjectionScope(S, getLangOpts()); 13525 } else { 13526 assert(TUK == TUK_Friend); 13527 // C++ [namespace.memdef]p3: 13528 // If a friend declaration in a non-local class first declares a 13529 // class or function, the friend class or function is a member of 13530 // the innermost enclosing namespace. 13531 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13532 } 13533 13534 // In C++, we need to do a redeclaration lookup to properly 13535 // diagnose some problems. 13536 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13537 // hidden declaration so that we don't get ambiguity errors when using a 13538 // type declared by an elaborated-type-specifier. In C that is not correct 13539 // and we should instead merge compatible types found by lookup. 13540 if (getLangOpts().CPlusPlus) { 13541 Previous.setRedeclarationKind(ForRedeclaration); 13542 LookupQualifiedName(Previous, SearchDC); 13543 } else { 13544 Previous.setRedeclarationKind(ForRedeclaration); 13545 LookupName(Previous, S); 13546 } 13547 } 13548 13549 // If we have a known previous declaration to use, then use it. 13550 if (Previous.empty() && SkipBody && SkipBody->Previous) 13551 Previous.addDecl(SkipBody->Previous); 13552 13553 if (!Previous.empty()) { 13554 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13555 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13556 13557 // It's okay to have a tag decl in the same scope as a typedef 13558 // which hides a tag decl in the same scope. Finding this 13559 // insanity with a redeclaration lookup can only actually happen 13560 // in C++. 13561 // 13562 // This is also okay for elaborated-type-specifiers, which is 13563 // technically forbidden by the current standard but which is 13564 // okay according to the likely resolution of an open issue; 13565 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13566 if (getLangOpts().CPlusPlus) { 13567 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13568 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13569 TagDecl *Tag = TT->getDecl(); 13570 if (Tag->getDeclName() == Name && 13571 Tag->getDeclContext()->getRedeclContext() 13572 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13573 PrevDecl = Tag; 13574 Previous.clear(); 13575 Previous.addDecl(Tag); 13576 Previous.resolveKind(); 13577 } 13578 } 13579 } 13580 } 13581 13582 // If this is a redeclaration of a using shadow declaration, it must 13583 // declare a tag in the same context. In MSVC mode, we allow a 13584 // redefinition if either context is within the other. 13585 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13586 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13587 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13588 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13589 !(OldTag && isAcceptableTagRedeclContext( 13590 *this, OldTag->getDeclContext(), SearchDC))) { 13591 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13592 Diag(Shadow->getTargetDecl()->getLocation(), 13593 diag::note_using_decl_target); 13594 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13595 << 0; 13596 // Recover by ignoring the old declaration. 13597 Previous.clear(); 13598 goto CreateNewDecl; 13599 } 13600 } 13601 13602 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13603 // If this is a use of a previous tag, or if the tag is already declared 13604 // in the same scope (so that the definition/declaration completes or 13605 // rementions the tag), reuse the decl. 13606 if (TUK == TUK_Reference || TUK == TUK_Friend || 13607 isDeclInScope(DirectPrevDecl, SearchDC, S, 13608 SS.isNotEmpty() || isMemberSpecialization)) { 13609 // Make sure that this wasn't declared as an enum and now used as a 13610 // struct or something similar. 13611 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13612 TUK == TUK_Definition, KWLoc, 13613 Name)) { 13614 bool SafeToContinue 13615 = (PrevTagDecl->getTagKind() != TTK_Enum && 13616 Kind != TTK_Enum); 13617 if (SafeToContinue) 13618 Diag(KWLoc, diag::err_use_with_wrong_tag) 13619 << Name 13620 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13621 PrevTagDecl->getKindName()); 13622 else 13623 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13624 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13625 13626 if (SafeToContinue) 13627 Kind = PrevTagDecl->getTagKind(); 13628 else { 13629 // Recover by making this an anonymous redefinition. 13630 Name = nullptr; 13631 Previous.clear(); 13632 Invalid = true; 13633 } 13634 } 13635 13636 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13637 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13638 13639 // If this is an elaborated-type-specifier for a scoped enumeration, 13640 // the 'class' keyword is not necessary and not permitted. 13641 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13642 if (ScopedEnum) 13643 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13644 << PrevEnum->isScoped() 13645 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13646 return PrevTagDecl; 13647 } 13648 13649 QualType EnumUnderlyingTy; 13650 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13651 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13652 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13653 EnumUnderlyingTy = QualType(T, 0); 13654 13655 // All conflicts with previous declarations are recovered by 13656 // returning the previous declaration, unless this is a definition, 13657 // in which case we want the caller to bail out. 13658 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13659 ScopedEnum, EnumUnderlyingTy, 13660 EnumUnderlyingIsImplicit, PrevEnum)) 13661 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13662 } 13663 13664 // C++11 [class.mem]p1: 13665 // A member shall not be declared twice in the member-specification, 13666 // except that a nested class or member class template can be declared 13667 // and then later defined. 13668 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13669 S->isDeclScope(PrevDecl)) { 13670 Diag(NameLoc, diag::ext_member_redeclared); 13671 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13672 } 13673 13674 if (!Invalid) { 13675 // If this is a use, just return the declaration we found, unless 13676 // we have attributes. 13677 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13678 if (Attr) { 13679 // FIXME: Diagnose these attributes. For now, we create a new 13680 // declaration to hold them. 13681 } else if (TUK == TUK_Reference && 13682 (PrevTagDecl->getFriendObjectKind() == 13683 Decl::FOK_Undeclared || 13684 PrevDecl->getOwningModule() != getCurrentModule()) && 13685 SS.isEmpty()) { 13686 // This declaration is a reference to an existing entity, but 13687 // has different visibility from that entity: it either makes 13688 // a friend visible or it makes a type visible in a new module. 13689 // In either case, create a new declaration. We only do this if 13690 // the declaration would have meant the same thing if no prior 13691 // declaration were found, that is, if it was found in the same 13692 // scope where we would have injected a declaration. 13693 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13694 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13695 return PrevTagDecl; 13696 // This is in the injected scope, create a new declaration in 13697 // that scope. 13698 S = getTagInjectionScope(S, getLangOpts()); 13699 } else { 13700 return PrevTagDecl; 13701 } 13702 } 13703 13704 // Diagnose attempts to redefine a tag. 13705 if (TUK == TUK_Definition) { 13706 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13707 // If we're defining a specialization and the previous definition 13708 // is from an implicit instantiation, don't emit an error 13709 // here; we'll catch this in the general case below. 13710 bool IsExplicitSpecializationAfterInstantiation = false; 13711 if (isMemberSpecialization) { 13712 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13713 IsExplicitSpecializationAfterInstantiation = 13714 RD->getTemplateSpecializationKind() != 13715 TSK_ExplicitSpecialization; 13716 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13717 IsExplicitSpecializationAfterInstantiation = 13718 ED->getTemplateSpecializationKind() != 13719 TSK_ExplicitSpecialization; 13720 } 13721 13722 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 13723 // not keep more that one definition around (merge them). However, 13724 // ensure the decl passes the structural compatibility check in 13725 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 13726 NamedDecl *Hidden = nullptr; 13727 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 13728 // There is a definition of this tag, but it is not visible. We 13729 // explicitly make use of C++'s one definition rule here, and 13730 // assume that this definition is identical to the hidden one 13731 // we already have. Make the existing definition visible and 13732 // use it in place of this one. 13733 if (!getLangOpts().CPlusPlus) { 13734 // Postpone making the old definition visible until after we 13735 // complete parsing the new one and do the structural 13736 // comparison. 13737 SkipBody->CheckSameAsPrevious = true; 13738 SkipBody->New = createTagFromNewDecl(); 13739 SkipBody->Previous = Hidden; 13740 } else { 13741 SkipBody->ShouldSkip = true; 13742 makeMergedDefinitionVisible(Hidden); 13743 } 13744 return Def; 13745 } else if (!IsExplicitSpecializationAfterInstantiation) { 13746 // A redeclaration in function prototype scope in C isn't 13747 // visible elsewhere, so merely issue a warning. 13748 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13749 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13750 else 13751 Diag(NameLoc, diag::err_redefinition) << Name; 13752 notePreviousDefinition(Def, 13753 NameLoc.isValid() ? NameLoc : KWLoc); 13754 // If this is a redefinition, recover by making this 13755 // struct be anonymous, which will make any later 13756 // references get the previous definition. 13757 Name = nullptr; 13758 Previous.clear(); 13759 Invalid = true; 13760 } 13761 } else { 13762 // If the type is currently being defined, complain 13763 // about a nested redefinition. 13764 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13765 if (TD->isBeingDefined()) { 13766 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13767 Diag(PrevTagDecl->getLocation(), 13768 diag::note_previous_definition); 13769 Name = nullptr; 13770 Previous.clear(); 13771 Invalid = true; 13772 } 13773 } 13774 13775 // Okay, this is definition of a previously declared or referenced 13776 // tag. We're going to create a new Decl for it. 13777 } 13778 13779 // Okay, we're going to make a redeclaration. If this is some kind 13780 // of reference, make sure we build the redeclaration in the same DC 13781 // as the original, and ignore the current access specifier. 13782 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13783 SearchDC = PrevTagDecl->getDeclContext(); 13784 AS = AS_none; 13785 } 13786 } 13787 // If we get here we have (another) forward declaration or we 13788 // have a definition. Just create a new decl. 13789 13790 } else { 13791 // If we get here, this is a definition of a new tag type in a nested 13792 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13793 // new decl/type. We set PrevDecl to NULL so that the entities 13794 // have distinct types. 13795 Previous.clear(); 13796 } 13797 // If we get here, we're going to create a new Decl. If PrevDecl 13798 // is non-NULL, it's a definition of the tag declared by 13799 // PrevDecl. If it's NULL, we have a new definition. 13800 13801 // Otherwise, PrevDecl is not a tag, but was found with tag 13802 // lookup. This is only actually possible in C++, where a few 13803 // things like templates still live in the tag namespace. 13804 } else { 13805 // Use a better diagnostic if an elaborated-type-specifier 13806 // found the wrong kind of type on the first 13807 // (non-redeclaration) lookup. 13808 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13809 !Previous.isForRedeclaration()) { 13810 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13811 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13812 << Kind; 13813 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13814 Invalid = true; 13815 13816 // Otherwise, only diagnose if the declaration is in scope. 13817 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13818 SS.isNotEmpty() || isMemberSpecialization)) { 13819 // do nothing 13820 13821 // Diagnose implicit declarations introduced by elaborated types. 13822 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13823 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13824 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13825 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13826 Invalid = true; 13827 13828 // Otherwise it's a declaration. Call out a particularly common 13829 // case here. 13830 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13831 unsigned Kind = 0; 13832 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13833 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13834 << Name << Kind << TND->getUnderlyingType(); 13835 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13836 Invalid = true; 13837 13838 // Otherwise, diagnose. 13839 } else { 13840 // The tag name clashes with something else in the target scope, 13841 // issue an error and recover by making this tag be anonymous. 13842 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13843 notePreviousDefinition(PrevDecl, NameLoc); 13844 Name = nullptr; 13845 Invalid = true; 13846 } 13847 13848 // The existing declaration isn't relevant to us; we're in a 13849 // new scope, so clear out the previous declaration. 13850 Previous.clear(); 13851 } 13852 } 13853 13854 CreateNewDecl: 13855 13856 TagDecl *PrevDecl = nullptr; 13857 if (Previous.isSingleResult()) 13858 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13859 13860 // If there is an identifier, use the location of the identifier as the 13861 // location of the decl, otherwise use the location of the struct/union 13862 // keyword. 13863 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13864 13865 // Otherwise, create a new declaration. If there is a previous 13866 // declaration of the same entity, the two will be linked via 13867 // PrevDecl. 13868 TagDecl *New; 13869 13870 bool IsForwardReference = false; 13871 if (Kind == TTK_Enum) { 13872 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13873 // enum X { A, B, C } D; D should chain to X. 13874 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13875 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13876 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13877 13878 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13879 StdAlignValT = cast<EnumDecl>(New); 13880 13881 // If this is an undefined enum, warn. 13882 if (TUK != TUK_Definition && !Invalid) { 13883 TagDecl *Def; 13884 if (!EnumUnderlyingIsImplicit && 13885 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13886 cast<EnumDecl>(New)->isFixed()) { 13887 // C++0x: 7.2p2: opaque-enum-declaration. 13888 // Conflicts are diagnosed above. Do nothing. 13889 } 13890 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13891 Diag(Loc, diag::ext_forward_ref_enum_def) 13892 << New; 13893 Diag(Def->getLocation(), diag::note_previous_definition); 13894 } else { 13895 unsigned DiagID = diag::ext_forward_ref_enum; 13896 if (getLangOpts().MSVCCompat) 13897 DiagID = diag::ext_ms_forward_ref_enum; 13898 else if (getLangOpts().CPlusPlus) 13899 DiagID = diag::err_forward_ref_enum; 13900 Diag(Loc, DiagID); 13901 13902 // If this is a forward-declared reference to an enumeration, make a 13903 // note of it; we won't actually be introducing the declaration into 13904 // the declaration context. 13905 if (TUK == TUK_Reference) 13906 IsForwardReference = true; 13907 } 13908 } 13909 13910 if (EnumUnderlying) { 13911 EnumDecl *ED = cast<EnumDecl>(New); 13912 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13913 ED->setIntegerTypeSourceInfo(TI); 13914 else 13915 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13916 ED->setPromotionType(ED->getIntegerType()); 13917 } 13918 } else { 13919 // struct/union/class 13920 13921 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13922 // struct X { int A; } D; D should chain to X. 13923 if (getLangOpts().CPlusPlus) { 13924 // FIXME: Look for a way to use RecordDecl for simple structs. 13925 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13926 cast_or_null<CXXRecordDecl>(PrevDecl)); 13927 13928 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13929 StdBadAlloc = cast<CXXRecordDecl>(New); 13930 } else 13931 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13932 cast_or_null<RecordDecl>(PrevDecl)); 13933 } 13934 13935 // C++11 [dcl.type]p3: 13936 // A type-specifier-seq shall not define a class or enumeration [...]. 13937 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 13938 TUK == TUK_Definition) { 13939 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13940 << Context.getTagDeclType(New); 13941 Invalid = true; 13942 } 13943 13944 // Maybe add qualifier info. 13945 if (SS.isNotEmpty()) { 13946 if (SS.isSet()) { 13947 // If this is either a declaration or a definition, check the 13948 // nested-name-specifier against the current context. We don't do this 13949 // for explicit specializations, because they have similar checking 13950 // (with more specific diagnostics) in the call to 13951 // CheckMemberSpecialization, below. 13952 if (!isMemberSpecialization && 13953 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13954 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13955 Invalid = true; 13956 13957 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13958 if (TemplateParameterLists.size() > 0) { 13959 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13960 } 13961 } 13962 else 13963 Invalid = true; 13964 } 13965 13966 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13967 // Add alignment attributes if necessary; these attributes are checked when 13968 // the ASTContext lays out the structure. 13969 // 13970 // It is important for implementing the correct semantics that this 13971 // happen here (in ActOnTag). The #pragma pack stack is 13972 // maintained as a result of parser callbacks which can occur at 13973 // many points during the parsing of a struct declaration (because 13974 // the #pragma tokens are effectively skipped over during the 13975 // parsing of the struct). 13976 if (TUK == TUK_Definition) { 13977 AddAlignmentAttributesForRecord(RD); 13978 AddMsStructLayoutForRecord(RD); 13979 } 13980 } 13981 13982 if (ModulePrivateLoc.isValid()) { 13983 if (isMemberSpecialization) 13984 Diag(New->getLocation(), diag::err_module_private_specialization) 13985 << 2 13986 << FixItHint::CreateRemoval(ModulePrivateLoc); 13987 // __module_private__ does not apply to local classes. However, we only 13988 // diagnose this as an error when the declaration specifiers are 13989 // freestanding. Here, we just ignore the __module_private__. 13990 else if (!SearchDC->isFunctionOrMethod()) 13991 New->setModulePrivate(); 13992 } 13993 13994 // If this is a specialization of a member class (of a class template), 13995 // check the specialization. 13996 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13997 Invalid = true; 13998 13999 // If we're declaring or defining a tag in function prototype scope in C, 14000 // note that this type can only be used within the function and add it to 14001 // the list of decls to inject into the function definition scope. 14002 if ((Name || Kind == TTK_Enum) && 14003 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14004 if (getLangOpts().CPlusPlus) { 14005 // C++ [dcl.fct]p6: 14006 // Types shall not be defined in return or parameter types. 14007 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14008 Diag(Loc, diag::err_type_defined_in_param_type) 14009 << Name; 14010 Invalid = true; 14011 } 14012 } else if (!PrevDecl) { 14013 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14014 } 14015 } 14016 14017 if (Invalid) 14018 New->setInvalidDecl(); 14019 14020 // Set the lexical context. If the tag has a C++ scope specifier, the 14021 // lexical context will be different from the semantic context. 14022 New->setLexicalDeclContext(CurContext); 14023 14024 // Mark this as a friend decl if applicable. 14025 // In Microsoft mode, a friend declaration also acts as a forward 14026 // declaration so we always pass true to setObjectOfFriendDecl to make 14027 // the tag name visible. 14028 if (TUK == TUK_Friend) 14029 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14030 14031 // Set the access specifier. 14032 if (!Invalid && SearchDC->isRecord()) 14033 SetMemberAccessSpecifier(New, PrevDecl, AS); 14034 14035 if (TUK == TUK_Definition) 14036 New->startDefinition(); 14037 14038 if (Attr) 14039 ProcessDeclAttributeList(S, New, Attr); 14040 AddPragmaAttributes(S, New); 14041 14042 // If this has an identifier, add it to the scope stack. 14043 if (TUK == TUK_Friend) { 14044 // We might be replacing an existing declaration in the lookup tables; 14045 // if so, borrow its access specifier. 14046 if (PrevDecl) 14047 New->setAccess(PrevDecl->getAccess()); 14048 14049 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14050 DC->makeDeclVisibleInContext(New); 14051 if (Name) // can be null along some error paths 14052 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14053 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14054 } else if (Name) { 14055 S = getNonFieldDeclScope(S); 14056 PushOnScopeChains(New, S, !IsForwardReference); 14057 if (IsForwardReference) 14058 SearchDC->makeDeclVisibleInContext(New); 14059 } else { 14060 CurContext->addDecl(New); 14061 } 14062 14063 // If this is the C FILE type, notify the AST context. 14064 if (IdentifierInfo *II = New->getIdentifier()) 14065 if (!New->isInvalidDecl() && 14066 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14067 II->isStr("FILE")) 14068 Context.setFILEDecl(New); 14069 14070 if (PrevDecl) 14071 mergeDeclAttributes(New, PrevDecl); 14072 14073 // If there's a #pragma GCC visibility in scope, set the visibility of this 14074 // record. 14075 AddPushedVisibilityAttribute(New); 14076 14077 if (isMemberSpecialization && !New->isInvalidDecl()) 14078 CompleteMemberSpecialization(New, Previous); 14079 14080 OwnedDecl = true; 14081 // In C++, don't return an invalid declaration. We can't recover well from 14082 // the cases where we make the type anonymous. 14083 if (Invalid && getLangOpts().CPlusPlus) { 14084 if (New->isBeingDefined()) 14085 if (auto RD = dyn_cast<RecordDecl>(New)) 14086 RD->completeDefinition(); 14087 return nullptr; 14088 } else { 14089 return New; 14090 } 14091 } 14092 14093 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14094 AdjustDeclIfTemplate(TagD); 14095 TagDecl *Tag = cast<TagDecl>(TagD); 14096 14097 // Enter the tag context. 14098 PushDeclContext(S, Tag); 14099 14100 ActOnDocumentableDecl(TagD); 14101 14102 // If there's a #pragma GCC visibility in scope, set the visibility of this 14103 // record. 14104 AddPushedVisibilityAttribute(Tag); 14105 } 14106 14107 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14108 SkipBodyInfo &SkipBody) { 14109 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14110 return false; 14111 14112 // Make the previous decl visible. 14113 makeMergedDefinitionVisible(SkipBody.Previous); 14114 return true; 14115 } 14116 14117 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14118 assert(isa<ObjCContainerDecl>(IDecl) && 14119 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14120 DeclContext *OCD = cast<DeclContext>(IDecl); 14121 assert(getContainingDC(OCD) == CurContext && 14122 "The next DeclContext should be lexically contained in the current one."); 14123 CurContext = OCD; 14124 return IDecl; 14125 } 14126 14127 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14128 SourceLocation FinalLoc, 14129 bool IsFinalSpelledSealed, 14130 SourceLocation LBraceLoc) { 14131 AdjustDeclIfTemplate(TagD); 14132 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14133 14134 FieldCollector->StartClass(); 14135 14136 if (!Record->getIdentifier()) 14137 return; 14138 14139 if (FinalLoc.isValid()) 14140 Record->addAttr(new (Context) 14141 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14142 14143 // C++ [class]p2: 14144 // [...] The class-name is also inserted into the scope of the 14145 // class itself; this is known as the injected-class-name. For 14146 // purposes of access checking, the injected-class-name is treated 14147 // as if it were a public member name. 14148 CXXRecordDecl *InjectedClassName 14149 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14150 Record->getLocStart(), Record->getLocation(), 14151 Record->getIdentifier(), 14152 /*PrevDecl=*/nullptr, 14153 /*DelayTypeCreation=*/true); 14154 Context.getTypeDeclType(InjectedClassName, Record); 14155 InjectedClassName->setImplicit(); 14156 InjectedClassName->setAccess(AS_public); 14157 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14158 InjectedClassName->setDescribedClassTemplate(Template); 14159 PushOnScopeChains(InjectedClassName, S); 14160 assert(InjectedClassName->isInjectedClassName() && 14161 "Broken injected-class-name"); 14162 } 14163 14164 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14165 SourceRange BraceRange) { 14166 AdjustDeclIfTemplate(TagD); 14167 TagDecl *Tag = cast<TagDecl>(TagD); 14168 Tag->setBraceRange(BraceRange); 14169 14170 // Make sure we "complete" the definition even it is invalid. 14171 if (Tag->isBeingDefined()) { 14172 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14173 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14174 RD->completeDefinition(); 14175 } 14176 14177 if (isa<CXXRecordDecl>(Tag)) { 14178 FieldCollector->FinishClass(); 14179 } 14180 14181 // Exit this scope of this tag's definition. 14182 PopDeclContext(); 14183 14184 if (getCurLexicalContext()->isObjCContainer() && 14185 Tag->getDeclContext()->isFileContext()) 14186 Tag->setTopLevelDeclInObjCContainer(); 14187 14188 // Notify the consumer that we've defined a tag. 14189 if (!Tag->isInvalidDecl()) 14190 Consumer.HandleTagDeclDefinition(Tag); 14191 } 14192 14193 void Sema::ActOnObjCContainerFinishDefinition() { 14194 // Exit this scope of this interface definition. 14195 PopDeclContext(); 14196 } 14197 14198 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14199 assert(DC == CurContext && "Mismatch of container contexts"); 14200 OriginalLexicalContext = DC; 14201 ActOnObjCContainerFinishDefinition(); 14202 } 14203 14204 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14205 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14206 OriginalLexicalContext = nullptr; 14207 } 14208 14209 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14210 AdjustDeclIfTemplate(TagD); 14211 TagDecl *Tag = cast<TagDecl>(TagD); 14212 Tag->setInvalidDecl(); 14213 14214 // Make sure we "complete" the definition even it is invalid. 14215 if (Tag->isBeingDefined()) { 14216 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14217 RD->completeDefinition(); 14218 } 14219 14220 // We're undoing ActOnTagStartDefinition here, not 14221 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14222 // the FieldCollector. 14223 14224 PopDeclContext(); 14225 } 14226 14227 // Note that FieldName may be null for anonymous bitfields. 14228 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14229 IdentifierInfo *FieldName, 14230 QualType FieldTy, bool IsMsStruct, 14231 Expr *BitWidth, bool *ZeroWidth) { 14232 // Default to true; that shouldn't confuse checks for emptiness 14233 if (ZeroWidth) 14234 *ZeroWidth = true; 14235 14236 // C99 6.7.2.1p4 - verify the field type. 14237 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14238 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14239 // Handle incomplete types with specific error. 14240 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14241 return ExprError(); 14242 if (FieldName) 14243 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14244 << FieldName << FieldTy << BitWidth->getSourceRange(); 14245 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14246 << FieldTy << BitWidth->getSourceRange(); 14247 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14248 UPPC_BitFieldWidth)) 14249 return ExprError(); 14250 14251 // If the bit-width is type- or value-dependent, don't try to check 14252 // it now. 14253 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14254 return BitWidth; 14255 14256 llvm::APSInt Value; 14257 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14258 if (ICE.isInvalid()) 14259 return ICE; 14260 BitWidth = ICE.get(); 14261 14262 if (Value != 0 && ZeroWidth) 14263 *ZeroWidth = false; 14264 14265 // Zero-width bitfield is ok for anonymous field. 14266 if (Value == 0 && FieldName) 14267 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14268 14269 if (Value.isSigned() && Value.isNegative()) { 14270 if (FieldName) 14271 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14272 << FieldName << Value.toString(10); 14273 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14274 << Value.toString(10); 14275 } 14276 14277 if (!FieldTy->isDependentType()) { 14278 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14279 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14280 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14281 14282 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14283 // ABI. 14284 bool CStdConstraintViolation = 14285 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14286 bool MSBitfieldViolation = 14287 Value.ugt(TypeStorageSize) && 14288 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14289 if (CStdConstraintViolation || MSBitfieldViolation) { 14290 unsigned DiagWidth = 14291 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14292 if (FieldName) 14293 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14294 << FieldName << (unsigned)Value.getZExtValue() 14295 << !CStdConstraintViolation << DiagWidth; 14296 14297 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14298 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14299 << DiagWidth; 14300 } 14301 14302 // Warn on types where the user might conceivably expect to get all 14303 // specified bits as value bits: that's all integral types other than 14304 // 'bool'. 14305 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14306 if (FieldName) 14307 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14308 << FieldName << (unsigned)Value.getZExtValue() 14309 << (unsigned)TypeWidth; 14310 else 14311 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14312 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14313 } 14314 } 14315 14316 return BitWidth; 14317 } 14318 14319 /// ActOnField - Each field of a C struct/union is passed into this in order 14320 /// to create a FieldDecl object for it. 14321 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14322 Declarator &D, Expr *BitfieldWidth) { 14323 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14324 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14325 /*InitStyle=*/ICIS_NoInit, AS_public); 14326 return Res; 14327 } 14328 14329 /// HandleField - Analyze a field of a C struct or a C++ data member. 14330 /// 14331 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14332 SourceLocation DeclStart, 14333 Declarator &D, Expr *BitWidth, 14334 InClassInitStyle InitStyle, 14335 AccessSpecifier AS) { 14336 if (D.isDecompositionDeclarator()) { 14337 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14338 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14339 << Decomp.getSourceRange(); 14340 return nullptr; 14341 } 14342 14343 IdentifierInfo *II = D.getIdentifier(); 14344 SourceLocation Loc = DeclStart; 14345 if (II) Loc = D.getIdentifierLoc(); 14346 14347 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14348 QualType T = TInfo->getType(); 14349 if (getLangOpts().CPlusPlus) { 14350 CheckExtraCXXDefaultArguments(D); 14351 14352 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14353 UPPC_DataMemberType)) { 14354 D.setInvalidType(); 14355 T = Context.IntTy; 14356 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14357 } 14358 } 14359 14360 // TR 18037 does not allow fields to be declared with address spaces. 14361 if (T.getQualifiers().hasAddressSpace()) { 14362 Diag(Loc, diag::err_field_with_address_space); 14363 D.setInvalidType(); 14364 } 14365 14366 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14367 // used as structure or union field: image, sampler, event or block types. 14368 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14369 T->isSamplerT() || T->isBlockPointerType())) { 14370 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14371 D.setInvalidType(); 14372 } 14373 14374 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14375 14376 if (D.getDeclSpec().isInlineSpecified()) 14377 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14378 << getLangOpts().CPlusPlus1z; 14379 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14380 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14381 diag::err_invalid_thread) 14382 << DeclSpec::getSpecifierName(TSCS); 14383 14384 // Check to see if this name was declared as a member previously 14385 NamedDecl *PrevDecl = nullptr; 14386 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14387 LookupName(Previous, S); 14388 switch (Previous.getResultKind()) { 14389 case LookupResult::Found: 14390 case LookupResult::FoundUnresolvedValue: 14391 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14392 break; 14393 14394 case LookupResult::FoundOverloaded: 14395 PrevDecl = Previous.getRepresentativeDecl(); 14396 break; 14397 14398 case LookupResult::NotFound: 14399 case LookupResult::NotFoundInCurrentInstantiation: 14400 case LookupResult::Ambiguous: 14401 break; 14402 } 14403 Previous.suppressDiagnostics(); 14404 14405 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14406 // Maybe we will complain about the shadowed template parameter. 14407 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14408 // Just pretend that we didn't see the previous declaration. 14409 PrevDecl = nullptr; 14410 } 14411 14412 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14413 PrevDecl = nullptr; 14414 14415 bool Mutable 14416 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14417 SourceLocation TSSL = D.getLocStart(); 14418 FieldDecl *NewFD 14419 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14420 TSSL, AS, PrevDecl, &D); 14421 14422 if (NewFD->isInvalidDecl()) 14423 Record->setInvalidDecl(); 14424 14425 if (D.getDeclSpec().isModulePrivateSpecified()) 14426 NewFD->setModulePrivate(); 14427 14428 if (NewFD->isInvalidDecl() && PrevDecl) { 14429 // Don't introduce NewFD into scope; there's already something 14430 // with the same name in the same scope. 14431 } else if (II) { 14432 PushOnScopeChains(NewFD, S); 14433 } else 14434 Record->addDecl(NewFD); 14435 14436 return NewFD; 14437 } 14438 14439 /// \brief Build a new FieldDecl and check its well-formedness. 14440 /// 14441 /// This routine builds a new FieldDecl given the fields name, type, 14442 /// record, etc. \p PrevDecl should refer to any previous declaration 14443 /// with the same name and in the same scope as the field to be 14444 /// created. 14445 /// 14446 /// \returns a new FieldDecl. 14447 /// 14448 /// \todo The Declarator argument is a hack. It will be removed once 14449 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14450 TypeSourceInfo *TInfo, 14451 RecordDecl *Record, SourceLocation Loc, 14452 bool Mutable, Expr *BitWidth, 14453 InClassInitStyle InitStyle, 14454 SourceLocation TSSL, 14455 AccessSpecifier AS, NamedDecl *PrevDecl, 14456 Declarator *D) { 14457 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14458 bool InvalidDecl = false; 14459 if (D) InvalidDecl = D->isInvalidType(); 14460 14461 // If we receive a broken type, recover by assuming 'int' and 14462 // marking this declaration as invalid. 14463 if (T.isNull()) { 14464 InvalidDecl = true; 14465 T = Context.IntTy; 14466 } 14467 14468 QualType EltTy = Context.getBaseElementType(T); 14469 if (!EltTy->isDependentType()) { 14470 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14471 // Fields of incomplete type force their record to be invalid. 14472 Record->setInvalidDecl(); 14473 InvalidDecl = true; 14474 } else { 14475 NamedDecl *Def; 14476 EltTy->isIncompleteType(&Def); 14477 if (Def && Def->isInvalidDecl()) { 14478 Record->setInvalidDecl(); 14479 InvalidDecl = true; 14480 } 14481 } 14482 } 14483 14484 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14485 if (BitWidth && getLangOpts().OpenCL) { 14486 Diag(Loc, diag::err_opencl_bitfields); 14487 InvalidDecl = true; 14488 } 14489 14490 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14491 // than a variably modified type. 14492 if (!InvalidDecl && T->isVariablyModifiedType()) { 14493 bool SizeIsNegative; 14494 llvm::APSInt Oversized; 14495 14496 TypeSourceInfo *FixedTInfo = 14497 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14498 SizeIsNegative, 14499 Oversized); 14500 if (FixedTInfo) { 14501 Diag(Loc, diag::warn_illegal_constant_array_size); 14502 TInfo = FixedTInfo; 14503 T = FixedTInfo->getType(); 14504 } else { 14505 if (SizeIsNegative) 14506 Diag(Loc, diag::err_typecheck_negative_array_size); 14507 else if (Oversized.getBoolValue()) 14508 Diag(Loc, diag::err_array_too_large) 14509 << Oversized.toString(10); 14510 else 14511 Diag(Loc, diag::err_typecheck_field_variable_size); 14512 InvalidDecl = true; 14513 } 14514 } 14515 14516 // Fields can not have abstract class types 14517 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14518 diag::err_abstract_type_in_decl, 14519 AbstractFieldType)) 14520 InvalidDecl = true; 14521 14522 bool ZeroWidth = false; 14523 if (InvalidDecl) 14524 BitWidth = nullptr; 14525 // If this is declared as a bit-field, check the bit-field. 14526 if (BitWidth) { 14527 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14528 &ZeroWidth).get(); 14529 if (!BitWidth) { 14530 InvalidDecl = true; 14531 BitWidth = nullptr; 14532 ZeroWidth = false; 14533 } 14534 } 14535 14536 // Check that 'mutable' is consistent with the type of the declaration. 14537 if (!InvalidDecl && Mutable) { 14538 unsigned DiagID = 0; 14539 if (T->isReferenceType()) 14540 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14541 : diag::err_mutable_reference; 14542 else if (T.isConstQualified()) 14543 DiagID = diag::err_mutable_const; 14544 14545 if (DiagID) { 14546 SourceLocation ErrLoc = Loc; 14547 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14548 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14549 Diag(ErrLoc, DiagID); 14550 if (DiagID != diag::ext_mutable_reference) { 14551 Mutable = false; 14552 InvalidDecl = true; 14553 } 14554 } 14555 } 14556 14557 // C++11 [class.union]p8 (DR1460): 14558 // At most one variant member of a union may have a 14559 // brace-or-equal-initializer. 14560 if (InitStyle != ICIS_NoInit) 14561 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14562 14563 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14564 BitWidth, Mutable, InitStyle); 14565 if (InvalidDecl) 14566 NewFD->setInvalidDecl(); 14567 14568 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14569 Diag(Loc, diag::err_duplicate_member) << II; 14570 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14571 NewFD->setInvalidDecl(); 14572 } 14573 14574 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14575 if (Record->isUnion()) { 14576 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14577 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14578 if (RDecl->getDefinition()) { 14579 // C++ [class.union]p1: An object of a class with a non-trivial 14580 // constructor, a non-trivial copy constructor, a non-trivial 14581 // destructor, or a non-trivial copy assignment operator 14582 // cannot be a member of a union, nor can an array of such 14583 // objects. 14584 if (CheckNontrivialField(NewFD)) 14585 NewFD->setInvalidDecl(); 14586 } 14587 } 14588 14589 // C++ [class.union]p1: If a union contains a member of reference type, 14590 // the program is ill-formed, except when compiling with MSVC extensions 14591 // enabled. 14592 if (EltTy->isReferenceType()) { 14593 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14594 diag::ext_union_member_of_reference_type : 14595 diag::err_union_member_of_reference_type) 14596 << NewFD->getDeclName() << EltTy; 14597 if (!getLangOpts().MicrosoftExt) 14598 NewFD->setInvalidDecl(); 14599 } 14600 } 14601 } 14602 14603 // FIXME: We need to pass in the attributes given an AST 14604 // representation, not a parser representation. 14605 if (D) { 14606 // FIXME: The current scope is almost... but not entirely... correct here. 14607 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14608 14609 if (NewFD->hasAttrs()) 14610 CheckAlignasUnderalignment(NewFD); 14611 } 14612 14613 // In auto-retain/release, infer strong retension for fields of 14614 // retainable type. 14615 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14616 NewFD->setInvalidDecl(); 14617 14618 if (T.isObjCGCWeak()) 14619 Diag(Loc, diag::warn_attribute_weak_on_field); 14620 14621 NewFD->setAccess(AS); 14622 return NewFD; 14623 } 14624 14625 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14626 assert(FD); 14627 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14628 14629 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14630 return false; 14631 14632 QualType EltTy = Context.getBaseElementType(FD->getType()); 14633 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14634 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14635 if (RDecl->getDefinition()) { 14636 // We check for copy constructors before constructors 14637 // because otherwise we'll never get complaints about 14638 // copy constructors. 14639 14640 CXXSpecialMember member = CXXInvalid; 14641 // We're required to check for any non-trivial constructors. Since the 14642 // implicit default constructor is suppressed if there are any 14643 // user-declared constructors, we just need to check that there is a 14644 // trivial default constructor and a trivial copy constructor. (We don't 14645 // worry about move constructors here, since this is a C++98 check.) 14646 if (RDecl->hasNonTrivialCopyConstructor()) 14647 member = CXXCopyConstructor; 14648 else if (!RDecl->hasTrivialDefaultConstructor()) 14649 member = CXXDefaultConstructor; 14650 else if (RDecl->hasNonTrivialCopyAssignment()) 14651 member = CXXCopyAssignment; 14652 else if (RDecl->hasNonTrivialDestructor()) 14653 member = CXXDestructor; 14654 14655 if (member != CXXInvalid) { 14656 if (!getLangOpts().CPlusPlus11 && 14657 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14658 // Objective-C++ ARC: it is an error to have a non-trivial field of 14659 // a union. However, system headers in Objective-C programs 14660 // occasionally have Objective-C lifetime objects within unions, 14661 // and rather than cause the program to fail, we make those 14662 // members unavailable. 14663 SourceLocation Loc = FD->getLocation(); 14664 if (getSourceManager().isInSystemHeader(Loc)) { 14665 if (!FD->hasAttr<UnavailableAttr>()) 14666 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14667 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14668 return false; 14669 } 14670 } 14671 14672 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14673 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14674 diag::err_illegal_union_or_anon_struct_member) 14675 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14676 DiagnoseNontrivial(RDecl, member); 14677 return !getLangOpts().CPlusPlus11; 14678 } 14679 } 14680 } 14681 14682 return false; 14683 } 14684 14685 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14686 /// AST enum value. 14687 static ObjCIvarDecl::AccessControl 14688 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14689 switch (ivarVisibility) { 14690 default: llvm_unreachable("Unknown visitibility kind"); 14691 case tok::objc_private: return ObjCIvarDecl::Private; 14692 case tok::objc_public: return ObjCIvarDecl::Public; 14693 case tok::objc_protected: return ObjCIvarDecl::Protected; 14694 case tok::objc_package: return ObjCIvarDecl::Package; 14695 } 14696 } 14697 14698 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14699 /// in order to create an IvarDecl object for it. 14700 Decl *Sema::ActOnIvar(Scope *S, 14701 SourceLocation DeclStart, 14702 Declarator &D, Expr *BitfieldWidth, 14703 tok::ObjCKeywordKind Visibility) { 14704 14705 IdentifierInfo *II = D.getIdentifier(); 14706 Expr *BitWidth = (Expr*)BitfieldWidth; 14707 SourceLocation Loc = DeclStart; 14708 if (II) Loc = D.getIdentifierLoc(); 14709 14710 // FIXME: Unnamed fields can be handled in various different ways, for 14711 // example, unnamed unions inject all members into the struct namespace! 14712 14713 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14714 QualType T = TInfo->getType(); 14715 14716 if (BitWidth) { 14717 // 6.7.2.1p3, 6.7.2.1p4 14718 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14719 if (!BitWidth) 14720 D.setInvalidType(); 14721 } else { 14722 // Not a bitfield. 14723 14724 // validate II. 14725 14726 } 14727 if (T->isReferenceType()) { 14728 Diag(Loc, diag::err_ivar_reference_type); 14729 D.setInvalidType(); 14730 } 14731 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14732 // than a variably modified type. 14733 else if (T->isVariablyModifiedType()) { 14734 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14735 D.setInvalidType(); 14736 } 14737 14738 // Get the visibility (access control) for this ivar. 14739 ObjCIvarDecl::AccessControl ac = 14740 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14741 : ObjCIvarDecl::None; 14742 // Must set ivar's DeclContext to its enclosing interface. 14743 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14744 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14745 return nullptr; 14746 ObjCContainerDecl *EnclosingContext; 14747 if (ObjCImplementationDecl *IMPDecl = 14748 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14749 if (LangOpts.ObjCRuntime.isFragile()) { 14750 // Case of ivar declared in an implementation. Context is that of its class. 14751 EnclosingContext = IMPDecl->getClassInterface(); 14752 assert(EnclosingContext && "Implementation has no class interface!"); 14753 } 14754 else 14755 EnclosingContext = EnclosingDecl; 14756 } else { 14757 if (ObjCCategoryDecl *CDecl = 14758 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14759 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14760 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14761 return nullptr; 14762 } 14763 } 14764 EnclosingContext = EnclosingDecl; 14765 } 14766 14767 // Construct the decl. 14768 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14769 DeclStart, Loc, II, T, 14770 TInfo, ac, (Expr *)BitfieldWidth); 14771 14772 if (II) { 14773 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14774 ForRedeclaration); 14775 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14776 && !isa<TagDecl>(PrevDecl)) { 14777 Diag(Loc, diag::err_duplicate_member) << II; 14778 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14779 NewID->setInvalidDecl(); 14780 } 14781 } 14782 14783 // Process attributes attached to the ivar. 14784 ProcessDeclAttributes(S, NewID, D); 14785 14786 if (D.isInvalidType()) 14787 NewID->setInvalidDecl(); 14788 14789 // In ARC, infer 'retaining' for ivars of retainable type. 14790 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14791 NewID->setInvalidDecl(); 14792 14793 if (D.getDeclSpec().isModulePrivateSpecified()) 14794 NewID->setModulePrivate(); 14795 14796 if (II) { 14797 // FIXME: When interfaces are DeclContexts, we'll need to add 14798 // these to the interface. 14799 S->AddDecl(NewID); 14800 IdResolver.AddDecl(NewID); 14801 } 14802 14803 if (LangOpts.ObjCRuntime.isNonFragile() && 14804 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14805 Diag(Loc, diag::warn_ivars_in_interface); 14806 14807 return NewID; 14808 } 14809 14810 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14811 /// class and class extensions. For every class \@interface and class 14812 /// extension \@interface, if the last ivar is a bitfield of any type, 14813 /// then add an implicit `char :0` ivar to the end of that interface. 14814 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14815 SmallVectorImpl<Decl *> &AllIvarDecls) { 14816 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14817 return; 14818 14819 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14820 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14821 14822 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14823 return; 14824 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14825 if (!ID) { 14826 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14827 if (!CD->IsClassExtension()) 14828 return; 14829 } 14830 // No need to add this to end of @implementation. 14831 else 14832 return; 14833 } 14834 // All conditions are met. Add a new bitfield to the tail end of ivars. 14835 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14836 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14837 14838 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14839 DeclLoc, DeclLoc, nullptr, 14840 Context.CharTy, 14841 Context.getTrivialTypeSourceInfo(Context.CharTy, 14842 DeclLoc), 14843 ObjCIvarDecl::Private, BW, 14844 true); 14845 AllIvarDecls.push_back(Ivar); 14846 } 14847 14848 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14849 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14850 SourceLocation RBrac, AttributeList *Attr) { 14851 assert(EnclosingDecl && "missing record or interface decl"); 14852 14853 // If this is an Objective-C @implementation or category and we have 14854 // new fields here we should reset the layout of the interface since 14855 // it will now change. 14856 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14857 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14858 switch (DC->getKind()) { 14859 default: break; 14860 case Decl::ObjCCategory: 14861 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14862 break; 14863 case Decl::ObjCImplementation: 14864 Context. 14865 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14866 break; 14867 } 14868 } 14869 14870 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14871 14872 // Start counting up the number of named members; make sure to include 14873 // members of anonymous structs and unions in the total. 14874 unsigned NumNamedMembers = 0; 14875 if (Record) { 14876 for (const auto *I : Record->decls()) { 14877 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14878 if (IFD->getDeclName()) 14879 ++NumNamedMembers; 14880 } 14881 } 14882 14883 // Verify that all the fields are okay. 14884 SmallVector<FieldDecl*, 32> RecFields; 14885 14886 bool ObjCFieldLifetimeErrReported = false; 14887 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14888 i != end; ++i) { 14889 FieldDecl *FD = cast<FieldDecl>(*i); 14890 14891 // Get the type for the field. 14892 const Type *FDTy = FD->getType().getTypePtr(); 14893 14894 if (!FD->isAnonymousStructOrUnion()) { 14895 // Remember all fields written by the user. 14896 RecFields.push_back(FD); 14897 } 14898 14899 // If the field is already invalid for some reason, don't emit more 14900 // diagnostics about it. 14901 if (FD->isInvalidDecl()) { 14902 EnclosingDecl->setInvalidDecl(); 14903 continue; 14904 } 14905 14906 // C99 6.7.2.1p2: 14907 // A structure or union shall not contain a member with 14908 // incomplete or function type (hence, a structure shall not 14909 // contain an instance of itself, but may contain a pointer to 14910 // an instance of itself), except that the last member of a 14911 // structure with more than one named member may have incomplete 14912 // array type; such a structure (and any union containing, 14913 // possibly recursively, a member that is such a structure) 14914 // shall not be a member of a structure or an element of an 14915 // array. 14916 if (FDTy->isFunctionType()) { 14917 // Field declared as a function. 14918 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14919 << FD->getDeclName(); 14920 FD->setInvalidDecl(); 14921 EnclosingDecl->setInvalidDecl(); 14922 continue; 14923 } else if (FDTy->isIncompleteArrayType() && Record && 14924 ((i + 1 == Fields.end() && !Record->isUnion()) || 14925 ((getLangOpts().MicrosoftExt || 14926 getLangOpts().CPlusPlus) && 14927 (i + 1 == Fields.end() || Record->isUnion())))) { 14928 // Flexible array member. 14929 // Microsoft and g++ is more permissive regarding flexible array. 14930 // It will accept flexible array in union and also 14931 // as the sole element of a struct/class. 14932 unsigned DiagID = 0; 14933 if (Record->isUnion()) 14934 DiagID = getLangOpts().MicrosoftExt 14935 ? diag::ext_flexible_array_union_ms 14936 : getLangOpts().CPlusPlus 14937 ? diag::ext_flexible_array_union_gnu 14938 : diag::err_flexible_array_union; 14939 else if (NumNamedMembers < 1) 14940 DiagID = getLangOpts().MicrosoftExt 14941 ? diag::ext_flexible_array_empty_aggregate_ms 14942 : getLangOpts().CPlusPlus 14943 ? diag::ext_flexible_array_empty_aggregate_gnu 14944 : diag::err_flexible_array_empty_aggregate; 14945 14946 if (DiagID) 14947 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14948 << Record->getTagKind(); 14949 // While the layout of types that contain virtual bases is not specified 14950 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14951 // virtual bases after the derived members. This would make a flexible 14952 // array member declared at the end of an object not adjacent to the end 14953 // of the type. 14954 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14955 if (RD->getNumVBases() != 0) 14956 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14957 << FD->getDeclName() << Record->getTagKind(); 14958 if (!getLangOpts().C99) 14959 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14960 << FD->getDeclName() << Record->getTagKind(); 14961 14962 // If the element type has a non-trivial destructor, we would not 14963 // implicitly destroy the elements, so disallow it for now. 14964 // 14965 // FIXME: GCC allows this. We should probably either implicitly delete 14966 // the destructor of the containing class, or just allow this. 14967 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14968 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14969 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14970 << FD->getDeclName() << FD->getType(); 14971 FD->setInvalidDecl(); 14972 EnclosingDecl->setInvalidDecl(); 14973 continue; 14974 } 14975 // Okay, we have a legal flexible array member at the end of the struct. 14976 Record->setHasFlexibleArrayMember(true); 14977 } else if (!FDTy->isDependentType() && 14978 RequireCompleteType(FD->getLocation(), FD->getType(), 14979 diag::err_field_incomplete)) { 14980 // Incomplete type 14981 FD->setInvalidDecl(); 14982 EnclosingDecl->setInvalidDecl(); 14983 continue; 14984 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14985 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14986 // A type which contains a flexible array member is considered to be a 14987 // flexible array member. 14988 Record->setHasFlexibleArrayMember(true); 14989 if (!Record->isUnion()) { 14990 // If this is a struct/class and this is not the last element, reject 14991 // it. Note that GCC supports variable sized arrays in the middle of 14992 // structures. 14993 if (i + 1 != Fields.end()) 14994 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14995 << FD->getDeclName() << FD->getType(); 14996 else { 14997 // We support flexible arrays at the end of structs in 14998 // other structs as an extension. 14999 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15000 << FD->getDeclName(); 15001 } 15002 } 15003 } 15004 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15005 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15006 diag::err_abstract_type_in_decl, 15007 AbstractIvarType)) { 15008 // Ivars can not have abstract class types 15009 FD->setInvalidDecl(); 15010 } 15011 if (Record && FDTTy->getDecl()->hasObjectMember()) 15012 Record->setHasObjectMember(true); 15013 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15014 Record->setHasVolatileMember(true); 15015 } else if (FDTy->isObjCObjectType()) { 15016 /// A field cannot be an Objective-c object 15017 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15018 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15019 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15020 FD->setType(T); 15021 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15022 Record && !ObjCFieldLifetimeErrReported && 15023 (!getLangOpts().CPlusPlus || Record->isUnion())) { 15024 // It's an error in ARC or Weak if a field has lifetime. 15025 // We don't want to report this in a system header, though, 15026 // so we just make the field unavailable. 15027 // FIXME: that's really not sufficient; we need to make the type 15028 // itself invalid to, say, initialize or copy. 15029 QualType T = FD->getType(); 15030 if (T.hasNonTrivialObjCLifetime()) { 15031 SourceLocation loc = FD->getLocation(); 15032 if (getSourceManager().isInSystemHeader(loc)) { 15033 if (!FD->hasAttr<UnavailableAttr>()) { 15034 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15035 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15036 } 15037 } else { 15038 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15039 << T->isBlockPointerType() << Record->getTagKind(); 15040 } 15041 ObjCFieldLifetimeErrReported = true; 15042 } 15043 } else if (getLangOpts().ObjC1 && 15044 getLangOpts().getGC() != LangOptions::NonGC && 15045 Record && !Record->hasObjectMember()) { 15046 if (FD->getType()->isObjCObjectPointerType() || 15047 FD->getType().isObjCGCStrong()) 15048 Record->setHasObjectMember(true); 15049 else if (Context.getAsArrayType(FD->getType())) { 15050 QualType BaseType = Context.getBaseElementType(FD->getType()); 15051 if (BaseType->isRecordType() && 15052 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15053 Record->setHasObjectMember(true); 15054 else if (BaseType->isObjCObjectPointerType() || 15055 BaseType.isObjCGCStrong()) 15056 Record->setHasObjectMember(true); 15057 } 15058 } 15059 if (Record && FD->getType().isVolatileQualified()) 15060 Record->setHasVolatileMember(true); 15061 // Keep track of the number of named members. 15062 if (FD->getIdentifier()) 15063 ++NumNamedMembers; 15064 } 15065 15066 // Okay, we successfully defined 'Record'. 15067 if (Record) { 15068 bool Completed = false; 15069 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15070 if (!CXXRecord->isInvalidDecl()) { 15071 // Set access bits correctly on the directly-declared conversions. 15072 for (CXXRecordDecl::conversion_iterator 15073 I = CXXRecord->conversion_begin(), 15074 E = CXXRecord->conversion_end(); I != E; ++I) 15075 I.setAccess((*I)->getAccess()); 15076 } 15077 15078 if (!CXXRecord->isDependentType()) { 15079 if (CXXRecord->hasUserDeclaredDestructor()) { 15080 // Adjust user-defined destructor exception spec. 15081 if (getLangOpts().CPlusPlus11) 15082 AdjustDestructorExceptionSpec(CXXRecord, 15083 CXXRecord->getDestructor()); 15084 } 15085 15086 if (!CXXRecord->isInvalidDecl()) { 15087 // Add any implicitly-declared members to this class. 15088 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15089 15090 // If we have virtual base classes, we may end up finding multiple 15091 // final overriders for a given virtual function. Check for this 15092 // problem now. 15093 if (CXXRecord->getNumVBases()) { 15094 CXXFinalOverriderMap FinalOverriders; 15095 CXXRecord->getFinalOverriders(FinalOverriders); 15096 15097 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15098 MEnd = FinalOverriders.end(); 15099 M != MEnd; ++M) { 15100 for (OverridingMethods::iterator SO = M->second.begin(), 15101 SOEnd = M->second.end(); 15102 SO != SOEnd; ++SO) { 15103 assert(SO->second.size() > 0 && 15104 "Virtual function without overridding functions?"); 15105 if (SO->second.size() == 1) 15106 continue; 15107 15108 // C++ [class.virtual]p2: 15109 // In a derived class, if a virtual member function of a base 15110 // class subobject has more than one final overrider the 15111 // program is ill-formed. 15112 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15113 << (const NamedDecl *)M->first << Record; 15114 Diag(M->first->getLocation(), 15115 diag::note_overridden_virtual_function); 15116 for (OverridingMethods::overriding_iterator 15117 OM = SO->second.begin(), 15118 OMEnd = SO->second.end(); 15119 OM != OMEnd; ++OM) 15120 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15121 << (const NamedDecl *)M->first << OM->Method->getParent(); 15122 15123 Record->setInvalidDecl(); 15124 } 15125 } 15126 CXXRecord->completeDefinition(&FinalOverriders); 15127 Completed = true; 15128 } 15129 } 15130 } 15131 } 15132 15133 if (!Completed) 15134 Record->completeDefinition(); 15135 15136 // We may have deferred checking for a deleted destructor. Check now. 15137 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15138 auto *Dtor = CXXRecord->getDestructor(); 15139 if (Dtor && Dtor->isImplicit() && 15140 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 15141 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15142 } 15143 15144 if (Record->hasAttrs()) { 15145 CheckAlignasUnderalignment(Record); 15146 15147 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15148 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15149 IA->getRange(), IA->getBestCase(), 15150 IA->getSemanticSpelling()); 15151 } 15152 15153 // Check if the structure/union declaration is a type that can have zero 15154 // size in C. For C this is a language extension, for C++ it may cause 15155 // compatibility problems. 15156 bool CheckForZeroSize; 15157 if (!getLangOpts().CPlusPlus) { 15158 CheckForZeroSize = true; 15159 } else { 15160 // For C++ filter out types that cannot be referenced in C code. 15161 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15162 CheckForZeroSize = 15163 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15164 !CXXRecord->isDependentType() && 15165 CXXRecord->isCLike(); 15166 } 15167 if (CheckForZeroSize) { 15168 bool ZeroSize = true; 15169 bool IsEmpty = true; 15170 unsigned NonBitFields = 0; 15171 for (RecordDecl::field_iterator I = Record->field_begin(), 15172 E = Record->field_end(); 15173 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15174 IsEmpty = false; 15175 if (I->isUnnamedBitfield()) { 15176 if (I->getBitWidthValue(Context) > 0) 15177 ZeroSize = false; 15178 } else { 15179 ++NonBitFields; 15180 QualType FieldType = I->getType(); 15181 if (FieldType->isIncompleteType() || 15182 !Context.getTypeSizeInChars(FieldType).isZero()) 15183 ZeroSize = false; 15184 } 15185 } 15186 15187 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15188 // allowed in C++, but warn if its declaration is inside 15189 // extern "C" block. 15190 if (ZeroSize) { 15191 Diag(RecLoc, getLangOpts().CPlusPlus ? 15192 diag::warn_zero_size_struct_union_in_extern_c : 15193 diag::warn_zero_size_struct_union_compat) 15194 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15195 } 15196 15197 // Structs without named members are extension in C (C99 6.7.2.1p7), 15198 // but are accepted by GCC. 15199 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15200 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15201 diag::ext_no_named_members_in_struct_union) 15202 << Record->isUnion(); 15203 } 15204 } 15205 } else { 15206 ObjCIvarDecl **ClsFields = 15207 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15208 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15209 ID->setEndOfDefinitionLoc(RBrac); 15210 // Add ivar's to class's DeclContext. 15211 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15212 ClsFields[i]->setLexicalDeclContext(ID); 15213 ID->addDecl(ClsFields[i]); 15214 } 15215 // Must enforce the rule that ivars in the base classes may not be 15216 // duplicates. 15217 if (ID->getSuperClass()) 15218 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15219 } else if (ObjCImplementationDecl *IMPDecl = 15220 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15221 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15222 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15223 // Ivar declared in @implementation never belongs to the implementation. 15224 // Only it is in implementation's lexical context. 15225 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15226 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15227 IMPDecl->setIvarLBraceLoc(LBrac); 15228 IMPDecl->setIvarRBraceLoc(RBrac); 15229 } else if (ObjCCategoryDecl *CDecl = 15230 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15231 // case of ivars in class extension; all other cases have been 15232 // reported as errors elsewhere. 15233 // FIXME. Class extension does not have a LocEnd field. 15234 // CDecl->setLocEnd(RBrac); 15235 // Add ivar's to class extension's DeclContext. 15236 // Diagnose redeclaration of private ivars. 15237 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15238 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15239 if (IDecl) { 15240 if (const ObjCIvarDecl *ClsIvar = 15241 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15242 Diag(ClsFields[i]->getLocation(), 15243 diag::err_duplicate_ivar_declaration); 15244 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15245 continue; 15246 } 15247 for (const auto *Ext : IDecl->known_extensions()) { 15248 if (const ObjCIvarDecl *ClsExtIvar 15249 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15250 Diag(ClsFields[i]->getLocation(), 15251 diag::err_duplicate_ivar_declaration); 15252 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15253 continue; 15254 } 15255 } 15256 } 15257 ClsFields[i]->setLexicalDeclContext(CDecl); 15258 CDecl->addDecl(ClsFields[i]); 15259 } 15260 CDecl->setIvarLBraceLoc(LBrac); 15261 CDecl->setIvarRBraceLoc(RBrac); 15262 } 15263 } 15264 15265 if (Attr) 15266 ProcessDeclAttributeList(S, Record, Attr); 15267 } 15268 15269 /// \brief Determine whether the given integral value is representable within 15270 /// the given type T. 15271 static bool isRepresentableIntegerValue(ASTContext &Context, 15272 llvm::APSInt &Value, 15273 QualType T) { 15274 assert(T->isIntegralType(Context) && "Integral type required!"); 15275 unsigned BitWidth = Context.getIntWidth(T); 15276 15277 if (Value.isUnsigned() || Value.isNonNegative()) { 15278 if (T->isSignedIntegerOrEnumerationType()) 15279 --BitWidth; 15280 return Value.getActiveBits() <= BitWidth; 15281 } 15282 return Value.getMinSignedBits() <= BitWidth; 15283 } 15284 15285 // \brief Given an integral type, return the next larger integral type 15286 // (or a NULL type of no such type exists). 15287 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15288 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15289 // enum checking below. 15290 assert(T->isIntegralType(Context) && "Integral type required!"); 15291 const unsigned NumTypes = 4; 15292 QualType SignedIntegralTypes[NumTypes] = { 15293 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15294 }; 15295 QualType UnsignedIntegralTypes[NumTypes] = { 15296 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15297 Context.UnsignedLongLongTy 15298 }; 15299 15300 unsigned BitWidth = Context.getTypeSize(T); 15301 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15302 : UnsignedIntegralTypes; 15303 for (unsigned I = 0; I != NumTypes; ++I) 15304 if (Context.getTypeSize(Types[I]) > BitWidth) 15305 return Types[I]; 15306 15307 return QualType(); 15308 } 15309 15310 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15311 EnumConstantDecl *LastEnumConst, 15312 SourceLocation IdLoc, 15313 IdentifierInfo *Id, 15314 Expr *Val) { 15315 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15316 llvm::APSInt EnumVal(IntWidth); 15317 QualType EltTy; 15318 15319 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15320 Val = nullptr; 15321 15322 if (Val) 15323 Val = DefaultLvalueConversion(Val).get(); 15324 15325 if (Val) { 15326 if (Enum->isDependentType() || Val->isTypeDependent()) 15327 EltTy = Context.DependentTy; 15328 else { 15329 SourceLocation ExpLoc; 15330 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15331 !getLangOpts().MSVCCompat) { 15332 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15333 // constant-expression in the enumerator-definition shall be a converted 15334 // constant expression of the underlying type. 15335 EltTy = Enum->getIntegerType(); 15336 ExprResult Converted = 15337 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15338 CCEK_Enumerator); 15339 if (Converted.isInvalid()) 15340 Val = nullptr; 15341 else 15342 Val = Converted.get(); 15343 } else if (!Val->isValueDependent() && 15344 !(Val = VerifyIntegerConstantExpression(Val, 15345 &EnumVal).get())) { 15346 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15347 } else { 15348 if (Enum->isFixed()) { 15349 EltTy = Enum->getIntegerType(); 15350 15351 // In Obj-C and Microsoft mode, require the enumeration value to be 15352 // representable in the underlying type of the enumeration. In C++11, 15353 // we perform a non-narrowing conversion as part of converted constant 15354 // expression checking. 15355 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15356 if (getLangOpts().MSVCCompat) { 15357 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15358 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15359 } else 15360 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15361 } else 15362 Val = ImpCastExprToType(Val, EltTy, 15363 EltTy->isBooleanType() ? 15364 CK_IntegralToBoolean : CK_IntegralCast) 15365 .get(); 15366 } else if (getLangOpts().CPlusPlus) { 15367 // C++11 [dcl.enum]p5: 15368 // If the underlying type is not fixed, the type of each enumerator 15369 // is the type of its initializing value: 15370 // - If an initializer is specified for an enumerator, the 15371 // initializing value has the same type as the expression. 15372 EltTy = Val->getType(); 15373 } else { 15374 // C99 6.7.2.2p2: 15375 // The expression that defines the value of an enumeration constant 15376 // shall be an integer constant expression that has a value 15377 // representable as an int. 15378 15379 // Complain if the value is not representable in an int. 15380 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15381 Diag(IdLoc, diag::ext_enum_value_not_int) 15382 << EnumVal.toString(10) << Val->getSourceRange() 15383 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15384 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15385 // Force the type of the expression to 'int'. 15386 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15387 } 15388 EltTy = Val->getType(); 15389 } 15390 } 15391 } 15392 } 15393 15394 if (!Val) { 15395 if (Enum->isDependentType()) 15396 EltTy = Context.DependentTy; 15397 else if (!LastEnumConst) { 15398 // C++0x [dcl.enum]p5: 15399 // If the underlying type is not fixed, the type of each enumerator 15400 // is the type of its initializing value: 15401 // - If no initializer is specified for the first enumerator, the 15402 // initializing value has an unspecified integral type. 15403 // 15404 // GCC uses 'int' for its unspecified integral type, as does 15405 // C99 6.7.2.2p3. 15406 if (Enum->isFixed()) { 15407 EltTy = Enum->getIntegerType(); 15408 } 15409 else { 15410 EltTy = Context.IntTy; 15411 } 15412 } else { 15413 // Assign the last value + 1. 15414 EnumVal = LastEnumConst->getInitVal(); 15415 ++EnumVal; 15416 EltTy = LastEnumConst->getType(); 15417 15418 // Check for overflow on increment. 15419 if (EnumVal < LastEnumConst->getInitVal()) { 15420 // C++0x [dcl.enum]p5: 15421 // If the underlying type is not fixed, the type of each enumerator 15422 // is the type of its initializing value: 15423 // 15424 // - Otherwise the type of the initializing value is the same as 15425 // the type of the initializing value of the preceding enumerator 15426 // unless the incremented value is not representable in that type, 15427 // in which case the type is an unspecified integral type 15428 // sufficient to contain the incremented value. If no such type 15429 // exists, the program is ill-formed. 15430 QualType T = getNextLargerIntegralType(Context, EltTy); 15431 if (T.isNull() || Enum->isFixed()) { 15432 // There is no integral type larger enough to represent this 15433 // value. Complain, then allow the value to wrap around. 15434 EnumVal = LastEnumConst->getInitVal(); 15435 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15436 ++EnumVal; 15437 if (Enum->isFixed()) 15438 // When the underlying type is fixed, this is ill-formed. 15439 Diag(IdLoc, diag::err_enumerator_wrapped) 15440 << EnumVal.toString(10) 15441 << EltTy; 15442 else 15443 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15444 << EnumVal.toString(10); 15445 } else { 15446 EltTy = T; 15447 } 15448 15449 // Retrieve the last enumerator's value, extent that type to the 15450 // type that is supposed to be large enough to represent the incremented 15451 // value, then increment. 15452 EnumVal = LastEnumConst->getInitVal(); 15453 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15454 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15455 ++EnumVal; 15456 15457 // If we're not in C++, diagnose the overflow of enumerator values, 15458 // which in C99 means that the enumerator value is not representable in 15459 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15460 // permits enumerator values that are representable in some larger 15461 // integral type. 15462 if (!getLangOpts().CPlusPlus && !T.isNull()) 15463 Diag(IdLoc, diag::warn_enum_value_overflow); 15464 } else if (!getLangOpts().CPlusPlus && 15465 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15466 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15467 Diag(IdLoc, diag::ext_enum_value_not_int) 15468 << EnumVal.toString(10) << 1; 15469 } 15470 } 15471 } 15472 15473 if (!EltTy->isDependentType()) { 15474 // Make the enumerator value match the signedness and size of the 15475 // enumerator's type. 15476 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15477 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15478 } 15479 15480 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15481 Val, EnumVal); 15482 } 15483 15484 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15485 SourceLocation IILoc) { 15486 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15487 !getLangOpts().CPlusPlus) 15488 return SkipBodyInfo(); 15489 15490 // We have an anonymous enum definition. Look up the first enumerator to 15491 // determine if we should merge the definition with an existing one and 15492 // skip the body. 15493 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15494 ForRedeclaration); 15495 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15496 if (!PrevECD) 15497 return SkipBodyInfo(); 15498 15499 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15500 NamedDecl *Hidden; 15501 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15502 SkipBodyInfo Skip; 15503 Skip.Previous = Hidden; 15504 return Skip; 15505 } 15506 15507 return SkipBodyInfo(); 15508 } 15509 15510 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15511 SourceLocation IdLoc, IdentifierInfo *Id, 15512 AttributeList *Attr, 15513 SourceLocation EqualLoc, Expr *Val) { 15514 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15515 EnumConstantDecl *LastEnumConst = 15516 cast_or_null<EnumConstantDecl>(lastEnumConst); 15517 15518 // The scope passed in may not be a decl scope. Zip up the scope tree until 15519 // we find one that is. 15520 S = getNonFieldDeclScope(S); 15521 15522 // Verify that there isn't already something declared with this name in this 15523 // scope. 15524 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15525 ForRedeclaration); 15526 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15527 // Maybe we will complain about the shadowed template parameter. 15528 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15529 // Just pretend that we didn't see the previous declaration. 15530 PrevDecl = nullptr; 15531 } 15532 15533 // C++ [class.mem]p15: 15534 // If T is the name of a class, then each of the following shall have a name 15535 // different from T: 15536 // - every enumerator of every member of class T that is an unscoped 15537 // enumerated type 15538 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15539 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15540 DeclarationNameInfo(Id, IdLoc)); 15541 15542 EnumConstantDecl *New = 15543 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15544 if (!New) 15545 return nullptr; 15546 15547 if (PrevDecl) { 15548 // When in C++, we may get a TagDecl with the same name; in this case the 15549 // enum constant will 'hide' the tag. 15550 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15551 "Received TagDecl when not in C++!"); 15552 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15553 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15554 if (isa<EnumConstantDecl>(PrevDecl)) 15555 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15556 else 15557 Diag(IdLoc, diag::err_redefinition) << Id; 15558 notePreviousDefinition(PrevDecl, IdLoc); 15559 return nullptr; 15560 } 15561 } 15562 15563 // Process attributes. 15564 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15565 AddPragmaAttributes(S, New); 15566 15567 // Register this decl in the current scope stack. 15568 New->setAccess(TheEnumDecl->getAccess()); 15569 PushOnScopeChains(New, S); 15570 15571 ActOnDocumentableDecl(New); 15572 15573 return New; 15574 } 15575 15576 // Returns true when the enum initial expression does not trigger the 15577 // duplicate enum warning. A few common cases are exempted as follows: 15578 // Element2 = Element1 15579 // Element2 = Element1 + 1 15580 // Element2 = Element1 - 1 15581 // Where Element2 and Element1 are from the same enum. 15582 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15583 Expr *InitExpr = ECD->getInitExpr(); 15584 if (!InitExpr) 15585 return true; 15586 InitExpr = InitExpr->IgnoreImpCasts(); 15587 15588 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15589 if (!BO->isAdditiveOp()) 15590 return true; 15591 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15592 if (!IL) 15593 return true; 15594 if (IL->getValue() != 1) 15595 return true; 15596 15597 InitExpr = BO->getLHS(); 15598 } 15599 15600 // This checks if the elements are from the same enum. 15601 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15602 if (!DRE) 15603 return true; 15604 15605 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15606 if (!EnumConstant) 15607 return true; 15608 15609 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15610 Enum) 15611 return true; 15612 15613 return false; 15614 } 15615 15616 namespace { 15617 struct DupKey { 15618 int64_t val; 15619 bool isTombstoneOrEmptyKey; 15620 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15621 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15622 }; 15623 15624 static DupKey GetDupKey(const llvm::APSInt& Val) { 15625 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15626 false); 15627 } 15628 15629 struct DenseMapInfoDupKey { 15630 static DupKey getEmptyKey() { return DupKey(0, true); } 15631 static DupKey getTombstoneKey() { return DupKey(1, true); } 15632 static unsigned getHashValue(const DupKey Key) { 15633 return (unsigned)(Key.val * 37); 15634 } 15635 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15636 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15637 LHS.val == RHS.val; 15638 } 15639 }; 15640 } // end anonymous namespace 15641 15642 // Emits a warning when an element is implicitly set a value that 15643 // a previous element has already been set to. 15644 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15645 EnumDecl *Enum, 15646 QualType EnumType) { 15647 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15648 return; 15649 // Avoid anonymous enums 15650 if (!Enum->getIdentifier()) 15651 return; 15652 15653 // Only check for small enums. 15654 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15655 return; 15656 15657 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15658 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15659 15660 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15661 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15662 ValueToVectorMap; 15663 15664 DuplicatesVector DupVector; 15665 ValueToVectorMap EnumMap; 15666 15667 // Populate the EnumMap with all values represented by enum constants without 15668 // an initialier. 15669 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15670 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15671 15672 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15673 // this constant. Skip this enum since it may be ill-formed. 15674 if (!ECD) { 15675 return; 15676 } 15677 15678 if (ECD->getInitExpr()) 15679 continue; 15680 15681 DupKey Key = GetDupKey(ECD->getInitVal()); 15682 DeclOrVector &Entry = EnumMap[Key]; 15683 15684 // First time encountering this value. 15685 if (Entry.isNull()) 15686 Entry = ECD; 15687 } 15688 15689 // Create vectors for any values that has duplicates. 15690 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15691 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15692 if (!ValidDuplicateEnum(ECD, Enum)) 15693 continue; 15694 15695 DupKey Key = GetDupKey(ECD->getInitVal()); 15696 15697 DeclOrVector& Entry = EnumMap[Key]; 15698 if (Entry.isNull()) 15699 continue; 15700 15701 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15702 // Ensure constants are different. 15703 if (D == ECD) 15704 continue; 15705 15706 // Create new vector and push values onto it. 15707 ECDVector *Vec = new ECDVector(); 15708 Vec->push_back(D); 15709 Vec->push_back(ECD); 15710 15711 // Update entry to point to the duplicates vector. 15712 Entry = Vec; 15713 15714 // Store the vector somewhere we can consult later for quick emission of 15715 // diagnostics. 15716 DupVector.push_back(Vec); 15717 continue; 15718 } 15719 15720 ECDVector *Vec = Entry.get<ECDVector*>(); 15721 // Make sure constants are not added more than once. 15722 if (*Vec->begin() == ECD) 15723 continue; 15724 15725 Vec->push_back(ECD); 15726 } 15727 15728 // Emit diagnostics. 15729 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15730 DupVectorEnd = DupVector.end(); 15731 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15732 ECDVector *Vec = *DupVectorIter; 15733 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15734 15735 // Emit warning for one enum constant. 15736 ECDVector::iterator I = Vec->begin(); 15737 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15738 << (*I)->getName() << (*I)->getInitVal().toString(10) 15739 << (*I)->getSourceRange(); 15740 ++I; 15741 15742 // Emit one note for each of the remaining enum constants with 15743 // the same value. 15744 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15745 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15746 << (*I)->getName() << (*I)->getInitVal().toString(10) 15747 << (*I)->getSourceRange(); 15748 delete Vec; 15749 } 15750 } 15751 15752 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15753 bool AllowMask) const { 15754 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15755 assert(ED->isCompleteDefinition() && "expected enum definition"); 15756 15757 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15758 llvm::APInt &FlagBits = R.first->second; 15759 15760 if (R.second) { 15761 for (auto *E : ED->enumerators()) { 15762 const auto &EVal = E->getInitVal(); 15763 // Only single-bit enumerators introduce new flag values. 15764 if (EVal.isPowerOf2()) 15765 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15766 } 15767 } 15768 15769 // A value is in a flag enum if either its bits are a subset of the enum's 15770 // flag bits (the first condition) or we are allowing masks and the same is 15771 // true of its complement (the second condition). When masks are allowed, we 15772 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15773 // 15774 // While it's true that any value could be used as a mask, the assumption is 15775 // that a mask will have all of the insignificant bits set. Anything else is 15776 // likely a logic error. 15777 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15778 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15779 } 15780 15781 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15782 Decl *EnumDeclX, 15783 ArrayRef<Decl *> Elements, 15784 Scope *S, AttributeList *Attr) { 15785 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15786 QualType EnumType = Context.getTypeDeclType(Enum); 15787 15788 if (Attr) 15789 ProcessDeclAttributeList(S, Enum, Attr); 15790 15791 if (Enum->isDependentType()) { 15792 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15793 EnumConstantDecl *ECD = 15794 cast_or_null<EnumConstantDecl>(Elements[i]); 15795 if (!ECD) continue; 15796 15797 ECD->setType(EnumType); 15798 } 15799 15800 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15801 return; 15802 } 15803 15804 // TODO: If the result value doesn't fit in an int, it must be a long or long 15805 // long value. ISO C does not support this, but GCC does as an extension, 15806 // emit a warning. 15807 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15808 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15809 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15810 15811 // Verify that all the values are okay, compute the size of the values, and 15812 // reverse the list. 15813 unsigned NumNegativeBits = 0; 15814 unsigned NumPositiveBits = 0; 15815 15816 // Keep track of whether all elements have type int. 15817 bool AllElementsInt = true; 15818 15819 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15820 EnumConstantDecl *ECD = 15821 cast_or_null<EnumConstantDecl>(Elements[i]); 15822 if (!ECD) continue; // Already issued a diagnostic. 15823 15824 const llvm::APSInt &InitVal = ECD->getInitVal(); 15825 15826 // Keep track of the size of positive and negative values. 15827 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15828 NumPositiveBits = std::max(NumPositiveBits, 15829 (unsigned)InitVal.getActiveBits()); 15830 else 15831 NumNegativeBits = std::max(NumNegativeBits, 15832 (unsigned)InitVal.getMinSignedBits()); 15833 15834 // Keep track of whether every enum element has type int (very commmon). 15835 if (AllElementsInt) 15836 AllElementsInt = ECD->getType() == Context.IntTy; 15837 } 15838 15839 // Figure out the type that should be used for this enum. 15840 QualType BestType; 15841 unsigned BestWidth; 15842 15843 // C++0x N3000 [conv.prom]p3: 15844 // An rvalue of an unscoped enumeration type whose underlying 15845 // type is not fixed can be converted to an rvalue of the first 15846 // of the following types that can represent all the values of 15847 // the enumeration: int, unsigned int, long int, unsigned long 15848 // int, long long int, or unsigned long long int. 15849 // C99 6.4.4.3p2: 15850 // An identifier declared as an enumeration constant has type int. 15851 // The C99 rule is modified by a gcc extension 15852 QualType BestPromotionType; 15853 15854 bool Packed = Enum->hasAttr<PackedAttr>(); 15855 // -fshort-enums is the equivalent to specifying the packed attribute on all 15856 // enum definitions. 15857 if (LangOpts.ShortEnums) 15858 Packed = true; 15859 15860 if (Enum->isFixed()) { 15861 BestType = Enum->getIntegerType(); 15862 if (BestType->isPromotableIntegerType()) 15863 BestPromotionType = Context.getPromotedIntegerType(BestType); 15864 else 15865 BestPromotionType = BestType; 15866 15867 BestWidth = Context.getIntWidth(BestType); 15868 } 15869 else if (NumNegativeBits) { 15870 // If there is a negative value, figure out the smallest integer type (of 15871 // int/long/longlong) that fits. 15872 // If it's packed, check also if it fits a char or a short. 15873 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15874 BestType = Context.SignedCharTy; 15875 BestWidth = CharWidth; 15876 } else if (Packed && NumNegativeBits <= ShortWidth && 15877 NumPositiveBits < ShortWidth) { 15878 BestType = Context.ShortTy; 15879 BestWidth = ShortWidth; 15880 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15881 BestType = Context.IntTy; 15882 BestWidth = IntWidth; 15883 } else { 15884 BestWidth = Context.getTargetInfo().getLongWidth(); 15885 15886 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15887 BestType = Context.LongTy; 15888 } else { 15889 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15890 15891 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15892 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15893 BestType = Context.LongLongTy; 15894 } 15895 } 15896 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15897 } else { 15898 // If there is no negative value, figure out the smallest type that fits 15899 // all of the enumerator values. 15900 // If it's packed, check also if it fits a char or a short. 15901 if (Packed && NumPositiveBits <= CharWidth) { 15902 BestType = Context.UnsignedCharTy; 15903 BestPromotionType = Context.IntTy; 15904 BestWidth = CharWidth; 15905 } else if (Packed && NumPositiveBits <= ShortWidth) { 15906 BestType = Context.UnsignedShortTy; 15907 BestPromotionType = Context.IntTy; 15908 BestWidth = ShortWidth; 15909 } else if (NumPositiveBits <= IntWidth) { 15910 BestType = Context.UnsignedIntTy; 15911 BestWidth = IntWidth; 15912 BestPromotionType 15913 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15914 ? Context.UnsignedIntTy : Context.IntTy; 15915 } else if (NumPositiveBits <= 15916 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15917 BestType = Context.UnsignedLongTy; 15918 BestPromotionType 15919 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15920 ? Context.UnsignedLongTy : Context.LongTy; 15921 } else { 15922 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15923 assert(NumPositiveBits <= BestWidth && 15924 "How could an initializer get larger than ULL?"); 15925 BestType = Context.UnsignedLongLongTy; 15926 BestPromotionType 15927 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15928 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15929 } 15930 } 15931 15932 // Loop over all of the enumerator constants, changing their types to match 15933 // the type of the enum if needed. 15934 for (auto *D : Elements) { 15935 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15936 if (!ECD) continue; // Already issued a diagnostic. 15937 15938 // Standard C says the enumerators have int type, but we allow, as an 15939 // extension, the enumerators to be larger than int size. If each 15940 // enumerator value fits in an int, type it as an int, otherwise type it the 15941 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15942 // that X has type 'int', not 'unsigned'. 15943 15944 // Determine whether the value fits into an int. 15945 llvm::APSInt InitVal = ECD->getInitVal(); 15946 15947 // If it fits into an integer type, force it. Otherwise force it to match 15948 // the enum decl type. 15949 QualType NewTy; 15950 unsigned NewWidth; 15951 bool NewSign; 15952 if (!getLangOpts().CPlusPlus && 15953 !Enum->isFixed() && 15954 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15955 NewTy = Context.IntTy; 15956 NewWidth = IntWidth; 15957 NewSign = true; 15958 } else if (ECD->getType() == BestType) { 15959 // Already the right type! 15960 if (getLangOpts().CPlusPlus) 15961 // C++ [dcl.enum]p4: Following the closing brace of an 15962 // enum-specifier, each enumerator has the type of its 15963 // enumeration. 15964 ECD->setType(EnumType); 15965 continue; 15966 } else { 15967 NewTy = BestType; 15968 NewWidth = BestWidth; 15969 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15970 } 15971 15972 // Adjust the APSInt value. 15973 InitVal = InitVal.extOrTrunc(NewWidth); 15974 InitVal.setIsSigned(NewSign); 15975 ECD->setInitVal(InitVal); 15976 15977 // Adjust the Expr initializer and type. 15978 if (ECD->getInitExpr() && 15979 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15980 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15981 CK_IntegralCast, 15982 ECD->getInitExpr(), 15983 /*base paths*/ nullptr, 15984 VK_RValue)); 15985 if (getLangOpts().CPlusPlus) 15986 // C++ [dcl.enum]p4: Following the closing brace of an 15987 // enum-specifier, each enumerator has the type of its 15988 // enumeration. 15989 ECD->setType(EnumType); 15990 else 15991 ECD->setType(NewTy); 15992 } 15993 15994 Enum->completeDefinition(BestType, BestPromotionType, 15995 NumPositiveBits, NumNegativeBits); 15996 15997 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15998 15999 if (Enum->isClosedFlag()) { 16000 for (Decl *D : Elements) { 16001 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16002 if (!ECD) continue; // Already issued a diagnostic. 16003 16004 llvm::APSInt InitVal = ECD->getInitVal(); 16005 if (InitVal != 0 && !InitVal.isPowerOf2() && 16006 !IsValueInFlagEnum(Enum, InitVal, true)) 16007 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16008 << ECD << Enum; 16009 } 16010 } 16011 16012 // Now that the enum type is defined, ensure it's not been underaligned. 16013 if (Enum->hasAttrs()) 16014 CheckAlignasUnderalignment(Enum); 16015 } 16016 16017 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16018 SourceLocation StartLoc, 16019 SourceLocation EndLoc) { 16020 StringLiteral *AsmString = cast<StringLiteral>(expr); 16021 16022 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16023 AsmString, StartLoc, 16024 EndLoc); 16025 CurContext->addDecl(New); 16026 return New; 16027 } 16028 16029 static void checkModuleImportContext(Sema &S, Module *M, 16030 SourceLocation ImportLoc, DeclContext *DC, 16031 bool FromInclude = false) { 16032 SourceLocation ExternCLoc; 16033 16034 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16035 switch (LSD->getLanguage()) { 16036 case LinkageSpecDecl::lang_c: 16037 if (ExternCLoc.isInvalid()) 16038 ExternCLoc = LSD->getLocStart(); 16039 break; 16040 case LinkageSpecDecl::lang_cxx: 16041 break; 16042 } 16043 DC = LSD->getParent(); 16044 } 16045 16046 while (isa<LinkageSpecDecl>(DC)) 16047 DC = DC->getParent(); 16048 16049 if (!isa<TranslationUnitDecl>(DC)) { 16050 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16051 ? diag::ext_module_import_not_at_top_level_noop 16052 : diag::err_module_import_not_at_top_level_fatal) 16053 << M->getFullModuleName() << DC; 16054 S.Diag(cast<Decl>(DC)->getLocStart(), 16055 diag::note_module_import_not_at_top_level) << DC; 16056 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16057 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16058 << M->getFullModuleName(); 16059 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16060 } 16061 } 16062 16063 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16064 SourceLocation ModuleLoc, 16065 ModuleDeclKind MDK, 16066 ModuleIdPath Path) { 16067 // A module implementation unit requires that we are not compiling a module 16068 // of any kind. A module interface unit requires that we are not compiling a 16069 // module map. 16070 switch (getLangOpts().getCompilingModule()) { 16071 case LangOptions::CMK_None: 16072 // It's OK to compile a module interface as a normal translation unit. 16073 break; 16074 16075 case LangOptions::CMK_ModuleInterface: 16076 if (MDK != ModuleDeclKind::Implementation) 16077 break; 16078 16079 // We were asked to compile a module interface unit but this is a module 16080 // implementation unit. That indicates the 'export' is missing. 16081 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16082 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16083 break; 16084 16085 case LangOptions::CMK_ModuleMap: 16086 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16087 return nullptr; 16088 } 16089 16090 // FIXME: Most of this work should be done by the preprocessor rather than 16091 // here, in order to support macro import. 16092 16093 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16094 // modules, the dots here are just another character that can appear in a 16095 // module name. 16096 std::string ModuleName; 16097 for (auto &Piece : Path) { 16098 if (!ModuleName.empty()) 16099 ModuleName += "."; 16100 ModuleName += Piece.first->getName(); 16101 } 16102 16103 // FIXME: If we've already seen a module-declaration, report an error. 16104 16105 // If a module name was explicitly specified on the command line, it must be 16106 // correct. 16107 if (!getLangOpts().CurrentModule.empty() && 16108 getLangOpts().CurrentModule != ModuleName) { 16109 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16110 << SourceRange(Path.front().second, Path.back().second) 16111 << getLangOpts().CurrentModule; 16112 return nullptr; 16113 } 16114 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16115 16116 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16117 Module *Mod; 16118 16119 switch (MDK) { 16120 case ModuleDeclKind::Module: { 16121 // FIXME: Check we're not in a submodule. 16122 16123 // We can't have parsed or imported a definition of this module or parsed a 16124 // module map defining it already. 16125 if (auto *M = Map.findModule(ModuleName)) { 16126 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16127 if (M->DefinitionLoc.isValid()) 16128 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16129 else if (const auto *FE = M->getASTFile()) 16130 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16131 << FE->getName(); 16132 return nullptr; 16133 } 16134 16135 // Create a Module for the module that we're defining. 16136 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 16137 assert(Mod && "module creation should not fail"); 16138 break; 16139 } 16140 16141 case ModuleDeclKind::Partition: 16142 // FIXME: Check we are in a submodule of the named module. 16143 return nullptr; 16144 16145 case ModuleDeclKind::Implementation: 16146 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16147 PP.getIdentifierInfo(ModuleName), Path[0].second); 16148 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16149 /*IsIncludeDirective=*/false); 16150 if (!Mod) 16151 return nullptr; 16152 break; 16153 } 16154 16155 // Enter the semantic scope of the module. 16156 ModuleScopes.push_back({}); 16157 ModuleScopes.back().Module = Mod; 16158 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16159 VisibleModules.setVisible(Mod, ModuleLoc); 16160 16161 // From now on, we have an owning module for all declarations we see. 16162 // However, those declarations are module-private unless explicitly 16163 // exported. 16164 Context.getTranslationUnitDecl()->setLocalOwningModule(Mod); 16165 16166 // FIXME: Create a ModuleDecl. 16167 return nullptr; 16168 } 16169 16170 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16171 SourceLocation ImportLoc, 16172 ModuleIdPath Path) { 16173 Module *Mod = 16174 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16175 /*IsIncludeDirective=*/false); 16176 if (!Mod) 16177 return true; 16178 16179 VisibleModules.setVisible(Mod, ImportLoc); 16180 16181 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16182 16183 // FIXME: we should support importing a submodule within a different submodule 16184 // of the same top-level module. Until we do, make it an error rather than 16185 // silently ignoring the import. 16186 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16187 // warn on a redundant import of the current module? 16188 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16189 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16190 Diag(ImportLoc, getLangOpts().isCompilingModule() 16191 ? diag::err_module_self_import 16192 : diag::err_module_import_in_implementation) 16193 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16194 16195 SmallVector<SourceLocation, 2> IdentifierLocs; 16196 Module *ModCheck = Mod; 16197 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16198 // If we've run out of module parents, just drop the remaining identifiers. 16199 // We need the length to be consistent. 16200 if (!ModCheck) 16201 break; 16202 ModCheck = ModCheck->Parent; 16203 16204 IdentifierLocs.push_back(Path[I].second); 16205 } 16206 16207 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16208 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 16209 Mod, IdentifierLocs); 16210 if (!ModuleScopes.empty()) 16211 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16212 TU->addDecl(Import); 16213 return Import; 16214 } 16215 16216 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16217 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16218 BuildModuleInclude(DirectiveLoc, Mod); 16219 } 16220 16221 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16222 // Determine whether we're in the #include buffer for a module. The #includes 16223 // in that buffer do not qualify as module imports; they're just an 16224 // implementation detail of us building the module. 16225 // 16226 // FIXME: Should we even get ActOnModuleInclude calls for those? 16227 bool IsInModuleIncludes = 16228 TUKind == TU_Module && 16229 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16230 16231 bool ShouldAddImport = !IsInModuleIncludes; 16232 16233 // If this module import was due to an inclusion directive, create an 16234 // implicit import declaration to capture it in the AST. 16235 if (ShouldAddImport) { 16236 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16237 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16238 DirectiveLoc, Mod, 16239 DirectiveLoc); 16240 if (!ModuleScopes.empty()) 16241 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16242 TU->addDecl(ImportD); 16243 Consumer.HandleImplicitImportDecl(ImportD); 16244 } 16245 16246 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16247 VisibleModules.setVisible(Mod, DirectiveLoc); 16248 } 16249 16250 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16251 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16252 16253 ModuleScopes.push_back({}); 16254 ModuleScopes.back().Module = Mod; 16255 if (getLangOpts().ModulesLocalVisibility) 16256 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16257 16258 VisibleModules.setVisible(Mod, DirectiveLoc); 16259 16260 // The enclosing context is now part of this module. 16261 // FIXME: Consider creating a child DeclContext to hold the entities 16262 // lexically within the module. 16263 if (getLangOpts().trackLocalOwningModule()) { 16264 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16265 cast<Decl>(DC)->setModuleOwnershipKind( 16266 getLangOpts().ModulesLocalVisibility 16267 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16268 : Decl::ModuleOwnershipKind::Visible); 16269 cast<Decl>(DC)->setLocalOwningModule(Mod); 16270 } 16271 } 16272 } 16273 16274 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16275 if (getLangOpts().ModulesLocalVisibility) { 16276 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16277 // Leaving a module hides namespace names, so our visible namespace cache 16278 // is now out of date. 16279 VisibleNamespaceCache.clear(); 16280 } 16281 16282 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16283 "left the wrong module scope"); 16284 ModuleScopes.pop_back(); 16285 16286 // We got to the end of processing a local module. Create an 16287 // ImportDecl as we would for an imported module. 16288 FileID File = getSourceManager().getFileID(EomLoc); 16289 SourceLocation DirectiveLoc; 16290 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16291 // We reached the end of a #included module header. Use the #include loc. 16292 assert(File != getSourceManager().getMainFileID() && 16293 "end of submodule in main source file"); 16294 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16295 } else { 16296 // We reached an EOM pragma. Use the pragma location. 16297 DirectiveLoc = EomLoc; 16298 } 16299 BuildModuleInclude(DirectiveLoc, Mod); 16300 16301 // Any further declarations are in whatever module we returned to. 16302 if (getLangOpts().trackLocalOwningModule()) { 16303 // The parser guarantees that this is the same context that we entered 16304 // the module within. 16305 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16306 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16307 if (!getCurrentModule()) 16308 cast<Decl>(DC)->setModuleOwnershipKind( 16309 Decl::ModuleOwnershipKind::Unowned); 16310 } 16311 } 16312 } 16313 16314 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16315 Module *Mod) { 16316 // Bail if we're not allowed to implicitly import a module here. 16317 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16318 VisibleModules.isVisible(Mod)) 16319 return; 16320 16321 // Create the implicit import declaration. 16322 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16323 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16324 Loc, Mod, Loc); 16325 TU->addDecl(ImportD); 16326 Consumer.HandleImplicitImportDecl(ImportD); 16327 16328 // Make the module visible. 16329 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16330 VisibleModules.setVisible(Mod, Loc); 16331 } 16332 16333 /// We have parsed the start of an export declaration, including the '{' 16334 /// (if present). 16335 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16336 SourceLocation LBraceLoc) { 16337 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16338 16339 // C++ Modules TS draft: 16340 // An export-declaration shall appear in the purview of a module other than 16341 // the global module. 16342 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16343 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16344 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16345 16346 // An export-declaration [...] shall not contain more than one 16347 // export keyword. 16348 // 16349 // The intent here is that an export-declaration cannot appear within another 16350 // export-declaration. 16351 if (D->isExported()) 16352 Diag(ExportLoc, diag::err_export_within_export); 16353 16354 CurContext->addDecl(D); 16355 PushDeclContext(S, D); 16356 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16357 return D; 16358 } 16359 16360 /// Complete the definition of an export declaration. 16361 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16362 auto *ED = cast<ExportDecl>(D); 16363 if (RBraceLoc.isValid()) 16364 ED->setRBraceLoc(RBraceLoc); 16365 16366 // FIXME: Diagnose export of internal-linkage declaration (including 16367 // anonymous namespace). 16368 16369 PopDeclContext(); 16370 return D; 16371 } 16372 16373 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16374 IdentifierInfo* AliasName, 16375 SourceLocation PragmaLoc, 16376 SourceLocation NameLoc, 16377 SourceLocation AliasNameLoc) { 16378 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16379 LookupOrdinaryName); 16380 AsmLabelAttr *Attr = 16381 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16382 16383 // If a declaration that: 16384 // 1) declares a function or a variable 16385 // 2) has external linkage 16386 // already exists, add a label attribute to it. 16387 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16388 if (isDeclExternC(PrevDecl)) 16389 PrevDecl->addAttr(Attr); 16390 else 16391 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16392 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16393 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16394 } else 16395 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16396 } 16397 16398 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16399 SourceLocation PragmaLoc, 16400 SourceLocation NameLoc) { 16401 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16402 16403 if (PrevDecl) { 16404 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16405 } else { 16406 (void)WeakUndeclaredIdentifiers.insert( 16407 std::pair<IdentifierInfo*,WeakInfo> 16408 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16409 } 16410 } 16411 16412 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16413 IdentifierInfo* AliasName, 16414 SourceLocation PragmaLoc, 16415 SourceLocation NameLoc, 16416 SourceLocation AliasNameLoc) { 16417 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16418 LookupOrdinaryName); 16419 WeakInfo W = WeakInfo(Name, NameLoc); 16420 16421 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16422 if (!PrevDecl->hasAttr<AliasAttr>()) 16423 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16424 DeclApplyPragmaWeak(TUScope, ND, W); 16425 } else { 16426 (void)WeakUndeclaredIdentifiers.insert( 16427 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16428 } 16429 } 16430 16431 Decl *Sema::getObjCDeclContext() const { 16432 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16433 } 16434