1 # ----------------------------------------------------------------------
2 # General structure of a MIPS assembly program
3 #
4 # (use `#` for comments)
5 #
6 # .data
7 # .ascii
8 # .asciiz
9 # .space
10 # .byte
11 # .align
12 # .word
13 #
14 #
15 # .text (functions, instructions)
16 #
17 # id:
18 # instr1
19 # instr2
20 # ...
21 #
22 # (remember that if you don't jump at the end of your function,
23 # the program will simply continue on to subsequent lines)
24 #
25 #
26 # .main (starting point for execution; must have this)
27 # instr1
28 # instr2
29 # ...
30 #
31 # ----------------------------------------------------------------------
32 # extern print_int(int);
33 # extern print_string(strcon);
34 #
35 # int x;
36 #
37 # void main(void)
38 # {
39 # x = 5;
40 # foo(x);
41 # }
42 #
43 # foo(int b)
44 # {
45 # print_int(b);
46 # print_str("\n");
47 # }
48 # ----------------------------------------------------------------------
49
50 .data
51
52 x:
53 .space 1
54 .align 2 # align next item to a 2^n byte boundary
55
56 newline:
57 .asciiz "\n"
58 .align 2
59
60 .text
61
62 main:
63 # prologue -----------------------------------------------------
64 sub $sp, 24
65 sw $fp, ($sp)
66 sw $ra, 4($sp)
67 add $fp, $sp, 20
68 # --------------------------------------------------------------
69
70 # integer constant
71 li $t1, 5
72
73 # assignment
74 la $t0, x
75 sw $t1, ($t0)
76
77 # prologue: foo
78 sub $sp, 12
79 sw $fp, 8($sp)
80 sw $ra, 4($sp) # preserve, so not lost after next jal
81
82 # param: x
83 la $t0, x
84 lw $t0, ($t0)
85 sw $t0, ($sp)
86
87 # call: foo
88 move $fp, $sp
89 jal foo
90
91 # epilogue: foo
92 lw $ra, 4($sp)
93 lw $fp, 8($sp)
94 add $sp, 12
95
96 done:
97 # epilogue -----------------------------------------------------
98 lw $ra, 4($sp)
99 lw $fp, ($sp)
100 add $sp, 24
101 jr $ra
102 # --------------------------------------------------------------
103
104
105 # foo defined on line 12
106 foo:
107 # enter: foo
108 sub $sp, 12
109 sw $fp, 8($sp)
110 sw $ra, 4($sp)
111
112 # param: bar
113 lw $t0, ($fp)
114 sw $t0, ($sp)
115
116 # procedure call: print_int
117 jal print_int
118
119 # param: "\n"
120 la $t0, newline
121 sw $t0, ($sp)
122
123 # procedure call: print_string
124 jal print_string
125
126 # leave: foo
127 lw $ra, 4($sp)
128 lw $fp, 8($sp)
129 add $sp, 12
130 jr $ra
131
132
133 print_int:
134 li $v0, 1
135 lw $a0, ($sp)
136 syscall
137 jr $ra
138
139 print_string:
140 li $v0, 4
141 lw $a0, ($sp)
142 syscall
143 jr $ra
144