[LLVMdev] optimization assumes malloc return is non-null

David Vandevoorde daveed at vandevoorde.com
Wed Apr 30 20:51:14 PDT 2008


On Apr 30, 2008, at 10:25 PM, Chris Lattner wrote:
> 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.

Ah yes, of course.  Does LLVM do this for known & small constant n?

(I suppose it could be transformed into:

	void f(size_t n) {
	  bool __opt = n < __L;
	  char *str = (char*)(opt ? alloca(n) : malloc(n));
	  // ...
	  if (!opt) free(str);
	}

The payoff is less obvious here.)

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

Cool.

	Daveed




More information about the llvm-dev mailing list