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

Jonathan Sauer jonathan.sauer at gmx.de
Fri May 18 10:11:07 PDT 2012


> 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.

Maybe I'm missing something, but constexpr does exactly that:

struct Foo {
  constexpr Foo(int i) : i(i) {}
  Foo(int i, int dummy) : i(i) {}

  int i;

constexpr Foo myFoo = Foo(42);

constexpr Foo myFoo2 = Foo(42, 0);

As only <myFoo>, but not <myFoo2> can be initialized at compile-time, this results in

error: constexpr variable 'myFoo2' must be initialized by a constant expression
 constexpr Foo myFoo2 = Foo(42, 0);
               ^        ~~~~~~~~~~


More information about the cfe-dev mailing list