Negating numbers in Y86

441 views Asked by At

I know there would be many methods to do it and I'm trying to find the most efficient way.

One particular way I'm trying to avoid is subtracting the number from zero since it would involve transfering the value from the register that used to have 0 back to the register that contains pre-negated number which would be a pain.

2

There are 2 answers

1
Greg Hewgill On

From the limited information I can find online about Y86, it is a simplified version of x86. The x86 instruction set has a NEG instruction to negate a number. Y86 does not. You will probably have to subtract your value from 0.

0
Y86 Tutoring On

Sorry, Y86 is limited, so almost any operation that you can imagine will end up costing more calories than a simple subtraction from 0.

What we can do it optimize the establishment of 0 (by using XOR) and the preservation/restoration of the interim value (by using the stack.)

The following code works:

 #
 # Negate a number in %ebx by subtracting it from 0
 #
 Start: 
  irmovl $999, %eax    // Some random value to prove non-destructiveness
  irmovl Stack, %esp   // Set the stack
  pushl %eax           // Preserve 

 Go:
  irmovl $300, %ebx
  xorl %eax, %eax
  subl %ebx,%eax
  rrmovl %eax, %ebx

 Finish:
  popl %eax             // Restore 
  halt

 .pos 0x0100
 Stack: