[LLVMdev] constant expression as initial value to global

Eli Friedman eli.friedman at gmail.com
Sat Nov 17 11:05:47 PST 2012


On Sat, Nov 17, 2012 at 9:10 AM, edA-qa mort-ora-y <eda-qa at disemia.com> wrote:
> How can I go about evaluating constant expressions and providing them as
> the initial value to globals?  I allow my globals to be initialized by
> an expression. In C syntax this looks like:
>         int const global_val = const_expr( 1, 2, 3 );
>
> I use the "const_expr" to indicate construction-time constant folding
> will not be possible. The IR optimizers however will likely reduce this
> to a single value.
>
> My first approach is to simply call a startup function which assigns the
> values (which is also kind of necessary if I don't use the optimization
> passes).

This is the approach C++ uses when the compiler can't constant-fold an
initializer.  If your frontend doesn't actually need to do anything
special with the folded value, this is the way to go.  You might want
to take a look at the code clang generates; the LLVM optimizers know
some special tricks involving "llvm.global_ctors".

> Beyond this I see that I could somehow JIT the const_expr
> results and then stick in the resulting value as the initial value.
>
> Is there an easier way to go about doing this type of initialization? Or
> could somebody explain how the C++11 constexpr support works (since it'd
> be about the same I think).

clang's constexpr support never touches IR; the standard has very
strict requirements of what can and cannot be constexpr-evaluated, so
the logic works directly on the C++ AST.

-Eli



More information about the llvm-dev mailing list