Code Generation/Exercise 7: Difference between revisions

From Wiki**3

< Code Generation
(Created page with "== The Original Code == 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[...")
 
(Redirected page to ist:Code Generation/Exercise 7)
 
(6 intermediate revisions 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:
 
<asm>
TEXT
ALIGN
GLOBL traverse, FUNC
LABEL traverse
ENTER 8  ; ptr@-4 ix@-8 vec@+8 lim@+12
 
; init prt (not assignment)
LOCV +8  ; vec
LOCV +12 ; lim
INT 4    ; sizeof int
MUL
ADD      ; vec + lim
INT 1
INT 4    ; sizeof int
MUL
SUB      ; vec + lim - 1
LOCA -4  ; ptr = vec + lim - 1
 
; init ix (not assignment)
LOCV +12 ; lim
INT 2
SUB
LOCA -8  ; ix = lim -2
 
; while start: test
ALIGN
LABEL while_test
LOCV -8
INT 0
GE      ; ix >= 0
JZ while_end
 
; while block
 
; ?: operator
LOCV +8  ; vec
LOCV -8  ; ix
INT 4    ; sizeof int
MUL
ADD      ; vec + ix
LOAD    ; *(vec+ix) --> vec[ix]
 
LOCV -4  ; ptr
LOAD    ; *ptr
 
GT
JZ three_false_part
 
; ?: true part
LOCV +8  ; vec
LOCV -8  ; ix
INT 4    ; sizeof int
MUL
ADD      ; vec + ix
 
JMP three_end
 
; ?: false part
LOCV -4  ; ptr
 
; ?: end
ALIGN
LABEL three_end
 
DUP      ; for assignment
LOCA -4  ; ptr = ?: ...
 
; trash expression value (used as instruction)
TRASH 4
 
; decrement ix
LOCV -8  ; ix
DUP
INT 1
SUB
LOCA -8  ; ix = ix - 1
TRASH 4  ; (ix-- used as instruction)
 
; end while block
JMP while_test
 
; exit while cycle
ALIGN
LABEL while_end
 
; return ptr
LOCV -4
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:Compilers]]
[[category:Teaching]]

Latest revision as of 18:15, 6 December 2018