Skip to content

Commit f9b9431

Browse files
committed
[Clang] Add __common_type builtin
1 parent 7e2b5e2 commit f9b9431

File tree

16 files changed

+511
-126
lines changed

16 files changed

+511
-126
lines changed

clang/include/clang/AST/ASTContext.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
399399
/// The identifier '__type_pack_element'.
400400
mutable IdentifierInfo *TypePackElementName = nullptr;
401401

402+
/// The identifier '__common_type'.
403+
mutable IdentifierInfo *CommonTypeName = nullptr;
404+
402405
QualType ObjCConstantStringType;
403406
mutable RecordDecl *CFConstantStringTagDecl = nullptr;
404407
mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
@@ -606,6 +609,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
606609
mutable ExternCContextDecl *ExternCContext = nullptr;
607610
mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
608611
mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
612+
mutable BuiltinTemplateDecl *CommonTypeDecl = nullptr;
609613

610614
/// The associated SourceManager object.
611615
SourceManager &SourceMgr;
@@ -1104,6 +1108,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
11041108
ExternCContextDecl *getExternCContextDecl() const;
11051109
BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
11061110
BuiltinTemplateDecl *getTypePackElementDecl() const;
1111+
BuiltinTemplateDecl *getCommonTypeDecl() const;
11071112

11081113
// Builtin Types.
11091114
CanQualType VoidTy;
@@ -1981,6 +1986,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
19811986
return TypePackElementName;
19821987
}
19831988

1989+
IdentifierInfo *getCommonTypeName() const {
1990+
if (!CommonTypeName)
1991+
CommonTypeName = &Idents.get("__common_type");
1992+
return CommonTypeName;
1993+
}
1994+
19841995
/// Retrieve the Objective-C "instancetype" type, if already known;
19851996
/// otherwise, returns a NULL type;
19861997
QualType getObjCInstanceType() {

clang/include/clang/AST/DeclID.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,9 @@ enum PredefinedDeclIDs {
8484

8585
/// The internal '__type_pack_element' template.
8686
PREDEF_DECL_TYPE_PACK_ELEMENT_ID = 17,
87+
88+
/// The internal '__common_type' template.
89+
PREDEF_DECL_COMMON_TYPE_ID = 17,
8790
};
8891

8992
/// The number of declaration IDs that are predefined.

clang/include/clang/Basic/Builtins.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,10 @@ enum BuiltinTemplateKind : int {
304304
BTK__make_integer_seq,
305305

306306
/// This names the __type_pack_element BuiltinTemplateDecl.
307-
BTK__type_pack_element
307+
BTK__type_pack_element,
308+
309+
/// This names the __common_type BuiltinTemplateDecl.
310+
BTK__common_type,
308311
};
309312

310313
} // end namespace clang

clang/include/clang/Sema/Sema.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2282,6 +2282,10 @@ class Sema final : public SemaBase {
22822282
/// Check to see if a given expression could have '.c_str()' called on it.
22832283
bool hasCStrMethod(const Expr *E);
22842284

2285+
// Check whether a type member 'Type::Name' exists, and if yes, return the
2286+
// type. If there is no type, the QualType is null
2287+
QualType getTypeMember(StringRef Name, QualType Type);
2288+
22852289
/// Diagnose pointers that are always non-null.
22862290
/// \param E the expression containing the pointer
22872291
/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is

clang/lib/AST/ASTContext.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1170,6 +1170,14 @@ ASTContext::getTypePackElementDecl() const {
11701170
return TypePackElementDecl;
11711171
}
11721172

1173+
BuiltinTemplateDecl *
1174+
ASTContext::getCommonTypeDecl() const {
1175+
if (!CommonTypeDecl)
1176+
CommonTypeDecl =
1177+
buildBuiltinTemplateDecl(BTK__common_type, getCommonTypeName());
1178+
return CommonTypeDecl;
1179+
}
1180+
11731181
RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
11741182
RecordDecl::TagKind TK) const {
11751183
SourceLocation Loc;

clang/lib/AST/ASTImporter.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5408,6 +5408,9 @@ ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
54085408
case BuiltinTemplateKind::BTK__type_pack_element:
54095409
ToD = Importer.getToContext().getTypePackElementDecl();
54105410
break;
5411+
case BuiltinTemplateKind::BTK__common_type:
5412+
ToD = Importer.getToContext().getCommonTypeDecl();
5413+
break;
54115414
}
54125415
assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
54135416
Importer.MapImported(D, ToD);

clang/lib/AST/DeclTemplate.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1599,13 +1599,66 @@ createTypePackElementParameterList(const ASTContext &C, DeclContext *DC) {
15991599
nullptr);
16001600
}
16011601

1602+
static TemplateParameterList *createCommonTypeList(const ASTContext &C,
1603+
DeclContext *DC) {
1604+
// class... Args
1605+
auto *Args = TemplateTypeParmDecl::Create(
1606+
C, DC, {}, {}, /*Depth=*/1, /*Position=*/0, /*Id=*/nullptr,
1607+
/*Typename=*/false, /*ParameterPack=*/true);
1608+
Args->setImplicit();
1609+
1610+
// <class... Args>
1611+
auto *BaseTemplateList =
1612+
TemplateParameterList::Create(C, {}, {}, Args, {}, nullptr);
1613+
1614+
// template <class... Args> class BaseTemplate
1615+
auto *BaseTemplate = TemplateTemplateParmDecl::Create(
1616+
C, DC, {}, /*Depth=*/0, /*Position=*/0, /*ParameterPack=*/false, {},
1617+
/*Typename=*/false, BaseTemplateList);
1618+
1619+
// class TypeMember
1620+
auto *TypeMember = TemplateTypeParmDecl::Create(
1621+
C, DC, {}, {}, /*Depth=*/1, /*Position=*/0, /*Id=*/nullptr,
1622+
/*Typename=*/false, /*ParameterPack=*/false);
1623+
1624+
// <class TypeMember>
1625+
auto *HasTypeMemberList =
1626+
TemplateParameterList::Create(C, {}, {}, TypeMember, {}, nullptr);
1627+
1628+
// template <class TypeMember> class HasTypeMember
1629+
auto *HasTypeMember =
1630+
TemplateTemplateParmDecl::Create(C, DC, {}, /*Depth=*/0, /*Position=*/1,
1631+
/*ParameterPack=*/false, {},
1632+
/*Typename=*/false, HasTypeMemberList);
1633+
1634+
// class HasNoTypeMember
1635+
auto *HasNoTypeMember = TemplateTypeParmDecl::Create(
1636+
C, DC, {}, {}, /*Depth=*/0, /*Position=*/2, /*Id=*/nullptr,
1637+
/*Typename=*/false, /*ParameterPack=*/false);
1638+
1639+
// class... Ts
1640+
auto *Ts = TemplateTypeParmDecl::Create(
1641+
C, DC, {}, {}, /*Depth=*/0, /*Position=*/3,
1642+
/*Id=*/nullptr, /*Typename=*/false, /*ParameterPack=*/true);
1643+
Ts->setImplicit();
1644+
1645+
// template <template <class... Args> class BaseTemplate,
1646+
// template <class TypeMember> class HasTypeMember, class HasNoTypeMember,
1647+
// class... Ts>
1648+
return TemplateParameterList::Create(
1649+
C, {}, {}, {BaseTemplate, HasTypeMember, HasNoTypeMember, Ts}, {},
1650+
nullptr);
1651+
}
1652+
16021653
static TemplateParameterList *createBuiltinTemplateParameterList(
16031654
const ASTContext &C, DeclContext *DC, BuiltinTemplateKind BTK) {
16041655
switch (BTK) {
16051656
case BTK__make_integer_seq:
16061657
return createMakeIntegerSeqParameterList(C, DC);
16071658
case BTK__type_pack_element:
16081659
return createTypePackElementParameterList(C, DC);
1660+
case BTK__common_type:
1661+
return createCommonTypeList(C, DC);
16091662
}
16101663

16111664
llvm_unreachable("unhandled BuiltinTemplateKind!");

clang/lib/Lex/PPMacroExpansion.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1822,6 +1822,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
18221822
// Report builtin templates as being builtins.
18231823
.Case("__make_integer_seq", getLangOpts().CPlusPlus)
18241824
.Case("__type_pack_element", getLangOpts().CPlusPlus)
1825+
.Case("__common_type", getLangOpts().CPlusPlus)
18251826
// Likewise for some builtin preprocessor macros.
18261827
// FIXME: This is inconsistent; we usually suggest detecting
18271828
// builtin macros via #ifdef. Don't add more cases here.

clang/lib/Sema/SemaChecking.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6844,6 +6844,14 @@ CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
68446844
return Results;
68456845
}
68466846

6847+
QualType Sema::getTypeMember(StringRef Name, QualType Type) {
6848+
auto Results = CXXRecordMembersNamed<TypeDecl>(Name, *this, Type);
6849+
assert(Results.size() <= 1);
6850+
if (Results.empty())
6851+
return {};
6852+
return Context.getTypeDeclType(*Results.begin());
6853+
}
6854+
68476855
/// Check if we could call '.c_str()' on an object.
68486856
///
68496857
/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't

clang/lib/Sema/SemaLookup.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,10 @@ bool Sema::LookupBuiltin(LookupResult &R) {
932932
R.addDecl(getASTContext().getTypePackElementDecl());
933933
return true;
934934
}
935+
if (II == getASTContext().getCommonTypeName()) {
936+
R.addDecl(getASTContext().getCommonTypeDecl());
937+
return true;
938+
}
935939
}
936940

937941
// Check if this is an OpenCL Builtin, and if so, insert its overloads.

clang/lib/Sema/SemaTemplate.cpp

Lines changed: 153 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3058,6 +3058,136 @@ void Sema::NoteAllFoundTemplates(TemplateName Name) {
30583058
}
30593059
}
30603060

3061+
static std::optional<QualType>
3062+
commonTypeImpl(Sema &S, TemplateName BaseTemplate,
3063+
SourceLocation TemplateLoc, ArrayRef<TemplateArgument> Ts) {
3064+
auto lookUpCommonType = [&](TemplateArgument T1,
3065+
TemplateArgument T2) -> std::optional<QualType> {
3066+
// Don't bother looking for other specializations if both types are
3067+
// builtins - users aren't allowed to specialize for them
3068+
if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3069+
return commonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3070+
3071+
TemplateArgumentListInfo Args;
3072+
Args.addArgument(TemplateArgumentLoc(
3073+
T1, S.Context.getTrivialTypeSourceInfo(T1.getAsType())));
3074+
Args.addArgument(TemplateArgumentLoc(
3075+
T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3076+
QualType BaseTemplateInst =
3077+
S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3078+
if (S.RequireCompleteType(TemplateLoc, BaseTemplateInst,
3079+
diag::err_incomplete_type))
3080+
return std::nullopt;
3081+
if (QualType Type = S.getTypeMember("type", BaseTemplateInst);
3082+
!Type.isNull()) {
3083+
return Type;
3084+
}
3085+
return std::nullopt;
3086+
};
3087+
3088+
// Note A: For the common_type trait applied to a template parameter pack T of
3089+
// types, the member type shall be either defined or not present as follows:
3090+
switch (Ts.size()) {
3091+
3092+
// If sizeof...(T) is zero, there shall be no member type.
3093+
case 0:
3094+
return std::nullopt;
3095+
3096+
// If sizeof...(T) is one, let T0 denote the sole type constituting the
3097+
// pack T. The member typedef-name type shall denote the same type, if any, as
3098+
// common_type_t<T0, T0>; otherwise there shall be no member type.
3099+
case 1:
3100+
return lookUpCommonType(Ts[0], Ts[0]);
3101+
3102+
// If sizeof...(T) is two, let the first and second types constituting T be
3103+
// denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3104+
// as decay_t<T1> and decay_t<T2>, respectively.
3105+
case 2: {
3106+
QualType T1 = Ts[0].getAsType();
3107+
QualType T2 = Ts[1].getAsType();
3108+
QualType D1 = S.BuiltinDecay(T1, {});
3109+
QualType D2 = S.BuiltinDecay(T2, {});
3110+
3111+
// If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3112+
// the same type, if any, as common_type_t<D1, D2>.
3113+
if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2)) {
3114+
return lookUpCommonType(D1, D2);
3115+
}
3116+
3117+
// Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3118+
// denotes a valid type, let C denote that type.
3119+
{
3120+
auto CheckConditionalOperands =
3121+
[&](bool ConstRefQual) -> std::optional<QualType> {
3122+
EnterExpressionEvaluationContext UnevaluatedContext(
3123+
S, Sema::ExpressionEvaluationContext::Unevaluated);
3124+
Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3125+
Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3126+
3127+
// false
3128+
OpaqueValueExpr CondExpr({}, S.Context.BoolTy,
3129+
ExprValueKind::VK_PRValue);
3130+
ExprResult Cond = &CondExpr;
3131+
3132+
// declval<D1>()
3133+
auto EVK = ConstRefQual ? ExprValueKind::VK_LValue
3134+
: ExprValueKind::VK_PRValue;
3135+
if (ConstRefQual) {
3136+
D1.addConst();
3137+
D2.addConst();
3138+
}
3139+
OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3140+
ExprResult LHS = &LHSExpr;
3141+
3142+
// declval<D2>()
3143+
OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3144+
ExprResult RHS = &RHSExpr;
3145+
3146+
ExprValueKind VK = VK_PRValue;
3147+
ExprObjectKind OK = OK_Ordinary;
3148+
3149+
QualType Result =
3150+
S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3151+
3152+
if (Result.isNull() || SFINAE.hasErrorOccurred())
3153+
return std::nullopt;
3154+
return Result;
3155+
};
3156+
3157+
if (auto Res = CheckConditionalOperands(false))
3158+
return Res;
3159+
3160+
// Let:
3161+
// CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3162+
// COND-RES(X, Y) be
3163+
// decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3164+
3165+
// C++20 only
3166+
// Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3167+
// the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3168+
if (!S.Context.getLangOpts().CPlusPlus20)
3169+
return std::nullopt;
3170+
return CheckConditionalOperands(true);
3171+
}
3172+
}
3173+
3174+
// If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3175+
// denote the first, second, and (pack of) remaining types constituting T. Let
3176+
// C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3177+
// a type C, the member typedef-name type shall denote the same type, if any,
3178+
// as common_type_t<C, R...>. Otherwise, there shall be no member type.
3179+
default: {
3180+
std::optional<QualType> Result = Ts[Ts.size() - 1].getAsType();
3181+
for (size_t i = Ts.size() - 1; i != 0; --i) {
3182+
Result = lookUpCommonType(Ts[i - 1].getAsType(), *Result);
3183+
if (!Result)
3184+
return std::nullopt;
3185+
}
3186+
return Result;
3187+
}
3188+
}
3189+
}
3190+
30613191
static QualType
30623192
checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
30633193
ArrayRef<TemplateArgument> Converted,
@@ -3114,7 +3244,7 @@ checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
31143244
TemplateLoc, SyntheticTemplateArgs);
31153245
}
31163246

3117-
case BTK__type_pack_element:
3247+
case BTK__type_pack_element: {
31183248
// Specializations of
31193249
// __type_pack_element<Index, T_1, ..., T_N>
31203250
// are treated like T_Index.
@@ -3140,6 +3270,28 @@ checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
31403270
int64_t N = Index.getExtValue();
31413271
return Ts.getPackAsArray()[N].getAsType();
31423272
}
3273+
3274+
case BTK__common_type:
3275+
assert(Converted.size() == 4);
3276+
if (Converted[0].isDependent() || Converted[1].isDependent() ||
3277+
Converted[2].isDependent() || Converted[3].isDependent())
3278+
return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3279+
Converted);
3280+
3281+
TemplateName BaseTemplate = Converted[0].getAsTemplate();
3282+
TemplateName HasTypeMember = Converted[1].getAsTemplate();
3283+
QualType HasNoTypeMember = Converted[2].getAsType();
3284+
ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3285+
if (auto CT = commonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts)) {
3286+
TemplateArgumentListInfo TAs;
3287+
TAs.addArgument(TemplateArgumentLoc(
3288+
TemplateArgument(*CT), SemaRef.Context.getTrivialTypeSourceInfo(
3289+
*CT, TemplateArgs[1].getLocation())));
3290+
3291+
return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3292+
}
3293+
return HasNoTypeMember;
3294+
}
31433295
llvm_unreachable("unexpected BuiltinTemplateDecl!");
31443296
}
31453297

clang/test/AST/Interp/crash-GH49103-2.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
// https://github.com/llvm/llvm-project/issues/49103
1010

1111
template<class> struct A; // expected-note 0+ {{}}
12-
struct S : __make_integer_seq<A, int, 42> { }; // expected-error 0+ {{}}
13-
S s;
12+
struct NoCommonType : __make_integer_seq<A, int, 42> { }; // expected-error 0+ {{}}
13+
NoCommonType s;

clang/test/SemaCXX/crash-GH49103-2.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
// https://github.com/llvm/llvm-project/issues/49103
1010

1111
template<class> struct A; // expected-note 0+ {{}}
12-
struct S : __make_integer_seq<A, int, 42> { }; // expected-error 0+ {{}}
13-
S s;
12+
struct NoCommonType : __make_integer_seq<A, int, 42> { }; // expected-error 0+ {{}}
13+
NoCommonType s;

0 commit comments

Comments
 (0)