function calling conventions 1 - github pages
TRANSCRIPT
FunctionCallingConventions1
CS64:ComputerOrganizationandDesignLogicLecture#9
ZiadMatni
Dept.ofComputerScience,UCSB
LectureOutline
• MoreonMIPSCallingConvention
– Functionscallingfunctions
– Theroleoftheconventionandhowtouseit
5/3/18 Matni,CS64,Sp18 2
MIPSCallingConventions
• Whatwearetalkingabouttodayandthenextlecture
• You*must*readthehandoutonMIPSCallingConventions– Foundonourwebpage
5/3/18 Matni,CS64,Sp18 3
AnyQuestionsFromLastLecture?
5/3/18 Matni,CS64,Sp18 4
CallingFunctionsonMIPS
• Twocrucialinstructions:jalandjr• Onespecializedregister:$ra
• jal(jump-and-link)– Simultaneouslyjumptoanaddress,andstorethelocationof
thenextinstructioninregister$ra
• jr(jump-register)– Jumptotheaddressstoredinaregister,often$ra
5/3/18 Matni,CS64,Sp18 5
PassingandReturningValuesinMIPS
• Registers$a0thru$a3– Argumentregisters,forpassingfunctionarguments
• Registers$v0and$v1– Returnregisters,forpassingreturnvalues
5/3/18 Matni,CS64,Sp18 6
FunctionCallsWithinFunctions…
Givenwhatwe’vesaidsofar…• Whataboutthiscodemakesourpreviouslydiscussedsetupbreak?– Youwouldneed
multiplecopiesof$ra
5/3/18 Matni,CS64,Sp18 7
• You’dhavetocopythevalueof$ratoanotherregister(ortomem)beforecallinganotherfunction
• Danger:Youcouldrunoutofregisters!
AnotherExample…
Whataboutthiscodemakesthissetupbreak?• Can’tfitallvariablesinregistersatthesametime!
• HowdoIknowwhichregistersareevenusablewithoutlookingatthecode?
5/3/18 Matni,CS64,Sp18 8
Solution??!!
• Storecertaininformationinmemoryonlyatcertaintimes
• Ultimately,thisiswherethecallstackcomesfrom
• Sowhat(registers/memory)savewhat???
5/3/18 Matni,CS64,Sp18 9
WhatSavesWhat?• ByMIPSconvention,certainregistersaredesignatedtobepreservedacrossacall
• Preservedregistersaresavedbythefunctioncalled(e.g.,$s0-$s7)– Sothesearesavedatthestartofeveryfunction
• Non-preservedregistersaresavedbythecallerofthefunction(e.g.,$t0-$t9)– Sothesearesavedbythefunction’scaller– Ornot…(theycanbeignoredundercertaincircumstances)
5/3/18 Matni,CS64,Sp18 10
AndWhereisitSaved?
• Registervaluesaresavedonthestack
• Thetopofthestackisheldin$sp(stackpointer)
• Thestackgrowsfromhighaddressestolowaddresses
5/3/18 Matni,CS64,Sp18 11
TheStack
Whenaprogramstartsexecuting,acertaincontiguoussectionofmemoryissetasidefortheprogramcalledthestack.
5/3/18 Matni,CS64,Sp18 12
TheStack• Thestackpointerisaregister($sp)thatcontainsthetopofthestack.
• $spcontainsthesmallestaddressxsuchthatanyaddresssmallerthanxisconsideredgarbage,andanyaddressgreaterthanorequaltoxisconsideredvalid.
5/3/18 Matni,CS64,Sp18 13
TheStack
• Inthisexample,$spcontainsthevalue0x00001000.
• Theshadedregionofthediagramrepresentsvalidpartsofthestack.
5/3/18 Matni,CS64,Sp18 14
TheStack• StackBottom:The
largestvalidaddressofastack.
• Whenastackisinitialized,$sppointstothestackbottom.
• StackLimit:Thesmallestvalidaddressofastack.
• If$spgetssmallerthanthis,thenthere'sastackoverflow
5/3/18 Matni,CS64,Sp18 15
5/3/18 Matni,CS64,Sp18 16
STACK(LIFO)PUSHANDPOP
StackPushandPop
• PUSHoneormoreregisters– Subtract4timesthenumber
ofregisterstobepushed onthestackpointer• Why????
– Copytheregisterstothestack(doaswinstruction)Example:addi$sp,$sp,-8#2registerstosavesw$s0,4($sp)sw$s1,0($sp)
5/3/18 Matni,CS64,Sp18 17
StackPushandPop
• POPoneormoreregisters– Reverseprocessfrompush– Copythedatafromthestacktotheregisters(doalwinstruction)
– Add4timesthenumberofregisters tobepoppedonthestack.
Example:lw$s0,4($sp)lw$s1,0($sp)addi$sp,$sp,8#2registerstorestore#Note:youcannotdotheaddifirst
5/3/18 Matni,CS64,Sp18 18
save_registers.asm• Theprogramwilllookat2integers(a0,a1)andultimately
returns(a0+a0)+(a1+a1)viaafunctioncall(i.e.jal)
• Thefunctionwillfirstcreateroomfor2wordsonthestack– Itwillpush$s0&$s1ontothestack– We’lluse$s0and$s1
b/cwewantthemtobepreservedacrossacall
• Itwillcalculatethereturnedvalueandputtheresultin$v0
• Wewillthenrestoretheoriginalregisters– Itwillpop2wordsfromthestack&placethemin$s0&$s1
5/3/18 Matni,CS64,Sp18 19
.datasolution_text:.asciiz"Solution:"saved_text:.asciiz"Saved:”newline:.asciiz"\n”.text#$a0:firstinteger#$a1:secondinteger#Returns($a0+$a0)+($a1+$a1)in$v0.#Uses$s0and$s1aspartofthisprocessbecausethesearepreservedacrossacall.#add_intsmustthereforesavetheirvaluesinternallyusingthestack.add_ints:#save$s0and$s1onthestack(i.e.push)addi$sp,$sp,-8#makeroomfortwowordssw$s0,4($sp)#notethenon-zerooffsetsw$s1,0($sp)#calculatethevalueadd$s0,$a0,$a0add$s1,$a1,$a1add$v0,$s0,$s1#because$t0isassumedtonotbepreserved,wecanmodifyitdirectly(anditwillnotmatterb/cwe’llpopthesaved$t0outofthestacklater)li$t0,4242#restoretheregistersandreturn(i.e.pop)lw$s1,0($sp)lw$s0,4($sp)addi$sp,$sp,8jr$ra
save_registers.asm
Matni,CS64,Sp18 20
main:#We“happen”tohavethevalue1in$t0and2in$s0inthisexample#$t0and$s0areindependentofthefunction…
li$t0,1li$s0,2
#Wewanttocalladd_ints.Becausewewanttosavethevalueof$t0,inthiscase,#andbecauseit'snotpreservedacrossacall(wecan’tassumeitwillbe),itisour#(thecaller’s)responsibilitytostoreitonthestackandrestoreitafterwardsaddi$sp,$sp,-4
sw$t0,0($sp)
#setupthefunctioncallandmakeitli$a0,3li$a1,7jaladd_ints
#restore$t0–also,wecan“assume”that$s0stillhasthevalue2init#becausetheCCsaysthefunctionhastopreserve$sregisterslw$t0,0($sp)addi$sp,$sp,4
#printoutthesolutionpromptmove$t1,$v0li$v0,4la$a0,solution_textsyscall
#printoutthesolutionitselfli$v0,1move$a0,$t1syscall
#printoutanewlineandend(notshown)la$a0,newlineli$v0,4syscall
save_registers.asm
5/3/18 21
#saving$t0isthecaller’sresponsibility,$s0isthecallee’s…
WhatisaCallingConvention?• It’saprotocolabouthowyoucallfunctions
andhowyouaresupposedtoreturnfromthem
• EveryCPUarchitecturehasone– Theycandifferfromonearch.toanother
• 3Reasonswhywecare:– Becauseitmakesprogrammingaloteasierifeveryoneagreestothe
sameconsistent(i.e.reliable)methods– Makestestingawholeloteasier– Iwillaskyoutouseitinassignmentsandinexams!
• Andyouloosemajorpoints(orallofthem)ifyoudon’t…
5/3/18 Matni,CS64,Sp18 22
Moreonthe“Why”• Haveawayofimplementingfunctionsinassembly
– Butnotaclear,easy-to-usewaytodocomplexfunctions
• InMIPS,wedonothaveaninherentwayofdoingnested/recursivefunctions– Example:Savinganarbitraryamountofvariables– Example:Jumpingbacktoaplaceincoderecursively
• Thereismorethanonewaytodothings– Butweoftenneedaconventiontosetworkingparameters– Helpsfacilitatethingsliketestingandinter-compatibility– ThisispartlywhyMIPShasdifferentregistersfordifferentuses
5/3/18 Matni,CS64,Sp18 23
InstructionstoWatchOutFor• jal<label>andjar$raalwaysgotogether
• FunctionargumentshavetobestoredONLYin$a0thru$a3
• FunctionreturnvalueshavetobestoredONLYin$v0and$v1
• Iffunctionsneedadditionalregisterswhosevalueswedon’tcareaboutkeepingafterthecall,thentheycanuse$t0thru$t9
• Whatabout$sregisters?AKAthepreservedregisters– Hanginthere…willtalkabouttheminafewslides…
5/3/18 Matni,CS64,Sp18 24
MIPSC.C.forCS64:Assumptions• Wewillnotutilize$fpand$gpregs
– $fp:framepointer– $gp:globalpointer
• Assumethatfunctionswillnottakemorethan4argumentsandwillnotreturnmorethan2arguments– Makesourlivesalittlesimpler…
• Assumethatallvaluesonthestackarealways32-bits– Thatis,nooverlylongdatatypesorcomplexdatastructureslike
C-Structs,Classes,etc…
5/3/18 Matni,CS64,Sp18 25
MIPSCallStack• WeknowwhataStackis…• A“CallStack”isusedforstoringthereturnaddressesofthevarious
functionswhichhavebeencalled
• Whenyoucallafunction(e.g.jalfuncA),theaddressthatweneedtoreturntoispushedintothecallstack.
…funcAdoesitsthing…then…
…Thefunctionneedstoreturn.
So,theaddressispoppedoffthecallstack
5/3/18 Matni,CS64,Sp18 26
MIPSCallStack
5/3/18 Matni,CS64,Sp18 27
TopoftheStackAddressofwheresecondshould
returnto(i.e.after“jalsecond”)
fourth:jr$rathird:push$rajalfourthpop$rajr$rasecond:push$rajalthirdpop$rajr$rafirst:jalsecondli$v0,10syscal
Addressofwheresecondshould
returnto(i.e.after“jalsecond”)
Addressofwherethirdshould
returnto(i.e.after“jalthird”)
voidfirst(){second()return;}
voidsecond(){third();return;}
voidthird(){fourth();return;}
voidforth(){return;}
PUSH
POP
5/3/18 Matni,CS64,Sp18 28
fourth:jr$rathird:addiu$sp,$sp,-4sw$ra,0($sp)jalfourthlw$ra,0($sp)addiu$sp,$sp,4jr$rasecond:addiu$sp,$sp,-4sw$ra,0($sp)jalthirdlw$ra,0($sp)addiu$sp,$sp,4jr$rafirst:jalsecondli$v0,10syscall
fourth:jr$rathird:push$rajalfourthpop$rajr$rasecond:push$rajalthirdpop$rajr$rafirst:jalsecondli$v0,10syscal
Whyaddiu?Becausethereisnosuchthingas
anegativememoryaddress
ANDwewanttoavoid
triggeringaprocessor-levelexceptiononoverflow
YOURTO-DOs
• MakesureyoureadthehandoutonMIPSCallingConventions
• Finishassignment/Lab#4– AssignmentdueonFRIDAY
• PrepforLab#5onMonday
5/3/18 Matni,CS64,Sp18 29
5/3/18 Matni,CS64,Sp18 30