MIPS Sakis Tutorial

27
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Tue, 11 Jan 2011 19:12:41 UTC Mips

Transcript of MIPS Sakis Tutorial

Page 1: MIPS Sakis Tutorial

PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information.PDF generated at: Tue, 11 Jan 2011 19:12:41 UTC

Mips

Page 2: MIPS Sakis Tutorial

ContentsArticles

MIPS Assembly/Introduction 1MIPS Assembly/MIPS Architecture 2MIPS Assembly/MIPS Processors 3MIPS Assembly/MIPS Details 3MIPS Assembly/MIPS Instructions 5MIPS Assembly/Arithmetic Instructions 7MIPS Assembly/Control Flow Instructions 9MIPS Assembly/Memory Instructions 11MIPS Assembly/Floating Point Instructions 12Floating Point 13MIPS Assembly/MIPS Assemblers 15MIPS Assembly/MIPS Emulation 15MIPS Assembly/Subroutines 16MIPS Assembly/Instruction Formats 17MIPS Assembly/System Instructions 20MIPS Assembly/Pseudoinstructions 21MIPS Assembly/Register File 22MIPS Assembly/Exceptions 23

ReferencesArticle Sources and Contributors 24

Article LicensesLicense 25

Page 3: MIPS Sakis Tutorial

MIPS Assembly/Introduction 1

MIPS Assembly/IntroductionThis page is going to serve as a general foreword about this book.

What This Book is AboutThis book is going to discuss the MIPS assembly language. This book will cover not only the straight-forward facetof this subject (how to program MIPS), but will also look deeper, and discuss MIPS from a very low level. In thisway, this book should be useful both for people just learning to program MIPS, and also to people who are lookingto do advanced tasks in MIPS (such as write a MIPS assembler program, or construct a low-level OS kernel inMIPS). This book will not talk about the specifics of MIPS hardware, however.

Who This Book is ForThis book is designed to be a reference for all people who are interested in MIPS. This book starts off with the basicsbehind the language, and discusses the various operations in such a manner that beginners will be able to get ahandle of MIPS programming. However, this book also contains a number of advanced sections for experiencedprogrammers who are looking at doing advanced projects with the MIPS architecture.

How This Book is OrganizedThis book is organized in such a fashion that the most simple material is presented first, and the most advancedmaterial is saved towards the end. The first section of the book is reserved for historical and interesting informationabout MIPS, and listings of real-world MIPS implementations. The second section is going to go into the MIPSassembly language, talking about each instruction individually, and explaining how to use them. The third section isgoing to talk about the topics of programming, assembling, and emulating MIPS code. Finally, the fourth section isgoing to talk about advanced topics, such as the internal machine code of MIPS machines, the nature ofpseudoinstructions, some advanced system instructions, and handling exceptions.

Where to Go From HereThis book will serve as a complete reference to programming MIPS. While there are no wikimedia resourcesspecifically designed to follow this text, the reader may benefit from reading about higher-level languages, orassemblers, or another advanced programming topic.For more information about how to design MIPS and other types of microprocessor systems, see MicroprocessorDesign.

Page 4: MIPS Sakis Tutorial

MIPS Assembly/MIPS Architecture 2

MIPS Assembly/MIPS Architecture

The MIPS architectureMIPS is a register based architecture, meaning the CPU uses registers to perform operations on. There are othertypes of processors out there as well, such as stack-based processors and accumulator-based processors.Registers are memory just like RAM, except registers are much smaller than RAM, and are much faster. In MIPS theCPU can only do operations on registers, and special immediate values.MIPS processors have 32 registers, but some of these are reserved. A fair number of registers however are availablefor your use. For example, one of these registers, the program counter, contains the memory address of the nextinstruction to be executed. As the processor executes the instruction, the program counter is incremented, and thenext memory address is fetched, executed, and so on.

Why MIPS?The MIPS processor is Reduced Instruction Set Computer (RISC) based. It was actually developed by the peoplewho pioneered RISC (John Hennessy, the president of Stanford University, founded MIPS Computer Systems, Inc,in 1984 to commercialize his research done on RISC systems at Stanford.) This means that you don't get complexand fun instructions like you would in say, VAX. It all boils down to how long one instruction takes to execute, aswell as how easily can we write a compiler for this architecture? For example, the VAX has a CRC (cyclicredundancy check) instruction, this is commonly used in things like TCP/IP. You'd be hard pressed to identify Ccode that did a CRC and replace it with that particular instruction as a compiler designer. This is one of the mainreasons why RISC was developed. There are quite a few others, a good guide to learning about more would be tolook up why x86 processors are non-RISC (CISC, complex instruction set computer) on the outside but RISC on theinside.MIPS instructions are always 32 bits long. There are only 3 instruction formats in MIPS, which makes programmingfun and easy. Try remembering the whole x86 instruction set some day.

MIPS Philosophies• Simplicity favors regularity• Good design demands good compromise• Smaller is faster• Make the common tasks the fastest

Page 5: MIPS Sakis Tutorial

MIPS Assembly/MIPS Processors 3

MIPS Assembly/MIPS ProcessorsThis page is going to talk about some of the specific MIPS implementations, and MIPS relatives.Most MIPS implementations use the classic 5 stage pipeline: instruction fetch, instruction decode/register fetch,execute, memory access, and register write back.

Further reading• The Microchip PIC32 microcontrollers are based on a MIPS32 M4K Core.• The MIPS architecture is one of several popular architectures in embedded systems.• The PlayStation uses a MIPS processor. Several Wikibooks discuss programming the PlayStation: Emulation/On

Playstation, Linux Guide/PlayStation 3, PSP Programming, Map This!.

MIPS Assembly/MIPS Details

RISC vs CISCRISC

RISC stands for Reduced Instruction Set Computer. MIPS is a RISC computer.CISC

CISC stands for Complex Instruction Set Computer. An example of a CISC architecture is the Intel x86Instruction Set.

Instruction FormatsThere are 3 different types of instructions: R Instructions, I Instructions, and J Instructions. We will discuss all 3varieties below.

R InstructionsR Instructions take three arguments: two source registers (rt and rs), and a destination register (rd). R instructionsare written using the following format:

instruction rd, rs, rtFor example, if we want to add the contents of $3 and $4 together, and store the result in $5, we would have thefollowing instruction:

add $5, $3, $4

An R-format instruction is encoded as

opcode rs rt rd shamt func

where opcode is a 6-bit field and gives the instruction its name, or its "operation code", the three register fields areeach 5-bit wide (2**5=32), shamt is a 5-bit field used in shift instructions to specify the number of places to shift thedestination register contents (again, one can specify any displacement from one to 32 places since 2**5=32), andfunc is a 6-bit field that specifies the operation for instructions with an opcode=0 ("simple" arithmetic and logicinstructions).

Page 6: MIPS Sakis Tutorial

MIPS Assembly/MIPS Details 4

I InstructionsI instructions take two register arguments and a 16-bit immediate value. The destination register (rd) is written first,followed by the source register (rs), and finally the immediate value:

instruction rd, rs, immFor example, let's say that we want to add the value 5 to the register $3, and store the result in $4:

addi $4, $3, 5

An I-format instruction is encoded as

opcode rs rt immed

where opcode is a 6-bit field and gives the instruction its name, or its "operation code", the two register fields areeach 5-bit wide (2**5=32), and immed is a 16-bit field that holds an immediate constant. Depending on theinstruction, the immed field is interpreted as a twos-complement number (arithmetic instructions, loads/stores,branches), or as a logical constant (logic instructions).

J InstructionsJ instructions are used to transfer program flow to a given, hardcoded offset from the current value of the IP register.J instructions are often used with labels, although the assembler will convert the label into a numerical offset value.A J instruction takes only one argument: the numerical offset to jump to.instruction destfor example, let's say that we have a label Label1:, and we want to jump to it:

j Label1

A J-format instruction is encoded as

opcode addr

where opcode is a 6-bit field and gives the instruction its name, and addr is a 26-bit field that specifies an address.

RegistersThe MIPS registers are arranged into a structure called a Register File. The register file contains 32 registers. Also,there are a few other architectural registers that are not located in the register file. A common example is theProgram Counter register (PC), that points to the current location of the program execution in memory.Registers can be referred to by either names or numbers. This means that we can refer to a given register as $a0, or$4. In general, there are many registers that can be used in your programs: the ten temporary registers and the eightsaved registers. Temporary registers are general-purpose registers that can be used for arithmetic and otherinstructions freely, while saved registers must be saved at procedure entry, and restored at procedure exit.Temporary register names all start with a $t. For instance, there are $t0, $t1 ... $t9. this means there are 10 temporaryregisters that can be used without worrying about saving and restoring their contents. The saved registers are named$s0 to $s7.There is a software convention regarding the use of several registers. For instance, $29 is reserved for use as a stackpointer ($sp), and $31 is used for linking the return address of procedure ($ra). $31 is always filled with the addressof the instruction that follows a jump-and-link (jal) instruction.The zero register, is named $zero ($0), and is a static register: it always contains the value zero. This register maynot be used as the target of a store operation, because its value is hardwired in, and cannot be changed by theprogram.

Page 7: MIPS Sakis Tutorial

MIPS Assembly/MIPS Instructions 5

MIPS Assembly/MIPS InstructionsInsert non-formatted text here

Writing assembly codeAn assembly language program has a few common features. These are:• labels• sections• directives• comments• commands

CommentsIn MIPS assembly, comments are denoted with a sharp sign("#"). Everything after # on the same line is "commentedout", and is not included in the assembly process.

LabelsA label is something to make your life simple. When you reference a piece of your program, instead of having tocount lines, you can just give it a name. You use this in loops, jumps, and variable names.Labels don't appear in your final code, they're only there for convenience, one of the few perks you'll get from thetypical MIPS assembler. It also makes life easy for the assembler, because it can now easily go around relocating andlinking code. Don't worry if you don't know what those are, that'll come later.Labels in MIPS assembly, actually in most variants of ASM as well, are created by writing

name:

where name is a name you use to refer to this label. Note that, you can't create a label with the same name as a MIPSinstruction.Labels are the same as their C cousins, the targets of goto operators.

SectionsA section is a way of dividing an assembly language program up into the instructions and the data logically. Sinceyour assembly program is loaded into memory, all the processor needs to know is the start of execution (known asthe entry point) and merely just increments the instruction pointer and continues along. If data is interspersed in theinstruction code in memory, the processor needs to know what is data and what is instructions - which serves for amuch more complicated processor. For simplicity, the data is set off in a different area than the instructions. Sectionsare used for this purpose.There are two sections you need to be mindful of in MIPS programming: the text and data sections. The text sectionholds your assembly program, and the data section holds your data. One designates a text section by starting with.text and the start of a data section by .data.

Page 8: MIPS Sakis Tutorial

MIPS Assembly/MIPS Instructions 6

DirectivesThe processor assembler (or your emulator) understands a few special commands that perform specific tasks to makeyour life easier: for example creating memory space for you to store data in variables.If you wish to create a variable for a number in your assembly program, you may want to:1. switch to the data section2. create a label to create a memory reference for your variable3. give it an appropriate name4. allocate some memory for it5. align it properly in memory.6. switch back to the text sectionFrom what we have learned, we can write the MIPS assembly code up to step 3:

.data

variable_name:

But now how can we allocate some memory? We use the .space directive. An integer takes up 4 bytes, usually,so we write

.data

variable_name:

.space 4

We need to align the data in memory now (we'll explain this below), so we use the .align directive

.data

variable_name:

.space 4

.align 2

.text

And we've switched back to the text section.Memory locations in MIPS assembler need to be aligned - that is, that memory locations must begin on the correctlocation otherwise the processor will crash. 4-byte integers must be aligned every 4 bytes, and so on. The .alignn directive aligns the data to a memory cell fit for 2n bytes. Therefore, for 32-bit (4-byte) integers we use .align2 for 22 or 4 bytes.

Comments-------------------------------------- To align the space allocated, the 'align n' should come before the 'space x'declaration. For example, here is a sample for allocating 6 words (6 x 4 = 24 bytes) in memory and aligning them atword boundaries

.data

.align 2

my_var_name:

.space 24

Page 9: MIPS Sakis Tutorial

MIPS Assembly/Arithmetic Instructions 7

MIPS Assembly/Arithmetic InstructionsThis page is going to talk about the arithmetic instructions of the MIPS architecture.

Register Arithmetic Instructions

Instruction: add type: R Type

This instruction adds the two operands together, and stores the result in the destination register. Negative numbersare handled automatically using Two's Complement Notation. This means that different instructions do not need tobe used for signed and unsigned numbers.

Instruction: sub type: R Type

The sub instruction subtracts the first operand from the second operand, and stores the result in the destination. Inpseudo-code, the operation performs the following:

rd = rs - rt

Multiplication and DivisionThe multiply and divide operations are slightly different from other operations. Even if they are R-type operations,they only take 2 operands. The result is stored in a special 64-bit result register. We will talk about the result registerafter this section.

Instruction: mult type: R Type

This operation multiplies the two operands together, and stores the result in rd. Multiplication operations mustdifferentiate between signed and unsigned quantities, because the simplicity of Two's Complement Notation does notcarry over to multiplication. The mul instruction multiplies and sign extends signed numbers.The result of multiplying 2 32-bit numbers is a 64-bit result. We will discuss the 64-bit results below.

Instruction: multu type: R Type

The multu instruction multiplies the two operands together, and stores the result in rd. This instruction is forunsigned numbers only, and does not sign extend a negative result. This operation also creates a 64-bit result.

Instruction: div type: R Type

The div instruction divides the first argument by the second argument. The quotient is stored in the lowest 32-bits ofthe result register. The remainder is stored in the highest 32-bits of the result register. Like multiplication, divisionrequires a differentiation between signed and unsigned numbers. This operation uses signed numbers.

Instruction: divu type: R Type

Like the div instruction, this operation divides the first operand by the second operand. The quotient is stored in thelowest 32-bits of the result, and the remainder is stored in the highest 32-bits of the result. This operand dividesunsigned numbers, and will not sign-extend the result.

Page 10: MIPS Sakis Tutorial

MIPS Assembly/Arithmetic Instructions 8

64-Bit ResultsThe 64-bit result register is broken into two 32-bit segments: HI and LO. We can interface with these registers usingthe mfhi and mflo operations, respectively.

Instruction: mfhi type: R Type

Takes only 1 operand. This instruction moves the high-32 bits of the result register into the target register.

Instruction: mflo type: R Type

Also takes only 1 operand. Moves the value from the LO part of the result register into the specified register.

Register Logic InstructionsThese operations perform bit-wise logical operations on their operands.

Instruction: and type: R Type

Performs a bitwise AND operation on the two operands, and stores the result in rd.

Instruction: or type: R Type

Performs a bitwise OR operation on the two operands, and stores the result in rd.

Instruction: nor type: R Type

Performs a bitwise NOR operation on the two operands, and stores the result in rd.

Instruction: xor type: R Type

Performs a bitwise XOR operation on the two operands, and stores the result in rd.

Immediate Arithmetic Instructions

Instruction: addi type: I Type

Adds an immediate 16-bit value to the destination register:

addi $1, $2, 255

Instruction: subi type: I Type

Subtracts an immediate 16-bit value from the register

Page 11: MIPS Sakis Tutorial

MIPS Assembly/Arithmetic Instructions 9

Immediate Logic Instructions

Instruction: andi type: I Type

Ands the register with a 16 bit immediate value.

Instruction: ori type: I Type

Ors the register with a 16 bit immediate value.

Instruction: xori type: I Type

Xors the register with a 16 bit immediate value.

Shift instructions

Instruction: sll type: R Type

Logical shift left.

Instruction: srl type: R Type

Logical shift right.

MIPS Assembly/Control Flow Instructions

Jump InstructionThe jump instructions load a new value into the IP register. This causes the next instruction read from memory to beretrieved from the new location.

Instruction: j type: J Type

The j instruction loads an immediate value into the IP register. This immediate value is either a numeric offset or alabel (and the assembler converts the label into an offset).

Instruction: jr type: R Type

The jr instruction loads the IP register with a value stored in a register. As such, the jr instruction can be called assuch:

jr $t0

assuming the target jump location is located in $t0.

Page 12: MIPS Sakis Tutorial

MIPS Assembly/Control Flow Instructions 10

Jump and LinkJump and Link instructions are similar to the jump instructions, except that they store a return address in the $ra($31) register. This allows a subroutine to return to the main body routine after completion.

Instruction: jal type: J Type

Like the j instruction, except that the return address is loaded into the $ra register.

Instruction: jalr type: R Type

The same as the jr instruction, except that the return address is loaded into the $ra register.

ExampleLet's say that we have a subroutine that starts with the label MySub. We can call the subroutine using the followingline:

jal MySub

...

And we can define MySub as follows to return to the main body of the parent routine:

jr $ra

Branch Instructions

Instruction: beq type: I Type

Instruction: bne type: I Type

Instruction: blez type: I Type

Instruction: bgtz type: I Type

Instruction: blt type: I Type

Instruction: bgt type: I Type

Instruction: ble type: I Type

Instruction: bge type: I Type

Page 13: MIPS Sakis Tutorial

MIPS Assembly/Control Flow Instructions 11

Set Instructions

Instruction: slt type: R Type

Instruction: slti type: I Type

Instruction: sltu type: R Type

Instruction: sltiu type: I Type

MIPS Assembly/Memory InstructionsThis page will discuss the load and store instructions that deal with memory access

Load Instructions

Instruction: lbu type: I Type

Instruction: lhu type: I Type

Instruction: lui type: I Type

Instruction: lw type: I Type

Instruction: li type: I Type

Store Instructions

Instruction: sb type: I Type

Instruction: sh type: I Type

Instruction: sw type: I Type

Page 14: MIPS Sakis Tutorial

MIPS Assembly/Memory Instructions 12

Move Instructions

Instruction: movz type: R Type

Instruction: movn type: R Type

Instruction: move type: R Type

32-bit ManipulationsTo manipulate 32-bit numbers, we need to break the values into 16-bit component parts, and manipulate the partsindividually.

LoadTo load a 32-bit number, we need to use lui to load the high 16 bits with the specified number. Then we need to useori to load the lower 16 bits. The result will be the complete 32 bit number.

MIPS Assembly/Floating Point Instructions

ArithmeticInteger implementation of floating-point addition

#Initialize variables

add $s0,$t0,$zero #first integer value

add $s1,$t1,$zero #second integer value

add $s2,$zero,$zero #initialize sum variable to 0

add $t3,$zero,$zero #initialize SUM OF SIGNIFICANDS value to 0

#get EXPONENT from values

sll $s5,$s0,1 #getting the exponent value

srl $s5,$s5,24 #$s5 = first value EXPONENT

sll $s6,$s1,1 #getting the exponent value

srl $s6,$s6,24 #$s6 = second value EXPONENT

#get SIGN from values

srl $s3,$s0,31 #$s3 = first value SIGN

srl $s4,$s1,31 #$s4 = second value SIGN

#get FRACTION from values

sll $s7,$s0,9

srl $s7,$s0,9 #$s7 = first value FRACTION

sll $t8,$s1,9

srl $t8,$s1,9 #$t8 = second value FRACTION

Page 15: MIPS Sakis Tutorial

MIPS Assembly/Floating Point Instructions 13

#compare the exponents of the two numbers

compareExp: ######################

beq $s5,$s6, addSig

blt $s5,$s6, shift1 #if first < second, go to shift1

blt $s6,$s5, shift2 #if second < first, go to shift2

j compareExp

shift1: #shift the smaller number to the right

srl $s7,$s7,1 #shift to the right 1

addi $s5,$s5,1

j compareExp

Further Reading• Floating Point

Floating PointThis wikibook discusses the IEEE 754 standard concerning floating-point numbers. Beginning chapters of this bookfocus on newcomers to the standard, who wish to understand and make use of floating point numbers, especially in aprogramming project. Later chapters of this book, however, focus more on the details of implementation of the IEEE754 standard. This way, advanced users who want more details, or users who are working to create a floating-pointimplementation of their own can find the information they need. This book can be used as an ancillary referencesource to support other books in the computer science and engineering fields.Programming examples found in this book attempt to use pseudocode where possible, to prevent an over-reliance onany particular language or platform. Specific examples may utilize a single computer language or assemblylanguage.Prerequisites to this book include an understanding of exponents and Algebra, and an understanding of binarynumber representation.

Table of Contents

Section 1: Number Representation• /Introduction/• /Scientific Notation/• /Fixed-Point Numbers/• /Floating-Point Numbers/

Section 2: IEEE 754• /IEEE 754/• /Floating Point Formats/• /Special Numbers/• /Normalization/

Page 16: MIPS Sakis Tutorial

Floating Point 14

Section 3: Floating Point Arithmetic• /Rounding/• /Floating Point Arithmetic/• /Epsilon/• /Arithmetic Errors/• Guard Bits• /Comparing FP Numbers/

Section 4: Floating Point Hardware• Converting FP and Integers• Exceptions• Trap Handlers• Flags• /Floating Point Hardware/• /Soft Implementations/

Section 5: Algorithms• Arithmetic Algorithms• Exponents and Square Roots• Trancendentals

Further Reading• IEEE 754 references [1]

• Let's Get To The (Floating) Point by Chris Hecker [2]

• What Every Computer Scientist Should Know About Floating-Point Arithmetic by David Goldberg [3] - a goodintroduction and explanation.

• IEEE 854-1987 [4] History and minutes• Converter [5]

• Another Converter [6]

• The pitfalls of verifying floating-point computations [7], by David Monniaux, also printed in ACM Transactionson programming languages and systems (TOPLAS), May 2008: a compendium of non-intuitive behaviours offloating-point on popular architectures, with implications for program verification and testing

References[1] http:/ / babbage. cs. qc. edu/ courses/ cs341/ IEEE-754references. html[2] http:/ / www. d6. com/ users/ checker/ pdfs/ gdmfp. pdf[3] http:/ / docs. sun. com/ source/ 806-3568/ ncg_goldberg. html[4] http:/ / www2. hursley. ibm. com/ decimal/ 854mins. html[5] http:/ / www. h-schmidt. net/ FloatApplet/ IEEE754. html[6] http:/ / babbage. cs. qc. edu/ courses/ cs341/ IEEE-754. html[7] http:/ / hal. archives-ouvertes. fr/ hal-00128124/ en/

Page 17: MIPS Sakis Tutorial

MIPS Assembly/MIPS Assemblers 15

MIPS Assembly/MIPS AssemblersThis page is going to list some assemblers for programming in MIPS, and will discuss how to program using MIPSassemblers./edit by Till Fischer, University of Ulm (Germany)Heres a link to a Download of the MARS, an emulation Assembler Program by the Missouri State University, weuse that one in our Studies in order to learn Assembler: http:/ / courses. missouristate. edu/ KenVollmar/ MARS/

MIPS Assembly/MIPS EmulationThis page is going to talk about using MIPS emulators to test MIPS code on a non-MIPS computer.A common MIPS Emulator is Spim which is fully cross platform. Another one is MIPS Assembler and Simulator [1],which has been successfuly deployed in used in a few high schools. QEMU [2] is another common emulatorenvironment for MIPS.Open Virtual Platforms (OVP) http:/ / www. OVPworld. org [3] includes the freely available simulator OVPsim, alibrary of models of processors, peripherals and platforms, and APIs which enable users to develop their ownmodels. The models in the library are open source, written in C, and include the MIPS 4K, 24K and 34K cores.These models are created and maintained by Imperas http:/ / www. imperas. com [4] and in partnership with MIPSTechnologies have been tested and assigned the MIPS-Verified(tm) mark. Sample MIPS-based platforms includeboth bare metal environments and platforms for booting unmodified Linux binary images. Theseplatforms/emulators are available as source or binaries and are fast, free, and easy to use. OVPsim is developed andmaintained by Imperas and is very fast (100s of million instructions per second), and built to handle multicorearchitectures. To download the MIPS OVPsim simulators/emulators visit http:/ / www. OVPworld. org/ mips [5].

References[1] http:/ / xavier. perseguers. ch/ programmation/ mips-assembler. html[2] http:/ / wiki. qemu. org/ Main_Page[3] http:/ / www. OVPworld2. org[4] http:/ / www. imperas. com[5] http:/ / www. OVPworld2. org/ mips

Page 18: MIPS Sakis Tutorial

MIPS Assembly/Subroutines 16

MIPS Assembly/SubroutinesThis page is going to talk about using subroutine structures in MIPS Assembly. Also, this page will talk about someof the common methods by which higher-level language constructs and subroutines are translated into MIPSassembly code.

Subroutine MechanicsIn MIPS, the general purpose registers are typically taken to be the function parameters and the function variables, asneeded. Previous values of the general purpose registers are stored on the stack. At the end of a subroutine, thevalues of all registers stored in this manner are restored from the stack.MIPS uses the stack to preserve these registers. The stack pointer points to the bottom of the stack, but the framepointer points to the top of the local frame. Offsetting from the stack or frame pointers can retrieve the various savedvalues and function parameters, as needed.

Stem and LeafIn the function hierarchy, a function that calls other functions is known as a stem function. A function which calls noother functions is known as a leaf function. Stem functions must save the value of $ra on the stack, so that itscontent is preserved across the other function calls, and so the called function can return to the calling function, or itsparent function.It is important to note that a leaf function does not need to preserve the value of the $ra register because it does notcall any other child function and hence its return address is preserved in $ra.

Stack FrameA function may set up a stack frame, with the $sp register pointing to the bottom of the stack, and the $fp registerpointing to the top of the stack at the start of the subroutine. In this manner, $fp will be pointing to the function'sinput arguments (if any are on the stack), and $sp will be pointing to the local variables for the function.The value of $fp needs to be preserved across function calls, and stem functions need to save the value of $fp beforecalling a child function, and restore it from the stack after calling the child function.The value of $sp does not need to be stored on the stack, but functions need to take care to return $sp to the value ithad at the beginning of the function, before the function returns. This means that at the beginning of a subroutine,values can be pushed onto the stack, and at the end of the subroutine, all those values need to be popped right backoff the stack. If this is not done correctly, it will destroy the stack frame of the parent function, and possibly causethe computer to crash.

Saved RegistersThere are a number of registers that must be preserved across a subroutine call. This means that if the subroutinewants to use those registers, it must save the previous values onto the stack (or some other place), and then reloadthose values at the end of the function. The $tx registers are all temporary registers and do not need to be saved.Likewise, the $ax registers are all function arguments, and do not need to be saved. Thr $v0 and $v1 registers areboth function return values, and do not need to be saved.The following registers do need to be preserved across a function call, and should be saved by the function if theyare going to be used in the function:$sx

The "Saved Temporary" registers

Page 19: MIPS Sakis Tutorial

MIPS Assembly/Subroutines 17

further reading• Embedded Systems/Mixed C and Assembly Programming

MIPS Assembly/Instruction FormatsThis page is going to discuss the implementation details of the MIPS instruction formats.

R InstructionsR instructions are used when all the data values used by the instruction are located in registers.All R-type instructions have the following format:

OP rd, rs, rt

Where "OP" is the mneumonic for the particular instruction. rs, and rt are the source registers, and rd is thedestination register. As an example, the add mneumonic can be used as:

add $s1, $s2, $s3

Where the values in $s2 and $s3 are added together, and the result is stored in $s1. In the main narrative of this book,the operands will be denoted by these names.

R FormatConverting an R mneumonic into the equivalent binary machine code is performed in the following way:

opcode rs rt rd shift funct

opcodeThe opcode is the machinecode representation of the instruction mneumonic. Several related instructions canhave the same opcode. The opcode field is 6 bits long (bit 26 to bit 31).

rs, rt, rdThe numeric representations of the source registers and the destination register. These numbers correspond tothe $X representation of a register, such as $0 or $31. Each of these fields is 5 bits long. (25 to 21, 20 to 16,and 15 to 11, respectively).

ShiftUsed with the shift and rotate instructions, this is the amount by which the source operand rs is rotated/shifted.This field is 5 bits long (6 to 10).

FunctFor instructions that share an opcode, the funct parameter contains the necessary control codes to differentiatethe different instructions. 6 bits long (0 to 5). Example: Opcode 0x00 accesses the ALU, and the funct selectswhich ALU function to use.

Page 20: MIPS Sakis Tutorial

MIPS Assembly/Instruction Formats 18

I InstructionsI instructions are used when the instruction must operate on an immediate value and a register value. Immediatevalues may be a maximum of 16 bits long. Larger numbers may not be manipulated by immediate instructions.I instructions are called in the following way:

OP rt, rs, IMM

Where rt is the destination register, rs is the source register, and IMM is the immediate value. The immediate valuecan be up to 16 bits long. For instance, the addi instruction can be called as:

addi $s1, $s2, 100

Where the value of $s2 plus 100 is stored in $s1.

I FormatI instructions are converted into machine code words in the following format:

opcode rs rt IMM

OpcodeThe 6-bit opcode of the instruction. In I instructions, all mneumonics have a one-to-one correspondence withthe underlying opcodes. This is because there is no funct parameter to differentiate instructions with anidentical opcode. 6 bits (26 to 31)

rs, rtThe source and destination register operands, respectively. 5 bits each (21 to 25 and 16 to 20, respectively).

IMMThe 16 bit immediate value. 16 bits (0 to 15).

J InstructionsJ instructions are used when a jump needs to be performed. The J instruction has the most space for an immediatevalue, because addresses are large numbers.J instructions are called in the following way:

OP LABEL

Where OP is the mneumonic for the particular jump instruction, and LABEL is the target address to jump to.

J FormatJ instructions have the following machine-code format:

Opcode Address

OpcodeThe 6 bit opcode corresponding to the particular jump command. (26 to 31).

AddressA 26-bit address of the destination. (0 to 25).

Page 21: MIPS Sakis Tutorial

MIPS Assembly/Instruction Formats 19

FR InstructionsFR instructions are similar to the R instructions described above, except they are reserved for use with floating-pointnumbers.

FI InstructionsFI instructions are similar to the I instructions described above, except they are reserved for use with floating-pointnumbers.

OpcodesThe following table contains a listing of MIPS instructions and the corresponding opcodes. Opcode and functnumbers are all listed in hexadecimal.

Mnemonic Type Opcode Funct

add R 0x00 0x20

addi I 0x08 NA

addiu I 0x09 NA

addu R 0x00 0x21

and R 0x00 0x24

andi I 0x0C NA

beq I 0x04 NA

bne I 0x05 NA

div R 0x00 0x1A

divu R 0x00 0x1B

j J 0x02 NA

jal J 0x03 NA

jr R 0x00 0x08

lbu I 0x24 NA

lhu I 0x25 NA

lui I 0xF NA

lw I 0x23 NA

mfhi R 0x00 0x10

mflo R 0x00 0x12

mfc0 R 0x10 NA

mult R 0x00 0x18

multu R 0x00 0x19

nor R 0x00 0x27

xor R 0x00 0x26

or R 0x00 0x25

ori I 0x0D NA

sb I 0x28 NA

Page 22: MIPS Sakis Tutorial

MIPS Assembly/Instruction Formats 20

sh I 0x29 NA

slt R 0x00 0x2A

slti I 0xA NA

sltiu I 0xB NA

sltu R 0x00 0x2B

sll R 0x00 0x00

srl R 0x00 0x02

sub R 0x00 0x22

subu R 0x00 0x23

sw I 0x2B NA

MIPS Assembly/System InstructionsThis page is going to discuss some of the more advanced MIPS instructions that might not be used in every-dayprogramming tasks.

Instruction: syscall type: R Type

syscall allows you to call upon the basic system functions. To use syscall, first set $v0 with the code of the functionyou want to call, then use ssyscall. The exact codes available may depend on the specific system used, but thefollowing are examples of common sytem calls.

code call arguments results

1 print integer $a0 = integer to print

2 print float $f12 = float to print

3 print double $f12 = float to print

4 print string $a0 = address of beginning of string

5 read integer integer stored in $v0

6 read float float stored in $f0

7 read double double stored in $f0

8 read string $a0 = pointer to buffer, $a1 = length of buffer string stored in buffer

9 sbrk (allocate memory buffer) $a0 = size needed $v0 = address of buffer

10 exit

Example: printing the number 12

li $a0, 12→;loads the number we want printed, 12 in this case, into the first argument register

li $v0, 1→;stores the code for the print integer call into $v0

syscall→;Executes system call

Instruction: break type: R Type

Instruction: sync type: R Type

Page 23: MIPS Sakis Tutorial

MIPS Assembly/System Instructions 21

Instruction: cache type: R Type

Instruction: pref type: R Type

MIPS Assembly/PseudoinstructionsThe MIPS instruction set is very small, so to do more complicated tasks we need to employ assembler macros calledpseudoinstructions.

List of PseudoinstructionsThe following is a list of the standard MIPS instructions that are implemented as pseudoinstructions:• blt• bgt• ble• blt• bge• li• move

Branch PseudoinstructionsBranch if less than (blt)The blt instruction compares 2 registers, treating them as signed integers, and takes a branch if one register is lessthan another.

blt $8, $9, 4

translates to

slt $1, $8, $9

bne $1, $0, 4

Other PseudoinstructionsLoad Immediate (li)The li pseudo instruction loads an immediate value into a register.

li $1, 0x3BF20

translates to

lui $2, 0x0003

ori $1, $2, 0xBF20

Move (move)The move pseudo instruction moves the contents of one register into another register.

move $1, $2

translates to

Page 24: MIPS Sakis Tutorial

MIPS Assembly/Pseudoinstructions 22

add $1, $2, $0

MIPS Assembly/Register FileThis page will talk about the structural details of the MIPS register file.

Zero RegisterThe zero register ($zero or $0) always contains a value of 0. It is built into the hardware and therefore cannot bemodified.

$at RegisterThe $at (Assembler Temporary) register is used for temporary values within pseudo commands. It is not preservedacross function calls.

$v RegistersThe $v Registers are used for returning values from functions. They are not preserved across function calls.

Argument RegistersThe $a registers are used for passing arguments to functions. They are not preserved across function calls.

TemporariesThe temporary registers are used by the assembler or assembly language programmer to store intermediate values.They are not preserved across function calls.

Saved TemporariesSaved Temporary registers are used to store longer lasting values. They are preserved across function calls.

$k RegistersThe k registers are reserved for use by the OS kernel.

Pointer Registers• Global Pointer ($gp)• Stack Pointer ($sp) - Used to store the value of the stack pointer.• Frame Pointer ($fp) - Used to store the value of the frame pointer.• Return Address ($ra) - Stores the return address (the location in the program that a function needs to return to).All Pointer Registers are preserved accross function calls.

Page 25: MIPS Sakis Tutorial

MIPS Assembly/Exceptions 23

MIPS Assembly/ExceptionsThis page is going to talk about exception handling. We will also talk about what exceptions are, and what causesthem.

Page 26: MIPS Sakis Tutorial

Article Sources and Contributors 24

Article Sources and ContributorsMIPS Assembly/Introduction  Source: http://en.wikibooks.org/w/index.php?oldid=1909265  Contributors: Whiteknight, 2 anonymous edits

MIPS Assembly/MIPS Architecture  Source: http://en.wikibooks.org/w/index.php?oldid=946090  Contributors: Herman Downs, Whiteknight, 7 anonymous edits

MIPS Assembly/MIPS Processors  Source: http://en.wikibooks.org/w/index.php?oldid=1493206  Contributors: DavidCary, Whiteknight

MIPS Assembly/MIPS Details  Source: http://en.wikibooks.org/w/index.php?oldid=1130966  Contributors: Jleedev, Whiteknight, 11 anonymous edits

MIPS Assembly/MIPS Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=1566762  Contributors: Hyad, Whiteknight, 4 anonymous edits

MIPS Assembly/Arithmetic Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=1326340  Contributors: Jomegat, Whiteknight, 10 anonymous edits

MIPS Assembly/Control Flow Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=1013282  Contributors: Whiteknight, 4 anonymous edits

MIPS Assembly/Memory Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=1689233  Contributors: Whiteknight, 1 anonymous edits

MIPS Assembly/Floating Point Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=1655377  Contributors: Webaware, Whiteknight, 4 anonymous edits

Floating Point  Source: http://en.wikibooks.org/w/index.php?oldid=1924913  Contributors: Adrignola, Darklama, David.Monniaux, DavidCary, Robert Horning, Whiteknight, Wknight8111

MIPS Assembly/MIPS Assemblers  Source: http://en.wikibooks.org/w/index.php?oldid=1188664  Contributors: Whiteknight, 1 anonymous edits

MIPS Assembly/MIPS Emulation  Source: http://en.wikibooks.org/w/index.php?oldid=1965967  Contributors: TomF, Whiteknight, 4 anonymous edits

MIPS Assembly/Subroutines  Source: http://en.wikibooks.org/w/index.php?oldid=1286478  Contributors: DavidCary, Spongebob88, Whiteknight, Xania, 2 anonymous edits

MIPS Assembly/Instruction Formats  Source: http://en.wikibooks.org/w/index.php?oldid=2015202  Contributors: Haaninjo, Ikarsik, Walker9010, Whiteknight, 17 anonymous edits

MIPS Assembly/System Instructions  Source: http://en.wikibooks.org/w/index.php?oldid=993635  Contributors: Whiteknight, 1 anonymous edits

MIPS Assembly/Pseudoinstructions  Source: http://en.wikibooks.org/w/index.php?oldid=1428924  Contributors: Robert ak, Whiteknight, 8 anonymous edits

MIPS Assembly/Register File  Source: http://en.wikibooks.org/w/index.php?oldid=1015633  Contributors: Whiteknight, 9 anonymous edits

MIPS Assembly/Exceptions  Source: http://en.wikibooks.org/w/index.php?oldid=1791918  Contributors: Whiteknight, 2 anonymous edits

Page 27: MIPS Sakis Tutorial

Image Sources, Licenses and Contributors 25

LicenseCreative Commons Attribution-Share Alike 3.0 Unportedhttp:/ / creativecommons. org/ licenses/ by-sa/ 3. 0/