Professional Documents
Culture Documents
(GSyC)
MARS
MIPS Assembler and Runtime Simulator
Introduccin
Qu es MARS?
!
q Es un entorno de desarrollo
interactivo (IDE) para la
programacin en el lenguaje
ensamblador MIPS!
q Orientado a la enseanza para
usarse junto con el Computer
Organization and Design de
Patterson y Hennessy!
Caractersticas de MARS
Features
!
q Control de la velocidad de ejecucin!
q 32 registros visibles de forma simultnea!
q Modificacin de los valores en registros y
en memoria!
q Posibilidad de mostrar los datos en
decimal o en hexadecimal!
q Navegacin por la memoria!
q Editor y ensamblador integrados en el
propio IDE!
Caractersticas de MARS
Repertorio de instrucciones
!
q Ensambla y simula casi todas las
instrucciones documentadas en el libro de
texto Computer Organization and Design,
Fourth Edition by Patterson and Hennessy,
Elsevier - Morgan Kaufmann, 2009!
q Todas las instrucciones bsicas,
pseudoinstrucciones, directivas y llamadas
al sistemas descritas en el Apndice B
estn implementadas
ori
slt
M I P S Reference Data
sll
dhex
0 / 2ahex
Store FP Single
Shift Left Logical
Store FP
Shift Right Logical
Double
swc1
sll
M[R[rs]+SignExtImm] = F[rt]
M[R[rs]+SignExtImm] = F[rt];
(2) 39/--/--/-(2)
0 / 00hex
31
26 25
21 20
M[R[rs]+SignExtImm](7:0) =
NAME
28hex
sb
Store Byte
I
R[rt] = (R[rs] < SignExtImm)? 1 : 0 (2) ahex
FLOATING-POINT
INSTRUCTION
FORMATS
R[rt](7:0)
(2)
Branch Less Than
R[rt] = (R[rs] < SignExtImm)
M[R[rs]+SignExtImm]
opcode sc
fmt
ft
fs= R[rt];
fd 38hex funct Branch Greater Than
bhex
StoreFR
Conditional
I
I
Branch Less Than or Equal
R[rt] = (atomic) ? 1 : 0 (2,7)
?1:0
(2,6)
31 SET
26 25
21 20 OPCODE
16 15
11 10
6 5
0
1
ARITHMETIC CORE INSTRUCTION
Branch
Greater Than or Equal
2
M[R[rs]+SignExtImm](15:0)
=
0
/
2b
R R[rd] = (R[rs] < R[rt]) ? 1 : 0
(6)
29hex
hex
StoreFI
Halfword
I
/ FMT
Load
Immediate
opcode sh
fmt
ft /FT
immediate
R[rt](15:0)
(2)
FOR/ FUNCT
Move
0 / 00hex
R R[rd] = R[rt] << shamt
31
26 25
21 20
16 15
0
sw
I M[R[rs]+SignExtImm]
= R[rt]
(2) 2bhex
NAME, MNEMONIC Store
MATWord
OPERATION
(Hex)
REGISTER
NAME, NUMBER, U
0 /FP02True
FI
11/8/1/-if(FPcond)PC=PC+4+BranchAddr
(4)
R R[rd] = R[rt] >> shamtOPCODE Branch On
hex bc1t
0
/
22
sub
PSEUDOINSTRUCTION
SET
Subtract
R R[rd] = R[rs] - R[rt]
(1)
Caractersticas de MARS
Shift Left Logical
(3)
Shift
Right Logical
CORE
INSTRUCTION
SET srl
FOR/ FUNCT
M[R[rs]+SignExtImm](7:0)
=
sb
Store Byte
I
NAME,
MNEMONIC MAT
OPERATION
(in Verilog)
(Hex)
R[rt](7:0)
0
/
20
add
Add
R R[rd] = R[rs] + R[rt]
(1)
hex
M[R[rs]+SignExtImm] =8 R[rt];
addi
AddStore
Immediate
I R[rt] = R[rs]
(1,2)
sc
Conditional
I + SignExtImm
hex
hex
Fl.
Pt. Num.
hex
sub
.f
00
0001
1
1
SOH
65
41
A
Double
Precision
Bias
=
1023.
4hex
beq
Branch On Equal
I
PRESERVEDACROSS
FP Divide
{F[fd],F[fd+1]} = {F[fs],F[fs+1]} /
PC=PC+4+BranchAddr
j
srl
USE rdMAX shamt 0
mul
0010 - R[rt]
2 (4) 2 STX
66
420 / 23Bhex div.d FRR NAME
opcodeNUMBER
rs
rt 11/11/--/3
funct
subu
Subtract Unsigned
R .fR[rd]00
= R[rs]
Double
{F[ft],F[ft+1]}
A CALL?
if(R[rs]!=R[rt])
jal
sra
.f
00 0011
3
3 5hex
ETX
67
43
C
MAX
06 5
NaN 0
Single
Precision
31 = F[fs]
26 25 and 21 20
16 15
11 10
bne
Branch On Not Equal
I May div
FR F[fd]
11/10/--/2
FP Multiply Single mul.s IEEE
* F[ft]
(1)
cause.f overflow
exception
PC=PC+4+BranchAddr
$zero
0
The Constant
Value
N.A.= 2047
beq
sllv
sqrt
00 0100
4 (4) 4 EOT
68
44
D
S.P.0MAX immediate
= 255, D.P. MAX
I
opcode
rs
rt
Double
Precision
Formats:
FP
Multiply
{F[fd],F[fd+1]}
=
{F[fs],F[fs+1]}
*
(2)
SignExtImm
= 00
{ 16{immediate[15]},
}45
j
bne
Jump
J PC=JumpAddr
abs.f
0101
5 (5) 5 2ENQ
69
E mul.d FR
11/11/--/2
hex immediate
$at
1
Assembler
Temporary
No
Double
31S
26 25{F[ft],F[ft+1]}
21 20
16 15 Fraction
0
Exponent
blez
srlv
mov.f
0110
6 immediate
46
F
(3)
ZeroExtImm
= 00
{ 16{1b0},
} 70
jal
Jump And Link
J R[31]=PC+8;PC=JumpAddr
(5) 6 3ACK
hex
11/10/--/1
FP Subtract Single sub.s FR F[fd]=F[fs] - F[ft]
NAME
NUMBER
$zero
$at
0
1
$v0-$v1
2-3
$a0-$a3
$t0-$t7
$s0-$s7
$t8-$t9
$k0-$k1
$gp
$sp
$fp
$ra
4-7
8-15
16-23
24-25
26-27
28
29
30
31
(Green Card) 1. Pull along perforation to separate card 2. Fold bottom side (columns 3 and 4) together
perforati
Or Immediate
The Co
Assem
Values
and Ex
Argum
Tempo
Saved
Tempo
Reserv
Global
Stack P
Frame
Return
63
62
52
51
0
(6)
unsigned
numbers
2
s
comp.)
+SignExtImm](7:0)}
slti
movz
00 1010 10 (2) a LF
74
4a
J
$t0-$t7
8-15
Temporaries
No
Load
F[rt]=M[R[rs]+SignExtImm];
(2)
ALLOCATION
STACK FRAME
(7) R[rt]={16b0,M[R[rs]
Atomic test&set00pair;
atomic,
0 ifFP4b
not atomic
sltiu movn
1011R[rt]
11= 1 ifbpair
VT
75
K
Load Halfword
ldc1 MEMORY
I
35/--/--/-25hex
lhu
I
Double
F[rt+1]=M[R[rs]+SignExtImm+4]
Higher
$s0-$s7
16-23 Stack
Saved Temporaries
Yes
andi
syscall round.w
Unsigned
+SignExtImm](15:0)}
.f 00 1100 12 (2) c FF
76
4c
L
...
BASIC INSTRUCTION
FORMATS .f 00 1101 13
mfhi $sp
R R[rd] =7fff
0 /--/--/10
Move From
Hi fffchex
Memory
ori
break
CR
77
4d HiM
ll
Load Linked
I R[rt] =trunc.w
M[R[rs]+SignExtImm]
(2,7) d 30hex
Argument
6
$t8-$t9
24-25
Temporaries
No
mflo
Move From
LoN
R R[rd] = Lo
0 /--/--/12
Addresses
xori
ceil.w.f rt
00 1110 14rd e f SO
78
4efunct
R
opcode
rs
shamt
Argument
5
lui
Load Upper Imm.
I R[rt] = {imm, 16b0}
mfc0
$k0-$k1
Reserved for
OS$fp
Kernel
No
Move From
R R[rd]
10 /0/--/0
= CR[rs] 26-27
lui
sync
floor.w.f 00 1111
15
f hexSI
79
4f Control
O
31
26I 25 R[rt] = M[R[rs]+SignExtImm]
21 20
16 15
11 10
6 5
0 mult R {Hi,Lo} = R[rs] * R[rt]
Multiply
0/--/--/18
lw
Load Word
mfhi
hex
01 0000 16 (2)10 23DLE
80
50
P
$gp
28
Global Pointer
Saved Registers Yes
Multiply51Unsigned
= R[rs] * R[rt]
(6) 0/--/--/19
I
opcode
rs = ~ (R[rs] | R[rt])
rt
immediate
mthi
(2)
01 0001 17
110 / 27
DC1
81
Q multu R {Hi,Lo}
Stack
nor
Nor
R R[rd]
hex
Dynamic
Data
$sp
29
Stack
Pointer
Yes
sra
Shift Right
Arith.
R
0/--/--/3
R[rd]
=
R[rt]
>>>
shamt
mflo
movz
.f
01
0010
18
12
DC2
82
52
R
Grows
$gp 1000 8000hex
31
26R25 R[rd] = R[rs]
21 20| R[rt]
16 15
0
0 / 25hex
or
Or
$fp
30 = F[rt]
Frame(2)
Pointer
Yes
swc1
Store FP53SingleS
I M[R[rs]+SignExtImm]
39/--/--/-mtlo
movn.f
01 0011 19
13 DC3
83
Jump Register
Static
Data
address
(3)14 dhex
Local Variables Yes
Store FP54
M[R[rs]+SignExtImm]
= F[rt];
20
DC4
84
T
$ra
Return(2)
Address
sdc1
I
3d/--/--/-1000 0000hex31
Double
M[R[rs]+SignExtImm+4]
=
F[rt+1]
21
15
NAK
85
55
U
0
0
/
2a
slt
$sp
hex
Text 4th ed.
01 0110
22 (2)16 Patterson
86
56
V Computer Organization and Design,
2009slti
by Elsevier,
All<rights
reserved.
and Hennessy,
aSYN
Lower
Set Copyright
Less Than Imm.
I R[rt]Inc.,
= (R[rs]
SignExtImm)?
1 : 0From
FLOATING-POINT
FORMATS
pc
0040
0000hex
01 0111 23
17 hex
ETB
87
57
W INSTRUCTION
Memory
Set Less Than Imm.
R[rt] = (R[rs] < SignExtImm)
FR
opcode
fmt
ft
fs
fd
funct
01 1000 24
18 bCAN
88
58
X
sltiu mult
I
Addresses
Unsigned
? 1 : 0 01 1001 25 (2,6)19 hex
Reserved
21 20
16 015
11
10
6 5
0
multu
EM
89
5931 Y 26 25
hex
Set Less Than Unsig. sltu div
R R[rd] = (R[rs] < R[rt])
? 1 : 0 26 (6)1a0 / 2b
01 1010
SUB
90 FI 5a opcode
Z
hex
fmt
ft
immediate
divu
01 1011 27
1b0 / 00
ESC
91
5b31 [ 26 25 DATA
ALIGNMENT
sll
Shift Left Logical
R R[rd] = R[rt] << shamt
21 20
16 15
0
hex
01 1100 28
1c0 / 02FS
92
5c
\
Shift Right Logical srl
R R[rd] = R[rt] >> shamt
Double Word
hex
PSEUDOINSTRUCTION
SET
01 1101 29
1d GS
93
5d
]
M[R[rs]+SignExtImm](7:0)
MNEMONIC Word OPERATION
Word
01 1110 = 30
1e 28hex
RS
94
5e
^NAME
sb
Store Byte
I
blt
R[rt](7:0)
if(R[rs]<R[rt]) PC = Label
01 1111 31 (2) 1f US
95 Branch
5f Less
_ Than
Halfword
Halfword
Halfword
Halfword
bgt
if(R[rs]>R[rt])
PC
=
Label
Branch
Greater
Than
M[R[rs]+SignExtImm]
= R[rt]; 32
add
cvt.s.f
10 0000
20 38Space 96
60
J
Or Immediate
opcode
ori
I R[rt] = R[rs] | ZeroExtImm
01 0100
01 0101
26R25 R[rd] = (R[rs] < R[rt])
?1:0
Caractersticas de MARS
Llamadas al sistema
!
q Varios servicios de sistema, principalmente para
la realizacin de operaciones de entrada/salida,
estn disponibles:!
q
q
q
q
q
q
q
q
q
q
print integer !
print float!
print double!
print string !
sbrk (allocate heap memory) !
exit (terminate execution)!
print character !
read character!
MIDI out!
!
(http://courses.missouristate.edu/KenVollmar/MARS/Help/SyscallHelp.html)!
GSyC 2012 - MARS
Caractersticas de MARS
Caractersticas de MARS
Ventana de ejecucin
!
q Para ensamblar un programa hay que
pinchar en el icono! !
q Si no hay errores de ensamblado, se abre
la ventana de ejecucin!
q En caso de que el ensamblado falle, se
muestra una ventana con los errores y su
correspondiente nmero de lnea!
Caractersticas de MARS
Ventana de ejecucin
Caractersticas de MARS
Ventana de ejecucin
Caractersticas de MARS
Ventana de ejecucin
q Ventana Data Segment:!
q Datos almacenados por el programa!
q Controles para mostrar el contenido de partes especiales de la
memoria, como la pila o el heap!
q Posibilidad de mostrar el contenido de las posiciones de
memoria en hexadecimal o en decimal!
q Ventana Registers:!
q Muestra el contenido de los registro, tanto en decimal como en
hexadecimal!
q Existen ventanas separadas para los registros de propsito
general, los registros de coma flotante del Coprocessor 1 y los
registros de excepcin del Coprocessor 0!
10
Caractersticas de MARS
Ventana de ejecucin
11
Caractersticas de MARS
Ventana de ejecucin
q Consola!
q Mensajes de MARS, mensajes de error de
ensamblado
q Mensajes de entrada/salida generados en
tiempo de ejecucin por las llamadas al sistema
q Estas ventanas se activan cuando se escribe
texto sobre ellas
12
Caractersticas de MARS
Instrucciones soportadas
13
Caractersticas de MARS
Instrucciones soportadas
14
Programacin en ensamblador
15
Programacin en ensamblador
Ensambladores
q Un programa ensamblador traduce un fichero con sentencias
en lenguaje ensamblador en un fichero con instrucciones
mquina y datos binarios!
q El proceso de traduccin tienen dos partes:!
1. Localizar posiciones de memoria etiquetadas, de tal forma
que la direccin de un nombre simblico se conozca cuando
las instrucciones se traduzcan!
2. Traducir cada sentencia en ensamblador combinando
cdigos de operacin, identificadores de registros y etiquetas
en una instruccin legal!
q El cdigo objeto o fichero objeto no puede ser ejecutado
puesto que incluye referencias a datos o procedimientos en
otros ficheros!
q Variables externas o globales!
q Variables locales!
16
A-8
Appendix A
Programacin en ensamblador
#include <stdio.h>
main (int
char *argv[])
Linkadores
o argc,
enlazadores
{
int
int i;
q El programa
depende de otra herramienta, el
int sum ensamblador
= 0;
linkador!
for (i = 0; i <= 100; i = i + 1) sum = sum + i * i;
printf ("The sum from 0 .. 100 is %d\n", sum);
q El linkador
combina un conjunto de ficheros objeto y libreras
}
en un fichero ejecutable resolviendo las referencias a
FIGURE A.1.5 The routine written in the C programming language.
etiquetas externas!
Program
Compiler
Assembler
Linker
Computer
FIGURE A.1.6
compiler.
tainty about the time cost of operations, programmers may find it difficult to
ensure that a high-level language program responds within a definite time intervalsay, 1 millisecond after a sensor detects that a tire is skidding. An assembly
language programmer, on the other hand, has tight control over which instrucexecute. In addition, in embedded applications, reducing a programs size,
GSyC 2012 -tions
MARS
so that it fits in fewer memory chips, reduces the cost of the embedded computer.
A hybrid approach, in which most of a program is written in a high-level language and time-critical sections are written in assembly language, builds on the
17
Programacin en ensamblador
Appendix A Assemblers, Linkers, and the SPIM Simulator
Text
segment
Data
segment
Relocation
information
Symbol
table
Debugging
information
FIGURE A.2.1 Object file. A UNIX assembler produces an object file with six distinct sections.
Programacin en ensamblador
A.5 Memory Usage
Gestin
de la memoria
!
q Los sistemas basados en el procesador MIPS dividen la memoria en
tres partes!
7fff fffchex
Stack segment
Dynamic data
10000000hex
Static data
Data segment
Text segment
400000hex
Reserved
FIGURE A.5.1
Layout
memory.
(text,
data,ofstack,
kernel text, kernel data) are limited to 4MB each
19
A MIPS processor consists of an integer processing unit (the CPU) and a collection of coprocessors that perform ancillary tasks or operate on other types of data
such as floating-point numbers (see Figure A.10.1). SPIM simulates two coprocesProgramacin
en 0ensamblador
sors. Coprocessor
handles exceptions and interrupts. Coprocessor 1 is the floating-point unit. SPIM simulates most aspects of this unit.
Modos
de direccionamiento
Addressing
Modes
!
MIPS
is a load-store
architecture, which
means that only load and lo
store
instrucq
MIPS
es una arquitectura
carga-almacenamiento,
que
tions access memory. Computation instructions operate only on values in regissignifica que slo las instrucciones de carga y
ters. The bare machine provides only one memory-addressing mode: c(rx),
almacenamiento
pueden
acceder
a memoria!
which
uses the sum of the
immediate
c and register rx as the address. The virq
instrucciones
computacionales
operan
slo
datos
tualLas
machine
provides the
following addressing
modes
for sobre
load and
store
instructions:
almacenados en registros!
Format
Address computation
(register)
contents of register
imm
immediate
imm (register)
label
address of label
label imm
Most load and store instructions operate only on aligned data. A quantity is
aligned if its memory address is a multiple of its size in bytes. Therefore, a halfGSyC 2012 - MARS
20
struction
expands to between
several machine
When youissingle-step
or examThe
correspondence
the twoinstructions.
sets of instructions
fairly simple
since
ine memory,
instructions
that you to
seefill
aredelay
different
SPIM
does notthe
reorganize
instructions
slots.from the source program.
The correspondence
between
the two sets of instructions is fairly simple since
Programacin
en ensamblador
SPIM does not reorganize instructions to fill delay slots.
Byte Order
Ordenacin
de los bytes
Processors
can
! number bytes within a word so the byte with the lowest number is
Byte Order
q Losorbytes
de unaone.
palabra
pueden enumerar!
either the leftmost
rightmost
These
convention
used by a machine is called
Processors can number bytes within a word so the byte with the lowest number is
its byte order. q
MIPS
processors que
can utiliza
operate
eithersebig-endian
La convencin
unawith
mquina
denomina or little-endian
either the leftmost
or rightmost
The convention used by a machine is called
ordenacin
losone.
bytes!
byte order. For example,
in adebig-endian
machine, the directive .byte 0, 1, 2, 3
its byte order.qMIPS
processors
can
operate
with either
big-endian
or little-endian
El
procesador
MIPS
puede
operar
tanto
en
big-endian
como
would result in a memory word containing
byte order. For example,
in a big-endian
machine, the directive .byte 0, 1, 2, 3
en little-endian
!
would resultq
in Por
a memory
word
containing
ejemplo,
en una
mquina big-endian, la directiva .byte
Byte
0, 1, 2, 3 resulta en
que# una palabra de memoria
contiene:!
0
1Byte 2#
Byte #
3
2Byte 1#
21
SPIM operates with both byte orders. SPIMs byte order is the same as the byte
q Etiquetas!
q Se utilizan para referirse a posiciones de memoria o a
instrucciones!
q Son case insensitive!
q Slo se puede utilizar una etiqueta por lnea!
q Van seguidas de :!
qSecciones ms importantes:
!!
q .data
q .text
GSyC 2012 - MARS
22
23
!
!
!
q.byte b1,, bn
Almacena n valores de 8 bits en bytes sucesivos de memoria!
q.half h1, , hn
Almacena n valores de 16 bits en medias palabras sucesivas de
memoria!
q.word w1,, wn
Almacena n valores de 32 bits en palabras sucesivas de memoria!
q.space n
Reserva n bytes de espacio en el segmento de datos
!
GSyC 2012 - MARS
24
operandos!
qEl tipo y nmero de los operandos viene
determinado por el tipo de instruccin!
GSyC 2012 - MARS
25
Ejemplo
fibs:
size:
main:
loop:
.data
.word
0 : 12
.word 12
.text
la
$t0, fibs
la
$t5, size
lw
$t5, 0($t5)
li
$t2, 1
add.d $f0, $f2, $f4
sw
$t2, 0($t0)
sw
$t2, 4($t0)
addi $t1, $t5, -2
lw
$t3, 0($t0)
lw
$t4, 4($t0)
add $t2, $t3, $t4
sw
$t2, 8($t0)
addi $t0, $t0, 4
addi $t1, $t1, -1
bgtz $t1, loop
la
$a0, fibs
add $a1, $zero, $t5
jal print
li
$v0, 10
syscall
load
load
load
1 is
address of array
address of size variable
array size
first and second Fib. number
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
F[0] = 1
F[1] = F[0] = 1
Counter for loop, will execute (size-2) times
Get value from array F[n]
Get value from array F[n+1]
$t2 = F[n] + F[n+1]
Store F[n+2] = F[n] + F[n+1] in array
increment address of Fib. number source
decrement loop counter
repeat if not finished yet.
first argument for print (array)
second argument for print (size)
call print routine.
system call for exit
we are out of here.
26
qLlamadas al sistema!
qEntrada/Salida!
qLlamada a procedimiento!
qExcepciones e interrupciones!
27