[LLVMdev] Unused malloc/free don't get optimized

Nick Lewycky nicholas at mxc.ca
Fri Feb 16 20:29:09 PST 2007

Reid Spencer wrote:
> On Wed, 2007-02-14 at 18:54 +0100, Nicola Lugato wrote:
>>I've made some other test and it looks like it don't remove even
>>simple malloc/free couple. Maybe there's something wrong in the way i
>>use the opt command.
> No, there's not. LLVM doesn't provide the transform you want. As Chris
> mentioned, if you open a Bugzilla report (http://llvm.org/bugs) and ask
> for the feature we are more likely to get it done than if you don't.

That's surprising to me. I thought there was a pass that converts
malloc's that trivially dominate all free's and whose pointer doesn't
escape would be lowered to alloca's -- but I looked and couldn't find one.

Why isn't there one? Because it wouldn't be profitable? Or because the
alias analysis is too complex? Or just because nobody's gotten to it yet?

I would've thought that this pattern would occur rather often. I know
I've written code that strdup's a value, reads/writes it, then frees it.
After inlining the strdup, changing the malloc/free to alloca should be

That said, you'd have to be careful to ensure that the malloc-free pair
isn't inside of a loop before converting it to alloca. Regardless, I'd
be interested in implementing this in a pass if noone else does.

Nick Lewycky

More information about the llvm-dev mailing list