This is an archive of the discontinued LLVM Phabricator instance.

[Support] Add a fancy helper function to get a static name for a type.
ClosedPublic

Authored by chandlerc on Feb 24 2016, 1:23 AM.

Details

Summary

This extracts the type name from PRETTY_FUNCTION for compilers that
support it (I've opted Clang, GCC, and ICC into this as I've tested that
they work) and it uses typeid and typeinfo in a pattern that work with
MSVC even without RTTI. The routine falls back gracefully on a stub
"UNKNOWN_TYPE" string with compilers or formats it doesn't understand.

This should be enough for a lot of common cases in LLVM where the real
goal is just to log or print a type name as a debugging aid, and save
a ton of boilerplate in the process.

The design and implementation is based on a bunch of advice and
discussion with Richard Smith and experimenting with most versions of
Clang, GCC, and MSVC 2015. We've also checked that ICC does something
reasonable and I'll watch the build bots for other compilers. It'd be
great if someone could contribute logic for xlC and/or other toolchains.

Comments or suggestions about how to make this better welcome. Hoping to
land this when the bots aren't too busy (which is not tonight with the
llvm.org hiccups) so tossing it out for review.

Diff Detail

Repository
rL LLVM

Event Timeline

chandlerc updated this revision to Diff 48896.Feb 24 2016, 1:23 AM
chandlerc retitled this revision from to [Support] Add a fancy helper function to get a static name for a type..
chandlerc updated this object.
chandlerc added reviewers: bogner, mehdi_amini, rsmith.
chandlerc added a subscriber: llvm-commits.
mehdi_amini accepted this revision.Feb 24 2016, 1:02 PM
mehdi_amini edited edge metadata.

I like how non-intrusive it is on the client! Also how you avoid any macro on the client side! Very clever :)
All the ugliness (because of the lack of compile-time introspection in C++) hidden in a single place is nice.
LGTM.

This revision is now accepted and ready to land.Feb 24 2016, 1:02 PM

How hot is this code?
Your typeid trickery will not melt away at compile time, it will get demangled by the runtime...
IIRC, they have some mechanism to cache the demangled names which means that typeid(T).name() also acquires a lock.

If this is moderately hot, I'd suggest using __FUNCSIG__ for MSVC.
Using __FUNCSIG__ in llvm::getTypeName<int>() would give you:
class llvm::StringRef __cdecl llvm::getTypeName<int>(void)
The type's pretty name can be dug out by looking inside __FUNCSIG__ for llvm::getTypeName< and looking backwards for >.

This revision was automatically updated to reflect the committed changes.