Download 3. SYSCALL functions available in MARS

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
MARS - Mips Assembly and Runtime Simulator
Release 4.3
January 2013
1. Introduction
MARS, the Mips Assembly and Runtime Simulator, will assemble and simulate the
execution of MIPS assembly language programs. It can be used either from a command
line or through its integrated development environment (IDE). MARS is written in Java
and requires at least Release 1.5 of the J2SE Java Runtime Environment (JRE) to work. It
is distributed as an executable JAR file. The MARS home page is
http://www.cs.missouristate.edu/MARS/. This document is available for printing
there.
As of Release 4.0, MARS assembles and simulates 155 basic instructions of the MIPS-32
instruction set, approximately 370 pseudo-instructions or instruction variations, the 17
syscall functions mainly for console and file I/O defined by SPIM, and an additional 22
syscalls for other uses such as MIDI output, random number generation and more. These
are listed in separate help tabs. It supports seven different memory addressing modes for
load and store instructions: label, immed, label+immed, ($reg), label($reg),
immed($reg), and label+immed($reg), where immed is an integer up to 32 bits. A
setting is available to disallow use of pseudo-instructions and extended instruction
formats and memory addressing modes.
Our guiding reference in implementing the instruction set has been Computer
Organization and Design, Fourth Edition by Patterson and Hennessy, Elsevier - Morgan
Kaufmann, 2009. It summarizes the MIPS-32 instruction set and pseudo-instructions in
Figures 3.24 and 3.25 on pages 279-281, with details provided in the text and in
Appendix B. MARS Releases 3.2 and above implement all the instructions in Appendix
B and those figures except the delay branches from the left column of Figure 3.25. It also
implements all the system services (syscalls) and assembler directives documented in
Appendix B.
The MARS IDE provides program editing and assembling but its real strength is its
support for interactive debugging. The programmer can easily set and remove execution
breakpoints or step through execution forward or backward (undo) while viewing and
directly editing register and memory contents.
Page 1
2. Configuration Settings
Releases 3.0 and later include a Settings menu. The Editor and Exception Handler items
launch a dialog but the rest are each controlled by a checkbox for selecting or deselecting
it (checked means true, unchecked means false). Settings and their default values are:
1. Display the Labels window in the Execute tab. Default value is false. If
selected, the Labels window, which shows the name and associated address for
each label defined in the program, will be displayed to the right of the Text
Segment.
2. Provide program arguments to the MIPS program. Default value is false.
New in Release 3.5. If selected, a text field will appear at the top of the Text
Segment Display. Any argument values in this text field at the time of program
execution will be stored in MIPS memory prior to execution. The argument count
(argc) will be placed in register $a0, and the address of an array of null-terminated
strings containing the arguments (argv) will be placed in register $a1. These
values are also available on the runtime stack ($sp).
3. Popup Dialog for input syscalls (5,6,7,8,12). New in Release 4.0. Default value
is false. If selected, runtime console input will be entered using popup dialogs
(this was the only option prior to Release 4.0). Otherwise, input is entered directly
into the Run I/O tab at the bottom of the screen.
4. Display memory addresses in hexadecimal. Default value is true. If deselected,
addresses will be displayed in decimal. This setting can also be toggled in a
checkbox on the lower border of the Data Segment Window.
5. Display memory and register contents in hexadecimal. Default value is true. If
deselected, vlaues will be displayed in decimal. This setting can also be toggled in
a checkbox on the lower border of the Data Segment Window.
6. Assemble a file automatically as soon as it is opened, and initialize the File
Open dialog with the most-recently opened file. Default value is false. This is
convenient if you use an external editor for composing your programs.
7. Assemble applies to all files in directory. Default value is false. If selected, the
file currently open in the editor will become the "main" program in a multi-file
assemble-and-link operation involving all assembly files (*.asm; *.s) in its
directory. If successful, execution will begin with the currently open file.
8. Assembler warnings are considered errors. Default value is false. New in
Release 3.5. If selected, the assemble operation will fail if any warnings are
produced. At this time, all assembler warnings relate to unrecognized or ignored
directives. MARS may be able to assemble code produced by compilers for other
MIPS assemblers if this setting is deselected.
9. Initialize Program Counter to global 'main' if defined. Default value is false.
New in Release 3.8. If selected, the Program Counter will be initialized to the
address of the text segment statement with the global label 'main' if it exists. If it
does not exist or if the setting is not selected, the Program Counter will be
initialized to the default text segment starting address.
Page 2
10. Permit programs to use extended (pseudo) instructions and formats. Default
value is true. This includes all memory addressing modes other than the MIPS
native mode (16 bit constant offset added to register content).
11. Assemble and execute programs using delayed branching. Default value is
false. MIPS processors use delayed branches as part of the pipelined design, but it
can be confusing to programmers. With delayed branching, the instruction
following a branch or jump instruction will always be executed even if the branch
condition is true! Assemblers and, failing that, programmers, often deal with this
by following branches and jumps with a "nop" instruction. The MARS assembler
does not insert a nop. When delayed branching was introduced in Release 3.3, the
machine code generated for a branch instruction depended on this setting since its
target value is relative to the Program Counter (PC-relative addressing).
Although technically correct, this led to confusion in the MARS community
because the generated code did not match textbook examples. Starting with
Release 3.4, the relative branching offset is always calculated as if delayed
branching is enabled even when it is not. The runtime simulation adjusts
accordingly.
12. The Editor dialog. Use it to view and modify editor font settings. New with
Release 3.3.
13. The Highlighting dialog. Use it to modify color and font settings for the
highlighting of table items in the Text Segment window, Data Segment window,
Registers window, Coprocessor0 window and Coprocessor1 window.
Highlighting occurs during timed, stepped, and backstepped simulation. Color and
font for normal (non-highlighted) display can also be set separately for evennumbered and odd-numbered display rows but not individually by windows. New
with Release 3.6.
14. The Exception Handler dialog. It has the setting: Include this exception handler
in all assemble operations. Default value is false. If selected, a button to browse to
the desired file is enabled. New with Release 3.2
15. The Memory Configuration dialog. Use it to select from among available MIPS
address space configurations. The default configuration is derived from SPIM; it
was only one available from MARS 1.0 through MARS 3.6. New with Release
3.7.
Beginning with Release 3.2, settings are retained from one interactive session to the next.
Settings
are
stored
in
a
system-dependent
way as
specified
by
java.util.prefs.Preferences. Windows systems use the Registry. These settings are
independent of command options given when using MARS from a command line; neither
affects the other. We anticipate future releases will include additional settings and
preferences.
Page 3
3. SYSCALL functions available in MARS
3.1. Introduction
A number of system services, mainly for input and output, are available for use by your
MIPS program. They are described in the table below.
MIPS register contents are not affected by a system call, except for result registers as
specified in the table below.
3.2.
How to use SYSCALL system services
Step 1. Load the service number in register $v0.
Step 2. Load argument values, if any, in $a0, $a1, $a2, or $f12 as specified.
Step 3. Issue the SYSCALL instruction.
Step 4. Retrieve return values, if any, from result registers as specified.
Example: display the value stored in $t0 on the console
li $v0, 1
add $a0, $t0, $zero
# service 1 is print integer
# load desired value into argument register
# $a0, using pseudo-op
syscall
3.3.
Table of Available Services
Service
Code
in
$v0
Arguments
Result
print integer
1
$a0 = integer to
print
print float
2
$f12 = float to print
print double
3
$f12 = double to
print
print string
4
$a0 = address of
null-terminated
string to print
read integer
5
$v0 contains integer read
read float
6
$f0 contains float read
read double
7
$f0 contains double read
read string
8
$a0 = address of
input buffer
$a1 = maximum
number of
characters to read
sbrk (allocate heap
9
$a0 = number of
See note below table
$v0 contains address of allocated
Page 4
memory)
exit (terminate
execution)
10
print character
11
read character
12
bytes to allocate
memory
$a0 = character to
print
See note below table
$v0 contains character read
13
$a0 = address of
null-terminated
string containing
filename
$a1 = flags
$a2 = mode
14
$a0 = file descriptor
$a1 = address of
$v0 contains number of characters
input buffer
read (0 if end-of-file, negative if
$a2 = maximum
error). See note below table
number of
characters to read
write to file
15
$a0 = file descriptor
$a1 = address of
$v0 contains number of characters
output buffer
written (negative if error). See note
$a2 = number of
below table
characters to write
close file
16
$a0 = file descriptor
exit2 (terminate with
value)
17
$a0 = termination
result
open file
read from file
$v0 contains file descriptor
(negative if error). See note below
table
See note below table
Services 1 through 17 are compatible with the SPIM simulator, other than Open File (13)
as described in the Notes below the table. Services 30 and higher are exclusive to MARS.
30
$a0 = low order 32 bits of system
time
$a1 = high order 32 bits of system
time. See note below table
MIDI out
31
$a0 = pitch (0-127)
$a1 = duration in
milliseconds
Generate tone and return
$a2 = instrument (0immediately. See note below table
127)
$a3 = volume (0127)
sleep
32
$a0 = the length of
time to sleep in
milliseconds.
time (system time)
Causes the MARS Java thread to
sleep for (at least) the specified
number of milliseconds. This timing
Page 5
will not be precise, as the Java
implementation will add some
overhead.
MIDI out synchronous
33
$a0 = pitch (0-127)
$a1 = duration in
milliseconds
Generate tone and return upon tone
$a2 = instrument (0completion. See note below table
127)
$a3 = volume (0127)
print integer in
hexadecimal
34
$a0 = integer to
print
Displayed value is 8 hexadecimal
digits, left-padding with zeroes if
necessary.
print integer in binary
35
$a0 = integer to
print
Displayed value is 32 bits, leftpadding with zeroes if necessary.
print integer as
unsigned
36
$a0 = integer to
print
Displayed as unsigned decimal
value.
40
$a0 = i.d. of
pseudorandom
number generator
(any int).
$a1 = seed for
corresponding
pseudorandom
number generator.
No values are returned. Sets the
seed of the corresponding
underlying Java pseudorandom
number generator
(java.util.Random). See note
below table
41
$a0 = i.d. of
pseudorandom
number generator
(any int).
$a0 contains the next
pseudorandom, uniformly
distributed int value from this
random number generator's
sequence. See note below table
42
$a0 = i.d. of
pseudorandom
number generator
(any int).
$a1 = upper bound
of range of returned
values.
$a0 contains pseudorandom,
uniformly distributed int value in
the range 0 <= [int] < [upper
bound], drawn from this random
number generator's sequence. See
note below table
43
$a0 = i.d. of
pseudorandom
number generator
(any int).
$f0 contains the next
pseudorandom, uniformly
distributed float value in the range
0.0 <= f < 1.0 from this random
number generator's sequence. See
(not used)
set seed
random int
random int range
random float
37-39
Page 6
note below table
random double
(not used)
ConfirmDialog
InputDialogInt
InputDialogFloat
InputDialogDouble
InputDialogString
$a0 = i.d. of
pseudorandom
number generator
(any int).
$f0 contains the next
pseudorandom, uniformly
distributed double value in the
range 0.0 <= f < 1.0 from this
random number generator's
sequence. See note below table
$a0 = address of
null-terminated
string that is the
message to user
$a0 contains value of user-chosen
option
0: Yes
1: No
2: Cancel
$a0 = address of
null-terminated
string that is the
message to user
$a0 contains int read
$a1 contains status value
0: OK status
-1: input data cannot be correctly
parsed
-2: Cancel was chosen
-3: OK was chosen but no data had
been input into field
$a0 = address of
null-terminated
string that is the
message to user
$f0 contains float read
$a1 contains status value
0: OK status
-1: input data cannot be correctly
parsed
-2: Cancel was chosen
-3: OK was chosen but no data had
been input into field
53
$a0 = address of
null-terminated
string that is the
message to user
$f0 contains double read
$a1 contains status value
0: OK status
-1: input data cannot be correctly
parsed
-2: Cancel was chosen
-3: OK was chosen but no data had
been input into field
54
$a0 = address of
null-terminated
string that is the
message to user
$a1 = address of
input buffer
$a2 = maximum
See Service 8 note below table
$a1 contains status value
0: OK status. Buffer contains the
input string.
-2: Cancel was chosen. No change
to buffer.
-3: OK was chosen but no data had
44
45-49
50
51
52
Page 7
number of
characters to read
MessageDialog
MessageDialogInt
MessageDialogFloat
been input into field. No change to
buffer.
-4: length of the input string
exceeded the specified maximum.
Buffer contains the maximum
allowable input string plus a
terminating null.
55
$a0 = address of
null-terminated
string that is the
message to user
$a1 = the type of
message to be
displayed:
0: error message,
indicated by Error
icon
1: information
N/A
message, indicated
by Information icon
2: warning message,
indicated by
Warning icon
3: question message,
indicated by
Question icon
other: plain message
(no icon displayed)
56
$a0 = address of
null-terminated
string that is an
information-type
message to user
$a1 = int value to
display in string
form after the first
string
57
$a0 = address of
null-terminated
string that is an
information-type
N/A
message to user
$f12 = float value to
display in string
form after the first
N/A
Page 8
string
MessageDialogDouble
MessageDialogString
58
$a0 = address of
null-terminated
string that is an
information-type
message to user
N/A
$f12 = double value
to display in string
form after the first
string
59
$a0 = address of
null-terminated
string that is an
information-type
message to user
$a1 = address of
null-terminated
string to display
after the first string
N/A
NOTES: Services numbered 30 and higher are not provided by SPIM
Service 8 - Follows semantics of UNIX 'fgets'. For specified length n, string can be no
longer than n-1. If less than that, adds newline to end. In either case, then pads with null
byte If n = 1, input is ignored and null byte placed at buffer address. If n < 1, input is
ignored
and
nothing
is
written
to
the
buffer.
Service 11 - Prints ASCII character corresponding to contents of low-order byte.
Service 13 - MARS implements three flag values: 0 for read-only, 1 for write-only with
create, and 9 for write-only with create and append. It ignores mode. The returned file
descriptor will be negative if the operation failed. The underlying file I/O implementation
uses
java.io.FileInputStream.read()
to
read
and
java.io.FileOutputStream.write() to write. MARS maintains file descriptors
internally and allocates them starting with 3. File descriptors 0, 1 and 2 are always open
for: reading from standard input, writing to standard output, and writing to standard error,
respectively
(new
in
release
4.3).
Services 13,14,15 - In MARS 3.7, the result register was changed to $v0 for SPIM
compatability. It was previously $a0 as erroneously printed in Appendix B of Computer
Organization
and
Design,.
Service 17 - If the MIPS program is run under control of the MARS graphical interface
(GUI),
the
exit
code
in
$a0
is
ignored.
Service 30 - System time comes from java.util.Date.getTime() as milliseconds
since
1
January
1970.
Services 31,33 - Simulate MIDI output through sound card. Details below.
Services 40-44 use underlying Java pseudorandom number generators provided by the
java.util.Random class. Each stream (identified by $a0 contents) is modeled by a
Page 9
different Random object. There are no default seed values, so use the Set Seed service (40)
if replicated random sequences are desired.
3.4.
Example of File I/O
The sample MIPS program below will open a new file for writing, write text to it from a
memory buffer, then close it. The file will be created in the directory in which MARS
was run.
# Sample MIPS program that writes to a new file.
#
by Kenneth Vollmar and Pete Sanderson
.data
fout:
.asciiz "testout.txt"
# filename for output
buffer: .asciiz "The quick brown fox jumps over the lazy dog."
.text
###############################################################
# Open (for writing) a file that does not exist
li
$v0, 13
# system call for open file
la
$a0, fout
# output file name
li
$a1, 1
# Open for writing (flags are 0: read, 1: write)
li
$a2, 0
# mode is ignored
syscall
# open a file (file descriptor returned in $v0)
move $s6, $v0
# save the file descriptor
###############################################################
# Write to file just opened
li
$v0, 15
# system call for write to file
move $a0, $s6
# file descriptor
la
$a1, buffer
# address of buffer from which to write
li
$a2, 44
# hardcoded buffer length
syscall
# write to file
###############################################################
# Close the file
li
$v0, 16
# system call for close file
move $a0, $s6
# file descriptor to close
syscall
# close file
###############################################################
3.5.
Using SYSCALL system services 31 and 33: MIDI output
These system services are unique to MARS, and provide a means of producing sound.
MIDI output is simulated by your system sound card, and the simulation is provided by
the javax.sound.midi package.
Service 31 will generate the tone then immediately return. Service 33 will generate the
tone then sleep for the tone's duration before returning. Thus it essentially combines
services 31 and 32.
This service requires four parameters as follows:
pitch ($a0)
Page 10
 Accepts a positive byte value (0-127) that denotes a pitch as it would be represented in
MIDI
 Each number is one semitone / half-step in the chromatic scale.
 0 represents a very low C and 127 represents a very high G (a standard 88 key piano
begins at 9-A and ends at 108-C).
 If the parameter value is outside this range, it applies a default value 60 which is the same
as middle C on a piano.
 From middle C, all other pitches in the octave are as follows:
 61 = C# or Db
 65 = E# or F
 69 = A
 62 = D
 66 = F# or Gb
 70 = A# or Bb
 63 = D# or Eb
 67 = G
 71 = B or Cb
 64 = E or Fb
 68 = G# or Ab
 72 = B# or C
 To produce these pitches in other octaves, add or subtract multiples of 12.
duration in milliseconds ($a1)
 Accepts a positive integer value that is the length of the tone in milliseconds.
 If the parameter value is negative, it applies a default value of one second (1000
milliseconds).
instrument ($a2)
 Accepts a positive byte value (0-127) that denotes the General MIDI "patch" used to play
the tone.
 If the parameter is outside this range, it applies a default value 0 which is an Acoustic
Grand Piano.
 General MIDI standardizes the number associated with each possible instrument (often
referred to as program change numbers), however it does not determine how the tone will
sound. This is determined by the synthesizer that is producing the sound. Thus a Tuba
(patch 58) on one computer may sound different than that same patch on another computer.
 The 128 available patches are divided into instrument families of 8:
0-7
Piano
64-71
Reed
8-15
Chromatic Percussion
72-79
Pipe
16-23
Organ
80-87
Synth Lead
24-31
Guitar
88-95
Synth Pad
32-39
Bass
96-103
Synth Effects
40-47
Strings
104-111 Ethnic
48-55
Ensemble
112-119 Percussion
56-63
Brass
120-127 Sound Effects
 Note that outside of Java, General MIDI usually refers to patches 1-128. When referring
to a list of General MIDI patches, 1 must be subtracted to play the correct patch. For a full
list of General MIDI instruments, see www.midi.org/about-midi/gm/gm1sound.shtml. The
General MIDI channel 10 percussion key map is not relevant to the toneGenerator method
Page 11
because it always defaults to MIDI channel 1.
volume ($a3)
 Accepts a positive byte value (0-127) where 127 is the loudest and 0 is silent. This value
denotes MIDI velocity which refers to the initial attack of the tone.
 If the parameter value is outside this range, it applies a default value 100.
 MIDI velocity measures how hard a note on (or note off) message is played, perhaps on a
MIDI controller like a keyboard. Most MIDI synthesizers will translate this into volume on
a logarithmic scale in which the difference in amplitude decreases as the velocity value
increases.
 Note that velocity value on more sophisticated synthesizers can also affect the timbre of
the tone (as most instruments sound different when they are played louder or softer).
System service 31 was developed and documented by Otterbein student Tony Brock in
July 2007.
4. Using MARS through its Integrated Development Environment
(IDE)
The IDE is invoked when MARS is run with no command arguments, e.g. java -jar
mars.jar. It may also be launched from a graphical interface by double-clicking the
mars.jar icon that represents this executable JAR file. The IDE provides basic editing,
assembling and execution capabilities. Hopefully it is intuitive to use. Here are comments
on some features.



Menus and Toolbar: Most menu items have equivalent toolbar icons. If the
function of a toolbar icon is not obvious, just hover the mouse over it and a tool
tip will soon appear. Nearly all menu items also have keyboard shortcuts. Any
menu item not appropriate in a given situation is disabled.
Editor: MARS includes two integrated text editors. The default editor, new in
Release 4.0, features syntax-aware color highlighting of most MIPS language
elements and popup instruction guides. The original, generic, text editor without
these features is still available and can be selected in the Editor Settings dialog. It
supports a single font which can be modified in the Editor Settings dialog. The
bottom border of either editor includes the cursor line and column position and
there is a checkbox to display line numbers. They are displayed outside the
editing area. If you use an external editor, MARS provides a convenience setting
that will automatically assemble a file as soon as it is opened. See the Settings
menu.
Message Areas: There are two tabbed message areas at the bottom of the screen.
The Run I/O tab is used at runtime for displaying console output and entering
console input as program execution progresses. You have the option of entering
console input into a pop-up dialog then echoes to the message area. The MARS
Messages tab is used for other messages such as assembly or runtime errors and
Page 12




informational messages. You can click on assembly error messages to select the
corresponding line of code in the editor.
MIPS Registers: MIPS registers are displayed at all times, even when you are
editing and not running a program. While writing your program, this serves as a
useful reference for register names and their conventional uses (hover mouse over
the register name to see tool tips). There are three register tabs: the Register File
(integer registers $0 through $31 plus LO, HI and the Program Counter), selected
Coprocesor 0 registers (exceptions and interrupts), and Coprocessor 1 floating
point registers.
Assembly: Select Assemble from the Run menu or the corresponding toolbar icon
to assemble the file currently in the Edit tab. Prior to Release 3.1, only one file
could be assembled and run at a time. Releases 3.1 and later provide a primitive
Project capability. To use it, go to the Settings menu and check Assemble
operation applies to all files in current directory. Subsequently, the assembler
will assemble the current file as the "main" program and also assemble all other
assembly files (*.asm; *.s) in the same directory. The results are linked and if all
these operations were successful the program can be executed. Labels that are
declared global with the ".globl" directive may be referenced in any of the other
files in the project. There is also a setting that permits automatic loading and
assembly of a selected exception handler file. MARS uses the MIPS32 starting
address for exception handlers: 0x80000180.
Execution: Once a MIPS program successfully assembles, the registers are
initialized and three windows in the Execute tab are filled: Text Segment, Data
Segment, and Program Labels. The major execution-time features are described
below.
Labels Window: Display of the Labels window (symbol table) is controlled
through the Settings menu. When displayed, you can click on any label or its
associated address to center and highlight the contents of that address in the Text
Segment window or Data Segment window as appropriate.
The assembler and simulator are invoked from the IDE when you select the Assemble,
Go, or Step operations from the Run menu or their corresponding toolbar icons or
keyboard shortcuts. MARS messages are displayed on the MARS Messages tab of the
message area at the bottom of the screen. Runtime console input and output is handled in
the Run I/O tab.
5. Interactive Debugging Features
MARS provides many features for interactive debugging through its Execute pane.
Features include:


In Step mode, the next instruction to be simulated is highlighted and memory
content displays are updated at each step.
Select the Go option if you want to simulate continually. It can also be used to
continue simulation from a paused (step, breakpoint, pause) state.
Page 13








Breakpoints are easily set and reset using the check boxes next to each instruction
displayed in the Text Segment window. New in Release 3.8: You can temporarily
suspend breakpoints using Toggle Breakpoints in the Run menu or by clicking the
"Bkpt" column header in the Text Segment window. Repeat, to re-activate.
When running in the Go mode, you can select the simulation speed using the Run
Speed slider. Available speeds range from .05 instructions per second (20 seconds
between steps) up to 30 instructions per second, then above this offers an
"unlimited" speed. When using "unlimited" speed, code highlighting and memory
display updating are turned off while simulating (but it executes really fast!).
When a breakpoint is reached, highlighting and updating occur. Run speed can be
adjusted while the program is running.
When running in the Go mode, you can pause or stop simulation at any time using
the Pause or Stop features. The former will pause execution and update the
display, as if you were stepping or at a breakpoint. The latter will terminate
execution and display final memory and register values. If running at "unlimited"
speed, the system may not respond immediately but it will respond.
You have the ability to interactively step "backward" through program execution
one instruction at a time to "undo" execution steps. It will buffer up to 2000 of the
most recent execution steps (this limit is stored in a properties file and can be
changed). It will undo changes made to MIPS memory, registers or condition
flags, but not console or file I/O. This should be a great debugging aid. It is
available anytime execution is paused and at termination (even if terminated due
to exception).
When program execution is paused or terminated, select Reset to reset all memory
cells and registers to their initial post-assembly values. In fact, Reset is
implemented by re-assembling the program.
Memory addresses and values, and register values, can be viewed in either
decimal or hexadecimal format. All data are stored in little-endian byte order
(each word consists of byte 3 followed by byte 2 then 1 then 0). Note that each
word can hold 4 characters of a string and those 4 characters will appear in the
reverse order from that of the string literal.
Data segment contents are displayed 512 bytes at a time (with scrolling) starting
with the data segment base address (0x10010000). Navigation buttons are
provided to change the display to the next section of memory, the previous, or
back to the initial (home) range. A combo box is also provided to view memory
contents in the vicinity of the stack pointer (contents of MIPS $sp register), global
pointer (contents of MIPS $gp register), the heap base address (0x10040000),
.extern globals (0x10000000), the kernel data segment (0x90000000), or memorymapped IO (MMIO, 0xFFFF0000).
Contents of any data segment memory word and almost any MIPS register can be
modified by editing its displayed table cell. Double-click on a cell to edit it and
press the Enter key when finished typing the new value. If you enter an invalid
32-bit integer, the word INVALID appears in the cell and memory/register
contents are not affected. Values can be entered in either decimal or hexadecimal
(leading "0x"). Negative hexadecimal values can be entered in either two's
Page 14



complement or signed format. Note that three of the integer registers (zero,
program counter, return address) cannot be edited.
Contents of cells representing floating point registers can be edited as described
above and will accept valid hexadecimal or decimal floating point values. Since
each double-precision register overlays two single-precision registers, any
changes to a double-precision register will affect one or both of the displayed
contents of its corresponding single-precision registers. Changes to a singleprecision register will affect the display of its corresponding double-precision
register. Values entered in hexadecimal need to conform to IEEE-754 format.
Values entered in decimal are entered using decimal points and E-notation (e.g.
12.5e3 is 12.5 times 10 cubed).
Cell contents can be edited during program execution and once accepted will
apply starting with the next instruction to be executed.
Clicking on a Labels window entry will cause the location associated with that
label to be centered and highlighted in the Text Segment or Data Segment
window as appropriate. Note the Labels window is not displayed by default but
can be by selecting it from the Settings menu.
Reference:http://courses.missouristate.edu/kenvollmar/mars/help/MarsHelpIntro.html
Page 15
An Assembly Language I.D.E. To Engage Students Of All Levels
* A Tutorial *
Pete Sanderson, Otterbein College, [email protected]
Ken Vollmar, Missouri State University, [email protected]
MARS is a software simulator for the MIPS assembly language intended for educational
use. We will explore the capabilities of MARS release 3.2.1 in this three part tutorial.
MARS may be downloaded from www.cs.missouristate.edu/MARS.
Part 1 : Basic MARS Use
The example program is Fibonacci.asm to compute everyone’s favorite number
sequence.
1. Start MARS from the Start menu or desktop icon.
2. Use the menubar File…Open or the Open icon
to open Fibonacci.asm in the
default folder. (All icons have menubar equivalents; the remainder of these steps will
use the icon whenever possible.)
3. The provided assembly program is complete. Assemble the program using the icon
4. Identify the location and values of the program’s initialized data. Use the checkbox to
toggle the display format between decimal and hexadecimal
.
 The nineteen-element array fibs is initialized to zero, at addresses 0x10010000
… 0x10010048.
 The data location size has value 19ten at 0x1001004c.
 The addresses 0x10010050 … 0x1001006c contain null-terminated ASCII strings.
Use the checkbox to toggle the display format between decimal and hexadecimal,
.
5. Use the Settings menu to configure the MARS displays. The settings will be retained
for the next MARS session.
Page 16




The Labels display contains the addresses of the assembly code statements with a
label, but the default is to not show this display. Select the checkbox from the
Settings menu.
Select your preference for allowing pseudo-instructions (programmer-friendly
instruction substitutions and shorthand).
Select your preference for assembling only one file, or many files together (all the
files in the current folder). This feature is useful for subroutines contained in
separate files, etc.
Select the startup display format of addresses and values (decimal or
hexadecimal).
6. Locate the Registers display, which shows the 32 common MIPS registers. Other tabs
in the Registers display show the floating-point registers (Coproc 1) and status codes
(Coproc 0).
7. Use the slider bar to change the run speed to about 10 instructions per second.
This allows us to “watch the action” instead of the
assembly program finishing directly.
8. Choose how you will execute the program:

The
icon runs the program to completion. Using this icon, you should
observe the yellow highlight showing the program’s progress and the values of
the Fibonacci sequence appearing in the Data Segment display.

The
icon resets the program and simulator to initial values. Memory
contents are those specified within the program, and register contents are
generally zero.

The
icon is “single-step.” Its complement is
(undoes each operation).
, “single-step backwards”
9. Observe the output of the program in the Run I/O display window:
The Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
-- program is finished running --
10. Modify the contents of memory. (Modifying a register value is exactly the same.)
 Set a breakpoint at the first instruction of the subroutine which prints results. Use
the checkbox at the left of the instruction whose address is 0x00400060 =
4194400ten.
Page 17


Reset
and re-run
the program, which stops at the breakpoint.
Double-click in one of the memory locations containing the computed Fibonacci
numbers. The cell will be highlighted and will accept keyboard entry, similar to a
spreadsheet. Enter some noticeably different value, and use the Enter key or click
outside the cell to indicate that the change is complete. Example: Memory address
0x10010020 = 268501024 ten presently contains data 0x00000022 = 34 ten.

Click
to continue from the breakpoint. The program output includes your
entered value instead of the computed Fibonacci number.
11. Open the Help
for information on MIPS instructions, pseudoinstructions,
directives, and syscalls.
12. Modify the program so that it prompts the user for the Fibonacci sequence length.

Select the Edit tab in the upper right to return to the program editor.

The MIPS comment symbol is #. All characters on the line after the character #
are ignored.
Un-comment lines 12-19. The newly exposed program fragment will prompt the
user for the length of the Fibonacci sequence to generate, in the range 2  x  19 .
(The length of the sequence must be limited to the size of the declared space for
result storage.)
Determine the correct syscall parameter to perform “read integer” from the user,
and insert the parameter at line The correct syscall parameter may be found at


Help
… Syscall tab…read integer service. The completed line will have the
form li $v0, 42 (where in this case 42 is not the right answer).

Reset
and re-run
the program. The program will stop at the breakpoint
you inserted previously. Continue and finish with
.
Page 18
Part 2 : MARS Tools
You may have noticed that MARS has a Tools menu. The capabilities provided through
this menu really catapult MARS into a different league of computer science educational
software.
We call each of the items in the Tools menu a MARS Tool. A MARS Tool is best
described as a pop-up application that observes MIPS memory and/or register activity
during MIPS program execution then communicates that activity to the tool user to serve
a particular purpose. This is best seen by example.
MARS Tools Activity 1 : Running the Data Cache Simulator tool
1. Close any MIPS programs you are currently using.
2. Open the program row-major.asm from the Examples folder. This program
will traverse a 16 by 16 element integer matrix in row-major order, assigning
elements the values 0 through 255 in order. It performs the following algorithm:
for (row = 0; row < 16; row++)
for (col = 0; col < 16; col++)
data[row][col] = value++;
3. Assemble the program.
4. From the Tools menu, select Data Cache Simulator. A new frame will appear in the
middle of the screen.
Page 19
This is a MARS Tool that will simulate the use and performance of cache memory
when the underlying MIPS program executes. Notice its three major sections:
 Cache Organization: You can use the combo boxes to specify how the cache
will be configured for this run. Feel free to explore the different settings, but
the default is fine for now.
 Cache Performance: With each memory access during program execution,
the simulator will determine whether or not that access can be satisfied from
cache and update the performance display accordingly.
 Tool Control: These buttons perform generic control functions as described
by their labels.
5. Click the tool's Connect to MIPS button. This causes the tool to register as an
observer of MIPS memory and thus respond during program execution.
6. Back in MARS, adjust the Run Speed slider to 30 instructions per second. It is
located at the right side of the toolbar. This slows execution so you can watch the
Cache Performance animation.
7. In MARS, run the program using the Run toolbar button
, the menu item or
keyboard shortcut. Watch the Cache Performance animate as it is updated with every
access to MIPS memory.
8. What was the final cache hit rate? _____________. With each miss, a block of 4
words are written into the cache. In a row-major traversal, matrix elements are
accessed in the same order they are stored in memory. Thus each cache miss is
followed by 3 hits as the next 3 elements are found in the same cache block. This is
followed by another miss when Direct Mapping maps to the next cache block, and the
patterns repeats itself. So 3 of every 4 memory accesses will be resolved in cache.
9. Given that explanation, what do you predict the hit rate will be if the block size is
increased from 4 words to 8 words? ______________. Decreased from 4 words to 2
words? ___________.
10. Verify your predictions by modifying the block size and re-running the program from
step 7.
NOTE: when you modify the Cache Organization, the performance values are
automatically reset (you can always use the tool's Reset button).
NOTE: You have to reset
the MIPS program before you can re-run it.
NOTE: Feel free to adjust the Run Speed slider to maximum speed anytime you
want.
Page 20
11. Repeat steps 2 through 10 for program column-major.asm from the Examples
folder. This program will traverse a 16 by 16 element integer matrix in column-major
order, assigning elements the values 0 through 255 in order. It performs the
following algorithm:
for (col = 0; col < 16; col++)
for (row = 0; row < 16; row++)
data[row][col] = value++;
NOTE: You can leave the Cache Simulator in place, move it out of the way, or close
it. It will not interfere with the actions needed to open, assemble, or run this new
program and will remain connected to MIPS memory. If you do not close the tool,
then skip steps 4 and 5.
12. What was the cache performance for this program? ____________. The problem is
the memory locations are now accessed not sequentially as before, but each access is
16 words beyond the previous one (circularly). With the settings we've used, no two
consecutive memory accesses occur in the same block so every access is a miss.
13. Change the block size to 16. Note this will reset the tool.
14. Create a second instance of the Cache Simulator by once again selecting Data Cache
Simulator from the Tools menu. Adjust the two frames so you can view both at the
same time. Connect the new tool instance to MIPS, change its block size to 16 and
change its number of blocks to 16.
15. Re-run the program. What is the cache performance of the original tool instance?
____________. Block size 16 didn't help because there was still only one access to
each block, the initial miss, before that block was replaced with a new one. What is
the cache performance of the second tool instance? ____________. At this point,
the entire matrix will fit into cache and so once a block is read in it is never replaced.
Only the first access to a block results in a miss.
In what courses might an exercise like this one be useful for your students? I have used a
variation on this exercise as a student exercise in Operating Systems, and for a lecture
illustration of the cache concept in Otterbein's CS 0 course, "The Scope of Computer
Science".
Page 21
MARS Tools Activity 2 : Running the Cache Simulator as a stand-alone
1. In command mode, traverse to the directory containing Mars.jar and enter the
command:
java
-classpath
Mars.jar
mars.tools.CacheSimulator
2. The cache simulator tool is launched. Its Tool Control section is replaced by
Application Control, which contains additional controls for loading, assembling and
running MIPS programs. It uses MARS' MIPS assembler and runtime simulator in
the background to control MIPS execution.
3. Click the Open MIPS program button and a File Open dialog will pop up. Browse
to and select a MIPS program to run. Select row_major.asm again if you wish.
4. The Assemble and Run button is now enabled. Click it to assemble and run the
program. The animation will be very rapid.
5. Use the Run Speed slider to adjust the running speed, click the Reset button then
click Assemble and Run again. While the program is running, the Stop button is
enabled. Program status is updated in the single line text field.
We plan to implement a small MARS Tool Suite application to simplify the selection and
launching of tools such as the Cache Simulator that are capable of running outside the
MARS integrated development environment.
Page 22
MARS Tools Activity 3 : The Memory Reference Visualization tool
1. Open the program row-major.asm from the Examples folder if it is not already
open.
2. Assemble the program.
3. From the Tools menu, select Memory Reference Visualization. A new frame will
appear in the middle of the screen.
This tool will paint a grid unit each time the corresponding MIPS memory word is
referenced. The base address, the first static data segment (.data directive) word,
corresponds to the upper-left grid unit. Address correspondence continues in rowmajor order (left to right, then next row down).
The color depends on the number of times the word has been referenced. Black is 0,
blue is 1, green is 2, yellow is 3 and 4, orange is 5 through 9, red is 10 or higher.
View the scale using the tool’s slider control. You can change the color (but not the
reference count) by clicking on the color patch.
4. Click the tool's Connect to MIPS button. This causes the tool to register as an
observer of MIPS memory and thus respond during program execution.
5. Back in MARS, adjust the Run Speed slider to 30 instructions per second.
Page 23
6. Run the program. Watch the tool animate as it is updated with every access to MIPS
memory. Feel free to stop the program at any time.
7. Hopefully you observed that the animation sequence corresponded to the expected
memory access sequence of the row-major.asm program. If you have trouble seeing
the blue, reset the tool, move the slider to position 1, change the color to something
brighter, and re-run.
8. Repeat steps 2 through 7, for column-major.asm. You should observe that the
animation sequence corresponded to the expected memory access sequence of this
program.
9. Repeat again for fibonacci.asm to observe the animated pattern of memory
references. Adjust the run speed and re-run if necessary.
10. (Optional) Create a new instance of the Data Cache Simulator. Move the two frames
around so you can see both. Connect the cache simulator to MIPS and reset the
Memory Reference Visualization. Re-run the program. This exercise illustrates that
two different tools can be used simultaneously.
The Memory Reference Visualization tool could be useful in an operating systems course
to illustrate spatial and temporal locality and memory reference patterns in general.
Page 24
Part 3 : Extending MARS Capabilities
Our session today is not long enough for interactive activities in this area, but we’ll
provide you with enough detail that you can pursue them on your own if you desire.
Abstract
MARS can be customized and extended in four different ways: (1) writing new MARS
Tools, (2) writing new MIPS system calls, (3) writing new MIPS pseudo-instructions,
and (4) writing new MIPS basic instructions. Techniques for all four are described here.
You have the ability to extend and customize certain MARS capabilities to make it more
useful in your courses. This document describes four different techniques for extending
MARS capabilities:
1. Ability to write MARS Tools for inclusion in the Tools menu and stand-alone use.
2. Ability to define and add new system calls for subsequent use by MIPS programs.
3. Ability to customize the instruction set by adding, removing or modifying pseudo
(macro) instruction specifications.
4. Ability to customize the basic instruction set by adding, removing or modifying
basic instruction specifications.
These procedures apply to MARS 3.2.1, released January 2007. Some may be
streamlined in future releases.
The ability to define and plug in new MARS Tools will be used to develop new learning
aids for students in a variety of computer science courses and provide micro-worlds for
assembly language students to target in their projects. Through those tools it is possible
to deeply engage students in both settings.
The ability to modify the set of system calls, basic instructions, and pseudo-instructions
can be used to define a complete instruction set for an alternative RISC architecture.
MARS was not designed with this in mind however, so support is uneven. For example,
instruction syntax analysis and code generation is driven by the example and template
provided with each instruction, whereas lexical analysis such as the recognition of
register names is embedded in program logic and cannot easily be modified. A
customized instruction set has to use MIPS conventions for labeling, register naming, and
so forth. Hopefully MARS can be refactored in future releases to facilitate its use for
alternative instruction sets.
Page 25
1. Writing your own MARS Tool and plugging it into MARS
Abstract
If you think MARS Tools like the Cache Simulator are cool then why not develop your
own? There are two different ways to do so: (1) write a class that implements the
MarsTool interface and is launched from the Tools menu in MARS, or (2) write a class
that extends the AbstractMarsToolAndApplication class and runs either from the Tools
menu or as a free-standing application. You can also write a free-standing application
that uses the Mars API.
This section describes two different techniques for developing your own MARS Tool.
1. Write a class that implements the mars.tools.MarsTool interface and keep
it in the mars.tools package. It will automatically be added to the Tools
menu the next time MARS is run and launched when its menu item is selected.
2. Write a class that extends
mars.tools.AbstractMarsToolAndApplication and keep it in the
mars.tools package. It will automatically be added to the Tools menu the
next time MARS is run and launched when its menu item is selected. It can also
be launched from outside MARS as a free-standing Java application that uses the
Mars API to control the assembly and execution of MIPS programs.
It is also possible to write your own application from scratch using the Mars API. This
should be considered only for very specialized applications and should be undertaken
with great care. The AbstractMarsToolAndApplication class provides full
support for assembling and running MIPS programs in the background and is the
preferred approach.
MyTool implements MarsTool approach
1. Extract the MARS distribution from its JAR file. The JAR file does not have an
outermost folder to contain everything, so you'll want to create one and extract it into
that folder.
2. Develop your class in the mars.tools package (mars/tools folder).
3. Your class must implement the MarsTool interface, which is in that package. This
has only two methods: String getName() to return the name to be displayed in
Page 26
its Tools menu item, and void action() which is invoked when that menu item
is selected by the MARS user. These will assure its inclusion in the Tools menu
when MARS is launched.
4. The user interface should be based on the javax.swing.JDialog class. The
tool interacts with simulated MIPS memory and registers through the
mars.mips.hardware.Memory and mars.mips.hardware.Register
classes, both of which extend java.util.Observable. The Memory class
provides several addObserver() methods that permit an Observer to register for
selected memory addresses or ranges. Javadoc-produced documentation is available
in the doc folder of the MARS distribution.
5. After successful compilation, MARS will automatically include the new tool in its
Tools menu.
MyTool extends AbstractMarsToolAndApplication approach
A better alternative is to extend the AbstractMarsToolAndApplication class,
which is also in the mars.tools package. By doing so, you get the following elements:
 ability to run either from the Tools menu or as a free-standing application
 basic user interface JDialog with Tool Control section (for tools)
 basic user interface JFrame with Application Control section (for applications)
 basic user interface layout (BorderLayout) and rendering algorithm
 basic MIPS memory and register observer capabilities
1. Extract the MARS distribution from its JAR file if you have not already done so.
2. Develop your class in the mars.tools package (mars/tools folder).
3. Your class must extend the AbstractMarsToolAndApplication abstract
class, which is in that package. Nineteen of the 21 methods in this class have default
implementations.
4. Define at least the two abstract methods: String getName() to return the tool’s
display name, and JComponent buildMainDisplayArea() to construct the
central area of the tool’s graphical user interface. It will automatically be placed in
the CENTER of a BorderLayout, with title information to its NORTH and tool
control buttons to its SOUTH. Several addAsObserver() methods are available for
registering as a memory and/or register observer.
Page 27
5. Override additional methods as desired. Some do nothing by default.
6. After successful compilation, MARS will automatically include the new tool in its
Tools menu.
7. To run it as a stand-alone application, you either need to add a main() to create the
tool object and call its go() method or write a short external application to do the
same.
For a better idea of the GUI elements that come with this abstract class, launch MARS
and select Introduction to Tools from the Tools menu.
By extending the provided abstract class
AbstractMarsToolAndApplication, you
get everything in this figure except the
scrolled JTextArea displayed in the
center.
You build the main user interface of your
tool by defining the inherited abstract
buildMainDisplayArea() method. This
method returns a JComponent that will
automatically be displayed in the center of
the default BorderLayout.
Javadoc-produced documentation of the
AbstractMarsToolAndApplicati
on class is available in the doc folder of
the MARS distribution.
Source code files for the MARS Tools are
included together with their bytecode files
in the mars/tools folder. Feel free to
refer to them. All MARS source files,
including tools, are included in the src
folder.
If you develop a nifty MARS Tool, feel free to send it to us and with your permission
we'll post it on the MARS web site for others to use!
Page 28
2. Writing a system call (syscall) and plugging it into MARS
Abstract
MIPS System calls are functions that interface with the operating system to perform I/O
and related operations. They are accessible to MIPS assembly programs through service
numbers and the syscall instruction. MARS provides the 17 system calls documented
in Computer Organization and Design Third Edition, but you can develop and add your
own by writing a class that implements the Syscall interface or extends the
AbstractSyscall class.
MIPS system calls perform operating system functions and input/output operations in
particular. A system call is used in MIPS assembly by loading its identifier (an integer)
into register $v0, loading any required arguments into registers as specified by the call's
protocol, then issuing the syscall instruction.
MARS supports the MIPS system call specifications given in Appendix A of Patterson
and Hennessy's Computer Organization and Design Third Edition. This appendix is
freely available on the web at http://www.cs.wisc.edu/~larus/HP_AppA.pdf.
MARS provides all 17 of the system calls specified there.
Page 29
MySystemCall implements Syscall approach
1. Extract the MARS distribution from its JAR file, if you have not done so.
2. Develop your class in the mars.mips.instructions.syscalls package
(mars/mips/instructions/syscalls folder).
3. Your class must implement the Syscall interface, which is in that package. This
has four methods: String getName() to return an assigned name for this
service, setNumber() and getNumber() to set and get its associated service
number, and simulate() to simulate the execution of the system call at MIPS
runtime.
4. After your class compiles successfully, it will be automatically plugged in and
available to MIPS programs the next time you launch MARS.
MySystemCall extends AbstractSyscall approach
1. Extract the MARS distribution from its JAR file, if you have not done so.
2. Develop your class in the mars.mips.instructions.syscalls package
(mars/mips/instructions/syscalls folder).
3. Your class must extend the AbstractSyscall class, which is in that package. It
provides a constructor and defines the three Syscall getter and setter methods. The
simulate() method is abstract so you must define that yourself.
4. After your class compiles successfully, it will be automatically plugged in and
available to MIPS programs the next time you launch MARS.
Additional Information
Implementation of the simulate() method may require access to one or more
simulated MIPS memory and register objects. The pertinent classes are
mars.mips.hardware.Memory and mars.mips.hardware.RegisterFile.
Also study the source code of existing system calls. Source code files for the 17 MARS
system calls are located in the src folder. Follow the folder hierarchy
mars/mips/instructions/syscalls.
Page 30
The MARS distribution includes a text file Syscall.properties which you can edit
to override any system service number assigned in a constructor. This allows you to
change number assignments without re-compiling any Java source files.
The Syscalls help page is static at this time so it will not reflect any additional system
calls or renumbering.
If you develop a nifty system call, please send it to us and with your permission we'll post
it on the MARS web site for others to access!
We have had philosophical discussions concerning the development of additional system
calls and so far have resisted doing so. On one hand, it would be very useful to have a
small library of handy functions such as random number generators available through the
syscall mechanism. On the other hand, such functions are not considered operating
system operations that would be performed in kernel mode and it would be misleading to
infer such status. Let us know what you think!
Page 31
3. Modifying the set of pseudo (extended, macro) instructions
Abstract
To define a new pseudo-instruction, edit the PseudoOps.txt file included in the
MARS distribution. The instruction specification is one line long and consists of a tabseparated list containing an example usage of the instruction followed by the one or more
basic instructions that the assembler will expand it to. Use specification language
symbols to control the substitution of program statement operands into the generated
basic instruction(s).
The MIPS instruction set includes a large number of pseudo-instructions. These are
instructions that follow MIPS instruction syntax specifications but are not directly
supported by the MIPS architecture. They are instead expanded into a sequence of one or
more basic instructions by the assembler. For this reason they are sometimes called
macro instructions.
The classic example of a pseudo-instruction is la, or load address. Here's an example:
la
$t0, number
where number is the label for a data item. A corresponding MIPS machine instruction
would have to include the operation code, the 5 bit register number and the 32 bit
address. But since machine instructions are only 32 bits long, this is not possible. It
requires two instructions.
Pseudo-instructions are provided entirely for the programmer's convenience, and MARS
includes an assembler setting that will disallow their use.
To modify the pseudo-instruction set, follow this process:
1. Extract the MARS distribution from its JAR file if you have not already done so.
2. Edit PseudoOps.txt appropriately. Each pseudo-instruction and its macro
expansion are specified on one line in this file. Details below.
3. Launch MARS and test your instruction.
Page 32
Here's an example specification, for the absolute value instruction abs
abs $1,$2
1
addu RG1,$0,RG2
2
bgez RG2,2
3
sub RG1,$0,RG2
4
1. Example instruction use. This instruction takes two register operands. The $1 and $2
represent generic registers and are used only to generate a token sequence for syntax
analysis. There is no relationship between register references in the example
instruction (item 1) and register references in the macro expansions (items 3 and 4)!
2. Each item in the specification must be separated by a single TAB character. Only the
first one is pointed out but there is also a TAB between each of the remaining items.
3. The first instruction of the macro expansion. RG1 is a formal parameter that will be
replaced by the actual first register operand of the statement being assembled. RG2 is
similarly replaced by the actual second register operand of the statement being
assembled.
4. Second and third instructions of the macro expansion. Perform similar substitutions.
Statement to assemble
abs
$t3, $t4
Macro expansion
addu
bgez
sub
$t3, $0, $t4
$t4, 2
$t3, $0, $t4
This example uses the simple substitutions RG1 and RG2. Other macro substitution
symbols are more complex, such as VL2P3 which means to substitute the low order 16
bits of the 32 bit value in source operand 2 after adding 3 to it (used in the expansion of
certain unaligned loads and stores).
The macro substitution language is described in detail in the file itself.
If you add any pseudo-instructions, they will automatically be included in the instruction
list produced by the Help feature's Extended (pseudo) Instructions subtab. If the
instruction specification ends with a comment on the same line (# is the comment marker,
just like in MIPS), that comment will be included in the list along with the example
instruction use.
Page 33
4. Modifying the set of Basic Instructions
Abstract
It is possible to modify the basic instruction set recognized by MARS. This requires you
to edit and re-compile the mars.mips.instructions.InstructionSet class.
The specification of a basic instruction includes four components: (1) an example of
instruction use, (2) the instruction format – R, I, or J, (3) a template for generating the 32
bit machine code from a program statement, and (4) a method to simulate the execution
of that program statement.
This is the one type of MARS extension that requires re-compilation of a standard MARS
source file. Specifications for the MIPS basic instruction set are contained in the
mars.mips.instructions.InstructionSet class. Each specification follows
the same format. Here is an example, for the and instruction that performs logical AND.
instructionList.add(new BasicInstruction(
"and $1,$2,$3",
1. example use
BasicInstructionFormat.R_FORMAT,
2. instruction format
"000000ssssstttttfffff00000100100",
3. machine code template
new SimulationCode()
4. execution simulator
{
public void simulate(ProgramStatement statement)
{
int[] operands = statement.getOperands();
RegisterFile.updateRegister(
operands[0],
RegisterFile.getValue(operands[1]) &
RegisterFile.getValue(operands[2])
);
}
}
));
The BasicInstruction constructor takes four parameters, annotated on the
example:
1. Example instruction use. This instruction takes three register operands. The $1, $2
and $3 represent generic registers and are used only to generate a token sequence for
syntax analysis.
Page 34
2. MIPS instruction format. MIPS defines the R-format (works with registers), I-format
(works with immediate value), and J-format (jump instruction). MARS defines a
second version of the I-format called I-branch-format when the immediate value is
used in a branch instruction.
3. Machine code template. This String of length 32 consists of the characters 0, 1, f, s,
and t. When the MIPS program statement syntactically matches this instruction, the
32 bit machine code instruction is constructed by substituting low order bits from the
first operand for f, low order bits from the second operand for s and low order bits
from the third operand for t. The result is converted to 32 bit binary. This example
has register numbers which are 5 bits because MIPS32 defines 32 integer registers.
4. Constructs the object whose simulate() method will be called to simulate the
execution of the program statement at MIPS runtime. The object is constructed from
an anonymous subclass of the SimulationCode class defined right here. The
simulate() method receives information about the program statement as a
parameter and manipulates MIPS registers and/or memory to carry out the instruction.
To modify the basic instruction set, follow this process:
1. Extract the MARS distribution from its JAR file if you have not already done so.
2. Copy InstructionSet.java from the src/mars/mips/instructions
folder into the mars/mips/instructions folder.
3. Make a backup copy of InstructionSet.java for safe keeping.
4. Edit InstructionSet.java appropriately. Implementation of the
simulate() method will likely require access to one or more simulated MIPS
memory and/or register objects. The pertinent classes are
mars.mips.hardware.Memory and
mars.mips.hardware.RegisterFile. Javadoc-generated documentation for
all MARS classes is provided in the distribution's doc folder. Also study the source
code of existing instructions.
5. Compile InstructionSet.java and test your instruction.
NOTE: This technique applies to MARS release 3.2.1. It is possible that the technique
for specifying basic instructions will change in a future release of MARS. If so, it would
be converted to a technique similar to that now used for system calls.
Page 35