Code Generation/Example 3

From Wiki**3

< Code Generation
Revision as of 10:18, 8 June 2009 by Root (talk | contribs) (New page: == The Original Code == Consider the following S9 function: <c> int *click(int *x, int dim) { int *res, i; for (i = dim-2, res = x+dim-1; i >= 0; i--) if (x[i] ...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The Original Code

Consider the following S9 function:

<c> int *click(int *x, int dim) {

 int *res, i;
 for (i = dim-2, res = x+dim-1; i >= 0; i--)
   if (x[i] > *res) res = &x[i];
 return res;

} </c>

Postfix Code

The Postfix code for the above function is as follows:

<asm> TEXT ALIGN GLOBL click, FUNC LABEL click ENTER 8  ;-- x@+8 dim@+12 res@-4 i@-8

for init
i = dim-2

LOCV 12 INT 2 SUB DUP LOCA -8 TRASH 4

res = x + dim - 1

LOCV 8 LOCV 12 INT 4 MUL ADD INT 1 INT 4 MUL SUB DUP LOCA -4 TRASH 4

for test

ALIGN LABEL for LOCV -8 INT 0 GE JZ forend

for block
if test

LOCV 8 ; x LOVC -8 ; i INT 4 MUL ADD ; x+i LOAD ; x[i] = *(x+i)

LOCV -4 ; res LOAD ; *res

GT JZ ifend

if block

LOCV 8 ; x LOVC -8 ; i INT 4 MUL ADD ; x+i = &x[i] DUP LOCA -4 ; res = &x[i] TRASH 4

ALIGN LABEL ifend

for increment

ALIGN LABEL forincr LOCV -8 ; i DUP INT 1 SUB LOCA -8 TRASH 4

for jump to cycle

JMP for

ALIGN LABEL forend

return

LOCV -4 ; res

POP LEAVE RET </asm>

Compiling and Running

To compile the Postfix code directly, pf2asm can be used:

  • pf2asm click.pf
  • yasm -felf click.asm