Podstawy techniki mikroprocesorowej ETEW006 Stos ndrzej Stępień Katedra Metrologii Elektronicznej i Fotonicznej Literatura J. Janiczek,. Stępień: Mikrokontrolery. WCKP, Wrocław, 1997 J. Janiczek,. Stępień: Laboratorium systemów mikroprocesorowych. Cz.1. WEZN, Wrocław, 1995 J. Janiczek,. Stępień: Laboratorium systemów mikroprocesorowych. Cz.2. WEZN, Wrocław, 1996 T. Starecki: Mikrokontrolery 8051 w praktyce. TC, Warszawa 2002 M430x4xx User s Guide. SLU056C, Texas Instruments, 2003 FMILY PROGMING MNUL. STMicroelectronics, March 1999. 8-IT MCU FMILY. USER GUIDE. STMicroelectronics, July 2002 Trevor Martin: The Insider's Guide To The Philips RM 7 ased Microcontrollers. (www.hitex.co.uk/arm/lpc2000book) RM rchitecture Reference Manual (Known as the "RM RM". RM Doc No.: DDI-0100) Jak rozwiązać problem? Jeśli w języku wysokiego poziomu (LGOL/FORTRN, rok 1950) zwiększyć jego efektywność i wydajność przez wprowadzenie podprogramów, to jak: zapamiętać adres powrotu z podprogramu? przenieść zmienne z programu głównego do tego podprogramu? zapamiętywać wartości chwilowe obliczeń? uprościć obliczenia, np. typu X = ( + ) (C + D)? Po co komu stos? Rozwiązanie wprowadzić stos (), liniową strukturę danych traktowaną jako rejestr typu LIFO (Last In First Out) wprowadzić instrukcje procesora typu: CLL addr, wywołanie podprogramu odesłanie na stos adresu powrotu z podprogramu, powrót z podprogramu pobranie ze stosu adresu powrotu, adresu dalszej części programu głównego PUSH arg, odesłanie argumentu na stos POP arg, pobranie argumentu ze stosu Procesory współpracujące ze stosem mogą: przyjmować przerwania wykonywać podprogramy obsługi przerwań Philip J. Koopman, Jr.: Computers the new wave. Typy stosu sprzętowy: - stos złożony z N dodatkowych, równoległych rejestrów lub rejestrów przesuwnych typu LIFO - szybkie (w stosunku do realizacji programowej) odwołania do stosu mały rozmiar stosu (w stosunku do realizacji programowej) programowy: - adresowanie dodatkowym rejestrem, wskaźnikiem stosu ( Pointer) - automatyczna inkrementacja / dekrementacja wskaźnika stosu przy każdorazowym odwołaniu do stosu - alokacja stosu w pamięci - rozmiar stosu ograniczony rozmiarem dostępnej pamięci z grawitacją, bez praw mechaniki LIFO 34 56 34 78 56 34 PUSH PUSH 34 PUSH 56 PUSH 78 PUSH POP 34 POP POP 34 56 34 POP 56 POP 78 TOS (Top Of ) Fig. 1.1 n example of stack operation 1
Philip J. Koopman, Jr.: Computers the new wave. Computers s are simple, a child intuitively understands a stack of things and how it works is a data structure that is accessed from one end or it is a LIFO (Last In First Out buffer). Computers are machines that have hardware and instructions to facilitate the use of stacks in programs. In the hardware within a processor a stack may be implemented using pointers on the processor or in memory to locations in memory. It can also be implemented as on-chip registers or it may have part of the stack cached in on-chip registers and have the rest of the stack in memory. s MCU architecture uses the load-store multiple instructions to carry out stack operations: PUSH operation (placing data onoto the stack) uses a store multiple instruction If a PUSH operation causes the stack pointer to increment or decrement beyond the maximum extent of the stack, a stack overflow occurs POP or PULL operation (removing data from a stack) uses a load multiple instruction If a POP operation on the stack causes the stack pointer to move past the origin of the stack, a stack underflow occurs Organisation will grow up or down, is: ascending () stack grow towards higher memory address or descending (D) stack grow towards lower memory address pointer points to an: full stack (F), the stack pointer points to an address that is the last used or full lacation ( points to the last item on the stack) empty stack (E), the points to an address that is the first unused or empty lacation ( points after the last item on the stack) addr+4 addr+3 addr+2 addr+1 = addr addr 1 addr 2 addr 3 addr 4 addr+4 addr+3 addr+2 addr+1 = addr addr 1 addr 2 addr 3 addr 4 + 3 + 2 last + 2 + 3 nex + 2 last last + 2 ddress Instructions Format 2-address instructions mat - saving in the number of bits required to store an instruction can be achieved by making the destination register the same as one of the source registers: DD d, s1 ; d := d + s1 f bits n bits n bits function op 1 addr dest addr 1-address instructions mat - if the destination register is made implicit it is often called the accumulator: f bits n bits DD s1 ; acc := acc + s1 function op 1 addr 0-address instructions mat - an architecture may make all operand references implicit by using an evaluation stack: DD ; top_of_stack := top_of_stack + _on_stack f bits function Machine Fig. 3.1 The Canonical Machine push pop operations (LIFO) DS Data RS Return store subroutine return address I/O Control Logic IR LU: addition, subtraction, logical (ND, OR, XOR) and test zero TOS Data D T u s Data LU Program Counter Memory ddress Register Program Memory ddress Top-Of- register http://en.wikipedia.org/wiki/reverse_polish_notation Reverse Polish Notation (1/2) Introduced in 1920 by the Polish mathematician Jan Łukasiewicz, is a mathematical notation wherein every operator follows all of its operands Operators follow their operands to add 3 + 4, one would write 3 4 + rackets and parentheses are unnecessary: the user simply perms calculations in the order that is required, letting the automatic stack store intermediate results on the fly later use utomatic stack permits the automatic storage of intermediate results use later: this key feature is what permits RPN calculators to easily evaluate expressions of arbitrary complexity State machine is always a stack of values awaiting operation; it is impossible to enter an operator onto the stack 2
http://en.wikipedia.org/wiki/reverse_polish_notation Reverse Polish Notation (2/2) expression "5 + ((1 + 2) * 4) 3" can be written in RPN: 5 1 2 + 4 * + 3 is evaluated left-to-right, with the inputs interpreted as shown in the table is the list of values the algorithm is "keeping track of" after the given in the middle column has taken place): Input Comment 5 Push operand 5 1 Push operand 5, 1 2 Push operand 5, 1, 2 + dd 5, 3 Pop two values (1, 2) and push result (3) 4 Push operand 5, 3, 4 * Multiply 5, Pop two values (3, 4) and push result () + dd 17 Pop two values (5, ) and push result (17) 3 Push operand 17, 3 Subtract 14 Pop two values (17, 3) and push result (14) Philip J. Koopman, Jr.: Computers the new wave. Single vs. multiple stacks (1/2) Single computers are those computers with exactly one stack supported by the instruction set. This stack is often intended state saving subroutine calls and interrupts. It may also be used expression evaluation. In either case, it is probably used subroutine parameter passing by compilers some languages. n advantage of having a single stack is that it is easier an operating system to manage only one block of variable sized memory per process. disadvantage of a single stack is that parameter and return address inmation are ced to become mutually well nested. Philip J. Koopman, Jr.: Computers the new wave. Single vs. multiple stacks (2/2) Multiple computers have two or more stacks supported by the instruction set: one stack is usually intended to store return addresses, the other stack is expression evaluation and/or subroutine parameter passing. The parameter stack is separate from the return address stack. Multiple stacks allow separating control flow inmation from data operands. n important advantage of having multiple stacks is one of speed. Multiple stacks allow access to multiple values within a clock cycle. s an example, a machine that has simultaneous access to both a data stack and a return address stack can perm subroutine calls and returns in parallel with data operations. Forth uses two stacks, one argument passing and one subroutine return addresses Stos sprzętowy - PIC17C4x (Microchip Technology) stosem jest 16-bitowy bu pierścieniowy; stos nie jest fragmentem pamięci programu lub danych, nie jest rejestrem specjalnym bu stosu jest 16-poziomowy 17-a operacja 'PUSH' nadpisuje wynik pierwszej operacji 'PUSH', 18-a operacja - drugiej itd. wskaźnik stosu jest zerowany po wszystkich typach zerowania procesora wskaźnik stosu nie jest dostępny do odczytu lub zapisu operacją 'PUSH' jest wywołanie podprogramu lub przyjęcie przerwania (brak instrukcji PUSH) operacją 'POP' jest powrót z podprogramu lub obsługi przerwania (brak instrukcji POP) jedynym znacznikiem stanu wskaźnika stosu jest STKV (STacK Vailable bit): STKV = 1 po zerowaniu procesora, STKV = 0 po osiągnięciu przez wskaźnik stosu maksymalnej wartości 0Fh Pointer () (1/2) ottom of the stack Top of the stack Pointer is a 16-bit register 1FFh = Reset Value (2334) 100h stack is 8 or 256 bytes deep, fixed by hardware 8 most significant bits are ced by hardware 8 least significant bits contain the address of the free location of the stack ( Pointer) Fixed by HW 17Fh = Reset Value (2264) Fixed by HW 0 0 0 0 0 0 0 1 x x x x x x x x Higher ddr 256 bytes (2334) 8 bytes (2264) Lower ddr Pointer () (2/2) 0 0 0 0 0 0 0 1 x x x x x x x x 1FFh = Reset Value (2334) 17Fh = Reset Value (251, 2264) 100h - Lower ddr after Reset (MCU Reset or instruction R) Pointer (R) contains its reset value (=1FFh 23xx or =17Fh 251, 22xx) which is the stack higher address is decremented when a value is stored using stack pointer - value stored will be placed at the address just below the previous one is incremented when the data is read back from the stack - data retrieved will be the one situated at the address above the previous value retrieved since the stack does not need the full 256-byte area, some of it may be allocated variables Note: when the lower limit is exceeded, the Pointer wraps around to the stack upper limit, without indicating the stack overflow. The previously stored inmation is then overwritten and theree lost. The stack also wraps in case of an underflow. ( overflow is not indicated) 3
PUSH - push into the POP - pop from PUSH src src:, X, Y, CC fter Reset: =1FFh POP dst dst:, X, Y, CC fter Reset: =1FFh (--) <= dst dst <= (++) Save into the stack the dst byte location. The stack pointer is decremented by one. Used to save a register value. PUSH Restore from the stack a data byte which will be placed in dst location. The stack pointer is incremented by one. Use to restore a register value. POP X CLL - CLL subroutine - return from subroutine CLL CLLR CLL Subroutine (bsolute) CLL Subroutine Relative CLL dst e.g.: call divide32_16 CLLR dst e.g.: callr divide32_16 = + lgth (--) = LS () (--) = MS () = dst The current register value is pushed onto the stack, then is loaded with the (relative) destination address. This instruction should be used versus CLLR when developing a program. MS () = (++) LS () = (++) Restore the from the stack. The stack pointer is incremented twice.this instruction is the last one of a subroutine. R - reset Pointer Manipulation R = Reset Value (=17Fh or =1FFh) =1FFh L H L H Y L H Y L H Y Reset the stack pointer to its reset initial value.this instruction may be put as first executed instruction in the reset routine. Trick It may be used to test current stack size used with an independent program. 100h fter Reset CLL Subroutine PUSH Y POP R 4
C51 Pointer () C51 PUSH - push into the / POP - pop from wydzielony logicznie obszar wewnętrznej pamięci (IDT) adresowany wskaźnikiem stosu ( Pointer) po sprzętowym zerowaniu procesora = 7 (adres R0 w banku R1) 0FFh segment bitowy; 8 bitów: 0.. 7Fh 4 banki rejestrów: R0.. R7 80h PSW P2 SFR DT P0 DPTR IDT IDT 7Fh 30h 0 0FFh 80h Synatx PUSH addr (++) dst ; + 1 ; () (addr) Synatx POP addr dst ( ) ; (addr) () ; 1 addr, e.g.: only cc not C51 CLL - CLL subroutine / - return from subroutine C51 Manipulation CLL addr_11 ; + 2 2 bajty, 2 cykle maszynowe ; INC ; () 7..0 ; INC ; () 15..8 ; addr 10..0 LCLL addr_16 ; + 3 3 bajty, 2 cykle maszynowe ; INC ; () 7..0 ; INC ; () 15..8 ; addr 15..0 ; 15..8 () 1 bajt, 2 cykle maszynowe ; DEC ; 7..0 () ; DEC Register ank R1 Register ank R0 0h 0h 9 8 =07h 6 fter Reset H L CLL Subroutine H L PUSH H L POP cc H L M430 The system stack pointer () is used the storage of the following items: Interrupt return addresses and status register contents Subroutine return addresses Intermediate results Variables subroutines, floating point package etc. The system Pointer is always decremented / incremented by two, independent of the byte suffix The Pointer always points to even addresses. This means the LS is always zero. Odd addresses will end up in non-predictable results. If bytes are pushed on the system stack, only the lower byte is used, the upper byte is not modified: PUSH #05h ; 0005h > TOS PUSH. #05h ; xx05h > TOS M430 Pointer () R0 - Program Counter 15 1 0 0 R1 - Pointer 15 1 0 0 fter a system reset, user software must initialize the M430 the application requirements. The following must occur: initialize the, typically to the top of : R2 - Status Register SR / Constant Generator CG1 R3 - Constant Generator CG2 R4.. R15 - user working register 5
The Pointer needs to be initialized bee the EINT instruction is executed or a CLL is used: MOV #2FFh+1, M430 Memory organisation ; locate stack at the high M430 asic Instructions: PUSH scr Word byte access Only word access Only byte access Interrupt Vector Table Program Memory ranch Control Tables Data Tables.. ootstrap Loader (SL) Data Memory () Data Memory () 16-bit Peripheral Modules 8-bit Peripheral Modules SFR 0xFFFF 0xFFE0 0x0C00 0x02FF Top of 0x0200 0x0100 0x0010 0x0000 Timer, WDC DC, DC I/O, LCD SFR Push word or byte on the stack: 2 Pointer (word) is pre-decremented by two scr @ move the source operand to TOS The source operand is not affected Status, OscOff, CPUOff and GIE bits are not affected The system Pointer is always decremented by two, independent of the byte suffix If bytes are pushed on the system stack, only the lower byte is used, the upper byte is not modified The system Pointer is also used by the interrupt routine service Example: PUSH SR ; save status register PUSH. R8 ; save lower bytes of R8 (R8 7..0 ) M430 Emulated Instructions: POP dst MOV @+, dst M430 asic Instructions: CLL dst The stack location pointed to by the Pointer (TOS) is moved to the destination. The Pointer is incremented by two afterwards: () dst + 2 Example: POP SR ; restore Status Register SR ; core instruction: MOV @+, SR POP. R7 ; the low byte of the stack is moved to R7 ; the high byte of R7 is 00h ; core instruction: MOV. @+, R7 system Pointer is always incremented by two, independent of the byte suffix n unconditional call to an address in the 64K address space: dst temp dst is evaluated and stored 2 Pointer (word) is decremented @ updated to TOS temp saved dst to subroutine call is made to an address anywhere in the 64K-address space ll addressing mode may be used The branch instruction is a word instruction system Pointer is also used by the and I instructions M430 Emulated Instructions: MOV @+, M430 16-bit Manipulation The stack location pointed to by the Pointer (TOS) is moved to the Program Counter. The Pointer is incremented by two afterward: () + 2 The programme continues at the code address following the subroutine call Status, OscOff, CPUOff and GIE bits are not affected Example: ; return from subroutine ; core instruction: MOV @+, =300h Data Code 200h fter Init CLL PUSH Subroutine POP R6 6
Stos w x86 Turbo Pascal (Intel x86) malejące adresy (dekrementacja ) przy zapisie do stosu rosnące adresy (inkrementacja ) przy odczycie ze stosu przetwarzanie danych przenoszenie argumentów do podprogramów: dostęp do szczytu stosu (TOS) adresowanie stosu tylko wskaźnikiem stosu dostęp do dowolnego elementu stosu adresowanie stosu wskaźnikiem stosu + offset (przesunięcie): Procedure ProcU (rg1, rg2: Integer); Proc(4660, 22136); ProcU MOV X, MOV X, SS:[X+2] MOV DX, SS:[X+4]... 4 =TOS X+4 uto-dekrementacja X+2 X==TOS h 34h 56h 78h 90h 01h rg1 (4660d=34h) DX rg2 (22136=5678h) X adres powrotu z podprogramu RM7 Operating Modes User usr Normal program execution mode; unprivileged mode under which most tasks run System sys Runs privileged operating system task; privileged mode using the same registers as user mode Supervisor svc protectd mode the operating system; entered on reset and when a Software Interrupt instruction is executed Privileged modes Exception modes bort abt Implements virtual memeory and/or memory protection; used to handle memory access violations Undefined und Supports software emulation of hardware coprocessors; used to handle undefined instructions IRQ irq Used general-purpose interrupt handling; entered when a low priority (normal) interrupt is raised FIQ fiq Supports a high-speed data transfer or channel process; entered when a high priority (fast) interrupt is raised Mode changes: software control, external interrupts or exception processing. RM7 CPU rchitecture Privileged Modes Exception Modes User System Supervisor bort Undefined Interrupt Saved Program Status Register R13 ( Pointer) R14 (Link Register) Current Program Status Register CPSR CPSR R0 R1 R2 R3 R4 R6 R7 R8 R9 R10 R11 R R13_svc R13_abt R13_und R14_svc R14_abt R14_und (Program Counter) CPSR_svc SR_svc CPSR_abt SR_abt CPSR_und SR_und R13_irq R14_irq CPSR_irq SR_irq Fast Interrupt R8_fiq R9_fiq R10_fiq R11_fiq R_fiq R13_fiq R14_fiq CPSR_fiq SR _fiq RM7 Register R13 RM7 Register R14 User System R13 R14 CPSR Other Modes R13_mod R14_mod CPSR_mod SR_mod Register R13 is normally used as a Pointer (). In the RM instruction set, this is by convention only, as there are no defined instructions or other functionality which use R13 in a special-case manner. Each exception mode has its own banked version of R13, which should normally be initialized to point to a stack dedicated to that exception mode. On entry, the exception handler typically be stores to this stack the values of the registers to be used. y reloading these values into the registers when it returns, the exception handler can ensure that it does not corrupt the state of the program that was being executed when the exception ocuured. In each mode register R14 is used to hold subroutine return address. The subroutine return is permed by copying R14 back to the program counter. User System R13 R14 CPSR Other Modes R13_mod R14_mod CPSR_mod SR_mod 7