Delphi is a
very high level language.
Its optimizer is great and it perfectly handles even the most complicated code.
However sometimes one needs much higher speed, escpecially when performing thousands (or millions)
of the same operations. In such cases it is worth to use assembler.
The following text is meant for people who have already used assembler.
Basics
Turbo Pascal as well as Delphi enable using assembler two ways:
1. As a remark in a function body:
begin
{..}
asm
mov eax, 10
{...}
end;
{..}
end;
|
2. As a whole function:
procedure Name(i: Integer); assembler;
asm
mov eax, 10
mov ebx, i
{...}
end;
|
The function result is always returned in EAX register.
Windows limitations
First of all one must remember that a Windows (32-bit Windows) application works in
32-bit mode. For x86 processors this mode is called protected mode.
Segments have various lengths, not all of them allow writing to, some do not allow reading.
There is no access neither to I/O ports nor to interrupts.
Some instructions are forbidden, e.g.:
CLI i
STI.
Any violation of protected mode rules throws GPF (General Protection Fault) exception.
Delphi limitations
EAX, ECX and EDX registers can be manipulated freely.
EBX register serves as loops counter.
One must also remember that if loop counter does not affect loop result then loop steps are
performed backwards.
Moreover it is worth consideration that even if loop counter occurs in loop body but
still doesn't affect the result then as well loop steps are performed backwards.
for i:=0 to 10 do MessageBeep(0);
|
Delphi will write it this way:
mov ebx, 10
loop:
push 0
call MessageBeep
dec ebx
jnz loop
|
Whereas if we use loop counter in loop body:
for i:=0 to 10 do MessageBeep(i);
|
then Delphi will write it that way:
xor ebx, ebx
loop:
push ebx
call MessageBeep
inc ebx
cmp ebx, 10
jne loop
|
That's a trick everyone should be aware of.
Advantages of Delphi optimizer
Not all the arguments are passed by means of stack.
Optimizer allways tries to pass them using processor registers.
Delphi uses all the registers except for EBP, ESP and segment registers.
Don't worry, you are allowed to use EAX, ECX and EDX registers. Delphi will consider this,
which means that if in a procedure body one of those is used then Delphi optimizer won't
use it.
For those who are interested in the subject I recommend watching disassembler window.
One can learn much from it.
That's it. If anyone has some questions please
write.
Michał B±kowski