CS 61C: Great Ideas in Computer Architecturecs61c/fa16/lec/06/L06.pdf · 2016. 9. 15. · •...
Transcript of CS 61C: Great Ideas in Computer Architecturecs61c/fa16/lec/06/L06.pdf · 2016. 9. 15. · •...
CS61C:GreatIdeasinComputerArchitecture
MoreMIPS InstructionsandHowtoImplementFunctions
Instructors:BernhardBoser andRandyH.Katz
http://inst.eecs.Berkeley.edu/~cs61c/fa16
9/14/16 Fall2016- Lecture#6 1
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 2
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 3
LevelsofRepresentation/Interpretation
lw $t0,0($2)lw $t1,4($2)sw $t1,0($2)sw $t0,4($2)
HighLevelLanguageProgram(e.g.,C)
AssemblyLanguageProgram(e.g.,MIPS)
MachineLanguageProgram(MIPS)
HardwareArchitectureDescription(e.g.,blockdiagrams)
Compiler
Assembler
MachineInterpretation
temp=v[k];v[k]=v[k+1];v[k+1]=temp;
0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
ArchitectureImplementation
Anythingcanberepresentedasanumber,
i.e.,dataorinstructions
LogicCircuitDescription(CircuitSchematicDiagrams)
9/14/16 Fall2016- Lecture#6 4
ReviewFromLastLecture…• Computer“words”and“vocabulary”arecalledinstructions andinstructionsetrespectively
• MIPSisexampleRISCinstructionsetusedinCS61C• Rigidformat:oneoperation,twosourceoperands,onedestination– add,sub,mul,div,and,or,sll,srl,sra– lw,sw,lb,sb tomovedatato/fromregistersfrom/tomemory
– beq, bne, j, slt, slti fordecision/flowcontrol• Simplemappingsfromarithmeticexpressions,arrayaccess,inCtoMIPSinstructions
9/14/16 Fall2016- Lecture#6 5
Processor
Control
Datapath
Review:ComponentsofaComputer
ProgramCounter
Registers
Arithmetic&LogicUnit(ALU)
MemoryInput
Output
Bytes
Enable?Read/Write
Address
WriteData
ReadData
Processor-Memory Interface I/O-MemoryInterfaces
Program
Data
9/14/16 Fall2016- Lecture#6 6
Reviewif-else Statement
• Assumingtranslationsbelow,compilef →$s0 g →$s1 h →$s2i →$s3 j →$s4
if (i == j) bne $s3,$s4,Else
f = g + h; add $s0,$s1,$s2
else j Exit
f = g – h; Else: sub $s0,$s1,$s2
Exit: 9/14/16 Fall2016- Lecture#6 7
Control-flowGraphs:AVisualization
8
bne $s3,$s4,Else
add $s0,$s1,$s2 j Exit
Else:sub $s0,$s1,$s2Exit:
bne $s3,$s4,Else
add$s0,$s1,$s2jExit
Else:sub$s0,$s1,$s2
Exit:…9/14/16 Fall2016- Lecture#6
Review:LoopsinC/Assembly• SimpleloopinC;A[] isanarrayofints
do { g = g + A[i];i = i + j;
} while (i != h);• Usethismapping: g, h,i,j,&A[0]
$s1,$s2,$s3,$s4,$s5
Loop:sll $t1,$s3,2 # $t1= 4*iaddu $t1,$t1,$s5 # $t1=addr A+4ilw $t1,0($t1) # $t1=A[i]add $s1,$s1,$t1 # g=g+A[i]addu $s3,$s3,$s4 # i=i+jbne $s3,$s2,Loop # goto Loop
# if i!=h9/14/16 Fall2016- Lecture#6 9
Clicker/PeerInstruction
• WhichofthefollowingisTRUE?A:add $t0,$t1,4($t2)isvalidMIPSB:canbyteaddress8GBwithaMIPSwordC:immmustbemultipleof4forlw $t0,imm($s0) tobevalid
D:IfMIPShalvedthenumberofregistersavailable,itwouldbetwiceasfast
E:Noneoftheabove
9/14/16 Fall2016- Lecture#6 10
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 11
HowProgramisStoredMemory
Bytes
Program
Data
OneMIPSInstruction=32bits
9/14/16 Fall2016- Lecture#6 12
AssemblertoMachineCode(morelaterincourse)
foo.S bar.S
Assembler Assembler
foo.o bar.o
Linker lib.o
a.out
Assemblersourcefiles(text)
Machinecodeobjectfiles
Pre-builtobjectfilelibraries
Machinecodeexecutablefile
Assemblerconvertshuman-readableassemblycodetoinstructionbitpatterns
9/14/16 Fall2016- Lecture#6 13
Processor
Control
Datapath
ProgramExecution
PC
Registers
Arithmetic&LogicUnit(ALU)
Memory
BytesInstructionAddress
ReadInstructionBits
Program
Data
• PC (programcounter) isinternalregisterinsideprocessorholding byte addressofnextinstruction tobeexecuted
• Instructionisfetchedfrommemory, thencontrolunitexecutesinstructionusingdatapath andmemorysystem,andupdatesprogramcounter(defaultisadd+4bytestoPC,tomovetonextsequential instruction)
9/14/16 Fall2016- Lecture#6 14
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 15
SixFundamentalStepsinCallingaFunction
1. Putparametersinaplacewherefunctioncanaccessthem
2. Transfercontroltofunction3. Acquire(local)storageresourcesneededfor
function4. Performdesiredtaskofthefunction5. Putresultvalueinaplacewherecallingcode
canaccessitandrestoreanyregistersyouused6. Returncontroltopointoforigin,sincea
functioncanbecalledfromseveralpointsinaprogram
9/14/16 Fall2016- Lecture#6 16
MIPSFunctionCallConventions
• Registersfasterthanmemory,sousethem• $a0–$a3:fourargumentregisterstopassparameters($4- $7)
• $v0,$v1:twovalueregisterstoreturnvalues($2,$3)
• $ra:onereturnaddressregistertoreturntothepointoforigin($31)
9/14/16 Fall2016- Lecture#6 17
InstructionSupportforFunctions(1/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;}address (shown in decimal)1000 1004 1008 1012 1016 …2000 2004
C
MIPS
InMIPS,allinstructionsare4bytes,andstoredinmemoryjustlikedata.Sohereweshowtheaddressesofwheretheprogramsarestored.
9/14/16 Fall2016- Lecture#6 18
InstructionSupportforFunctions(2/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;}address (shown in decimal)1000 add $a0,$s0,$zero # x = a1004 add $a1,$s1,$zero # y = b1008 addi $ra,$zero,1016 #$ra=10161012 j sum #jump to sum1016 … # next instruction…2000 sum: add $v0,$a0,$a12004 jr $ra # new instr. “jump register”
C
MIPS
9/14/16 Fall2016- Lecture#6 19
InstructionSupportforFunctions(3/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;}
2000 sum: add $v0,$a0,$a12004 jr $ra # new instr. “jump register”
• Question:Whyuse jr here?Whynot usej?
• Answer:summightbecalledbymanyplaces,sowecan’treturntoafixedplace.Thecallingproctosummustbeabletosay“returnhere”somehow.
C
MIPS
9/14/16 Fall2016- Lecture#6 20
InstructionSupportforFunctions(4/4)
• Singleinstructiontojumpandsavereturnaddress:jumpandlink(jal)
• Before:1008 addi $ra,$zero,1016 #$ra=10161012 j sum #goto sum
• After:1008 jal sum # $ra=1012,goto sum
• Whyhaveajal?– Makethecommoncasefast:functioncalls verycommon.– Don’thavetoknowwhere codeis inmemorywithjal!
9/14/16 Fall2016- Lecture#6 21
Break!
9/14/16 Fall2016- Lecture#6 22
MIPSFunctionCallInstructions• Invokefunction:jumpandlinkinstruction(jal)
(reallyshouldbelaj “linkandjump”)– “link”meansformanaddressorlinkthatpointstocallingsitetoallowfunctiontoreturntoproperaddress
– Jumpstoaddressandsimultaneouslysavestheaddressofthefollowing instructioninregister$rajal FunctionLabel
• Returnfromfunction:jumpregisterinstruction(jr)– Unconditionaljumptoaddressspecifiedinregisterjr $ra
9/14/16 Fall2016- Lecture#6 23
NotesonFunctions• Callingprogram(caller)putsparametersintoregisters$a0-$a3 andusesjal X toinvoke(callee)ataddresslabeledX
• Musthaveregisterincomputerwithaddressofcurrentlyexecutinginstruction– InsteadofInstructionAddressRegister (bettername),historicallycalledProgramCounter (PC)
– It’saprogram’scounter;itdoesn’tcountprograms!
• Whatvaluedoesjal X placeinto$ra?
9/14/16 Fall2016- Lecture#6 24
NotesonFunctions• Callingprogram(caller)putsparametersintoregisters$a0-$a3 andusesjal X toinvoke(callee)ataddresslabeledX
• Musthaveregisterincomputerwithaddressofcurrentlyexecutinginstruction– InsteadofInstructionAddressRegister (bettername),historicallycalledProgramCounter (PC)
– It’saprogram’scounter;itdoesn’tcountprograms!
• Whatvaluedoesjal X placeinto$ra?• jr $ra putsaddressinside$ra backintoPC9/14/16 Fall2016- Lecture#6 25
WhereAreOldRegisterValuesSavedtoRestoreThemAfterFunctionCall?• Needaplacetosaveoldvaluesbeforecallfunction,restorethemwhenreturn,anddelete
• Idealisstack:last-in-first-outqueue(e.g.,stackofplates)– Push:placingdataontostack– Pop:removingdatafromstack
• Stackinmemory,soneedregistertopointtoit• $sp isthestackpointerinMIPS($29)• Conventionisgrowfromhightolowaddresses– Push decrements$sp,Pop increments$sp
9/14/16 Fall2016- Lecture#6 26
Administrivia
• Project#1isout!• C-basedguerrillasessionsstartingsoon• TwoweekstoMidterm#1!
9/14/16 Fall2016- Lecture#6 27
9/14/16 Fall2016- Lecture#6 28
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 29
Exampleint Leaf(int g, int h, int i, int j)
{int f;f = (g + h) – (i + j);return f;
}• Parametervariablesg,h,i,andj inargumentregisters$a0,$a1,$a2,and$a3,andf in$s0
• Assumeneedonetemporaryregister$t0
9/14/16 Fall2016- Lecture#6 30
StackBefore,During,AfterFunction
• Needtosaveoldvaluesof$s0 and$t0
Contentsof$s0Contentsof$t0
9/14/16 Fall2016- Lecture#6 31
MIPSCodeforLeaf()Leaf: addi $sp,$sp,-8 # adjuststackfor2items
sw $t0, 4($sp) # save$t0foruseafterwardssw $s0, 0($sp) # save$s0foruseafterwards
add $s0,$a0,$a1 # f=g+hadd $t0,$a2,$a3 # t0=i +jsub $v0,$s0,$t0 # returnvalue(g+h)– (i +j)
lw $s0, 0($sp) # restoreregister$s0forcallerlw $t0, 4($sp) # restoreregister$t0forcalleraddi $sp,$sp,8 # adjuststacktodelete2itemsjr $ra # jumpbacktocallingroutine
9/14/16 Fall2016- Lecture#6 32
WhatIfaFunctionCallsaFunction?RecursiveFunctionCalls?
• Wouldclobbervaluesin$a0 to$a3 and$ra• Whatisthesolution?
9/14/16 Fall2016- Lecture#6 33
NestedProcedures(1/2)int sumSquare(int x, int y) {return mult(x,x)+ y;}
• SomethingcalledsumSquare,nowsumSquare iscallingmult
• Sothere’savaluein$ra thatsumSquarewantstojumpbackto,butthiswillbeoverwrittenbythecalltomult
NeedtosavesumSquare returnaddressbeforecalltomult
9/14/16 Fall2016- Lecture#6 34
NestedProcedures(2/2)
• Ingeneral,mayneedtosavesomeotherinfoinadditionto$ra.
• WhenaCprogramisrun,therearethreeimportantmemoryareasallocated:– Static:Variablesdeclaredonceperprogram,ceasetoexistonlyafterexecutioncompletes- e.g.,Cglobals
– Heap:Variablesdeclareddynamicallyviamalloc– Stack:Spacetobeusedbyprocedureduringexecution;thisiswherewecansaveregistervalues
359/14/16 Fall2016- Lecture#6
OptimizedFunctionConventionToreduceexpensiveloadsandstoresfromspillingandrestoringregisters,MIPSdividesregistersintotwocategories:
1. Preservedacrossfunctioncall– Callercanrelyonvaluesbeingunchanged– $sp,$gp,$fp,“savedregisters”$s0- $s7
2. Notpreservedacrossfunctioncall– Callercannotrelyonvaluesbeingunchanged– Returnvalueregisters$v0,$v1,Argumentregisters
$a0-$a3,“temporaryregisters”$t0-$t9,$ra9/14/16 Fall2016- Lecture#6 36
Clickers/PeerInstruction
• WhichstatementisFALSE?
B: jal savesPC+1in$ra
C: Thecallee canusetemporaryregisters($ti)withoutsavingandrestoringthem
D: Thecallercanrelyonsaveregisters($si)withoutfearofcallee changingthem
A:MIPSusesjal toinvokeafunctionandjr toreturnfromafunction
9/14/16 Fall2016- Lecture#6 37
Break!
9/14/16 Fall2016- Lecture#6 38
AllocatingSpaceonStack• Chastwostorageclasses:automaticandstatic– Automatic variablesarelocaltofunctionanddiscardedwhenfunctionexits
– Staticvariablesexistacrossexitsfromandentriestoprocedures
• Usestackforautomatic(local)variablesthatdon’tfitinregisters
• Procedure frameor activationrecord:segmentofstackwithsavedregistersandlocalvariables
• SomeMIPScompilersuseaframepointer($fp)topointtofirstwordofframe
9/14/16 Fall2016- Lecture#6 39
StackBefore,During,AfterCall
9/14/16 Fall2016- Lecture#6 40
UsingtheStack(1/2)• Sowehavearegister$sp whichalwayspointstothelastusedspaceinthestack
• Tousestack,wedecrementthispointerbytheamountofspaceweneedandthenfillitwithinfo
• So,howdowecompilethis?int sumSquare(int x, int y) {
return mult(x,x)+ y;}
9/14/16 Fall2016- Lecture#6 41
UsingtheStack(2/2)• Hand-compilesumSquare:
addi $sp,$sp,-8 # space on stacksw $ra, 4($sp) # save ret addrsw $a1, 0($sp) # save yadd $a1,$a0,$zero # mult(x,x)jal mult # call multlw $a1, 0($sp) # restore yadd $v0,$v0,$a1 # mult()+ylw $ra, 4($sp) # get ret addraddi $sp,$sp,8 # restore stackjr $ra
mult: ...
int sumSquare(int x, int y) {return mult(x,x)+ y; }
“push”
“pop”
9/14/16 Fall2016- Lecture#6 42
BasicStructureofaFunction
entry_label: addi $sp,$sp, -framesizesw $ra, framesize-4($sp) # save $rasave other regs if need be
...
restore other regs if need belw $ra, framesize-4($sp) # restore $raaddi $sp,$sp, framesizejr $ra
Epilogue
Prologue
Body (call other functions…)
ra
memory
9/14/16 Fall2016- Lecture#6 43
WhereistheStackinMemory?• MIPSconvention• Stackstartsinhighmemoryandgrowsdown– Hexadecimal(base16):7ffffffchex
• MIPSprograms(textsegment)inlowend– 00400000hex
• staticdatasegment(constantsandotherstaticvariables)abovetextforstaticvariables– MIPSconventionglobalpointer($gp)pointstostatic
• Heapabovestaticfordatastructuresthatgrowandshrink;growsuptohighaddresses
9/14/16 Fall2016- Lecture#6 44
MIPSMemoryAllocation
9/14/16 Fall2016- Lecture#6 45
RegisterAllocationandNumbering
9/14/16 Fall2016- Lecture#6 46
Outline
• MIPSISAandC-to-MIPSReview• ProgramExecutionOverview• FunctionCall• FunctionCallExample• AndinConclusion…
9/14/16 Fall2016- Lecture#6 47
AndinConclusion…• Functionscalledwithjal,returnwithjr $ra.• Thestackisyourfriend:Useittosaveanythingyouneed.
Just leaveitthewayyoufoundit!• Instructionsweknowsofar…
Arithmetic:add, addi, sub, addu, addiu, subuMemory: lw, sw, lb, sbDecision:beq, bne, slt, slti, sltu, sltiuUnconditionalBranches(Jumps):j, jal, jr
• Registersweknowsofar– Allofthem!– $a0-$a3forfunctionarguments,$v0-$v1forreturnvalues– $sp,stackpointer,$fp framepointer,$ra returnaddress
489/14/16 Fall2016- Lecture#6