Macros

Constant Macro Expressions

The simplest form of the macro is an expression. For example:

macro expr DATA_WIDTH = 15;
int DATA_WIDTH x;

This form of the macro is similar to the #define macro. Whenever DATA_WIDTH appears in the program, the constant 15 is inserted in its place. More generally, real expressions can be used. For example:

macro expr sum = (x + y) @ (y + z);
v = sum;
w = sum;

 

Macro Procedures

Macros may be used to replace statements to avoid tedious repetition. Handel-C provides simple macro constructs to expand single statements into complex blocks of code. The general syntax of macro procedures is:

macro proc Name(Params) Statement

For example:

macro proc output(x, y)
{
out ! x; out ! y;
}

output(a + b, c * d);
output(a + b, c * d);

 

Parametrised Macro Expressions

Handel-C also allows macros with parameters. For example:

macro expr add3(x) = x + 3;
y = add3(z);

This is equivalent to the following code:

y = z + 3;

 

Select Operator

Handel-C provides a select(...)operator which is used to mean ‘select at compile time’. Its general usage is:

select(Expression, Expression if True, Expression if False)

The first expression must be a compile time constant. If the first expression evaluates to true then the Handel-C compiler replaces the whole expression with the second expression. If the first expression evaluates to false then the Handel-C compiler replaces it with the third expression.

A more useful example can be seen when macros are combined with this feature. For example:

macro expr adjust(x, n) =
     select(width(x) < n, (0 @ x), (x <- n));

unsigned 4 a;
unsigned 5 b;
unsigned 6 c;
b = adjust(a, width(b));
b = adjust(c, width(b));

This example is for a macro that equalises widths of variables in an assignment.

 

Shared Expressions

The shared expression allows hardware to be shared between different parts of the program to decrease hardware usage. The shared expression has the same format as a macro expression but does not allow recursion. An example program where shared expressions are extremely useful is:

shared expr mult(x, y) = x * y;
a = mult(b, c);
d = mult(e, f);
g = mult(h, i);

In this example, only one multiplier is built and it is used on every clock cycle. This is more efficient use of hardware.