Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM assembly: assign integer constant to register

I'm writing a compiler that uses LLVM as a backend, and my compiler generates the following LLVM assembly code

@0 = private constant [25 x i8] c"Hello World to %dntegers\00"

declare void @printf (i8*, i32)

define void @main () {
  %1 = getelementptr [25 x i8]* @0, i32 0, i32 0
  %2 = 1
  tail call void @printf(i8* %1, i32 %2)
  ret void
}

But I get the following error:

c.ll:8:8: error: expected instruction opcode
  %2 = 1
       ^

The documentation shows examples like that though.

Do you know how to get this to work? Currently, I'm using instead:

  %2 = add i32 0, 1 ; FIXME
like image 450
Mildred Avatar asked Jun 16 '11 15:06

Mildred


Video Answer


1 Answers

See the LLVMdev discussion "How to assign a constant to a register?" As pointed out there by Duncan Sands:

let me say that in general doing this is pointless. Due to SSA form, if %x is set to 5 you can't set it to something else later. Thus everywhere that you use %x you might as well just directly use 5 there instead. A common situation is that you have a register %x, and due to performing optimizations you discover that in fact %x will always have the value 5. You can use RAUW (aka the replaceAllUsesWith method) to replace %x with 5 everywhere.

The thread did generate a couple alternatives to directly using the constant:

  • Use alloca to get a pointer, store to it, then load the value as needed.
  • Create a global pointing to the constant, then load that value as needed.

Someone pointed out that the alloca approach will end up using a register after optimization.

Regardless, using the constant directly as suggested by @SK-logic seems to be the cleanest solution.

like image 75
Jeremy W. Sherman Avatar answered Oct 28 '22 00:10

Jeremy W. Sherman