Code Generation/Example 4: Difference between revisions
From Wiki**3
< Code Generation
Line 31: | Line 31: | ||
; int ix = lo is NOT an assignment | ; int ix = lo is NOT an assignment | ||
LOCAL +8 | LOCAL +8 | ||
LDINT ; read lo | |||
LOCAL -4 | LOCAL -4 | ||
STINT ; write to ix | |||
ALIGN | ALIGN | ||
LABEL whiletest | LABEL whiletest | ||
LOCAL -4 | LOCAL -4 | ||
LDINT ; read ix | |||
LOCAL +12 | LOCAL +12 | ||
LDINT ; read hi | |||
LT | LT | ||
JZ whileend | JZ whileend | ||
Line 49: | Line 49: | ||
LOCAL -4 | LOCAL -4 | ||
LDINT ; second printf arg: read ix | |||
; put string literal in read-only memory | ; put string literal in read-only memory | ||
Line 55: | Line 55: | ||
ALIGN | ALIGN | ||
LABEL strlit | LABEL strlit | ||
SSTRING "%d\n" | |||
; now get the address of the string literal (strlit) | ; now get the address of the string literal (strlit) | ||
TEXT | TEXT | ||
Line 67: | Line 67: | ||
; get printf return value | ; get printf return value | ||
LDFVAL32 | |||
; get rid of return value (printf used as instruction) | ; get rid of return value (printf used as instruction) | ||
Line 74: | Line 74: | ||
; increment ix | ; increment ix | ||
LOCAL -4 | LOCAL -4 | ||
LDINT ; read ix | |||
DUP32 | |||
INT 1 | INT 1 | ||
ADD | ADD | ||
LOCAL -4 | LOCAL -4 | ||
STINT ; ix = ix + 1 | |||
; trash old value of ix | ; trash old value of ix | ||
Line 95: | Line 95: | ||
; prepare return value | ; prepare return value | ||
LOCAL -4 | LOCAL -4 | ||
LDINT ; read ix | |||
; put it in the accumulator (register) to conform with Cdecl | ; put it in the accumulator (register) to conform with Cdecl | ||
STFVAL32 | |||
LEAVE ; release stack frame | LEAVE ; release stack frame |
Revision as of 22:33, 1 May 2018
The Original Code
Consider the following C function:
<c> extern int printf(const char *format, ...); int printlist(int lo, int hi) {
int ix = lo; while (ix < hi) { printf("%d\n", ix); ix++; } return ix;
} </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 while.pf
- yasm -felf while.asm