7

please i've this GCC inline assembler piece of code

int   src = 0;
dword n;
__asm(
            "sar %%cl,%%edx"
            : "=d" (n) // saves in eax,edx
            : "c" (src), "d" (n) // the inputs
            );

and my delphi attempt is :

asm
mov ecx, &src
mov edx, &n
sar cl,edx
mov eax,edx
end;

please is that correct ?

1
  • 5
    My advice would be to convert this code into Pascal rather than assembler. Commented Feb 24, 2012 at 12:07

1 Answer 1

10

Inline assembler does not work the same way in Delphi as it does in GCC. For starters, you don't have the same kind of macro and template support in Delphi, so if you want to use a declare-once general purpose assembler routine, you have to declare it as a function:

function ShiftArithmeticRight(aShift: Byte; aValue: LongInt): LongInt;
{$IFDEF WIN64}
asm
  sar edx,cl
  mov eax,edx
end;
{$ELSE}
{$IFDEF CPU386}
asm
  mov cl,al
  sar edx,cl
  mov eax,edx
end;
{$ELSE}
begin
  if aValue < 0 then
    Result := not (not aValue shr aShift)
  else
    Result := aValue shr aShift;
end;
{$ENDIF}
{$ENDIF}

In Delphi, inline assembler has to be implemented at the spot where it is used, and it is only supported in 32-bit. In such asm blocks you can use the EAX,ECX,EDX freely, plus any identifiers in the surrounding code. For instance:

var
  lValue: LongInt;
  lShift: Byte;
begin
  // Enter pascal code here
  asm
    mov cl,lShift
    sar lValue,cl
  end;
  // Enter pascal code here
end;
Sign up to request clarification or add additional context in comments.

13 Comments

many thanks Henrick Hellström , i will re-start based on your valuable answer. thank you
Fixed a bug in my original answer. SAR is a signed operation, so the aValue parameter should be LongInt and not LongWord.
@Alexis Thanks. That's excellent. And I would again re-iterate that a Pascal solution should really be preferred here.
Assembler might be useful in cases like this only if you want to make sure the compiler does exactly what you intend, and if it would matter if the compiler implementation of the shr operator would change between versions (such as always bitwise shr in one versions, but sar for signed types in another).
Don't get me wrong. You wrote a fantastic answer that covered all the bases. I upvoted you and encouraged Alexis to accept. I would just have preferred to see some guidance as to which route to go, especially for a coder who is not as proficient as you clearly are in asm. What's best for you may not be best for everyone if you follow me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.