Skip to content

[Clang] Add __builtin_common_type #99473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions clang/docs/LanguageExtensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1511,6 +1511,46 @@ Attributes (N2335) C2
``#embed`` (N3017) C23 C89, C++
============================================ ================================ ============= =============

Builtin type aliases
====================

Clang provides a few builtin aliases to improve the throughput of certain metaprogramming facilities.

__common_type
-------------

.. code-block:: c++

template <template <class... Args> class BaseTemplate,
template <class TypeMember> class HasTypeMember,
class HasNoTypeMember,
class... Ts>
using __common_type = ...;

This alias is used for implementing ``std::common_type``. If ``std::common_type`` should contain a ``type`` member,
it is an alias to ``HasTypeMember<TheCommonType>``. Otherwise it is an alias to ``HasNoTypeMember``. The
``BaseTemplate`` is usually ``std::common_type``. ``Ts`` are the arguments to ``std::common_type``.

__type_pack_element
-------------------

.. code-block:: c++

template <std::size_t Index, class... Ts>
using __type_pack_element = ...;

This alias returns the type at ``Index`` in the parameter pack ``Ts``.

__make_integer_seq
------------------

.. code-block:: c++

template <template <class IntSeqT, IntSeqT... Ints> class IntSeq, class T, T N>
using __make_integer_seq = ...;

This alias returns ``IntSeq`` instantiated with ``IntSeqT = T``and ``Ints`` being the pack ``0, ..., N - 1``.

Type Trait Primitives
=====================

Expand Down
5 changes: 4 additions & 1 deletion clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ sections with improvements to Clang's support for those languages.
C++ Language Changes
--------------------

- The builtin type alias ``__common_type`` has been added to improve the
performance of ``std::common_type``.

C++17 Feature Support
^^^^^^^^^^^^^^^^^^^^^

Expand Down Expand Up @@ -117,7 +120,7 @@ Improvements to Clang's diagnostics
- Some template related diagnostics have been improved.

.. code-block:: c++

void foo() { template <typename> int i; } // error: templates can only be declared in namespace or class scope

struct S {
Expand Down
11 changes: 11 additions & 0 deletions clang/include/clang/AST/ASTContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,9 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// The identifier '__type_pack_element'.
mutable IdentifierInfo *TypePackElementName = nullptr;

/// The identifier '__common_type'.
mutable IdentifierInfo *CommonTypeName = nullptr;

QualType ObjCConstantStringType;
mutable RecordDecl *CFConstantStringTagDecl = nullptr;
mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
Expand Down Expand Up @@ -606,6 +609,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
mutable ExternCContextDecl *ExternCContext = nullptr;
mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
mutable BuiltinTemplateDecl *CommonTypeDecl = nullptr;

/// The associated SourceManager object.
SourceManager &SourceMgr;
Expand Down Expand Up @@ -1113,6 +1117,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
ExternCContextDecl *getExternCContextDecl() const;
BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
BuiltinTemplateDecl *getTypePackElementDecl() const;
BuiltinTemplateDecl *getCommonTypeDecl() const;

// Builtin Types.
CanQualType VoidTy;
Expand Down Expand Up @@ -1990,6 +1995,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
return TypePackElementName;
}

IdentifierInfo *getCommonTypeName() const {
if (!CommonTypeName)
CommonTypeName = &Idents.get("__common_type");
return CommonTypeName;
}

/// Retrieve the Objective-C "instancetype" type, if already known;
/// otherwise, returns a NULL type;
QualType getObjCInstanceType() {
Expand Down
5 changes: 4 additions & 1 deletion clang/include/clang/AST/DeclID.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,16 @@ enum PredefinedDeclIDs {

/// The internal '__type_pack_element' template.
PREDEF_DECL_TYPE_PACK_ELEMENT_ID = 17,

/// The internal '__common_type' template.
PREDEF_DECL_COMMON_TYPE_ID = 18,
};

/// The number of declaration IDs that are predefined.
///
/// For more information about predefined declarations, see the
/// \c PredefinedDeclIDs type and the PREDEF_DECL_*_ID constants.
const unsigned int NUM_PREDEF_DECL_IDS = 18;
const unsigned int NUM_PREDEF_DECL_IDS = 19;

/// GlobalDeclID means DeclID in the current ASTContext and LocalDeclID means
/// DeclID specific to a certain ModuleFile. Specially, in ASTWriter, the
Expand Down
5 changes: 4 additions & 1 deletion clang/include/clang/Basic/Builtins.h
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,10 @@ enum BuiltinTemplateKind : int {
BTK__make_integer_seq,

/// This names the __type_pack_element BuiltinTemplateDecl.
BTK__type_pack_element
BTK__type_pack_element,

/// This names the __common_type BuiltinTemplateDecl.
BTK__common_type,
};

} // end namespace clang
Expand Down
4 changes: 4 additions & 0 deletions clang/include/clang/Sema/Sema.h
Original file line number Diff line number Diff line change
Expand Up @@ -2282,6 +2282,10 @@ class Sema final : public SemaBase {
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);

// Check whether a type member 'Type::Name' exists, and if yes, return the
// type. If there is no type, the QualType is null
QualType getTypeMember(QualType Type, StringRef Name);

/// Diagnose pointers that are always non-null.
/// \param E the expression containing the pointer
/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
Expand Down
7 changes: 7 additions & 0 deletions clang/lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,13 @@ ASTContext::getTypePackElementDecl() const {
return TypePackElementDecl;
}

BuiltinTemplateDecl *ASTContext::getCommonTypeDecl() const {
if (!CommonTypeDecl)
CommonTypeDecl =
buildBuiltinTemplateDecl(BTK__common_type, getCommonTypeName());
return CommonTypeDecl;
}

RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
RecordDecl::TagKind TK) const {
SourceLocation Loc;
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/AST/ASTImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5413,6 +5413,9 @@ ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
case BuiltinTemplateKind::BTK__type_pack_element:
ToD = Importer.getToContext().getTypePackElementDecl();
break;
case BuiltinTemplateKind::BTK__common_type:
ToD = Importer.getToContext().getCommonTypeDecl();
break;
}
assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
Importer.MapImported(D, ToD);
Expand Down
56 changes: 56 additions & 0 deletions clang/lib/AST/DeclTemplate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1608,13 +1608,69 @@ createTypePackElementParameterList(const ASTContext &C, DeclContext *DC) {
nullptr);
}

static TemplateParameterList *createCommonTypeList(const ASTContext &C,
DeclContext *DC) {
// class... Args
auto *Args =
TemplateTypeParmDecl::Create(C, DC, SourceLocation(), SourceLocation(),
/*Depth=*/1, /*Position=*/0, /*Id=*/nullptr,
/*Typename=*/false, /*ParameterPack=*/true);

// <class... Args>
auto *BaseTemplateList = TemplateParameterList::Create(
C, SourceLocation(), SourceLocation(), Args, SourceLocation(), nullptr);

// template <class... Args> class BaseTemplate
auto *BaseTemplate = TemplateTemplateParmDecl::Create(
C, DC, SourceLocation(), /*Depth=*/0, /*Position=*/0,
/*ParameterPack=*/false, /*Id=*/nullptr,
/*Typename=*/false, BaseTemplateList);

// class TypeMember
auto *TypeMember =
TemplateTypeParmDecl::Create(C, DC, SourceLocation(), SourceLocation(),
/*Depth=*/1, /*Position=*/0, /*Id=*/nullptr,
/*Typename=*/false, /*ParameterPack=*/false);

// <class TypeMember>
auto *HasTypeMemberList =
TemplateParameterList::Create(C, SourceLocation(), SourceLocation(),
TypeMember, SourceLocation(), nullptr);

// template <class TypeMember> class HasTypeMember
auto *HasTypeMember = TemplateTemplateParmDecl::Create(
C, DC, SourceLocation(), /*Depth=*/0, /*Position=*/1,
/*ParameterPack=*/false, /*Id=*/nullptr,
/*Typename=*/false, HasTypeMemberList);

// class HasNoTypeMember
auto *HasNoTypeMember = TemplateTypeParmDecl::Create(
C, DC, {}, {}, /*Depth=*/0, /*Position=*/2, /*Id=*/nullptr,
/*Typename=*/false, /*ParameterPack=*/false);

// class... Ts
auto *Ts = TemplateTypeParmDecl::Create(
C, DC, SourceLocation(), SourceLocation(), /*Depth=*/0, /*Position=*/3,
/*Id=*/nullptr, /*Typename=*/false, /*ParameterPack=*/true);

// template <template <class... Args> class BaseTemplate,
// template <class TypeMember> class HasTypeMember, class HasNoTypeMember,
// class... Ts>
return TemplateParameterList::Create(
C, SourceLocation(), SourceLocation(),
{BaseTemplate, HasTypeMember, HasNoTypeMember, Ts}, SourceLocation(),
nullptr);
}

static TemplateParameterList *createBuiltinTemplateParameterList(
const ASTContext &C, DeclContext *DC, BuiltinTemplateKind BTK) {
switch (BTK) {
case BTK__make_integer_seq:
return createMakeIntegerSeqParameterList(C, DC);
case BTK__type_pack_element:
return createTypePackElementParameterList(C, DC);
case BTK__common_type:
return createCommonTypeList(C, DC);
}

llvm_unreachable("unhandled BuiltinTemplateKind!");
Expand Down
1 change: 1 addition & 0 deletions clang/lib/Lex/PPMacroExpansion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1826,6 +1826,7 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
// Report builtin templates as being builtins.
.Case("__make_integer_seq", getLangOpts().CPlusPlus)
.Case("__type_pack_element", getLangOpts().CPlusPlus)
.Case("__common_type", getLangOpts().CPlusPlus)
// Likewise for some builtin preprocessor macros.
// FIXME: This is inconsistent; we usually suggest detecting
// builtin macros via #ifdef. Don't add more cases here.
Expand Down
8 changes: 8 additions & 0 deletions clang/lib/Sema/SemaChecking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6848,6 +6848,14 @@ CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
return Results;
}

QualType Sema::getTypeMember(QualType Type, StringRef Name) {
auto Results = CXXRecordMembersNamed<TypeDecl>(Name, *this, Type);
assert(Results.size() <= 1);
if (Results.empty())
return {};
return Context.getTypeDeclType(*Results.begin());
}

/// Check if we could call '.c_str()' on an object.
///
/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
Expand Down
7 changes: 6 additions & 1 deletion clang/lib/Sema/SemaLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -928,10 +928,15 @@ bool Sema::LookupBuiltin(LookupResult &R) {
if (II == getASTContext().getMakeIntegerSeqName()) {
R.addDecl(getASTContext().getMakeIntegerSeqDecl());
return true;
} else if (II == getASTContext().getTypePackElementName()) {
}
if (II == getASTContext().getTypePackElementName()) {
R.addDecl(getASTContext().getTypePackElementDecl());
return true;
}
if (II == getASTContext().getCommonTypeName()) {
R.addDecl(getASTContext().getCommonTypeDecl());
return true;
}
}

// Check if this is an OpenCL Builtin, and if so, insert its overloads.
Expand Down
Loading
Loading