How to add conditional branch instruction without else option?

131 Views Asked by At

I am trying get my IR to look like below. Is it possible to achieve this in LLVM?

entry:
 %2 = call i32 @func()
 %3 = icmp ne i32 %2, 0, !dbg
  br i1 %3, label %if.then.block

  call void @abc()
  ret void

if.then.block:
  ; Insert instructions for the "if.then.block"
  ; ...

  ret void

I tried an approach which gave my branch instruction with a else block for false case. I am not looking for that.

2

There are 2 best solutions below

0
sepp2k On

You can't do that.

The whole point of a basic block is that there's no (local) control flow inside of it. You can jump to the beginning of a block and you can jump out of it at the very end through the single terminator instruction. Between that it's just a linear sequence of instructions.

So not only can't you have a conditional branch with only one target, you also can't further instructions in the same block following the branch. The branch terminates the block.

0
kamkow1 On

I've encountered a similar problem when creating my compiler. You can check if there's an else block available in your parse tree. If it's not, then you still emit the else branch but leave it empty and just terminate it with a branch to a merging block. Here's an example:

...
  br i1 %15, label %then, label %else

then:                                             ; preds = %entry
  ret i32 55

else:                                             ; preds = %entry
  br label %merge ; no else block in original source code, so we just jump into merge block

merge:                                            ; preds = %else
  %16 = alloca i32, align 4
  store i32 44, ptr %16, align 4
  ret i32 2