Documente Academic
Documente Profesional
Documente Cultură
A.Introduction
Objectives
Attheendofthislabyoushouldbeableto:
Usedirectandindirectaddressingmodesofaccessingdatainmemory
Createaniterativeloopofinstructions
DisplaytextonconsoleusinganIOinstruction
Createasubroutine,callandreturnfromsubroutine
Passparameterstoasubroutine
B.Processor(CPU)Simulators
Thecomputerarchitecturetutorialsaresupportedbysimulators,whicharecreated
tounderpintheoreticalconceptsnormallycoveredduringthelectures.The
simulatorsprovidevisualandanimatedrepresentationofmechanismsinvolvedand
enablethestudentstoobservethehiddeninnerworkingsofsystems,whichwould
bedifficultorimpossibletodootherwise.Theaddedadvantageofusingsimulators
isthattheyallowthestudentstoexperimentandexploredifferenttechnological
aspectsofsystemswithouthavingtoinstallandconfiguretherealsystems.
C.BasicTheory
Theprogrammingmodelofcomputerarchitecturedefinesthoselowlevel
architecturalcomponents,whichincludethefollowing
CPUinstructionset
CPUregisters
Differentwaysofaddressinginstructionsanddataininstructions
Italsodefinesinteractionbetweentheabovecomponents.Itisthislowlevel
programmingmodelwhichmakesprogrammedcomputationspossible.Youshould
doadditionalreadinginordertoformabetterunderstandingofthedifferentparts
ofamodernCPUarchitecture(refertotherecommendedreadinglistavailableinthe
modulehandbookandontheBB).
D.SimulatorDetails
Thissectionincludessomebasicinformationonthesimulator,whichshouldenable
thestudentstousethesimulator.Thetutor(s)willbeavailabletohelpanyone
experiencingdifficultyinusingthesimulator.Thesimulatorforthislabisan
applicationrunningonaPCrunningMSWindowsoperatingsystem.
Themainsimulatorwindowiscomposedofseveralviews,whichrepresentdifferent
functionalpartsofthesimulatedprocessor.TheseareshowninImage1belowand
arecomposedof
1
CPUInstructionmemory
SpecialCPUregisters
CPU(generalpurpose)registers
Programstack
Programcreationandrunningfeatures
Memoryinwhichdataisstored
Input,outputconsole
CPUInstruction
memoryview
SpecialCPU
registersview
Addprogram
instructionstab Programlist view
Createprogramtab
Clicktoviewprogram
datamemory
CPUregisters
view
Programstackview
Clicktoview
IOconsole
Image1CPUSimulatorwindow
Thepartsofthesimulatorrelevanttothislabaredescribedbelow.Pleasereadthis
informationcarefullyandtrytoidentifythedifferentpartsontheCPUSimulator
windowBEFOREattemptingthefollowingexercises.Usetheinformationinthis
sectioninconjunctionwiththeexercisesthatfollow.
1.CPUinstructionmemoryview
Image2Instructionmemory
view
Thisviewcontainstheprogram
instructions. The instructions
are displayed as sequences of
lowlevel
instruction
mnemonics (assemblerlevel
format)andnotasbinarycode.
This is done for clarity and
makes code more readable by
humans.
2.SpecialCPUregistersview ThisviewshowsthesetofCPUregisters,
Image3SpecialCPU
registersview
whichhavepredefinedspecialistfunctions:
PC:ProgramCountercontainstheaddress
ofthenextinstructiontobeexecuted.
IR:InstructionRegistercontainsthe
instructioncurrentlybeingexecuted.
SR:StatusRegistercontainsinformation
pertainingtotheresultofthelastexecuted
instruction.
SP:StackPointerregisterpointstothevalue
maintainedatthetopoftheprogramstack
(seebelow).
BR:BaseRegistercontainscurrentbase
address.
MAR:MemoryAddressRegistercontains
thememoryaddresscurrentlybeing
accessed.
Statusbits:OV:Overflow;Z:Zero;N:
Negative
3
3.CPUregistersview
Image4 CPURegistersview
The register set view shows the
contents of all the generalpurpose
registers, which are used to maintain
temporary values as the program's
instructionsareexecuted.Registersare
very fast memories that hold
temporary values while the CPU
executesinstructions.
Thisarchitecturesupportsfrom8to64
registers. These registers are often
used to hold values of a program's
variables as defined in highlevel
languages.
Thisviewdisplayseachregister'sname
(Reg),itscurrentvalue(Val)andsome
additional values, which are reserved
for program debugging. It can also be
used to reset the individual register
values manually which is often useful
for advanced debugging. To manually
changearegisterscontent,firstselect
the register then enter the new value
inthetextbox,RegValue,andclickon
the CHANGE button in the Registers
tab.
4.Programstackview
Image5Programstackview
Theprogramstackisanotherareawhich
maintains temporary values as the
instructions are executed. The stack is a
LIFO(lastinfirstout)datastructure.Itis
often used for efficient interrupt
handling and subroutine calls. Each
programhasitsownindividualstack.
TheCPUinstructionsPSH(push)andPOP
are used to store values on top of stack
and pop values from top of stack
respectively.
5.Programlistview
Image6 ProgramListView
6.Programcreation
Image7 Createprogramtab
Tocreateanewprogramenterits
nameintheProgramNamebox
anditsbaseaddressintheBase
AddressboxthenclickontheADD
button.Thenewprogramsname
willappearintheProgramListview
(seeImage6).
Image8Addprogram
instructionstab
Use ADD NEW button to add a
new instruction; use EDIT
button to edit the selected
instruction; use MOVE DOWN/
MOVE UP buttons to move the
selected instruction down or up;
use INSERT ABOVE/INSERT
BELOWbuttonstoinsertanew
instruction above or below the
selectedinstructionrespectively.
7.Programdatamemoryview
Image9Programdatamemoryview
TheCPUinstructionsthataccessthatpartofthememorycontainingdatacanwrite
orreadthedatainaddressedlocations.Thisdatacanbeseeninthememorypages
windowshowninImage9above.YoucandisplaythiswindowbyclickingtheSHOW
PROGRAMDATAMEMORYbuttonshowninImage6above.TheLadd(logical
address)columnshowsthestartingaddressofeachlineinthedisplay.Eachlineof
thedisplayrepresents8bytesofdata.ColumnsB0throughtoB7representbytes0
to7oneachline.TheDatacolumnshowsthedisplayablecharacterscorresponding
tothe8bytes.Thosebytesthatcorrespondtonondisplayablecharactersareshown
asdots.Thedatabytesaredisplayedinhexformatonly.Forexample,inImage9,
therearenonzerodatabytesinaddresslocations19and37.Thesedatabytes
correspondtodisplayablecharacterscapitalAandB.
Tochangethevaluesofanybytes,firstselecttheline(s)containingthebytes.Then
usetheinformationintheInitializeDataframetomodifythevaluesofthebytesin
theselectedline(s)asInteger,BooleanorStringformats.Youneedtoclickthe
UPDATEbuttontomakethechange.
8.IOconsoleview
Image10Input,outputconsoleview
Image10aboveshowstheconsolewhichisusedbyprogramstowritemessagesto
andreaddatafrom.ItcanbedisplayedbyclickingontheINPUTOUTPUTbutton
showninImage1above.ClickontheSHOWKEYBDbuttontodisplayasmall
keyboardwindowwhichcanbeusedtoinputdatatoprogramsrequestinginput.
1. IntheAppendixattheendofthisdocument,locatetheinstruction,whichis
usedtostoreonebyteofdatainamemorylocation.Useittostorenumber65in
addresslocation20(allnumbersareindecimal).Thisisanexampleofdirect
addressing.RefertoImage9toseehowtodisplaythecontentsofdatamemory.
Makeanotebelowoftheinstructionused:
2. Createaninstructiontomovedecimalnumber22toregisterR01andmakea
noteofitbelow.ExecutethisinstructionandverifytheresultinR01.
3. Createaninstructiontostoredecimalnumber51inmemorylocationthe
addressofwhichiscurrentlystoredinregisterR01.Thisisanexampleofindirect
addressing.Notetheuseofthe@prefixnexttoR01inthiscase.
4. Makeanoteofwhatyouseeindatamemorylocations20and22(refertoImage
9forhelpinformationonhowtodisplaythedatamemory).
5. Now,letscreatealoop.First,enterthefollowingcode.The#prefixisusedto
denotealiteralvaluethusdistinguishingitfromanaddressvaluewhichdoesnot
useit.R01representsanarbitraryregister;youcanuseanyoftheregistersfrom
R00toR31.
MOV
ADD
CMP
JNE
HLT
#0, R01
#1, R01
#5, R01
0
6. Theabovecodeisnotquitereadyyet.TheJNEinstructionusesanumericvalue
astheaddresstojumpto.Inthiscaseitis0.Thismaynotalwaysbethecaseso
inordertomakethecodemoreflexiblewecanuselabelstorepresent
instructionaddresses.Thesimulatorallowsyoutodothis.Followthe
instructionsbelowforthis:
HighlighttheaboveMOVinstruction(i.e.theoneintheboxabove)
ClickontheINSERTBELOWbutton
TypelabelnameL0intheboxnexttotheENTERLABELbuttoninthe
windowyouusetoenterinstructions
ClicktheENTERLABELbutton
Thenewcodeshouldnowlooklikethis(modificationsareinredcolour):
MOV
L0:
ADD
CMP
JNE
HLT
#0, R01
#1, R01
#5, R01
0
Next,highlighttheJNEinstruction
ClickontheEDITbutton
SelectL0inthedropdownlistundertheSourceOperandsectionbutton
inthewindowyouusetoenterinstructions
ClicktheEDITbutton
Thenewcodeshouldnowlooklikethis:
MOV
L0:
ADD
CMP
JNE
HLT
#0, R01
#1, R01
#5, R01
$L0
7. Asyoucansee,thelabelL0representstheaddressoftheinstruction
immediatelybelowit,i.e.theADDinstruction.SonowtheJNEinstructioncan
useL0astheaddresstojumpto.AsthelabelL0canrepresentanyaddressthis
codeshouldworkanywhereinmemorymakingitveryflexible.The$sign
indicatesthatL0isalabel.Theabovecodeisnowreadytorun.Torunthis
program,followtheinstructionsbelow:
ClickontheRESETPROGRAMbuttonintheCPUSimulatorwindow
HighlighttheMOVinstruction,i.e.thefirstinstructionoftheprogram
Adjustthespeedslidertoavalue,say,nearesttothevalue80
ClickontheRUNbutton
Afterashortwhiletheprogramshouldstop.Ifitappearstoruntoolong
thenclickontheSTOPbuttonandcheckyourcode.Correctitifnecessary
andrepeattheaboveinstructionsonceagain.
WhentheprogramstopsmakeanoteofthevalueinR01below
8. Nowyoullmakeaslightmodificationtotheaboveprogram.Changethe
programcodesothattheprogramloopisrepeatedaslongasthevalueofR01is
lessthanorequalto3(youmaywishtorefertotheAppendixforthis)andtest
10
it.WhenyougetitrightmakeanoteofthevalueinR01andcopythenewcode
below.Now,changethemodifiedinstructionsbacktotheoriginalinstructions
(youcanusetheUNDObuttonforthisseeImage8above).
9. Ok,letscreateasimplesubroutine.Enterthefollowingnewcode.Youneedto
createanewlabelL1atthestartofthesubroutine.Thislabelrepresentsthe
startingaddressofthesubroutine.YoumustenterthelabelusingtheENTER
LABELbuttononlyasexplainedin(6).Also,makesureyouselecttheDirectMem
radiobuttonwhenenteringthefirstoperandvalue24oftheOUTinstruction:
L1:
OUT 24, 0
RET
10. Theabovesubroutinecodesimplydisplaysthetextstartingatdatamemory
location24andreturns(seeRETinstructioninappendix).Forittoworkthere
needstobesometextindataaddresslocation24.Youcandothismanuallyby
followingthestepsbelow:
ClickontheSHOWPROGRAMDATAMEMORYbutton(seeImage6).
Inthedisplayedwindowhighlighttheline0024underLAddcolumn
UnderInitialiseDataclickontheStringradiobutton
EntersometextinthetextboxlabelledValue,e.g.MynameisBesim
ClicktheUPDATEbutton
11. Now,asubroutineisofnousebyitself.Forittobeusefulyourprogrammustcall
itusingtheinstructionsMSFfollowedbyCAL(refertotheAppendix).TheMSF
(MarkStackFrame)isneededtoreserveaplaceforthereturnaddressonthe
programstack.TheCALinstructionneedstospecifythestartingaddressofthe
calledsubroutine.Letsmodifyourcodesothatwhentheabovesubroutineis
calleditdisplaysthetextrepeatedlyinaloop.Forexample,usingthecodeadded
in(6)and(9)themodifiedprogramshouldlooksomethinglikethis:
MOV
L0:
ADD
MSF
CAL
CMP
JNE
HLT
L1:
OUT
RET
#0, R01
#1, R01
$L1
#5, R01
$L0
24, 0
11
12. Theabovecodeisnowreadytorun.Inordertoseethedisplayedtextyouneed
toshowtheconsolewindow.ClickontheINPUTOUTPUTbutton(seeImage1)
whichwilldisplaythesimulatedconsolewindow.Torunthisprogram,followthe
instructionsbelow:
ClickontheRESETPROGRAMbutton
HighlighttheMOVinstruction,i.e.thefirstinstructionoftheprogram
Adjustthespeedslidertoavaluenearesttothevalue80
ClickontheRUNbutton
13. Weneedtomakeasmallchangetooursubroutine.CurrentlytheOUT
instructionusesdirectmemoryaddressing,i.e.thememoryaddress24ispartof
theinstruction.Wenowwishtomakeituseindirectaddressinginawaysimilar
tothatin(3).So,youllneedtoplacethememoryaddress24inaregister(any
spareregister).ThenyouneedtohavetheOUTinstructionusethisregister
indirectlyasthesourceoftheaddressofthetexttodisplay.Runthecodetotest
yourmodification.Makeanoteofthemodifiedpartoftheprogramcodebelow.
UsetheUNDObuttontorestoretheinstructionsbeforethismodification:
14. Ok,letsgetalittlebitmoreambitiousasachallenge.Letsconverttheloopinto
anothersubroutineandthencallit.So,nowwewillhavetwosubroutineswhere
onecallstheother.Thefollowingcoderepresentsthischange.Noticethatthe
HLTinstructionischangedtotheRETinstructionandthenewinstructionsMSF,
CALandHLTareaddedtogetherwiththenewlabelL2atthetopofthecode.
CAL$L2callsthesubroutinewiththeloopandCAL$L1callsthesubroutinethat
displaysthetext.
MSF
CAL $L2
HLT
L2:
MOV #0, R01
L0:
ADD #1, R01
MSF
CAL $L1
CMP #5, R01
JNE $L0
RET
L1:
OUT 24, 0
RET
Now,firstresettheprogramthenhighlightthefirstMSFinstruction.Runthe
programandverifytheresultintheconsolewindowasbefore.
12
15. Whystophere!Letsmakeitabitmoreinteresting.Theabovecodewilldothe
loop5timesandthisnumberisfixed.Forflexibilitywecanpassthenumberof
loopsasaparametertothesubroutine(startingatlabelL2).Forthiswewilluse
thePSHandPOPinstructions(seetheAppendix).Modifyyourcodetolooklike
theonebelowandrunitobservingthedisplaysontheconsole:
MSF
PSH
CAL
HLT
L2:
POP
MOV
L0:
ADD
MSF
CAL
CMP
JNE
RET
L1:
OUT
RET
#8
$L2
R02
#0, R01
#1, R01
$L1
R02, R01
$L0
24, 0
16. Examinetheabovecodeandbrieflyexplainhowtheparameterpassingworks:
17. Finally,asarealchallenge,modifytheabovecodesothatasecondparameteris
passedtothesubroutine(startingatlabelL2)inthesamewayasthefirst
parameterispassed.ThesecondparameterisusedtoinitialisetheregisterR01
tothevalueofthissecondparameter.Copythemodifiedcodeonlytothepoint
ofthelastmodificationintheboxbelow:
13
AppendixSimulatorInstructionSubset
Inst
Datatransferinstructions
MOV
LDB
LDW
STB
STW
PSH
POP
Description
Movedatatoregister;moveregistertoregister
e.g.
MOV#2,R01movesnumber2intoregisterR01
MOVR01,R03movescontentsofregisterR01intoregisterR03
Loadabytefrommemorytoregister
e.g.
LDB1022,R03loadsabytefrommemoryaddress1022intoR03
LDB@R02,R05loadsabytefrommemorytheaddressofwhichisinR02
Loadaword(2bytes)frommemorytoregister
SameasinLDBbutaword(i.e.2bytes)isloadedintoaregister
Storeabytefromregistertomemory
STBR07,2146storesabytefromR07intomemoryaddress2146
STBR04,@R08storesabytefromR04intomemoryaddressofwhichisin
R08
Storeaword(2bytes)fromregistertomemory
SameasinSTBbutaword(i.e.2bytes)isloadedstoredinmemory
Pushdatatotopofhardwarestack(TOS);pushregistertoTOS
e.g.
PSH#6pushesnumber6ontopofthestack
PSHR03pushesthecontentsofregisterR03ontopofthestack
Popdatafromtopofhardwarestacktoregister
e.g.
POPR05popscontentsoftopofstackintoregisterR05
Note:IfyoutrytoPOPfromanemptystackyouwillgettheerrormessage
Stackunderflow.
Arithmeticinstructions
ADD
Addnumbertoregister;addregistertoregister
e.g.
ADD#3,R02addsnumber3tocontentsofregisterR02andstoresthe
resultinregisterR02.
ADDR00,R01addscontentsofregisterR00tocontentsofregisterR01
andstorestheresultinregisterR01.
SUB
Subtractnumberfromregister;subtractregisterfromregister
MUL
Multiplynumberwithregister;multiplyregisterwithregister
DIV
Dividenumberwithregister;divideregisterwithregister
Controltransferinstructions
JMP
Jumptoinstructionaddressunconditionally
e.g.
JMP100unconditionallyjumpstoaddresslocation100wherethereis
anotherinstruction
14
JLT
Jumptoinstructionaddressiflessthan(afterlastcomparison)
JGT
Jumptoinstructionaddressifgreaterthan(afterlastcomparison)
JEQ
Jumptoinstructionaddressifequal(afterlastcomparisoninstruction)
e.g.
JEQ200jumpstoaddresslocation200ifthepreviouscomparison
instructionresultindicatesthatthetwonumbersareequal,i.e.theZ
statusflagisset(theZboxwillbecheckedinthiscase).
JNE
Jumptoinstructionaddressifnotequal(afterlastcomparison)
MSF
CAL
MarkStackFrameinstructionisusedinconjunctionwiththeCAL
instruction.
e.g.
MSFreserveaspaceforthereturnaddressonprogramstack
CAL1456savethereturnaddressinthereservedspaceandjumpto
subroutineinaddresslocation1456
Jumptosubroutineaddress(savesthereturnaddressonprogramstack)
ThisinstructionisusedinconjunctionwiththeMSFinstruction.Youll
needanMSFinstructionbeforetheCALinstruction.Seetheexample
above
RET
Returnfromsubroutine(usesthereturnaddressonstack)
SWI
Softwareinterrupt(usedtorequestOShelp)
HLT
Haltsimulation
Comparisoninstruction
CMP
Comparenumberwithregister;compareregisterwithregister
e.g.
CMP#5,R02comparenumber5withthecontentsofregisterR02
CMPR01,R03comparethecontentsofregistersR01andR03
Note:
IfR01=R03thenthestatusflagZwillbeset,i.e.theZboxischecked.
IfR03>R01thennonofthestatusflagswillbeset,i.e.noneofthestatus
flagboxesarechecked.
IfR01>R03thenthestatusflagNwillbeset,i.e.theNstatusboxis
checked.
Input,outputinstructions
IN
Getinputdata(ifavailable)fromanexternalIOdevice
OUT
OutputdatatoanexternalIOdevice
e.g.
OUT16,0outputscontentsofdatainlocation16totheconsole(the
secondparametermustalwaysbea0)
15