samedi 4 novembre 2017

Make loop variable a constant in C++

I am currently creating arithmetic operators libraries for high level synthesis.

For this, I am also creating a library to manipulate bits and bit vectors like it would be done in VHDL. To make my libraries synthesizable, nearly everything must be resolved at compile time.

However, I have an issue with loops.

Indeed, I would like to be able to write things like that:

const int N = 5;
for(int i = 0; i < N-2; i++) {
    x.bit<i+2>() = x.bit<i>();
}

Of course, it does not compile since i is a variable and not a constant determined at compile time.

However, N being a constant, this code is strictly equivalent to:

x.bit<2>() = x.bit<0>();
x.bit<3>() = x.bit<1>();
x.bit<4>() = x.bit<2>();

which compiles and works perfectly.

Is there a way to make the compiler (gcc in my case) unroll the loop since N is constant? Or to define a macro or a constexpr which could do it with a clean syntax? This would be the equivalent of for generate in VHDL.

Aucun commentaire:

Enregistrer un commentaire