Code Generation/Example 3: Difference between revisions

From Wiki**3

< Code Generation
No edit summary
Line 15: Line 15:


The Postfix code for the above function is as follows:  
The Postfix code for the above function is as follows:  
 
{{CollapsedCode|Postfix code|
<asm>
<asm>
TEXT
TEXT
Line 26: Line 26:


;; i = dim-2
;; i = dim-2
LOCV 12
LOCAL 12
LOAD
INT 2
INT 2
SUB
SUB
DUP
DUP
LOCA -8
LOCAL -8
STORE
TRASH 4
TRASH 4


;; res = x + dim - 1
;; res = x + dim - 1
LOCV 8
LOCAL 8
LOCV 12
LOAD
LOCAL 12
LOAD
INT 4
INT 4
MUL
MUL
Line 44: Line 48:
SUB
SUB
DUP
DUP
LOCA -4
LOCAL -4
STORE
TRASH 4
TRASH 4


Line 50: Line 55:
ALIGN
ALIGN
LABEL for
LABEL for
LOCV -8
LOCAL -8
LOAD
INT 0
INT 0
GE
GE
Line 58: Line 64:


;; if test
;; if test
LOCV 8 ; x
LOCAL 8
LOCV -8 ; i
LOAD ; x
LOCAL -8
LOAD ; i
INT 4
INT 4
MUL
MUL
Line 65: Line 73:
LOAD ; x[i] = *(x+i)
LOAD ; x[i] = *(x+i)


LOCV -4 ; res
LOCAL -4
LOAD ; res
LOAD ; *res
LOAD ; *res


Line 72: Line 81:


;; if block
;; if block
LOCV 8 ; x
LOCAL 8
LOCV -8 ; i
LOAD ; x
LOCAL -8
LOAD ; i
INT 4
INT 4
MUL
MUL
ADD ; x+i = &x[i]
ADD ; x+i = &x[i]
DUP
DUP
LOCA -4 ; res = &x[i]
LOCAL -4
STORE ; res = &x[i]
TRASH 4
TRASH 4


Line 87: Line 99:
ALIGN
ALIGN
LABEL forincr
LABEL forincr
LOCV -8 ; i
LOCAL -8
LOAD ; i
DUP
DUP
INT 1
INT 1
SUB
SUB
LOCA -8
LOCAL -8
STORE
TRASH 4
TRASH 4


Line 101: Line 115:


;; return
;; return
LOCV -4 ; res
LOCAL -4
LOAD ; res


POP
POP
Line 107: Line 122:
RET
RET
</asm>
</asm>
}}


== Compiling and Running ==
== Compiling and Running ==

Revision as of 07:29, 9 May 2017

The Original Code

Consider the following C 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:

Postfix code
{{{2}}}

Compiling and Running

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

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