Page 1 of 1

NASM addressing problem

Posted: Mon May 12, 2008 3:36 am
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?

Posted: Tue May 13, 2008 11:21 pm
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.

Posted: Thu May 15, 2008 2:52 pm
by svdmeer
Thanks! Your solution works (also with Nasm).