[LLVMdev] optimization assumes malloc return is non-null

Chris Lattner sabre at nondot.org
Wed Apr 30 19:25:27 PDT 2008


On Wed, 30 Apr 2008, David Vandevoorde wrote:
> Note that more interesting optimizations are possible.  E.g., it's
> perfectly valid to transform:
>
> 	void f(size_t n) {
> 	  char *str = (char*)malloc(n);
> 	  // use str[0 .. 99 ]
> 	  free(str);
> 	}
>
> into
>
> 	void f(size_t n) {
> 	  char *str = (char*)alloca(n);
> 	  // use str[0 .. 99 ]
> 	}
>
> (Can LLVM do that?  Is that maybe why the optimization happens?)

This isn't safe in general unless you can (tightly) bound "n".  You don't 
want to overflow the stack.

We do delete "free(malloc(n))" though.

-Chris

-- 
http://nondot.org/sabre/
http://llvm.org/



More information about the llvm-dev mailing list