[llvm-dev] LLVM Pass To Remove Dead Code In A Basic Block

Dean Michael Berris via llvm-dev llvm-dev at lists.llvm.org
Sun May 27 03:05:51 PDT 2018



> On 26 May 2018, at 07:24, Aaron <acraft at gmail.com> wrote:
> 
> > I’m just wondering why not have a ‘br’ to an exit basic block instead of ‘ret’ mid-stream of instructions.
> > Have you considered this approach instead?
> 
> Thanks for bringing this up.
> 
> Yes. In fact, I tried that approach/pattern first. Simply, you create default exit block and a local return variable (to track return value) per function, but it requires extra flags and variables to track function exit block and return value anytime during code generation (which my approach does not need to do these). 
> 
> When generating code, every time you see a return instruction, you store return value into that local variable (if it returns a value) and create branch instruction to function's exit block. Then function can generate return instruction by using local return variable or just ret void.
> 
> entry:
>   <this is the entry block>
>   <alloc local return variable>
>   <…>
>   <store return value into local return variable, if returns a value>
>   br .exit
> 
> .bb0:
>   <this is by definition unreachable>
>   <…>
>   <store return value into local return variables, if returns a value>
>   br .exit
> 
> .exit:
>   ret <local return value> OR ret void.
> 
> 
> But this approach still does not resolve the issue I had. Front-end still can create multiple "br" instruction per block. Now we hit the original problem: we can't create multiple terminator instructions in a block.
> 

The way I’ve seen this done, is to use a phi node in the exit block which consolidates all the potential values of the result, with all the potential predecessors contributing to the value marked out.

https://llvm.org/docs/LangRef.html#phi-instruction

That makes it clear that the value being returned can come only specifically from specific basic blocks.

This works really well when you’ve internalised the SSA form that LLVM models.

> One or the other pattern could have advantages based on language spec or the way you implement front-end. Who knows, I may want to return back to this approach in the future if creates better advantages. I'm constantly considering alternatives. The simplest / cleanest design wins.
> 

If you’re looking to use LLVM most effectively, I think it would make sense to see how some of the other front-ends (and the various tutorials out there for using LLVM effectively) do it. In this case, from your front-end it would make sense to identify more granular basic blocks if you can do that. It would also greatly help with the LLVM passes which assume a certain structure.

Cheers

-- Dean



More information about the llvm-dev mailing list