[PATCH] A new HeapToStack allocation promotion pass

Matthias Braun mbraun at apple.com
Mon Sep 23 17:14:27 PDT 2013


On Sep 23, 2013, at 2:18 PM, David Blaikie <dblaikie at gmail.com> wrote:

> 
> 
> 
> On Mon, Sep 23, 2013 at 2:00 PM, hfinkel at anl.gov <hfinkel at anl.gov> wrote:
> Hi chandlerc,
> 
> This adds a new optimization pass that can 'promote' malloc'd memory to stack-allocated memory when the lifetime of the allocation can be determined to be bounded by the execution of the function.
> 
> To be specific, consider the following three cases:
> 
> void bar(int *x);
> 
> void foo1() {
>   int *x = malloc(16);
>   bar(x);
>   free(x);
> }
> 
> In this case the malloc can be replaced by an alloca, and the free removed. Note that this is true even though the pointer 'x' is definitely captured (and may be recorded in global storage, etc.).
> 
> The pairing between the malloc and the free need not be 1:1, for example:
> 
> void foo2(int a) {
>   int *x;
> 
>   if (a == 0)
>     x = malloc(16);
>   else
>     x = malloc(32);
> 
>   bar(x);
>   free(x);
> }
> 
> where both mallocs and the free can be removed, and, finally, the free might not exclusively be used to free stack-promotable allocations, as in:
> 
> void foo3(int *y) {
>   if (y == 0)
>     y = malloc(48);
> 
>   bar(y);
>   free(y);
> }
> 
> to handle this last case, which is referred to as an 'ambiguous' free in the code, a new boolean value is introduced to track the source of the allocation. The malloc is removed, but the free is not. Instead, the pointer passed to the free is conditionally set to null to prevent freeing a stack address.
> 
> I don't believe free is guaranteed to be a no-op on null (I believe it's undefined), unlike C++ delete (which is defined to no-op on null). Should this instead make the whole call conditional, rather than the argument?
The C (89 and newer) standards requires that free(NULL) is a noop.

Greetings,
	Matthias
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20130923/17725e01/attachment.html>


More information about the llvm-commits mailing list