Re: function attributes on function pointers

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ian Lance Taylor <iant@xxxxxxxxxx> writes:

> In general, you can use function attributes on function pointers like
> this:
>
> void * (* __attribute__ ((malloc)) my_malloc) (size_t) = malloc;
>
> Unfortunately, this is only supported for some attributes.  It will only
> work if the attribute can be attached to a function type rather than to
> a specific function declaration.  The malloc attribute is not
> implemented in that way, so this does not work for the malloc attribute.

I tried to work around that limitation by defining a function
that has the malloc attribute and then calls the function pointer:

........................................................................
#include <stddef.h>

extern void* (*my_malloc) (size_t size);
void* __attribute__ ((malloc)) call_my_malloc (size_t size);

void* __attribute__ ((malloc))
call_my_malloc (size_t size)
{
  return my_malloc (size);
}

int
gcc_suspects_aliasing (void)
{
  int *p = call_my_malloc (sizeof (int));
  int *q = call_my_malloc (sizeof (int));
  *p = 0;
  *q = 0;
  ++*p;
  ++*q;
  return *p;
}
........................................................................

However, "gcc (Debian 4.4.5-8) 4.4.5" -O2 on x86_64 generates
code that assumes the pointers may alias:

........................................................................
gcc_suspects_aliasing:
.LFB1:
	.cfi_startproc
	pushq	%rbx
	.cfi_def_cfa_offset 16
	movl	$4, %edi
	.cfi_offset 3, -16
	call	*my_malloc(%rip)
	movq	%rax, %rbx
	movl	$4, %edi
	call	*my_malloc(%rip)
	movl	$0, (%rbx)
	movl	$0, (%rax)
	addl	$1, (%rbx)
	addl	$1, (%rax)
	movl	(%rbx), %eax
	popq	%rbx
	ret
........................................................................

If I remove the definition of call_my_malloc, so that gcc cannot
inline it, then gcc respects the malloc attribute:

........................................................................
gcc_suspects_aliasing:
.LFB0:
	.cfi_startproc
	pushq	%rbx
	.cfi_def_cfa_offset 16
	movl	$4, %edi
	.cfi_offset 3, -16
	call	call_my_malloc
	movl	$4, %edi
	movq	%rax, %rbx
	call	call_my_malloc
	movl	$1, (%rbx)
	movl	$1, (%rax)
	movl	$1, %eax
	popq	%rbx
	ret
........................................................................

I wonder if this qualifies as a missed-optimization bug,
and whether later versions of gcc do the same.


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux