Search code examples
delphiassemblypascalcpu-registerstranslate

Converting this inline Assembler function to Delphi Pascal


I am currently working on a legacy product in Delphi that includes some inline assembly, I need help understanding what the function does and how to convert it to Pascal.

The code is:

function lswap(i : longint) : longint; assembler;
asm
{$IFDEF CPU64}
    mov eax,ecx
{$ENDIF CPU64}
    db $0f,$c8  {bswap eax  !! requires at least 486 CPU!!}
end;

Solution

  • By way of helping you to understand what this does:

    You can use the debugger to look at what is happening in your code, including in assembler.

    If you have a test program that calls this routine (probably multiple times with different arguments) and stores the result in a standard Delphi variable then to debug you would:

    • set a breakpoint where you first call it
    • when you hit the breakpoint ensure you have your debug to 'Full CPU' and also choose 'mixed source' display.

    Look at the code the compiler has produced. The first thing the compiler will do is prepare the arguments for the routine you are calling. For Pascal routines this normally means putting the values into appropriate CPU registers.

    Step into the code line by line. In the Registers window (part of the full cpu display) you will see the values of the registers and how they are changed with each instruction.

    On return from the routine the compiler will store the result somewhere so you will be able to understand how the compiler is interpreting the result.

    Simply looking at the input and output may be enough for you without having to understand everything in the routine.

    Inline assembler has been widely used in lots of code-bases but with an increasing move away from a fixed x86 architecture there are an increasing number of reasons to remove such code.