[fpc-devel] estimating function code size
Thomas Schatzl
tom_at_work at gmx.at
Wed Jan 18 17:41:24 CET 2012
Hi,
On Wed, 2012-01-18 at 15:17 +0200, Žilvinas Ledas wrote:
> On 2012-01-18 15:08, Gennadiy Poryev wrote:
> >> Do you think it's granted that there is only one return in a function ?
> >> Maybe optimization or "exit" could create additional returns
> > Actually I do. Because I write this function :)
> > It uses quite a lot of loops and ifs, but no exits.
> > And what I need is a reliable way to get its code size at runtime without manually inspecting it on every rebuild.
try this:
{$CODEALIGN PROC=1} // force code alignment on 1 byte boundaries
var
size : ptruint;
procedure findmysize;
label
StartFindMySize, EndFindMySize; // actually things should work with
local labels too
begin
asm
call StartFindMySize
StartFindMySize:
popq %rax
movq %rax, size
end;
writeln('calculating size');
asm
call EndFindMySize
EndFindMySize:
popq %rax
subq size, %rax
movq %rax, size
end;
end;
procedure findmysize_dummy;
begin
end;
begin
findmysize;
writeln(ptruint(@findmysize_dummy) - ptruint(@findmysize), ' ', size);
end.
It shows two ways of doing this, with different disadvantages. The first
type is using assembler and calculating the range of addresses between
two labels. This has the disadvantages that it is platform dependent
(shwoing x64 code here, I'm sure you could make it more "optimized"),
and only calculates the distance between the two labels, i.e. without
entry and exit code. It is also always off by 5 bytes (single "call +
<address>").
The other way is relying on the dodgy assumption that nobody changes the
order of functions in the object file or during loading or linking. This
is usually the case. It may not be completely safe, i.e. only work on
particular platforms etc., but usually it should be okay in the absence
of compiler options like e.g. smartlinking.
Further that while it includes method entry and exit code, it may not be
completely accurate due to the compiler aligning code
You may want to check the returned sizes by dumping the memory
containing the code using a debugger and choose the one which is more
suitable for you.
Thomas
More information about the fpc-devel
mailing list