#include "TypeLocBuilder.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/CommentDiagnostic.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/NonTrivialTypeVisitor.h"
#include "clang/AST/Randstruct.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/CXXFieldCollector.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Triple.h"
#include <algorithm>
#include <cstring>
#include <functional>
#include <unordered_map>
using namespace clang;
using namespace sema;
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
if (OwnedType) {
Decl *Group[2] = { OwnedType, Ptr };
return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
}
return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
}
namespace {
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
public:
TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
bool AllowTemplates = false,
bool AllowNonTemplates = true)
: AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
WantExpressionKeywords = false;
WantCXXNamedCasts = false;
WantRemainingKeywords = false;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (NamedDecl *ND = candidate.getCorrectionDecl()) {
if (!AllowInvalidDecl && ND->isInvalidDecl())
return false;
if (getAsTypeTemplateDecl(ND))
return AllowTemplates;
bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
if (!IsType)
return false;
if (AllowNonTemplates)
return true;
if (AllowTemplates) {
auto *RD = dyn_cast<CXXRecordDecl>(ND);
if (!RD || !RD->isInjectedClassName())
return false;
RD = cast<CXXRecordDecl>(RD->getDeclContext());
return RD->getDescribedClassTemplate() ||
isa<ClassTemplateSpecializationDecl>(RD);
}
return false;
}
return !WantClassName && candidate.isKeyword();
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<TypeNameValidatorCCC>(*this);
}
private:
bool AllowInvalidDecl;
bool WantClassName;
bool AllowTemplates;
bool AllowNonTemplates;
};
}
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
switch (Kind) {
case tok::kw_short:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw_void:
case tok::kw_char:
case tok::kw_int:
case tok::kw_half:
case tok::kw_float:
case tok::kw_double:
case tok::kw___bf16:
case tok::kw__Float16:
case tok::kw___float128:
case tok::kw___ibm128:
case tok::kw_wchar_t:
case tok::kw_bool:
case tok::kw___underlying_type:
case tok::kw___auto_type:
return true;
case tok::annot_typename:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_typeof:
case tok::annot_decltype:
case tok::kw_decltype:
return getLangOpts().CPlusPlus;
case tok::kw_char8_t:
return getLangOpts().Char8;
default:
break;
}
return false;
}
namespace {
enum class UnqualifiedTypeNameLookupResult {
NotFound,
FoundNonType,
FoundType
};
}
static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
SourceLocation NameLoc,
const CXXRecordDecl *RD) {
if (!RD->hasDefinition())
return UnqualifiedTypeNameLookupResult::NotFound;
UnqualifiedTypeNameLookupResult FoundTypeDecl =
UnqualifiedTypeNameLookupResult::NotFound;
for (const auto &Base : RD->bases()) {
const CXXRecordDecl *BaseRD = nullptr;
if (auto *BaseTT = Base.getType()->getAs<TagType>())
BaseRD = BaseTT->getAsCXXRecordDecl();
else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
if (!TST || !TST->isDependentType())
continue;
auto *TD = TST->getTemplateName().getAsTemplateDecl();
if (!TD)
continue;
if (auto *BasePrimaryTemplate =
dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
BaseRD = BasePrimaryTemplate;
else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
if (const ClassTemplatePartialSpecializationDecl *PS =
CTD->findPartialSpecialization(Base.getType()))
if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
BaseRD = PS;
}
}
}
if (BaseRD) {
for (NamedDecl *ND : BaseRD->lookup(&II)) {
if (!isa<TypeDecl>(ND))
return UnqualifiedTypeNameLookupResult::FoundNonType;
FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
}
if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
case UnqualifiedTypeNameLookupResult::FoundNonType:
return UnqualifiedTypeNameLookupResult::FoundNonType;
case UnqualifiedTypeNameLookupResult::FoundType:
FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
break;
case UnqualifiedTypeNameLookupResult::NotFound:
break;
}
}
}
}
return FoundTypeDecl;
}
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
const IdentifierInfo &II,
SourceLocation NameLoc) {
const CXXRecordDecl *RD = nullptr;
UnqualifiedTypeNameLookupResult FoundTypeDecl =
UnqualifiedTypeNameLookupResult::NotFound;
for (DeclContext *DC = S.CurContext;
DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
DC = DC->getParent()) {
RD = dyn_cast<CXXRecordDecl>(DC);
if (RD && RD->getDescribedClassTemplate())
FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
}
if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
return nullptr;
S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
ASTContext &Context = S.Context;
auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
cast<Type>(Context.getRecordType(RD)));
QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
CXXScopeSpec SS;
SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
TypeLocBuilder Builder;
DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
DepTL.setNameLoc(NameLoc);
DepTL.setElaboratedKeywordLoc(SourceLocation());
DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
}
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS,
bool isClassName, bool HasTrailingDot,
ParsedType ObjectTypePtr,
bool IsCtorOrDtorName,
bool WantNontrivialTypeSourceInfo,
bool IsClassTemplateDeductionContext,
IdentifierInfo **CorrectedII) {
bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
!isClassName && !HasTrailingDot;
DeclContext *LookupCtx = nullptr;
if (ObjectTypePtr) {
QualType ObjectType = ObjectTypePtr.get();
if (ObjectType->isRecordType())
LookupCtx = computeDeclContext(ObjectType);
} else if (SS && SS->isNotEmpty()) {
LookupCtx = computeDeclContext(*SS, false);
if (!LookupCtx) {
if (isDependentScopeSpecifier(*SS)) {
if (!isClassName && !IsCtorOrDtorName)
return nullptr;
if (WantNontrivialTypeSourceInfo)
return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
II, NameLoc);
return ParsedType::make(T);
}
return nullptr;
}
if (!LookupCtx->isDependentContext() &&
RequireCompleteDeclContext(*SS, LookupCtx))
return nullptr;
}
LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
LookupOrdinaryName;
LookupResult Result(*this, &II, NameLoc, Kind);
if (LookupCtx) {
LookupQualifiedName(Result, LookupCtx);
if (ObjectTypePtr && Result.empty()) {
LookupName(Result, S);
}
} else {
LookupName(Result, S);
if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
if (ParsedType TypeInBase =
recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
return TypeInBase;
}
}
NamedDecl *IIDecl = nullptr;
UsingShadowDecl *FoundUsingShadow = nullptr;
switch (Result.getResultKind()) {
case LookupResult::NotFound:
case LookupResult::NotFoundInCurrentInstantiation:
if (CorrectedII) {
TypeNameValidatorCCC CCC(true, isClassName,
AllowDeducedTemplate);
TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
S, SS, CCC, CTK_ErrorRecovery);
IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
TemplateTy Template;
bool MemberOfUnknownSpecialization;
UnqualifiedId TemplateName;
TemplateName.setIdentifier(NewII, NameLoc);
NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
CXXScopeSpec NewSS, *NewSSPtr = SS;
if (SS && NNS) {
NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
NewSSPtr = &NewSS;
}
if (Correction && (NNS || NewII != &II) &&
!(getLangOpts().CPlusPlus && NewSSPtr &&
isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
Template, MemberOfUnknownSpecialization))) {
ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
isClassName, HasTrailingDot, ObjectTypePtr,
IsCtorOrDtorName,
WantNontrivialTypeSourceInfo,
IsClassTemplateDeductionContext);
if (Ty) {
diagnoseTypo(Correction,
PDiag(diag::err_unknown_type_or_class_name_suggest)
<< Result.getLookupName() << isClassName);
if (SS && NNS)
SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
*CorrectedII = NewII;
return Ty;
}
}
}
LLVM_FALLTHROUGH;
case LookupResult::FoundOverloaded:
case LookupResult::FoundUnresolvedValue:
Result.suppressDiagnostics();
return nullptr;
case LookupResult::Ambiguous:
if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
Result.suppressDiagnostics();
return nullptr;
}
for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
Res != ResEnd; ++Res) {
NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
RealRes) ||
(AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
if (!IIDecl ||
RealRes->getLocation() < IIDecl->getLocation()) {
IIDecl = RealRes;
FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
}
}
}
if (!IIDecl) {
Result.suppressDiagnostics();
return nullptr;
}
break;
case LookupResult::Found:
IIDecl = Result.getFoundDecl();
FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
break;
}
assert(IIDecl && "Didn't find decl");
QualType T;
if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
FoundRD->isInjectedClassName() &&
declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
<< &II << 1;
DiagnoseUseOfDecl(IIDecl, NameLoc);
T = Context.getTypeDeclType(TD);
MarkAnyDeclReferenced(TD->getLocation(), TD, false);
} else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
(void)DiagnoseUseOfDecl(IDecl, NameLoc);
if (!HasTrailingDot)
T = Context.getObjCInterfaceType(IDecl);
FoundUsingShadow = nullptr; } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
(void)DiagnoseUseOfDecl(UD, NameLoc);
T = Context.IntTy;
FoundUsingShadow = nullptr;
} else if (AllowDeducedTemplate) {
if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
TemplateName Template =
FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
false);
FoundUsingShadow = nullptr;
}
}
if (T.isNull()) {
Result.suppressDiagnostics();
return nullptr;
}
if (FoundUsingShadow)
T = Context.getUsingType(FoundUsingShadow, T);
if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
!isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
if (WantNontrivialTypeSourceInfo) {
TypeLocBuilder Builder;
Builder.pushTypeSpec(T).setNameLoc(NameLoc);
T = getElaboratedType(ETK_None, *SS, T);
ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
ElabTL.setElaboratedKeywordLoc(SourceLocation());
ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
} else {
T = getElaboratedType(ETK_None, *SS, T);
}
}
return ParsedType::make(T);
}
static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
for (;; DC = DC->getLookupParent()) {
DC = DC->getPrimaryContext();
auto *ND = dyn_cast<NamespaceDecl>(DC);
if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
return NestedNameSpecifier::Create(Context, nullptr, ND);
else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
RD->getTypeForDecl());
else if (isa<TranslationUnitDecl>(DC))
return NestedNameSpecifier::GlobalSpecifier(Context);
}
llvm_unreachable("something isn't in TU scope?");
}
static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
DC = DC->getPrimaryContext();
if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
if (MD->getParent()->hasAnyDependentBases())
return MD->getParent();
}
return nullptr;
}
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg) {
assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
NestedNameSpecifier *NNS = nullptr;
if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
} else if (const CXXRecordDecl *RD =
findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
RD->getTypeForDecl());
Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
<< RD;
} else {
return ParsedType();
}
QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
NestedNameSpecifierLocBuilder NNSLocBuilder;
NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
TypeLocBuilder Builder;
DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
DepTL.setNameLoc(NameLoc);
DepTL.setElaboratedKeywordLoc(SourceLocation());
DepTL.setQualifierLoc(QualifierLoc);
return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
}
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
LookupResult R(*this, &II, SourceLocation(), LookupTagName);
LookupName(R, S, false);
R.suppressDiagnostics();
if (R.getResultKind() == LookupResult::Found)
if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
switch (TD->getTagKind()) {
case TTK_Struct: return DeclSpec::TST_struct;
case TTK_Interface: return DeclSpec::TST_interface;
case TTK_Union: return DeclSpec::TST_union;
case TTK_Class: return DeclSpec::TST_class;
case TTK_Enum: return DeclSpec::TST_enum;
}
}
return DeclSpec::TST_unspecified;
}
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
if (CurContext->isRecord()) {
if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
return true;
const Type *Ty = SS->getScopeRep()->getAsType();
CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
for (const auto &Base : RD->bases())
if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
return true;
return S->isFunctionPrototypeScope();
}
return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
}
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName) {
if (II->isEditorPlaceholder())
return;
SuggestedType = nullptr;
TypeNameValidatorCCC CCC(false, false,
IsTemplateName,
!IsTemplateName);
if (TypoCorrection Corrected =
CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
CCC, CTK_ErrorRecovery)) {
bool CanRecover = !IsTemplateName;
if (Corrected.isKeyword()) {
diagnoseTypo(Corrected,
PDiag(IsTemplateName ? diag::err_no_template_suggest
: diag::err_unknown_typename_suggest)
<< II);
II = Corrected.getCorrectionAsIdentifierInfo();
} else {
if (!SS || !SS->isSet()) {
diagnoseTypo(Corrected,
PDiag(IsTemplateName ? diag::err_no_template_suggest
: diag::err_unknown_typename_suggest)
<< II, CanRecover);
} else if (DeclContext *DC = computeDeclContext(*SS, false)) {
std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
II->getName().equals(CorrectedStr);
diagnoseTypo(Corrected,
PDiag(IsTemplateName
? diag::err_no_member_template_suggest
: diag::err_unknown_nested_typename_suggest)
<< II << DC << DroppedSpecifier << SS->getRange(),
CanRecover);
} else {
llvm_unreachable("could not have corrected a typo here");
}
if (!CanRecover)
return;
CXXScopeSpec tmpSS;
if (Corrected.getCorrectionSpecifier())
tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
SourceRange(IILoc));
SuggestedType =
getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
false,
true);
}
return;
}
if (getLangOpts().CPlusPlus && !IsTemplateName) {
UnqualifiedId Name;
Name.setIdentifier(II, IILoc);
CXXScopeSpec EmptySS;
TemplateTy TemplateResult;
bool MemberOfUnknownSpecialization;
if (isTemplateName(S, SS ? *SS : EmptySS, false,
Name, nullptr, true, TemplateResult,
MemberOfUnknownSpecialization) == TNK_Type_template) {
diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
return;
}
}
if (!SS || (!SS->isSet() && !SS->isInvalid()))
Diag(IILoc, IsTemplateName ? diag::err_no_template
: diag::err_unknown_typename)
<< II;
else if (DeclContext *DC = computeDeclContext(*SS, false))
Diag(IILoc, IsTemplateName ? diag::err_no_member_template
: diag::err_typename_nested_not_found)
<< II << DC << SS->getRange();
else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
SuggestedType =
ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
} else if (isDependentScopeSpecifier(*SS)) {
unsigned DiagID = diag::err_typename_missing;
if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
DiagID = diag::ext_typename_missing;
Diag(SS->getRange().getBegin(), DiagID)
<< SS->getScopeRep() << II->getName()
<< SourceRange(SS->getRange().getBegin(), IILoc)
<< FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
SuggestedType = ActOnTypenameType(S, SourceLocation(),
*SS, *II, IILoc).get();
} else {
assert(SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed");
}
}
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
NextToken.is(tok::less);
for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
return true;
if (CheckTemplate && isa<TemplateDecl>(*I))
return true;
}
return false;
}
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name,
SourceLocation NameLoc) {
LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
SemaRef.LookupParsedName(R, S, &SS);
if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
StringRef FixItTagName;
switch (Tag->getTagKind()) {
case TTK_Class:
FixItTagName = "class ";
break;
case TTK_Enum:
FixItTagName = "enum ";
break;
case TTK_Struct:
FixItTagName = "struct ";
break;
case TTK_Interface:
FixItTagName = "__interface ";
break;
case TTK_Union:
FixItTagName = "union ";
break;
}
StringRef TagName = FixItTagName.drop_back();
SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
<< Name << TagName << SemaRef.getLangOpts().CPlusPlus
<< FixItHint::CreateInsertion(NameLoc, FixItTagName);
for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
I != IEnd; ++I)
SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
<< Name << TagName;
Result.clear(Sema::LookupTagName);
SemaRef.LookupParsedName(Result, S, &SS);
return true;
}
return false;
}
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name,
SourceLocation NameLoc,
const Token &NextToken,
CorrectionCandidateCallback *CCC) {
DeclarationNameInfo NameInfo(Name, NameLoc);
ObjCMethodDecl *CurMethod = getCurMethodDecl();
assert(NextToken.isNot(tok::coloncolon) &&
"parse nested name specifiers before calling ClassifyName");
if (getLangOpts().CPlusPlus && SS.isSet() &&
isCurrentClassName(*Name, S, &SS)) {
return NameClassification::Unknown();
}
LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
LookupParsedName(Result, S, &SS, !CurMethod);
if (SS.isInvalid())
return NameClassification::Error();
if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
if (ParsedType TypeInBase =
recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
return TypeInBase;
}
if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
if (Ivar.isInvalid())
return NameClassification::Error();
if (Ivar.isUsable())
return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
if (Result.empty())
LookupBuiltin(Result);
}
bool SecondTry = false;
bool IsFilteredTemplateName = false;
Corrected:
switch (Result.getResultKind()) {
case LookupResult::NotFound:
if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
if (getLangOpts().CPlusPlus)
return NameClassification::UndeclaredNonType();
if (getLangOpts().implicitFunctionsAllowed()) {
if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
return NameClassification::NonType(D);
}
}
if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
TemplateName Template =
Context.getAssumedTemplateName(NameInfo.getName());
return NameClassification::UndeclaredTemplate(Template);
}
if (!getLangOpts().CPlusPlus && !SecondTry &&
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
break;
}
if (!SecondTry && CCC) {
SecondTry = true;
if (TypoCorrection Corrected =
CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
&SS, *CCC, CTK_ErrorRecovery)) {
unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
unsigned QualifiedDiag = diag::err_no_member_suggest;
NamedDecl *FirstDecl = Corrected.getFoundDecl();
NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
UnqualifiedDiag = diag::err_no_template_suggest;
QualifiedDiag = diag::err_no_member_template_suggest;
} else if (UnderlyingFirstDecl &&
(isa<TypeDecl>(UnderlyingFirstDecl) ||
isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
UnqualifiedDiag = diag::err_unknown_typename_suggest;
QualifiedDiag = diag::err_unknown_nested_typename_suggest;
}
if (SS.isEmpty()) {
diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
} else { std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Name->getName().equals(CorrectedStr);
diagnoseTypo(Corrected, PDiag(QualifiedDiag)
<< Name << computeDeclContext(SS, false)
<< DroppedSpecifier << SS.getRange());
}
Name = Corrected.getCorrectionAsIdentifierInfo();
if (Corrected.isKeyword())
return Name;
Result.clear();
Result.setLookupName(Corrected.getCorrection());
if (FirstDecl)
Result.addDecl(FirstDecl);
if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
DeclResult R =
LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
if (R.isInvalid())
return NameClassification::Error();
if (R.isUsable())
return NameClassification::NonType(Ivar);
}
goto Corrected;
}
}
Result.suppressDiagnostics();
return NameClassification::Unknown();
case LookupResult::NotFoundInCurrentInstantiation: {
return NameClassification::DependentNonType();
}
case LookupResult::Found:
case LookupResult::FoundOverloaded:
case LookupResult::FoundUnresolvedValue:
break;
case LookupResult::Ambiguous:
if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
hasAnyAcceptableTemplateNames(Result, true,
false)) {
FilterAcceptableTemplateNames(Result);
if (!Result.isAmbiguous()) {
IsFilteredTemplateName = true;
break;
}
}
return NameClassification::Error();
}
if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
(IsFilteredTemplateName ||
hasAnyAcceptableTemplateNames(
Result, true,
false,
SS.isEmpty() &&
getLangOpts().CPlusPlus20))) {
if (!IsFilteredTemplateName)
FilterAcceptableTemplateNames(Result);
bool IsFunctionTemplate;
bool IsVarTemplate;
TemplateName Template;
if (Result.end() - Result.begin() > 1) {
IsFunctionTemplate = true;
Template = Context.getOverloadedTemplateName(Result.begin(),
Result.end());
} else if (!Result.empty()) {
auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
*Result.begin(), true,
false));
IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
IsVarTemplate = isa<VarTemplateDecl>(TD);
UsingShadowDecl *FoundUsingShadow =
dyn_cast<UsingShadowDecl>(*Result.begin());
assert(!FoundUsingShadow ||
TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
Template =
FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
if (SS.isNotEmpty())
Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
false,
Template);
} else {
IsFunctionTemplate = true;
Template = Context.getAssumedTemplateName(NameInfo.getName());
}
if (IsFunctionTemplate) {
Result.suppressDiagnostics();
return NameClassification::FunctionTemplate(Template);
}
return IsVarTemplate ? NameClassification::VarTemplate(Template)
: NameClassification::TypeTemplate(Template);
}
auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
QualType T = Context.getTypeDeclType(Type);
if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
T = Context.getUsingType(USD, T);
if (SS.isEmpty()) return ParsedType::make(T);
TypeLocBuilder Builder;
Builder.pushTypeSpec(T).setNameLoc(NameLoc);
T = getElaboratedType(ETK_None, SS, T);
ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
ElabTL.setElaboratedKeywordLoc(SourceLocation());
ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
};
NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
DiagnoseUseOfDecl(Type, NameLoc);
MarkAnyDeclReferenced(Type->getLocation(), Type, false);
return BuildTypeFor(Type, *Result.begin());
}
ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
if (!Class) {
if (ObjCCompatibleAliasDecl *Alias =
dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
Class = Alias->getClassInterface();
}
if (Class) {
DiagnoseUseOfDecl(Class, NameLoc);
if (NextToken.is(tok::period)) {
Result.suppressDiagnostics();
return NameClassification::Unknown();
}
QualType T = Context.getObjCInterfaceType(Class);
return ParsedType::make(T);
}
if (isa<ConceptDecl>(FirstDecl))
return NameClassification::Concept(
TemplateName(cast<TemplateDecl>(FirstDecl)));
if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
(void)DiagnoseUseOfDecl(EmptyD, NameLoc);
return NameClassification::Error();
}
if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
!isa<VarTemplateDecl>(FirstDecl))
return NameClassification::TypeTemplate(
TemplateName(cast<TemplateDecl>(FirstDecl)));
bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
if ((NextToken.is(tok::identifier) ||
(NextIsOp &&
FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
TypeDecl *Type = Result.getAsSingle<TypeDecl>();
DiagnoseUseOfDecl(Type, NameLoc);
return BuildTypeFor(Type, *Result.begin());
}
bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
return NameClassification::NonType(Result.getRepresentativeDecl());
Result.suppressDiagnostics();
return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
Result.begin(), Result.end()));
}
ExprResult
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
SourceLocation NameLoc) {
assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
CXXScopeSpec SS;
LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
return BuildDeclarationNameExpr(SS, Result, true);
}
ExprResult
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsAddressOfOperand) {
DeclarationNameInfo NameInfo(Name, NameLoc);
return ActOnDependentIdExpression(SS, SourceLocation(),
NameInfo, IsAddressOfOperand,
nullptr);
}
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken) {
if (getCurMethodDecl() && SS.isEmpty())
if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
return BuildIvarRefExpr(S, NameLoc, Ivar);
LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
Result.addDecl(Found);
Result.resolveKind();
bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
return BuildDeclarationNameExpr(SS, Result, ADL);
}
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
auto *ULE = cast<UnresolvedLookupExpr>(E);
if ((*ULE->decls_begin())->isCXXClassMember()) {
CXXScopeSpec SS;
SS.Adopt(ULE->getQualifierLoc());
LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
LookupOrdinaryName);
Result.setNamingClass(ULE->getNamingClass());
for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
Result.addDecl(*I, I.getAccess());
Result.resolveKind();
return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
nullptr, S);
}
return ULE;
}
Sema::TemplateNameKindForDiagnostics
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
auto *TD = Name.getAsTemplateDecl();
if (!TD)
return TemplateNameKindForDiagnostics::DependentTemplate;
if (isa<ClassTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::ClassTemplate;
if (isa<FunctionTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::FunctionTemplate;
if (isa<VarTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::VarTemplate;
if (isa<TypeAliasTemplateDecl>(TD))
return TemplateNameKindForDiagnostics::AliasTemplate;
if (isa<TemplateTemplateParmDecl>(TD))
return TemplateNameKindForDiagnostics::TemplateTemplateParam;
if (isa<ConceptDecl>(TD))
return TemplateNameKindForDiagnostics::Concept;
return TemplateNameKindForDiagnostics::DependentTemplate;
}
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
assert(DC->getLexicalParent() == CurContext &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = DC;
S->setEntity(DC);
}
void Sema::PopDeclContext() {
assert(CurContext && "DeclContext imbalance!");
CurContext = CurContext->getLexicalParent();
assert(CurContext && "Popped translation unit!");
}
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
Decl *D) {
auto Result = static_cast<SkippedDefinitionContext>(CurContext);
CurContext = cast<TagDecl>(D)->getDefinition();
assert(CurContext && "skipping definition of undefined tag");
S->setEntity(CurContext->getLookupParent());
return Result;
}
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
CurContext = static_cast<decltype(CurContext)>(Context);
}
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
assert(!S->getEntity() && "scope already has entity");
#ifndef NDEBUG
Scope *Ancestor = S->getParent();
while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
#endif
CurContext = DC;
S->setEntity(DC);
if (S->getParent()->isTemplateParamScope()) {
EnterTemplatedContext(S->getParent(), DC);
}
}
void Sema::ExitDeclaratorContext(Scope *S) {
assert(S->getEntity() == CurContext && "Context imbalance!");
Scope *Ancestor = S->getParent();
while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
CurContext = Ancestor->getEntity();
}
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
assert(S->isTemplateParamScope() &&
"expected to be initializing a template parameter scope");
unsigned ScopeDepth = getTemplateDepth(S);
for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
DeclContext *SearchDCAfterScope = DC;
for (; DC; DC = DC->getLookupParent()) {
if (const TemplateParameterList *TPL =
cast<Decl>(DC)->getDescribedTemplateParams()) {
unsigned DCDepth = TPL->getDepth() + 1;
if (DCDepth > ScopeDepth)
continue;
if (ScopeDepth == DCDepth)
SearchDCAfterScope = DC = DC->getLookupParent();
break;
}
}
S->setLookupEntity(SearchDCAfterScope);
}
}
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
FunctionDecl *FD = D->getAsFunction();
if (!FD)
return;
assert(CurContext == FD->getLexicalParent() &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = FD;
S->setEntity(CurContext);
for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
ParmVarDecl *Param = FD->getParamDecl(P);
if (Param->getIdentifier()) {
S->AddDecl(Param);
IdResolver.AddDecl(Param);
}
}
}
void Sema::ActOnExitFunctionContext() {
assert(CurContext && "DeclContext imbalance!");
CurContext = CurContext->getLexicalParent();
assert(CurContext && "Popped translation unit!");
}
static bool AllowOverloadingOfFunction(const LookupResult &Previous,
ASTContext &Context,
const FunctionDecl *New) {
if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
return true;
if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
return llvm::any_of(Previous, [](const NamedDecl *ND) {
return ND->hasAttr<OverloadableAttr>();
});
} else if (Previous.getResultKind() == LookupResult::Found)
return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
return false;
}
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
while (S->getEntity() && S->getEntity()->isTransparentContext())
S = S->getParent();
if (AddToContext)
CurContext->addDecl(D);
if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
return;
if (isa<FunctionDecl>(D) &&
cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
return;
IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
IEnd = IdResolver.end();
for (; I != IEnd; ++I) {
if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
S->RemoveDecl(*I);
IdResolver.RemoveDecl(*I);
break;
}
}
S->AddDecl(D);
if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
if (IDC == CurContext) {
if (!S->isDeclScope(*I))
continue;
} else if (IDC->Encloses(CurContext))
break;
}
IdResolver.InsertDeclAfter(I, D);
} else {
IdResolver.AddDecl(D);
}
warnOnReservedIdentifier(D);
}
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
bool AllowInlineNamespace) {
return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
}
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
DeclContext *TargetDC = DC->getPrimaryContext();
do {
if (DeclContext *ScopeDC = S->getEntity())
if (ScopeDC->getPrimaryContext() == TargetDC)
return S;
} while ((S = S->getParent()));
return nullptr;
}
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
DeclContext*,
ASTContext&);
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage,
bool AllowInlineNamespace) {
LookupResult::Filter F = R.makeFilter();
while (F.hasNext()) {
NamedDecl *D = F.next();
if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
continue;
if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
continue;
F.erase();
}
F.done();
}
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
if (New->getFriendObjectKind() &&
Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
New->setLocalOwningModule(Old->getOwningModule());
makeMergedDefinitionVisible(New);
return false;
}
Module *NewM = New->getOwningModule();
Module *OldM = Old->getOwningModule();
if (NewM && NewM->isPrivateModule())
NewM = NewM->Parent;
if (OldM && OldM->isPrivateModule())
OldM = OldM->Parent;
if (NewM == OldM)
return false;
if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
return NewM->getPrimaryModuleInterfaceName() ==
OldM->getPrimaryModuleInterfaceName();
bool NewIsModuleInterface = NewM && NewM->isModulePurview();
bool OldIsModuleInterface = OldM && OldM->isModulePurview();
if (NewIsModuleInterface || OldIsModuleInterface) {
Diag(New->getLocation(), diag::err_mismatched_owning_module)
<< New
<< NewIsModuleInterface
<< (NewIsModuleInterface ? NewM->getFullModuleName() : "")
<< OldIsModuleInterface
<< (OldIsModuleInterface ? OldM->getFullModuleName() : "");
Diag(Old->getLocation(), diag::note_previous_declaration);
New->setInvalidDecl();
return true;
}
return false;
}
bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
if (!New->getLexicalDeclContext()
->getNonTransparentContext()
->isFileContext() ||
!Old->getLexicalDeclContext()
->getNonTransparentContext()
->isFileContext())
return false;
bool IsNewExported = New->isInExportDeclContext();
bool IsOldExported = Old->isInExportDeclContext();
if (!IsNewExported && !IsOldExported)
return false;
if (IsOldExported)
return false;
assert(IsNewExported);
auto Lk = Old->getFormalLinkage();
int S = 0;
if (Lk == Linkage::InternalLinkage)
S = 1;
else if (Lk == Linkage::ModuleLinkage)
S = 2;
Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
Diag(Old->getLocation(), diag::note_previous_declaration);
return true;
}
bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
if (CheckRedeclarationModuleOwnership(New, Old))
return true;
if (CheckRedeclarationExported(New, Old))
return true;
return false;
}
bool Sema::IsRedefinitionInModule(const NamedDecl *New,
const NamedDecl *Old) const {
assert(getASTContext().isSameEntity(New, Old) &&
"New and Old are not the same definition, we should diagnostic it "
"immediately instead of checking it.");
assert(const_cast<Sema *>(this)->isReachable(New) &&
const_cast<Sema *>(this)->isReachable(Old) &&
"We shouldn't see unreachable definitions here.");
Module *NewM = New->getOwningModule();
Module *OldM = Old->getOwningModule();
if (NewM && NewM->isHeaderLikeModule())
NewM = nullptr;
if (OldM && OldM->isHeaderLikeModule())
OldM = nullptr;
if (!NewM && !OldM)
return true;
if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
return true;
if (NewM)
NewM = NewM->getTopLevelModule();
if (OldM)
OldM = OldM->getTopLevelModule();
return OldM == NewM;
}
static bool isUsingDecl(NamedDecl *D) {
return isa<UsingShadowDecl>(D) ||
isa<UnresolvedUsingTypenameDecl>(D) ||
isa<UnresolvedUsingValueDecl>(D);
}
static void RemoveUsingDecls(LookupResult &R) {
LookupResult::Filter F = R.makeFilter();
while (F.hasNext())
if (isUsingDecl(F.next()))
F.erase();
F.done();
}
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
if (D->doesThisDeclarationHaveABody())
return false;
if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
return CD->isCopyConstructor();
return D->isCopyAssignmentOperator();
}
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
const DeclContext *DC = D->getDeclContext();
while (!DC->isTranslationUnit()) {
if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
if (!RD->hasNameForLinkage())
return true;
}
DC = DC->getParent();
}
return !D->isExternallyVisible();
}
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
if (S.TUKind != TU_Complete)
return false;
return S.SourceMgr.isInMainFile(Loc);
}
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
assert(D);
if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
return false;
if (D->getDeclContext()->isDependentContext() ||
D->getLexicalDeclContext()->isDependentContext())
return false;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
return false;
if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
return false;
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
return false;
} else {
if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
return false;
}
if (FD->doesThisDeclarationHaveABody() &&
Context.DeclMustBeEmitted(FD))
return false;
} else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
if (!isMainFileLoc(*this, VD->getLocation()))
return false;
if (Context.DeclMustBeEmitted(VD))
return false;
if (VD->isStaticDataMember() &&
VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
return false;
if (VD->isStaticDataMember() &&
VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
return false;
if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
return false;
} else {
return false;
}
return mightHaveNonExternalLinkage(D);
}
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
if (!D)
return;
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
const FunctionDecl *First = FD->getFirstDecl();
if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
return; }
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
const VarDecl *First = VD->getFirstDecl();
if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
return; }
if (ShouldWarnIfUnusedFileScopedDecl(D))
UnusedFileScopedDecls.push_back(D);
}
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
if (D->isInvalidDecl())
return false;
if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
for (auto *BD : DD->bindings())
if (BD->isReferenced())
return false;
} else if (!D->getDeclName()) {
return false;
} else if (D->isReferenced() || D->isUsed()) {
return false;
}
if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
return false;
if (isa<LabelDecl>(D))
return true;
bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
WithinFunction =
WithinFunction || (R->isLocalClass() && !R->isDependentType());
if (!WithinFunction)
return false;
if (isa<TypedefNameDecl>(D))
return true;
if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
return false;
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
const Expr *Init = VD->getInit();
if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
Init = Cleanups->getSubExpr();
const auto *Ty = VD->getType().getTypePtr();
if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
if (TT->getDecl()->hasAttr<UnusedAttr>())
return false;
}
if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
if (MTE->getExtendingDecl()) {
Ty = VD->getType().getNonReferenceType().getTypePtr();
Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
}
}
if (Ty->isIncompleteType() || Ty->isDependentType())
return false;
Ty = Ty->getBaseElementTypeUnsafe();
if (const TagType *TT = Ty->getAs<TagType>()) {
const TagDecl *Tag = TT->getDecl();
if (Tag->hasAttr<UnusedAttr>())
return false;
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
return false;
if (Init) {
const CXXConstructExpr *Construct =
dyn_cast<CXXConstructExpr>(Init);
if (Construct && !Construct->isElidable()) {
CXXConstructorDecl *CD = Construct->getConstructor();
if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
(VD->getInit()->isValueDependent() || !VD->evaluateValue()))
return false;
}
if (Init->isTypeDependent()) {
for (const CXXConstructorDecl *Ctor : RD->ctors())
if (!Ctor->isTrivial())
return false;
}
if (isa<CXXUnresolvedConstructExpr>(Init))
return false;
}
}
}
}
return true;
}
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
FixItHint &Hint) {
if (isa<LabelDecl>(D)) {
SourceLocation AfterColon = Lexer::findLocationAfterToken(
D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
true);
if (AfterColon.isInvalid())
return;
Hint = FixItHint::CreateRemoval(
CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
}
}
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
if (D->getTypeForDecl()->isDependentType())
return;
for (auto *TmpD : D->decls()) {
if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
DiagnoseUnusedDecl(T);
else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
DiagnoseUnusedNestedTypedefs(R);
}
}
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
if (!ShouldDiagnoseUnusedDecl(D))
return;
if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
UnusedLocalTypedefNameCandidates.insert(TD);
return;
}
FixItHint Hint;
GenerateFixForUnusedDecl(D, Context, Hint);
unsigned DiagID;
if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
DiagID = diag::warn_unused_exception_param;
else if (isa<LabelDecl>(D))
DiagID = diag::warn_unused_label;
else
DiagID = diag::warn_unused_variable;
Diag(D->getLocation(), DiagID) << D << Hint;
}
void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
VD->hasAttr<CleanupAttr>())
return;
const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
if (Ty->isReferenceType() || Ty->isDependentType())
return;
if (const TagType *TT = Ty->getAs<TagType>()) {
const TagDecl *Tag = TT->getDecl();
if (Tag->hasAttr<UnusedAttr>())
return;
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
if (!RD->hasAttr<WarnUnusedAttr>())
return;
}
}
if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
return;
if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
return;
auto iter = RefsMinusAssignments.find(VD);
if (iter == RefsMinusAssignments.end())
return;
assert(iter->getSecond() >= 0 &&
"Found a negative number of references to a VarDecl");
if (iter->getSecond() != 0)
return;
unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
: diag::warn_unused_but_set_variable;
Diag(VD->getLocation(), DiagID) << VD;
}
static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
bool Diagnose = false;
if (L->isMSAsmLabel())
Diagnose = !L->isResolvedMSAsmLabel();
else
Diagnose = L->getStmt() == nullptr;
if (Diagnose)
S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
}
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
S->applyNRVO();
if (S->decl_empty()) return;
assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
"Scope shouldn't contain decls!");
for (auto *TmpD : S->decls()) {
assert(TmpD && "This decl didn't get pushed??");
assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
NamedDecl *D = cast<NamedDecl>(TmpD);
if (!S->hasUnrecoverableErrorOccurred()) {
DiagnoseUnusedDecl(D);
if (const auto *RD = dyn_cast<RecordDecl>(D))
DiagnoseUnusedNestedTypedefs(RD);
if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
DiagnoseUnusedButSetDecl(VD);
RefsMinusAssignments.erase(VD);
}
}
if (!D->getDeclName()) continue;
if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
CheckPoppedLabel(LD, *this);
IdResolver.RemoveDecl(D);
auto ShadowI = ShadowingDecls.find(D);
if (ShadowI != ShadowingDecls.end()) {
if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
<< D << FD << FD->getParent();
Diag(FD->getLocation(), diag::note_previous_declaration);
}
ShadowingDecls.erase(ShadowI);
}
}
}
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool DoTypoCorrection) {
NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
if (!IDecl && DoTypoCorrection) {
DeclFilterCCC<ObjCInterfaceDecl> CCC{};
if (TypoCorrection C =
CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
Id = IDecl->getIdentifier();
}
}
ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
if (Def && Def->getDefinition())
Def = Def->getDefinition();
return Def;
}
Scope *Sema::getNonFieldDeclScope(Scope *S) {
while (((S->getFlags() & Scope::DeclScope) == 0) ||
(S->getEntity() && S->getEntity()->isTransparentContext()) ||
(S->isClassScope() && !getLangOpts().CPlusPlus))
S = S->getParent();
return S;
}
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
ASTContext::GetBuiltinTypeError Error) {
switch (Error) {
case ASTContext::GE_None:
return "";
case ASTContext::GE_Missing_type:
return BuiltinInfo.getHeaderName(ID);
case ASTContext::GE_Missing_stdio:
return "stdio.h";
case ASTContext::GE_Missing_setjmp:
return "setjmp.h";
case ASTContext::GE_Missing_ucontext:
return "ucontext.h";
}
llvm_unreachable("unhandled error kind");
}
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
unsigned ID, SourceLocation Loc) {
DeclContext *Parent = Context.getTranslationUnitDecl();
if (getLangOpts().CPlusPlus) {
LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
CLinkageDecl->setImplicit();
Parent->addDecl(CLinkageDecl);
Parent = CLinkageDecl;
}
FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
nullptr, SC_Extern,
getCurFPFeatures().isFPConstrained(),
false, Type->isFunctionProtoType());
New->setImplicit();
New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
SmallVector<ParmVarDecl *, 16> Params;
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
ParmVarDecl *parm = ParmVarDecl::Create(
Context, New, SourceLocation(), SourceLocation(), nullptr,
FT->getParamType(i), nullptr, SC_None, nullptr);
parm->setScopeInfo(0, i);
Params.push_back(parm);
}
New->setParams(Params);
}
AddKnownFunctionAttributes(New);
return New;
}
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc) {
LookupNecessaryTypesForBuiltin(S, ID);
ASTContext::GetBuiltinTypeError Error;
QualType R = Context.GetBuiltinType(ID, Error);
if (Error) {
if (!ForRedeclaration)
return nullptr;
if (Error == ASTContext::GE_Missing_type ||
Context.BuiltinInfo.allowTypeMismatch(ID))
return nullptr;
if (Error == ASTContext::GE_Missing_setjmp) {
Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
<< Context.BuiltinInfo.getName(ID);
return nullptr;
}
Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
<< getHeaderName(Context.BuiltinInfo, ID, Error)
<< Context.BuiltinInfo.getName(ID);
return nullptr;
}
if (!ForRedeclaration &&
(Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
: diag::ext_implicit_lib_function_decl)
<< Context.BuiltinInfo.getName(ID) << R;
if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
Diag(Loc, diag::note_include_header_or_declare)
<< Header << Context.BuiltinInfo.getName(ID);
}
if (R.isNull())
return nullptr;
FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
RegisterLocallyScopedExternCDecl(New, S);
DeclContext *SavedContext = CurContext;
CurContext = New->getDeclContext();
PushOnScopeChains(New, TUScope);
CurContext = SavedContext;
return New;
}
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
TypedefNameDecl *Decl,
LookupResult &Previous) {
if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
return;
if (Previous.empty())
return;
LookupResult::Filter Filter = Previous.makeFilter();
while (Filter.hasNext()) {
NamedDecl *Old = Filter.next();
if (S.isVisible(Old))
continue;
if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
if (S.Context.hasSameType(OldTD->getUnderlyingType(),
Decl->getUnderlyingType()))
continue;
if (OldTD->getAnonDeclWithTypedefName(true) &&
Decl->getAnonDeclWithTypedefName())
continue;
}
Filter.erase();
}
Filter.done();
}
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
QualType OldType;
if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
OldType = OldTypedef->getUnderlyingType();
else
OldType = Context.getTypeDeclType(Old);
QualType NewType = New->getUnderlyingType();
if (NewType->isVariablyModifiedType()) {
int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
<< Kind << NewType;
if (Old->getLocation().isValid())
notePreviousDefinition(Old, New->getLocation());
New->setInvalidDecl();
return true;
}
if (OldType != NewType &&
!OldType->isDependentType() &&
!NewType->isDependentType() &&
!Context.hasSameType(OldType, NewType)) {
int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
Diag(New->getLocation(), diag::err_redefinition_different_typedef)
<< Kind << NewType << OldType;
if (Old->getLocation().isValid())
notePreviousDefinition(Old, New->getLocation());
New->setInvalidDecl();
return true;
}
return false;
}
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls) {
if (New->isInvalidDecl()) return;
if (getLangOpts().ObjC) {
const IdentifierInfo *TypeID = New->getIdentifier();
switch (TypeID->getLength()) {
default: break;
case 2:
{
if (!TypeID->isStr("id"))
break;
QualType T = New->getUnderlyingType();
if (!T->isPointerType())
break;
if (!T->isVoidPointerType()) {
QualType PT = T->castAs<PointerType>()->getPointeeType();
if (!PT->isStructureType())
break;
}
Context.setObjCIdRedefinitionType(T);
New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
return;
}
case 5:
if (!TypeID->isStr("Class"))
break;
Context.setObjCClassRedefinitionType(New->getUnderlyingType());
New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
return;
case 3:
if (!TypeID->isStr("SEL"))
break;
Context.setObjCSelRedefinitionType(New->getUnderlyingType());
New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
return;
}
}
TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
NamedDecl *OldD = OldDecls.getRepresentativeDecl();
if (OldD->getLocation().isValid())
notePreviousDefinition(OldD, New->getLocation());
return New->setInvalidDecl();
}
if (Old->isInvalidDecl())
return New->setInvalidDecl();
if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
auto *OldTag = OldTD->getAnonDeclWithTypedefName(true);
auto *NewTag = New->getAnonDeclWithTypedefName();
NamedDecl *Hidden = nullptr;
if (OldTag && NewTag &&
OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
!hasVisibleDefinition(OldTag, &Hidden)) {
New->setTypeForDecl(OldTD->getTypeForDecl());
if (OldTD->isModed())
New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
OldTD->getUnderlyingType());
else
New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
makeMergedDefinitionVisible(Hidden);
if (isa<EnumDecl>(NewTag)) {
Scope *EnumScope = getNonFieldDeclScope(S);
for (auto *D : NewTag->decls()) {
auto *ED = cast<EnumConstantDecl>(D);
assert(EnumScope->isDeclScope(ED));
EnumScope->RemoveDecl(ED);
IdResolver.RemoveDecl(ED);
ED->getLexicalDeclContext()->removeDecl(ED);
}
}
}
}
if (isIncompatibleTypedef(Old, New))
return;
if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
New->setPreviousDecl(Typedef);
mergeDeclAttributes(New, Old);
}
if (getLangOpts().MicrosoftExt)
return;
if (getLangOpts().CPlusPlus) {
if (!isa<CXXRecordDecl>(CurContext))
return;
if (!isa<TypedefNameDecl>(Old))
return;
Diag(New->getLocation(), diag::err_redefinition)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
return New->setInvalidDecl();
}
if (getLangOpts().Modules || getLangOpts().C11)
return;
if (getDiagnostics().getSuppressSystemWarnings() &&
(Old->isImplicit() ||
Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
Context.getSourceManager().isInSystemHeader(New->getLocation())))
return;
Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
<< New->getDeclName();
notePreviousDefinition(Old, New->getLocation());
}
static bool DeclHasAttr(const Decl *D, const Attr *A) {
const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
for (const auto *i : D->attrs())
if (i->getKind() == A->getKind()) {
if (Ann) {
if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
return true;
continue;
}
if (OA && isa<OwnershipAttr>(i))
return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
return true;
}
return false;
}
static bool isAttributeTargetADefinition(Decl *D) {
if (VarDecl *VD = dyn_cast<VarDecl>(D))
return VD->isThisDeclarationADefinition();
if (TagDecl *TD = dyn_cast<TagDecl>(D))
return TD->isCompleteDefinition() || TD->isBeingDefined();
return true;
}
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
AlignedAttr *OldAlignasAttr = nullptr;
AlignedAttr *OldStrictestAlignAttr = nullptr;
unsigned OldAlign = 0;
for (auto *I : Old->specific_attrs<AlignedAttr>()) {
if (I->isAlignmentDependent())
return false;
if (I->isAlignas())
OldAlignasAttr = I;
unsigned Align = I->getAlignment(S.Context);
if (Align > OldAlign) {
OldAlign = Align;
OldStrictestAlignAttr = I;
}
}
AlignedAttr *NewAlignasAttr = nullptr;
unsigned NewAlign = 0;
for (auto *I : New->specific_attrs<AlignedAttr>()) {
if (I->isAlignmentDependent())
return false;
if (I->isAlignas())
NewAlignasAttr = I;
unsigned Align = I->getAlignment(S.Context);
if (Align > NewAlign)
NewAlign = Align;
}
if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
if (OldAlign == 0 || NewAlign == 0) {
QualType Ty;
if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
Ty = VD->getType();
else
Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
if (OldAlign == 0)
OldAlign = S.Context.getTypeAlign(Ty);
if (NewAlign == 0)
NewAlign = S.Context.getTypeAlign(Ty);
}
if (OldAlign != NewAlign) {
S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
<< (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
<< (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
}
}
if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
<< OldAlignasAttr;
S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
<< OldAlignasAttr;
}
bool AnyAdded = false;
if (OldAlign > NewAlign) {
AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
Clone->setInherited(true);
New->addAttr(Clone);
AnyAdded = true;
}
if (OldAlignasAttr && !NewAlignasAttr &&
!(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
Clone->setInherited(true);
New->addAttr(Clone);
AnyAdded = true;
}
return AnyAdded;
}
#define WANT_DECL_MERGE_LOGIC
#include "clang/Sema/AttrParsedAttrImpl.inc"
#undef WANT_DECL_MERGE_LOGIC
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
const InheritableAttr *Attr,
Sema::AvailabilityMergeKind AMK) {
if (!DiagnoseMutualExclusions(S, D, Attr))
return false;
InheritableAttr *NewAttr = nullptr;
if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
NewAttr = S.mergeAvailabilityAttr(
D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
AA->getPriority());
else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
NewAttr = S.mergeDLLImportAttr(D, *ImportA);
else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
NewAttr = S.mergeDLLExportAttr(D, *ExportA);
else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
FA->getFirstArg());
else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
IA->getInheritanceModel());
else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
&S.Context.Idents.get(AA->getSpelling()));
else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
(isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
isa<CUDAGlobalAttr>(Attr))) {
return false;
} else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
NewAttr = S.mergeMinSizeAttr(D, *MA);
else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
else if (isa<AlignedAttr>(Attr))
NewAttr = nullptr;
else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
(AMK == Sema::AMK_Override ||
AMK == Sema::AMK_ProtocolImplementation ||
AMK == Sema::AMK_OptionalProtocolImplementation))
NewAttr = nullptr;
else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
NewAttr = S.mergeImportModuleAttr(D, *IMA);
else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
NewAttr = S.mergeImportNameAttr(D, *INA);
else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
NewAttr =
S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
if (NewAttr) {
NewAttr->setInherited(true);
D->addAttr(NewAttr);
if (isa<MSInheritanceAttr>(NewAttr))
S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
return true;
}
return false;
}
static const NamedDecl *getDefinition(const Decl *D) {
if (const TagDecl *TD = dyn_cast<TagDecl>(D))
return TD->getDefinition();
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
const VarDecl *Def = VD->getDefinition();
if (Def)
return Def;
return VD->getActingDefinition();
}
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
const FunctionDecl *Def = nullptr;
if (FD->isDefined(Def, true))
return Def;
}
return nullptr;
}
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
for (const auto *Attribute : D->attrs())
if (Attribute->getKind() == Kind)
return true;
return false;
}
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
if (!New->hasAttrs())
return;
const NamedDecl *Def = getDefinition(Old);
if (!Def || Def == New)
return;
AttrVec &NewAttributes = New->getAttrs();
for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
const Attr *NewAttribute = NewAttributes[I];
if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
Sema::SkipBodyInfo SkipBody;
S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
if (SkipBody.ShouldSkip) {
NewAttributes.erase(NewAttributes.begin() + I);
--E;
continue;
}
} else {
VarDecl *VD = cast<VarDecl>(New);
unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
VarDecl::TentativeDefinition
? diag::err_alias_after_tentative
: diag::err_redefinition;
S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
if (Diag == diag::err_redefinition)
S.notePreviousDefinition(Def, VD->getLocation());
else
S.Diag(Def->getLocation(), diag::note_previous_definition);
VD->setInvalidDecl();
}
++I;
continue;
}
if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
++I;
continue;
}
}
if (hasAttribute(Def, NewAttribute->getKind())) {
++I;
continue; }
if (isa<C11NoReturnAttr>(NewAttribute)) {
++I;
continue;
} else if (isa<UuidAttr>(NewAttribute)) {
++I;
continue;
} else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
if (AA->isAlignas()) {
S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
<< AA;
S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
<< AA;
NewAttributes.erase(NewAttributes.begin() + I);
--E;
continue;
}
} else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
if (!S.getLangOpts().CPlusPlus) {
S.Diag(NewAttribute->getLocation(),
diag::err_loader_uninitialized_redeclaration);
S.Diag(Def->getLocation(), diag::note_previous_definition);
NewAttributes.erase(NewAttributes.begin() + I);
--E;
continue;
}
} else if (isa<SelectAnyAttr>(NewAttribute) &&
cast<VarDecl>(New)->isInline() &&
!cast<VarDecl>(New)->isInlineSpecified()) {
++I;
continue;
} else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
++I;
continue;
}
S.Diag(NewAttribute->getLocation(),
diag::warn_attribute_precede_definition);
S.Diag(Def->getLocation(), diag::note_previous_definition);
NewAttributes.erase(NewAttributes.begin() + I);
--E;
}
}
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
const ConstInitAttr *CIAttr,
bool AttrBeforeInit) {
SourceLocation InsertLoc = InitDecl->getInnerLocStart();
std::string SuitableSpelling;
if (S.getLangOpts().CPlusPlus20)
SuitableSpelling = std::string(
S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
InsertLoc, {tok::l_square, tok::l_square,
S.PP.getIdentifierInfo("clang"), tok::coloncolon,
S.PP.getIdentifierInfo("require_constant_initialization"),
tok::r_square, tok::r_square}));
if (SuitableSpelling.empty())
SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
S.PP.getIdentifierInfo("require_constant_initialization"),
tok::r_paren, tok::r_paren}));
if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
SuitableSpelling = "constinit";
if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
SuitableSpelling = "[[clang::require_constant_initialization]]";
if (SuitableSpelling.empty())
SuitableSpelling = "__attribute__((require_constant_initialization))";
SuitableSpelling += " ";
if (AttrBeforeInit) {
assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
<< InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
} else {
S.Diag(CIAttr->getLocation(),
CIAttr->isConstinit() ? diag::err_constinit_added_too_late
: diag::warn_require_const_init_added_too_late)
<< FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
<< CIAttr->isConstinit()
<< FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
}
}
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK) {
if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
UsedAttr *NewAttr = OldAttr->clone(Context);
NewAttr->setInherited(true);
New->addAttr(NewAttr);
}
if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
RetainAttr *NewAttr = OldAttr->clone(Context);
NewAttr->setInherited(true);
New->addAttr(NewAttr);
}
if (!Old->hasAttrs() && !New->hasAttrs())
return;
const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
const auto *NewConstInit = New->getAttr<ConstInitAttr>();
if (bool(OldConstInit) != bool(NewConstInit)) {
const auto *OldVD = cast<VarDecl>(Old);
auto *NewVD = cast<VarDecl>(New);
const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
if (!InitDecl &&
(NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
InitDecl = NewVD;
if (InitDecl == NewVD) {
if (OldConstInit && OldConstInit->isConstinit())
diagnoseMissingConstinit(*this, NewVD, OldConstInit,
true);
} else if (NewConstInit) {
if (InitDecl && InitDecl != NewVD) {
diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
false);
NewVD->dropAttr<ConstInitAttr>();
}
}
}
checkNewAttributesAfterDef(*this, New, Old);
if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
if (!OldA->isEquivalent(NewA)) {
Diag(New->getLocation(), diag::err_different_asm_label);
Diag(OldA->getLocation(), diag::note_previous_declaration);
}
} else if (Old->isUsed()) {
Diag(New->getLocation(), diag::err_late_asm_label_name)
<< isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
}
}
if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
for (const auto &NewTag : NewAbiTagAttr->tags()) {
if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
Diag(NewAbiTagAttr->getLocation(),
diag::err_new_abi_tag_on_redeclaration)
<< NewTag;
Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
}
}
} else {
Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
Diag(Old->getLocation(), diag::note_previous_declaration);
}
}
if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
if (auto *VD = dyn_cast<VarDecl>(New)) {
if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
Diag(Old->getLocation(), diag::note_previous_declaration);
}
}
}
const auto *NewCSA = New->getAttr<CodeSegAttr>();
if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
!NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
Diag(New->getLocation(), diag::warn_mismatched_section)
<< 0 ;
Diag(Old->getLocation(), diag::note_previous_declaration);
}
if (!Old->hasAttrs())
return;
bool foundAny = New->hasAttrs();
if (!foundAny) New->setAttrs(AttrVec());
for (auto *I : Old->specific_attrs<InheritableAttr>()) {
AvailabilityMergeKind LocalAMK = AMK_None;
if (isa<DeprecatedAttr>(I) ||
isa<UnavailableAttr>(I) ||
isa<AvailabilityAttr>(I)) {
switch (AMK) {
case AMK_None:
continue;
case AMK_Redeclaration:
case AMK_Override:
case AMK_ProtocolImplementation:
case AMK_OptionalProtocolImplementation:
LocalAMK = AMK;
break;
}
}
if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
continue;
if (mergeDeclAttribute(*this, New, I, LocalAMK))
foundAny = true;
}
if (mergeAlignedAttrs(*this, New, Old))
foundAny = true;
if (!foundAny) New->dropAttrs();
}
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
const ParmVarDecl *oldDecl,
Sema &S) {
const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
S.Diag(CDA->getLocation(),
diag::err_carries_dependency_missing_on_first_decl) << 1;
const FunctionDecl *FirstFD =
cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
const ParmVarDecl *FirstVD =
FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
S.Diag(FirstVD->getLocation(),
diag::note_carries_dependency_missing_first_decl) << 1;
}
if (!oldDecl->hasAttrs())
return;
bool foundAny = newDecl->hasAttrs();
if (!foundAny) newDecl->setAttrs(AttrVec());
for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
if (!DeclHasAttr(newDecl, I)) {
InheritableAttr *newAttr =
cast<InheritableParamAttr>(I->clone(S.Context));
newAttr->setInherited(true);
newDecl->addAttr(newAttr);
foundAny = true;
}
}
if (!foundAny) newDecl->dropAttrs();
}
static bool EquivalentArrayTypes(QualType Old, QualType New,
const ASTContext &Ctx) {
auto NoSizeInfo = [&Ctx](QualType Ty) {
if (Ty->isIncompleteArrayType() || Ty->isPointerType())
return true;
if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
return false;
};
if (NoSizeInfo(Old) && NoSizeInfo(New))
return true;
if (Old->isVariableArrayType() && New->isVariableArrayType()) {
const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
const auto *NewVAT = Ctx.getAsVariableArrayType(New);
if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
(NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
return false;
return true;
}
if (Old->isConstantArrayType() && New->isConstantArrayType()) {
return Ctx.getAsConstantArrayType(Old)->getSize() ==
Ctx.getAsConstantArrayType(New)->getSize();
}
if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
return true;
}
return Old == New;
}
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
const ParmVarDecl *OldParam,
Sema &S) {
if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
if (*Oldnullability != *Newnullability) {
S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
<< DiagNullabilityKind(
*Newnullability,
((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0))
<< DiagNullabilityKind(
*Oldnullability,
((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0));
S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
}
} else {
QualType NewT = NewParam->getType();
NewT = S.Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*Oldnullability),
NewT, NewT);
NewParam->setType(NewT);
}
}
const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
if (OldParamDT && NewParamDT &&
OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
QualType OldParamOT = OldParamDT->getOriginalType();
QualType NewParamOT = NewParamDT->getOriginalType();
if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
<< NewParam << NewParamOT;
S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
<< OldParamOT;
}
}
}
namespace {
struct GNUCompatibleParamWarning {
ParmVarDecl *OldParm;
ParmVarDecl *NewParm;
QualType PromotedType;
};
}
template <typename T>
static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
diag::kind PrevDiag;
SourceLocation OldLocation = Old->getLocation();
if (Old->isThisDeclarationADefinition())
PrevDiag = diag::note_previous_definition;
else if (Old->isImplicit()) {
PrevDiag = diag::note_previous_implicit_declaration;
if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
if (FD->getBuiltinID())
PrevDiag = diag::note_previous_builtin_declaration;
}
if (OldLocation.isInvalid())
OldLocation = New->getLocation();
} else
PrevDiag = diag::note_previous_declaration;
return std::make_pair(PrevDiag, OldLocation);
}
static bool canRedefineFunction(const FunctionDecl *FD,
const LangOptions& LangOpts) {
return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
!LangOpts.CPlusPlus &&
FD->isInlineSpecified() &&
FD->getStorageClass() == SC_Extern);
}
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
const AttributedType *AT = T->getAs<AttributedType>();
while (AT && !AT->isCallingConv())
AT = AT->getModifiedType()->getAs<AttributedType>();
return AT;
}
template <typename T>
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
const DeclContext *DC = Old->getDeclContext();
if (DC->isRecord())
return false;
LanguageLinkage OldLinkage = Old->getLanguageLinkage();
if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
return true;
if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
return true;
return false;
}
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
static bool isExternC(VarTemplateDecl *) { return false; }
static bool isExternC(FunctionTemplateDecl *) { return false; }
template<typename ExpectedDecl>
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
ExpectedDecl *New) {
auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
if (Old &&
!Old->getDeclContext()->getRedeclContext()->Equals(
New->getDeclContext()->getRedeclContext()) &&
!(isExternC(Old) && isExternC(New)))
Old = nullptr;
if (!Old) {
S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
return true;
}
return false;
}
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
const FunctionDecl *B) {
assert(A->getNumParams() == B->getNumParams());
auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
if (AttrA == AttrB)
return true;
return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
AttrA->isDynamic() == AttrB->isDynamic();
};
return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
}
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
DeclaratorDecl *OldD) {
if (!NewD->getQualifier())
return;
auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
if (NamedDC->Equals(SemaDC))
return;
assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
"unexpected context for redeclaration");
auto *LexDC = NewD->getLexicalDeclContext();
auto FixSemaDC = [=](NamedDecl *D) {
if (!D)
return;
D->setDeclContext(SemaDC);
D->setLexicalDeclContext(LexDC);
};
FixSemaDC(NewD);
if (auto *FD = dyn_cast<FunctionDecl>(NewD))
FixSemaDC(FD->getDescribedFunctionTemplate());
else if (auto *VD = dyn_cast<VarDecl>(NewD))
FixSemaDC(VD->getDescribedVarTemplate());
}
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
bool MergeTypeWithOld, bool NewDeclIsDefn) {
FunctionDecl *Old = OldD->getAsFunction();
if (!Old) {
if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
if (New->getFriendObjectKind()) {
Diag(New->getLocation(), diag::err_using_decl_friend);
Diag(Shadow->getTargetDecl()->getLocation(),
diag::note_using_decl_target);
Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
<< 0;
return true;
}
if (FunctionTemplateDecl *NewTemplate =
New->getDescribedFunctionTemplate()) {
if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
NewTemplate))
return true;
OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
->getAsFunction();
} else {
if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
return true;
OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
}
} else {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
notePreviousDefinition(OldD, New->getLocation());
return true;
}
}
adjustDeclContextForDeclaratorDecl(New, Old);
if (Old->isInvalidDecl())
return true;
if (!getASTContext().canBuiltinBeRedeclared(Old)) {
Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
<< Old << Old->getType();
return true;
}
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation) =
getNoteDiagForInvalidRedeclaration(Old, New);
if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
New->getStorageClass() == SC_Static &&
Old->hasExternalFormalLinkage() &&
!New->getTemplateSpecializationInfo() &&
!canRedefineFunction(Old, getLangOpts())) {
if (getLangOpts().MicrosoftExt) {
Diag(New->getLocation(), diag::ext_static_non_static) << New;
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_static_non_static) << New;
Diag(OldLocation, PrevDiag);
return true;
}
}
if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
if (!Old->hasAttr<InternalLinkageAttr>()) {
Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
<< ILA;
Diag(Old->getLocation(), diag::note_previous_declaration);
New->dropAttr<InternalLinkageAttr>();
}
if (auto *EA = New->getAttr<ErrorAttr>()) {
if (!Old->hasAttr<ErrorAttr>()) {
Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
Diag(Old->getLocation(), diag::note_previous_declaration);
New->dropAttr<ErrorAttr>();
}
}
if (CheckRedeclarationInModule(New, Old))
return true;
if (!getLangOpts().CPlusPlus) {
bool OldOvl = Old->hasAttr<OverloadableAttr>();
if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
<< New << OldOvl;
const Decl *DiagOld = Old;
if (OldOvl) {
auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
const auto *A = D->getAttr<OverloadableAttr>();
return A && !A->isImplicit();
});
DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
}
if (DiagOld)
Diag(DiagOld->getLocation(),
diag::note_attribute_overloadable_prev_overload)
<< OldOvl;
if (OldOvl)
New->addAttr(OverloadableAttr::CreateImplicit(Context));
else
New->dropAttr<OverloadableAttr>();
}
}
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
const FunctionType *OldType = cast<FunctionType>(OldQType);
const FunctionType *NewType = cast<FunctionType>(NewQType);
FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
bool RequiresAdjustment = false;
if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
FunctionDecl *First = Old->getFirstDecl();
const FunctionType *FT =
First->getType().getCanonicalType()->castAs<FunctionType>();
FunctionType::ExtInfo FI = FT->getExtInfo();
bool NewCCExplicit = getCallingConvAttributedType(New->getType());
if (!NewCCExplicit) {
NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
RequiresAdjustment = true;
} else if (Old->getBuiltinID()) {
Diag(New->getLocation(), diag::warn_cconv_unsupported)
<< FunctionType::getNameForCallConv(NewTypeInfo.getCC())
<< (int)CallingConventionIgnoredReason::BuiltinFunction;
NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
RequiresAdjustment = true;
} else {
bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
Diag(New->getLocation(), diag::err_cconv_change)
<< FunctionType::getNameForCallConv(NewTypeInfo.getCC())
<< !FirstCCExplicit
<< (!FirstCCExplicit ? "" :
FunctionType::getNameForCallConv(FI.getCC()));
Diag(First->getLocation(), diag::note_previous_declaration);
return true;
}
}
if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
NewTypeInfo = NewTypeInfo.withNoReturn(true);
RequiresAdjustment = true;
}
if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
if (NewTypeInfo.getHasRegParm()) {
Diag(New->getLocation(), diag::err_regparm_mismatch)
<< NewType->getRegParmType()
<< OldType->getRegParmType();
Diag(OldLocation, diag::note_previous_declaration);
return true;
}
NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
RequiresAdjustment = true;
}
if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
if (NewTypeInfo.getProducesResult()) {
Diag(New->getLocation(), diag::err_function_attribute_mismatch)
<< "'ns_returns_retained'";
Diag(OldLocation, diag::note_previous_declaration);
return true;
}
NewTypeInfo = NewTypeInfo.withProducesResult(true);
RequiresAdjustment = true;
}
if (OldTypeInfo.getNoCallerSavedRegs() !=
NewTypeInfo.getNoCallerSavedRegs()) {
if (NewTypeInfo.getNoCallerSavedRegs()) {
AnyX86NoCallerSavedRegistersAttr *Attr =
New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
Diag(OldLocation, diag::note_previous_declaration);
return true;
}
NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
RequiresAdjustment = true;
}
if (RequiresAdjustment) {
const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
New->setType(QualType(AdjustedType, 0));
NewQType = Context.getCanonicalType(New->getType());
}
if (!Old->isInlined() && New->isInlined() &&
!New->hasAttr<GNUInlineAttr>() &&
!getLangOpts().GNUInline &&
Old->isUsed(false) &&
!Old->isDefined() && !New->isThisDeclarationADefinition())
UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
SourceLocation()));
if (New->hasAttr<GNUInlineAttr>() &&
Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
UndefinedButUsed.erase(Old->getCanonicalDecl());
}
if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
!hasIdenticalPassObjectSizeAttrs(Old, New)) {
Diag(New->getLocation(), diag::err_different_pass_object_size_params)
<< New->getDeclName();
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
}
if (getLangOpts().CPlusPlus) {
if (CheckEquivalentExceptionSpec(Old, New))
return true;
OldQType = Context.getCanonicalType(Old->getType());
NewQType = Context.getCanonicalType(New->getType());
QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
QualType NewDeclaredReturnType = New->getDeclaredReturnType();
if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
OldDeclaredReturnType)) {
QualType ResQT;
if (NewDeclaredReturnType->isObjCObjectPointerType() &&
OldDeclaredReturnType->isObjCObjectPointerType())
ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
if (ResQT.isNull()) {
if (New->isCXXClassMember() && New->isOutOfLine())
Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
<< New << New->getReturnTypeSourceRange();
else
Diag(New->getLocation(), diag::err_ovl_diff_return_type)
<< New->getReturnTypeSourceRange();
Diag(OldLocation, PrevDiag) << Old << Old->getType()
<< Old->getReturnTypeSourceRange();
return true;
}
else
NewQType = ResQT;
}
QualType OldReturnType = OldType->getReturnType();
QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
if (OldReturnType != NewReturnType) {
AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
if (OldAT && OldAT->isDeduced()) {
QualType DT = OldAT->getDeducedType();
if (DT.isNull()) {
New->setType(SubstAutoTypeDependent(New->getType()));
NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
} else {
New->setType(SubstAutoType(New->getType(), DT));
NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
}
}
}
const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
if (OldMethod && NewMethod) {
NewMethod->setTrivial(OldMethod->isTrivial());
bool IsClassScopeExplicitSpecialization =
OldMethod->isFunctionTemplateSpecialization() &&
NewMethod->isFunctionTemplateSpecialization();
bool isFriend = NewMethod->getFriendObjectKind();
if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
!IsClassScopeExplicitSpecialization) {
if (OldMethod->isStatic() != NewMethod->isStatic()) {
Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
}
if (!inTemplateInstantiation()) {
unsigned NewDiag;
if (isa<CXXConstructorDecl>(OldMethod))
NewDiag = diag::err_constructor_redeclared;
else if (isa<CXXDestructorDecl>(NewMethod))
NewDiag = diag::err_destructor_redeclared;
else if (isa<CXXConversionDecl>(NewMethod))
NewDiag = diag::err_conv_function_redeclared;
else
NewDiag = diag::err_member_redeclared;
Diag(New->getLocation(), NewDiag);
} else {
Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
<< New << New->getType();
}
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
} else if (OldMethod->isImplicit()) {
if (isFriend) {
NewMethod->setImplicit();
} else {
Diag(NewMethod->getLocation(),
diag::err_definition_of_implicitly_declared_member)
<< New << getSpecialMember(OldMethod);
return true;
}
} else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
Diag(NewMethod->getLocation(),
diag::err_definition_of_explicitly_defaulted_member)
<< getSpecialMember(OldMethod);
return true;
}
}
if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
if (!Old->hasAttr<CXX11NoReturnAttr>()) {
Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
<< NRA;
Diag(Old->getLocation(), diag::note_previous_declaration);
}
const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
Diag(CDA->getLocation(),
diag::err_carries_dependency_missing_on_first_decl) << 0;
Diag(Old->getFirstDecl()->getLocation(),
diag::note_carries_dependency_missing_first_decl) << 0;
}
QualType OldQTypeForComparison = OldQType;
if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
auto *OldType = OldQType->castAs<FunctionProtoType>();
const FunctionType *OldTypeForComparison
= Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
OldQTypeForComparison = QualType(OldTypeForComparison, 0);
assert(OldQTypeForComparison.isCanonical());
}
if (haveIncompatibleLanguageLinkages(Old, New)) {
if (New->getFriendObjectKind() != Decl::FOK_None) {
Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Diag(OldLocation, PrevDiag);
return true;
}
}
if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
NewQType))
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
return false;
}
if (!getLangOpts().CPlusPlus) {
if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
if (Old->hasInheritedPrototype())
Old = Old->getCanonicalDecl();
Diag(New->getLocation(), diag::err_conflicting_types) << New;
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
return true;
}
if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
!New->isImplicit() && !Old->isImplicit()) {
const FunctionDecl *WithProto, *WithoutProto;
if (New->hasWrittenPrototype()) {
WithProto = New;
WithoutProto = Old;
} else {
WithProto = Old;
WithoutProto = New;
}
if (WithProto->getNumParams() != 0) {
if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
bool IsWithoutProtoADef = false, IsWithProtoADef = false;
if (WithoutProto == New)
IsWithoutProtoADef = NewDeclIsDefn;
else
IsWithProtoADef = NewDeclIsDefn;
Diag(WithoutProto->getLocation(),
diag::warn_non_prototype_changes_behavior)
<< IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
<< (WithoutProto == Old) << IsWithProtoADef;
if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
!IsWithoutProtoADef)
Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
}
}
}
if (Context.typesAreCompatible(OldQType, NewQType)) {
const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
const FunctionProtoType *OldProto = nullptr;
if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
NewQType =
Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
OldProto->getExtProtoInfo());
New->setType(NewQType);
New->setHasInheritedPrototype();
SmallVector<ParmVarDecl *, 16> Params;
for (const auto &ParamType : OldProto->param_types()) {
ParmVarDecl *Param = ParmVarDecl::Create(
Context, New, SourceLocation(), SourceLocation(), nullptr,
ParamType, nullptr, SC_None, nullptr);
Param->setScopeInfo(0, Params.size());
Param->setImplicit();
Params.push_back(Param);
}
New->setParams(Params);
}
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
}
}
if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
return false;
if (!getLangOpts().CPlusPlus &&
Old->hasPrototype() && !New->hasPrototype() &&
New->getType()->getAs<FunctionProtoType>() &&
Old->getNumParams() == New->getNumParams()) {
SmallVector<QualType, 16> ArgTypes;
SmallVector<GNUCompatibleParamWarning, 16> Warnings;
const FunctionProtoType *OldProto
= Old->getType()->getAs<FunctionProtoType>();
const FunctionProtoType *NewProto
= New->getType()->getAs<FunctionProtoType>();
QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
NewProto->getReturnType());
bool LooseCompatible = !MergedReturn.isNull();
for (unsigned Idx = 0, End = Old->getNumParams();
LooseCompatible && Idx != End; ++Idx) {
ParmVarDecl *OldParm = Old->getParamDecl(Idx);
ParmVarDecl *NewParm = New->getParamDecl(Idx);
if (Context.typesAreCompatible(OldParm->getType(),
NewProto->getParamType(Idx))) {
ArgTypes.push_back(NewParm->getType());
} else if (Context.typesAreCompatible(OldParm->getType(),
NewParm->getType(),
true)) {
GNUCompatibleParamWarning Warn = { OldParm, NewParm,
NewProto->getParamType(Idx) };
Warnings.push_back(Warn);
ArgTypes.push_back(NewParm->getType());
} else
LooseCompatible = false;
}
if (LooseCompatible) {
for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
Diag(Warnings[Warn].NewParm->getLocation(),
diag::ext_param_promoted_not_compatible_with_prototype)
<< Warnings[Warn].PromotedType
<< Warnings[Warn].OldParm->getType();
if (Warnings[Warn].OldParm->getLocation().isValid())
Diag(Warnings[Warn].OldParm->getLocation(),
diag::note_previous_declaration);
}
if (MergeTypeWithOld)
New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
OldProto->getExtProtoInfo()));
return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
}
}
unsigned BuiltinID;
if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Diag(OldLocation, diag::note_previous_builtin_declaration)
<< Old << Old->getType();
return false;
}
PrevDiag = diag::note_previous_builtin_declaration;
}
Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Diag(OldLocation, PrevDiag) << Old << Old->getType();
return true;
}
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld) {
mergeDeclAttributes(New, Old);
if (Old->isPure())
New->setPure();
if (Old->getMostRecentDecl()->isUsed(false))
New->setIsUsed();
if (New->getNumParams() == Old->getNumParams())
for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
ParmVarDecl *NewParam = New->getParamDecl(i);
ParmVarDecl *OldParam = Old->getParamDecl(i);
mergeParamDeclAttributes(NewParam, OldParam, *this);
mergeParamDeclTypes(NewParam, OldParam, *this);
}
if (getLangOpts().CPlusPlus)
return MergeCXXFunctionDecl(New, Old, S);
QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
if (!Merged.isNull() && MergeTypeWithOld)
New->setType(Merged);
return false;
}
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
ObjCMethodDecl *oldMethod) {
AvailabilityMergeKind MergeKind =
isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
: AMK_ProtocolImplementation)
: isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
: AMK_Override;
mergeDeclAttributes(newMethod, oldMethod, MergeKind);
ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
oe = oldMethod->param_end();
for (ObjCMethodDecl::param_iterator
ni = newMethod->param_begin(), ne = newMethod->param_end();
ni != ne && oi != oe; ++ni, ++oi)
mergeParamDeclAttributes(*ni, *oi, *this);
CheckObjCMethodOverride(newMethod, oldMethod);
}
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
assert(!S.Context.hasSameType(New->getType(), Old->getType()));
S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
? diag::err_redefinition_different_type
: diag::err_redeclaration_different_type)
<< New->getDeclName() << New->getType() << Old->getType();
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation)
= getNoteDiagForInvalidRedeclaration(Old, New);
S.Diag(OldLocation, PrevDiag);
New->setInvalidDecl();
}
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
bool MergeTypeWithOld) {
if (New->isInvalidDecl() || Old->isInvalidDecl())
return;
QualType MergedT;
if (getLangOpts().CPlusPlus) {
if (New->getType()->isUndeducedType()) {
return;
} else if (Context.hasSameType(New->getType(), Old->getType())) {
return MergeVarDeclExceptionSpecs(New, Old);
}
else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
const ArrayType *NewArray = Context.getAsArrayType(New->getType());
if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
PrevVD = PrevVD->getPreviousDecl()) {
QualType PrevVDTy = PrevVD->getType();
if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
continue;
if (!Context.hasSameType(New->getType(), PrevVDTy))
return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
}
}
if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
if (Context.hasSameType(OldArray->getElementType(),
NewArray->getElementType()))
MergedT = New->getType();
}
else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
if (Context.hasSameType(OldArray->getElementType(),
NewArray->getElementType()))
MergedT = Old->getType();
}
}
else if (New->getType()->isObjCObjectPointerType() &&
Old->getType()->isObjCObjectPointerType()) {
MergedT = Context.mergeObjCGCQualifiers(New->getType(),
Old->getType());
}
} else {
MergedT = Context.mergeTypes(New->getType(), Old->getType());
}
if (MergedT.isNull()) {
if ((New->getType()->isDependentType() ||
Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
if (!New->getType()->isDependentType() && MergeTypeWithOld)
New->setType(Context.DependentTy);
return;
}
return diagnoseVarDeclTypeMismatch(*this, New, Old);
}
if (MergeTypeWithOld)
New->setType(MergedT);
}
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
LookupResult &Previous) {
if (Previous.isShadowed())
return false;
if (S.getLangOpts().CPlusPlus) {
return NewVD->isPreviousDeclInSameBlockScope() ||
(!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
!NewVD->getLexicalDeclContext()->isFunctionOrMethod());
} else {
return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
}
}
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
if (New->isInvalidDecl())
return;
if (!shouldLinkPossiblyHiddenDecl(Previous, New))
return;
VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
VarDecl *Old = nullptr;
VarTemplateDecl *OldTemplate = nullptr;
if (Previous.isSingleResult()) {
if (NewTemplate) {
OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
if (auto *Shadow =
dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
return New->setInvalidDecl();
} else {
Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
if (auto *Shadow =
dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
return New->setInvalidDecl();
}
}
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
notePreviousDefinition(Previous.getRepresentativeDecl(),
New->getLocation());
return New->setInvalidDecl();
}
adjustDeclContextForDeclaratorDecl(New, Old);
if (NewTemplate &&
!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
OldTemplate->getTemplateParameters(),
true, TPL_TemplateMatch))
return New->setInvalidDecl();
if (Old->isStaticDataMember() && !New->isOutOfLine()) {
Diag(New->getLocation(), diag::err_duplicate_member)
<< New->getIdentifier();
Diag(Old->getLocation(), diag::note_previous_declaration);
New->setInvalidDecl();
}
mergeDeclAttributes(New, Old);
if (New->hasAttr<WeakImportAttr>() &&
Old->getStorageClass() == SC_None &&
!Old->hasAttr<WeakImportAttr>()) {
Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_declaration);
New->dropAttr<WeakImportAttr>();
}
if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
if (!Old->hasAttr<InternalLinkageAttr>()) {
Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
<< ILA;
Diag(Old->getLocation(), diag::note_previous_declaration);
New->dropAttr<InternalLinkageAttr>();
}
VarDecl *MostRecent = Old->getMostRecentDecl();
if (MostRecent != Old) {
MergeVarDeclTypes(New, MostRecent,
mergeTypeWithPrevious(*this, New, MostRecent, Previous));
if (New->isInvalidDecl())
return;
}
MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
if (New->isInvalidDecl())
return;
diag::kind PrevDiag;
SourceLocation OldLocation;
std::tie(PrevDiag, OldLocation) =
getNoteDiagForInvalidRedeclaration(Old, New);
if (New->getStorageClass() == SC_Static &&
!New->isStaticDataMember() &&
Old->hasExternalFormalLinkage()) {
if (getLangOpts().MicrosoftExt) {
Diag(New->getLocation(), diag::ext_static_non_static)
<< New->getDeclName();
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_static_non_static)
<< New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
}
}
if (New->hasExternalStorage() && Old->hasLinkage())
;
else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
!New->isStaticDataMember() &&
Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
}
if (New->hasExternalStorage() &&
!Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
}
if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
!New->hasExternalStorage()) {
Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
}
if (CheckRedeclarationInModule(New, Old))
return;
if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
!(Old->getLexicalDeclContext()->isRecord() &&
!New->getLexicalDeclContext()->isRecord())) {
Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Diag(OldLocation, PrevDiag);
return New->setInvalidDecl();
}
if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
if (VarDecl *Def = Old->getDefinition()) {
Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
Diag(Def->getLocation(), diag::note_previous_definition);
}
}
if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
!Old->getDefinition() && !New->isThisDeclarationADefinition())
UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
SourceLocation()));
if (New->getTLSKind() != Old->getTLSKind()) {
if (!Old->getTLSKind()) {
Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
Diag(OldLocation, PrevDiag);
} else if (!New->getTLSKind()) {
Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
Diag(OldLocation, PrevDiag);
} else {
Diag(New->getLocation(), diag::err_thread_thread_different_kind)
<< New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
Diag(OldLocation, PrevDiag);
}
}
if (getLangOpts().CPlusPlus) {
if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
Old->getCanonicalDecl()->isConstexpr()) {
Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
VarDecl *Def = Old->getDefinition();
if (Def && checkVarDeclRedefinition(Def, New))
return;
}
}
if (haveIncompatibleLanguageLinkages(Old, New)) {
Diag(New->getLocation(), diag::err_different_language_linkage) << New;
Diag(OldLocation, PrevDiag);
New->setInvalidDecl();
return;
}
if (Old->getMostRecentDecl()->isUsed(false))
New->setIsUsed();
New->setPreviousDecl(Old);
if (NewTemplate)
NewTemplate->setPreviousDecl(OldTemplate);
New->setAccess(Old->getAccess());
if (NewTemplate)
NewTemplate->setAccess(New->getAccess());
if (Old->isInline())
New->setImplicitlyInline();
}
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
SourceManager &SrcMgr = getSourceManager();
auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
auto &HSI = PP.getHeaderSearchInfo();
StringRef HdrFilename =
SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
auto noteFromModuleOrInclude = [&](Module *Mod,
SourceLocation IncLoc) -> bool {
if (IncLoc.isValid()) {
if (Mod) {
Diag(IncLoc, diag::note_redefinition_modules_same_file)
<< HdrFilename.str() << Mod->getFullModuleName();
if (!Mod->DefinitionLoc.isInvalid())
Diag(Mod->DefinitionLoc, diag::note_defined_here)
<< Mod->getFullModuleName();
} else {
Diag(IncLoc, diag::note_redefinition_include_same_file)
<< HdrFilename.str();
}
return true;
}
return false;
};
if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
bool EmittedDiag =
noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
Diag(Old->getLocation(), diag::note_use_ifdef_guards);
if (EmittedDiag)
return;
}
if (Old->getLocation().isValid())
Diag(Old->getLocation(), diag::note_previous_definition);
}
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
if (!hasVisibleDefinition(Old) &&
(New->getFormalLinkage() == InternalLinkage ||
New->isInline() ||
New->getDescribedVarTemplate() ||
New->getNumTemplateParameterLists() ||
New->getDeclContext()->isDependentContext())) {
New->demoteThisDefinitionToDeclaration();
if (auto *OldTD = Old->getDescribedVarTemplate())
makeMergedDefinitionVisible(OldTD);
makeMergedDefinitionVisible(Old);
return false;
} else {
Diag(New->getLocation(), diag::err_redefinition) << New;
notePreviousDefinition(Old, New->getLocation());
New->setInvalidDecl();
return true;
}
}
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS,
const ParsedAttributesView &DeclAttrs,
RecordDecl *&AnonRecord) {
return ParsedFreeStandingDeclSpec(
S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
}
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
? S->getMSCurManglingNumber()
: S->getMSLastManglingNumber();
}
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
if (!Context.getLangOpts().CPlusPlus)
return;
if (isa<CXXRecordDecl>(Tag->getParent())) {
if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
return;
MangleNumberingContext &MCtx =
Context.getManglingNumberContext(Tag->getParent());
Context.setManglingNumber(
Tag, MCtx.getManglingNumber(
Tag, getMSManglingNumber(getLangOpts(), TagScope)));
return;
}
MangleNumberingContext *MCtx;
Decl *ManglingContextDecl;
std::tie(MCtx, ManglingContextDecl) =
getCurrentMangleNumberContext(Tag->getDeclContext());
if (MCtx) {
Context.setManglingNumber(
Tag, MCtx->getManglingNumber(
Tag, getMSManglingNumber(getLangOpts(), TagScope)));
}
}
namespace {
struct NonCLikeKind {
enum {
None,
BaseClass,
DefaultMemberInit,
Lambda,
Friend,
OtherMember,
Invalid,
} Kind = None;
SourceRange Range;
explicit operator bool() { return Kind != None; }
};
}
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
if (RD->isInvalidDecl())
return {NonCLikeKind::Invalid, {}};
if (RD->getNumBases())
return {NonCLikeKind::BaseClass,
SourceRange(RD->bases_begin()->getBeginLoc(),
RD->bases_end()[-1].getEndLoc())};
bool Invalid = false;
for (Decl *D : RD->decls()) {
if (D->isInvalidDecl()) {
Invalid = true;
continue;
}
if (auto *FD = dyn_cast<FieldDecl>(D)) {
if (FD->hasInClassInitializer()) {
auto *Init = FD->getInClassInitializer();
return {NonCLikeKind::DefaultMemberInit,
Init ? Init->getSourceRange() : D->getSourceRange()};
}
continue;
}
if (isa<FriendDecl>(D))
return {NonCLikeKind::Friend, D->getSourceRange()};
if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
isa<EnumDecl>(D))
continue;
auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
if (!MemberRD) {
if (D->isImplicit())
continue;
return {NonCLikeKind::OtherMember, D->getSourceRange()};
}
if (MemberRD->isLambda())
return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
if (MemberRD->isThisDeclarationADefinition()) {
if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
return Kind;
}
}
return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
}
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD) {
if (TagFromDeclSpec->isInvalidDecl())
return;
if (TagFromDeclSpec->hasNameForLinkage())
return;
assert(TagFromDeclSpec->isThisDeclarationADefinition());
if (!Context.hasSameType(NewTD->getUnderlyingType(),
Context.getTagDeclType(TagFromDeclSpec))) {
if (getLangOpts().CPlusPlus)
Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
return;
}
const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
: NonCLikeKind();
bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
if (NonCLike || ChangesLinkage) {
if (NonCLike.Kind == NonCLikeKind::Invalid)
return;
unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
if (ChangesLinkage) {
if (NonCLike.Kind == NonCLikeKind::None)
DiagID = diag::err_typedef_changes_linkage;
else
DiagID = diag::err_non_c_like_anon_struct_in_typedef;
}
SourceLocation FixitLoc =
getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
llvm::SmallString<40> TextToInsert;
TextToInsert += ' ';
TextToInsert += NewTD->getIdentifier()->getName();
Diag(FixitLoc, DiagID)
<< isa<TypeAliasDecl>(NewTD)
<< FixItHint::CreateInsertion(FixitLoc, TextToInsert);
if (NonCLike.Kind != NonCLikeKind::None) {
Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
<< NonCLike.Kind - 1 << NonCLike.Range;
}
Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
<< NewTD << isa<TypeAliasDecl>(NewTD);
if (ChangesLinkage)
return;
}
TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
}
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
switch (T) {
case DeclSpec::TST_class:
return 0;
case DeclSpec::TST_struct:
return 1;
case DeclSpec::TST_interface:
return 2;
case DeclSpec::TST_union:
return 3;
case DeclSpec::TST_enum:
return 4;
default:
llvm_unreachable("unexpected type specifier");
}
}
Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS,
const ParsedAttributesView &DeclAttrs,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord) {
Decl *TagD = nullptr;
TagDecl *Tag = nullptr;
if (DS.getTypeSpecType() == DeclSpec::TST_class ||
DS.getTypeSpecType() == DeclSpec::TST_struct ||
DS.getTypeSpecType() == DeclSpec::TST_interface ||
DS.getTypeSpecType() == DeclSpec::TST_union ||
DS.getTypeSpecType() == DeclSpec::TST_enum) {
TagD = DS.getRepAsDecl();
if (!TagD) return nullptr;
if (isa<TagDecl>(TagD))
Tag = cast<TagDecl>(TagD);
else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
Tag = CTD->getTemplatedDecl();
}
if (Tag) {
handleTagNumbering(Tag, S);
Tag->setFreeStanding();
if (Tag->isInvalidDecl())
return Tag;
}
if (unsigned TypeQuals = DS.getTypeQualifiers()) {
if (TypeQuals & DeclSpec::TQ_restrict)
Diag(DS.getRestrictSpecLoc(),
diag::err_typecheck_invalid_restrict_not_pointer_noarg)
<< DS.getSourceRange();
}
if (DS.isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
if (DS.hasConstexprSpecifier()) {
if (Tag)
Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
<< GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
<< static_cast<int>(DS.getConstexprSpecifier());
else
Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
<< static_cast<int>(DS.getConstexprSpecifier());
return TagD;
}
DiagnoseFunctionSpecifiers(DS);
if (DS.isFriendSpecified()) {
if (TagD && !Tag)
return nullptr;
return ActOnFriendTypeDecl(S, DS, TemplateParams);
}
const CXXScopeSpec &SS = DS.getTypeSpecScope();
bool IsExplicitSpecialization =
!TemplateParams.empty() && TemplateParams.back()->size() == 0;
if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
!IsExplicitInstantiation && !IsExplicitSpecialization &&
!isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
<< GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
return nullptr;
}
bool DeclaresAnything = true;
if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
if (!Record->getDeclName() && Record->isCompleteDefinition() &&
DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
if (getLangOpts().CPlusPlus ||
Record->getDeclContext()->isRecord()) {
if (CurContext->isFunctionOrMethod())
AnonRecord = Record;
return BuildAnonymousStructOrUnion(S, DS, AS, Record,
Context.getPrintingPolicy());
}
DeclaresAnything = false;
}
}
if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
if ((Tag && Tag->getDeclName()) ||
DS.getTypeSpecType() == DeclSpec::TST_typename) {
RecordDecl *Record = nullptr;
if (Tag)
Record = dyn_cast<RecordDecl>(Tag);
else if (const RecordType *RT =
DS.getRepAsType().get()->getAsStructureType())
Record = RT->getDecl();
else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
Record = UT->getDecl();
if (Record && getLangOpts().MicrosoftExt) {
Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
<< Record->isUnion() << DS.getSourceRange();
return BuildMicrosoftCAnonymousStruct(S, DS, Record);
}
DeclaresAnything = false;
}
}
if (DS.getTypeSpecType() == DeclSpec::TST_error ||
(TagD && TagD->isInvalidDecl()))
return TagD;
if (getLangOpts().CPlusPlus &&
DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
if (Enum->enumerator_begin() == Enum->enumerator_end() &&
!Enum->getIdentifier() && !Enum->isInvalidDecl())
DeclaresAnything = false;
if (!DS.isMissingDeclaratorOk()) {
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
<< DS.getSourceRange();
else
DeclaresAnything = false;
}
if (DS.isModulePrivateSpecified() &&
Tag && Tag->getDeclContext()->isFunctionOrMethod())
Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
<< Tag->getTagKind()
<< FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
ActOnDocumentableDecl(TagD);
if (!DeclaresAnything) {
Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
? diag::err_no_declarators
: diag::ext_no_declarators)
<< DS.getSourceRange();
return TagD;
}
unsigned DiagID = diag::warn_standalone_specifier;
if (getLangOpts().CPlusPlus)
DiagID = diag::ext_standalone_specifier;
if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
if (SCS == DeclSpec::SCS_mutable)
Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
Diag(DS.getStorageClassSpecLoc(), DiagID)
<< DeclSpec::getSpecifierName(SCS);
}
if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
<< DeclSpec::getSpecifierName(TSCS);
if (DS.getTypeQualifiers()) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(), DiagID) << "const";
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
}
if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
if (TypeSpecType == DeclSpec::TST_class ||
TypeSpecType == DeclSpec::TST_struct ||
TypeSpecType == DeclSpec::TST_interface ||
TypeSpecType == DeclSpec::TST_union ||
TypeSpecType == DeclSpec::TST_enum) {
for (const ParsedAttr &AL : DS.getAttributes())
Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
<< AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
for (const ParsedAttr &AL : DeclAttrs)
Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
<< AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
}
}
return TagD;
}
static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
Scope *S,
DeclContext *Owner,
DeclarationName Name,
SourceLocation NameLoc,
bool IsUnion) {
LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
Sema::ForVisibleRedeclaration);
if (!SemaRef.LookupName(R, S)) return false;
NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
assert(PrevDecl && "Expected a non-null Decl");
if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
return false;
SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
<< IsUnion << Name;
SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
return true;
}
static bool
InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
RecordDecl *AnonRecord, AccessSpecifier AS,
SmallVectorImpl<NamedDecl *> &Chaining) {
bool Invalid = false;
for (auto *D : AnonRecord->decls()) {
if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
cast<NamedDecl>(D)->getDeclName()) {
ValueDecl *VD = cast<ValueDecl>(D);
if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
VD->getLocation(),
AnonRecord->isUnion())) {
Invalid = true;
} else {
unsigned OldChainingSize = Chaining.size();
if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
Chaining.append(IF->chain_begin(), IF->chain_end());
else
Chaining.push_back(VD);
assert(Chaining.size() >= 2);
NamedDecl **NamedChain =
new (SemaRef.Context)NamedDecl*[Chaining.size()];
for (unsigned i = 0; i < Chaining.size(); i++)
NamedChain[i] = Chaining[i];
IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
VD->getType(), {NamedChain, Chaining.size()});
for (const auto *Attr : VD->attrs())
IndirectField->addAttr(Attr->clone(SemaRef.Context));
IndirectField->setAccess(AS);
IndirectField->setImplicit();
SemaRef.PushOnScopeChains(IndirectField, S);
if (AS != AS_none) IndirectField->setAccess(AS);
Chaining.resize(OldChainingSize);
}
}
}
return Invalid;
}
static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
assert(StorageClassSpec != DeclSpec::SCS_typedef &&
"Parser allowed 'typedef' as storage class VarDecl.");
switch (StorageClassSpec) {
case DeclSpec::SCS_unspecified: return SC_None;
case DeclSpec::SCS_extern:
if (DS.isExternInLinkageSpec())
return SC_None;
return SC_Extern;
case DeclSpec::SCS_static: return SC_Static;
case DeclSpec::SCS_auto: return SC_Auto;
case DeclSpec::SCS_register: return SC_Register;
case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
case DeclSpec::SCS_mutable: case DeclSpec::SCS_typedef: return SC_None;
}
llvm_unreachable("unknown storage class specifier");
}
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
assert(Record->hasInClassInitializer());
for (const auto *I : Record->decls()) {
const auto *FD = dyn_cast<FieldDecl>(I);
if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
FD = IFD->getAnonField();
if (FD && FD->hasInClassInitializer())
return FD->getLocation();
}
llvm_unreachable("couldn't find in-class initializer");
}
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
SourceLocation DefaultInitLoc) {
if (!Parent->isUnion() || !Parent->hasInClassInitializer())
return;
S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
}
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
CXXRecordDecl *AnonUnion) {
if (!Parent->isUnion() || !Parent->hasInClassInitializer())
return;
checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
}
Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy) {
DeclContext *Owner = Record->getDeclContext();
if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
Diag(Record->getLocation(), diag::ext_anonymous_union);
else if (!Record->isUnion() && getLangOpts().CPlusPlus)
Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
else if (!Record->isUnion() && !getLangOpts().C11)
Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
bool Invalid = false;
if (getLangOpts().CPlusPlus) {
const char *PrevSpec = nullptr;
if (Record->isUnion()) {
unsigned DiagID;
DeclContext *OwnerScope = Owner->getRedeclContext();
if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
(OwnerScope->isTranslationUnit() ||
(OwnerScope->isNamespace() &&
!cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
<< FixItHint::CreateInsertion(Record->getLocation(), "static ");
DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
PrevSpec, DiagID, Policy);
}
else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
isa<RecordDecl>(Owner)) {
Diag(DS.getStorageClassSpecLoc(),
diag::err_anonymous_union_with_storage_spec)
<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
SourceLocation(),
PrevSpec, DiagID, Context.getPrintingPolicy());
}
}
if (DS.getTypeQualifiers()) {
if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "const"
<< FixItHint::CreateRemoval(DS.getConstSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
Diag(DS.getVolatileSpecLoc(),
diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "volatile"
<< FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
Diag(DS.getRestrictSpecLoc(),
diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "restrict"
<< FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
Diag(DS.getAtomicSpecLoc(),
diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "_Atomic"
<< FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
Diag(DS.getUnalignedSpecLoc(),
diag::ext_anonymous_struct_union_qualified)
<< Record->isUnion() << "__unaligned"
<< FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
DS.ClearTypeQualifiers();
}
for (auto *Mem : Record->decls()) {
if (Mem->isInvalidDecl())
continue;
if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
assert(FD->getAccess() != AS_none);
if (FD->getAccess() != AS_public) {
Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
<< Record->isUnion() << (FD->getAccess() == AS_protected);
Invalid = true;
}
if (CheckNontrivialField(FD))
Invalid = true;
} else if (Mem->isImplicit()) {
} else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
} else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
if (!MemRecord->isAnonymousStructOrUnion() &&
MemRecord->getDeclName()) {
if (getLangOpts().MicrosoftExt)
Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
<< Record->isUnion();
else {
Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
<< Record->isUnion();
Invalid = true;
}
} else {
Diag(MemRecord->getLocation(),
diag::ext_anonymous_record_with_anonymous_type)
<< Record->isUnion();
}
} else if (isa<AccessSpecDecl>(Mem)) {
} else if (isa<StaticAssertDecl>(Mem)) {
} else {
unsigned DK = diag::err_anonymous_record_bad_member;
if (isa<TypeDecl>(Mem))
DK = diag::err_anonymous_record_with_type;
else if (isa<FunctionDecl>(Mem))
DK = diag::err_anonymous_record_with_function;
else if (isa<VarDecl>(Mem))
DK = diag::err_anonymous_record_with_static;
if (getLangOpts().MicrosoftExt &&
DK == diag::err_anonymous_record_with_type)
Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
<< Record->isUnion();
else {
Diag(Mem->getLocation(), DK) << Record->isUnion();
Invalid = true;
}
}
}
if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
Owner->isRecord())
checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
cast<CXXRecordDecl>(Record));
}
if (!Record->isUnion() && !Owner->isRecord()) {
Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
<< getLangOpts().CPlusPlus;
Invalid = true;
}
if (getLangOpts().CPlusPlus && Record->field_empty())
Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
assert(TInfo && "couldn't build declarator info for anonymous struct/union");
NamedDecl *Anon = nullptr;
if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Anon = FieldDecl::Create(
Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
nullptr, Context.getTypeDeclType(Record), TInfo,
nullptr, false,
ICIS_NoInit);
Anon->setAccess(AS);
ProcessDeclAttributes(S, Anon, Dc);
if (getLangOpts().CPlusPlus)
FieldCollector->Add(cast<FieldDecl>(Anon));
} else {
DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
if (SCSpec == DeclSpec::SCS_mutable) {
Diag(Record->getLocation(), diag::err_mutable_nonmember);
Invalid = true;
SC = SC_None;
}
assert(DS.getAttributes().empty() && "No attribute expected");
Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
Record->getLocation(), nullptr,
Context.getTypeDeclType(Record), TInfo, SC);
ActOnUninitializedDecl(Anon);
}
Anon->setImplicit();
Record->setAnonymousStructOrUnion(true);
Owner->addDecl(Anon);
SmallVector<NamedDecl*, 2> Chain;
Chain.push_back(Anon);
if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
Invalid = true;
if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
MangleNumberingContext *MCtx;
Decl *ManglingContextDecl;
std::tie(MCtx, ManglingContextDecl) =
getCurrentMangleNumberContext(NewVD->getDeclContext());
if (MCtx) {
Context.setManglingNumber(
NewVD, MCtx->getManglingNumber(
NewVD, getMSManglingNumber(getLangOpts(), S)));
Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
}
}
}
if (Invalid)
Anon->setInvalidDecl();
return Anon;
}
Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record) {
assert(Record && "expected a record!");
Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
assert(TInfo && "couldn't build declarator info for anonymous struct");
auto *ParentDecl = cast<RecordDecl>(CurContext);
QualType RecTy = Context.getTypeDeclType(Record);
NamedDecl *Anon =
FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
nullptr, RecTy, TInfo,
nullptr, false,
ICIS_NoInit);
Anon->setImplicit();
CurContext->addDecl(Anon);
SmallVector<NamedDecl*, 2> Chain;
Chain.push_back(Anon);
RecordDecl *RecordDef = Record->getDefinition();
if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
diag::err_field_incomplete_or_sizeless) ||
InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
AS_none, Chain)) {
Anon->setInvalidDecl();
ParentDecl->setInvalidDecl();
}
return Anon;
}
DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
return GetNameFromUnqualifiedId(D.getName());
}
DeclarationNameInfo
Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
DeclarationNameInfo NameInfo;
NameInfo.setLoc(Name.StartLocation);
switch (Name.getKind()) {
case UnqualifiedIdKind::IK_ImplicitSelfParam:
case UnqualifiedIdKind::IK_Identifier:
NameInfo.setName(Name.Identifier);
return NameInfo;
case UnqualifiedIdKind::IK_DeductionGuideName: {
TemplateName TN = Name.TemplateName.get().get();
auto *Template = TN.getAsTemplateDecl();
if (!Template || !isa<ClassTemplateDecl>(Template)) {
Diag(Name.StartLocation,
diag::err_deduction_guide_name_not_class_template)
<< (int)getTemplateNameKindForDiagnostics(TN) << TN;
if (Template)
Diag(Template->getLocation(), diag::note_template_decl_here);
return DeclarationNameInfo();
}
NameInfo.setName(
Context.DeclarationNames.getCXXDeductionGuideName(Template));
return NameInfo;
}
case UnqualifiedIdKind::IK_OperatorFunctionId:
NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
Name.OperatorFunctionId.Operator));
NameInfo.setCXXOperatorNameRange(SourceRange(
Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
return NameInfo;
case UnqualifiedIdKind::IK_LiteralOperatorId:
NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
Name.Identifier));
NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
return NameInfo;
case UnqualifiedIdKind::IK_ConversionFunctionId: {
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
if (Ty.isNull())
return DeclarationNameInfo();
NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
Context.getCanonicalType(Ty)));
NameInfo.setNamedTypeInfo(TInfo);
return NameInfo;
}
case UnqualifiedIdKind::IK_ConstructorName: {
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
if (Ty.isNull())
return DeclarationNameInfo();
NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(Ty)));
NameInfo.setNamedTypeInfo(TInfo);
return NameInfo;
}
case UnqualifiedIdKind::IK_ConstructorTemplateId: {
CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
return DeclarationNameInfo();
QualType CurClassType = Context.getTypeDeclType(CurClass);
NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(CurClassType)));
NameInfo.setNamedTypeInfo(nullptr);
return NameInfo;
}
case UnqualifiedIdKind::IK_DestructorName: {
TypeSourceInfo *TInfo;
QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
if (Ty.isNull())
return DeclarationNameInfo();
NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
Context.getCanonicalType(Ty)));
NameInfo.setNamedTypeInfo(TInfo);
return NameInfo;
}
case UnqualifiedIdKind::IK_TemplateId: {
TemplateName TName = Name.TemplateId->Template.get();
SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
return Context.getNameForTemplate(TName, TNameLoc);
}
}
llvm_unreachable("Unknown name kind");
}
static QualType getCoreType(QualType Ty) {
do {
if (Ty->isPointerType() || Ty->isReferenceType())
Ty = Ty->getPointeeType();
else if (Ty->isArrayType())
Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
else
return Ty.withoutLocalFastQualifiers();
} while (true);
}
static bool hasSimilarParameters(ASTContext &Context,
FunctionDecl *Declaration,
FunctionDecl *Definition,
SmallVectorImpl<unsigned> &Params) {
Params.clear();
if (Declaration->param_size() != Definition->param_size())
return false;
for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
continue;
QualType DeclParamBaseTy = getCoreType(DeclParamTy);
QualType DefParamBaseTy = getCoreType(DefParamTy);
const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
(DeclTyName && DeclTyName == DefTyName))
Params.push_back(Idx);
else return false;
}
return true;
}
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
DeclarationName Name) {
DeclSpec &DS = D.getMutableDeclSpec();
switch (DS.getTypeSpecType()) {
case DeclSpec::TST_typename:
case DeclSpec::TST_typeofType:
case DeclSpec::TST_underlyingType:
case DeclSpec::TST_atomic: {
TypeSourceInfo *TSI = nullptr;
QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
if (T.isNull() || !T->isInstantiationDependentType()) break;
if (!TSI)
TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
if (!TSI) return true;
ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
DS.UpdateTypeRep(LocType);
break;
}
case DeclSpec::TST_decltype:
case DeclSpec::TST_typeofExpr: {
Expr *E = DS.getRepAsExpr();
ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
if (Result.isInvalid()) return true;
DS.UpdateExprRep(Result.get());
break;
}
default:
break;
}
for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
DeclaratorChunk &Chunk = D.getTypeObject(I);
if (Chunk.Kind != DeclaratorChunk::MemberPointer)
continue;
CXXScopeSpec &SS = Chunk.Mem.Scope();
if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
return true;
}
return false;
}
static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
return SM.isInSystemHeader(D->getLocation()) ||
SM.isInSystemMacro(D->getLocation());
}
void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
if (D->getPreviousDecl() || D->isImplicit())
return;
ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
if (Status != ReservedIdentifierStatus::NotReserved &&
!isFromSystemHeader(Context.getSourceManager(), D)) {
Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
<< D << static_cast<int>(Status);
}
}
Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
SmallVector<FunctionDecl *, 4> Bases;
if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
implementation_extension_bind_to_declaration))
ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
S, D, MultiTemplateParamsArg(), Bases);
Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
Dcl && Dcl->getDeclContext()->isFileContext())
Dcl->setTopLevelDeclInObjCContainer();
if (!Bases.empty())
ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
return Dcl;
}
bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
DeclarationNameInfo NameInfo) {
DeclarationName Name = NameInfo.getName();
CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
while (Record && Record->isAnonymousStructOrUnion())
Record = dyn_cast<CXXRecordDecl>(Record->getParent());
if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
return true;
}
return false;
}
bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name,
SourceLocation Loc, bool IsTemplateId) {
DeclContext *Cur = CurContext;
while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
Cur = Cur->getParent();
if (Cur->Equals(DC)) {
if (Cur->isRecord()) {
Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
: diag::err_member_extra_qualification)
<< Name << FixItHint::CreateRemoval(SS.getRange());
SS.clear();
} else {
Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
}
return false;
}
if (!Cur->Encloses(DC) && !IsTemplateId) {
if (Cur->isRecord())
Diag(Loc, diag::err_member_qualification)
<< Name << SS.getRange();
else if (isa<TranslationUnitDecl>(DC))
Diag(Loc, diag::err_invalid_declarator_global_scope)
<< Name << SS.getRange();
else if (isa<FunctionDecl>(Cur))
Diag(Loc, diag::err_invalid_declarator_in_function)
<< Name << SS.getRange();
else if (isa<BlockDecl>(Cur))
Diag(Loc, diag::err_invalid_declarator_in_block)
<< Name << SS.getRange();
else if (isa<ExportDecl>(Cur)) {
if (!isa<NamespaceDecl>(DC))
Diag(Loc, diag::err_export_non_namespace_scope_name)
<< Name << SS.getRange();
else
return false;
} else
Diag(Loc, diag::err_invalid_declarator_scope)
<< Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
return true;
}
if (Cur->isRecord()) {
Diag(Loc, diag::err_member_qualification)
<< Name << SS.getRange();
SS.clear();
if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
Name.getNameKind() == DeclarationName::CXXDestructorName) &&
!Context.hasSameType(Name.getCXXNameType(),
Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
return true;
return false;
}
NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
while (SpecLoc.getPrefix())
SpecLoc = SpecLoc.getPrefix();
if (isa_and_nonnull<DecltypeType>(
SpecLoc.getNestedNameSpecifier()->getAsType()))
Diag(Loc, diag::err_decltype_in_declarator)
<< SpecLoc.getTypeLoc().getSourceRange();
return false;
}
NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists) {
DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
DeclarationName Name = NameInfo.getName();
if (D.isDecompositionDeclarator()) {
return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
} else if (!Name) {
if (!D.isInvalidType()) Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
<< D.getDeclSpec().getSourceRange() << D.getSourceRange();
return nullptr;
} else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
return nullptr;
while ((S->getFlags() & Scope::DeclScope) == 0 ||
(S->getFlags() & Scope::TemplateParamScope) != 0)
S = S->getParent();
DeclContext *DC = CurContext;
if (D.getCXXScopeSpec().isInvalid())
D.setInvalidType();
else if (D.getCXXScopeSpec().isSet()) {
if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
UPPC_DeclarationQualifier))
return nullptr;
bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
if (!DC || isa<EnumDecl>(DC)) {
Diag(D.getIdentifierLoc(),
diag::err_template_qualified_declarator_no_match)
<< D.getCXXScopeSpec().getScopeRep()
<< D.getCXXScopeSpec().getRange();
return nullptr;
}
bool IsDependentContext = DC->isDependentContext();
if (!IsDependentContext &&
RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
return nullptr;
if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
Diag(D.getIdentifierLoc(),
diag::err_member_def_undefined_record)
<< Name << DC << D.getCXXScopeSpec().getRange();
return nullptr;
}
if (!D.getDeclSpec().isFriendSpecified()) {
if (diagnoseQualifiedDeclaration(
D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
if (DC->isRecord())
return nullptr;
D.setInvalidType();
}
}
if (EnteringContext && IsDependentContext &&
TemplateParamLists.size() != 0) {
ContextRAII SavedContext(*this, DC);
if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
D.setInvalidType();
}
}
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType R = TInfo->getType();
if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
UPPC_DeclarationType))
D.setInvalidType();
LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
forRedeclarationInCurContext());
if (!D.getCXXScopeSpec().isSet()) {
bool IsLinkageLookup = false;
bool CreateBuiltins = false;
if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
;
else if (CurContext->isFunctionOrMethod() &&
(D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
R->isFunctionType())) {
IsLinkageLookup = true;
CreateBuiltins =
CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
} else if (CurContext->getRedeclContext()->isTranslationUnit() &&
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
CreateBuiltins = true;
if (IsLinkageLookup) {
Previous.clear(LookupRedeclarationWithLinkage);
Previous.setRedeclarationKind(ForExternalRedeclaration);
}
LookupName(Previous, S, CreateBuiltins);
} else { LookupQualifiedName(Previous, DC);
RemoveUsingDecls(Previous);
}
if (Previous.isSingleResult() &&
Previous.getFoundDecl()->isTemplateParameter()) {
if (!D.isInvalidType())
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Previous.getFoundDecl());
Previous.clear();
}
if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
Previous.clear();
if (Previous.isSingleTagDecl() &&
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
(TemplateParamLists.size() == 0 || R->isFunctionType()))
Previous.clear();
if (getLangOpts().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
NamedDecl *New;
bool AddToScope = true;
if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
if (TemplateParamLists.size()) {
Diag(D.getIdentifierLoc(), diag::err_template_typedef);
return nullptr;
}
New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
} else if (R->isFunctionType()) {
New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
TemplateParamLists,
AddToScope);
} else {
New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
AddToScope);
}
if (!New)
return nullptr;
if (New->getDeclName() && AddToScope)
PushOnScopeChains(New, S);
if (isInOpenMPDeclareTargetContext())
checkDeclIsAllowedInOpenMPTarget(nullptr, New);
return New;
}
static QualType TryToFixInvalidVariablyModifiedType(QualType T,
ASTContext &Context,
bool &SizeIsNegative,
llvm::APSInt &Oversized) {
SizeIsNegative = false;
Oversized = 0;
if (T->isDependentType())
return QualType();
QualifierCollector Qs;
const Type *Ty = Qs.strip(T);
if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
QualType Pointee = PTy->getPointeeType();
QualType FixedType =
TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
Oversized);
if (FixedType.isNull()) return FixedType;
FixedType = Context.getPointerType(FixedType);
return Qs.apply(Context, FixedType);
}
if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
QualType Inner = PTy->getInnerType();
QualType FixedType =
TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
Oversized);
if (FixedType.isNull()) return FixedType;
FixedType = Context.getParenType(FixedType);
return Qs.apply(Context, FixedType);
}
const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
if (!VLATy)
return QualType();
QualType ElemTy = VLATy->getElementType();
if (ElemTy->isVariablyModifiedType()) {
ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
SizeIsNegative, Oversized);
if (ElemTy.isNull())
return QualType();
}
Expr::EvalResult Result;
if (!VLATy->getSizeExpr() ||
!VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
return QualType();
llvm::APSInt Res = Result.Val.getInt();
if (Res.isSigned() && Res.isNegative()) {
SizeIsNegative = true;
return QualType();
}
unsigned ActiveSizeBits =
(!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
!ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
: Res.getActiveBits();
if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Oversized = Res;
return QualType();
}
QualType FoldedArrayType = Context.getConstantArrayType(
ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
return Qs.apply(Context, FoldedArrayType);
}
static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
SrcTL = SrcTL.getUnqualifiedLoc();
DstTL = DstTL.getUnqualifiedLoc();
if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
DstPTL.getPointeeLoc());
DstPTL.setStarLoc(SrcPTL.getStarLoc());
return;
}
if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
DstPTL.getInnerLoc());
DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
return;
}
ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
TypeLoc SrcElemTL = SrcATL.getElementLoc();
TypeLoc DstElemTL = DstATL.getElementLoc();
if (VariableArrayTypeLoc SrcElemATL =
SrcElemTL.getAs<VariableArrayTypeLoc>()) {
ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
} else {
DstElemTL.initializeFullCopy(SrcElemTL);
}
DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
DstATL.setSizeExpr(SrcATL.getSizeExpr());
DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
}
static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
ASTContext &Context,
bool &SizeIsNegative,
llvm::APSInt &Oversized) {
QualType FixedTy
= TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
SizeIsNegative, Oversized);
if (FixedTy.isNull())
return nullptr;
TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
FixedTInfo->getTypeLoc());
return FixedTInfo;
}
bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
QualType &T, SourceLocation Loc,
unsigned FailedFoldDiagID) {
bool SizeIsNegative;
llvm::APSInt Oversized;
TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
TInfo, Context, SizeIsNegative, Oversized);
if (FixedTInfo) {
Diag(Loc, diag::ext_vla_folded_to_constant);
TInfo = FixedTInfo;
T = FixedTInfo->getType();
return true;
}
if (SizeIsNegative)
Diag(Loc, diag::err_typecheck_negative_array_size);
else if (Oversized.getBoolValue())
Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
else if (FailedFoldDiagID)
Diag(Loc, FailedFoldDiagID);
return false;
}
void
Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
if (!getLangOpts().CPlusPlus &&
ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
return;
Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
}
NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
auto Result = Context.getExternCContextDecl()->lookup(Name);
return Result.empty() ? nullptr : *Result.begin();
}
void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
if (DS.isVirtualSpecified())
Diag(DS.getVirtualSpecLoc(),
diag::err_virtual_non_function);
if (DS.hasExplicitSpecifier())
Diag(DS.getExplicitSpecLoc(),
diag::err_explicit_non_function);
if (DS.isNoreturnSpecified())
Diag(DS.getNoreturnSpecLoc(),
diag::err_noreturn_non_function);
}
NamedDecl*
Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo, LookupResult &Previous) {
if (D.getCXXScopeSpec().isSet()) {
Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
<< D.getCXXScopeSpec().getRange();
D.setInvalidType();
DC = CurContext;
Previous.clear();
}
DiagnoseFunctionSpecifiers(D.getDeclSpec());
if (D.getDeclSpec().isInlineSpecified())
Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
if (D.getDeclSpec().hasConstexprSpecifier())
Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
<< 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
Diag(D.getName().StartLocation,
diag::err_deduction_guide_invalid_specifier)
<< "typedef";
else
Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
<< D.getName().getSourceRange();
return nullptr;
}
TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
if (!NewTD) return nullptr;
ProcessDeclAttributes(S, NewTD, D);
CheckTypedefForVariablyModifiedType(S, NewTD);
bool Redeclaration = D.isRedeclaration();
NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
D.setRedeclaration(Redeclaration);
return ND;
}
void
Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
QualType T = TInfo->getType();
if (T->isVariablyModifiedType()) {
setFunctionHasBranchProtectedScope();
if (S->getFnParent() == nullptr) {
bool SizeIsNegative;
llvm::APSInt Oversized;
TypeSourceInfo *FixedTInfo =
TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
SizeIsNegative,
Oversized);
if (FixedTInfo) {
Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
NewTD->setTypeSourceInfo(FixedTInfo);
} else {
if (SizeIsNegative)
Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
else if (T->isVariableArrayType())
Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
else if (Oversized.getBoolValue())
Diag(NewTD->getLocation(), diag::err_array_too_large)
<< toString(Oversized, 10);
else
Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
NewTD->setInvalidDecl();
}
}
}
}
NamedDecl*
Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
LookupResult &Previous, bool &Redeclaration) {
NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
FilterLookupForScope(Previous, DC, S, false,
false);
filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
if (!Previous.empty()) {
Redeclaration = true;
MergeTypedefNameDecl(S, NewTD, Previous);
} else {
inferGslPointerAttribute(NewTD);
}
if (ShadowedDecl && !Redeclaration)
CheckShadow(NewTD, ShadowedDecl, Previous);
if (IdentifierInfo *II = NewTD->getIdentifier())
if (!NewTD->isInvalidDecl() &&
NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
if (II->isStr("FILE"))
Context.setFILEDecl(NewTD);
else if (II->isStr("jmp_buf"))
Context.setjmp_bufDecl(NewTD);
else if (II->isStr("sigjmp_buf"))
Context.setsigjmp_bufDecl(NewTD);
else if (II->isStr("ucontext_t"))
Context.setucontext_tDecl(NewTD);
}
return NewTD;
}
static bool
isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
ASTContext &Context) {
if (!PrevDecl)
return false;
if (!PrevDecl->hasLinkage())
return false;
if (Context.getLangOpts().CPlusPlus) {
DeclContext *OuterContext = DC->getRedeclContext();
if (!OuterContext->isFunctionOrMethod())
return false;
DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
if (PrevOuterContext->isRecord())
return false;
OuterContext = OuterContext->getEnclosingNamespaceContext();
PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
if (!OuterContext->Equals(PrevOuterContext))
return false;
}
return true;
}
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
CXXScopeSpec &SS = D.getCXXScopeSpec();
if (!SS.isSet()) return;
DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
}
bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
QualType type = decl->getType();
Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
if (lifetime == Qualifiers::OCL_Autoreleasing) {
unsigned kind = -1U;
if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
if (var->hasAttr<BlocksAttr>())
kind = 0; else if (!var->hasLocalStorage())
kind = 1; } else if (isa<ObjCIvarDecl>(decl)) {
kind = 3; } else if (isa<FieldDecl>(decl)) {
kind = 2; }
if (kind != -1U) {
Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
<< kind;
}
} else if (lifetime == Qualifiers::OCL_None) {
if (!type->isObjCLifetimeType())
return false;
lifetime = type->getObjCARCImplicitLifetime();
type = Context.getLifetimeQualifiedType(type, lifetime);
decl->setType(type);
}
if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
var->getTLSKind()) {
Diag(var->getLocation(), diag::err_arc_thread_ownership)
<< var->getType();
return true;
}
}
return false;
}
void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
if (Decl->getType().hasAddressSpace())
return;
if (Decl->getType()->isDependentType())
return;
if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
QualType Type = Var->getType();
if (Type->isSamplerT() || Type->isVoidType())
return;
LangAS ImplAS = LangAS::opencl_private;
if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
Var->hasGlobalStorage())
ImplAS = LangAS::opencl_global;
if (auto DT = dyn_cast<DecayedType>(Type)) {
auto OrigTy = DT->getOriginalType();
if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
Type = Context.getDecayedType(OrigTy);
}
}
Type = Context.getAddrSpaceQualType(Type, ImplAS);
if (Type->isArrayType())
Type = QualType(Context.getAsArrayType(Type), 0);
Decl->setType(Type);
}
}
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
assert(S.ParsingInitForAutoVars.count(&ND) == 0);
if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
if (!ND.isExternallyVisible()) {
S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
ND.dropAttr<WeakAttr>();
}
}
if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
if (ND.isExternallyVisible()) {
S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
ND.dropAttr<WeakRefAttr>();
ND.dropAttr<AliasAttr>();
}
}
if (auto *VD = dyn_cast<VarDecl>(&ND)) {
if (VD->hasInit()) {
if (const auto *Attr = VD->getAttr<AliasAttr>()) {
assert(VD->isThisDeclarationADefinition() &&
!VD->isExternallyVisible() && "Broken AliasAttr handled late!");
S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
VD->dropAttr<AliasAttr>();
}
}
}
if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
S.Diag(Attr->getLocation(),
diag::err_attribute_selectany_non_extern_data);
ND.dropAttr<SelectAnyAttr>();
}
}
if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
auto *VD = dyn_cast<VarDecl>(&ND);
bool IsAnonymousNS = false;
bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
if (VD) {
const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
while (NS && !IsAnonymousNS) {
IsAnonymousNS = NS->isAnonymousNamespace();
NS = dyn_cast<NamespaceDecl>(NS->getParent());
}
}
bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
(!AnonNSInMicrosoftMode &&
(!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
<< &ND << Attr;
ND.setInvalidDecl();
}
}
if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
AttributedTypeLoc ATL;
for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
(ATL = TL.getAsAdjusted<AttributedTypeLoc>());
TL = ATL.getModifiedLoc()) {
if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
const auto *MD = dyn_cast<CXXMethodDecl>(FD);
if (!MD || MD->isStatic()) {
S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
<< !MD << A->getRange();
} else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
<< isa<CXXDestructorDecl>(MD) << A->getRange();
}
}
}
}
}
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
NamedDecl *NewDecl,
bool IsSpecialization,
bool IsDefinition) {
if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
return;
bool IsTemplate = false;
if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
OldDecl = OldTD->getTemplatedDecl();
IsTemplate = true;
if (!IsSpecialization)
IsDefinition = false;
}
if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
NewDecl = NewTD->getTemplatedDecl();
IsTemplate = true;
}
if (!OldDecl || !NewDecl)
return;
const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
(NewExportAttr && !NewExportAttr->isInherited());
bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
bool JustWarn = false;
if (!OldDecl->isCXXClassMember()) {
auto *VD = dyn_cast<VarDecl>(OldDecl);
if (VD && !VD->getDescribedVarTemplate())
JustWarn = true;
auto *FD = dyn_cast<FunctionDecl>(OldDecl);
if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
JustWarn = true;
}
if (OldDecl->isUsed())
if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
JustWarn = false;
unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
: diag::err_attribute_dll_redeclaration;
S.Diag(NewDecl->getLocation(), DiagID)
<< NewDecl
<< (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
if (!JustWarn) {
NewDecl->setInvalidDecl();
return;
}
}
bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
IsStaticDataMember = VD->isStaticDataMember();
IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
VarDecl::DeclarationOnly;
} else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
IsInline = FD->isInlined();
IsQualifiedFriend = FD->getQualifier() &&
FD->getFriendObjectKind() == Decl::FOK_Declared;
}
if (OldImportAttr && !HasNewAttr &&
(!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
!NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
if (IsMicrosoftABI && IsDefinition) {
S.Diag(NewDecl->getLocation(),
diag::warn_redeclaration_without_import_attribute)
<< NewDecl;
S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
NewDecl->dropAttr<DLLImportAttr>();
NewDecl->addAttr(
DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
} else {
S.Diag(NewDecl->getLocation(),
diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
<< NewDecl << OldImportAttr;
S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
OldDecl->dropAttr<DLLImportAttr>();
NewDecl->dropAttr<DLLImportAttr>();
}
} else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
OldDecl->dropAttr<DLLImportAttr>();
NewDecl->dropAttr<DLLImportAttr>();
S.Diag(NewDecl->getLocation(),
diag::warn_dllimport_dropped_from_inline_function)
<< NewDecl << OldImportAttr;
}
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
!NewImportAttr && !NewExportAttr) {
if (const DLLExportAttr *ParentExportAttr =
MD->getParent()->getAttr<DLLExportAttr>()) {
DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
NewAttr->setInherited(true);
NewDecl->addAttr(NewAttr);
}
}
}
}
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
if (!FD->isInlined()) return false;
if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
return false;
return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
}
template<typename T>
static bool isIncompleteDeclExternC(Sema &S, const T *D) {
if (S.getLangOpts().CPlusPlus) {
if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
return false;
if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
D->template hasAttr<CUDAHostAttr>()))
return false;
}
return D->isExternC();
}
static bool shouldConsiderLinkage(const VarDecl *VD) {
const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
isa<OMPDeclareMapperDecl>(DC))
return VD->hasExternalStorage();
if (DC->isFileContext())
return true;
if (DC->isRecord())
return false;
if (isa<RequiresExprBodyDecl>(DC))
return false;
llvm_unreachable("Unexpected context");
}
static bool shouldConsiderLinkage(const FunctionDecl *FD) {
const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
if (DC->isFileContext() || DC->isFunctionOrMethod() ||
isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
return true;
if (DC->isRecord())
return false;
llvm_unreachable("Unexpected context");
}
static bool hasParsedAttr(Scope *S, const Declarator &PD,
ParsedAttr::Kind Kind) {
if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
return true;
for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
return true;
}
return PD.getAttributes().hasAttribute(Kind) ||
PD.getDeclarationAttributes().hasAttribute(Kind);
}
bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
if (!DC->isFunctionOrMethod())
return false;
if (DC->isDependentContext())
return true;
while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
DC = DC->getParent();
return true;
}
static bool isDeclExternC(const Decl *D) {
if (const auto *FD = dyn_cast<FunctionDecl>(D))
return FD->isExternC();
if (const auto *VD = dyn_cast<VarDecl>(D))
return VD->isExternC();
llvm_unreachable("Unknown type of decl!");
}
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
DeclContext *DC = NewVD->getDeclContext();
QualType R = NewVD->getType();
if (R->isImageType() || R->isPipeType()) {
Se.Diag(NewVD->getLocation(),
diag::err_opencl_type_can_only_be_used_as_function_parameter)
<< R;
NewVD->setInvalidDecl();
return false;
}
if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
Se.Diag(NewVD->getLocation(),
diag::err_invalid_type_for_program_scope_var)
<< R;
NewVD->setInvalidDecl();
return false;
}
}
if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
Se.getLangOpts())) {
QualType NR = R.getCanonicalType();
while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
NR->isReferenceType()) {
if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
NR->isFunctionReferenceType()) {
Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
<< NR->isReferenceType();
NewVD->setInvalidDecl();
return false;
}
NR = NR->getPointeeType();
}
}
if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
Se.getLangOpts())) {
if (Se.Context.getBaseElementType(R)->isHalfType()) {
Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
NewVD->setInvalidDecl();
return false;
}
}
if (R->isEventT()) {
if (R.getAddressSpace() != LangAS::opencl_private) {
Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
NewVD->setInvalidDecl();
return false;
}
}
if (R->isSamplerT()) {
if (R.getAddressSpace() == LangAS::opencl_local ||
R.getAddressSpace() == LangAS::opencl_global) {
Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
NewVD->setInvalidDecl();
}
if (DC->isTranslationUnit() &&
!(R.getAddressSpace() == LangAS::opencl_constant ||
R.isConstQualified())) {
Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
NewVD->setInvalidDecl();
}
if (NewVD->isInvalidDecl())
return false;
}
return true;
}
template <typename AttrTy>
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
const TypedefNameDecl *TND = TT->getDecl();
if (const auto *Attribute = TND->getAttr<AttrTy>()) {
AttrTy *Clone = Attribute->clone(S.Context);
Clone->setInherited(true);
D->addAttr(Clone);
}
}
NamedDecl *Sema::ActOnVariableDeclarator(
Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
QualType R = TInfo->getType();
DeclarationName Name = GetNameForDeclarator(D).getName();
IdentifierInfo *II = Name.getAsIdentifierInfo();
if (D.isDecompositionDeclarator()) {
auto &Decomp = D.getDecompositionDeclarator();
if (!Decomp.bindings().empty()) {
II = Decomp.bindings()[0].Name;
Name = II;
}
} else if (!II) {
Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
return nullptr;
}
DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
if (SC == SC_None && !DC->isRecord() &&
hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
!hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
SC = SC_Extern;
DeclContext *OriginalDC = DC;
bool IsLocalExternDecl = SC == SC_Extern &&
adjustContextForLocalExternDecl(DC);
if (SCSpec == DeclSpec::SCS_mutable) {
Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
D.setInvalidType();
SC = SC_None;
}
if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
!D.getAsmLabel() && !getSourceManager().isInSystemMacro(
D.getDeclSpec().getStorageClassSpecLoc())) {
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
: diag::warn_deprecated_register)
<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
}
DiagnoseFunctionSpecifiers(D.getDeclSpec());
if (!DC->isRecord() && S->getFnParent() == nullptr) {
if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
D.setInvalidType();
}
}
if (D.hasInitializer() && R->isVariableArrayType())
tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
0);
bool IsMemberSpecialization = false;
bool IsVariableTemplateSpecialization = false;
bool IsPartialSpecialization = false;
bool IsVariableTemplate = false;
VarDecl *NewVD = nullptr;
VarTemplateDecl *NewTemplate = nullptr;
TemplateParameterList *TemplateParams = nullptr;
if (!getLangOpts().CPlusPlus) {
NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
II, R, TInfo, SC);
if (R->getContainedDeducedType())
ParsingInitForAutoVars.insert(NewVD);
if (D.isInvalidType())
NewVD->setInvalidDecl();
if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
NewVD->hasLocalStorage())
checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
NTCUC_AutoVar, NTCUK_Destruct);
} else {
bool Invalid = false;
if (DC->isRecord() && !CurContext->isRecord()) {
switch (SC) {
case SC_None:
break;
case SC_Static:
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_static_out_of_line)
<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
break;
case SC_Auto:
case SC_Register:
case SC_Extern:
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_storage_class_for_static_member)
<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
break;
case SC_PrivateExtern:
llvm_unreachable("C storage class in c++!");
}
}
if (SC == SC_Static && CurContext->isRecord()) {
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
const DeclContext *FunctionOrMethod = nullptr;
const CXXRecordDecl *AnonStruct = nullptr;
for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
if (Ctxt->isFunctionOrMethod()) {
FunctionOrMethod = Ctxt;
break;
}
const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
if (ParentDecl && !ParentDecl->getDeclName()) {
AnonStruct = ParentDecl;
break;
}
}
if (FunctionOrMethod) {
Diag(D.getIdentifierLoc(),
diag::err_static_data_member_not_allowed_in_local_class)
<< Name << RD->getDeclName() << RD->getTagKind();
} else if (AnonStruct) {
Diag(D.getIdentifierLoc(),
diag::err_static_data_member_not_allowed_in_anon_struct)
<< Name << AnonStruct->getTagKind();
Invalid = true;
} else if (RD->isUnion()) {
Diag(D.getIdentifierLoc(),
getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_static_data_member_in_union
: diag::ext_static_data_member_in_union) << Name;
}
}
}
bool InvalidScope = false;
TemplateParams = MatchTemplateParametersToScopeSpecifier(
D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
D.getCXXScopeSpec(),
D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
? D.getName().TemplateId
: nullptr,
TemplateParamLists,
false, IsMemberSpecialization, InvalidScope);
Invalid |= InvalidScope;
if (TemplateParams) {
if (!TemplateParams->size() &&
D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
Diag(TemplateParams->getTemplateLoc(),
diag::err_template_variable_noparams)
<< II
<< SourceRange(TemplateParams->getTemplateLoc(),
TemplateParams->getRAngleLoc());
TemplateParams = nullptr;
} else {
if (CheckTemplateDeclScope(S, TemplateParams))
return nullptr;
if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
IsVariableTemplateSpecialization = true;
IsPartialSpecialization = TemplateParams->size() > 0;
} else { IsVariableTemplate = true;
Diag(D.getIdentifierLoc(),
getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_variable_template
: diag::ext_variable_template);
}
}
} else {
if (!TemplateParamLists.empty() && IsMemberSpecialization &&
CheckTemplateDeclScope(S, TemplateParamLists.back()))
return nullptr;
assert((Invalid ||
D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
"should have a 'template<>' for this decl");
}
if (IsVariableTemplateSpecialization) {
SourceLocation TemplateKWLoc =
TemplateParamLists.size() > 0
? TemplateParamLists[0]->getTemplateLoc()
: SourceLocation();
DeclResult Res = ActOnVarTemplateSpecialization(
S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
IsPartialSpecialization);
if (Res.isInvalid())
return nullptr;
NewVD = cast<VarDecl>(Res.get());
AddToScope = false;
} else if (D.isDecompositionDeclarator()) {
NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
D.getIdentifierLoc(), R, TInfo, SC,
Bindings);
} else
NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
D.getIdentifierLoc(), II, R, TInfo, SC);
if (IsVariableTemplate) {
NewTemplate =
VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
TemplateParams, NewVD);
NewVD->setDescribedVarTemplate(NewTemplate);
}
if (R->getContainedDeducedType())
ParsingInitForAutoVars.insert(NewVD);
if (D.isInvalidType() || Invalid) {
NewVD->setInvalidDecl();
if (NewTemplate)
NewTemplate->setInvalidDecl();
}
SetNestedNameSpecifier(*this, NewVD, D);
unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
if (TemplateParamLists.size() > VDTemplateParamLists)
NewVD->setTemplateParameterListsInfo(
Context, TemplateParamLists.drop_back(VDTemplateParamLists));
}
if (D.getDeclSpec().isInlineSpecified()) {
if (!getLangOpts().CPlusPlus) {
Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
<< 0;
} else if (CurContext->isFunctionOrMethod()) {
Diag(D.getDeclSpec().getInlineSpecLoc(),
diag::err_inline_declaration_block_scope) << Name
<< FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
} else {
Diag(D.getDeclSpec().getInlineSpecLoc(),
getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
: diag::ext_inline_variable);
NewVD->setInlineSpecified();
}
}
NewVD->setLexicalDeclContext(CurContext);
if (NewTemplate)
NewTemplate->setLexicalDeclContext(CurContext);
if (IsLocalExternDecl) {
if (D.isDecompositionDeclarator())
for (auto *B : Bindings)
B->setLocalExternDecl();
else
NewVD->setLocalExternDecl();
}
bool EmitTLSUnsupportedError = false;
if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
if (NewVD->hasLocalStorage() &&
(SCSpec != DeclSpec::SCS_unspecified ||
TSCS != DeclSpec::TSCS_thread_local ||
!DC->isFunctionOrMethod()))
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_thread_non_global)
<< DeclSpec::getSpecifierName(TSCS);
else if (!Context.getTargetInfo().isTLSSupported()) {
if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
getLangOpts().SYCLIsDevice) {
EmitTLSUnsupportedError = true;
NewVD->setTSCSpec(TSCS);
} else
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_thread_unsupported);
} else
NewVD->setTSCSpec(TSCS);
}
switch (D.getDeclSpec().getConstexprSpecifier()) {
case ConstexprSpecKind::Unspecified:
break;
case ConstexprSpecKind::Consteval:
Diag(D.getDeclSpec().getConstexprSpecLoc(),
diag::err_constexpr_wrong_decl_kind)
<< static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
LLVM_FALLTHROUGH;
case ConstexprSpecKind::Constexpr:
NewVD->setConstexpr(true);
if (NewVD->isStaticDataMember() &&
(getLangOpts().CPlusPlus17 ||
Context.getTargetInfo().getCXXABI().isMicrosoft()))
NewVD->setImplicitlyInline();
break;
case ConstexprSpecKind::Constinit:
if (!NewVD->hasGlobalStorage())
Diag(D.getDeclSpec().getConstexprSpecLoc(),
diag::err_constinit_local_variable);
else
NewVD->addAttr(ConstInitAttr::Create(
Context, D.getDeclSpec().getConstexprSpecLoc(),
AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
break;
}
if (SC == SC_Static && S->getFnParent() != nullptr &&
!NewVD->getType().isConstQualified()) {
FunctionDecl *CurFD = getCurFunctionDecl();
if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::warn_static_local_in_extern_inline);
MaybeSuggestAddingStaticToDecl(CurFD);
}
}
if (D.getDeclSpec().isModulePrivateSpecified()) {
if (IsVariableTemplateSpecialization)
Diag(NewVD->getLocation(), diag::err_module_private_specialization)
<< (IsPartialSpecialization ? 1 : 0)
<< FixItHint::CreateRemoval(
D.getDeclSpec().getModulePrivateSpecLoc());
else if (IsMemberSpecialization)
Diag(NewVD->getLocation(), diag::err_module_private_specialization)
<< 2
<< FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
else if (NewVD->hasLocalStorage())
Diag(NewVD->getLocation(), diag::err_module_private_local)
<< 0 << NewVD
<< SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
<< FixItHint::CreateRemoval(
D.getDeclSpec().getModulePrivateSpecLoc());
else {
NewVD->setModulePrivate();
if (NewTemplate)
NewTemplate->setModulePrivate();
for (auto *B : Bindings)
B->setModulePrivate();
}
}
if (getLangOpts().OpenCL) {
deduceOpenCLAddressSpace(NewVD);
DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
if (TSC != TSCS_unspecified) {
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_opencl_unknown_type_specifier)
<< getLangOpts().getOpenCLVersionString()
<< DeclSpec::getSpecifierName(TSC) << 1;
NewVD->setInvalidDecl();
}
}
ProcessDeclAttributes(S, NewVD, D);
if (R->isFunctionPointerType())
if (const auto *TT = R->getAs<TypedefType>())
copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
getLangOpts().SYCLIsDevice) {
if (EmitTLSUnsupportedError &&
((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
(getLangOpts().OpenMPIsDevice &&
OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_thread_unsupported);
if (EmitTLSUnsupportedError &&
(LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
if (SC == SC_None && S->getFnParent() != nullptr &&
(NewVD->hasAttr<CUDASharedAttr>() ||
NewVD->hasAttr<CUDAConstantAttr>())) {
NewVD->setStorageClass(SC_Static);
}
}
assert(!NewVD->hasAttr<DLLImportAttr>() ||
NewVD->getAttr<DLLImportAttr>()->isInherited() ||
NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
NewVD->setInvalidDecl();
if (Expr *E = (Expr*)D.getAsmLabel()) {
StringLiteral *SE = cast<StringLiteral>(E);
StringRef Label = SE->getString();
if (S->getFnParent() != nullptr) {
switch (SC) {
case SC_None:
case SC_Auto:
Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
break;
case SC_Register:
if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
break;
case SC_Static:
case SC_Extern:
case SC_PrivateExtern:
break;
}
} else if (SC == SC_Register) {
if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
const auto &TI = Context.getTargetInfo();
bool HasSizeMismatch;
if (!TI.isValidGCCRegisterName(Label))
Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
else if (!TI.validateGlobalRegisterVariable(Label,
Context.getTypeSize(R),
HasSizeMismatch))
Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
else if (HasSizeMismatch)
Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
}
if (!R->isIntegralType(Context) && !R->isPointerType()) {
Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
NewVD->setInvalidDecl(true);
}
}
NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
true,
SE->getStrTokenLoc(0)));
} else if (!ExtnameUndeclaredIdentifiers.empty()) {
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
if (I != ExtnameUndeclaredIdentifiers.end()) {
if (isDeclExternC(NewVD)) {
NewVD->addAttr(I->second);
ExtnameUndeclaredIdentifiers.erase(I);
} else
Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
<< 1 << NewVD;
}
}
NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
? getShadowedDeclaration(NewVD, Previous)
: nullptr;
FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
D.getCXXScopeSpec().isNotEmpty() ||
IsMemberSpecialization ||
IsVariableTemplateSpecialization);
if (getLangOpts().CPlusPlus &&
NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
NewVD->setPreviousDeclInSameBlockScope(
Previous.isSingleResult() && !Previous.isShadowed() &&
isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
if (!getLangOpts().CPlusPlus) {
D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
} else {
if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
CheckMemberSpecialization(NewVD, Previous))
NewVD->setInvalidDecl();
if (!Previous.empty()) {
if (Previous.isSingleResult() &&
isa<FieldDecl>(Previous.getFoundDecl()) &&
D.getCXXScopeSpec().isSet()) {
Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
<< D.getCXXScopeSpec().getRange();
Previous.clear();
NewVD->setInvalidDecl();
}
} else if (D.getCXXScopeSpec().isSet()) {
Diag(D.getIdentifierLoc(), diag::err_no_member)
<< Name << computeDeclContext(D.getCXXScopeSpec(), true)
<< D.getCXXScopeSpec().getRange();
NewVD->setInvalidDecl();
}
if (!IsVariableTemplateSpecialization)
D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
if (NewTemplate) {
VarTemplateDecl *PrevVarTemplate =
NewVD->getPreviousDecl()
? NewVD->getPreviousDecl()->getDescribedVarTemplate()
: nullptr;
if (CheckTemplateParameterList(
TemplateParams,
PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
: nullptr,
(D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
DC->isDependentContext())
? TPC_ClassTemplateMember
: TPC_VarTemplate))
NewVD->setInvalidDecl();
if (PrevVarTemplate &&
PrevVarTemplate->getInstantiatedFromMemberTemplate())
PrevVarTemplate->setMemberSpecialization();
}
}
if (ShadowedDecl && !D.isRedeclaration())
CheckShadow(NewVD, ShadowedDecl, Previous);
ProcessPragmaWeak(S, NewVD);
if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
isIncompleteDeclExternC(*this, NewVD))
RegisterLocallyScopedExternCDecl(NewVD, S);
if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
MangleNumberingContext *MCtx;
Decl *ManglingContextDecl;
std::tie(MCtx, ManglingContextDecl) =
getCurrentMangleNumberContext(NewVD->getDeclContext());
if (MCtx) {
Context.setManglingNumber(
NewVD, MCtx->getManglingNumber(
NewVD, getMSManglingNumber(getLangOpts(), S)));
Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
}
}
if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
!getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
if (getLangOpts().CPlusPlus)
Diag(D.getBeginLoc(), diag::err_main_global_variable);
else if (NewVD->hasExternalFormalLinkage())
Diag(D.getBeginLoc(), diag::warn_main_redefined);
}
if (D.isRedeclaration() && !Previous.empty()) {
NamedDecl *Prev = Previous.getRepresentativeDecl();
checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
D.isFunctionDefinition());
}
if (NewTemplate) {
if (NewVD->isInvalidDecl())
NewTemplate->setInvalidDecl();
ActOnDocumentableDecl(NewTemplate);
return NewTemplate;
}
if (IsMemberSpecialization && !NewVD->isInvalidDecl())
CompleteMemberSpecialization(NewVD, Previous);
return NewVD;
}
enum ShadowedDeclKind {
SDK_Local,
SDK_Global,
SDK_StaticMember,
SDK_Field,
SDK_Typedef,
SDK_Using,
SDK_StructuredBinding
};
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
const DeclContext *OldDC) {
if (isa<TypeAliasDecl>(ShadowedDecl))
return SDK_Using;
else if (isa<TypedefDecl>(ShadowedDecl))
return SDK_Typedef;
else if (isa<BindingDecl>(ShadowedDecl))
return SDK_StructuredBinding;
else if (isa<RecordDecl>(OldDC))
return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
return OldDC->isFileContext() ? SDK_Global : SDK_Local;
}
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
const VarDecl *VD) {
for (const Capture &Capture : LSI->Captures) {
if (Capture.isVariableCapture() && Capture.getVariable() == VD)
return Capture.getLocation();
}
return SourceLocation();
}
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
const LookupResult &R) {
if (R.getResultKind() != LookupResult::Found)
return false;
return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
}
NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
const LookupResult &R) {
if (!shouldWarnIfShadowedDecl(Diags, R))
return nullptr;
if (D->hasGlobalStorage())
return nullptr;
NamedDecl *ShadowedDecl = R.getFoundDecl();
return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
: nullptr;
}
NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R) {
if (D->getDeclContext()->isRecord())
return nullptr;
if (!shouldWarnIfShadowedDecl(Diags, R))
return nullptr;
NamedDecl *ShadowedDecl = R.getFoundDecl();
return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
}
NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
const LookupResult &R) {
if (!shouldWarnIfShadowedDecl(Diags, R))
return nullptr;
NamedDecl *ShadowedDecl = R.getFoundDecl();
return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
: nullptr;
}
void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R) {
DeclContext *NewDC = D->getDeclContext();
if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
if (MD->isStatic())
return;
if (isa<CXXConstructorDecl>(NewDC))
if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
return;
}
}
if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
if (shadowedVar->isExternC()) {
for (auto I : shadowedVar->redecls())
if (I->isFileVarDecl()) {
ShadowedDecl = I;
break;
}
}
DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
unsigned WarningDiag = diag::warn_decl_shadow;
SourceLocation CaptureLoc;
if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
isa<CXXMethodDecl>(NewDC)) {
if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
if (RD->getLambdaCaptureDefault() == LCD_None) {
const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
if (CaptureLoc.isInvalid())
WarningDiag = diag::warn_decl_shadow_uncaptured_local;
} else {
cast<LambdaScopeInfo>(getCurFunction())
->ShadowingDecls.push_back(
{cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
return;
}
}
if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
for (DeclContext *ParentDC = NewDC;
ParentDC && !ParentDC->Equals(OldDC);
ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
!isLambdaCallOperator(ParentDC)) {
return;
}
}
}
}
}
if (NewDC && NewDC->isRecord()) {
if (!OldDC->isRecord())
return;
}
DeclarationName Name = R.getLookupName();
ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
if (!CaptureLoc.isInvalid())
Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
<< Name << 1;
Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
}
void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
for (const auto &Shadow : LSI->ShadowingDecls) {
const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
const DeclContext *OldDC = ShadowedDecl->getDeclContext();
Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
? diag::warn_decl_shadow_uncaptured_local
: diag::warn_decl_shadow)
<< Shadow.VD->getDeclName()
<< computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
if (!CaptureLoc.isInvalid())
Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
<< Shadow.VD->getDeclName() << 0;
Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
}
}
void Sema::CheckShadow(Scope *S, VarDecl *D) {
if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
return;
LookupResult R(*this, D->getDeclName(), D->getLocation(),
Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
LookupName(R, S);
if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
CheckShadow(D, ShadowedDecl, R);
}
void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
return;
E = E->IgnoreParenImpCasts();
auto *DRE = dyn_cast<DeclRefExpr>(E);
if (!DRE)
return;
const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
auto I = ShadowingDecls.find(D);
if (I == ShadowingDecls.end())
return;
const NamedDecl *ShadowedDecl = I->second;
const DeclContext *OldDC = ShadowedDecl->getDeclContext();
Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
Diag(D->getLocation(), diag::note_var_declared_here) << D;
Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
ShadowingDecls.erase(I);
}
template<typename T>
static bool checkGlobalOrExternCConflict(
Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
return false;
}
if (Prev) {
if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
Previous.clear();
Previous.addDecl(Prev);
return true;
}
if (!isa<VarDecl>(ND))
return false;
} else {
if (IsGlobal) {
IsGlobal = false;
for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
I != E; ++I) {
if (isa<VarDecl>(*I)) {
Prev = *I;
break;
}
}
} else {
DeclContext::lookup_result R =
S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
I != E; ++I) {
if (isa<VarDecl>(*I)) {
Prev = *I;
break;
}
}
}
if (!Prev)
return false;
}
assert(Prev && "should have found a previous declaration to diagnose");
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
Prev = FD->getFirstDecl();
else
Prev = cast<VarDecl>(Prev)->getFirstDecl();
S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
<< IsGlobal << ND;
S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
<< IsGlobal;
return false;
}
template<typename T>
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
LookupResult &Previous) {
if (!S.getLangOpts().CPlusPlus) {
if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
Previous.clear();
Previous.addDecl(Prev);
return true;
}
}
return false;
}
if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
return checkGlobalOrExternCConflict(S, ND, true, Previous);
if (isIncompleteDeclExternC(S,ND))
return checkGlobalOrExternCConflict(S, ND, false, Previous);
return false;
}
void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
if (NewVD->isInvalidDecl())
return;
QualType T = NewVD->getType();
if (T->isUndeducedType())
return;
if (NewVD->hasAttrs())
CheckAlignasUnderalignment(NewVD);
if (T->isObjCObjectType()) {
Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
<< FixItHint::CreateInsertion(NewVD->getLocation(), "*");
T = Context.getObjCObjectPointerType(T);
NewVD->setType(T);
}
if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
T.getAddressSpace() != LangAS::Default) {
Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
NewVD->setInvalidDecl();
return;
}
if (getLangOpts().OpenCLVersion == 120 &&
!getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
getLangOpts()) &&
NewVD->isStaticLocal()) {
Diag(NewVD->getLocation(), diag::err_static_function_scope);
NewVD->setInvalidDecl();
return;
}
if (getLangOpts().OpenCL) {
if (!diagnoseOpenCLTypes(*this, NewVD))
return;
if (NewVD->hasAttr<BlocksAttr>()) {
Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
return;
}
if (T->isBlockPointerType()) {
if (!T.isConstQualified()) {
Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
<< 0 ;
NewVD->setInvalidDecl();
return;
}
if (NewVD->hasExternalStorage()) {
Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
NewVD->setInvalidDecl();
return;
}
}
if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
NewVD->hasExternalStorage()) {
if (!T->isSamplerT() && !T->isDependentType() &&
!(T.getAddressSpace() == LangAS::opencl_constant ||
(T.getAddressSpace() == LangAS::opencl_global &&
getOpenCLOptions().areProgramScopeVariablesSupported(
getLangOpts())))) {
int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
<< Scope << "global or constant";
else
Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
<< Scope << "constant";
NewVD->setInvalidDecl();
return;
}
} else {
if (T.getAddressSpace() == LangAS::opencl_global) {
Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
<< 1 << "global";
NewVD->setInvalidDecl();
return;
}
if (T.getAddressSpace() == LangAS::opencl_constant ||
T.getAddressSpace() == LangAS::opencl_local) {
FunctionDecl *FD = getCurFunctionDecl();
if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
if (T.getAddressSpace() == LangAS::opencl_constant)
Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
<< 0 << "constant";
else
Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
<< 0 << "local";
NewVD->setInvalidDecl();
return;
}
if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
if (!getCurScope()->isFunctionScope()) {
if (T.getAddressSpace() == LangAS::opencl_constant)
Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
<< "constant";
else
Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
<< "local";
NewVD->setInvalidDecl();
return;
}
}
} else if (T.getAddressSpace() != LangAS::opencl_private &&
T.getAddressSpace() != LangAS::Default) {
Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
NewVD->setInvalidDecl();
return;
}
}
}
if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
&& !NewVD->hasAttr<BlocksAttr>()) {
if (getLangOpts().getGC() != LangOptions::NonGC)
Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
else {
assert(!getLangOpts().ObjCAutoRefCount);
Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
}
}
bool isVM = T->isVariablyModifiedType();
if (isVM || NewVD->hasAttr<CleanupAttr>() ||
NewVD->hasAttr<BlocksAttr>())
setFunctionHasBranchProtectedScope();
if ((isVM && NewVD->hasLinkage()) ||
(T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
bool SizeIsNegative;
llvm::APSInt Oversized;
TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
QualType FixedT;
if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
FixedT = FixedTInfo->getType();
else if (FixedTInfo) {
FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
Oversized);
}
if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
if (NewVD->isFileVarDecl())
Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
<< SizeRange;
else if (NewVD->isStaticLocal())
Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
<< SizeRange;
else
Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
<< SizeRange;
NewVD->setInvalidDecl();
return;
}
if (!FixedTInfo) {
if (NewVD->isFileVarDecl())
Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
else
Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
NewVD->setInvalidDecl();
return;
}
Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
NewVD->setType(FixedT);
NewVD->setTypeSourceInfo(FixedTInfo);
}
if (T->isVoidType()) {
if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
<< T;
NewVD->setInvalidDecl();
return;
}
}
if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
NewVD->setInvalidDecl();
return;
}
if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
NewVD->setInvalidDecl();
return;
}
if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Diag(NewVD->getLocation(), diag::err_block_on_vm);
NewVD->setInvalidDecl();
return;
}
if (NewVD->isConstexpr() && !T->isDependentType() &&
RequireLiteralType(NewVD->getLocation(), T,
diag::err_constexpr_var_non_literal)) {
NewVD->setInvalidDecl();
return;
}
if (Context.getTargetInfo().getTriple().isPPC64() &&
!NewVD->isLocalVarDecl() &&
CheckPPCMMAType(T, NewVD->getLocation())) {
NewVD->setInvalidDecl();
return;
}
}
bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
CheckVariableDeclarationType(NewVD);
if (NewVD->isInvalidDecl())
return false;
if (Previous.empty() &&
checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
Previous.setShadowed();
if (!Previous.empty()) {
MergeVarDecl(NewVD, Previous);
return true;
}
return false;
}
bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
CXXBasePaths Paths(true, false,
false);
auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
DeclarationName Name = MD->getDeclName();
if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
QualType T = Context.getTypeDeclType(BaseRecord);
CanQualType CT = Context.getCanonicalType(T);
Name = Context.DeclarationNames.getCXXDestructorName(CT);
}
for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
CXXMethodDecl *BaseMD =
dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
if (!BaseMD || !BaseMD->isVirtual() ||
IsOverload(MD, BaseMD, false,
true,
false))
continue;
if (Overridden.insert(BaseMD).second) {
MD->addOverriddenMethod(BaseMD);
CheckOverridingFunctionReturnType(MD, BaseMD);
CheckOverridingFunctionAttributes(MD, BaseMD);
CheckOverridingFunctionExceptionSpec(MD, BaseMD);
CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
}
return true;
}
return false;
};
DC->lookupInBases(VisitBase, Paths);
return !Overridden.empty();
}
namespace {
struct ActOnFDArgs {
Scope *S;
Declarator &D;
MultiTemplateParamsArg TemplateParamLists;
bool AddToScope;
};
}
namespace {
class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
public:
DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
CXXRecordDecl *Parent)
: Context(Context), OriginalFD(TypoFD),
ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (candidate.getEditDistance() == 0)
return false;
SmallVector<unsigned, 1> MismatchedParams;
for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
CDeclEnd = candidate.end();
CDecl != CDeclEnd; ++CDecl) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
if (FD && !FD->hasBody() &&
hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
CXXRecordDecl *Parent = MD->getParent();
if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
return true;
} else if (!ExpectedParent) {
return true;
}
}
}
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<DifferentNameValidatorCCC>(*this);
}
private:
ASTContext &Context;
FunctionDecl *OriginalFD;
CXXRecordDecl *ExpectedParent;
};
}
void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
TypoCorrectedFunctionDefinitions.insert(F);
}
static NamedDecl *DiagnoseInvalidRedeclaration(
Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
DeclarationName Name = NewFD->getDeclName();
DeclContext *NewDC = NewFD->getDeclContext();
SmallVector<unsigned, 1> MismatchedParams;
SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
TypoCorrection Correction;
bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
unsigned DiagMsg =
IsLocalFriend ? diag::err_no_matching_local_friend :
NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
diag::err_member_decl_does_not_match;
LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
IsLocalFriend ? Sema::LookupLocalFriendName
: Sema::LookupOrdinaryName,
Sema::ForVisibleRedeclaration);
NewFD->setInvalidDecl();
if (IsLocalFriend)
SemaRef.LookupName(Prev, S);
else
SemaRef.LookupQualifiedName(Prev, NewDC);
assert(!Prev.isAmbiguous() &&
"Cannot have an ambiguity in previous-declaration lookup");
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
MD ? MD->getParent() : nullptr);
if (!Prev.empty()) {
for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
Func != FuncEnd; ++Func) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
if (FD &&
hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
unsigned ParamNum =
MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
NearMatches.push_back(std::make_pair(FD, ParamNum));
}
}
} else if ((Correction = SemaRef.CorrectTypo(
Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
&ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
IsLocalFriend ? nullptr : NewDC))) {
ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
ExtraArgs.D.getIdentifierLoc());
Previous.clear();
Previous.setLookupName(Correction.getCorrection());
for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
CDeclEnd = Correction.end();
CDecl != CDeclEnd; ++CDecl) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
if (FD && !FD->hasBody() &&
hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
Previous.addDecl(FD);
}
}
bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
NamedDecl *Result;
{
Sema::SFINAETrap Trap(SemaRef);
Result = SemaRef.ActOnFunctionDeclarator(
ExtraArgs.S, ExtraArgs.D,
Correction.getCorrectionDecl()->getDeclContext(),
NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
ExtraArgs.AddToScope);
if (Trap.hasErrorOccurred())
Result = nullptr;
}
if (Result) {
Decl *Canonical = Result->getCanonicalDecl();
for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
I != E; ++I)
if ((*I)->getCanonicalDecl() == Canonical)
Correction.setCorrectionDecl(*I);
SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
SemaRef.diagnoseTypo(
Correction,
SemaRef.PDiag(IsLocalFriend
? diag::err_no_matching_local_friend_suggest
: diag::err_member_decl_does_not_match_suggest)
<< Name << NewDC << IsDefinition);
return Result;
}
ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
ExtraArgs.D.getIdentifierLoc());
ExtraArgs.D.setRedeclaration(wasRedeclaration);
Previous.clear();
Previous.setLookupName(Name);
}
SemaRef.Diag(NewFD->getLocation(), DiagMsg)
<< Name << NewDC << IsDefinition << NewFD->getLocation();
bool NewFDisConst = false;
if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
NewFDisConst = NewMD->isConst();
for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
NearMatch != NearMatchEnd; ++NearMatch) {
FunctionDecl *FD = NearMatch->first;
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
bool FDisConst = MD && MD->isConst();
bool IsMember = MD || !IsLocalFriend;
if (unsigned Idx = NearMatch->second) {
ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
SourceLocation Loc = FDParam->getTypeSpecStartLoc();
if (Loc.isInvalid()) Loc = FD->getLocation();
SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
: diag::note_local_decl_close_param_match)
<< Idx << FDParam->getType()
<< NewFD->getParamDecl(Idx - 1)->getType();
} else if (FDisConst != NewFDisConst) {
SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
<< NewFDisConst << FD->getSourceRange().getEnd()
<< (NewFDisConst
? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
.getConstQualifierLoc())
: FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
.getRParenLoc()
.getLocWithOffset(1),
" const"));
} else
SemaRef.Diag(FD->getLocation(),
IsMember ? diag::note_member_def_close_match
: diag::note_local_decl_close_match);
}
return nullptr;
}
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
switch (D.getDeclSpec().getStorageClassSpec()) {
default: llvm_unreachable("Unknown storage class!");
case DeclSpec::SCS_auto:
case DeclSpec::SCS_register:
case DeclSpec::SCS_mutable:
SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_typecheck_sclass_func);
D.getMutableDeclSpec().ClearStorageClassSpecs();
D.setInvalidType();
break;
case DeclSpec::SCS_unspecified: break;
case DeclSpec::SCS_extern:
if (D.getDeclSpec().isExternInLinkageSpec())
return SC_None;
return SC_Extern;
case DeclSpec::SCS_static: {
if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_static_block_func);
break;
} else
return SC_Static;
}
case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
}
return SC_None;
}
static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
DeclContext *DC, QualType &R,
TypeSourceInfo *TInfo,
StorageClass SC,
bool &IsVirtualOkay) {
DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
DeclarationName Name = NameInfo.getName();
FunctionDecl *NewFD = nullptr;
bool isInline = D.getDeclSpec().isInlineSpecified();
if (!SemaRef.getLangOpts().CPlusPlus) {
bool HasPrototype =
(D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
(D.getDeclSpec().isTypeRep() &&
D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
(!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
assert(
(HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
"Strict prototypes are required");
NewFD = FunctionDecl::Create(
SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
ConstexprSpecKind::Unspecified,
nullptr);
if (D.isInvalidType())
NewFD->setInvalidDecl();
return NewFD;
}
ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
if (ConstexprKind == ConstexprSpecKind::Constinit) {
SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
diag::err_constexpr_wrong_decl_kind)
<< static_cast<int>(ConstexprKind);
ConstexprKind = ConstexprSpecKind::Unspecified;
D.getMutableDeclSpec().ClearConstexprSpec();
}
Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
if (!DC->isRecord() &&
SemaRef.RequireNonAbstractType(
D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
D.setInvalidType();
if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
assert(DC->isRecord() &&
"Constructors can only be declared in a member context");
R = SemaRef.CheckConstructorDeclarator(D, R, SC);
return CXXConstructorDecl::Create(
SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
isInline, false, ConstexprKind,
InheritedConstructor(), TrailingRequiresClause);
} else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
if (DC->isRecord()) {
R = SemaRef.CheckDestructorDeclarator(D, R, SC);
CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
false, ConstexprKind,
TrailingRequiresClause);
if (Record->isBeingDefined())
NewDD->setIneligibleOrNotSelected(true);
if (SemaRef.getLangOpts().CPlusPlus11)
SemaRef.AdjustDestructorExceptionSpec(NewDD);
IsVirtualOkay = true;
return NewDD;
} else {
SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
D.setInvalidType();
return FunctionDecl::Create(
SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
true, ConstexprKind, TrailingRequiresClause);
}
} else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
if (!DC->isRecord()) {
SemaRef.Diag(D.getIdentifierLoc(),
diag::err_conv_function_not_member);
return nullptr;
}
SemaRef.CheckConversionDeclarator(D, R, SC);
if (D.isInvalidType())
return nullptr;
IsVirtualOkay = true;
return CXXConversionDecl::Create(
SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
ExplicitSpecifier, ConstexprKind, SourceLocation(),
TrailingRequiresClause);
} else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
if (TrailingRequiresClause)
SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
diag::err_trailing_requires_clause_on_deduction_guide)
<< TrailingRequiresClause->getSourceRange();
SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
ExplicitSpecifier, NameInfo, R, TInfo,
D.getEndLoc());
} else if (DC->isRecord()) {
if (Name.getAsIdentifierInfo() &&
Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
<< SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
<< SourceRange(D.getIdentifierLoc());
return nullptr;
}
CXXMethodDecl *Ret = CXXMethodDecl::Create(
SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
ConstexprKind, SourceLocation(), TrailingRequiresClause);
IsVirtualOkay = !Ret->isStatic();
return Ret;
} else {
bool isFriend =
SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
if (!isFriend && SemaRef.CurContext->isRecord())
return nullptr;
return FunctionDecl::Create(
SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
true , ConstexprKind, TrailingRequiresClause);
}
}
enum OpenCLParamType {
ValidKernelParam,
PtrPtrKernelParam,
PtrKernelParam,
InvalidAddrSpacePtrKernelParam,
InvalidKernelParam,
RecordKernelParam
};
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
QualType DesugaredTy = Ty;
do {
ArrayRef<StringRef> Names(SizeTypeNames);
auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
if (Names.end() != Match)
return true;
Ty = DesugaredTy;
DesugaredTy = Ty.getSingleStepDesugaredType(C);
} while (DesugaredTy != Ty);
return false;
}
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
if (PT->isDependentType())
return InvalidKernelParam;
if (PT->isPointerType() || PT->isReferenceType()) {
QualType PointeeType = PT->getPointeeType();
if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
PointeeType.getAddressSpace() == LangAS::opencl_private ||
PointeeType.getAddressSpace() == LangAS::Default)
return InvalidAddrSpacePtrKernelParam;
if (PointeeType->isPointerType()) {
OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
if (ParamKind == InvalidAddrSpacePtrKernelParam ||
ParamKind == InvalidKernelParam)
return ParamKind;
return PtrPtrKernelParam;
}
if (S.getLangOpts().OpenCLCPlusPlus &&
!S.getOpenCLOptions().isAvailableOption(
"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
!PointeeType->isStandardLayoutType())
return InvalidKernelParam;
return PtrKernelParam;
}
if (isOpenCLSizeDependentType(S.getASTContext(), PT))
return InvalidKernelParam;
if (PT->isImageType())
return PtrKernelParam;
if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
return InvalidKernelParam;
if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
PT->isHalfType())
return InvalidKernelParam;
if (PT->isArrayType()) {
const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
}
if (S.getLangOpts().OpenCLCPlusPlus &&
!S.getOpenCLOptions().isAvailableOption(
"__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
!PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
return InvalidKernelParam;
if (PT->isRecordType())
return RecordKernelParam;
return ValidKernelParam;
}
static void checkIsValidOpenCLKernelParameter(
Sema &S,
Declarator &D,
ParmVarDecl *Param,
llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
QualType PT = Param->getType();
if (ValidTypes.count(PT.getTypePtr()))
return;
switch (getOpenCLKernelParameterType(S, PT)) {
case PtrPtrKernelParam:
if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
D.setInvalidType();
return;
}
ValidTypes.insert(PT.getTypePtr());
return;
case InvalidAddrSpacePtrKernelParam:
S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
D.setInvalidType();
return;
case InvalidKernelParam:
if (!PT->isHalfType()) {
S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
const TypedefType *Typedef = nullptr;
while ((Typedef = PT->getAs<TypedefType>())) {
SourceLocation Loc = Typedef->getDecl()->getLocation();
if (Loc.isValid())
S.Diag(Loc, diag::note_entity_declared_at) << PT;
PT = Typedef->desugar();
}
}
D.setInvalidType();
return;
case PtrKernelParam:
case ValidKernelParam:
ValidTypes.insert(PT.getTypePtr());
return;
case RecordKernelParam:
break;
}
SmallVector<const Decl *, 4> VisitStack;
SmallVector<const FieldDecl *, 4> HistoryStack;
HistoryStack.push_back(nullptr);
assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
const RecordType *RecTy =
PT->getPointeeOrArrayElementType()->getAs<RecordType>();
const RecordDecl *OrigRecDecl = RecTy->getDecl();
VisitStack.push_back(RecTy->getDecl());
assert(VisitStack.back() && "First decl null?");
do {
const Decl *Next = VisitStack.pop_back_val();
if (!Next) {
assert(!HistoryStack.empty());
if (const FieldDecl *Hist = HistoryStack.pop_back_val())
ValidTypes.insert(Hist->getType().getTypePtr());
continue;
}
const RecordDecl *RD;
if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
HistoryStack.push_back(Field);
QualType FieldTy = Field->getType();
assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.");
const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
RD = FieldRecTy->castAs<RecordType>()->getDecl();
} else {
RD = cast<RecordDecl>(Next);
}
VisitStack.push_back(nullptr);
for (const auto *FD : RD->fields()) {
QualType QT = FD->getType();
if (ValidTypes.count(QT.getTypePtr()))
continue;
OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
if (ParamType == ValidKernelParam)
continue;
if (ParamType == RecordKernelParam) {
VisitStack.push_back(FD);
continue;
}
if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
ParamType == InvalidAddrSpacePtrKernelParam) {
S.Diag(Param->getLocation(),
diag::err_record_with_pointers_kernel_param)
<< PT->isUnionType()
<< PT;
} else {
S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
}
S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
<< OrigRecDecl->getDeclName();
for (ArrayRef<const FieldDecl *>::const_iterator
I = HistoryStack.begin() + 1,
E = HistoryStack.end();
I != E; ++I) {
const FieldDecl *OuterField = *I;
S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
<< OuterField->getType();
}
S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
<< QT->isPointerType()
<< QT;
D.setInvalidType();
return;
}
} while (!VisitStack.empty());
}
static DeclContext *getTagInjectionContext(DeclContext *DC) {
while (!DC->isFileContext() && !DC->isFunctionOrMethod())
DC = DC->getParent();
return DC;
}
static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
while (S->isClassScope() ||
(LangOpts.CPlusPlus &&
S->isFunctionPrototypeScope()) ||
((S->getFlags() & Scope::DeclScope) == 0) ||
(S->getEntity() && S->getEntity()->isTransparentContext()))
S = S->getParent();
return S;
}
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
unsigned BuiltinID) {
switch (BuiltinID) {
case Builtin::BI__GetExceptionInfo:
return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
case Builtin::BIaddressof:
case Builtin::BI__addressof:
case Builtin::BIforward:
case Builtin::BImove:
case Builtin::BImove_if_noexcept:
case Builtin::BIas_const: {
const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
return FPT->getNumParams() == 1 && !FPT->isVariadic();
}
default:
return false;
}
}
NamedDecl*
Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo, LookupResult &Previous,
MultiTemplateParamsArg TemplateParamListsRef,
bool &AddToScope) {
QualType R = TInfo->getType();
assert(R->isFunctionType());
if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
SmallVector<TemplateParameterList *, 4> TemplateParamLists;
llvm::append_range(TemplateParamLists, TemplateParamListsRef);
if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
if (!TemplateParamLists.empty() &&
Invented->getDepth() == TemplateParamLists.back()->getDepth())
TemplateParamLists.back() = Invented;
else
TemplateParamLists.push_back(Invented);
}
DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
DeclarationName Name = NameInfo.getName();
StorageClass SC = getFunctionStorageClass(*this, D);
if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_invalid_thread)
<< DeclSpec::getSpecifierName(TSCS);
if (D.isFirstDeclarationOfMember())
adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
D.getIdentifierLoc());
bool isFriend = false;
FunctionTemplateDecl *FunctionTemplate = nullptr;
bool isMemberSpecialization = false;
bool isFunctionTemplateSpecialization = false;
bool isDependentClassScopeExplicitSpecialization = false;
bool HasExplicitTemplateArgs = false;
TemplateArgumentListInfo TemplateArgs;
bool isVirtualOkay = false;
DeclContext *OriginalDC = DC;
bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
isVirtualOkay);
if (!NewFD) return nullptr;
if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
NewFD->setTopLevelDeclInObjCContainer();
NewFD->setLexicalDeclContext(CurContext);
if (IsLocalExternDecl)
NewFD->setLocalExternDecl();
if (getLangOpts().CPlusPlus) {
bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
!NewFD->getOwningModule() ||
NewFD->getOwningModule()->isGlobalModule() ||
NewFD->getOwningModule()->isModuleMapModule();
bool isInline = D.getDeclSpec().isInlineSpecified();
bool isVirtual = D.getDeclSpec().isVirtualSpecified();
bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
isFriend = D.getDeclSpec().isFriendSpecified();
if (isFriend && !isInline && D.isFunctionDefinition()) {
NewFD->setImplicitlyInline(ImplicitInlineCXX20);
}
if (const CXXRecordDecl *Parent =
dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
NewFD->setPure(true);
if (isVirtual && Parent->isUnion()) {
Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
NewFD->setInvalidDecl();
}
if ((Parent->isClass() || Parent->isStruct()) &&
Parent->hasAttr<SYCLSpecialClassAttr>() &&
NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
NewFD->getName() == "__init" && D.isFunctionDefinition()) {
if (auto *Def = Parent->getDefinition())
Def->setInitMethod(true);
}
}
SetNestedNameSpecifier(*this, NewFD, D);
isMemberSpecialization = false;
isFunctionTemplateSpecialization = false;
if (D.isInvalidType())
NewFD->setInvalidDecl();
bool Invalid = false;
TemplateParameterList *TemplateParams =
MatchTemplateParametersToScopeSpecifier(
D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
D.getCXXScopeSpec(),
D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
? D.getName().TemplateId
: nullptr,
TemplateParamLists, isFriend, isMemberSpecialization,
Invalid);
if (TemplateParams) {
if (CheckTemplateDeclScope(S, TemplateParams))
NewFD->setInvalidDecl();
if (TemplateParams->size() > 0) {
if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Diag(NewFD->getLocation(), diag::err_destructor_template);
NewFD->setInvalidDecl();
}
if (DC->isDependentContext()) {
ContextRAII SavedContext(*this, DC);
if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
Invalid = true;
}
FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
NewFD->getLocation(),
Name, TemplateParams,
NewFD);
FunctionTemplate->setLexicalDeclContext(CurContext);
NewFD->setDescribedFunctionTemplate(FunctionTemplate);
if (TemplateParamLists.size() > 1) {
NewFD->setTemplateParameterListsInfo(Context,
ArrayRef<TemplateParameterList *>(TemplateParamLists)
.drop_back(1));
}
} else {
isFunctionTemplateSpecialization = true;
if (TemplateParamLists.size() > 0)
NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
if (isFriend) {
SourceRange RemoveRange = TemplateParams->getSourceRange();
SourceLocation InsertLoc;
if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
InsertLoc = D.getName().getSourceRange().getEnd();
InsertLoc = getLocForEndOfToken(InsertLoc);
}
Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
<< Name << RemoveRange
<< FixItHint::CreateRemoval(RemoveRange)
<< FixItHint::CreateInsertion(InsertLoc, "<>");
Invalid = true;
}
}
} else {
if (!TemplateParamLists.empty() && isMemberSpecialization &&
CheckTemplateDeclScope(S, TemplateParamLists.back()))
NewFD->setInvalidDecl();
if (TemplateParamLists.size() > 0)
NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
}
if (Invalid) {
NewFD->setInvalidDecl();
if (FunctionTemplate)
FunctionTemplate->setInvalidDecl();
}
if (isVirtual && !NewFD->isInvalidDecl()) {
if (!isVirtualOkay) {
Diag(D.getDeclSpec().getVirtualSpecLoc(),
diag::err_virtual_non_function);
} else if (!CurContext->isRecord()) {
Diag(D.getDeclSpec().getVirtualSpecLoc(),
diag::err_virtual_out_of_class)
<< FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
} else if (NewFD->getDescribedFunctionTemplate()) {
Diag(D.getDeclSpec().getVirtualSpecLoc(),
diag::err_virtual_member_function_template)
<< FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
} else {
NewFD->setVirtualAsWritten(true);
}
if (getLangOpts().CPlusPlus14 &&
NewFD->getReturnType()->isUndeducedType())
Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
}
if (getLangOpts().CPlusPlus14 &&
(NewFD->isDependentContext() ||
(isFriend && CurContext->isDependentContext())) &&
NewFD->getReturnType()->isUndeducedType()) {
const FunctionProtoType *FPT =
NewFD->getType()->castAs<FunctionProtoType>();
QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
FPT->getExtProtoInfo()));
}
if (isInline && !NewFD->isInvalidDecl()) {
if (CurContext->isFunctionOrMethod()) {
Diag(D.getDeclSpec().getInlineSpecLoc(),
diag::err_inline_declaration_block_scope) << Name
<< FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
}
}
if (hasExplicit && !NewFD->isInvalidDecl() &&
!isa<CXXDeductionGuideDecl>(NewFD)) {
if (!CurContext->isRecord()) {
Diag(D.getDeclSpec().getExplicitSpecLoc(),
diag::err_explicit_out_of_class)
<< FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
} else if (!isa<CXXConstructorDecl>(NewFD) &&
!isa<CXXConversionDecl>(NewFD)) {
Diag(D.getDeclSpec().getExplicitSpecLoc(),
diag::err_explicit_non_ctor_or_conv_function)
<< FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
}
}
ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
if (ConstexprKind != ConstexprSpecKind::Unspecified) {
NewFD->setImplicitlyInline();
if (isa<CXXDestructorDecl>(NewFD) &&
(!getLangOpts().CPlusPlus20 ||
ConstexprKind == ConstexprSpecKind::Consteval)) {
Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
<< static_cast<int>(ConstexprKind);
NewFD->setConstexprKind(getLangOpts().CPlusPlus20
? ConstexprSpecKind::Unspecified
: ConstexprSpecKind::Constexpr);
}
if (ConstexprKind == ConstexprSpecKind::Consteval &&
(NewFD->getOverloadedOperator() == OO_New ||
NewFD->getOverloadedOperator() == OO_Array_New ||
NewFD->getOverloadedOperator() == OO_Delete ||
NewFD->getOverloadedOperator() == OO_Array_Delete)) {
Diag(D.getDeclSpec().getConstexprSpecLoc(),
diag::err_invalid_consteval_decl_kind)
<< NewFD;
NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
}
}
if (D.getDeclSpec().isModulePrivateSpecified()) {
if (isFunctionTemplateSpecialization) {
SourceLocation ModulePrivateLoc
= D.getDeclSpec().getModulePrivateSpecLoc();
Diag(ModulePrivateLoc, diag::err_module_private_specialization)
<< 0
<< FixItHint::CreateRemoval(ModulePrivateLoc);
} else {
NewFD->setModulePrivate();
if (FunctionTemplate)
FunctionTemplate->setModulePrivate();
}
}
if (isFriend) {
if (FunctionTemplate) {
FunctionTemplate->setObjectOfFriendDecl();
FunctionTemplate->setAccess(AS_public);
}
NewFD->setObjectOfFriendDecl();
NewFD->setAccess(AS_public);
}
switch (D.getFunctionDefinitionKind()) {
case FunctionDefinitionKind::Declaration:
case FunctionDefinitionKind::Definition:
break;
case FunctionDefinitionKind::Defaulted:
NewFD->setDefaulted();
break;
case FunctionDefinitionKind::Deleted:
NewFD->setDeletedAsWritten();
break;
}
if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
D.isFunctionDefinition() && !isInline) {
NewFD->setImplicitlyInline(ImplicitInlineCXX20);
}
if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
!CurContext->isRecord()) {
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
(getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
? diag::ext_static_out_of_line : diag::err_static_out_of_line)
<< FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
}
const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
if ((Name.getCXXOverloadedOperator() == OO_Delete ||
Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
NewFD->setType(Context.getFunctionType(
FPT->getReturnType(), FPT->getParamTypes(),
FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
}
FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
D.getCXXScopeSpec().isNotEmpty() ||
isMemberSpecialization ||
isFunctionTemplateSpecialization);
if (Expr *E = (Expr*) D.getAsmLabel()) {
StringLiteral *SE = cast<StringLiteral>(E);
NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
true,
SE->getStrTokenLoc(0)));
} else if (!ExtnameUndeclaredIdentifiers.empty()) {
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
if (I != ExtnameUndeclaredIdentifiers.end()) {
if (isDeclExternC(NewFD)) {
NewFD->addAttr(I->second);
ExtnameUndeclaredIdentifiers.erase(I);
} else
Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
<< 0 << NewFD;
}
}
SmallVector<ParmVarDecl*, 16> Params;
unsigned FTIIdx;
if (D.isFunctionDeclarator(FTIIdx)) {
DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
assert(Param->getDeclContext() != NewFD && "Was set before ?");
Param->setDeclContext(NewFD);
Params.push_back(Param);
if (Param->isInvalidDecl())
NewFD->setInvalidDecl();
}
}
if (!getLangOpts().CPlusPlus) {
DeclContext *PrototypeTagContext =
getTagInjectionContext(NewFD->getLexicalDeclContext());
for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
auto *TD = dyn_cast<TagDecl>(NonParmDecl);
if (!TD) {
if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
TD = cast<EnumDecl>(ECD->getDeclContext());
}
if (!TD)
continue;
DeclContext *TagDC = TD->getLexicalDeclContext();
if (!TagDC->containsDecl(TD))
continue;
TagDC->removeDecl(TD);
TD->setDeclContext(NewFD);
NewFD->addDecl(TD);
if (TagDC != PrototypeTagContext)
TD->setLexicalDeclContext(TagDC);
}
}
} else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
for (const auto &AI : FT->param_types()) {
ParmVarDecl *Param =
BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
Param->setScopeInfo(0, Params.size());
Params.push_back(Param);
}
} else {
assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
"Should not need args for typedef of non-prototype fn");
}
NewFD->setParams(Params);
if (D.getDeclSpec().isNoreturnSpecified())
NewFD->addAttr(C11NoReturnAttr::Create(Context,
D.getDeclSpec().getNoreturnSpecLoc(),
AttributeCommonInfo::AS_Keyword));
if (!NewFD->isInvalidDecl() &&
NewFD->getReturnType()->isVariablyModifiedType()) {
Diag(NewFD->getLocation(), diag::err_vm_func_decl);
NewFD->setInvalidDecl();
}
if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
!NewFD->hasAttr<SectionAttr>())
NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
Context, PragmaClangTextSection.SectionName,
PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
!NewFD->hasAttr<SectionAttr>()) {
NewFD->addAttr(SectionAttr::CreateImplicit(
Context, CodeSegStack.CurrentValue->getString(),
CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
SectionAttr::Declspec_allocate));
if (UnifySection(CodeSegStack.CurrentValue->getString(),
ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
ASTContext::PSF_Read,
NewFD))
NewFD->dropAttr<SectionAttr>();
}
if (!NewFD->hasAttr<CodeSegAttr>()) {
if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
D.isFunctionDefinition())) {
NewFD->addAttr(SAttr);
}
}
ProcessDeclAttributes(S, NewFD, D);
if (getLangOpts().OpenCL) {
LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
if (AddressSpace != LangAS::Default) {
Diag(NewFD->getLocation(),
diag::err_opencl_return_value_with_address_space);
NewFD->setInvalidDecl();
}
}
if (!getLangOpts().CPlusPlus) {
if (!NewFD->isInvalidDecl() && NewFD->isMain())
CheckMain(NewFD, D.getDeclSpec());
if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
CheckMSVCRTEntryPoint(NewFD);
if (!NewFD->isInvalidDecl())
D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
isMemberSpecialization,
D.isFunctionDefinition()));
else if (!Previous.empty())
D.setRedeclaration(true);
assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Previous.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded");
const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
CallingConv CC = FT->getExtInfo().getCC();
if (!supportsVariadicCall(CC)) {
int DiagID =
CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
Diag(NewFD->getLocation(), DiagID)
<< FunctionType::getNameForCallConv(CC);
}
}
if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
checkNonTrivialCUnion(NewFD->getReturnType(),
NewFD->getReturnTypeSourceRange().getBegin(),
NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
} else {
if (D.getDeclSpec().isInlineSpecified() &&
NewFD->isReplaceableGlobalAllocationFunction() &&
!NewFD->hasAttr<UsedAttr>())
Diag(D.getDeclSpec().getInlineSpecLoc(),
diag::ext_operator_new_delete_declared_inline)
<< NewFD->getDeclName();
if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
TemplateId->NumArgs);
translateTemplateArguments(TemplateArgsPtr,
TemplateArgs);
HasExplicitTemplateArgs = true;
if (NewFD->isInvalidDecl()) {
HasExplicitTemplateArgs = false;
} else if (FunctionTemplate) {
Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
<< SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
HasExplicitTemplateArgs = false;
} else {
assert((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) &&
"should have a 'template<>' for this decl");
isFunctionTemplateSpecialization = true;
}
} else if (isFriend && isFunctionTemplateSpecialization) {
HasExplicitTemplateArgs = true;
TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
}
if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
if (isFunctionTemplateSpecialization && isFriend &&
(NewFD->getType()->isDependentType() || DC->isDependentContext() ||
TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
TemplateArgs.arguments()))) {
assert(HasExplicitTemplateArgs &&
"friend function specialization without template args");
if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
Previous))
NewFD->setInvalidDecl();
} else if (isFunctionTemplateSpecialization) {
if (CurContext->isDependentContext() && CurContext->isRecord()
&& !isFriend) {
isDependentClassScopeExplicitSpecialization = true;
} else if (!NewFD->isInvalidDecl() &&
CheckFunctionTemplateSpecialization(
NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
Previous))
NewFD->setInvalidDecl();
FunctionTemplateSpecializationInfo *Info =
NewFD->getTemplateSpecializationInfo();
if (Info && SC != SC_None) {
if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
Diag(NewFD->getLocation(),
diag::err_explicit_specialization_inconsistent_storage_class)
<< SC
<< FixItHint::CreateRemoval(
D.getDeclSpec().getStorageClassSpecLoc());
else
Diag(NewFD->getLocation(),
diag::ext_explicit_specialization_storage_class)
<< FixItHint::CreateRemoval(
D.getDeclSpec().getStorageClassSpecLoc());
}
} else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
if (CheckMemberSpecialization(NewFD, Previous))
NewFD->setInvalidDecl();
}
if (!isDependentClassScopeExplicitSpecialization) {
if (!NewFD->isInvalidDecl() && NewFD->isMain())
CheckMain(NewFD, D.getDeclSpec());
if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
CheckMSVCRTEntryPoint(NewFD);
if (!NewFD->isInvalidDecl())
D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
isMemberSpecialization,
D.isFunctionDefinition()));
else if (!Previous.empty())
D.setRedeclaration(true);
}
assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
Previous.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded");
NamedDecl *PrincipalDecl = (FunctionTemplate
? cast<NamedDecl>(FunctionTemplate)
: NewFD);
if (isFriend && NewFD->getPreviousDecl()) {
AccessSpecifier Access = AS_public;
if (!NewFD->isInvalidDecl())
Access = NewFD->getPreviousDecl()->getAccess();
NewFD->setAccess(Access);
if (FunctionTemplate) FunctionTemplate->setAccess(Access);
}
if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
PrincipalDecl->setNonMemberOperator();
if (FunctionTemplate) {
FunctionTemplateDecl *PrevTemplate =
FunctionTemplate->getPreviousDecl();
CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
PrevTemplate ? PrevTemplate->getTemplateParameters()
: nullptr,
D.getDeclSpec().isFriendSpecified()
? (D.isFunctionDefinition()
? TPC_FriendFunctionTemplateDefinition
: TPC_FriendFunctionTemplate)
: (D.getCXXScopeSpec().isSet() &&
DC && DC->isRecord() &&
DC->isDependentContext())
? TPC_ClassTemplateMember
: TPC_FunctionTemplate);
}
if (NewFD->isInvalidDecl()) {
} else if (!D.isRedeclaration()) {
struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
AddToScope };
if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
NewFD->setAccess(AS_public);
if (D.getCXXScopeSpec().isSet()) {
if (isFriend &&
(D.getCXXScopeSpec().getScopeRep()->isDependent() ||
(!Previous.empty() && CurContext->isDependentContext()))) {
} else if (NewFD->isCPUDispatchMultiVersion() ||
NewFD->isCPUSpecificMultiVersion()) {
} else {
if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
*this, Previous, NewFD, ExtraArgs, false, nullptr)) {
AddToScope = ExtraArgs.AddToScope;
return Result;
}
}
} else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
*this, Previous, NewFD, ExtraArgs, true, S)) {
AddToScope = ExtraArgs.AddToScope;
return Result;
}
}
} else if (!D.isFunctionDefinition() &&
isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
!isFriend && !isFunctionTemplateSpecialization &&
!isMemberSpecialization) {
Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
<< D.getCXXScopeSpec().getRange();
}
}
if (!D.isRedeclaration()) {
if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
if (unsigned BuiltinID = II->getBuiltinID()) {
bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
if (!InStdNamespace &&
NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
} else {
ASTContext::GetBuiltinTypeError Error;
LookupNecessaryTypesForBuiltin(S, BuiltinID);
QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
if (!Error && !BuiltinType.isNull() &&
Context.hasSameFunctionTypeIgnoringExceptionSpec(
NewFD->getType(), BuiltinType))
NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
}
}
} else if (InStdNamespace && NewFD->isInStdNamespace() &&
isStdBuiltin(Context, NewFD, BuiltinID)) {
NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
}
}
}
}
ProcessPragmaWeak(S, NewFD);
checkAttributesAfterMerging(*this, *NewFD);
AddKnownFunctionAttributes(NewFD);
if (NewFD->hasAttr<OverloadableAttr>() &&
!NewFD->getType()->getAs<FunctionProtoType>()) {
Diag(NewFD->getLocation(),
diag::err_attribute_overloadable_no_prototype)
<< NewFD;
const auto *FT = NewFD->getType()->castAs<FunctionType>();
FunctionProtoType::ExtProtoInfo EPI(
Context.getDefaultCallingConvention(true, false));
EPI.Variadic = true;
EPI.ExtInfo = FT->getExtInfo();
QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
NewFD->setType(R);
}
if (!DC->isRecord() && NewFD->isExternallyVisible())
AddPushedVisibilityAttribute(NewFD);
AddCFAuditedAttribute(NewFD);
if (D.isFunctionDefinition()) {
AddRangeBasedOptnone(NewFD);
AddImplicitMSFunctionNoBuiltinAttr(NewFD);
AddSectionMSAllocText(NewFD);
ModifyFnAttributesMSPragmaOptimize(NewFD);
}
if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
isIncompleteDeclExternC(*this, NewFD))
RegisterLocallyScopedExternCDecl(NewFD, S);
NewFD->setRangeEnd(D.getSourceRange().getEnd());
if (D.isRedeclaration() && !Previous.empty()) {
NamedDecl *Prev = Previous.getRepresentativeDecl();
checkDLLAttributeRedeclaration(*this, Prev, NewFD,
isMemberSpecialization ||
isFunctionTemplateSpecialization,
D.isFunctionDefinition());
}
if (getLangOpts().CUDA) {
IdentifierInfo *II = NewFD->getIdentifier();
if (II && II->isStr(getCudaConfigureFuncName()) &&
!NewFD->isInvalidDecl() &&
NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
Diag(NewFD->getLocation(), diag::err_config_scalar_return)
<< getCudaConfigureFuncName();
Context.setcudaConfigureCallDecl(NewFD);
}
if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
(NewFD->hasAttr<CUDADeviceAttr>() ||
NewFD->hasAttr<CUDAGlobalAttr>()) &&
!(II && II->isStr("printf") && NewFD->isExternC() &&
!D.isFunctionDefinition())) {
Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
}
}
MarkUnusedFileScopedDecl(NewFD);
if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
if (SC == SC_Static) {
Diag(D.getIdentifierLoc(), diag::err_static_kernel);
D.setInvalidType();
}
if (!NewFD->getReturnType()->isVoidType()) {
SourceRange RTRange = NewFD->getReturnTypeSourceRange();
Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
<< (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
: FixItHint());
D.setInvalidType();
}
llvm::SmallPtrSet<const Type *, 16> ValidTypes;
for (auto Param : NewFD->parameters())
checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
if (getLangOpts().OpenCLCPlusPlus) {
if (DC->isRecord()) {
Diag(D.getIdentifierLoc(), diag::err_method_kernel);
D.setInvalidType();
}
if (FunctionTemplate) {
Diag(D.getIdentifierLoc(), diag::err_template_kernel);
D.setInvalidType();
}
}
}
if (getLangOpts().CPlusPlus) {
if (FunctionTemplate) {
if (NewFD->isInvalidDecl())
FunctionTemplate->setInvalidDecl();
return FunctionTemplate;
}
if (isMemberSpecialization && !NewFD->isInvalidDecl())
CompleteMemberSpecialization(NewFD, Previous);
}
for (const ParmVarDecl *Param : NewFD->parameters()) {
QualType PT = Param->getType();
if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
QualType ElemTy = PipeTy->getElementType();
if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
D.setInvalidType();
}
}
}
}
if (isDependentClassScopeExplicitSpecialization) {
ClassScopeFunctionSpecializationDecl *NewSpec =
ClassScopeFunctionSpecializationDecl::Create(
Context, CurContext, NewFD->getLocation(),
cast<CXXMethodDecl>(NewFD),
HasExplicitTemplateArgs, TemplateArgs);
CurContext->addDecl(NewSpec);
AddToScope = false;
}
if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
if (NewFD->hasAttr<ConstructorAttr>()) {
Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
<< 1;
NewFD->dropAttr<AvailabilityAttr>();
}
if (NewFD->hasAttr<DestructorAttr>()) {
Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
<< 2;
NewFD->dropAttr<AvailabilityAttr>();
}
}
if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
switch (D.getFunctionDefinitionKind()) {
case FunctionDefinitionKind::Defaulted:
case FunctionDefinitionKind::Deleted:
Diag(NBA->getLocation(),
diag::err_attribute_no_builtin_on_defaulted_deleted_function)
<< NBA->getSpelling();
break;
case FunctionDefinitionKind::Declaration:
Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
<< NBA->getSpelling();
break;
case FunctionDefinitionKind::Definition:
break;
}
return NewFD;
}
static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
const auto *Method = dyn_cast<CXXMethodDecl>(FD);
if (!Method)
return nullptr;
const CXXRecordDecl *Parent = Method->getParent();
if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
Attr *NewAttr = SAttr->clone(S.getASTContext());
NewAttr->setImplicit(true);
return NewAttr;
}
if (S.CodeSegStack.CurrentValue)
return nullptr;
while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
Attr *NewAttr = SAttr->clone(S.getASTContext());
NewAttr->setImplicit(true);
return NewAttr;
}
}
return nullptr;
}
Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition) {
if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
return A;
if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
CodeSegStack.CurrentValue)
return SectionAttr::CreateImplicit(
getASTContext(), CodeSegStack.CurrentValue->getString(),
CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
SectionAttr::Declspec_allocate);
return nullptr;
}
bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT) {
if (!NewD->getLexicalDeclContext()->isDependentContext())
return true;
if (NewT->isDependentType() &&
(NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
return false;
if (OldT->isDependentType() && OldD->isLocalExternDecl())
return false;
return true;
}
bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
if (!D->getLexicalDeclContext()->isDependentContext())
return true;
if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
return false;
auto *VD = dyn_cast<ValueDecl>(D);
auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
return !VD || !PrevVD ||
canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
PrevVD->getType());
}
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
const auto *TA = FD->getAttr<TargetAttr>();
assert(TA && "MultiVersion Candidate requires a target attribute");
ParsedTargetAttr ParseInfo = TA->parse();
const TargetInfo &TargetInfo = S.Context.getTargetInfo();
enum ErrType { Feature = 0, Architecture = 1 };
if (!ParseInfo.Architecture.empty() &&
!TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
<< Architecture << ParseInfo.Architecture;
return true;
}
for (const auto &Feat : ParseInfo.Features) {
auto BareFeat = StringRef{Feat}.substr(1);
if (Feat[0] == '-') {
S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
<< Feature << ("no-" + BareFeat).str();
return true;
}
if (!TargetInfo.validateCpuSupports(BareFeat) ||
!TargetInfo.isValidFeatureName(BareFeat)) {
S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
<< Feature << BareFeat;
return true;
}
}
return false;
}
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
MultiVersionKind MVKind) {
switch (Kind) {
default:
return false;
case attr::Used:
return MVKind == MultiVersionKind::Target;
case attr::NonNull:
case attr::NoThrow:
return true;
}
}
static bool checkNonMultiVersionCompatAttributes(Sema &S,
const FunctionDecl *FD,
const FunctionDecl *CausedFD,
MultiVersionKind MVKind) {
const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
<< static_cast<unsigned>(MVKind) << A;
if (CausedFD)
S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
return true;
};
for (const Attr *A : FD->attrs()) {
switch (A->getKind()) {
case attr::CPUDispatch:
case attr::CPUSpecific:
if (MVKind != MultiVersionKind::CPUDispatch &&
MVKind != MultiVersionKind::CPUSpecific)
return Diagnose(S, A);
break;
case attr::Target:
if (MVKind != MultiVersionKind::Target)
return Diagnose(S, A);
break;
case attr::TargetClones:
if (MVKind != MultiVersionKind::TargetClones)
return Diagnose(S, A);
break;
default:
if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
return Diagnose(S, A);
break;
}
}
return false;
}
bool Sema::areMultiversionVariantFunctionsCompatible(
const FunctionDecl *OldFD, const FunctionDecl *NewFD,
const PartialDiagnostic &NoProtoDiagID,
const PartialDiagnosticAt &NoteCausedDiagIDAt,
const PartialDiagnosticAt &NoSupportDiagIDAt,
const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
bool ConstexprSupported, bool CLinkageMayDiffer) {
enum DoesntSupport {
FuncTemplates = 0,
VirtFuncs = 1,
DeducedReturn = 2,
Constructors = 3,
Destructors = 4,
DeletedFuncs = 5,
DefaultedFuncs = 6,
ConstexprFuncs = 7,
ConstevalFuncs = 8,
Lambda = 9,
};
enum Different {
CallingConv = 0,
ReturnType = 1,
ConstexprSpec = 2,
InlineSpec = 3,
Linkage = 4,
LanguageLinkage = 5,
};
if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
!OldFD->getType()->getAs<FunctionProtoType>()) {
Diag(OldFD->getLocation(), NoProtoDiagID);
Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
return true;
}
if (NoProtoDiagID.getDiagID() != 0 &&
!NewFD->getType()->getAs<FunctionProtoType>())
return Diag(NewFD->getLocation(), NoProtoDiagID);
if (!TemplatesSupported &&
NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< FuncTemplates;
if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
if (NewCXXFD->isVirtual())
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< VirtFuncs;
if (isa<CXXConstructorDecl>(NewCXXFD))
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< Constructors;
if (isa<CXXDestructorDecl>(NewCXXFD))
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< Destructors;
}
if (NewFD->isDeleted())
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< DeletedFuncs;
if (NewFD->isDefaulted())
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< DefaultedFuncs;
if (!ConstexprSupported && NewFD->isConstexpr())
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
QualType NewQType = Context.getCanonicalType(NewFD->getType());
const auto *NewType = cast<FunctionType>(NewQType);
QualType NewReturnType = NewType->getReturnType();
if (NewReturnType->isUndeducedType())
return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
<< DeducedReturn;
if (OldFD) {
QualType OldQType = Context.getCanonicalType(OldFD->getType());
const auto *OldType = cast<FunctionType>(OldQType);
FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
QualType OldReturnType = OldType->getReturnType();
if (OldReturnType != NewReturnType)
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
if (CheckEquivalentExceptionSpec(
OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
return true;
}
return false;
}
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
const FunctionDecl *NewFD,
bool CausesMV,
MultiVersionKind MVKind) {
if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
if (OldFD)
S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
return true;
}
bool IsCPUSpecificCPUDispatchMVKind =
MVKind == MultiVersionKind::CPUDispatch ||
MVKind == MultiVersionKind::CPUSpecific;
if (CausesMV && OldFD &&
checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
return true;
if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
return true;
if (OldFD && CausesMV && OldFD->isUsed(false))
return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
return S.areMultiversionVariantFunctionsCompatible(
OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
PartialDiagnosticAt(NewFD->getLocation(),
S.PDiag(diag::note_multiversioning_caused_here)),
PartialDiagnosticAt(NewFD->getLocation(),
S.PDiag(diag::err_multiversion_doesnt_support)
<< static_cast<unsigned>(MVKind)),
PartialDiagnosticAt(NewFD->getLocation(),
S.PDiag(diag::err_multiversion_diff)),
false,
!IsCPUSpecificCPUDispatchMVKind,
false);
}
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
MultiVersionKind MVKind,
const TargetAttr *TA) {
assert(MVKind != MultiVersionKind::None &&
"Function lacks multiversion attribute");
if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
return false;
if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
FD->setInvalidDecl();
return true;
}
if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
FD->setInvalidDecl();
return true;
}
FD->setIsMultiVersion();
return false;
}
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
return true;
}
return false;
}
static bool CheckTargetCausesMultiVersioning(
Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
const auto *OldTA = OldFD->getAttr<TargetAttr>();
ParsedTargetAttr NewParsed = NewTA->parse();
llvm::sort(NewParsed.Features);
if (!NewTA->isDefaultVersion() &&
(!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
return false;
if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
MultiVersionKind::Target)) {
NewFD->setInvalidDecl();
return true;
}
if (CheckMultiVersionValue(S, NewFD)) {
NewFD->setInvalidDecl();
return true;
}
if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
Redeclaration = true;
OldDecl = OldFD;
OldFD->setIsMultiVersion();
NewFD->setIsMultiVersion();
return false;
}
if (CheckMultiVersionValue(S, OldFD)) {
S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
NewFD->setInvalidDecl();
return true;
}
ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
if (OldParsed == NewParsed) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
for (const auto *FD : OldFD->redecls()) {
const auto *CurTA = FD->getAttr<TargetAttr>();
if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
(!CurTA || CurTA->isInherited())) {
S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
<< 0;
S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
NewFD->setInvalidDecl();
return true;
}
}
OldFD->setIsMultiVersion();
NewFD->setIsMultiVersion();
Redeclaration = false;
OldDecl = nullptr;
Previous.clear();
return false;
}
static bool MultiVersionTypesCompatible(MultiVersionKind Old,
MultiVersionKind New) {
if (Old == New || Old == MultiVersionKind::None ||
New == MultiVersionKind::None)
return true;
return (Old == MultiVersionKind::CPUDispatch &&
New == MultiVersionKind::CPUSpecific) ||
(Old == MultiVersionKind::CPUSpecific &&
New == MultiVersionKind::CPUDispatch);
}
static bool CheckMultiVersionAdditionalDecl(
Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
MultiVersionKind NewMVKind, const TargetAttr *NewTA,
const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
LookupResult &Previous) {
MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
ParsedTargetAttr NewParsed;
if (NewTA) {
NewParsed = NewTA->parse();
llvm::sort(NewParsed.Features);
}
bool UseMemberUsingDeclRules =
S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
bool MayNeedOverloadableChecks =
AllowOverloadingOfFunction(Previous, S.Context, NewFD);
for (NamedDecl *ND : Previous) {
FunctionDecl *CurFD = ND->getAsFunction();
if (!CurFD)
continue;
if (MayNeedOverloadableChecks &&
S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
continue;
switch (NewMVKind) {
case MultiVersionKind::None:
assert(OldMVKind == MultiVersionKind::TargetClones &&
"Only target_clones can be omitted in subsequent declarations");
break;
case MultiVersionKind::Target: {
const auto *CurTA = CurFD->getAttr<TargetAttr>();
if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
NewFD->setIsMultiVersion();
Redeclaration = true;
OldDecl = ND;
return false;
}
ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
if (CurParsed == NewParsed) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
break;
}
case MultiVersionKind::TargetClones: {
const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
Redeclaration = true;
OldDecl = CurFD;
NewFD->setIsMultiVersion();
if (CurClones && NewClones &&
(CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
!std::equal(CurClones->featuresStrs_begin(),
CurClones->featuresStrs_end(),
NewClones->featuresStrs_begin()))) {
S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
return false;
}
case MultiVersionKind::CPUSpecific:
case MultiVersionKind::CPUDispatch: {
const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
if (NewMVKind == MultiVersionKind::CPUDispatch &&
CurFD->hasAttr<CPUDispatchAttr>()) {
if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
std::equal(
CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
NewCPUDisp->cpus_begin(),
[](const IdentifierInfo *Cur, const IdentifierInfo *New) {
return Cur->getName() == New->getName();
})) {
NewFD->setIsMultiVersion();
Redeclaration = true;
OldDecl = ND;
return false;
}
S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
std::equal(
CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
NewCPUSpec->cpus_begin(),
[](const IdentifierInfo *Cur, const IdentifierInfo *New) {
return Cur->getName() == New->getName();
})) {
NewFD->setIsMultiVersion();
Redeclaration = true;
OldDecl = ND;
return false;
}
for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
if (CurII == NewII) {
S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
<< NewII;
S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
return true;
}
}
}
}
break;
}
}
}
if (NewMVKind == MultiVersionKind::Target &&
CheckMultiVersionValue(S, NewFD)) {
NewFD->setInvalidDecl();
return true;
}
if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
!OldFD->isMultiVersion(), NewMVKind)) {
NewFD->setInvalidDecl();
return true;
}
if (!OldFD->isMultiVersion()) {
OldFD->setIsMultiVersion();
NewFD->setIsMultiVersion();
Redeclaration = true;
OldDecl = OldFD;
return false;
}
NewFD->setIsMultiVersion();
Redeclaration = false;
OldDecl = nullptr;
Previous.clear();
return false;
}
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
bool &Redeclaration, NamedDecl *&OldDecl,
LookupResult &Previous) {
const auto *NewTA = NewFD->getAttr<TargetAttr>();
const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
MultiVersionKind MVKind = NewFD->getMultiVersionKind();
if (NewFD->isMain()) {
if (MVKind != MultiVersionKind::None &&
!(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
NewFD->setInvalidDecl();
return true;
}
return false;
}
if (!OldDecl || !OldDecl->getAsFunction() ||
OldDecl->getDeclContext()->getRedeclContext() !=
NewFD->getDeclContext()->getRedeclContext()) {
if (MVKind == MultiVersionKind::None)
return false;
return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
}
FunctionDecl *OldFD = OldDecl->getAsFunction();
if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
return false;
if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
<< (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
NewFD->setInvalidDecl();
return true;
}
if (!OldFD->isMultiVersion()) {
switch (MVKind) {
case MultiVersionKind::Target:
return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
Redeclaration, OldDecl, Previous);
case MultiVersionKind::TargetClones:
if (OldFD->isUsed(false)) {
NewFD->setInvalidDecl();
return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
}
OldFD->setIsMultiVersion();
break;
case MultiVersionKind::CPUDispatch:
case MultiVersionKind::CPUSpecific:
case MultiVersionKind::None:
break;
}
}
return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
NewCPUDisp, NewCPUSpec, NewClones,
Redeclaration, OldDecl, Previous);
}
bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
LookupResult &Previous,
bool IsMemberSpecialization,
bool DeclIsDefn) {
assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here");
bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
!Previous.isShadowed();
bool Redeclaration = false;
NamedDecl *OldDecl = nullptr;
bool MayNeedOverloadableChecks = false;
if (!Previous.empty()) {
if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
NamedDecl *Candidate = Previous.getRepresentativeDecl();
if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
Redeclaration = true;
OldDecl = Candidate;
}
} else {
MayNeedOverloadableChecks = true;
switch (CheckOverload(S, NewFD, Previous, OldDecl,
false)) {
case Ovl_Match:
Redeclaration = true;
break;
case Ovl_NonFunction:
Redeclaration = true;
break;
case Ovl_Overload:
Redeclaration = false;
break;
}
}
}
if (!Redeclaration &&
checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
if (!Previous.empty()) {
Redeclaration = true;
OldDecl = Previous.getFoundDecl();
MergeTypeWithPrevious = false;
if (OldDecl->hasAttr<OverloadableAttr>() ||
NewFD->hasAttr<OverloadableAttr>()) {
if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
MayNeedOverloadableChecks = true;
Redeclaration = false;
OldDecl = nullptr;
}
}
}
}
if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
return Redeclaration;
if (Context.getTargetInfo().getTriple().isPPC64() &&
CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
NewFD->setInvalidDecl();
}
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
!MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
!isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
CXXMethodDecl *OldMD = nullptr;
if (OldDecl)
OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
if (!OldMD || !OldMD->isStatic()) {
const FunctionProtoType *FPT =
MD->getType()->castAs<FunctionProtoType>();
FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
EPI.TypeQuals.addConst();
MD->setType(Context.getFunctionType(FPT->getReturnType(),
FPT->getParamTypes(), EPI));
if (!inTemplateInstantiation()) {
SourceLocation AddConstLoc;
if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
.IgnoreParens().getAs<FunctionTypeLoc>())
AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
<< FixItHint::CreateInsertion(AddConstLoc, " const");
}
}
}
if (Redeclaration) {
if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
DeclIsDefn)) {
NewFD->setInvalidDecl();
return Redeclaration;
}
Previous.clear();
Previous.addDecl(OldDecl);
if (FunctionTemplateDecl *OldTemplateDecl =
dyn_cast<FunctionTemplateDecl>(OldDecl)) {
auto *OldFD = OldTemplateDecl->getTemplatedDecl();
FunctionTemplateDecl *NewTemplateDecl
= NewFD->getDescribedFunctionTemplate();
assert(NewTemplateDecl && "Template/non-template mismatch");
NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
NewFD->setPreviousDeclaration(OldFD);
if (NewFD->isCXXClassMember()) {
NewFD->setAccess(OldTemplateDecl->getAccess());
NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
}
if (IsMemberSpecialization &&
NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
NewTemplateDecl->setMemberSpecialization();
assert(OldTemplateDecl->isMemberSpecialization());
if (OldFD->isDeleted()) {
assert(OldFD->getCanonicalDecl() == OldFD);
OldFD->setDeletedAsWritten(false);
}
}
} else {
if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
auto *OldFD = cast<FunctionDecl>(OldDecl);
NewFD->setPreviousDeclaration(OldFD);
if (NewFD->isCXXClassMember())
NewFD->setAccess(OldFD->getAccess());
}
}
} else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
!NewFD->getAttr<OverloadableAttr>()) {
assert((Previous.empty() ||
llvm::any_of(Previous,
[](const NamedDecl *ND) {
return ND->hasAttr<OverloadableAttr>();
})) &&
"Non-redecls shouldn't happen without overloadable present");
auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
const auto *FD = dyn_cast<FunctionDecl>(ND);
return FD && !FD->hasAttr<OverloadableAttr>();
});
if (OtherUnmarkedIter != Previous.end()) {
Diag(NewFD->getLocation(),
diag::err_attribute_overloadable_multiple_unmarked_overloads);
Diag((*OtherUnmarkedIter)->getLocation(),
diag::note_attribute_overloadable_prev_overload)
<< false;
NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
}
}
if (LangOpts.OpenMP)
ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
if (getLangOpts().CPlusPlus) {
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
CheckConstructor(Constructor);
} else if (CXXDestructorDecl *Destructor =
dyn_cast<CXXDestructorDecl>(NewFD)) {
CXXRecordDecl *Record = Destructor->getParent();
QualType ClassType = Context.getTypeDeclType(Record);
if (!ClassType->isDependentType()) {
DeclarationName Name
= Context.DeclarationNames.getCXXDestructorName(
Context.getCanonicalType(ClassType));
if (NewFD->getDeclName() != Name) {
Diag(NewFD->getLocation(), diag::err_destructor_name);
NewFD->setInvalidDecl();
return Redeclaration;
}
}
} else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
if (auto *TD = Guide->getDescribedFunctionTemplate())
CheckDeductionGuideTemplate(TD);
if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
<< 1;
}
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
if (!Method->isFunctionTemplateSpecialization() &&
!Method->getDescribedFunctionTemplate() &&
Method->isCanonicalDecl()) {
AddOverriddenMethods(Method->getParent(), Method);
}
if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
diag::err_constrained_virtual_method);
if (Method->isStatic())
checkThisInStaticMemberFunctionType(Method);
}
if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
}
if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
ActOnConversionDeclarator(Conversion);
if (NewFD->isOverloadedOperator() &&
CheckOverloadedOperatorDeclaration(NewFD)) {
NewFD->setInvalidDecl();
return Redeclaration;
}
if (NewFD->getLiteralIdentifier() &&
CheckLiteralOperatorDeclaration(NewFD)) {
NewFD->setInvalidDecl();
return Redeclaration;
}
if (!CurContext->isRecord())
CheckCXXDefaultArguments(NewFD);
if (Previous.empty() && NewFD->isExternC()) {
QualType R = NewFD->getReturnType();
if (R->isIncompleteType() && !R->isVoidType())
Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
<< NewFD << R;
else if (!R.isPODType(Context) && !R->isVoidType() &&
!R->isObjCObjectPointerType())
Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
}
if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
auto HasNoexcept = [&](QualType T) -> bool {
if (auto *RT = T->getAs<ReferenceType>())
T = RT->getPointeeType();
else if (T->isAnyPointerType())
T = T->getPointeeType();
else if (auto *MPT = T->getAs<MemberPointerType>())
T = MPT->getPointeeType();
if (auto *FPT = T->getAs<FunctionProtoType>())
if (FPT->isNothrow())
return true;
return false;
};
auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
for (QualType T : FPT->param_types())
AnyNoexcept |= HasNoexcept(T);
if (AnyNoexcept)
Diag(NewFD->getLocation(),
diag::warn_cxx17_compat_exception_spec_in_signature)
<< NewFD;
}
if (!Redeclaration && LangOpts.CUDA)
checkCUDATargetOverload(NewFD, Previous);
}
return Redeclaration;
}
void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
if (FD->getStorageClass() == SC_Static)
Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
? diag::err_static_main : diag::warn_static_main)
<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
if (FD->isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
<< FixItHint::CreateRemoval(DS.getInlineSpecLoc());
if (DS.isNoreturnSpecified()) {
SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
Diag(NoreturnLoc, diag::ext_noreturn_main);
Diag(NoreturnLoc, diag::note_main_remove_noreturn)
<< FixItHint::CreateRemoval(NoreturnRange);
}
if (FD->isConstexpr()) {
Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
<< FD->isConsteval()
<< FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
FD->setConstexprKind(ConstexprSpecKind::Unspecified);
}
if (getLangOpts().OpenCL) {
Diag(FD->getLocation(), diag::err_opencl_no_main)
<< FD->hasAttr<OpenCLKernelAttr>();
FD->setInvalidDecl();
return;
}
if (getLangOpts().HLSL)
return;
QualType T = FD->getType();
assert(T->isFunctionType() && "function decl is not of function type");
const FunctionType* FT = T->castAs<FunctionType>();
if (FT->getCallConv() != CC_C) {
FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
FD->setType(QualType(FT, 0));
T = Context.getCanonicalType(FD->getType());
}
if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
FD->setHasImplicitReturnZero(true);
else {
Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
SourceRange RTRange = FD->getReturnTypeSourceRange();
if (RTRange.isValid())
Diag(RTRange.getBegin(), diag::note_main_change_return_type)
<< FixItHint::CreateReplacement(RTRange, "int");
}
} else {
if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
FD->setHasImplicitReturnZero(true);
else {
SourceRange RTRange = FD->getReturnTypeSourceRange();
Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
<< (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
: FixItHint());
FD->setInvalidDecl(true);
}
}
if (isa<FunctionNoProtoType>(FT)) return;
const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
unsigned nparams = FTP->getNumParams();
assert(FD->getNumParams() == nparams);
bool HasExtraParameters = (nparams > 3);
if (FTP->isVariadic()) {
Diag(FD->getLocation(), diag::ext_variadic_main);
}
if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
HasExtraParameters = false;
if (HasExtraParameters) {
Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
FD->setInvalidDecl(true);
nparams = 3;
}
QualType CharPP =
Context.getPointerType(Context.getPointerType(Context.CharTy));
QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
for (unsigned i = 0; i < nparams; ++i) {
QualType AT = FTP->getParamType(i);
bool mismatch = true;
if (Context.hasSameUnqualifiedType(AT, Expected[i]))
mismatch = false;
else if (Expected[i] == CharPP) {
QualifierCollector qs;
const PointerType* PT;
if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
(PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
Context.CharTy)) {
qs.removeConst();
mismatch = !qs.empty();
}
}
if (mismatch) {
Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
FD->setInvalidDecl(true);
}
}
if (nparams == 1 && !FD->isInvalidDecl()) {
Diag(FD->getLocation(), diag::warn_main_one_arg);
}
if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
FD->setInvalidDecl();
}
}
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
if (FD->getName() == "main" || FD->getName() == "wmain")
return false;
const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
if (T.isWindowsGNUEnvironment())
return false;
if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
return true;
return false;
}
void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
QualType T = FD->getType();
assert(T->isFunctionType() && "function decl is not of function type");
const FunctionType *FT = T->castAs<FunctionType>();
if (FT->getReturnType()->isIntegralOrEnumerationType() ||
FT->getReturnType()->isAnyPointerType() ||
FT->getReturnType()->isNullPtrType())
if (FD->getName() != "DllMain")
FD->setHasImplicitReturnZero(true);
if (!hasExplicitCallingConv(T)) {
if (isDefaultStdCall(FD, *this)) {
if (FT->getCallConv() != CC_X86StdCall) {
FT = Context.adjustFunctionType(
FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
FD->setType(QualType(FT, 0));
}
} else if (FT->getCallConv() != CC_C) {
FT = Context.adjustFunctionType(FT,
FT->getExtInfo().withCallingConv(CC_C));
FD->setType(QualType(FT, 0));
}
}
if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
FD->setInvalidDecl();
}
}
bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
if (Init->isValueDependent()) {
assert(Init->containsErrors() &&
"Dependent code should only occur in error-recovery path.");
return true;
}
const Expr *Culprit;
if (Init->isConstantInitializer(Context, false, &Culprit))
return false;
Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
<< Culprit->getSourceRange();
return true;
}
namespace {
class SelfReferenceChecker
: public EvaluatedExprVisitor<SelfReferenceChecker> {
Sema &S;
Decl *OrigDecl;
bool isRecordType;
bool isPODType;
bool isReferenceType;
bool isInitList;
llvm::SmallVector<unsigned, 4> InitFieldIndex;
public:
typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
S(S), OrigDecl(OrigDecl) {
isPODType = false;
isRecordType = false;
isReferenceType = false;
isInitList = false;
if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
isPODType = VD->getType().isPODType(S.Context);
isRecordType = VD->getType()->isRecordType();
isReferenceType = VD->getType()->isReferenceType();
}
}
void CheckExpr(Expr *E) {
InitListExpr *InitList = dyn_cast<InitListExpr>(E);
if (!InitList) {
Visit(E);
return;
}
isInitList = true;
InitFieldIndex.push_back(0);
for (auto Child : InitList->children()) {
CheckExpr(cast<Expr>(Child));
++InitFieldIndex.back();
}
InitFieldIndex.pop_back();
}
bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
llvm::SmallVector<FieldDecl*, 4> Fields;
Expr *Base = E;
bool ReferenceField = false;
while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
if (!FD)
return false;
Fields.push_back(FD);
if (FD->getType()->isReferenceType())
ReferenceField = true;
Base = ME->getBase()->IgnoreParenImpCasts();
}
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
if (!DRE || DRE->getDecl() != OrigDecl)
return false;
if (CheckReference && !ReferenceField)
return true;
llvm::SmallVector<unsigned, 4> UsedFieldIndex;
for (const FieldDecl *I : llvm::reverse(Fields))
UsedFieldIndex.push_back(I->getFieldIndex());
for (auto UsedIter = UsedFieldIndex.begin(),
UsedEnd = UsedFieldIndex.end(),
OrigIter = InitFieldIndex.begin(),
OrigEnd = InitFieldIndex.end();
UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
if (*UsedIter < *OrigIter)
return true;
if (*UsedIter > *OrigIter)
break;
}
HandleDeclRefExpr(DRE);
return true;
}
void HandleValue(Expr *E) {
E = E->IgnoreParens();
if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
HandleDeclRefExpr(DRE);
return;
}
if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Visit(CO->getCond());
HandleValue(CO->getTrueExpr());
HandleValue(CO->getFalseExpr());
return;
}
if (BinaryConditionalOperator *BCO =
dyn_cast<BinaryConditionalOperator>(E)) {
Visit(BCO->getCond());
HandleValue(BCO->getFalseExpr());
return;
}
if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
HandleValue(OVE->getSourceExpr());
return;
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
if (BO->getOpcode() == BO_Comma) {
Visit(BO->getLHS());
HandleValue(BO->getRHS());
return;
}
}
if (isa<MemberExpr>(E)) {
if (isInitList) {
if (CheckInitListMemberExpr(cast<MemberExpr>(E),
false ))
return;
}
Expr *Base = E->IgnoreParenImpCasts();
while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
if (!isa<FieldDecl>(ME->getMemberDecl()))
return;
Base = ME->getBase()->IgnoreParenImpCasts();
}
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
HandleDeclRefExpr(DRE);
return;
}
Visit(E);
}
void VisitDeclRefExpr(DeclRefExpr *E) {
if (isReferenceType)
HandleDeclRefExpr(E);
}
void VisitImplicitCastExpr(ImplicitCastExpr *E) {
if (E->getCastKind() == CK_LValueToRValue) {
HandleValue(E->getSubExpr());
return;
}
Inherited::VisitImplicitCastExpr(E);
}
void VisitMemberExpr(MemberExpr *E) {
if (isInitList) {
if (CheckInitListMemberExpr(E, true ))
return;
}
if (E->getType()->canDecayToPointerType()) return;
CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
bool Warn = (MD && !MD->isStatic());
Expr *Base = E->getBase()->IgnoreParenImpCasts();
while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
if (!isa<FieldDecl>(ME->getMemberDecl()))
Warn = false;
Base = ME->getBase()->IgnoreParenImpCasts();
}
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
if (Warn)
HandleDeclRefExpr(DRE);
return;
}
Visit(Base);
}
void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
Expr *Callee = E->getCallee();
if (isa<UnresolvedLookupExpr>(Callee))
return Inherited::VisitCXXOperatorCallExpr(E);
Visit(Callee);
for (auto Arg: E->arguments())
HandleValue(Arg->IgnoreParenImpCasts());
}
void VisitUnaryOperator(UnaryOperator *E) {
if (E->getOpcode() == UO_AddrOf && isRecordType &&
isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
if (!isPODType)
HandleValue(E->getSubExpr());
return;
}
if (E->isIncrementDecrementOp()) {
HandleValue(E->getSubExpr());
return;
}
Inherited::VisitUnaryOperator(E);
}
void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
void VisitCXXConstructExpr(CXXConstructExpr *E) {
if (E->getConstructor()->isCopyConstructor()) {
Expr *ArgExpr = E->getArg(0);
if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
if (ILE->getNumInits() == 1)
ArgExpr = ILE->getInit(0);
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
if (ICE->getCastKind() == CK_NoOp)
ArgExpr = ICE->getSubExpr();
HandleValue(ArgExpr);
return;
}
Inherited::VisitCXXConstructExpr(E);
}
void VisitCallExpr(CallExpr *E) {
if (E->isCallToStdMove()) {
HandleValue(E->getArg(0));
return;
}
Inherited::VisitCallExpr(E);
}
void VisitBinaryOperator(BinaryOperator *E) {
if (E->isCompoundAssignmentOp()) {
HandleValue(E->getLHS());
Visit(E->getRHS());
return;
}
Inherited::VisitBinaryOperator(E);
}
void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
Visit(E->getCond());
Visit(E->getFalseExpr());
}
void HandleDeclRefExpr(DeclRefExpr *DRE) {
Decl* ReferenceDecl = DRE->getDecl();
if (OrigDecl != ReferenceDecl) return;
unsigned diag;
if (isReferenceType) {
diag = diag::warn_uninit_self_reference_in_reference_init;
} else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
diag = diag::warn_static_self_reference_in_init;
} else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
DRE->getDecl()->getType()->isRecordType()) {
diag = diag::warn_uninit_self_reference_in_init;
} else {
return;
}
S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
S.PDiag(diag)
<< DRE->getDecl() << OrigDecl->getLocation()
<< DRE->getSourceRange());
}
};
static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
bool DirectInit) {
if (isa<ParmVarDecl>(OrigDecl))
return;
E = E->IgnoreParens();
if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
if (ICE->getCastKind() == CK_LValueToRValue)
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
if (DRE->getDecl() == OrigDecl)
return;
SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
}
}
namespace {
struct VarDeclOrName {
VarDecl *VDecl;
DeclarationName Name;
friend const Sema::SemaDiagnosticBuilder &
operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
}
};
}
QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
DeclarationName Name, QualType Type,
TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init) {
bool IsInitCapture = !VDecl;
assert((!VDecl || !VDecl->isInitCapture()) &&
"init captures are expected to be deduced prior to initialization");
VarDeclOrName VN{VDecl, Name};
DeducedType *Deduced = Type->getContainedDeducedType();
assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
if (!Init) {
assert(VDecl && "no init for init capture deduction?");
if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
VDecl->hasExternalStorage() ||
VDecl->isStaticDataMember()) {
Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
<< VDecl->getDeclName() << Type;
return QualType();
}
}
ArrayRef<Expr*> DeduceInits;
if (Init)
DeduceInits = Init;
if (DirectInit) {
if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
DeduceInits = PL->exprs();
}
if (isa<DeducedTemplateSpecializationType>(Deduced)) {
assert(VDecl && "non-auto type for init capture deduction?");
InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
InitializationKind Kind = InitializationKind::CreateForInit(
VDecl->getLocation(), DirectInit, Init);
SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
InitsCopy);
}
if (DirectInit) {
if (auto *IL = dyn_cast<InitListExpr>(Init))
DeduceInits = IL->inits();
}
if (DeduceInits.empty()) {
Diag(Init->getBeginLoc(), IsInitCapture
? diag::err_init_capture_no_expression
: diag::err_auto_var_init_no_expression)
<< VN << Type << Range;
return QualType();
}
if (DeduceInits.size() > 1) {
Diag(DeduceInits[1]->getBeginLoc(),
IsInitCapture ? diag::err_init_capture_multiple_expressions
: diag::err_auto_var_init_multiple_expressions)
<< VN << Type << Range;
return QualType();
}
Expr *DeduceInit = DeduceInits[0];
if (DirectInit && isa<InitListExpr>(DeduceInit)) {
Diag(Init->getBeginLoc(), IsInitCapture
? diag::err_init_capture_paren_braces
: diag::err_auto_var_init_paren_braces)
<< isa<InitListExpr>(Init) << VN << Type << Range;
return QualType();
}
bool DefaultedAnyToId = false;
if (getLangOpts().DebuggerCastResultToId &&
Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
if (Result.isInvalid()) {
return QualType();
}
Init = Result.get();
DefaultedAnyToId = true;
}
if (VDecl && isa<DecompositionDecl>(VDecl) &&
Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
DeduceInit->getType()->isConstantArrayType())
return Context.getQualifiedType(DeduceInit->getType(),
Type.getQualifiers());
QualType DeducedType;
if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
if (!IsInitCapture)
DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
else if (isa<InitListExpr>(Init))
Diag(Range.getBegin(),
diag::err_init_capture_deduction_failure_from_init_list)
<< VN
<< (DeduceInit->getType().isNull() ? TSI->getType()
: DeduceInit->getType())
<< DeduceInit->getSourceRange();
else
Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
<< VN << TSI->getType()
<< (DeduceInit->getType().isNull() ? TSI->getType()
: DeduceInit->getType())
<< DeduceInit->getSourceRange();
}
if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
!DeducedType.isNull() && DeducedType->isObjCIdType()) {
SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
}
return DeducedType;
}
bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init) {
assert(!Init || !Init->containsErrors());
QualType DeducedType = deduceVarTypeFromInitializer(
VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
VDecl->getSourceRange(), DirectInit, Init);
if (DeducedType.isNull()) {
VDecl->setInvalidDecl();
return true;
}
VDecl->setType(DeducedType);
assert(VDecl->isLinkageValid());
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
VDecl->setInvalidDecl();
if (getLangOpts().OpenCL)
deduceOpenCLAddressSpace(VDecl);
if (VarDecl *Old = VDecl->getPreviousDecl()) {
MergeVarDeclTypes(VDecl, Old, false);
}
CheckVariableDeclarationType(VDecl);
return VDecl->isInvalidDecl();
}
void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
SourceLocation Loc) {
if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
Init = EWC->getSubExpr();
if (auto *CE = dyn_cast<ConstantExpr>(Init))
Init = CE->getSubExpr();
QualType InitType = Init->getType();
assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct");
if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
for (auto I : ILE->inits()) {
if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
!I->getType().hasNonTrivialToPrimitiveCopyCUnion())
continue;
SourceLocation SL = I->getExprLoc();
checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
}
return;
}
if (isa<ImplicitValueInitExpr>(Init)) {
if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
NTCUK_Init);
} else {
if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
}
}
namespace {
bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
return FD->hasAttr<UnavailableAttr>();
}
struct DiagNonTrivalCUnionDefaultInitializeVisitor
: DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
void> {
using Super =
DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
void>;
DiagNonTrivalCUnionDefaultInitializeVisitor(
QualType OrigTy, SourceLocation OrigLoc,
Sema::NonTrivialCUnionContext UseContext, Sema &S)
: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
const FieldDecl *FD, bool InNonTrivialUnion) {
if (const auto *AT = S.Context.getAsArrayType(QT))
return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
InNonTrivialUnion);
return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
}
void visitARCStrong(QualType QT, const FieldDecl *FD,
bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 0 << QT << FD->getName();
}
void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 0 << QT << FD->getName();
}
void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
if (RD->isUnion()) {
if (OrigLoc.isValid()) {
bool IsUnion = false;
if (auto *OrigRD = OrigTy->getAsRecordDecl())
IsUnion = OrigRD->isUnion();
S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
<< 0 << OrigTy << IsUnion << UseContext;
OrigLoc = SourceLocation();
}
InNonTrivialUnion = true;
}
if (InNonTrivialUnion)
S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
<< 0 << 0 << QT.getUnqualifiedType() << "";
for (const FieldDecl *FD : RD->fields())
if (!shouldIgnoreForRecordTriviality(FD))
asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
}
void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
QualType OrigTy;
SourceLocation OrigLoc;
Sema::NonTrivialCUnionContext UseContext;
Sema &S;
};
struct DiagNonTrivalCUnionDestructedTypeVisitor
: DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
using Super =
DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
DiagNonTrivalCUnionDestructedTypeVisitor(
QualType OrigTy, SourceLocation OrigLoc,
Sema::NonTrivialCUnionContext UseContext, Sema &S)
: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
void visitWithKind(QualType::DestructionKind DK, QualType QT,
const FieldDecl *FD, bool InNonTrivialUnion) {
if (const auto *AT = S.Context.getAsArrayType(QT))
return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
InNonTrivialUnion);
return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
}
void visitARCStrong(QualType QT, const FieldDecl *FD,
bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 1 << QT << FD->getName();
}
void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 1 << QT << FD->getName();
}
void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
if (RD->isUnion()) {
if (OrigLoc.isValid()) {
bool IsUnion = false;
if (auto *OrigRD = OrigTy->getAsRecordDecl())
IsUnion = OrigRD->isUnion();
S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
<< 1 << OrigTy << IsUnion << UseContext;
OrigLoc = SourceLocation();
}
InNonTrivialUnion = true;
}
if (InNonTrivialUnion)
S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
<< 0 << 1 << QT.getUnqualifiedType() << "";
for (const FieldDecl *FD : RD->fields())
if (!shouldIgnoreForRecordTriviality(FD))
asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
}
void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
void visitCXXDestructor(QualType QT, const FieldDecl *FD,
bool InNonTrivialUnion) {}
QualType OrigTy;
SourceLocation OrigLoc;
Sema::NonTrivialCUnionContext UseContext;
Sema &S;
};
struct DiagNonTrivalCUnionCopyVisitor
: CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
Sema::NonTrivialCUnionContext UseContext,
Sema &S)
: OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
const FieldDecl *FD, bool InNonTrivialUnion) {
if (const auto *AT = S.Context.getAsArrayType(QT))
return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
InNonTrivialUnion);
return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
}
void visitARCStrong(QualType QT, const FieldDecl *FD,
bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 2 << QT << FD->getName();
}
void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
if (InNonTrivialUnion)
S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
<< 1 << 2 << QT << FD->getName();
}
void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
if (RD->isUnion()) {
if (OrigLoc.isValid()) {
bool IsUnion = false;
if (auto *OrigRD = OrigTy->getAsRecordDecl())
IsUnion = OrigRD->isUnion();
S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
<< 2 << OrigTy << IsUnion << UseContext;
OrigLoc = SourceLocation();
}
InNonTrivialUnion = true;
}
if (InNonTrivialUnion)
S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
<< 0 << 2 << QT.getUnqualifiedType() << "";
for (const FieldDecl *FD : RD->fields())
if (!shouldIgnoreForRecordTriviality(FD))
asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
}
void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
const FieldDecl *FD, bool InNonTrivialUnion) {}
void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
bool InNonTrivialUnion) {}
QualType OrigTy;
SourceLocation OrigLoc;
Sema::NonTrivialCUnionContext UseContext;
Sema &S;
};
}
void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind) {
assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
QT.hasNonTrivialToPrimitiveDestructCUnion() ||
QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C union");
if ((NonTrivialKind & NTCUK_Init) &&
QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
.visit(QT, nullptr, false);
if ((NonTrivialKind & NTCUK_Destruct) &&
QT.hasNonTrivialToPrimitiveDestructCUnion())
DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
.visit(QT, nullptr, false);
if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
.visit(QT, nullptr, false);
}
void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
if (!RealDecl || RealDecl->isInvalidDecl()) {
CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
return;
}
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
Diag(Method->getLocation(), diag::err_member_function_initialization)
<< Method->getDeclName() << Init->getSourceRange();
Method->setInvalidDecl();
return;
}
VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
if (!VDecl) {
assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
RealDecl->setInvalidDecl();
return;
}
if (VDecl->getType()->isUndeducedType()) {
ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
if (!Res.isUsable()) {
RealDecl->setInvalidDecl();
return;
}
if (Res.get()->containsErrors()) {
RealDecl->setInvalidDecl();
VDecl->setInit(Res.get());
return;
}
Init = Res.get();
if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
return;
}
if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
VDecl->setInvalidDecl();
return;
}
if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
VDecl->setInvalidDecl();
return;
}
if (!VDecl->getType()->isDependentType()) {
QualType BaseDeclType = VDecl->getType();
if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
BaseDeclType = Array->getElementType();
if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
diag::err_typecheck_decl_incomplete_type)) {
RealDecl->setInvalidDecl();
return;
}
if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
diag::err_abstract_type_in_decl,
AbstractVariableType))
VDecl->setInvalidDecl();
}
if (VarDecl *Def = VDecl->getDefinition())
if (Def != VDecl &&
(!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
!VDecl->isThisDeclarationADemotedDefinition() &&
checkVarDeclRedefinition(Def, VDecl))
return;
if (getLangOpts().CPlusPlus) {
if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
<< VDecl->getDeclName();
Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
diag::note_previous_initializer)
<< 0;
return;
}
if (VDecl->hasLocalStorage())
setFunctionHasBranchProtectedScope();
if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
VDecl->setInvalidDecl();
return;
}
}
if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
Diag(VDecl->getLocation(), diag::err_local_cant_init);
VDecl->setInvalidDecl();
return;
}
if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
VDecl->setInvalidDecl();
return;
}
QualType DclT = VDecl->getType(), SavT = DclT;
if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
Init->getType() == Context.UnknownAnyTy) {
ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
if (Result.isInvalid()) {
VDecl->setInvalidDecl();
return;
}
Init = Result.get();
}
ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
if (!VDecl->isInvalidDecl()) {
InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
InitializationKind Kind = InitializationKind::CreateForInit(
VDecl->getLocation(), DirectInit, Init);
MultiExprArg Args = Init;
if (CXXDirectInit)
Args = MultiExprArg(CXXDirectInit->getExprs(),
CXXDirectInit->getNumExprs());
for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
ExprResult Res = CorrectDelayedTyposInExpr(
Args[Idx], VDecl, true,
[this, Entity, Kind](Expr *E) {
InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
return Init.Failed() ? ExprError() : E;
});
if (Res.isInvalid()) {
VDecl->setInvalidDecl();
} else if (Res.get() != Args[Idx]) {
Args[Idx] = Res.get();
}
}
if (VDecl->isInvalidDecl())
return;
InitializationSequence InitSeq(*this, Entity, Kind, Args,
false,
false);
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
if (Result.isInvalid()) {
auto RecoveryExpr =
CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
if (RecoveryExpr.get())
VDecl->setInit(RecoveryExpr.get());
return;
}
Init = Result.getAs<Expr>();
}
if (getLangOpts().CPlusPlus)
if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
VDecl->getType()->isReferenceType())
CheckSelfReference(*this, RealDecl, Init, DirectInit);
if (!VDecl->isInvalidDecl() && (DclT != SavT))
VDecl->setType(DclT);
if (!VDecl->isInvalidDecl()) {
checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
if (VDecl->hasAttr<BlocksAttr>())
checkRetainCycles(VDecl, Init);
if (FunctionScopeInfo *FSI = getCurFunction())
if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
Init->getBeginLoc()))
FSI->markSafeWeakUse(Init);
}
ExprResult Result =
ActOnFinishFullExpr(Init, VDecl->getLocation(),
false, VDecl->isConstexpr());
if (Result.isInvalid()) {
VDecl->setInvalidDecl();
return;
}
Init = Result.get();
VDecl->setInit(Init);
if (VDecl->isLocalVarDecl()) {
if (VDecl->isInvalidDecl()) {
} else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
CheckForConstantInitializer(Init, DclT);
} else if (getLangOpts().CPlusPlus) {
} else if (VDecl->getStorageClass() == SC_Static) {
CheckForConstantInitializer(Init, DclT);
} else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
isa<InitListExpr>(Init)) {
const Expr *Culprit;
if (!Init->isConstantInitializer(Context, false, &Culprit)) {
Diag(Culprit->getExprLoc(),
diag::ext_aggregate_init_not_constant)
<< Culprit->getSourceRange();
}
}
if (auto *E = dyn_cast<ExprWithCleanups>(Init))
if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
if (VDecl->hasLocalStorage())
BE->getBlockDecl()->setCanAvoidCopyToHeap();
} else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
VDecl->getLexicalDeclContext()->isRecord()) {
if (DclT->isDependentType()) {
} else if (VDecl->isConstexpr()) {
} else if (!DclT.isConstQualified()) {
Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
<< Init->getSourceRange();
VDecl->setInvalidDecl();
} else if (DclT->isIntegralOrEnumerationType()) {
SourceLocation Loc;
if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
else if (Init->isValueDependent())
; else if (Init->isIntegerConstantExpr(Context, &Loc))
; else if (Init->getType()->isScopedEnumeralType() &&
Init->isCXX11ConstantExpr(Context))
; else if (Init->isEvaluatable(Context)) {
Diag(Loc, diag::ext_in_class_initializer_non_constant)
<< Init->getSourceRange();
} else {
Diag(Loc, diag::err_in_class_initializer_non_constant)
<< Init->getSourceRange();
VDecl->setInvalidDecl();
}
} else if (DclT->isFloatingType()) { if (getLangOpts().CPlusPlus11) {
Diag(VDecl->getLocation(),
diag::ext_in_class_initializer_float_type_cxx11)
<< DclT << Init->getSourceRange();
Diag(VDecl->getBeginLoc(),
diag::note_in_class_initializer_float_type_cxx11)
<< FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
} else {
Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
<< DclT << Init->getSourceRange();
if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
<< Init->getSourceRange();
VDecl->setInvalidDecl();
}
}
} else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
<< DclT << Init->getSourceRange()
<< FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
VDecl->setConstexpr(true);
} else {
Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
<< DclT << Init->getSourceRange();
VDecl->setInvalidDecl();
}
} else if (VDecl->isFileVarDecl()) {
if (VDecl->getStorageClass() == SC_Extern &&
((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
!Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
!(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
!isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
Diag(VDecl->getLocation(), diag::warn_extern_init);
if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
VDecl->setStorageClass(SC_Extern);
if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
CheckForConstantInitializer(Init, DclT);
}
QualType InitType = Init->getType();
if (!InitType.isNull() &&
(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
InitType.hasNonTrivialToPrimitiveCopyCUnion()))
checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
if (CXXDirectInit) {
assert(DirectInit && "Call-style initializer must be direct init.");
VDecl->setInitStyle(VarDecl::CallInit);
} else if (DirectInit) {
VDecl->setInitStyle(VarDecl::ListInit);
}
if (LangOpts.OpenMP &&
(LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
VDecl->isFileVarDecl())
DeclsToCheckForDeferredDiags.insert(VDecl);
CheckCompleteVariableDeclaration(VDecl);
}
void Sema::ActOnInitializerError(Decl *D) {
if (!D || D->isInvalidDecl()) return;
VarDecl *VD = dyn_cast<VarDecl>(D);
if (!VD) return;
if (auto *DD = dyn_cast<DecompositionDecl>(D))
for (auto *BD : DD->bindings())
BD->setInvalidDecl();
if (VD->getType()->isUndeducedType()) {
D->setInvalidDecl();
return;
}
QualType Ty = VD->getType();
if (Ty->isDependentType()) return;
if (RequireCompleteType(VD->getLocation(),
Context.getBaseElementType(Ty),
diag::err_typecheck_decl_incomplete_type)) {
VD->setInvalidDecl();
return;
}
if (RequireNonAbstractType(VD->getLocation(), Ty,
diag::err_abstract_type_in_decl,
AbstractVariableType)) {
VD->setInvalidDecl();
return;
}
}
void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
if (!RealDecl)
return;
if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
QualType Type = Var->getType();
if (isa<DecompositionDecl>(RealDecl)) {
Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
Var->setInvalidDecl();
return;
}
if (Type->isUndeducedType() &&
DeduceVariableDeclarationType(Var, false, nullptr))
return;
if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
!Var->isThisDeclarationADemotedDefinition()) {
if (Var->isStaticDataMember()) {
if (!getLangOpts().CPlusPlus17 &&
!Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Diag(Var->getLocation(),
diag::err_constexpr_static_mem_var_requires_init)
<< Var;
Var->setInvalidDecl();
return;
}
} else {
Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
Var->setInvalidDecl();
return;
}
}
if (!Var->isInvalidDecl() &&
Var->getType().getAddressSpace() == LangAS::opencl_constant &&
Var->getStorageClass() != SC_Extern && !Var->getInit()) {
bool HasConstExprDefaultConstructor = false;
if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
for (auto *Ctor : RD->ctors()) {
if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
Ctor->getMethodQualifiers().getAddressSpace() ==
LangAS::opencl_constant) {
HasConstExprDefaultConstructor = true;
}
}
}
if (!HasConstExprDefaultConstructor) {
Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
Var->setInvalidDecl();
return;
}
}
if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
if (Var->getStorageClass() == SC_Extern) {
Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
<< Var;
Var->setInvalidDecl();
return;
}
if (RequireCompleteType(Var->getLocation(), Var->getType(),
diag::err_typecheck_decl_incomplete_type)) {
Var->setInvalidDecl();
return;
}
if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
if (!RD->hasTrivialDefaultConstructor()) {
Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
Var->setInvalidDecl();
return;
}
}
return;
}
VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
NTCUC_DefaultInitializedObject, NTCUK_Init);
switch (DefKind) {
case VarDecl::Definition:
if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
break;
LLVM_FALLTHROUGH;
case VarDecl::DeclarationOnly:
if (!Type->isDependentType() && Var->isLocalVarDecl() &&
!Var->hasLinkage() && !Var->isInvalidDecl() &&
RequireCompleteType(Var->getLocation(), Type,
diag::err_typecheck_decl_incomplete_type))
Var->setInvalidDecl();
if (!Type->isDependentType() && !Var->isInvalidDecl() &&
RequireNonAbstractType(Var->getLocation(), Type,
diag::err_abstract_type_in_decl,
AbstractVariableType))
Var->setInvalidDecl();
if (!Type->isDependentType() && !Var->isInvalidDecl() &&
Var->getStorageClass() == SC_PrivateExtern) {
Diag(Var->getLocation(), diag::warn_private_extern);
Diag(Var->getLocation(), diag::note_private_extern);
}
if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
!Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
ExternalDeclarations.push_back(Var);
return;
case VarDecl::TentativeDefinition:
if (!Var->isInvalidDecl()) {
if (const IncompleteArrayType *ArrayT
= Context.getAsIncompleteArrayType(Type)) {
if (RequireCompleteSizedType(
Var->getLocation(), ArrayT->getElementType(),
diag::err_array_incomplete_or_sizeless_type))
Var->setInvalidDecl();
} else if (Var->getStorageClass() == SC_Static) {
if (Var->isFirstDecl())
RequireCompleteType(Var->getLocation(), Type,
diag::ext_typecheck_decl_incomplete_type);
}
}
if (!Var->isInvalidDecl())
TentativeDefinitions.push_back(Var);
return;
}
if (Type->isIncompleteArrayType()) {
Diag(Var->getLocation(),
diag::err_typecheck_incomplete_array_needs_initializer);
Var->setInvalidDecl();
return;
}
if (Type->isReferenceType()) {
Diag(Var->getLocation(), diag::err_reference_var_requires_init)
<< Var << SourceRange(Var->getLocation(), Var->getLocation());
return;
}
if (Type->isDependentType())
return;
if (Var->isInvalidDecl())
return;
if (!Var->hasAttr<AliasAttr>()) {
if (RequireCompleteType(Var->getLocation(),
Context.getBaseElementType(Type),
diag::err_typecheck_decl_incomplete_type)) {
Var->setInvalidDecl();
return;
}
} else {
return;
}
if (RequireNonAbstractType(Var->getLocation(), Type,
diag::err_abstract_type_in_decl,
AbstractVariableType)) {
Var->setInvalidDecl();
return;
}
if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
if (const RecordType *Record
= Context.getBaseElementType(Type)->getAs<RecordType>()) {
CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
if (!CXXRecord->isPOD())
setFunctionHasBranchProtectedScope();
}
}
if (getLangOpts().OpenCL &&
Var->getType().getAddressSpace() == LangAS::opencl_local)
return;
InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
InitializationKind Kind
= InitializationKind::CreateDefault(Var->getLocation());
InitializationSequence InitSeq(*this, Entity, Kind, None);
ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
if (Init.get()) {
Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Var->setInitStyle(VarDecl::CallInit);
} else if (Init.isInvalid()) {
auto RecoveryExpr =
CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
if (RecoveryExpr.get())
Var->setInit(RecoveryExpr.get());
}
CheckCompleteVariableDeclaration(Var);
}
}
void Sema::ActOnCXXForRangeDecl(Decl *D) {
if (!D)
return;
VarDecl *VD = dyn_cast<VarDecl>(D);
if (!VD) {
Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
D->setInvalidDecl();
return;
}
VD->setCXXForRangeDecl(true);
int Error = -1;
switch (VD->getStorageClass()) {
case SC_None:
break;
case SC_Extern:
Error = 0;
break;
case SC_Static:
Error = 1;
break;
case SC_PrivateExtern:
Error = 2;
break;
case SC_Auto:
Error = 3;
break;
case SC_Register:
Error = 4;
break;
}
switch (VD->getTSCSpec()) {
case TSCS_thread_local:
Error = 6;
break;
case TSCS___thread:
case TSCS__Thread_local:
case TSCS_unspecified:
break;
}
if (Error != -1) {
Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
<< VD << Error;
D->setInvalidDecl();
}
}
StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs) {
DeclSpec DS(Attrs.getPool().getFactory());
const char *PrevSpec;
unsigned DiagID;
DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
getPrintingPolicy());
Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
D.SetIdentifier(Ident, IdentLoc);
D.takeAttributes(Attrs);
D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, false),
IdentLoc);
Decl *Var = ActOnDeclarator(S, D);
cast<VarDecl>(Var)->setCXXForRangeDecl(true);
FinalizeDeclaration(Var);
return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
: IdentLoc);
}
void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
if (var->isInvalidDecl()) return;
MaybeAddCUDAConstantAttr(var);
if (getLangOpts().OpenCL) {
if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
!var->hasInit()) {
Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
<< 1 ;
var->setInvalidDecl();
return;
}
}
if (getLangOpts().ObjC &&
var->hasLocalStorage()) {
switch (var->getType().getObjCLifetime()) {
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
break;
case Qualifiers::OCL_Weak:
case Qualifiers::OCL_Strong:
setFunctionHasBranchProtectedScope();
break;
}
}
if (var->hasLocalStorage() &&
var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
setFunctionHasBranchProtectedScope();
if (var->isThisDeclarationADefinition() &&
var->getDeclContext()->getRedeclContext()->isFileContext() &&
var->isExternallyVisible() && var->hasLinkage() &&
!var->isInline() && !var->getDescribedVarTemplate() &&
!isa<VarTemplatePartialSpecializationDecl>(var) &&
!isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
!getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
var->getLocation())) {
VarDecl *prev = var->getPreviousDecl();
while (prev && prev->isThisDeclarationADefinition())
prev = prev->getPreviousDecl();
if (!prev) {
Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
<< 0;
}
}
Optional<bool> CacheHasConstInit;
const Expr *CacheCulprit = nullptr;
auto checkConstInit = [&]() mutable {
if (!CacheHasConstInit)
CacheHasConstInit = var->getInit()->isConstantInitializer(
Context, var->getType()->isReferenceType(), &CacheCulprit);
return *CacheHasConstInit;
};
if (var->getTLSKind() == VarDecl::TLS_Static) {
if (var->getType().isDestructedType()) {
Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
if (getLangOpts().CPlusPlus11)
Diag(var->getLocation(), diag::note_use_thread_local);
} else if (getLangOpts().CPlusPlus && var->hasInit()) {
if (!checkConstInit()) {
Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
<< CacheCulprit->getSourceRange();
if (getLangOpts().CPlusPlus11)
Diag(var->getLocation(), diag::note_use_thread_local);
}
}
}
if (!var->getType()->isStructureType() && var->hasInit() &&
isa<InitListExpr>(var->getInit())) {
const auto *ILE = cast<InitListExpr>(var->getInit());
unsigned NumInits = ILE->getNumInits();
if (NumInits > 2)
for (unsigned I = 0; I < NumInits; ++I) {
const auto *Init = ILE->getInit(I);
if (!Init)
break;
const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
if (!SL)
break;
unsigned NumConcat = SL->getNumConcatenated();
if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
bool OnlyOneMissingComma = true;
for (unsigned J = I + 1; J < NumInits; ++J) {
const auto *Init = ILE->getInit(J);
if (!Init)
break;
const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
if (!SLJ || SLJ->getNumConcatenated() > 1) {
OnlyOneMissingComma = false;
break;
}
}
if (OnlyOneMissingComma) {
SmallVector<FixItHint, 1> Hints;
for (unsigned i = 0; i < NumConcat - 1; ++i)
Hints.push_back(FixItHint::CreateInsertion(
PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
Diag(SL->getStrTokenLoc(1),
diag::warn_concatenated_literal_array_init)
<< Hints;
Diag(SL->getBeginLoc(),
diag::note_concatenated_string_literal_silence);
}
break;
}
}
}
QualType type = var->getType();
if (var->hasAttr<BlocksAttr>())
getCurFunction()->addByrefBlockVar(var);
Expr *Init = var->getInit();
bool GlobalStorage = var->hasGlobalStorage();
bool IsGlobal = GlobalStorage && !var->isStaticLocal();
QualType baseType = Context.getBaseElementType(type);
bool HasConstInit = true;
if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
!Init->isValueDependent() &&
(GlobalStorage || var->isConstexpr() ||
var->mightBeUsableInConstantExpressions(Context))) {
SmallVector<PartialDiagnosticAt, 8> Notes;
if (!getLangOpts().CPlusPlus11) {
HasConstInit = checkConstInit();
if (HasConstInit) {
(void)var->checkForConstantInitialization(Notes);
Notes.clear();
} else if (CacheCulprit) {
Notes.emplace_back(CacheCulprit->getExprLoc(),
PDiag(diag::note_invalid_subexpr_in_const_expr));
Notes.back().second << CacheCulprit->getSourceRange();
}
} else {
HasConstInit = var->checkForConstantInitialization(Notes);
}
if (HasConstInit) {
} else if (var->isConstexpr()) {
SourceLocation DiagLoc = var->getLocation();
if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
diag::note_invalid_subexpr_in_const_expr) {
DiagLoc = Notes[0].first;
Notes.clear();
}
Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
<< var << Init->getSourceRange();
for (unsigned I = 0, N = Notes.size(); I != N; ++I)
Diag(Notes[I].first, Notes[I].second);
} else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
auto *Attr = var->getAttr<ConstInitAttr>();
Diag(var->getLocation(), diag::err_require_constant_init_failed)
<< Init->getSourceRange();
Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
<< Attr->getRange() << Attr->isConstinit();
for (auto &it : Notes)
Diag(it.first, it.second);
} else if (IsGlobal &&
!getDiagnostics().isIgnored(diag::warn_global_constructor,
var->getLocation())) {
CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
if (!(RD && !RD->hasTrivialDestructor())) {
if (!checkConstInit())
Diag(var->getLocation(), diag::warn_global_constructor)
<< Init->getSourceRange();
}
}
}
if (GlobalStorage && var->isThisDeclarationADefinition() &&
!inTemplateInstantiation()) {
PragmaStack<StringLiteral *> *Stack = nullptr;
int SectionFlags = ASTContext::PSF_Read;
if (var->getType().isConstQualified()) {
if (HasConstInit)
Stack = &ConstSegStack;
else {
Stack = &BSSSegStack;
SectionFlags |= ASTContext::PSF_Write;
}
} else if (var->hasInit() && HasConstInit) {
Stack = &DataSegStack;
SectionFlags |= ASTContext::PSF_Write;
} else {
Stack = &BSSSegStack;
SectionFlags |= ASTContext::PSF_Write;
}
if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
SectionFlags |= ASTContext::PSF_Implicit;
UnifySection(SA->getName(), SectionFlags, var);
} else if (Stack->CurrentValue) {
SectionFlags |= ASTContext::PSF_Implicit;
auto SectionName = Stack->CurrentValue->getString();
var->addAttr(SectionAttr::CreateImplicit(
Context, SectionName, Stack->CurrentPragmaLocation,
AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
if (UnifySection(SectionName, SectionFlags, var))
var->dropAttr<SectionAttr>();
}
if (CurInitSeg && var->getInit())
var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
CurInitSegLoc,
AttributeCommonInfo::AS_Pragma));
}
if (!getLangOpts().CPlusPlus) {
if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
Context.addModuleInitializer(ModuleScopes.back().Module, var);
return;
}
if (!type->isDependentType())
if (const RecordType *recordType = baseType->getAs<RecordType>())
FinalizeVarWithDestructor(var, recordType);
if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
Context.addModuleInitializer(ModuleScopes.back().Module, var);
if (auto *DD = dyn_cast<DecompositionDecl>(var))
CheckCompleteDecompositionDeclaration(DD);
}
void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
assert(VD->isStaticLocal());
auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
while (FD && !getDLLAttr(FD) &&
!FD->hasAttr<DLLExportStaticLocalAttr>() &&
!FD->hasAttr<DLLImportStaticLocalAttr>()) {
FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
}
if (!FD)
return;
if (Attr *A = getDLLAttr(FD)) {
auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
NewAttr->setInherited(true);
VD->addAttr(NewAttr);
} else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
NewAttr->setInherited(true);
VD->addAttr(NewAttr);
if (!FD->hasAttr<DLLExportAttr>())
FD->addAttr(NewAttr);
} else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
NewAttr->setInherited(true);
VD->addAttr(NewAttr);
}
}
void Sema::FinalizeDeclaration(Decl *ThisDecl) {
ParsingInitForAutoVars.erase(ThisDecl);
VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
if (!VD)
return;
if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
!inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
if (PragmaClangBSSSection.Valid)
VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
Context, PragmaClangBSSSection.SectionName,
PragmaClangBSSSection.PragmaLocation,
AttributeCommonInfo::AS_Pragma));
if (PragmaClangDataSection.Valid)
VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
Context, PragmaClangDataSection.SectionName,
PragmaClangDataSection.PragmaLocation,
AttributeCommonInfo::AS_Pragma));
if (PragmaClangRodataSection.Valid)
VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
Context, PragmaClangRodataSection.SectionName,
PragmaClangRodataSection.PragmaLocation,
AttributeCommonInfo::AS_Pragma));
if (PragmaClangRelroSection.Valid)
VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
Context, PragmaClangRelroSection.SectionName,
PragmaClangRelroSection.PragmaLocation,
AttributeCommonInfo::AS_Pragma));
}
if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
for (auto *BD : DD->bindings()) {
FinalizeDeclaration(BD);
}
}
checkAttributesAfterMerging(*this, *VD);
if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
if (Context.getDeclAlign(VD) > MaxAlignChars) {
Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
<< (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
<< (unsigned)MaxAlignChars.getQuantity();
}
}
}
if (VD->isStaticLocal())
CheckStaticLocalForDllExport(VD);
if (getLangOpts().CUDA)
checkAllowedCUDAInitializer(VD);
const InheritableAttr *DLLAttr = getDLLAttr(VD);
if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
if (VD->isStaticDataMember() && VD->isOutOfLine() &&
VD->isThisDeclarationADefinition()) {
CXXRecordDecl *Context =
cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
bool IsClassTemplateMember =
isa<ClassTemplatePartialSpecializationDecl>(Context) ||
Context->getDescribedClassTemplate();
Diag(VD->getLocation(),
IsClassTemplateMember
? diag::warn_attribute_dllimport_static_field_definition
: diag::err_attribute_dllimport_static_field_definition);
Diag(IA->getLocation(), diag::note_attribute);
if (!IsClassTemplateMember)
VD->setInvalidDecl();
}
}
if (DLLAttr && VD->getTLSKind()) {
auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
if (F && getDLLAttr(F)) {
assert(VD->isStaticLocal());
} else {
Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
<< DLLAttr;
VD->setInvalidDecl();
}
}
if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
<< Attr;
VD->dropAttr<UsedAttr>();
}
}
if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
<< Attr;
VD->dropAttr<RetainAttr>();
}
}
const DeclContext *DC = VD->getDeclContext();
if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
AddPushedVisibilityAttribute(VD);
if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
MarkUnusedFileScopedDecl(VD);
if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
!VD->getType()->isIntegralOrEnumerationType())
return;
for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
const Expr *MagicValueExpr = VD->getInit();
if (!MagicValueExpr) {
continue;
}
Optional<llvm::APSInt> MagicValueInt;
if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
Diag(I->getRange().getBegin(),
diag::err_type_tag_for_datatype_not_ice)
<< LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
continue;
}
if (MagicValueInt->getActiveBits() > 64) {
Diag(I->getRange().getBegin(),
diag::err_type_tag_for_datatype_too_large)
<< LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
continue;
}
uint64_t MagicValue = MagicValueInt->getZExtValue();
RegisterTypeTagForDatatype(I->getArgumentKind(),
MagicValue,
I->getMatchingCType(),
I->getLayoutCompatible(),
I->getMustBeNull());
}
}
static bool hasDeducedAuto(DeclaratorDecl *DD) {
auto *VD = dyn_cast<VarDecl>(DD);
return VD && !VD->getType()->hasAutoForTrailingReturnType();
}
Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group) {
SmallVector<Decl*, 8> Decls;
if (DS.isTypeSpecOwned())
Decls.push_back(DS.getRepAsDecl());
DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
bool DiagnosedMultipleDecomps = false;
DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
bool DiagnosedNonDeducedAuto = false;
for (unsigned i = 0, e = Group.size(); i != e; ++i) {
if (Decl *D = Group[i]) {
if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
if (!FirstDeclaratorInGroup)
FirstDeclaratorInGroup = DD;
if (!FirstDecompDeclaratorInGroup)
FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
!hasDeducedAuto(DD))
FirstNonDeducedAutoInGroup = DD;
if (FirstDeclaratorInGroup != DD) {
if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
Diag(FirstDecompDeclaratorInGroup->getLocation(),
diag::err_decomp_decl_not_alone)
<< FirstDeclaratorInGroup->getSourceRange()
<< DD->getSourceRange();
DiagnosedMultipleDecomps = true;
}
if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
Diag(FirstNonDeducedAutoInGroup->getLocation(),
diag::err_auto_non_deduced_not_alone)
<< FirstNonDeducedAutoInGroup->getType()
->hasAutoForTrailingReturnType()
<< FirstDeclaratorInGroup->getSourceRange()
<< DD->getSourceRange();
DiagnosedNonDeducedAuto = true;
}
}
}
Decls.push_back(D);
}
}
if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
handleTagNumbering(Tag, S);
if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
getLangOpts().CPlusPlus)
Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
}
}
return BuildDeclaratorGroup(Decls);
}
Sema::DeclGroupPtrTy
Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
if (Group.size() > 1) {
QualType Deduced;
VarDecl *DeducedDecl = nullptr;
for (unsigned i = 0, e = Group.size(); i != e; ++i) {
VarDecl *D = dyn_cast<VarDecl>(Group[i]);
if (!D || D->isInvalidDecl())
break;
DeducedType *DT = D->getType()->getContainedDeducedType();
if (!DT || DT->getDeducedType().isNull())
continue;
if (Deduced.isNull()) {
Deduced = DT->getDeducedType();
DeducedDecl = D;
} else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
auto *AT = dyn_cast<AutoType>(DT);
auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
diag::err_auto_different_deductions)
<< (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
<< DeducedDecl->getDeclName() << DT->getDeducedType()
<< D->getDeclName();
if (DeducedDecl->hasInit())
Dia << DeducedDecl->getInit()->getSourceRange();
if (D->getInit())
Dia << D->getInit()->getSourceRange();
D->setInvalidDecl();
break;
}
}
}
ActOnDocumentableDecls(Group);
return DeclGroupPtrTy::make(
DeclGroupRef::Create(Context, Group.data(), Group.size()));
}
void Sema::ActOnDocumentableDecl(Decl *D) {
ActOnDocumentableDecls(D);
}
void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
if (Group.empty() || !Group[0])
return;
if (Diags.isIgnored(diag::warn_doc_param_not_found,
Group[0]->getLocation()) &&
Diags.isIgnored(diag::warn_unknown_comment_command_name,
Group[0]->getLocation()))
return;
if (Group.size() >= 2) {
Decl *MaybeTagDecl = Group[0];
if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
Group = Group.slice(1);
}
}
Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
}
void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
if (getLangOpts().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
if (D.getCXXScopeSpec().isSet()) {
Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
<< D.getCXXScopeSpec().getRange();
}
switch (D.getName().getKind()) {
case UnqualifiedIdKind::IK_Identifier:
break;
case UnqualifiedIdKind::IK_OperatorFunctionId:
case UnqualifiedIdKind::IK_ConversionFunctionId:
case UnqualifiedIdKind::IK_LiteralOperatorId:
case UnqualifiedIdKind::IK_ConstructorName:
case UnqualifiedIdKind::IK_DestructorName:
case UnqualifiedIdKind::IK_ImplicitSelfParam:
case UnqualifiedIdKind::IK_DeductionGuideName:
Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
<< GetNameForDeclarator(D).getName();
break;
case UnqualifiedIdKind::IK_TemplateId:
case UnqualifiedIdKind::IK_ConstructorTemplateId:
Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
break;
}
}
Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
const DeclSpec &DS = D.getDeclSpec();
StorageClass SC = SC_None;
if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
SC = SC_Register;
if (getLangOpts().CPlusPlus11) {
Diag(DS.getStorageClassSpecLoc(),
getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
: diag::warn_deprecated_register)
<< FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
}
} else if (getLangOpts().CPlusPlus &&
DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
SC = SC_Auto;
} else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Diag(DS.getStorageClassSpecLoc(),
diag::err_invalid_storage_class_in_func_decl);
D.getMutableDeclSpec().ClearStorageClassSpecs();
}
if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
<< DeclSpec::getSpecifierName(TSCS);
if (DS.isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
if (DS.hasConstexprSpecifier())
Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
<< 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
DiagnoseFunctionSpecifiers(DS);
CheckFunctionOrTemplateParamDeclarator(S, D);
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType parmDeclType = TInfo->getType();
IdentifierInfo *II = D.getIdentifier();
if (II) {
LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
ForVisibleRedeclaration);
LookupName(R, S);
if (R.isSingleResult()) {
NamedDecl *PrevDecl = R.getFoundDecl();
if (PrevDecl->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
PrevDecl = nullptr;
} else if (S->isDeclScope(PrevDecl)) {
Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
II = nullptr;
D.SetIdentifier(nullptr, D.getIdentifierLoc());
D.setInvalidType(true);
}
}
}
ParmVarDecl *New =
CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
if (D.isInvalidType())
New->setInvalidDecl();
assert(S->isFunctionPrototypeScope());
assert(S->getFunctionPrototypeDepth() >= 1);
New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
S->getNextFunctionPrototypeIndex());
S->AddDecl(New);
if (II)
IdResolver.AddDecl(New);
ProcessDeclAttributes(S, New, D);
if (D.getDeclSpec().isModulePrivateSpecified())
Diag(New->getLocation(), diag::err_module_private_local)
<< 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
<< FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
if (New->hasAttr<BlocksAttr>()) {
Diag(New->getLocation(), diag::err_block_on_nonlocal);
}
if (getLangOpts().OpenCL)
deduceOpenCLAddressSpace(New);
return New;
}
ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T) {
ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
T, Context.getTrivialTypeSourceInfo(T, Loc),
SC_None, nullptr);
Param->setImplicit();
return Param;
}
void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
if (inTemplateInstantiation())
return;
for (const ParmVarDecl *Parameter : Parameters) {
if (!Parameter->isReferenced() && Parameter->getDeclName() &&
!Parameter->hasAttr<UnusedAttr>()) {
Diag(Parameter->getLocation(), diag::warn_unused_parameter)
<< Parameter->getDeclName();
}
}
}
void Sema::DiagnoseSizeOfParametersAndReturnValue(
ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
if (LangOpts.NumLargeByValueCopy == 0) return;
if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
if (Size > LangOpts.NumLargeByValueCopy)
Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
}
for (const ParmVarDecl *Parameter : Parameters) {
QualType T = Parameter->getType();
if (T->isDependentType() || !T.isPODType(Context))
continue;
unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
if (Size > LangOpts.NumLargeByValueCopy)
Diag(Parameter->getLocation(), diag::warn_parameter_size)
<< Parameter << Size;
}
}
ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC) {
if (getLangOpts().ObjCAutoRefCount &&
T.getObjCLifetime() == Qualifiers::OCL_None &&
T->isObjCLifetimeType()) {
Qualifiers::ObjCLifetime lifetime;
if (T->isArrayType()) {
if (!T.isConstQualified()) {
if (DelayedDiagnostics.shouldDelayDiagnostics())
DelayedDiagnostics.add(
sema::DelayedDiagnostic::makeForbiddenType(
NameLoc, diag::err_arc_array_param_no_ownership, T, false));
else
Diag(NameLoc, diag::err_arc_array_param_no_ownership)
<< TSInfo->getTypeLoc().getSourceRange();
}
lifetime = Qualifiers::OCL_ExplicitNone;
} else {
lifetime = T->getObjCARCImplicitLifetime();
}
T = Context.getLifetimeQualifiedType(T, lifetime);
}
ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Context.getAdjustedParameterType(T),
TSInfo, SC, nullptr);
if (New->isParameterPack())
if (auto *LSI = getEnclosingLambda())
LSI->LocalPacks.push_back(New);
if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
New->getType().hasNonTrivialToPrimitiveCopyCUnion())
checkNonTrivialCUnion(New->getType(), New->getLocation(),
NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
if (!CurContext->isRecord() &&
RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
AbstractParamType))
New->setInvalidDecl();
if (T->isObjCObjectType()) {
SourceLocation TypeEndLoc =
getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
Diag(NameLoc,
diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
<< FixItHint::CreateInsertion(TypeEndLoc, "*");
T = Context.getObjCObjectPointerType(T);
New->setType(T);
}
if (T.getAddressSpace() != LangAS::Default &&
!(getLangOpts().OpenCL &&
(T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
Diag(NameLoc, diag::err_arg_with_address_space);
New->setInvalidDecl();
}
if (Context.getTargetInfo().getTriple().isPPC64() &&
CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
New->setInvalidDecl();
}
return New;
}
void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls) {
DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
if (!FTI.hasPrototype) {
for (int i = FTI.NumParams; i != 0; ) {
--i;
if (FTI.Params[i].Param == nullptr) {
if (getLangOpts().C99) {
SmallString<256> Code;
llvm::raw_svector_ostream(Code)
<< " int " << FTI.Params[i].Ident->getName() << ";\n";
Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
<< FTI.Params[i].Ident
<< FixItHint::CreateInsertion(LocAfterDecls, Code);
}
AttributeFactory attrs;
DeclSpec DS(attrs);
const char* PrevSpec; unsigned DiagID; DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
DiagID, Context.getPrintingPolicy());
DS.SetRangeStart(FTI.Params[i].IdentLoc);
DS.SetRangeEnd(FTI.Params[i].IdentLoc);
Declarator ParamD(DS, ParsedAttributesView::none(),
DeclaratorContext::KNRTypeList);
ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
}
}
}
}
Decl *
Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
assert(D.isFunctionDeclarator() && "Not a function declarator!");
Scope *ParentScope = FnBodyScope->getParent();
SmallVector<FunctionDecl *, 4> Bases;
if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
ParentScope, D, TemplateParameterLists, Bases);
D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
if (!Bases.empty())
ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
return Dcl;
}
void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
Consumer.HandleInlineFunctionDefinition(D);
}
static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
const FunctionDecl *&PossiblePrototype) {
if (FD->isInvalidDecl())
return false;
if (!FD->isGlobal())
return false;
if (isa<CXXMethodDecl>(FD))
return false;
if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
if (IdentifierInfo *II = FD->getIdentifier())
if (II->isStr("main") || II->isStr("efi_main"))
return false;
if (FD->isInlined())
return false;
if (FD->getDescribedFunctionTemplate())
return false;
if (FD->isFunctionTemplateSpecialization())
return false;
if (FD->hasAttr<OpenCLKernelAttr>())
return false;
if (FD->isDeleted())
return false;
if (!FD->isExternallyVisible())
return false;
for (const FunctionDecl *Prev = FD->getPreviousDecl();
Prev; Prev = Prev->getPreviousDecl()) {
if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
continue;
PossiblePrototype = Prev;
return Prev->getType()->isFunctionNoProtoType();
}
return true;
}
void
Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
const FunctionDecl *EffectiveDefinition,
SkipBodyInfo *SkipBody) {
const FunctionDecl *Definition = EffectiveDefinition;
if (!Definition &&
!FD->isDefined(Definition, true))
return;
if (Definition->getFriendObjectKind() != Decl::FOK_None) {
if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
if (declaresSameEntity(OrigFD, OrigDef) &&
declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
cast<Decl>(FD->getLexicalDeclContext())))
return;
}
}
}
if (canRedefineFunction(Definition, getLangOpts()))
return;
if (TypoCorrectedFunctionDefinitions.count(Definition))
return;
if (SkipBody && !hasVisibleDefinition(Definition) &&
(Definition->getFormalLinkage() == InternalLinkage ||
Definition->isInlined() ||
Definition->getDescribedFunctionTemplate() ||
Definition->getNumTemplateParameterLists())) {
SkipBody->ShouldSkip = true;
SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
if (auto *TD = Definition->getDescribedFunctionTemplate())
makeMergedDefinitionVisible(TD);
makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
return;
}
if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
Definition->getStorageClass() == SC_Extern)
Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
<< FD << getLangOpts().CPlusPlus;
else
Diag(FD->getLocation(), diag::err_redefinition) << FD;
Diag(Definition->getLocation(), diag::note_previous_definition);
FD->setInvalidDecl();
}
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
Sema &S) {
CXXRecordDecl *const LambdaClass = CallOperator->getParent();
LambdaScopeInfo *LSI = S.PushLambdaScope();
LSI->CallOperator = CallOperator;
LSI->Lambda = LambdaClass;
LSI->ReturnType = CallOperator->getReturnType();
const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
if (LCD == LCD_None)
LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
else if (LCD == LCD_ByCopy)
LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
else if (LCD == LCD_ByRef)
LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
DeclarationNameInfo DNI = CallOperator->getNameInfo();
LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
LSI->Mutable = !CallOperator->isConst();
auto I = LambdaClass->field_begin();
for (const auto &C : LambdaClass->captures()) {
if (C.capturesVariable()) {
VarDecl *VD = C.getCapturedVar();
if (VD->isInitCapture())
S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
const bool ByRef = C.getCaptureKind() == LCK_ByRef;
LSI->addCapture(VD, false, ByRef,
true, C.getLocation(),
C.isPackExpansion()
? C.getEllipsisLoc() : SourceLocation(),
I->getType(), false);
} else if (C.capturesThis()) {
LSI->addThisCapture( false, C.getLocation(), I->getType(),
C.getCaptureKind() == LCK_StarThis);
} else {
LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
I->getType());
}
++I;
}
}
Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
SkipBodyInfo *SkipBody,
FnBodyKind BodyKind) {
if (!D) {
PushFunctionScope();
PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
return D;
}
FunctionDecl *FD = nullptr;
if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
FD = FunTmpl->getTemplatedDecl();
else
FD = cast<FunctionDecl>(D);
if (!isLambdaCallOperator(FD))
PushExpressionEvaluationContext(
FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
: ExprEvalContexts.back().Context);
if (const auto *Attr = FD->getAttr<AliasAttr>()) {
Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
FD->dropAttr<AliasAttr>();
FD->setInvalidDecl();
}
if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
FD->dropAttr<IFuncAttr>();
FD->setInvalidDecl();
}
if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
Ctor->isDefaultConstructor() &&
Context.getTargetInfo().getCXXABI().isMicrosoft()) {
InstantiateDefaultCtorDefaultArgs(Ctor);
}
}
if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
!FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
CheckForFunctionRedefinition(FD, nullptr, SkipBody);
if (SkipBody && SkipBody->ShouldSkip)
return D;
}
FD->setWillHaveBody();
if (isGenericLambdaCallOperatorSpecialization(FD)) {
assert(inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!");
RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
} else {
PushFunctionScope();
}
if (unsigned BuiltinID = FD->getBuiltinID()) {
if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
!Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
FD->setInvalidDecl();
}
}
QualType ResultType = FD->getReturnType();
if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
!FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
RequireCompleteType(FD->getLocation(), ResultType,
diag::err_func_def_incomplete_result))
FD->setInvalidDecl();
if (FnBodyScope)
PushDeclContext(FnBodyScope, FD);
if (BodyKind != FnBodyKind::Delete)
CheckParmsForFunctionDef(FD->parameters(),
true);
if (FnBodyScope) {
for (Decl *NPD : FD->decls()) {
auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
if (!NonParmDecl)
continue;
assert(!isa<ParmVarDecl>(NonParmDecl) &&
"parameters should not be in newly created FD yet");
if (NonParmDecl->getDeclName())
PushOnScopeChains(NonParmDecl, FnBodyScope, false);
if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
for (auto *EI : ED->enumerators())
PushOnScopeChains(EI, FnBodyScope, false);
}
}
}
for (auto Param : FD->parameters()) {
Param->setOwningFunction(FD);
if (Param->getIdentifier() && FnBodyScope) {
CheckShadow(FnBodyScope, Param);
PushOnScopeChains(Param, FnBodyScope);
}
}
if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
ResolveExceptionSpec(D->getLocation(), FPT);
if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
!FD->isTemplateInstantiation()) {
assert(!FD->hasAttr<DLLExportAttr>());
Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
FD->setInvalidDecl();
return D;
}
ActOnDocumentableDecl(D);
if (getCurLexicalContext()->isObjCContainer() &&
getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
return D;
}
void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
ReturnStmt **Returns = Scope->Returns.data();
for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
if (!NRVOCandidate->isNRVOVariable())
Returns[I]->setNRVOCandidate(nullptr);
}
}
}
bool Sema::canDelayFunctionBody(const Declarator &D) {
if (D.getDeclSpec().hasConstexprSpecifier())
return false;
if (D.getDeclSpec().hasAutoTypeSpec()) {
if (D.getNumTypeObjects()) {
const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
if (Outer.Kind == DeclaratorChunk::Function &&
Outer.Fun.hasTrailingReturnType()) {
QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
return Ty.isNull() || !Ty->isUndeducedType();
}
}
return false;
}
return true;
}
bool Sema::canSkipFunctionBody(Decl *D) {
if (const FunctionDecl *FD = D->getAsFunction()) {
if (FD->isConstexpr())
return false;
if (FD->getReturnType()->getContainedDeducedType())
return false;
}
return Consumer.shouldSkipFunctionBody(D);
}
Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
if (!Decl)
return nullptr;
if (FunctionDecl *FD = Decl->getAsFunction())
FD->setHasSkippedBody();
else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
MD->setHasSkippedBody();
return Decl;
}
Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
return ActOnFinishFunctionBody(D, BodyArg, false);
}
class ExitFunctionBodyRAII {
public:
ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII() {
if (!IsLambda)
S.PopExpressionEvaluationContext();
}
private:
Sema &S;
bool IsLambda = false;
};
static void diagnoseImplicitlyRetainedSelf(Sema &S) {
llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
if (EscapeInfo.count(BD))
return EscapeInfo[BD];
bool R = false;
const BlockDecl *CurBD = BD;
do {
R = !CurBD->doesNotEscape();
if (R)
break;
CurBD = CurBD->getParent()->getInnermostBlockDecl();
} while (CurBD);
return EscapeInfo[BD] = R;
};
for (const std::pair<SourceLocation, const BlockDecl *> &P :
S.ImplicitlyRetainedSelfLocs)
if (IsOrNestedInEscapingBlock(P.second))
S.Diag(P.first, diag::warn_implicitly_retains_self)
<< FixItHint::CreateInsertion(P.first, "self->");
}
Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
bool IsInstantiation) {
FunctionScopeInfo *FSI = getCurFunction();
FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
FD->addAttr(StrictFPAttr::CreateImplicit(Context));
sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
if (getLangOpts().Coroutines && FSI->isCoroutine())
CheckCompletedCoroutineBody(FD, Body);
{
ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
if (FD) {
FD->setBody(Body);
FD->setWillHaveBody(false);
if (getLangOpts().CPlusPlus14) {
if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
FD->getReturnType()->isUndeducedType()) {
if (!FD->getReturnType()->getAs<AutoType>()) {
Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
<< FD->getReturnType();
FD->setInvalidDecl();
} else {
Expr *Dummy = nullptr;
if (DeduceFunctionTypeFromReturnExpr(
FD, dcl->getLocation(), Dummy,
FD->getReturnType()->getAs<AutoType>()))
FD->setInvalidDecl();
}
}
} else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
auto *LSI = getCurLambda();
if (LSI->HasImplicitReturnType) {
deduceClosureReturnType(*LSI);
QualType RetType =
LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
Proto->getExtProtoInfo()));
}
}
if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
WP.disableCheckFallThrough();
if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
Diag(FD->getLocation(), diag::ext_pure_function_definition);
if (!FD->isInvalidDecl()) {
if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
!FD->hasAttr<NakedAttr>())
DiagnoseUnusedParameters(FD->parameters());
DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
FD->getReturnType(), FD);
if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
MarkVTableUsed(FD->getLocation(), Constructor->getParent());
else if (CXXDestructorDecl *Destructor =
dyn_cast<CXXDestructorDecl>(FD))
MarkVTableUsed(FD->getLocation(), Destructor->getParent());
if (FD->getReturnType()->isRecordType() &&
(!getLangOpts().CPlusPlus || !FD->isDependentContext()))
computeNRVO(Body, FSI);
}
const FunctionDecl *PossiblePrototype = nullptr;
if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
if (PossiblePrototype) {
if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
TypeLoc TL = TI->getTypeLoc();
if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
Diag(PossiblePrototype->getLocation(),
diag::note_declaration_not_a_prototype)
<< (FD->getNumParams() != 0)
<< (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
FTL.getRParenLoc(), "void")
: FixItHint{});
}
} else {
auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
const LangOptions &LangOpts) {
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
if (LocInfo.first.isInvalid())
return false;
bool Invalid = false;
StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
if (Invalid)
return false;
if (LocInfo.second > Buffer.size())
return false;
const char *LexStart = Buffer.data() + LocInfo.second;
StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
return StartTok.consume_front("const") &&
(StartTok.empty() || isWhitespace(StartTok[0]) ||
StartTok.startswith("/*") || StartTok.startswith("//"));
};
auto findBeginLoc = [&]() {
if ((FD->getReturnType()->isAnyPointerType() &&
FD->getReturnType()->getPointeeType().isConstQualified()) ||
FD->getReturnType().isConstQualified()) {
if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
getLangOpts()))
return FD->getBeginLoc();
}
return FD->getTypeSpecStartLoc();
};
Diag(FD->getTypeSpecStartLoc(),
diag::note_static_for_internal_linkage)
<< 1
<< (FD->getStorageClass() == SC_None
? FixItHint::CreateInsertion(findBeginLoc(), "static ")
: FixItHint{});
}
}
if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
(!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
!PossiblePrototype->isImplicit()))) {
Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
<< 1 << 0;
if (PossiblePrototype)
Diag(PossiblePrototype->getLocation(),
diag::warn_non_prototype_changes_behavior)
<< 0 << 1 << 1
<< 1;
}
if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
if (!CmpndBody->body_empty())
Diag(CmpndBody->body_front()->getBeginLoc(),
diag::warn_dispatch_body_ignored);
if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
const CXXMethodDecl *KeyFunction;
if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
MD->isVirtual() &&
(KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
MD == KeyFunction->getCanonicalDecl()) {
if (FD->isInlined() &&
!Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Context.setNonKeyFunction(MD);
KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
const FunctionDecl *Definition;
if (KeyFunction && KeyFunction->isDefined(Definition))
MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
} else {
MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
}
}
}
assert(
(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
"Function parsing confused");
} else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
assert(MD == getCurMethodDecl() && "Method parsing confused");
MD->setBody(Body);
if (!MD->isInvalidDecl()) {
DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
MD->getReturnType(), MD);
if (Body)
computeNRVO(Body, FSI);
}
if (FSI->ObjCShouldCallSuper) {
Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
<< MD->getSelector().getAsString();
FSI->ObjCShouldCallSuper = false;
}
if (FSI->ObjCWarnForNoDesignatedInitChain) {
const ObjCMethodDecl *InitMethod = nullptr;
bool isDesignated =
MD->isDesignatedInitializerForTheInterface(&InitMethod);
assert(isDesignated && InitMethod);
(void)isDesignated;
auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
auto IFace = MD->getClassInterface();
if (!IFace)
return false;
auto SuperD = IFace->getSuperClass();
if (!SuperD)
return false;
return SuperD->getIdentifier() ==
NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
};
if (!MD->isUnavailable() && !superIsNSObject(MD)) {
Diag(MD->getLocation(),
diag::warn_objc_designated_init_missing_super_call);
Diag(InitMethod->getLocation(),
diag::note_objc_designated_init_marked_here);
}
FSI->ObjCWarnForNoDesignatedInitChain = false;
}
if (FSI->ObjCWarnForNoInitDelegation) {
if (!MD->isUnavailable())
Diag(MD->getLocation(),
diag::warn_objc_secondary_init_missing_init_call);
FSI->ObjCWarnForNoInitDelegation = false;
}
diagnoseImplicitlyRetainedSelf(*this);
} else {
PopFunctionScopeInfo(ActivePolicy, dcl);
return nullptr;
}
if (Body && FSI->HasPotentialAvailabilityViolations)
DiagnoseUnguardedAvailabilityViolations(dcl);
assert(!FSI->ObjCShouldCallSuper &&
"This should only be set for ObjC methods, which should have been "
"handled in the block above.");
if (Body && (!FD || !FD->isDefaulted())) {
if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
DiagnoseInvalidJumps(Body);
if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
if (!Destructor->getParent()->isDependentType())
CheckDestructor(Destructor);
MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
Destructor->getParent());
}
if (hasUncompilableErrorOccurred() ||
getDiagnostics().getSuppressAllDiagnostics()) {
DiscardCleanupsInEvaluationContext();
}
if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
ActivePolicy = &WP;
}
if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
!CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
FD->setInvalidDecl();
if (FD && FD->hasAttr<NakedAttr>()) {
for (const Stmt *S : Body->children()) {
bool RegisterVariables = false;
if (auto *DS = dyn_cast<DeclStmt>(S)) {
for (const auto *Decl : DS->decls()) {
if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
RegisterVariables =
Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
if (!RegisterVariables)
break;
}
}
}
if (RegisterVariables)
continue;
if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
FD->setInvalidDecl();
break;
}
}
}
assert(ExprCleanupObjects.size() ==
ExprEvalContexts.back().NumCleanupObjects &&
"Leftover temporaries in function");
assert(!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function");
assert(MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking");
}
}
if (!IsInstantiation)
PopDeclContext();
PopFunctionScopeInfo(ActivePolicy, dcl);
if (hasUncompilableErrorOccurred()) {
DiscardCleanupsInEvaluationContext();
}
if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
!LangOpts.OMPTargetTriples.empty())) ||
LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
auto ES = getEmissionStatus(FD);
if (ES == Sema::FunctionEmissionStatus::Emitted ||
ES == Sema::FunctionEmissionStatus::Unknown)
DeclsToCheckForDeferredDiags.insert(FD);
}
if (FD && !FD->isDeleted())
checkTypeSupport(FD->getType(), FD->getLocation(), FD);
return dcl;
}
void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
ParsedAttributes &Attrs) {
if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
D = TD->getTemplatedDecl();
ProcessDeclAttributeList(S, D, Attrs);
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
if (Method->isStatic())
checkThisInStaticMemberFunctionAttributes(Method);
}
NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
IdentifierInfo &II, Scope *S) {
assert(LangOpts.implicitFunctionsAllowed() &&
"Implicit function declarations aren't allowed in this language mode");
Scope *BlockScope = S;
while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
BlockScope = BlockScope->getParent();
Scope *ContextScope = BlockScope;
while (!ContextScope->getEntity())
ContextScope = ContextScope->getParent();
ContextRAII SavedContext(*this, ContextScope->getEntity());
NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
if (ExternCPrev) {
PushOnScopeChains(ExternCPrev, BlockScope, false);
if (!isa<FunctionDecl>(ExternCPrev) ||
!Context.typesAreCompatible(
cast<FunctionDecl>(ExternCPrev)->getType(),
Context.getFunctionNoProtoType(Context.IntTy))) {
Diag(Loc, diag::ext_use_out_of_scope_declaration)
<< ExternCPrev << !getLangOpts().C99;
Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
return ExternCPrev;
}
}
unsigned diag_id;
if (II.getName().startswith("__builtin_"))
diag_id = diag::warn_builtin_unknown;
else if (getLangOpts().C99)
diag_id = diag::ext_implicit_function_decl_c99;
else
diag_id = diag::warn_implicit_function_decl;
TypoCorrection Corrected;
if (S && !ExternCPrev &&
(Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
DeclFilterCCC<FunctionDecl> CCC{};
Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
S, nullptr, CCC, CTK_NonError);
}
Diag(Loc, diag_id) << &II;
if (Corrected) {
bool Diagnose = true;
if (const auto *D = Corrected.getCorrectionDecl())
Diagnose = !D->isImplicit();
if (Diagnose)
diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
false);
}
if (ExternCPrev)
return ExternCPrev;
const char *Dummy;
AttributeFactory attrFactory;
DeclSpec DS(attrFactory);
unsigned DiagID;
bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
Context.getPrintingPolicy());
(void)Error; assert(!Error && "Error setting up implicit decl!");
SourceLocation NoLoc;
Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
D.AddTypeInfo(DeclaratorChunk::getFunction(false,
false,
NoLoc,
nullptr,
0,
NoLoc,
NoLoc,
true,
NoLoc,
NoLoc, EST_None,
SourceRange(),
nullptr,
nullptr,
0,
nullptr,
nullptr,
None, Loc,
Loc, D),
std::move(DS.getAttributes()), SourceLocation());
D.SetIdentifier(&II, Loc);
FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
FD->setImplicit();
AddKnownFunctionAttributes(FD);
return FD;
}
void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
FunctionDecl *FD) {
if (FD->isInvalidDecl())
return;
if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
return;
Optional<unsigned> AlignmentParam;
bool IsNothrow = false;
if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
return;
if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
if (!FD->hasAttr<AllocSizeAttr>()) {
FD->addAttr(AllocSizeAttr::CreateImplicit(
Context, ParamIdx(1, FD),
ParamIdx(), FD->getLocation()));
}
if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
FD->addAttr(AllocAlignAttr::CreateImplicit(
Context, ParamIdx(AlignmentParam.value(), FD), FD->getLocation()));
}
}
void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
if (FD->isInvalidDecl())
return;
if (unsigned BuiltinID = FD->getBuiltinID()) {
unsigned FormatIdx;
bool HasVAListArg;
if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
if (!FD->hasAttr<FormatAttr>()) {
const char *fmt = "printf";
unsigned int NumParams = FD->getNumParams();
if (FormatIdx < NumParams && FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
fmt = "NSString";
FD->addAttr(FormatAttr::CreateImplicit(Context,
&Context.Idents.get(fmt),
FormatIdx+1,
HasVAListArg ? 0 : FormatIdx+2,
FD->getLocation()));
}
}
if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
HasVAListArg)) {
if (!FD->hasAttr<FormatAttr>())
FD->addAttr(FormatAttr::CreateImplicit(Context,
&Context.Idents.get("scanf"),
FormatIdx+1,
HasVAListArg ? 0 : FormatIdx+2,
FD->getLocation()));
}
SmallVector<int, 4> Encoding;
if (!FD->hasAttr<CallbackAttr>() &&
Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
FD->addAttr(CallbackAttr::CreateImplicit(
Context, Encoding.data(), Encoding.size(), FD->getLocation()));
if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
!FD->hasAttr<ConstAttr>()) {
switch (BuiltinID) {
case Builtin::BI__builtin_fma:
case Builtin::BI__builtin_fmaf:
case Builtin::BI__builtin_fmal:
case Builtin::BIfma:
case Builtin::BIfmaf:
case Builtin::BIfmal:
FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
break;
default:
break;
}
}
if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
!FD->hasAttr<ReturnsTwiceAttr>())
FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
FD->getLocation()));
if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
!FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
if (getLangOpts().CUDAIsDevice !=
Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
else
FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
}
switch (BuiltinID) {
case Builtin::BImemalign:
case Builtin::BIaligned_alloc:
if (!FD->hasAttr<AllocAlignAttr>())
FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
FD->getLocation()));
break;
default:
break;
}
switch (BuiltinID) {
case Builtin::BIcalloc:
FD->addAttr(AllocSizeAttr::CreateImplicit(
Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
break;
case Builtin::BImemalign:
case Builtin::BIaligned_alloc:
case Builtin::BIrealloc:
FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
ParamIdx(), FD->getLocation()));
break;
case Builtin::BImalloc:
FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
ParamIdx(), FD->getLocation()));
break;
default:
break;
}
}
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
if (!FPT || FPT->getExceptionSpecType() == EST_None)
FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
}
IdentifierInfo *Name = FD->getIdentifier();
if (!Name)
return;
if ((!getLangOpts().CPlusPlus &&
FD->getDeclContext()->isTranslationUnit()) ||
(isa<LinkageSpecDecl>(FD->getDeclContext()) &&
cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
LinkageSpecDecl::lang_c)) {
} else
return;
if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
if (!FD->hasAttr<FormatAttr>())
FD->addAttr(FormatAttr::CreateImplicit(Context,
&Context.Idents.get("printf"), 2,
Name->isStr("vasprintf") ? 0 : 3,
FD->getLocation()));
}
if (Name->isStr("__CFStringMakeConstantString")) {
if (!FD->hasAttr<FormatArgAttr>())
FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
FD->getLocation()));
}
}
TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo) {
assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
if (!TInfo) {
assert(D.isInvalidType() && "no declarator info for valid type");
TInfo = Context.getTrivialTypeSourceInfo(T);
}
TypedefDecl *NewTD =
TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
D.getIdentifierLoc(), D.getIdentifier(), TInfo);
if (D.isInvalidType()) {
NewTD->setInvalidDecl();
return NewTD;
}
if (D.getDeclSpec().isModulePrivateSpecified()) {
if (CurContext->isFunctionOrMethod())
Diag(NewTD->getLocation(), diag::err_module_private_local)
<< 2 << NewTD
<< SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
<< FixItHint::CreateRemoval(
D.getDeclSpec().getModulePrivateSpecLoc());
else
NewTD->setModulePrivate();
}
switch (D.getDeclSpec().getTypeSpecType()) {
case TST_enum:
case TST_struct:
case TST_interface:
case TST_union:
case TST_class: {
TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
break;
}
default:
break;
}
return NewTD;
}
bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
QualType T = TI->getType();
if (T->isDependentType())
return false;
if (const BuiltinType *BT = T->getAs<BuiltinType>())
if (BT->isInteger())
return false;
if (T->isBitIntType())
return false;
return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
}
bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev) {
if (IsScoped != Prev->isScoped()) {
Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
<< Prev->isScoped();
Diag(Prev->getLocation(), diag::note_previous_declaration);
return true;
}
if (IsFixed && Prev->isFixed()) {
if (!EnumUnderlyingTy->isDependentType() &&
!Prev->getIntegerType()->isDependentType() &&
!Context.hasSameUnqualifiedType(EnumUnderlyingTy,
Prev->getIntegerType())) {
Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
<< EnumUnderlyingTy << Prev->getIntegerType();
Diag(Prev->getLocation(), diag::note_previous_declaration)
<< Prev->getIntegerTypeRange();
return true;
}
} else if (IsFixed != Prev->isFixed()) {
Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
<< Prev->isFixed();
Diag(Prev->getLocation(), diag::note_previous_declaration);
return true;
}
return false;
}
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
switch (Tag) {
case TTK_Struct: return 0;
case TTK_Interface: return 1;
case TTK_Class: return 2;
default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
}
}
static bool isClassCompatTagKind(TagTypeKind Tag)
{
return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
}
Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
TagTypeKind TTK) {
if (isa<TypedefDecl>(PrevDecl))
return NTK_Typedef;
else if (isa<TypeAliasDecl>(PrevDecl))
return NTK_TypeAlias;
else if (isa<ClassTemplateDecl>(PrevDecl))
return NTK_Template;
else if (isa<TypeAliasTemplateDecl>(PrevDecl))
return NTK_TypeAliasTemplate;
else if (isa<TemplateTemplateParmDecl>(PrevDecl))
return NTK_TemplateTemplateArgument;
switch (TTK) {
case TTK_Struct:
case TTK_Interface:
case TTK_Class:
return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
case TTK_Union:
return NTK_NonUnion;
case TTK_Enum:
return NTK_NonEnum;
}
llvm_unreachable("invalid TTK");
}
bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name) {
TagTypeKind OldTag = Previous->getTagKind();
if (OldTag != NewTag &&
!(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
return false;
if (!isClassCompatTagKind(NewTag))
return true;
auto IsIgnoredLoc = [&](SourceLocation Loc) {
return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
Loc);
};
if (IsIgnoredLoc(NewTagLoc))
return true;
auto IsIgnored = [&](const TagDecl *Tag) {
return IsIgnoredLoc(Tag->getLocation());
};
while (IsIgnored(Previous)) {
Previous = Previous->getPreviousDecl();
if (!Previous)
return true;
OldTag = Previous->getTagKind();
}
bool isTemplate = false;
if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
isTemplate = Record->getDescribedClassTemplate();
if (inTemplateInstantiation()) {
if (OldTag != NewTag) {
Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
<< getRedeclDiagFromTagKind(OldTag);
}
return true;
}
if (isDefinition) {
if (Previous->getDefinition()) {
return true;
}
bool previousMismatch = false;
for (const TagDecl *I : Previous->redecls()) {
if (I->getTagKind() != NewTag) {
if (IsIgnored(I))
continue;
if (!previousMismatch) {
previousMismatch = true;
Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
<< getRedeclDiagFromTagKind(I->getTagKind());
}
Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
<< getRedeclDiagFromTagKind(NewTag)
<< FixItHint::CreateReplacement(I->getInnerLocStart(),
TypeWithKeyword::getTagTypeKindName(NewTag));
}
}
return true;
}
const TagDecl *PrevDef = Previous->getDefinition();
if (PrevDef && IsIgnored(PrevDef))
PrevDef = nullptr;
const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
if (Redecl->getTagKind() != NewTag) {
Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
<< getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
<< getRedeclDiagFromTagKind(OldTag);
Diag(Redecl->getLocation(), diag::note_previous_use);
if (PrevDef) {
Diag(NewTagLoc, diag::note_struct_class_suggestion)
<< getRedeclDiagFromTagKind(Redecl->getTagKind())
<< FixItHint::CreateReplacement(SourceRange(NewTagLoc),
TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
}
}
return true;
}
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
SourceLocation NameLoc) {
SmallVector<IdentifierInfo *, 4> Namespaces;
DeclContext *DC = ND->getDeclContext()->getRedeclContext();
for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
if (!Namespace || Namespace->isAnonymousNamespace())
return FixItHint();
IdentifierInfo *II = Namespace->getIdentifier();
Namespaces.push_back(II);
NamedDecl *Lookup = SemaRef.LookupSingleName(
S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
if (Lookup == Namespace)
break;
}
SmallString<64> Insertion;
llvm::raw_svector_ostream OS(Insertion);
if (DC->isTranslationUnit())
OS << "::";
std::reverse(Namespaces.begin(), Namespaces.end());
for (auto *II : Namespaces)
OS << II->getName() << "::";
return FixItHint::CreateInsertion(NameLoc, Insertion);
}
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
DeclContext *NewDC) {
OldDC = OldDC->getRedeclContext();
NewDC = NewDC->getRedeclContext();
if (OldDC->Equals(NewDC))
return true;
if (S.getLangOpts().MSVCCompat &&
(OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
return true;
return false;
}
Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attrs, AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists,
bool &OwnedDecl, bool &IsDependent,
SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody) {
IdentifierInfo *OrigName = Name;
assert((Name != nullptr || TUK == TUK_Definition) &&
"Nameless record must be a definition!");
assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
OwnedDecl = false;
TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
bool ScopedEnum = ScopedEnumKWLoc.isValid();
bool isMemberSpecialization = false;
bool Invalid = false;
if (TemplateParameterLists.size() > 0 ||
(SS.isNotEmpty() && TUK != TUK_Reference)) {
if (TemplateParameterList *TemplateParams =
MatchTemplateParametersToScopeSpecifier(
KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
if (Kind == TTK_Enum) {
Diag(KWLoc, diag::err_enum_template);
return nullptr;
}
if (TemplateParams->size() > 0) {
if (Invalid)
return nullptr;
OwnedDecl = false;
DeclResult Result = CheckClassTemplate(
S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
AS, ModulePrivateLoc,
SourceLocation(), TemplateParameterLists.size() - 1,
TemplateParameterLists.data(), SkipBody);
return Result.get();
} else {
Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
<< TypeWithKeyword::getTagTypeKindName(Kind) << Name;
isMemberSpecialization = true;
}
}
if (!TemplateParameterLists.empty() && isMemberSpecialization &&
CheckTemplateDeclScope(S, TemplateParameterLists.back()))
return nullptr;
}
llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
if (Kind == TTK_Enum) {
if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
EnumUnderlying = Context.IntTy.getTypePtr();
} else if (UnderlyingType.get()) {
TypeSourceInfo *TI = nullptr;
GetTypeFromParser(UnderlyingType.get(), &TI);
EnumUnderlying = TI;
if (CheckEnumUnderlyingType(TI))
EnumUnderlying = Context.IntTy.getTypePtr();
if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
UPPC_FixedUnderlyingType))
EnumUnderlying = Context.IntTy.getTypePtr();
} else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
EnumUnderlying = Context.IntTy.getTypePtr();
}
}
DeclContext *SearchDC = CurContext;
DeclContext *DC = CurContext;
bool isStdBadAlloc = false;
bool isStdAlignValT = false;
RedeclarationKind Redecl = forRedeclarationInCurContext();
if (TUK == TUK_Friend || TUK == TUK_Reference)
Redecl = NotForRedeclaration;
auto createTagFromNewDecl = [&]() -> TagDecl * {
assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
TagDecl *New = nullptr;
if (Kind == TTK_Enum) {
New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
if (TUK != TUK_Definition && !Invalid)
return nullptr;
if (EnumUnderlying) {
EnumDecl *ED = cast<EnumDecl>(New);
if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
ED->setIntegerTypeSourceInfo(TI);
else
ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
QualType EnumTy = ED->getIntegerType();
ED->setPromotionType(EnumTy->isPromotableIntegerType()
? Context.getPromotedIntegerType(EnumTy)
: EnumTy);
}
} else { New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
nullptr);
}
if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
AddAlignmentAttributesForRecord(RD);
AddMsStructLayoutForRecord(RD);
}
}
New->setLexicalDeclContext(CurContext);
return New;
};
LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
if (Name && SS.isNotEmpty()) {
if (SS.isInvalid()) {
Name = nullptr;
goto CreateNewDecl;
}
if (TUK == TUK_Friend || TUK == TUK_Reference) {
DC = computeDeclContext(SS, false);
if (!DC) {
IsDependent = true;
return nullptr;
}
} else {
DC = computeDeclContext(SS, true);
if (!DC) {
Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
<< SS.getRange();
return nullptr;
}
}
if (RequireCompleteDeclContext(SS, DC))
return nullptr;
SearchDC = DC;
LookupQualifiedName(Previous, DC);
if (Previous.isAmbiguous())
return nullptr;
if (Previous.empty()) {
if (Previous.wasNotFoundInCurrentInstantiation() &&
(TUK == TUK_Reference || TUK == TUK_Friend)) {
IsDependent = true;
return nullptr;
}
Diag(NameLoc, diag::err_not_tag_in_scope)
<< Kind << Name << DC << SS.getRange();
Name = nullptr;
Invalid = true;
goto CreateNewDecl;
}
} else if (Name) {
if (TUK != TUK_Reference && TUK != TUK_Friend &&
DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
return nullptr;
LookupName(Previous, S);
if (Previous.isAmbiguous() &&
(TUK == TUK_Definition || TUK == TUK_Declaration)) {
LookupResult::Filter F = Previous.makeFilter();
while (F.hasNext()) {
NamedDecl *ND = F.next();
if (!ND->getDeclContext()->getRedeclContext()->Equals(
SearchDC->getRedeclContext()))
F.erase();
}
F.done();
}
if (!Previous.empty() && TUK == TUK_Friend) {
DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
LookupResult::Filter F = Previous.makeFilter();
bool FriendSawTagOutsideEnclosingNamespace = false;
while (F.hasNext()) {
NamedDecl *ND = F.next();
DeclContext *DC = ND->getDeclContext()->getRedeclContext();
if (DC->isFileContext() &&
!EnclosingNS->Encloses(ND->getDeclContext())) {
if (getLangOpts().MSVCCompat)
FriendSawTagOutsideEnclosingNamespace = true;
else
F.erase();
}
}
F.done();
if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
NamedDecl *ND = Previous.getFoundDecl();
Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
<< createFriendTagNNSFixIt(*this, ND, S, NameLoc);
}
}
if (Previous.isAmbiguous())
return nullptr;
if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
SearchDC = SearchDC->getParent();
} else if (getLangOpts().CPlusPlus) {
while (isa<ObjCContainerDecl>(SearchDC))
SearchDC = SearchDC->getParent();
}
} else if (getLangOpts().CPlusPlus) {
while (isa<ObjCContainerDecl>(SearchDC))
SearchDC = SearchDC->getParent();
}
if (Previous.isSingleResult() &&
Previous.getFoundDecl()->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Previous.clear();
}
if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
DC->Equals(getStdNamespace())) {
if (Name->isStr("bad_alloc")) {
isStdBadAlloc = true;
if (Previous.empty() && StdBadAlloc)
Previous.addDecl(getStdBadAlloc());
} else if (Name->isStr("align_val_t")) {
isStdAlignValT = true;
if (Previous.empty() && StdAlignValT)
Previous.addDecl(getStdAlignValT());
}
}
if (Name && Previous.empty() &&
(TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
if (Invalid) goto CreateNewDecl;
assert(SS.isEmpty());
if (TUK == TUK_Reference || IsTemplateParamOrArg) {
SearchDC = getTagInjectionContext(SearchDC);
S = getTagInjectionScope(S, getLangOpts());
} else {
assert(TUK == TUK_Friend);
SearchDC = SearchDC->getEnclosingNamespaceContext();
}
if (getLangOpts().CPlusPlus) {
Previous.setRedeclarationKind(forRedeclarationInCurContext());
LookupQualifiedName(Previous, SearchDC);
} else {
Previous.setRedeclarationKind(forRedeclarationInCurContext());
LookupName(Previous, S);
}
}
if (Previous.empty() && SkipBody && SkipBody->Previous)
Previous.addDecl(SkipBody->Previous);
if (!Previous.empty()) {
NamedDecl *PrevDecl = Previous.getFoundDecl();
NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
if (getLangOpts().CPlusPlus) {
if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
TagDecl *Tag = TT->getDecl();
if (Tag->getDeclName() == Name &&
Tag->getDeclContext()->getRedeclContext()
->Equals(TD->getDeclContext()->getRedeclContext())) {
PrevDecl = Tag;
Previous.clear();
Previous.addDecl(Tag);
Previous.resolveKind();
}
}
}
}
if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
!(OldTag && isAcceptableTagRedeclContext(
*this, OldTag->getDeclContext(), SearchDC))) {
Diag(KWLoc, diag::err_using_decl_conflict_reverse);
Diag(Shadow->getTargetDecl()->getLocation(),
diag::note_using_decl_target);
Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
<< 0;
Previous.clear();
goto CreateNewDecl;
}
}
if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
if (TUK == TUK_Reference || TUK == TUK_Friend ||
isDeclInScope(DirectPrevDecl, SearchDC, S,
SS.isNotEmpty() || isMemberSpecialization)) {
if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
TUK == TUK_Definition, KWLoc,
Name)) {
bool SafeToContinue
= (PrevTagDecl->getTagKind() != TTK_Enum &&
Kind != TTK_Enum);
if (SafeToContinue)
Diag(KWLoc, diag::err_use_with_wrong_tag)
<< Name
<< FixItHint::CreateReplacement(SourceRange(KWLoc),
PrevTagDecl->getKindName());
else
Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
if (SafeToContinue)
Kind = PrevTagDecl->getTagKind();
else {
Name = nullptr;
Previous.clear();
Invalid = true;
}
}
if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
if (TUK == TUK_Reference || TUK == TUK_Friend)
return PrevTagDecl;
QualType EnumUnderlyingTy;
if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
EnumUnderlyingTy = TI->getType().getUnqualifiedType();
else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
EnumUnderlyingTy = QualType(T, 0);
if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
ScopedEnum, EnumUnderlyingTy,
IsFixed, PrevEnum))
return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
}
if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
S->isDeclScope(PrevDecl)) {
Diag(NameLoc, diag::ext_member_redeclared);
Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
}
if (!Invalid) {
if (TUK == TUK_Reference || TUK == TUK_Friend) {
if (!Attrs.empty()) {
} else if (TUK == TUK_Reference &&
(PrevTagDecl->getFriendObjectKind() ==
Decl::FOK_Undeclared ||
PrevDecl->getOwningModule() != getCurrentModule()) &&
SS.isEmpty()) {
if (!getTagInjectionContext(CurContext)->getRedeclContext()
->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
return PrevTagDecl;
S = getTagInjectionScope(S, getLangOpts());
} else {
return PrevTagDecl;
}
}
if (TUK == TUK_Definition) {
if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
bool IsExplicitSpecializationAfterInstantiation = false;
if (isMemberSpecialization) {
if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
IsExplicitSpecializationAfterInstantiation =
RD->getTemplateSpecializationKind() !=
TSK_ExplicitSpecialization;
else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
IsExplicitSpecializationAfterInstantiation =
ED->getTemplateSpecializationKind() !=
TSK_ExplicitSpecialization;
}
NamedDecl *Hidden = nullptr;
if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
if (!getLangOpts().CPlusPlus) {
SkipBody->CheckSameAsPrevious = true;
SkipBody->New = createTagFromNewDecl();
SkipBody->Previous = Def;
return Def;
} else {
SkipBody->ShouldSkip = true;
SkipBody->Previous = Def;
makeMergedDefinitionVisible(Hidden);
}
} else if (!IsExplicitSpecializationAfterInstantiation) {
if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
else
Diag(NameLoc, diag::err_redefinition) << Name;
notePreviousDefinition(Def,
NameLoc.isValid() ? NameLoc : KWLoc);
Name = nullptr;
Previous.clear();
Invalid = true;
}
} else {
auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
if (TD->isBeingDefined()) {
Diag(NameLoc, diag::err_nested_redefinition) << Name;
Diag(PrevTagDecl->getLocation(),
diag::note_previous_definition);
Name = nullptr;
Previous.clear();
Invalid = true;
}
}
}
if (TUK == TUK_Friend || TUK == TUK_Reference) {
SearchDC = PrevTagDecl->getDeclContext();
AS = AS_none;
}
}
} else {
Previous.clear();
}
} else {
if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
!Previous.isForRedeclaration()) {
NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
<< Kind;
Diag(PrevDecl->getLocation(), diag::note_declared_at);
Invalid = true;
} else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
SS.isNotEmpty() || isMemberSpecialization)) {
} else if (TUK == TUK_Reference || TUK == TUK_Friend) {
NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
Invalid = true;
} else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
unsigned Kind = 0;
if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
Diag(NameLoc, diag::err_tag_definition_of_typedef)
<< Name << Kind << TND->getUnderlyingType();
Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
Invalid = true;
} else {
Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
notePreviousDefinition(PrevDecl, NameLoc);
Name = nullptr;
Invalid = true;
}
Previous.clear();
}
}
CreateNewDecl:
TagDecl *PrevDecl = nullptr;
if (Previous.isSingleResult())
PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
TagDecl *New;
if (Kind == TTK_Enum) {
New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
ScopedEnumUsesClassTag, IsFixed);
if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
StdAlignValT = cast<EnumDecl>(New);
if (TUK != TUK_Definition && !Invalid) {
TagDecl *Def;
if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
}
else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Diag(Loc, diag::ext_forward_ref_enum_def)
<< New;
Diag(Def->getLocation(), diag::note_previous_definition);
} else {
unsigned DiagID = diag::ext_forward_ref_enum;
if (getLangOpts().MSVCCompat)
DiagID = diag::ext_ms_forward_ref_enum;
else if (getLangOpts().CPlusPlus)
DiagID = diag::err_forward_ref_enum;
Diag(Loc, DiagID);
}
}
if (EnumUnderlying) {
EnumDecl *ED = cast<EnumDecl>(New);
if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
ED->setIntegerTypeSourceInfo(TI);
else
ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
QualType EnumTy = ED->getIntegerType();
ED->setPromotionType(EnumTy->isPromotableIntegerType()
? Context.getPromotedIntegerType(EnumTy)
: EnumTy);
assert(ED->isComplete() && "enum with type should be complete");
}
} else {
if (getLangOpts().CPlusPlus) {
New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
cast_or_null<CXXRecordDecl>(PrevDecl));
if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
StdBadAlloc = cast<CXXRecordDecl>(New);
} else
New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
cast_or_null<RecordDecl>(PrevDecl));
}
if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
TUK == TUK_Definition) {
Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
<< Context.getTagDeclType(New);
Invalid = true;
}
if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
DC->getDeclKind() == Decl::Enum) {
Diag(New->getLocation(), diag::err_type_defined_in_enum)
<< Context.getTagDeclType(New);
Invalid = true;
}
if (SS.isNotEmpty()) {
if (SS.isSet()) {
if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
isMemberSpecialization))
Invalid = true;
New->setQualifierInfo(SS.getWithLocInContext(Context));
if (TemplateParameterLists.size() > 0) {
New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
}
}
else
Invalid = true;
}
if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
AddAlignmentAttributesForRecord(RD);
AddMsStructLayoutForRecord(RD);
}
}
if (ModulePrivateLoc.isValid()) {
if (isMemberSpecialization)
Diag(New->getLocation(), diag::err_module_private_specialization)
<< 2
<< FixItHint::CreateRemoval(ModulePrivateLoc);
else if (!SearchDC->isFunctionOrMethod())
New->setModulePrivate();
}
if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
Invalid = true;
if ((Name || Kind == TTK_Enum) &&
getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
if (getLangOpts().CPlusPlus) {
if (TUK == TUK_Definition && !IsTypeSpecifier) {
Diag(Loc, diag::err_type_defined_in_param_type)
<< Name;
Invalid = true;
}
} else if (!PrevDecl) {
Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
}
}
if (Invalid)
New->setInvalidDecl();
New->setLexicalDeclContext(CurContext);
if (TUK == TUK_Friend)
New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
if (!Invalid && SearchDC->isRecord())
SetMemberAccessSpecifier(New, PrevDecl, AS);
if (PrevDecl)
CheckRedeclarationInModule(New, PrevDecl);
if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
New->startDefinition();
ProcessDeclAttributeList(S, New, Attrs);
AddPragmaAttributes(S, New);
if (TUK == TUK_Friend) {
if (PrevDecl)
New->setAccess(PrevDecl->getAccess());
DeclContext *DC = New->getDeclContext()->getRedeclContext();
DC->makeDeclVisibleInContext(New);
if (Name) if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
PushOnScopeChains(New, EnclosingScope, false);
} else if (Name) {
S = getNonFieldDeclScope(S);
PushOnScopeChains(New, S, true);
} else {
CurContext->addDecl(New);
}
if (IdentifierInfo *II = New->getIdentifier())
if (!New->isInvalidDecl() &&
New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
II->isStr("FILE"))
Context.setFILEDecl(New);
if (PrevDecl)
mergeDeclAttributes(New, PrevDecl);
if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
inferGslOwnerPointerAttribute(CXXRD);
AddPushedVisibilityAttribute(New);
if (isMemberSpecialization && !New->isInvalidDecl())
CompleteMemberSpecialization(New, Previous);
OwnedDecl = true;
if (Invalid && getLangOpts().CPlusPlus) {
if (New->isBeingDefined())
if (auto RD = dyn_cast<RecordDecl>(New))
RD->completeDefinition();
return nullptr;
} else if (SkipBody && SkipBody->ShouldSkip) {
return SkipBody->Previous;
} else {
return New;
}
}
void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
AdjustDeclIfTemplate(TagD);
TagDecl *Tag = cast<TagDecl>(TagD);
PushDeclContext(S, Tag);
ActOnDocumentableDecl(TagD);
AddPushedVisibilityAttribute(Tag);
}
bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
if (!hasStructuralCompatLayout(Prev, SkipBody.New))
return false;
makeMergedDefinitionVisible(SkipBody.Previous);
return true;
}
void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
assert(IDecl->getLexicalParent() == CurContext &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = IDecl;
}
void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
bool IsAbstract,
SourceLocation LBraceLoc) {
AdjustDeclIfTemplate(TagD);
CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
FieldCollector->StartClass();
if (!Record->getIdentifier())
return;
if (IsAbstract)
Record->markAbstract();
if (FinalLoc.isValid()) {
Record->addAttr(FinalAttr::Create(
Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
}
CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
Record->getLocation(), Record->getIdentifier(),
nullptr,
true);
Context.getTypeDeclType(InjectedClassName, Record);
InjectedClassName->setImplicit();
InjectedClassName->setAccess(AS_public);
if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
InjectedClassName->setDescribedClassTemplate(Template);
PushOnScopeChains(InjectedClassName, S);
assert(InjectedClassName->isInjectedClassName() &&
"Broken injected-class-name");
}
void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
SourceRange BraceRange) {
AdjustDeclIfTemplate(TagD);
TagDecl *Tag = cast<TagDecl>(TagD);
Tag->setBraceRange(BraceRange);
if (Tag->isBeingDefined()) {
assert(Tag->isInvalidDecl() && "We should already have completed it");
if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
RD->completeDefinition();
}
if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
FieldCollector->FinishClass();
if (RD->hasAttr<SYCLSpecialClassAttr>()) {
auto *Def = RD->getDefinition();
assert(Def && "The record is expected to have a completed definition");
unsigned NumInitMethods = 0;
for (auto *Method : Def->methods()) {
if (!Method->getIdentifier())
continue;
if (Method->getName() == "__init")
NumInitMethods++;
}
if (NumInitMethods > 1 || !Def->hasInitMethod())
Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
}
}
PopDeclContext();
if (getCurLexicalContext()->isObjCContainer() &&
Tag->getDeclContext()->isFileContext())
Tag->setTopLevelDeclInObjCContainer();
if (!Tag->isInvalidDecl())
Consumer.HandleTagDeclDefinition(Tag);
if (Context.getTargetInfo().getTriple().isOSAIX() &&
AlignPackStack.hasValue()) {
AlignPackInfo APInfo = AlignPackStack.CurrentValue;
if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
return;
const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
if (!RD)
return;
if (llvm::any_of(RD->fields(),
[](const FieldDecl *FD) { return FD->isBitField(); }))
Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
}
}
void Sema::ActOnObjCContainerFinishDefinition() {
PopDeclContext();
}
void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
assert(ObjCCtx == CurContext && "Mismatch of container contexts");
OriginalLexicalContext = ObjCCtx;
ActOnObjCContainerFinishDefinition();
}
void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
ActOnObjCContainerStartDefinition(ObjCCtx);
OriginalLexicalContext = nullptr;
}
void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
AdjustDeclIfTemplate(TagD);
TagDecl *Tag = cast<TagDecl>(TagD);
Tag->setInvalidDecl();
if (Tag->isBeingDefined()) {
if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
RD->completeDefinition();
}
PopDeclContext();
}
ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
IdentifierInfo *FieldName, QualType FieldTy,
bool IsMsStruct, Expr *BitWidth) {
assert(BitWidth);
if (BitWidth->containsErrors())
return ExprError();
if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
if (RequireCompleteSizedType(FieldLoc, FieldTy,
diag::err_field_incomplete_or_sizeless))
return ExprError();
if (FieldName)
return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
<< FieldName << FieldTy << BitWidth->getSourceRange();
return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
<< FieldTy << BitWidth->getSourceRange();
} else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
UPPC_BitFieldWidth))
return ExprError();
if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
return BitWidth;
llvm::APSInt Value;
ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
if (ICE.isInvalid())
return ICE;
BitWidth = ICE.get();
if (Value == 0 && FieldName)
return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
if (Value.isSigned() && Value.isNegative()) {
if (FieldName)
return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
<< FieldName << toString(Value, 10);
return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
<< toString(Value, 10);
}
if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
return Diag(FieldLoc, diag::err_bitfield_too_wide)
<< !FieldName << FieldName << toString(Value, 10);
}
if (!FieldTy->isDependentType()) {
uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
uint64_t TypeWidth = Context.getIntWidth(FieldTy);
bool BitfieldIsOverwide = Value.ugt(TypeWidth);
bool CStdConstraintViolation =
BitfieldIsOverwide && !getLangOpts().CPlusPlus;
bool MSBitfieldViolation =
Value.ugt(TypeStorageSize) &&
(IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
if (CStdConstraintViolation || MSBitfieldViolation) {
unsigned DiagWidth =
CStdConstraintViolation ? TypeWidth : TypeStorageSize;
return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
<< (bool)FieldName << FieldName << toString(Value, 10)
<< !CStdConstraintViolation << DiagWidth;
}
if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
<< FieldName << toString(Value, 10)
<< (unsigned)TypeWidth;
}
}
return BitWidth;
}
Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth) {
FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
DeclStart, D, static_cast<Expr*>(BitfieldWidth),
ICIS_NoInit, AS_public);
return Res;
}
FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
SourceLocation DeclStart,
Declarator &D, Expr *BitWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS) {
if (D.isDecompositionDeclarator()) {
const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
<< Decomp.getSourceRange();
return nullptr;
}
IdentifierInfo *II = D.getIdentifier();
SourceLocation Loc = DeclStart;
if (II) Loc = D.getIdentifierLoc();
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType T = TInfo->getType();
if (getLangOpts().CPlusPlus) {
CheckExtraCXXDefaultArguments(D);
if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
UPPC_DataMemberType)) {
D.setInvalidType();
T = Context.IntTy;
TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
}
}
DiagnoseFunctionSpecifiers(D.getDeclSpec());
if (D.getDeclSpec().isInlineSpecified())
Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_invalid_thread)
<< DeclSpec::getSpecifierName(TSCS);
NamedDecl *PrevDecl = nullptr;
LookupResult Previous(*this, II, Loc, LookupMemberName,
ForVisibleRedeclaration);
LookupName(Previous, S);
switch (Previous.getResultKind()) {
case LookupResult::Found:
case LookupResult::FoundUnresolvedValue:
PrevDecl = Previous.getAsSingle<NamedDecl>();
break;
case LookupResult::FoundOverloaded:
PrevDecl = Previous.getRepresentativeDecl();
break;
case LookupResult::NotFound:
case LookupResult::NotFoundInCurrentInstantiation:
case LookupResult::Ambiguous:
break;
}
Previous.suppressDiagnostics();
if (PrevDecl && PrevDecl->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
PrevDecl = nullptr;
}
if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
PrevDecl = nullptr;
bool Mutable
= (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
SourceLocation TSSL = D.getBeginLoc();
FieldDecl *NewFD
= CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
TSSL, AS, PrevDecl, &D);
if (NewFD->isInvalidDecl())
Record->setInvalidDecl();
if (D.getDeclSpec().isModulePrivateSpecified())
NewFD->setModulePrivate();
if (NewFD->isInvalidDecl() && PrevDecl) {
} else if (II) {
PushOnScopeChains(NewFD, S);
} else
Record->addDecl(NewFD);
return NewFD;
}
FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D) {
IdentifierInfo *II = Name.getAsIdentifierInfo();
bool InvalidDecl = false;
if (D) InvalidDecl = D->isInvalidType();
if (T.isNull() || T->containsErrors()) {
InvalidDecl = true;
T = Context.IntTy;
}
QualType EltTy = Context.getBaseElementType(T);
if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
if (RequireCompleteSizedType(Loc, EltTy,
diag::err_field_incomplete_or_sizeless)) {
Record->setInvalidDecl();
InvalidDecl = true;
} else {
NamedDecl *Def;
EltTy->isIncompleteType(&Def);
if (Def && Def->isInvalidDecl()) {
Record->setInvalidDecl();
InvalidDecl = true;
}
}
}
if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
Diag(Loc, diag::err_field_with_address_space);
Record->setInvalidDecl();
InvalidDecl = true;
}
if (LangOpts.OpenCL) {
if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
T->isBlockPointerType()) {
Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
Record->setInvalidDecl();
InvalidDecl = true;
}
if (BitWidth && !getOpenCLOptions().isAvailableOption(
"__cl_clang_bitfields", LangOpts)) {
Diag(Loc, diag::err_opencl_bitfields);
InvalidDecl = true;
}
}
if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
T.hasQualifiers()) {
InvalidDecl = true;
Diag(Loc, diag::err_anon_bitfield_qualifiers);
}
if (!InvalidDecl && T->isVariablyModifiedType()) {
if (!tryToFixVariablyModifiedVarType(
TInfo, T, Loc, diag::err_typecheck_field_variable_size))
InvalidDecl = true;
}
if (!InvalidDecl && RequireNonAbstractType(Loc, T,
diag::err_abstract_type_in_decl,
AbstractFieldType))
InvalidDecl = true;
if (InvalidDecl)
BitWidth = nullptr;
if (BitWidth) {
BitWidth =
VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
if (!BitWidth) {
InvalidDecl = true;
BitWidth = nullptr;
}
}
if (!InvalidDecl && Mutable) {
unsigned DiagID = 0;
if (T->isReferenceType())
DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
: diag::err_mutable_reference;
else if (T.isConstQualified())
DiagID = diag::err_mutable_const;
if (DiagID) {
SourceLocation ErrLoc = Loc;
if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
Diag(ErrLoc, DiagID);
if (DiagID != diag::ext_mutable_reference) {
Mutable = false;
InvalidDecl = true;
}
}
}
if (InitStyle != ICIS_NoInit)
checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
BitWidth, Mutable, InitStyle);
if (InvalidDecl)
NewFD->setInvalidDecl();
if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
Diag(Loc, diag::err_duplicate_member) << II;
Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
NewFD->setInvalidDecl();
}
if (!InvalidDecl && getLangOpts().CPlusPlus) {
if (Record->isUnion()) {
if (const RecordType *RT = EltTy->getAs<RecordType>()) {
CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
if (RDecl->getDefinition()) {
if (CheckNontrivialField(NewFD))
NewFD->setInvalidDecl();
}
}
if (EltTy->isReferenceType()) {
Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
diag::ext_union_member_of_reference_type :
diag::err_union_member_of_reference_type)
<< NewFD->getDeclName() << EltTy;
if (!getLangOpts().MicrosoftExt)
NewFD->setInvalidDecl();
}
}
}
if (D) {
ProcessDeclAttributes(getCurScope(), NewFD, *D);
if (NewFD->hasAttrs())
CheckAlignasUnderalignment(NewFD);
}
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
NewFD->setInvalidDecl();
if (T.isObjCGCWeak())
Diag(Loc, diag::warn_attribute_weak_on_field);
if (Context.getTargetInfo().getTriple().isPPC64() &&
CheckPPCMMAType(T, NewFD->getLocation()))
NewFD->setInvalidDecl();
NewFD->setAccess(AS);
return NewFD;
}
bool Sema::CheckNontrivialField(FieldDecl *FD) {
assert(FD);
assert(getLangOpts().CPlusPlus && "valid check only for C++");
if (FD->isInvalidDecl() || FD->getType()->isDependentType())
return false;
QualType EltTy = Context.getBaseElementType(FD->getType());
if (const RecordType *RT = EltTy->getAs<RecordType>()) {
CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
if (RDecl->getDefinition()) {
CXXSpecialMember member = CXXInvalid;
if (RDecl->hasNonTrivialCopyConstructor())
member = CXXCopyConstructor;
else if (!RDecl->hasTrivialDefaultConstructor())
member = CXXDefaultConstructor;
else if (RDecl->hasNonTrivialCopyAssignment())
member = CXXCopyAssignment;
else if (RDecl->hasNonTrivialDestructor())
member = CXXDestructor;
if (member != CXXInvalid) {
if (!getLangOpts().CPlusPlus11 &&
getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
SourceLocation Loc = FD->getLocation();
if (getSourceManager().isInSystemHeader(Loc)) {
if (!FD->hasAttr<UnavailableAttr>())
FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
return false;
}
}
Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
diag::err_illegal_union_or_anon_struct_member)
<< FD->getParent()->isUnion() << FD->getDeclName() << member;
DiagnoseNontrivial(RDecl, member);
return !getLangOpts().CPlusPlus11;
}
}
}
return false;
}
static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
switch (ivarVisibility) {
default: llvm_unreachable("Unknown visitibility kind");
case tok::objc_private: return ObjCIvarDecl::Private;
case tok::objc_public: return ObjCIvarDecl::Public;
case tok::objc_protected: return ObjCIvarDecl::Protected;
case tok::objc_package: return ObjCIvarDecl::Package;
}
}
Decl *Sema::ActOnIvar(Scope *S,
SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind Visibility) {
IdentifierInfo *II = D.getIdentifier();
Expr *BitWidth = (Expr*)BitfieldWidth;
SourceLocation Loc = DeclStart;
if (II) Loc = D.getIdentifierLoc();
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType T = TInfo->getType();
if (BitWidth) {
BitWidth = VerifyBitField(Loc, II, T, false, BitWidth).get();
if (!BitWidth)
D.setInvalidType();
} else {
}
if (T->isReferenceType()) {
Diag(Loc, diag::err_ivar_reference_type);
D.setInvalidType();
}
else if (T->isVariablyModifiedType()) {
if (!tryToFixVariablyModifiedVarType(
TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
D.setInvalidType();
}
ObjCIvarDecl::AccessControl ac =
Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
: ObjCIvarDecl::None;
ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
return nullptr;
ObjCContainerDecl *EnclosingContext;
if (ObjCImplementationDecl *IMPDecl =
dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
if (LangOpts.ObjCRuntime.isFragile()) {
EnclosingContext = IMPDecl->getClassInterface();
assert(EnclosingContext && "Implementation has no class interface!");
}
else
EnclosingContext = EnclosingDecl;
} else {
if (ObjCCategoryDecl *CDecl =
dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
return nullptr;
}
}
EnclosingContext = EnclosingDecl;
}
ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
DeclStart, Loc, II, T,
TInfo, ac, (Expr *)BitfieldWidth);
if (II) {
NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
ForVisibleRedeclaration);
if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
&& !isa<TagDecl>(PrevDecl)) {
Diag(Loc, diag::err_duplicate_member) << II;
Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
NewID->setInvalidDecl();
}
}
ProcessDeclAttributes(S, NewID, D);
if (D.isInvalidType())
NewID->setInvalidDecl();
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
NewID->setInvalidDecl();
if (D.getDeclSpec().isModulePrivateSpecified())
NewID->setModulePrivate();
if (II) {
S->AddDecl(NewID);
IdResolver.AddDecl(NewID);
}
if (LangOpts.ObjCRuntime.isNonFragile() &&
!NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
Diag(Loc, diag::warn_ivars_in_interface);
return NewID;
}
void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
SmallVectorImpl<Decl *> &AllIvarDecls) {
if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
return;
Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
return;
ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
if (!ID) {
if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
if (!CD->IsClassExtension())
return;
}
else
return;
}
llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
DeclLoc, DeclLoc, nullptr,
Context.CharTy,
Context.getTrivialTypeSourceInfo(Context.CharTy,
DeclLoc),
ObjCIvarDecl::Private, BW,
true);
AllIvarDecls.push_back(Ivar);
}
namespace {
void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
if (!Record->hasUserDeclaredDestructor()) {
return;
}
SourceLocation Loc = Record->getLocation();
OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
for (auto *Decl : Record->decls()) {
if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
if (DD->isInvalidDecl())
continue;
S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
OCS);
assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
}
}
if (OCS.empty()) {
return;
}
OverloadCandidateSet::iterator Best;
unsigned Msg = 0;
OverloadCandidateDisplayKind DisplayKind;
switch (OCS.BestViableFunction(S, Loc, Best)) {
case OR_Success:
case OR_Deleted:
Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
break;
case OR_Ambiguous:
Msg = diag::err_ambiguous_destructor;
DisplayKind = OCD_AmbiguousCandidates;
break;
case OR_No_Viable_Function:
Msg = diag::err_no_viable_destructor;
DisplayKind = OCD_AllCandidates;
break;
}
if (Msg) {
if (!S.LangOpts.OpenCL) {
PartialDiagnostic Diag = S.PDiag(Msg) << Record;
OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
Record->setInvalidDecl();
}
Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
}
}
}
void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac,
const ParsedAttributesView &Attrs) {
assert(EnclosingDecl && "missing record or interface decl");
if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
switch (DC->getKind()) {
default: break;
case Decl::ObjCCategory:
Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
break;
case Decl::ObjCImplementation:
Context.
ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
break;
}
}
RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
if (CXXRecord && !CXXRecord->isDependentType())
ComputeSelectedDestructor(*this, CXXRecord);
unsigned NumNamedMembers = 0;
if (Record) {
for (const auto *I : Record->decls()) {
if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
if (IFD->getDeclName())
++NumNamedMembers;
}
}
SmallVector<FieldDecl*, 32> RecFields;
for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
i != end; ++i) {
FieldDecl *FD = cast<FieldDecl>(*i);
const Type *FDTy = FD->getType().getTypePtr();
if (!FD->isAnonymousStructOrUnion()) {
RecFields.push_back(FD);
}
if (FD->isInvalidDecl()) {
EnclosingDecl->setInvalidDecl();
continue;
}
bool IsLastField = (i + 1 == Fields.end());
if (FDTy->isFunctionType()) {
Diag(FD->getLocation(), diag::err_field_declared_as_function)
<< FD->getDeclName();
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
} else if (FDTy->isIncompleteArrayType() &&
(Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
if (Record) {
unsigned DiagID = 0;
if (!Record->isUnion() && !IsLastField) {
Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
<< FD->getDeclName() << FD->getType() << Record->getTagKind();
Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
} else if (Record->isUnion())
DiagID = getLangOpts().MicrosoftExt
? diag::ext_flexible_array_union_ms
: getLangOpts().CPlusPlus
? diag::ext_flexible_array_union_gnu
: diag::err_flexible_array_union;
else if (NumNamedMembers < 1)
DiagID = getLangOpts().MicrosoftExt
? diag::ext_flexible_array_empty_aggregate_ms
: getLangOpts().CPlusPlus
? diag::ext_flexible_array_empty_aggregate_gnu
: diag::err_flexible_array_empty_aggregate;
if (DiagID)
Diag(FD->getLocation(), DiagID) << FD->getDeclName()
<< Record->getTagKind();
if (CXXRecord && CXXRecord->getNumVBases() != 0)
Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
<< FD->getDeclName() << Record->getTagKind();
if (!getLangOpts().C99)
Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
<< FD->getDeclName() << Record->getTagKind();
QualType BaseElem = Context.getBaseElementType(FD->getType());
if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
<< FD->getDeclName() << FD->getType();
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
Record->setHasFlexibleArrayMember(true);
} else {
}
} else if (!FDTy->isDependentType() &&
RequireCompleteSizedType(
FD->getLocation(), FD->getType(),
diag::err_field_incomplete_or_sizeless)) {
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
} else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
Record->setHasFlexibleArrayMember(true);
if (!Record->isUnion()) {
if (!IsLastField)
Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
<< FD->getDeclName() << FD->getType();
else {
Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
<< FD->getDeclName();
}
}
}
if (isa<ObjCContainerDecl>(EnclosingDecl) &&
RequireNonAbstractType(FD->getLocation(), FD->getType(),
diag::err_abstract_type_in_decl,
AbstractIvarType)) {
FD->setInvalidDecl();
}
if (Record && FDTTy->getDecl()->hasObjectMember())
Record->setHasObjectMember(true);
if (Record && FDTTy->getDecl()->hasVolatileMember())
Record->setHasVolatileMember(true);
} else if (FDTy->isObjCObjectType()) {
Diag(FD->getLocation(), diag::err_statically_allocated_object)
<< FixItHint::CreateInsertion(FD->getLocation(), "*");
QualType T = Context.getObjCObjectPointerType(FD->getType());
FD->setType(T);
} else if (Record && Record->isUnion() &&
FD->getType().hasNonTrivialObjCLifetime() &&
getSourceManager().isInSystemHeader(FD->getLocation()) &&
!getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
(FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
!Context.hasDirectOwnershipQualifier(FD->getType()))) {
FD->addAttr(UnavailableAttr::CreateImplicit(
Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
FD->getLocation()));
} else if (getLangOpts().ObjC &&
getLangOpts().getGC() != LangOptions::NonGC && Record &&
!Record->hasObjectMember()) {
if (FD->getType()->isObjCObjectPointerType() ||
FD->getType().isObjCGCStrong())
Record->setHasObjectMember(true);
else if (Context.getAsArrayType(FD->getType())) {
QualType BaseType = Context.getBaseElementType(FD->getType());
if (BaseType->isRecordType() &&
BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
Record->setHasObjectMember(true);
else if (BaseType->isObjCObjectPointerType() ||
BaseType.isObjCGCStrong())
Record->setHasObjectMember(true);
}
}
if (Record && !getLangOpts().CPlusPlus &&
!shouldIgnoreForRecordTriviality(FD)) {
QualType FT = FD->getType();
if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
Record->setNonTrivialToPrimitiveDefaultInitialize(true);
if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
Record->isUnion())
Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
}
QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
Record->setNonTrivialToPrimitiveCopy(true);
if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
}
if (FT.isDestructedType()) {
Record->setNonTrivialToPrimitiveDestroy(true);
Record->setParamDestroyedInCallee(true);
if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
}
if (const auto *RT = FT->getAs<RecordType>()) {
if (RT->getDecl()->getArgPassingRestrictions() ==
RecordDecl::APK_CanNeverPassInRegs)
Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
} else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
}
if (Record && FD->getType().isVolatileQualified())
Record->setHasVolatileMember(true);
if (FD->getIdentifier())
++NumNamedMembers;
}
if (Record) {
bool Completed = false;
if (CXXRecord) {
if (!CXXRecord->isInvalidDecl()) {
for (CXXRecordDecl::conversion_iterator
I = CXXRecord->conversion_begin(),
E = CXXRecord->conversion_end(); I != E; ++I)
I.setAccess((*I)->getAccess());
}
AddImplicitlyDeclaredMembersToClass(CXXRecord);
if (!CXXRecord->isDependentType()) {
if (!CXXRecord->isInvalidDecl()) {
if (CXXRecord->getNumVBases()) {
CXXFinalOverriderMap FinalOverriders;
CXXRecord->getFinalOverriders(FinalOverriders);
for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
MEnd = FinalOverriders.end();
M != MEnd; ++M) {
for (OverridingMethods::iterator SO = M->second.begin(),
SOEnd = M->second.end();
SO != SOEnd; ++SO) {
assert(SO->second.size() > 0 &&
"Virtual function without overriding functions?");
if (SO->second.size() == 1)
continue;
Diag(Record->getLocation(), diag::err_multiple_final_overriders)
<< (const NamedDecl *)M->first << Record;
Diag(M->first->getLocation(),
diag::note_overridden_virtual_function);
for (OverridingMethods::overriding_iterator
OM = SO->second.begin(),
OMEnd = SO->second.end();
OM != OMEnd; ++OM)
Diag(OM->Method->getLocation(), diag::note_final_overrider)
<< (const NamedDecl *)M->first << OM->Method->getParent();
Record->setInvalidDecl();
}
}
CXXRecord->completeDefinition(&FinalOverriders);
Completed = true;
}
}
}
}
if (!Completed)
Record->completeDefinition();
ProcessDeclAttributeList(S, Record, Attrs);
auto IsFunctionPointer = [&](const Decl *D) {
const FieldDecl *FD = dyn_cast<FieldDecl>(D);
if (!FD)
return false;
QualType FieldType = FD->getType().getDesugaredType(Context);
if (isa<PointerType>(FieldType)) {
QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
return PointeeType.getDesugaredType(Context)->isFunctionType();
}
return false;
};
if (!getLangOpts().CPlusPlus &&
(Record->hasAttr<RandomizeLayoutAttr>() ||
(!Record->hasAttr<NoRandomizeLayoutAttr>() &&
llvm::all_of(Record->decls(), IsFunctionPointer))) &&
!Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
!Record->isRandomized()) {
SmallVector<Decl *, 32> NewDeclOrdering;
if (randstruct::randomizeStructureLayout(Context, Record,
NewDeclOrdering))
Record->reorderDecls(NewDeclOrdering);
}
if (CXXRecord) {
auto *Dtor = CXXRecord->getDestructor();
if (Dtor && Dtor->isImplicit() &&
ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
CXXRecord->setImplicitDestructorIsDeleted();
SetDeclDeleted(Dtor, CXXRecord->getLocation());
}
}
if (Record->hasAttrs()) {
CheckAlignasUnderalignment(Record);
if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
IA->getRange(), IA->getBestCase(),
IA->getInheritanceModel());
}
bool CheckForZeroSize;
if (!getLangOpts().CPlusPlus) {
CheckForZeroSize = true;
} else {
CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
CheckForZeroSize =
CXXRecord->getLexicalDeclContext()->isExternCContext() &&
!CXXRecord->isDependentType() && !inTemplateInstantiation() &&
CXXRecord->isCLike();
}
if (CheckForZeroSize) {
bool ZeroSize = true;
bool IsEmpty = true;
unsigned NonBitFields = 0;
for (RecordDecl::field_iterator I = Record->field_begin(),
E = Record->field_end();
(NonBitFields == 0 || ZeroSize) && I != E; ++I) {
IsEmpty = false;
if (I->isUnnamedBitfield()) {
if (!I->isZeroLengthBitField(Context))
ZeroSize = false;
} else {
++NonBitFields;
QualType FieldType = I->getType();
if (FieldType->isIncompleteType() ||
!Context.getTypeSizeInChars(FieldType).isZero())
ZeroSize = false;
}
}
if (ZeroSize) {
Diag(RecLoc, getLangOpts().CPlusPlus ?
diag::warn_zero_size_struct_union_in_extern_c :
diag::warn_zero_size_struct_union_compat)
<< IsEmpty << Record->isUnion() << (NonBitFields > 1);
}
if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
diag::ext_no_named_members_in_struct_union)
<< Record->isUnion();
}
}
} else {
ObjCIvarDecl **ClsFields =
reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
ID->setEndOfDefinitionLoc(RBrac);
for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
ClsFields[i]->setLexicalDeclContext(ID);
ID->addDecl(ClsFields[i]);
}
if (ID->getSuperClass())
DiagnoseDuplicateIvars(ID, ID->getSuperClass());
} else if (ObjCImplementationDecl *IMPDecl =
dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
ClsFields[I]->setLexicalDeclContext(IMPDecl);
CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
IMPDecl->setIvarLBraceLoc(LBrac);
IMPDecl->setIvarRBraceLoc(RBrac);
} else if (ObjCCategoryDecl *CDecl =
dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
if (IDecl) {
if (const ObjCIvarDecl *ClsIvar =
IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
Diag(ClsFields[i]->getLocation(),
diag::err_duplicate_ivar_declaration);
Diag(ClsIvar->getLocation(), diag::note_previous_definition);
continue;
}
for (const auto *Ext : IDecl->known_extensions()) {
if (const ObjCIvarDecl *ClsExtIvar
= Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
Diag(ClsFields[i]->getLocation(),
diag::err_duplicate_ivar_declaration);
Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
continue;
}
}
}
ClsFields[i]->setLexicalDeclContext(CDecl);
CDecl->addDecl(ClsFields[i]);
}
CDecl->setIvarLBraceLoc(LBrac);
CDecl->setIvarRBraceLoc(RBrac);
}
}
}
static bool isRepresentableIntegerValue(ASTContext &Context,
llvm::APSInt &Value,
QualType T) {
assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!");
unsigned BitWidth = Context.getIntWidth(T);
if (Value.isUnsigned() || Value.isNonNegative()) {
if (T->isSignedIntegerOrEnumerationType())
--BitWidth;
return Value.getActiveBits() <= BitWidth;
}
return Value.getMinSignedBits() <= BitWidth;
}
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
assert((T->isIntegralType(Context) ||
T->isEnumeralType()) && "Integral type required!");
const unsigned NumTypes = 4;
QualType SignedIntegralTypes[NumTypes] = {
Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
};
QualType UnsignedIntegralTypes[NumTypes] = {
Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
Context.UnsignedLongLongTy
};
unsigned BitWidth = Context.getTypeSize(T);
QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
: UnsignedIntegralTypes;
for (unsigned I = 0; I != NumTypes; ++I)
if (Context.getTypeSize(Types[I]) > BitWidth)
return Types[I];
return QualType();
}
EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *Val) {
unsigned IntWidth = Context.getTargetInfo().getIntWidth();
llvm::APSInt EnumVal(IntWidth);
QualType EltTy;
if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
Val = nullptr;
if (Val)
Val = DefaultLvalueConversion(Val).get();
if (Val) {
if (Enum->isDependentType() || Val->isTypeDependent() ||
Val->containsErrors())
EltTy = Context.DependentTy;
else {
if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
EltTy = Enum->getIntegerType();
ExprResult Converted =
CheckConvertedConstantExpression(Val, EltTy, EnumVal,
CCEK_Enumerator);
if (Converted.isInvalid())
Val = nullptr;
else
Val = Converted.get();
} else if (!Val->isValueDependent() &&
!(Val =
VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
.get())) {
} else {
if (Enum->isComplete()) {
EltTy = Enum->getIntegerType();
if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
if (Context.getTargetInfo()
.getTriple()
.isWindowsMSVCEnvironment()) {
Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
} else {
Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
}
}
Val = ImpCastExprToType(Val, EltTy,
EltTy->isBooleanType() ? CK_IntegralToBoolean
: CK_IntegralCast)
.get();
} else if (getLangOpts().CPlusPlus) {
EltTy = Val->getType();
} else {
if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
Diag(IdLoc, diag::ext_enum_value_not_int)
<< toString(EnumVal, 10) << Val->getSourceRange()
<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());
else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
}
EltTy = Val->getType();
}
}
}
}
if (!Val) {
if (Enum->isDependentType())
EltTy = Context.DependentTy;
else if (!LastEnumConst) {
if (Enum->isFixed()) {
EltTy = Enum->getIntegerType();
}
else {
EltTy = Context.IntTy;
}
} else {
EnumVal = LastEnumConst->getInitVal();
++EnumVal;
EltTy = LastEnumConst->getType();
if (EnumVal < LastEnumConst->getInitVal()) {
QualType T = getNextLargerIntegralType(Context, EltTy);
if (T.isNull() || Enum->isFixed()) {
EnumVal = LastEnumConst->getInitVal();
EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
++EnumVal;
if (Enum->isFixed())
Diag(IdLoc, diag::err_enumerator_wrapped)
<< toString(EnumVal, 10)
<< EltTy;
else
Diag(IdLoc, diag::ext_enumerator_increment_too_large)
<< toString(EnumVal, 10);
} else {
EltTy = T;
}
EnumVal = LastEnumConst->getInitVal();
EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
++EnumVal;
if (!getLangOpts().CPlusPlus && !T.isNull())
Diag(IdLoc, diag::warn_enum_value_overflow);
} else if (!getLangOpts().CPlusPlus &&
!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
Diag(IdLoc, diag::ext_enum_value_not_int)
<< toString(EnumVal, 10) << 1;
}
}
}
if (!EltTy->isDependentType()) {
EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
}
return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Val, EnumVal);
}
Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc) {
if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
!getLangOpts().CPlusPlus)
return SkipBodyInfo();
NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
forRedeclarationInCurContext());
auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
if (!PrevECD)
return SkipBodyInfo();
EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
NamedDecl *Hidden;
if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
SkipBodyInfo Skip;
Skip.Previous = Hidden;
return Skip;
}
return SkipBodyInfo();
}
Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val) {
EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
EnumConstantDecl *LastEnumConst =
cast_or_null<EnumConstantDecl>(lastEnumConst);
S = getNonFieldDeclScope(S);
LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
LookupName(R, S);
NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
if (PrevDecl && PrevDecl->isTemplateParameter()) {
DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
PrevDecl = nullptr;
}
if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
DeclarationNameInfo(Id, IdLoc));
EnumConstantDecl *New =
CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
if (!New)
return nullptr;
if (PrevDecl) {
if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
CheckShadow(New, PrevDecl, R);
}
assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!");
if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
if (isa<EnumConstantDecl>(PrevDecl))
Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
else
Diag(IdLoc, diag::err_redefinition) << Id;
notePreviousDefinition(PrevDecl, IdLoc);
return nullptr;
}
}
ProcessDeclAttributeList(S, New, Attrs);
AddPragmaAttributes(S, New);
New->setAccess(TheEnumDecl->getAccess());
PushOnScopeChains(New, S);
ActOnDocumentableDecl(New);
return New;
}
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
Expr *InitExpr = ECD->getInitExpr();
if (!InitExpr)
return true;
InitExpr = InitExpr->IgnoreImpCasts();
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
if (!BO->isAdditiveOp())
return true;
IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
if (!IL)
return true;
if (IL->getValue() != 1)
return true;
InitExpr = BO->getLHS();
}
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
if (!DRE)
return true;
EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
if (!EnumConstant)
return true;
if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
Enum)
return true;
return false;
}
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
EnumDecl *Enum, QualType EnumType) {
if (!Enum->getIdentifier())
return;
if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
return;
if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
return;
typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
auto EnumConstantToKey = [](const EnumConstantDecl *D) {
llvm::APSInt Val = D->getInitVal();
return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
};
DuplicatesVector DupVector;
ValueToVectorMap EnumMap;
for (auto *Element : Elements) {
EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
if (!ECD) {
return;
}
if (ECD->getInitExpr())
continue;
EnumMap.insert({EnumConstantToKey(ECD), ECD});
}
if (EnumMap.size() == 0)
return;
for (auto *Element : Elements) {
EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
if (!ValidDuplicateEnum(ECD, Enum))
continue;
auto Iter = EnumMap.find(EnumConstantToKey(ECD));
if (Iter == EnumMap.end())
continue;
DeclOrVector& Entry = Iter->second;
if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
if (D == ECD)
continue;
auto Vec = std::make_unique<ECDVector>();
Vec->push_back(D);
Vec->push_back(ECD);
Entry = Vec.get();
DupVector.emplace_back(std::move(Vec));
continue;
}
ECDVector *Vec = Entry.get<ECDVector*>();
if (*Vec->begin() == ECD)
continue;
Vec->push_back(ECD);
}
for (const auto &Vec : DupVector) {
assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
auto *FirstECD = Vec->front();
S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
<< FirstECD << toString(FirstECD->getInitVal(), 10)
<< FirstECD->getSourceRange();
for (auto *ECD : llvm::drop_begin(*Vec))
S.Diag(ECD->getLocation(), diag::note_duplicate_element)
<< ECD << toString(ECD->getInitVal(), 10)
<< ECD->getSourceRange();
}
}
bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const {
assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
assert(ED->isCompleteDefinition() && "expected enum definition");
auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
llvm::APInt &FlagBits = R.first->second;
if (R.second) {
for (auto *E : ED->enumerators()) {
const auto &EVal = E->getInitVal();
if (EVal.isPowerOf2())
FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
}
}
llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
}
void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attrs) {
EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
QualType EnumType = Context.getTypeDeclType(Enum);
ProcessDeclAttributeList(S, Enum, Attrs);
if (Enum->isDependentType()) {
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
EnumConstantDecl *ECD =
cast_or_null<EnumConstantDecl>(Elements[i]);
if (!ECD) continue;
ECD->setType(EnumType);
}
Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
return;
}
unsigned IntWidth = Context.getTargetInfo().getIntWidth();
unsigned CharWidth = Context.getTargetInfo().getCharWidth();
unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
unsigned NumNegativeBits = 0;
unsigned NumPositiveBits = 0;
for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
EnumConstantDecl *ECD =
cast_or_null<EnumConstantDecl>(Elements[i]);
if (!ECD) continue;
const llvm::APSInt &InitVal = ECD->getInitVal();
if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
unsigned ActiveBits = InitVal.getActiveBits();
NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
} else {
NumNegativeBits = std::max(NumNegativeBits,
(unsigned)InitVal.getMinSignedBits());
}
}
if (!NumPositiveBits && !NumNegativeBits)
NumPositiveBits = 1;
QualType BestType;
unsigned BestWidth;
QualType BestPromotionType;
bool Packed = Enum->hasAttr<PackedAttr>();
if (LangOpts.ShortEnums)
Packed = true;
if (Enum->isComplete()) {
BestType = Enum->getIntegerType();
if (BestType->isPromotableIntegerType())
BestPromotionType = Context.getPromotedIntegerType(BestType);
else
BestPromotionType = BestType;
BestWidth = Context.getIntWidth(BestType);
}
else if (NumNegativeBits) {
if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
BestType = Context.SignedCharTy;
BestWidth = CharWidth;
} else if (Packed && NumNegativeBits <= ShortWidth &&
NumPositiveBits < ShortWidth) {
BestType = Context.ShortTy;
BestWidth = ShortWidth;
} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
BestType = Context.IntTy;
BestWidth = IntWidth;
} else {
BestWidth = Context.getTargetInfo().getLongWidth();
if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
BestType = Context.LongTy;
} else {
BestWidth = Context.getTargetInfo().getLongLongWidth();
if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Diag(Enum->getLocation(), diag::ext_enum_too_large);
BestType = Context.LongLongTy;
}
}
BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
} else {
if (Packed && NumPositiveBits <= CharWidth) {
BestType = Context.UnsignedCharTy;
BestPromotionType = Context.IntTy;
BestWidth = CharWidth;
} else if (Packed && NumPositiveBits <= ShortWidth) {
BestType = Context.UnsignedShortTy;
BestPromotionType = Context.IntTy;
BestWidth = ShortWidth;
} else if (NumPositiveBits <= IntWidth) {
BestType = Context.UnsignedIntTy;
BestWidth = IntWidth;
BestPromotionType
= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedIntTy : Context.IntTy;
} else if (NumPositiveBits <=
(BestWidth = Context.getTargetInfo().getLongWidth())) {
BestType = Context.UnsignedLongTy;
BestPromotionType
= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
} else {
BestWidth = Context.getTargetInfo().getLongLongWidth();
assert(NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?");
BestType = Context.UnsignedLongLongTy;
BestPromotionType
= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
}
}
for (auto *D : Elements) {
auto *ECD = cast_or_null<EnumConstantDecl>(D);
if (!ECD) continue;
llvm::APSInt InitVal = ECD->getInitVal();
QualType NewTy;
unsigned NewWidth;
bool NewSign;
if (!getLangOpts().CPlusPlus &&
!Enum->isFixed() &&
isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
NewTy = Context.IntTy;
NewWidth = IntWidth;
NewSign = true;
} else if (ECD->getType() == BestType) {
if (getLangOpts().CPlusPlus)
ECD->setType(EnumType);
continue;
} else {
NewTy = BestType;
NewWidth = BestWidth;
NewSign = BestType->isSignedIntegerOrEnumerationType();
}
InitVal = InitVal.extOrTrunc(NewWidth);
InitVal.setIsSigned(NewSign);
ECD->setInitVal(InitVal);
if (ECD->getInitExpr() &&
!Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
ECD->setInitExpr(ImplicitCastExpr::Create(
Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
nullptr, VK_PRValue, FPOptionsOverride()));
if (getLangOpts().CPlusPlus)
ECD->setType(EnumType);
else
ECD->setType(NewTy);
}
Enum->completeDefinition(BestType, BestPromotionType,
NumPositiveBits, NumNegativeBits);
CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
if (Enum->isClosedFlag()) {
for (Decl *D : Elements) {
EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
if (!ECD) continue;
llvm::APSInt InitVal = ECD->getInitVal();
if (InitVal != 0 && !InitVal.isPowerOf2() &&
!IsValueInFlagEnum(Enum, InitVal, true))
Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
<< ECD << Enum;
}
}
if (Enum->hasAttrs())
CheckAlignasUnderalignment(Enum);
}
Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation StartLoc,
SourceLocation EndLoc) {
StringLiteral *AsmString = cast<StringLiteral>(expr);
FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
AsmString, StartLoc,
EndLoc);
CurContext->addDecl(New);
return New;
}
void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation NameLoc,
SourceLocation AliasNameLoc) {
NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
LookupOrdinaryName);
AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
AttributeCommonInfo::AS_Pragma);
AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
Context, AliasName->getName(), true, Info);
if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
if (isDeclExternC(PrevDecl))
PrevDecl->addAttr(Attr);
else
Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
<< (isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
} else
(void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
}
void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
SourceLocation PragmaLoc,
SourceLocation NameLoc) {
Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
if (PrevDecl) {
PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
} else {
(void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
}
}
void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation NameLoc,
SourceLocation AliasNameLoc) {
Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
LookupOrdinaryName);
WeakInfo W = WeakInfo(Name, NameLoc);
if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
if (!PrevDecl->hasAttr<AliasAttr>())
if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
DeclApplyPragmaWeak(TUScope, ND, W);
} else {
(void)WeakUndeclaredIdentifiers[AliasName].insert(W);
}
}
ObjCContainerDecl *Sema::getObjCDeclContext() const {
return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
}
Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
bool Final) {
assert(FD && "Expected non-null FunctionDecl");
if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
return FunctionEmissionStatus::Emitted;
if (FD->isDependentContext())
return FunctionEmissionStatus::TemplateDiscarded;
auto IsEmittedForExternalSymbol = [this, FD]() {
FunctionDecl *Def = FD->getDefinition();
return Def && !isDiscardableGVALinkage(
getASTContext().GetGVALinkageForFunction(Def));
};
if (LangOpts.OpenMPIsDevice) {
Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
if (DevTy)
if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
return FunctionEmissionStatus::OMPDiscarded;
if (isInOpenMPDeclareTargetContext() || DevTy)
if (IsEmittedForExternalSymbol())
return FunctionEmissionStatus::Emitted;
if (Final)
return FunctionEmissionStatus::OMPDiscarded;
} else if (LangOpts.OpenMP > 45) {
Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
if (DevTy)
if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
return FunctionEmissionStatus::OMPDiscarded;
}
if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
return FunctionEmissionStatus::Emitted;
if (LangOpts.CUDA) {
Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
return FunctionEmissionStatus::CUDADiscarded;
if (!LangOpts.CUDAIsDevice &&
(T == Sema::CFT_Device || T == Sema::CFT_Global))
return FunctionEmissionStatus::CUDADiscarded;
if (IsEmittedForExternalSymbol())
return FunctionEmissionStatus::Emitted;
}
return FunctionEmissionStatus::Unknown;
}
bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
IdentifyCUDATarget(Callee) == CFT_Global;
}