-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32_stack_frame.asm
More file actions
62 lines (55 loc) · 2.08 KB
/
32_stack_frame.asm
File metadata and controls
62 lines (55 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
; Exercise 32: Stack-Based Parameters with Frame Pointer
; Level: 4 - Stack & Subroutines
;
; Goal: Pass three arguments via the stack to a function
; Function uses frame pointer to access arguments, computes sum
; Also demonstrates local variables with negative offsets
; Call sum(5, 10, 15) and get R0 = 30
;
; Instructions to use: LOADI, PUSH, MOVSPR, LOAD, STORE, ADD, CALL, RET, HALT
; Expected result: R0 = 30
;
; Hint: Push arguments in reverse order: arg3, arg2, arg1
; Hint: Function uses MOVSPR to get frame pointer (SP into R6:R7)
; Hint: Access arguments via POSITIVE offset: [R6:R7 + offset]
; Hint: Access local variables via NEGATIVE offset: [R6:R7 - offset]
; Hint: Signed offsets range from -128 to +127
;
; Stack layout after MOVSPR and local allocation:
; Higher addresses
; [FP + 5] = arg1 (5) - first pushed
; [FP + 4] = arg2 (10)
; [FP + 3] = arg3 (15) - last pushed
; [FP + 2] = return address high byte
; [FP + 1] = return address low byte
; [FP + 0] = SP points here after CALL <- FP saved here
; [FP - 1] = local1 (temporary sum) <- pushed after MOVSPR
; Lower addresses
section .code
; Push arguments in order: arg1, arg2, arg3
loadi r0, 5
push r0 ; arg1
loadi r0, 10
push r0 ; arg2
loadi r0, 15
push r0 ; arg3
call sum_three
halt
sum_three:
movspr r6:r7 ; R6:R7 = SP (frame pointer)
; Allocate space for local variable
loadi r0, 0
push r0 ; local1 at [FP - 1]
; Load arguments using positive offsets
load r0, [r6:r7 + 5] ; arg1 (5) at FP+5 (first pushed)
load r1, [r6:r7 + 4] ; arg2 (10) at FP+4
add r0, r1 ; R0 = 5 + 10 = 15
; Store intermediate result in local variable using negative offset
store r0, [r6:r7 - 1] ; Store 15 in local1
; Load local and add final argument
load r0, [r6:r7 - 1] ; Load local1 (15)
load r2, [r6:r7 + 3] ; arg3 (15) at FP+3 (last pushed)
add r0, r2 ; R0 = 15 + 15 = 30
; Clean up local variable
pop r1
ret