Problem while using mem2reg Optimization

Hi,

I am using various LLVM optimization passes and I noticed a strange behaviour in Mem2Reg Optimization. These pass is used for SSA construction and basically removed alloca of the corresponding pointers are just used in load/stores.

I tried the following .ll file

define i32 @test(i32 %y,i32 %z) {
entry:
%X = alloca i32 ; type of %X is i32*.
%X.0 = add i32 %y ,%z
store i32 %X.0, i32* %X ; Update X
br label %cond_next

cond_next:
%tmp1 = alloca i32
%tmp2 = sub i32 %y, 3
store i32 %tmp2,i32* %tmp1
ret i32 0
}

I tried the Mem2Reg pass on above file and I got following output:

; ModuleID = ‘test4.bc’
define i32 @test(i32 %y, i32 %z) {
entry:
%X.0 = add i32 %y, %z ; [#uses=0]
br label %cond_next

cond_next: ; preds = %entry
%tmp1 = alloca i32 ; <i32*> [#uses=1]
%tmp2 = sub i32 %y, 3 ; [#uses=1]
store i32 %tmp2, i32* %tmp1
ret i32 0
}

So, it removed the alloca from first basic block and not from others. If I remove the alloca from cond_next basic block and instead put that also in first Basic Block, the mem2Reg optimizes this and I get following output

; ModuleID = ‘test4.bc’
define i32 @test(i32 %y, i32 %z) {
entry:
%X.0 = add i32 %y, %z ; [#uses=0]
br label %cond_next
cond_next: ; preds = %entry
%tmp2 = sub i32 %y, 3 ; [#uses=0]
ret i32 0
}

So, is there any restriction that all the alloca should be put in first basic block?

Thanks

Kapil

Yes, there is exactly such a restriction;
http://llvm.org/docs/tutorial/LangImpl7.html has a good description of
using mem2reg for SSA construction.

-Eli

Yes, there is exactly such a restriction;
http://llvm.org/docs/tutorial/LangImpl7.html has a good description of
using mem2reg for SSA construction.

From that page:
"mem2reg only looks for alloca instructions in the entry block of the
function. Being in the entry block guarantees that the alloca is only executed
once, which makes analysis simpler."

I was thinking you could just move any alloca to the entry block for free, but
I hadn't considered looping.

Gr.

Matthijs