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

Andy Gibbs andyg1001 at hotmail.co.uk
Fri May 18 11:14:17 PDT 2012

On Friday, May 18, 2012 7:11 PM, Jonathan Sauer wrote:

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

It does and it doesn't.  If you declare a variable 'constexpr' then you can 
expect that a compile-time-evaluated constant is assigned to it.  However, a 
'constexpr'-declared variable is forever immutable (which may not be what 
you want) and if you do not declare a variable 'constexpr' then you cannot 
assume it will be given an initial value which is compile-time-evaluated. 
In this way, 'constexpr' can be considered merely a hint to the compiler, 
like 'inline' is: the compiler can choose whether to obey it or not, usually 
depending on the optimisation level.  There is not, as far as I am aware, a 
way within the C++11 standard of actually forcing an expression to be 
evaluated by the compiler, except by tricks.  On such way is as follows:

template <typename T, T Value>
struct Constant {
    static constexpr T value = Value;

#define CONST(X) Constant<decltype(X),(X)>::value

int value = CONST(... some expression ...);

This trick will not work, however, where 'T' is (for example) a double or a 
struct, since you cannot pass such a value as a template parameter.

Using __builtin_constant_p(...), it is possible to test whether an 
expression can be compile-time evaluated, the next logical step would be a 
builtin which returns the result of the evaluation itself.  It would form a 
contract between user and compiler: the user would be sure that as long as 
his code compiles, his expression is evaluated by the compiler and never at 



More information about the cfe-dev mailing list