CS270 Colorado State University ============= TRAPS ============= TRAPS are useful because ... programmers can use TRAPS instead of accessing device registers directly TRAPS can be set up to run in privileged mode privileged mode programs have to have certain privileges to access hardware registers I/O including memory mapped I/O resetting the clock HALT supervisor versus user program OS is considered the supervisor program and in charge of TRAPS ------------------------------ TRAPS: 1111 0000 0010 0101 opcode trap vector stores linkage in R7 loads address of routine, which is stored in trap vector, into PC x0020 | x0400 | x0021 | x0430 | ... x0025 | xFD70 | How many traps are possible in LC3? ------------------------------ Example: Character output (code from book page 227) .ORIG x0430 ST R1, SaveR1 TryWrite LDI R1, DSR BRzp TryWrite WriteIt STI R0, DDR Return LD R1, SaveR1 RET DSR .FILL xFE04 DDR .FILL xFE06 SaveR1 .BLKW 1 .END ------------------------------ Saving and restoring registers Character output example saves R1 before using it caller-save versus callee-save x86 convention http://pdos.csail.mit.edu/6.828/2004/lec/l2.html %eax, %ecx, %edx are "caller-save" registers         %ebp, %ebx, %esi, %edi are "callee-save" registers ------------------------------ Subroutines functions, procedures, methods Useful enables code reuse and as such reduces code duplication enables decomposition of task into smaller problems enables interfaces and information hiding Implementation needs passing parameters and return values ability to call routine and return from it ------------------------------ JSR and JSRR JSR LABEL 0100 1 PCoffset11 JSRR BaseR 0100 0 BaseR 0000000 Why is JSRR necessary? ------------------------------ LC3 example with subroutines ; Subroutine multi ; (Copied from course slides that come with book) ; Multiply 2 positive numbers ; Parameters: ; In: R1, R2; Out: R3 ; multi AND R3, R3, #0 ADD R4, R1, #0 BRz zero loop ADD R3, R2, R3 ADD R1, R1, # -1 BRp loop zero RET .END Notes about example passing parameters through registers sending return value through register multi does not call any other routines or use a TRAP so do not have to save R7 ------------------------------ Example: Factorial ; Subroutine fact ; Compute factorial for parameter. ; Parameters: ; In: R4; Out: R5 ; if (R4==1) R5 = 1 ; else R5 = R4 * fact(R4-1) fact ST R7, Save7 ADD R6, R4, #-1 BRz BASE ; if R4==1 then goto base case RECURSE ST R4, SaveR4 ADD R4, R6, #0 ; R$ = R4-1 JSR fact LD R4, SaveR4 ADD R1, R4, #0 ; R1 <- R4 ADD R2, R5, #0 ; R2 <- R5, output of fact call JSR multi ADD R5, R3, #0 ; R5 <- R1*R2 JMP DONE BASE AND R5, R5, #0 ADD R5, R5, #1 DONE LD R7, Save7 RET SaveR7 .BLKW 1 SaveR4 .BLKW 1 .END Notes about example ------------------------ mstrout@cs.colostate.edu, 10/27/08