11/09/2016
MIPS Quick Tutorial
MIPSArchitectureandAssemblyLanguageOverview
Adaptedfrom:http://edge.mcs.dre.g.el.edu/GICL/people/sevy/architecture/MIPSRef(SPIM).html
[RegisterDescription][I/ODescription]
DataTypesandLiterals
Datatypes:
Instructionsareall32bits
byte(8bits),halfword(2bytes),word(4bytes)
acharacterrequires1byteofstorage
anintegerrequires1word(4bytes)ofstorage
Literals:
numbersenteredasis.e.g.4
charactersenclosedinsinglequotes.e.g.'b'
stringsenclosedindoublequotes.e.g."Astring"
Registers
32generalpurposeregisters
registerprecededby$inassemblylanguageinstruction
twoformatsforaddressing:
usingregisternumbere.g.$0through$31
usingequivalentnamese.g.$t1,$sp
specialregistersLoandHiusedtostoreresultofmultiplicationanddivision
notdirectlyaddressablecontentsaccessedwithspecialinstructionmfhi("movefromHi")andmflo("movefromLo")
stackgrowsfromhighmemorytolowmemory
ThisisfromFigure9.9intheGoodman&Millertext
Register
Number
0
1
23
47
Alternative
Name
zero
$at
$v0$v1
$a0$a3
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
Description
thevalue0
(assemblertemporary)reservedbytheassembler
(values)fromexpressionevaluationandfunctionresults
(arguments)Firstfourparametersforsubroutine.
Notpreservedacrossprocedurecalls
1/8
11/09/2016
MIPS Quick Tutorial
815
$t0$t7
1623
$s0$s7
2425
$t8$t9
2627
$k0$k1
28
$gp
29
$sp
30
$s8/$fp
31
$ra
(temporaries)Callersavedifneeded.Subroutinescanusew/outsaving.
Notpreservedacrossprocedurecalls
(savedvalues)Calleesaved.
Asubroutineusingoneofthesemustsaveoriginalandrestoreitbeforeexiting.
Preservedacrossprocedurecalls
(temporaries)Callersavedifneeded.Subroutinescanusew/outsaving.
Theseareinadditionto$t0$t7above.
Notpreservedacrossprocedurecalls.
reservedforusebytheinterrupt/traphandler
globalpointer.
Pointstothemiddleofthe64Kblockofmemoryinthestaticdata
segment.
stackpointer
Pointstolastlocationonthestack.
savedvalue/framepointer
Preservedacrossprocedurecalls
returnaddress
SeealsoBrittonsection1.9,Sweetmansection2.21,LarusAppendixsectionA.6
ProgramStructure
justplaintextfilewithdatadeclarations,programcode(nameoffileshouldendinsuffix.stobeusedwithSPIMsimulator)
datadeclarationsectionfollowedbyprogramcodesection
DataDeclarations
placedinsectionofprogramidentifiedwithassemblerdirective.data
declaresvariablenamesusedinprogramstorageallocatedinmainmemory(RAM)
Code
placedinsectionoftextidentifiedwithassemblerdirective.text
containsprogramcode(instructions)
startingpointforcodee.g.ecutiongivenlabelmain:
endingpointofmaincodeshoulduseexitsystemcall(seebelowunderSystemCalls)
Comments
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
2/8
11/09/2016
MIPS Quick Tutorial
anythingfollowing#onaline
#Thisstuffwouldbeconsideredacomment
TemplateforaMIPSassemblylanguageprogram:
# Comment giving name of program and description of function
# Template.s
# Bare-bones outline of MIPS assembly language program
.data
# variable declarations follow this line
# ...
.text
# instructions follow this line
main:
# indicates start of code (first instruction to execute)
# ...
# End of program, leave a blank line afterwards to make SPIM happy
DataDeclarations
formatfordeclarations:
name:
storage_type
value(s)
createstorageforvariableofspecifiedtypewithgivennameandspecifiedvalue
value(s)usuallygivesinitialvalue(s)forstoragetype.space,givesnumberofspacestobeallocated
Note:labelsalwaysfollowedbycolon(:)
example
var1:
array1:
.word
.byte
3
# create a single integer variable with initial value 3
'a','b' # create a 2-element character array with elements initialized
# to a and b
.space 40
# allocate 40 consecutive bytes, with storage uninitialized
# could be used as a 40-element character array, or a
# 10-element integer array; a comment should indicate which!
array2:
Load/StoreInstructions
RAMaccessonlyallowedwithloadandstoreinstructions
allotherinstructionsuseregisteroperands
load:
lw
register_destination, RAM_source
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
3/8
11/09/2016
MIPS Quick Tutorial
#copyword(4bytes)atsourceRAMlocationtodestinationregister.
lb
register_destination, RAM_source
#copybyteatsourceRAMlocationtoloworderbyteofdestinationregister,
#andsigne.g.tendtohigherorderbytes
storeword:
sw
register_source, RAM_destination
#storewordinsourceregisterintoRAMdestination
sb
register_source, RAM_destination
#storebyte(loworder)insourceregisterintoRAMdestination
loadimmediate:
li
register_destination, value
#loadimmediatevalueintodestinationregister
example:
.data
var1: .word
.text
__start:
lw
li
sw
done
23
# declare storage for var1; initial value is 23
$t0, var1
$t1, 5
$t1, var1
# load contents of RAM location into register $t0: $t0 = var1
# $t1 = 5 ("load immediate")
# store contents of register $t1 into RAM: var1 = $t1
IndirectandBasedAddressing
Usedonlywithloadandstoreinstructions
loadaddress:
la
$t0, var1
copyRAMaddressofvar1(presumablyalabeldefinedintheprogram)intoregister$t0
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
4/8
11/09/2016
MIPS Quick Tutorial
indirectaddressing:
lw
$t2, ($t0)
loadwordatRAMaddresscontainedin$t0into$t2
sw
$t2, ($t0)
storewordinregister$t2intoRAMataddresscontainedin$t0
basedorindexedaddressing:
lw
$t2, 4($t0)
loadwordatRAMaddress($t0+4)intoregister$t2
"4"givesoffsetfromaddressinregister$t0
sw
$t2, -12($t0)
storewordinregister$t2intoRAMataddress($t012)
negativeoffsetsarefine
Note:basedaddressingisespeciallyusefulfor:
arraysaccesselementsasoffsetfrombaseaddress
stackseasytoaccesselementsatoffsetfromstackpointerorframepointer
example
array1:
__start:
.data
.space 12
.text
la
$t0, array1
li
$t1, 5
sw $t1, ($t0)
li $t1, 13
sw $t1, 4($t0)
li $t1, -7
sw $t1, 8($t0)
done
# declare 12 bytes of storage to hold array of 3 integers
#
#
#
#
#
#
# load base address of array into register $t0
$t1 = 5 ("load immediate")
first array element set to 5; indirect addressing
$t1 = 13
second array element set to 13
$t1 = -7
third array element set to -7
ArithmeticInstructions
mostuse3operands
alloperandsareregistersnoRAMorindirectaddressing
operandsizeisword(4bytes)
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
5/8
11/09/2016
MIPS Quick Tutorial
add
sub
addi
addu
subu
$t0,$t1,$t2
$t2,$t3,$t4
$t2,$t3, 5
$t1,$t6,$t7
$t1,$t6,$t7
#
#
#
#
#
$t0 = $t1 + $t2; add as signed (2's complement) integers
$t2 = $t3 $t4
$t2 = $t3 + 5; "add immediate" (no sub immediate)
$t1 = $t6 + $t7; add as unsigned integers
$t1 = $t6 + $t7; subtract as unsigned integers
mult
$t3,$t4
div
$t5,$t6
mfhi
mflo
$t0
$t1
#
#
#
#
#
#
#
multiply 32-bit quantities in $t3 and $t4, and store 64-bit
result in special registers Lo and Hi: (Hi,Lo) = $t3 * $t4
Lo = $t5 / $t6 (integer quotient)
Hi = $t5 mod $t6 (remainder)
move quantity in special register Hi to $t0: $t0 = Hi
move quantity in special register Lo to $t1: $t1 = Lo
used to get at result of product or quotient
move
$t2,$t3 # $t2 = $t3
ControlStructures
Branches
comparisonforconditionalbranchesisbuiltintoinstruction
b
beq
blt
ble
bgt
bge
bne
target
$t0,$t1,target
$t0,$t1,target
$t0,$t1,target
$t0,$t1,target
$t0,$t1,target
$t0,$t1,target
#
#
#
#
#
#
#
unconditional branch to program label target
branch to target if $t0 = $t1
branch to target if $t0 < $t1
branch to target if $t0 <= $t1
branch to target if $t0 > $t1
branch to target if $t0 >= $t1
branch to target if $t0 <> $t1
j
jr
target # unconditional jump to program label target
$t3
# jump to address contained in $t3 ("jump register")
Jumps
SubroutineCalls
subroutinecall:"jumpandlink"instruction
jal
sub_label
# "jump and link"
copyprogramcounter(returnaddress)toregister$ra(returnaddressregister)
jumptoprogramstatementatsub_label
subroutinereturn:"jumpregister"instruction
jr
$ra
# "jump register"
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
6/8
11/09/2016
MIPS Quick Tutorial
jumptoreturnaddressin$ra(storedbyjalinstruction)
Note:returnaddressstoredinregister$raifsubroutinewillcallothersubroutines,orisrecursive,returnaddressshouldbecopiedfrom$raontostacktopreserveit,since
jalalwaysplacesreturnaddressinthisregisterandhencewilloverwritepreviousvalue
SystemCallsandI/O(SPIMSimulator)
usedtoreadorprintvaluesorstringsfrominput/outputwindow,andindicateprogramend
usesyscalloperatingsystemroutinecall
firstsupplyappropriatevaluesinregisters$v0and$a0$a1
resultvalue(ifany)returnedinregister$v0
Thefollowingtableliststhepossiblesyscallservices.
Service
print_int
Code
Arguments
in$v0
1
$a0=integertobeprinted
print_float
print_double
print_string
read_int
read_float
read_double
2
3
4
5
6
7
read_string
sbrk
exit
9
10
Results
$f12=floattobeprinted
$f12=doubletobeprinted
$a0=addressofstringinmemory
integerreturnedin$v0
floatreturnedin$v0
doublereturnedin$v0
$a0=memoryaddressofstringinput
buffer
$a1=lengthofstringbuffer(n)
$a0=amount
addressin$v0
Theprint_stringserviceexpectstheaddresstostartanullterminatedcharacterstring.Thedirective.asciizcreatesanullterminatedcharacterstring.
Theread_int,read_floatandread_doubleservicesreadanentirelineofinputuptoandincludingthenewlinecharacter.
Theread_stringservicehasthesamesemanticesastheUNIXlibraryroutinefgets.
Itreadsupton1charactersintoabufferandterminatesthestringwithanullcharacter.
Iffewerthann1charactersareinthecurrentline,itreadsuptoandincludingthenewlineandterminatesthestringwithanullcharacter.
Thesbrkservicereturnstheaddresstoablockofmemorycontainingnadditionalbytes.Thiswouldbeusedfordynamicmemoryallocation.
Theexitservicestopsaprogramfromrunning.
e.g.
Print out integer value contained in register $t2
li
$v0, 1
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
# load appropriate system call code into register $v0;
# code for printing integer is 1
7/8
11/09/2016
MIPS Quick Tutorial
move
$a0, $t2
syscall
e.g.
# move integer to be printed into $a0: $a0 = $t2
# call operating system to perform operation
Read integer value, store in RAM location with label int_value (presumably declared in data section)
li
$v0, 5
# load appropriate system call code into register $v0;
# code for reading integer is 5
# call operating system to perform operation
# value read from keyboard returned in register $v0;
# store this in desired location
syscall
sw
$v0, int_value
e.g.
Print out string (useful for prompts)
string1
.data
.asciiz "Print this.\n"
main:
.text
li
# declaration for string variable,
# .asciiz directive makes string null terminated
$v0, 4
# load appropriate system call code into register $v0;
# code for printing string is 4
# load address of string to be printed into $a0
# call operating system to perform print operation
la
$a0, string1
syscall
e.g. To indicate end of program, use exit system call; thus last lines of program should be:
li
$v0, 10
syscall
# system call code for exit = 10
# call operating sys
http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm
8/8