billybob2
billybob2

Reputation: 701

LLVM accessing variables

I know how to store a int variable 'x' in LLVM code, I would use the command:

  store i32 1, i32* %x

If I then want to pull '%x' out and use it in a command such as add, how would I do that?

%Temp1 = add i32 1, %x

Basically asking how to reference the store

Upvotes: 1

Views: 1457

Answers (1)

JKRT
JKRT

Reputation: 1207

As one of the commenters replied the solution is to use the load instruction. When you use the store instruction in LLVM you write to some memory address.

To read the said variable and save it into a virtual register you use the load instruction.

For instance, consider the following function that adds two integers.

define i32 @add(i32, i32) {
  %3 = alloca i32
  %4 = alloca i32
  store i32 %0, i32* %3
  store i32 %1, i32* %4
  %5 = load i32, i32* %3
  %6 = load i32, i32* %4
  %7 = add i32 %5, %6
  ret i32 %7
}

The first two lines allocate memory on the stack for two integers that are four bytes in size. We then write the value of the function arguments to these locations. Before we can use add we load these two variables from memory into the virtual registers %5 and %6. The add instruction is then executed, with the result assigned to the virtual register %7.

We then return the result of the computation using the ret instruction which is also the only terminator of the single basic block that makes up this example function.

Upvotes: 1

Related Questions