MIPS Assembly - University of the...
-
Upload
duongxuyen -
Category
Documents
-
view
216 -
download
1
Transcript of MIPS Assembly - University of the...
ìComputer Systems and NetworksECPE170– JeffShafer– UniversityofthePacific
MIPSAssembly
Lab Schedule
Activitiesì ThisWeek
ì MIPSdiscussionì Practiceproblems
(whiteboard)ì UsingtheQtSPIM
simulatorì Discussavailableresources
AssignmentsDueì Lab10
ì DuebyApr12th 5:00am
ì Lab11ì DuebyApr19th 5:00am
ì Lab12ì DuebyMay3rd 5:00am
Spring2017ComputerSystemsandNetworks
2
Person of the Day – John Cocke
ì Computerarchitecturepioneerì “FatherofRISCArchitecture”ì DevelopedIBM801processor,
1975-1980
ì Winner,ACMTuringAward,1987
Spring2017ComputerSystemsandNetworks
3
RISC=ReducedInstructionSetComputing
Achievehigherperformancewithsimpleinstructionsthatexecutefaster
Person of the Day – John Hennessy
ì Computerarchitecturepioneer
ì PopularizedRISCarchitectureinearly1980’s
ì FounderofMIPSComputerSystemsin1984
ì Currentlypresidentofanobscureschool:StanfordUniversity
Spring2017ComputerSystemsandNetworks
4
Class to Date
Spring2017ComputerSystemsandNetworks
5
Human(CCode)
Compiler(Assemblycode)
Compiler(Objectfile/binarycode)
Linker(Executableprogram)
Class Now
Spring2017ComputerSystemsandNetworks
6
Human(Assemblycode)
Assembler(Objectfile/binarycode)
Linker(ExecutableProgram)
ìMIPS
Spring2017ComputerSystemsandNetworks
7
MIPS Overview
ì Familyofcomputerprocessorsfirstintroducedin1981
ì MicroprocessorwithoutInterlockedPipelineStagesì Originalacronymì NowMIPSstandsfornothingatall…
Spring2017ComputerSystemsandNetworks
8
MIPS Products
ì Embeddeddevicesì Cisco/Linksysroutersì Cableboxesì MIPSprocessorisburiedinsideSystem-on-a-Chip(SOC)
ì Gaming/entertainmentì Nintendo64ì Playstation,Playstation 2,PSP
ì Computers?ì Notsomuchanymore…ì SGI/DEC/NECworkstationsbackin1990’s
Spring2017ComputerSystemsandNetworks
9
MIPS Products
ì NASANewHorizonsprobeì LaunchedJanuary2006
ì MIPS“Mongoose-V”chipì 12MhZ (2006,remember?)
ì RadiationHardenedì BasedonR3000
(PlayStationCPU)
Spring2017ComputerSystemsandNetworks
10
http://blog.imgtec.com/mips-processors/mips-goes-to-plutohttp://synova.com/proc/MongooseV.pdf
MIPS Design
ì RISC–Whatdoesthismean?ì ReducedInstructionSetComputingì Simplifieddesignforinstructionsì Usemoreinstructionstoaccomplishsametask
ì Buteachinstructionrunsmuchfaster!
ì 32bits(originally)–Whatdoesthismean?ì 1“word”=32bitsì Sizeofdataprocessedbyanintegeraddinstructionì New(er)MIPS64designis64bits,butwewon’t
focusonthat
Spring2017ComputerSystemsandNetworks
11
ìMIPS Assembly Programming
Spring2017ComputerSystemsandNetworks
12
Quotes – Donald Knuth
Spring2017ComputerSystemsandNetworks
13
“People who are more than casually interested in computers should have at least some idea of what the underlying hardware is like. Otherwise the programs they write will be pretty weird.” – Donald Knuth
Thisisyourmotivationintheassemblylabs!
Why Learn Assembly Programming?
ì ComputerSciencetrackì Understandcapabilities(andlimitations)ofphysical
machineì Abilitytooptimizeprogramperformance(or
functionality)attheassemblylevelifnecessary
ì ComputerEngineer trackì Futurecourses(e.g.ECPE173)willfocusonprocessor
designì Startattheassemblyprogramminglevelandmoveinto
hardwareì How doestheprocessorimplementtheadd instruction?ì How doestheprocessorknowwhatdatatoprocess?
Spring2017ComputerSystemsandNetworks
14
Instruction Set Architecture
ì InstructionSetArchitecture(ISA)istheinterfacebetweenhardwareandsoftwareì Specifiestheformatofprocessorinstructionsì Specifiestheformatofmemoryaddresses
(andaddressingmodes)ì Specifiestheprimitiveoperationstheprocessorcan
perform
Spring2017ComputerSystemsandNetworks
15
Instruction Set Architecture
ì ISAisthe“contract”betweenthehardwaredesignerandtheassembly-levelprogrammer
ì Documentedinamanualthatcanbehundredsorthousandsofpageslongì Example:Intel64andIA-32ArchitecturesSoftware
DevelopersManualì http://www.intel.com/content/www/us/en/process
ors/architectures-software-developer-manuals.htmlì Nojoke– themanualPDFfromDecember2015
is3883pageslong!
Spring2017ComputerSystemsandNetworks
16
Instruction Set Architecture
ì ProcessorfamiliessharethesameISA
ì ExampleISAs:ì Intelx86ì Intel/AMDx86-64ì IntelItaniumì ARMì IBMPowerPCì MIPS
Spring2017ComputerSystemsandNetworks
17
Allcompletelydifferent,inthewaythatC++,Java,Perl,andPHParealldifferent…
…andyetlearningonelanguagemakeslearningthenextonemucheasier
Why MIPS?
ì WhychooseMIPS?ì TheMIPSISAmanual(volume1,atleast)isasvelte
108pages!ì ExtremelycommonISAintextbooksì Freelyavailablesimulatorì Commonembeddedprocessorì Goodbuilding-blockforotherRISC-styleprocessorsì AlignswithECPE173course
Spring2017ComputerSystemsandNetworks
18
Arithmetic Instructions
ì Addition
ì Subtraction
Spring2017ComputerSystemsandNetworks
19
add <result>, <input1>, <input2>
sub <result>, <input1>, <input2>
Operation/“Opcode” Operands
Task : Write Code
ì WriteMIPSassemblyfor
Spring2017ComputerSystemsandNetworks
20
f=(g+h)– (i+j)
add temp0, g, hadd temp1, i, jsub f, temp0, temp1
Spring2017ComputerSystemsandNetworks
21
Congratulations!
You’renowanassemblyprogrammingexpert!
Data Sources
ì Previousexamplewas(justalittlebit) fake…ì Wemadeupsomevariables:
temp0,temp1,f,g,h,i,andjì ThisiswhatyoudowhenprogramminginC++
(oranyhighlevellanguage)
Spring2017ComputerSystemsandNetworks
22
Problem:Youcan’tmakeupvariablesinassembly!(asleast,notinthisfashion)
Data Sources
Spring2017ComputerSystemsandNetworks
23
Wherecanweexplicitly placedatainassemblyprogramming?
CPU
ALU
1. Registersì OntheCPUitselfì VeryclosetoALUì Tinyì Accesstime:1cycle
2. Memoryì Off-chipì Largeì Accesstime:100+cycles
Cache Memory
Aside – Cache
ì Review:Doestheprogrammerexplicitlymanagethecache?
ì Answer:No!ì Theassemblyprogrammerjustreads/writes
memoryaddressesì Cacheismanagedautomaticallyinhardwareì Result:Memoryappears tobefasterthanitreallyis
Spring2017ComputerSystemsandNetworks
24
ECPE 71
ì FromyourknowledgeofECPE71(DigitalDesign),howwouldyouconstructaregister?
Spring2017ComputerSystemsandNetworks
25
FlipFlops!(DFlipFlopshown)
ECPE 71 – Group of Registers
Spring2017ComputerSystemsandNetworks
26
Registers
ì MIPSdesign:32integerregisters,eachholding32bitsì “Wordsize”=32bits
ì Thisisonly19– wherearetherestofthe32?ì Reservedbyconvention forotherusesì We’lllearnafewmorelater…
Spring2017ComputerSystemsandNetworks
27
Name Use
$zero Constantvalue:ZERO
$s0-$s7 Localvariables
$t0-$t9 Temporaryresults
Task : Write Code
ì WriteMIPSassemblyusingregisters for:
Spring2017ComputerSystemsandNetworks
28
f=(g+h)– (i+j)
Code:add $t0, $s0, $s1add $t1, $s2, $s3sub $s4, $t0, $t1
Map:$s0=g$s1=h$s2=i$s3=j$s4=f
More Arithmetic Instructions
ì AddImmediate
Spring2017ComputerSystemsandNetworks
29
addi <result>, <input1>, <constant>
Canbeapositiveornegativenumber!
RegisterRegister
Task : Write Code
ì WriteMIPSassemblyusingregisters for:
Spring2017ComputerSystemsandNetworks
30
f=g+20
Code:addi $s0, $s1, 20
Map:$s0=f$s1=g
Memory
ì Challenge:Limitedsupplyofregistersì Physicallimitation:Wecan’tputmoreonthe
processorchip,andmaintaintheircurrentspeedì ManyelementscompeteforspaceintheCPU…
ì Solution:Storedatainmemory
ì MIPSprovidesinstructionsthattransferdatabetweenmemoryandregisters
Spring2017ComputerSystemsandNetworks
31
Memory Fundamentals
Spring2017ComputerSystemsandNetworks
32
MIPScannot directlymanipulatedatainmemory!
Datamustbemovedtoaregisterfirst!(Andresultsmustbesavedto
aregisterwhenfinished)
ThisisacommondesigninRISC-stylemachines:aload-store architecture
Memory Fundamentals
Spring2017ComputerSystemsandNetworks
33
Yes,it’sapain tokeepmovingdatabetweenregistersandmemory.
Butconsiderityourmotivationtoreducethenumberofmemoryaccesses.Thatwillimproveprogramperformance!
Memory Fundamentals
ì Fourquestionstoaskwhenaccessingmemory:1. Whatdirection doIwanttocopydata?
(i.e.tomemory,orfrommemory?)2. Whatisthespecificmemoryaddress?3. Whatisthespecificregistername?(ornumber)4. HowmuchdatadoIwanttomove?
Spring2017ComputerSystemsandNetworks
34
CPU
Memory – Fundamental Operations
Loadì Copydatafrom
memorytoregister
Storeì Copydatafrom
registertomemory
Spring2017ComputerSystemsandNetworks
35
CPUMemory Memory
Memory – Determining Address
ì Therearemanywaystocalculatethedesiredmemoryaddressì Thesearecalledaddressingmodesì We’lljustlearnonemodenow:
base+offset
ì ThebaseaddresscouldbeHUGE!(32bits)ì We’llplaceitinaregister
ì Theoffsetistypicallysmallì We’lldirectlyincludeitinthe
instructionasan“immediate”
Spring2017ComputerSystemsandNetworks
36
Memory
0
1
2
3
4
Base
Offset
MIPSnotation:offset(base)
Memory – Register Name
ì Whatisthenameoftheregistertouseaseitherthedatadestination(foraload)oradatasource(forastore)?
ì Usethesameregisternamespreviouslylearned
Spring2017ComputerSystemsandNetworks
37
Memory - Data Transfer Size
ì HowmuchdatadoIwanttoloadorstore?ì Afullword?(32bits)ì A“halfword”?(16bits)ì Abyte?(8bits)
ì We’llhaveadifferentinstructionforeachquantityofdata
ì Nooptiontoloadanentirearray!ì Willneedaloopthatloads1elementatatime…
Spring2017ComputerSystemsandNetworks
38
Memory – Data Transfer Instructions
ì Load (copyfrommemorytoregister)
ì Store (copyfromregistertomemory)
Spring2017ComputerSystemsandNetworks
39
lw <reg>, <offset>(<base addr reg>)
lb <reg>, <offset>(<base addr reg>)
sw <reg>, <offset>(<base addr reg>)
sb <reg>, <offset>(<base addr reg>)
Word:
Byte:
Word:
Byte:
Register MemoryLocation
Example
ì Whatwillthisinstructiondo?
ì Loadwordcopiesfrommemorytoregister:ì Baseaddress:storedinregister$s2ì Offset:20bytesì Destinationregister:$s1ì Amountofdatatransferred:1word(32bits)
Spring2017ComputerSystemsandNetworks
40
lw $s1, 20($s2)
Task : Write Code
ì WriteMIPSassemblyfor:
Spring2017ComputerSystemsandNetworks
41
g=h+array[16](Arrayofwords.Canleavegandhinregisters)
Code:# Assume $s3 is already set
lw $t0, 16($s3)add $s1, $s2, $t0
Map:$s1=g$s2=h$s3=baseaddressofarray
Memory Address
ì Slightflaw inprevioussolutionì Theprogrammerintendedtoloadthe16th array
elementì Eachelementis4bytes(1word)ì Theoffsetisinbytesì 16*4=64
Spring2017ComputerSystemsandNetworks
42
Correct Code:# Assume $s3 is already set
lw $t0, 64($s3)add $s1, $s2, $t0
Task : Write Code
ì WriteMIPSassemblyfor:
Spring2017ComputerSystemsandNetworks
43
array[12]=h+array[8](Arrayofwords.Assumehisinregister)
Code:# Assume $s3 is already set
lw $t0, 32($s3)add $t1, $s2, $t0sw $t1, 48($s3)
Map:$s2=h$s3=baseaddressofarray$t1=temp
Task : Write Code
ì WriteMIPSassemblyfor:
Spring2017ComputerSystemsandNetworks
44
g=h+array[i](Arrayofwords.Assumeg,h,andi areinregisters)
Code:# "Multiply" i by 4add $t1, $s4, $s4 # x2add $t1, $t1, $t1 # x2 again# Get addr of array[i]add $t1, $t1, $s3# Load array[i]lw $t0, 0($t1)# Compute addadd $s1, $s2, $t0
Map:$s1=g$s2=h$s3=baseaddressofarray$s4=i
Aside – Compiler
ì WhenprogramminginC/C++,areyourvariables(int,float,char,…)storedinmemoryorinregisters?
ì Answer:Itdepends
ì Compilerwillchoosewheretoplacevariablesì Registers:Loopcounters,frequentlyaccessedscalar
values,variableslocaltoaprocedureì Memory:Arrays,infrequentlyaccesseddatavalues
Spring2017ComputerSystemsandNetworks
45
ìMIPS Branches / Loops
Spring2017ComputerSystemsandNetworks
46
Branches, Tests, Jump
ì BranchonEqual(if$1==$2,goto dest)
ì SetonLessThan(if$2<$3,set$1=1,otherwise0)
ì Jump(goto dest)
Spring2017ComputerSystemsandNetworks
47
beq <reg1>, <reg2>, <destination>
slt <reg1>, <reg2>, <reg3>
j <destination>
Task : Write Code
ì WriteMIPSassemblyfor:
Spring2017ComputerSystemsandNetworks
48
if(A==B){
<equal-code>}else{
<not-equal-code>}<after-if-code>
A==B?
… …
True False
Task : Write Code
ì WriteMIPSassembly:
Spring2017ComputerSystemsandNetworks
49
Code:beq $s0,$s1,equal<not-equal-code>j done
equal: <equal-code>j done
done: <after-if-code>
Map:$s0=A$s1=B
Task : Write Code
ì WriteMIPSassemblyfor:
Spring2017ComputerSystemsandNetworks
50
while(A!=B){
<loop-body>}
<post-loop-code>
A!=B?
…
…
True
False
Task : Write Code
ì WriteMIPSassembly:
Spring2017ComputerSystemsandNetworks
51
Code:
start: beq $s0,$s1,done<loop-body>j start
done: <post-loop-code>
Map:$s0=A$s1=B
Spring2017ComputerSystemsandNetworks
52
Therearemany,many,variationsofbranchortestinstructionsintendedtosimplifyprogramming
1. Show:AppendixAReference
2. Discuss:InstructionversusPseudo-Instruction
Resources
ì ResourcesonWebsite– view“Resources”pageì MIPSInstructionSet(partialguide)
ì ResourcesavailableinSakaisite(underECPE170)ì HP_AppA.pdf
ì AppendixAfromfamousHennessy&PattersonComputerOrganization textbook
ì Assemblers,Linkers,andtheSPIMsimulatorì Startingonpage51isanoverviewoftheMIPSassembly
commands!ì MIPS_Green_Sheet.pdf
ì “Cheatsheet”forexpertprogrammersì MIPScommands,registers,memoryconventions,…
Spring2017ComputerSystemsandNetworks
53
ìMIPS Simulator Walkthrough
Spring2017ComputerSystemsandNetworks
54
Spring2017ComputerSystemsandNetworks
55
SingleStepButton!
(Advanceby1instruction)
Spring2017ComputerSystemsandNetworks
56