Code Generation/Exercise 7: Difference between revisions

From Wiki**3

< Code Generation
(Redirected page to ist:Code Generation/Exercise 7)
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
== The Original Code ==
#REDIRECT [[ist:Code Generation/Exercise 7]]
 
Consider the following C function:
 
<c>
int *traverse(int vec[], int lim) {
  int *ptr = vec + lim - 1, ix = lim - 2;
  while (ix >= 0) {
    ptr = (vec[ix] > *ptr) ? vec + ix : ptr;
    ix--;
  }
  return ptr;
}
</c>
 
== Postfix Code ==
 
The Postfix code for the above function is as follows:
{{CollapsedCode|Postfix code|
<asm>
TEXT
ALIGN
GLOBL traverse, FUNC
LABEL traverse
ENTER 8  ; ptr@-4 ix@-8 vec@+8 lim@+12
 
; init prt (not assignment)
LOCAL +8
LOAD  ; vec
LOCAL +12
LOAD ; lim
INT 4    ; sizeof int
MUL
ADD      ; vec + lim
INT 1
INT 4    ; sizeof int
MUL
SUB      ; vec + lim - 1
LOCAL -4
STORE  ; ptr = vec + lim - 1
 
; init ix (not assignment)
LOCAL +12
LOAD ; lim
INT 2
SUB
LOCAL -8
STORE  ; ix = lim -2
 
; while start: test
ALIGN
LABEL while_test
LOCAL -8
LOAD
INT 0
GE      ; ix >= 0
JZ while_end
 
; while block
 
; ?: operator
LOCAL +8
LOAD  ; vec
LOCAL -8
LOAD  ; ix
INT 4    ; sizeof int
MUL
ADD      ; vec + ix
LOAD    ; *(vec+ix) --> vec[ix]
 
LOCAL -4
LOAD  ; ptr
LOAD  ; *ptr
 
GT
JZ three_false_part
 
; ?: true part
LOCAL +8
LOAD  ; vec
LOCAL -8
LOAD  ; ix
INT 4    ; sizeof int
MUL
ADD      ; vec + ix
 
JMP three_end
 
; ?: false part
ALIGN
LABEL three_false_part
 
LOCAL -4
LOAD  ; ptr
 
; ?: end
ALIGN
LABEL three_end
 
DUP      ; for assignment
LOCAL -4
STORE  ; ptr = ?: ...
 
; trash expression value (used as instruction)
TRASH 4
 
; decrement ix
LOCAL -8
LOAD  ; ix
DUP
INT 1
SUB
LOCAL -8
STORE  ; ix = ix - 1
TRASH 4  ; (ix-- used as instruction)
 
; end while block
JMP while_test
 
; exit while cycle
ALIGN
LABEL while_end
 
; return ptr
LOCAL -4
LOAD
POP
LEAVE
RET
</asm>
}}
 
== Compiling and Running ==
 
To compile the Postfix code directly, [[pf2asm]] can be used:
 
pf2asm traverse.pf
yasm -felf traverse.asm
 
[[category:Compiladores]]
[[category:Ensino]]

Latest revision as of 18:15, 6 December 2018