constant folding-like optimization at compile time

Hi everyone!

I am new to llvm and excuse me if this is a wrong question for this forum.

I am trying to design a front end for my own programming language using the LLVM infrastructure for a personal project. It’s a very simple procedural language for now; no object oriented business.

I am playing around with a simple concept and was wondering if it’s possible to implement it in the LLVM environment.

Consider I have a simple declaration statement.

float array a[sqrt(9)];

Is it possible to evaluate “sqrt(9)” before generating LLVM IR by calling some math library function? This is still compile time and way before the JIT kicks in, so I won’t be able to take advantage of the JIT. In other words, the LLVM IRBuilder would probably see something like – “float array a[3];”, and won’t even know that “sqrt(9)” existed. Only my parser would be aware of its existence.

Let me know if this is possible.

Thanks,
Pranav

Of course, but it’s nothing to do with LLVM, it’s purely about normal programming in your front end in whatever language you are using.

Assuming you have some suitable classes defined for your parse tree you’ll write something like this:

if node.type = functionType and
node.fn.name = “sqrt” and
node.fn.args.len = 1 and
node.fn.args[0].isConstant
then
float result = sqrt(node.fn.args[0].constantValue)
replaceNode(node, newLiteralNode(result))
endif

… just using whatever sqrt funtion your programming language has built in.