NASM addressing problem

Programming, for all ages and all languages.
Post Reply
svdmeer
Member
Member
Posts: 87
Joined: Tue May 06, 2008 9:32 am
Location: The Netherlands

NASM addressing problem

Post by svdmeer »

With addressing with bp+x (x-128<x<x+128) you can generate smaller code in x86 asm language.

Code: Select all

inc byte [ErrorValue]
ErrorValue is defined in the very beginning of the file. Moving of this definition to the end of the file doesn't matter.

Code: Select all

%define ErrorValue	bp + bp_size + (ErrorValuePTR - 7C00h)
ErrorValuePTR is inside the code:

Code: Select all

show_error_LE:	call Print
		db 'Error '
ErrorValuePTR:	db '1',0
Addresses: bp_size = 20h (defined constant), ErrorValuePTR=7C59h (calculated address)

Zo result of the calculation of ErrorValue is 79h
This value is small enough, to generate one byte less code:
inc byte [bp+79h] is 3 bytes of code.
inc byte [bp+bigvalue] or inc byte [value] is 4 bytes of code.

The problem is Nasm generates 4 bytes of code. When I define ErrorValue manually with value 79h, everything is fine, I get the shorter code.
When I replace (ErrorValuePTR - 7C00h) with 59h, everything is also fine.

Code: Select all

%define ErrorValue	bp + bp_size + (ErrorValuePTR - 7C00h)
Generates for inc byte [ErrorValue]: fe 86 79 00

Code: Select all

%define ErrorValue	bp + bp_size + 59h        ; (ErrorValuePTR - 7C00h) replaced
Generates for inc byte [ErrorValue]: fe 46 79


I prefer to use ErrorValue and definition with ErrorValuePTR because the address of the address of ErrorValuePTR can change a little bit (but within reach of bp-7fh and bp+7fh)
How can Nasm understand that my definition can use the smaller code?
jnc100
Member
Member
Posts: 775
Joined: Mon Apr 09, 2007 12:10 pm
Location: London, UK
Contact:

Post by jnc100 »

The issue is in the type of ModR/M byte NASM outputs (46/86) which decides whether (in 16-bit code) a 8-bit or 16-bit displacement is used. I guess NASM defaults to the larger size because it doesn't know what the displacement is until it has assembled all the other code so it can then work out the offset.

To override, try

Code: Select all

inc byte [byte ErrorValue]
(it works in yasm)

Regards,
John.
svdmeer
Member
Member
Posts: 87
Joined: Tue May 06, 2008 9:32 am
Location: The Netherlands

Post by svdmeer »

Thanks! Your solution works (also with Nasm).
Post Reply