[cfe-dev] How to create a new builtin in clang?

Andy Gibbs andyg1001 at hotmail.co.uk
Fri May 18 09:12:42 PDT 2012


Hi,

I'd like to learn a little about how clang works on the inside, and would 
like to have a go at implementing a new "builtin" function which forces an 
expression to be folded to a constant.  The idea would be that it would 
either compile-time-evaluate the expression or halt compilation with an 
error.  I believe there isn't anything currently that does this for 
arbitrary types, only integers.

What I envisage is something like...

   auto x = __builtin_fold(<expression>)

which returns a constant value of appropriate type for the expression.

I'd envisage it as a replacement for an already-possible two-step approach 
as follows:

struct __fold_impl_1
    {
    static constexpr auto value = <expression>;
    };

...
auto x = __fold_impl_1::value;

The obvious down-side of the two-step approach is requiring a special macro 
for generating __fold_impl_xxx for each folded expression, plus the 
inconvenience and possible scope problems of having to use such a macro! 
I'd also like it to work in non-C++11 code.

I could imagine that it should be very possible to get clang to generate 
such a struct on-the-fly which avoided the scope problems and substitute the 
expression for a reference to the value.

The questions I have are:

 - how does one go about getting clang to build such substitutiary code in 
this way?

 - is this the best approach, or is there a better/simpler way?

I've been looking into how __builtin_constant_p and __extension__ work, as 
well as the Expr::Evaluate* functions and 
CodeGenFunction::tryEmitAsConstant, but to little gain I'm afraid! ;o)

Many thanks for any and all suggestions

Andy






More information about the cfe-dev mailing list