How to create a variable with an initial value in LLVM IR?

Viewed 958

So in LLVM IR we can create a variable giving it the returned value of an instruction:

%1 = mul i32 %A, %B

But how to create a variable giving it an initial value?

It C++ it would be:

int x = 5;

However this kind of initialization seems not allowed in LLVM IR:

%x = i32 5

llc compiler emits an error:

 error: expected instruction opcode
    %x = i32 5
         ^

Does this mean that variables in LLVM IR can only have the returned values of instructions? What if I want to set a variable to some known predefined initial value?

Can it be done without using alloca, without creating a variable on the stack?

2 Answers

One thing you could do is declare a constant global variable and hope that the optimizer will inline each usage of it. It would look something like this:

@var = private constant i32 5

...

%var = load i32, i32* @var

The downside of this, however, is that you would not be able to use %var in constant expressions. It also would not be modifiable, but then, no value in llvm of the form %var is modifiable.

Given that we're working in a static single assign framework, The answer of making it a constant is a good one, since that value is never going to be reassigned anyway.

But if you really want to load a constant value directly into a register in a single instruction without declaring a constant, there is no direct way to do that, but you could simply add a value to 0.

%x = add i32 5, 0
Related