Code Generation/Example 3: Difference between revisions

From Wiki**3

< Code Generation
(Redirected page to ist:Code Generation/Example 3)
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
== The Original Code ==
#REDIRECT [[ist:Code Generation/Example 3]]
 
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:
{{CollapsedCode|Postfix code|
<asm>
TEXT
ALIGN
GLOBL click, FUNC
LABEL click
ENTER 8  ;-- x@+8 dim@+12 res@-4 i@-8
 
;; for init
 
;; i = dim-2
LOCAL 12
LOAD
INT 2
SUB
DUP
LOCAL -8
STORE
TRASH 4
 
;; res = x + dim - 1
LOCAL 8
LOAD
LOCAL 12
LOAD
INT 4
MUL
ADD
INT 1
INT 4
MUL
SUB
DUP
LOCAL -4
STORE
TRASH 4
 
;; for test
ALIGN
LABEL for
LOCAL -8
LOAD
INT 0
GE
JZ forend
 
;; for block
 
;; if test
LOCAL 8
LOAD ; x
LOCAL -8
LOAD ; i
INT 4
MUL
ADD ; x+i
LOAD ; x[i] = *(x+i)
 
LOCAL -4
LOAD ; res
LOAD ; *res
 
GT
JZ ifend
 
;; if block
LOCAL 8
LOAD ; x
LOCAL -8
LOAD ; i
INT 4
MUL
ADD ; x+i = &x[i]
DUP
LOCAL -4
STORE ; res = &x[i]
TRASH 4
 
ALIGN
LABEL ifend
 
;; for increment
ALIGN
LABEL forincr
LOCAL -8
LOAD ; i
DUP
INT 1
SUB
LOCAL -8
STORE
TRASH 4
 
;; for jump to cycle
JMP for
 
ALIGN
LABEL forend
 
;; return
LOCAL -4
LOAD ; 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
 
[[category:Compiladores]]
[[category:Ensino]]

Latest revision as of 18:14, 6 December 2018