How do I eliminate LLVM function calls and replace them with basic instructions?

210 views Asked by At

My Problem

I am new to LLVM and C++.

I am currently creating an LLVM backend compiler and need to replace LLVM function calls with the instructions in its definition. Is there already an existing pass that accomplishes this?

Examples

For example, I have the following C code, compiled to LLVM IR with clang-14 -S -emit-llvm.

int add(int a, int b) {
    return a + b;
}

int main() {
    int a = 10;
    int b = 20;
    int c = add(a, b);
    return c;
}

Then, I get a LLVM IR code below.

define dso_local i32 @add(i32 noundef %a, i32 noundef %b) #0 {
entry:
  %a.addr = alloca i32, align 4
  %b.addr = alloca i32, align 4
  store i32 %a, i32* %a.addr, align 4
  store i32 %b, i32* %b.addr, align 4
  %0 = load i32, i32* %a.addr, align 4
  %1 = load i32, i32* %b.addr, align 4
  %add = add nsw i32 %0, %1
  ret i32 %add
}

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32 @main() #0 {
entry:
  %retval = alloca i32, align 4
  %a = alloca i32, align 4
  %b = alloca i32, align 4
  %c = alloca i32, align 4
  store i32 0, i32* %retval, align 4
  store i32 10, i32* %a, align 4
  store i32 20, i32* %b, align 4
  %0 = load i32, i32* %a, align 4
  %1 = load i32, i32* %b, align 4
  %call = call i32 @add(i32 noundef %0, i32 noundef %1)
  store i32 %call, i32* %c, align 4
  %2 = load i32, i32* %c, align 4
  ret i32 %2
}

I want to replace the function call @add with instructions in it's definition from the code above using opt command, and emit the following new code.

define dso_local i32 @main() #0 {
entry:
  %retval = alloca i32, align 4
  %a = alloca i32, align 4
  %b = alloca i32, align 4
  %c = alloca i32, align 4
  store i32 0, i32* %retval, align 4
  store i32 10, i32* %a, align 4
  store i32 20, i32* %b, align 4
  %0 = load i32, i32* %a, align 4
  %1 = load i32, i32* %b, align 4
  %add = add nsw i32 %0, %1
  store i32 %add, i32* %c, align 4
  %2 = load i32, i32* %c, align 4
  ret i32 %2
}

I searched the following sites for such a path, but could not find one suitable. https://llvm.org/docs/Passes.html#loops-natural-loop-information

0

There are 0 answers