LLVM 'while' statement IR seems correct but has segmentation fault

Hello, I am a llvm beginner. I recently try to run my own toy-c-compiler project but when I test ‘while’ statement, I find that it produces seemingly right IR codes but is unable to finish my “make run” command.
Here are my test codes and corresponding llvm IR and errors.

Test Code
extern void printi(int n); 
extern void scanfi(int* intaddr);

int main(){
    int a = 1;
    int b = 2; 
    return 0; 

llvm IR
; ModuleID = 'main'
source_filename = "main"

declare i32 @printf(ptr, ...)

declare i32 @scanf(ptr, ...)

declare void @printi(i32)

declare void @scanfi(ptr)

define i32 @main() {
  %a = alloca i32, align 4, addrspace(4)
  store i32 1, ptr addrspace(4) %a, align 4
  %b = alloca i32, align 4, addrspace(4)
  store i32 2, ptr addrspace(4) %b, align 4
  br label %cond
  %letmp = icmp sle i32 %a1, 10
  %addtmp = add i32 %a4, 1
  br label %merge5

cond:                                             ; preds = %body2, %entry
  %a1 = load i32, ptr addrspace(4) %a, align 4
  br i1 %letmp, label %body2, label %merge5

body2:                                            ; preds = %cond
  %a3 = load i32, ptr addrspace(4) %a, align 4
  %calltmp = call void @printi(i32 %a3)
  %a4 = load i32, ptr addrspace(4) %a, align 4
  store i32 %a4, ptr addrspace(4) %a, align 4
  br label %cond

merge5:                                           ; preds = %entry, %cond
  %calltmp6 = call void @printi(i32 20)
  ret i32 0
make: *** [Makefile:36: run] Segmentation fault (core dumped)

But it cannot run and error with segmentation fault when I use My engine trying to run it:

llvm::ExecutionEngine* EE = llvm::EngineBuilder(std::unique_ptr<llvm::Module>(_module)).create();
    std::vector<llvm::GenericValue> noargs;
    llvm::GenericValue v = EE->runFunction(_module->getFunction("main"), noargs);

I don’t know where the problem is and I want to find a solution to debug my codes. Thank you in advance!

This code is dead, and %a1 and %a4 are not yet defined

This is unused

This is reading from the never-initialised %letemp (since the code is dead), but even if it was initialised, you’re not recomputing the value on every iteration so you’ll end up with a loop that either never runs or runs forever

Assigning void to a value?

I suggest you run your IR through the IR verifier, and maybe use an assertions build of LLVM for debugging so it stops you creating nonsense IR in the first place.

Thank you for your suggestion :smiley: :nerd_face: