book.tex 416 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,while,begin},
  76. deletekeywords={read,mapping},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. (In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency.) Dybvig, with later help from his students Dipanwita
  170. Sarkar and Andrew Keep, developed infrastructure to support this
  171. approach and evolved the course, first to use smaller micro-passes and
  172. then into even smaller
  173. nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student in this
  174. compiler course in the early 2000's as part of his Ph.D. studies at
  175. Indiana University. Needless to say, I enjoyed the course immensely!
  176. During that time, another graduate student named Abdulaziz Ghuloum
  177. observed that the front-to-back organization of the course made it
  178. difficult for students to understand the rationale for the compiler
  179. design. Ghuloum proposed an incremental approach in which the students
  180. build the compiler in stages; they start by implementing a complete
  181. compiler for a very small subset of the input language and in each
  182. subsequent stage they add a language feature and add or modify passes
  183. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  184. students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, I was able to teach much of the
  192. same content from the Indiana compiler course. I very much enjoyed
  193. teaching the course organized in this way, and even better, many of
  194. the students learned a lot and got excited about compilers.
  195. I returned to teach at Indiana University in 2013. In my absence the
  196. compiler course had switched from the front-to-back organization to a
  197. back-to-front organization. Seeing how well the incremental approach
  198. worked at Colorado, I started porting and adapting the structure of
  199. the Colorado course back into the land of Scheme. In the meantime
  200. Indiana University had moved on from Scheme to Racket, so the course
  201. is now about compiling a subset of Racket (and Typed Racket) to the
  202. x86 assembly language. The compiler is implemented in
  203. Racket~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book I
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study compilers at Indiana University. Many of
  209. the compiler design decisions in this book are drawn from the
  210. assignment descriptions of \cite{Dybvig:2010aa}. I have captured what
  211. I think are the most important topics from \cite{Dybvig:2010aa} but
  212. have omitted topics that are less interesting conceptually. I have
  213. also made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we I the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  226. It is helpful but not necessary for the student to have prior exposure
  227. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  228. from a computer systems
  229. course~\citep{Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %
  232. We follow the System V calling
  233. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  234. assembly code that we generate will work properly with our runtime
  235. system (written in C) when it is compiled using the GNU C compiler
  236. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  237. adjustments are needed for MacOS which we note as they arise.)
  238. %
  239. When running on the Microsoft Windows operating system, the GNU C
  240. compiler follows the Microsoft x64 calling
  241. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  242. code that we generate will \emph{not} work properly with our runtime
  243. system on Windows. One option to consider for using a Windows computer
  244. is to run a virtual machine with Linux as the guest operating system.
  245. %\section*{Structure of book}
  246. % You might want to add short description about each chapter in this book.
  247. %\section*{About the companion website}
  248. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  249. %\begin{itemize}
  250. % \item A link to (freely downlodable) latest version of this document.
  251. % \item Link to download LaTeX source for this document.
  252. % \item Miscellaneous material (e.g. suggested readings etc).
  253. %\end{itemize}
  254. \section*{Acknowledgments}
  255. Many people have contributed to the ideas, techniques, and
  256. organization of this book and have taught courses based on it. We
  257. especially thank John Clements, Bor-Yuh Evan Chang, Kent Dybvig,
  258. Daniel P. Friedman, Ronald Garcia, Abdulaziz Ghuloum, Andrew Keep, Jay
  259. McCarthy, Nate Nystrom, Dipanwita Sarkar, Oscar Waddell, and Michael
  260. Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.
  276. \index{concrete syntax}
  277. \index{abstract syntax}
  278. \index{abstract syntax tree}
  279. \index{AST}
  280. \index{program}
  281. \index{parse}
  282. %
  283. The translation from concrete syntax to abstract syntax is a process
  284. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  285. and implementation of parsing in this book. A parser is provided in
  286. the supporting materials for translating from concrete syntax to
  287. abstract syntax for the languages used in this book.
  288. ASTs can be represented in many different ways inside the compiler,
  289. depending on the programming language used to write the compiler.
  290. %
  291. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  292. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  293. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  294. and pattern matching to inspect individual nodes in an AST
  295. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  296. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  297. chapter provides an brief introduction to these ideas.
  298. \index{struct}
  299. \section{Abstract Syntax Trees and Racket Structures}
  300. \label{sec:ast}
  301. Compilers use abstract syntax trees to represent programs because
  302. compilers often need to ask questions like: for a given part of a
  303. program, what kind of language feature is it? What are the sub-parts
  304. of this part of the program? Consider the program on the left and its
  305. AST on the right. This program is an addition and it has two
  306. sub-parts, a read operation and a negation. The negation has another
  307. sub-part, the integer constant \code{8}. By using a tree to represent
  308. the program, we can easily follow the links to go from one part of a
  309. program to its sub-parts.
  310. \begin{center}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{lstlisting}
  313. (+ (read) (- 8))
  314. \end{lstlisting}
  315. \end{minipage}
  316. \begin{minipage}{0.4\textwidth}
  317. \begin{equation}
  318. \begin{tikzpicture}
  319. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  320. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  321. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  322. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  323. \draw[->] (plus) to (read);
  324. \draw[->] (plus) to (minus);
  325. \draw[->] (minus) to (8);
  326. \end{tikzpicture}
  327. \label{eq:arith-prog}
  328. \end{equation}
  329. \end{minipage}
  330. \end{center}
  331. We use the standard terminology for trees to describe ASTs: each
  332. circle above is called a \emph{node}. The arrows connect a node to its
  333. \emph{children} (which are also nodes). The top-most node is the
  334. \emph{root}. Every node except for the root has a \emph{parent} (the
  335. node it is the child of). If a node has no children, it is a
  336. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  337. \index{node}
  338. \index{children}
  339. \index{root}
  340. \index{parent}
  341. \index{leaf}
  342. \index{internal node}
  343. %% Recall that an \emph{symbolic expression} (S-expression) is either
  344. %% \begin{enumerate}
  345. %% \item an atom, or
  346. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  347. %% where $e_1$ and $e_2$ are each an S-expression.
  348. %% \end{enumerate}
  349. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  350. %% null value \code{'()}, etc. We can create an S-expression in Racket
  351. %% simply by writing a backquote (called a quasi-quote in Racket)
  352. %% followed by the textual representation of the S-expression. It is
  353. %% quite common to use S-expressions to represent a list, such as $a, b
  354. %% ,c$ in the following way:
  355. %% \begin{lstlisting}
  356. %% `(a . (b . (c . ())))
  357. %% \end{lstlisting}
  358. %% Each element of the list is in the first slot of a pair, and the
  359. %% second slot is either the rest of the list or the null value, to mark
  360. %% the end of the list. Such lists are so common that Racket provides
  361. %% special notation for them that removes the need for the periods
  362. %% and so many parenthesis:
  363. %% \begin{lstlisting}
  364. %% `(a b c)
  365. %% \end{lstlisting}
  366. %% The following expression creates an S-expression that represents AST
  367. %% \eqref{eq:arith-prog}.
  368. %% \begin{lstlisting}
  369. %% `(+ (read) (- 8))
  370. %% \end{lstlisting}
  371. %% When using S-expressions to represent ASTs, the convention is to
  372. %% represent each AST node as a list and to put the operation symbol at
  373. %% the front of the list. The rest of the list contains the children. So
  374. %% in the above case, the root AST node has operation \code{`+} and its
  375. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  376. %% diagram \eqref{eq:arith-prog}.
  377. %% To build larger S-expressions one often needs to splice together
  378. %% several smaller S-expressions. Racket provides the comma operator to
  379. %% splice an S-expression into a larger one. For example, instead of
  380. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. %% we could have first created an S-expression for AST
  382. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  383. %% S-expression.
  384. %% \begin{lstlisting}
  385. %% (define ast1.4 `(- 8))
  386. %% (define ast1.1 `(+ (read) ,ast1.4))
  387. %% \end{lstlisting}
  388. %% In general, the Racket expression that follows the comma (splice)
  389. %% can be any expression that produces an S-expression.
  390. We define a Racket \code{struct} for each kind of node. For this
  391. chapter we require just two kinds of nodes: one for integer constants
  392. and one for primitive operations. The following is the \code{struct}
  393. definition for integer constants.
  394. \begin{lstlisting}
  395. (struct Int (value))
  396. \end{lstlisting}
  397. An integer node includes just one thing: the integer value.
  398. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  399. \begin{lstlisting}
  400. (define eight (Int 8))
  401. \end{lstlisting}
  402. We say that the value created by \code{(Int 8)} is an
  403. \emph{instance} of the \code{Int} structure.
  404. The following is the \code{struct} definition for primitives operations.
  405. \begin{lstlisting}
  406. (struct Prim (op arg*))
  407. \end{lstlisting}
  408. A primitive operation node includes an operator symbol \code{op}
  409. and a list of children \code{arg*}. For example, to create
  410. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  411. \begin{lstlisting}
  412. (define neg-eight (Prim '- (list eight)))
  413. \end{lstlisting}
  414. Primitive operations may have zero or more children. The \code{read}
  415. operator has zero children:
  416. \begin{lstlisting}
  417. (define rd (Prim 'read '()))
  418. \end{lstlisting}
  419. whereas the addition operator has two children:
  420. \begin{lstlisting}
  421. (define ast1.1 (Prim '+ (list rd neg-eight)))
  422. \end{lstlisting}
  423. We have made a design choice regarding the \code{Prim} structure.
  424. Instead of using one structure for many different operations
  425. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  426. structure for each operation, as follows.
  427. \begin{lstlisting}
  428. (struct Read ())
  429. (struct Add (left right))
  430. (struct Neg (value))
  431. \end{lstlisting}
  432. The reason we choose to use just one structure is that in many parts
  433. of the compiler the code for the different primitive operators is the
  434. same, so we might as well just write that code once, which is enabled
  435. by using a single structure.
  436. When compiling a program such as \eqref{eq:arith-prog}, we need to
  437. know that the operation associated with the root node is addition and
  438. we need to be able to access its two children. Racket provides pattern
  439. matching over structures to support these kinds of queries, as we
  440. see in Section~\ref{sec:pattern-matching}.
  441. In this book, we often write down the concrete syntax of a program
  442. even when we really have in mind the AST because the concrete syntax
  443. is more concise. We recommend that, in your mind, you always think of
  444. programs as abstract syntax trees.
  445. \section{Grammars}
  446. \label{sec:grammar}
  447. \index{integer}
  448. \index{literal}
  449. \index{constant}
  450. A programming language can be thought of as a \emph{set} of programs.
  451. The set is typically infinite (one can always create larger and larger
  452. programs), so one cannot simply describe a language by listing all of
  453. the programs in the language. Instead we write down a set of rules, a
  454. \emph{grammar}, for building programs. Grammars are often used to
  455. define the concrete syntax of a language, but they can also be used to
  456. describe the abstract syntax. We write our rules in a variant of
  457. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  458. \index{Backus-Naur Form}\index{BNF}
  459. As an example, we describe a small language, named $R_0$, that consists of
  460. integers and arithmetic operations.
  461. \index{grammar}
  462. The first grammar rule for the abstract syntax of $R_0$ says that an
  463. instance of the \code{Int} structure is an expression:
  464. \begin{equation}
  465. \Exp ::= \INT{\Int} \label{eq:arith-int}
  466. \end{equation}
  467. %
  468. Each rule has a left-hand-side and a right-hand-side. The way to read
  469. a rule is that if you have all the program parts on the
  470. right-hand-side, then you can create an AST node and categorize it
  471. according to the left-hand-side.
  472. %
  473. A name such as $\Exp$ that is
  474. defined by the grammar rules is a \emph{non-terminal}.
  475. \index{non-terminal}
  476. %
  477. The name $\Int$ is a also a non-terminal, but instead of defining it
  478. with a grammar rule, we define it with the following explanation. We
  479. make the simplifying design decision that all of the languages in this
  480. book only handle machine-representable integers. On most modern
  481. machines this corresponds to integers represented with 64-bits, i.e.,
  482. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  483. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  484. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  485. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  486. that the sequence of decimals represent an integer in range $-2^{62}$
  487. to $2^{62}-1$.
  488. The second grammar rule is the \texttt{read} operation that receives
  489. an input integer from the user of the program.
  490. \begin{equation}
  491. \Exp ::= \READ{} \label{eq:arith-read}
  492. \end{equation}
  493. The third rule says that, given an $\Exp$ node, you can build another
  494. $\Exp$ node by negating it.
  495. \begin{equation}
  496. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  497. \end{equation}
  498. Symbols in typewriter font such as \key{-} and \key{read} are
  499. \emph{terminal} symbols and must literally appear in the program for
  500. the rule to be applicable.
  501. \index{terminal}
  502. We can apply the rules to build ASTs in the $R_0$
  503. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  504. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  505. an $\Exp$.
  506. \begin{center}
  507. \begin{minipage}{0.4\textwidth}
  508. \begin{lstlisting}
  509. (Prim '- (list (Int 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \begin{minipage}{0.25\textwidth}
  513. \begin{equation}
  514. \begin{tikzpicture}
  515. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  516. \node[draw, circle] (8) at (0, -1.2) {$8$};
  517. \draw[->] (minus) to (8);
  518. \end{tikzpicture}
  519. \label{eq:arith-neg8}
  520. \end{equation}
  521. \end{minipage}
  522. \end{center}
  523. The next grammar rule defines addition expressions:
  524. \begin{equation}
  525. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  526. \end{equation}
  527. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  528. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  529. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  530. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  531. to show that
  532. \begin{lstlisting}
  533. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  534. \end{lstlisting}
  535. is an $\Exp$ in the $R_0$ language.
  536. If you have an AST for which the above rules do not apply, then the
  537. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  538. is not in $R_0$ because there are no rules for \code{+} with only one
  539. argument, nor for \key{-} with two arguments. Whenever we define a
  540. language with a grammar, the language only includes those programs
  541. that are justified by the rules.
  542. The last grammar rule for $R_0$ states that there is a \code{Program}
  543. node to mark the top of the whole program:
  544. \[
  545. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  546. \]
  547. The \code{Program} structure is defined as follows
  548. \begin{lstlisting}
  549. (struct Program (info body))
  550. \end{lstlisting}
  551. where \code{body} is an expression. In later chapters, the \code{info}
  552. part will be used to store auxiliary information but for now it is
  553. just the empty list.
  554. It is common to have many grammar rules with the same left-hand side
  555. but different right-hand sides, such as the rules for $\Exp$ in the
  556. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  557. combine several right-hand-sides into a single rule.
  558. We collect all of the grammar rules for the abstract syntax of $R_0$
  559. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  560. defined in Figure~\ref{fig:r0-concrete-syntax}.
  561. The \code{read-program} function provided in \code{utilities.rkt} of
  562. the support materials reads a program in from a file (the sequence of
  563. characters in the concrete syntax of Racket) and parses it into an
  564. abstract syntax tree. See the description of \code{read-program} in
  565. Appendix~\ref{appendix:utilities} for more details.
  566. \begin{figure}[tp]
  567. \fbox{
  568. \begin{minipage}{0.96\textwidth}
  569. \[
  570. \begin{array}{rcl}
  571. \begin{array}{rcl}
  572. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  573. R_0 &::=& \Exp
  574. \end{array}
  575. \end{array}
  576. \]
  577. \end{minipage}
  578. }
  579. \caption{The concrete syntax of $R_0$.}
  580. \label{fig:r0-concrete-syntax}
  581. \end{figure}
  582. \begin{figure}[tp]
  583. \fbox{
  584. \begin{minipage}{0.96\textwidth}
  585. \[
  586. \begin{array}{rcl}
  587. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  588. &\mid& \ADD{\Exp}{\Exp} \\
  589. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  590. \end{array}
  591. \]
  592. \end{minipage}
  593. }
  594. \caption{The abstract syntax of $R_0$.}
  595. \label{fig:r0-syntax}
  596. \end{figure}
  597. \section{Pattern Matching}
  598. \label{sec:pattern-matching}
  599. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  600. the parts of an AST node. Racket provides the \texttt{match} form to
  601. access the parts of a structure. Consider the following example and
  602. the output on the right. \index{match} \index{pattern matching}
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (match ast1.1
  607. [(Prim op (list child1 child2))
  608. (print op)])
  609. \end{lstlisting}
  610. \end{minipage}
  611. \vrule
  612. \begin{minipage}{0.25\textwidth}
  613. \begin{lstlisting}
  614. '+
  615. \end{lstlisting}
  616. \end{minipage}
  617. \end{center}
  618. In the above example, the \texttt{match} form takes the AST
  619. \eqref{eq:arith-prog} and binds its parts to the three pattern
  620. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  621. general, a match clause consists of a \emph{pattern} and a
  622. \emph{body}.
  623. \index{pattern}
  624. Patterns are recursively defined to be either a pattern
  625. variable, a structure name followed by a pattern for each of the
  626. structure's arguments, or an S-expression (symbols, lists, etc.).
  627. (See Chapter 12 of The Racket
  628. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  629. and Chapter 9 of The Racket
  630. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  631. for a complete description of \code{match}.)
  632. %
  633. The body of a match clause may contain arbitrary Racket code. The
  634. pattern variables can be used in the scope of the body.
  635. A \code{match} form may contain several clauses, as in the following
  636. function \code{leaf?} that recognizes when an $R_0$ node is
  637. a leaf. The \code{match} proceeds through the clauses in order,
  638. checking whether the pattern can match the input AST. The
  639. body of the first clause that matches is executed. The output of
  640. \code{leaf?} for several ASTs is shown on the right.
  641. \begin{center}
  642. \begin{minipage}{0.6\textwidth}
  643. \begin{lstlisting}
  644. (define (leaf? arith)
  645. (match arith
  646. [(Int n) #t]
  647. [(Prim 'read '()) #t]
  648. [(Prim '- (list c1)) #f]
  649. [(Prim '+ (list c1 c2)) #f]))
  650. (leaf? (Prim 'read '()))
  651. (leaf? (Prim '- (list (Int 8))))
  652. (leaf? (Int 8))
  653. \end{lstlisting}
  654. \end{minipage}
  655. \vrule
  656. \begin{minipage}{0.25\textwidth}
  657. \begin{lstlisting}
  658. #t
  659. #f
  660. #t
  661. \end{lstlisting}
  662. \end{minipage}
  663. \end{center}
  664. When writing a \code{match}, we refer to the grammar definition to
  665. identify which non-terminal we are expecting to match against, then we
  666. make sure that 1) we have one clause for each alternative of that
  667. non-terminal and 2) that the pattern in each clause corresponds to the
  668. corresponding right-hand side of a grammar rule. For the \code{match}
  669. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  670. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  671. alternatives, so the \code{match} has 4 clauses. The pattern in each
  672. clause corresponds to the right-hand side of a grammar rule. For
  673. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  674. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  675. patterns, replace non-terminals such as $\Exp$ with pattern variables
  676. of your choice (e.g. \code{c1} and \code{c2}).
  677. \section{Recursion}
  678. \label{sec:recursion}
  679. \index{recursive function}
  680. Programs are inherently recursive. For example, an $R_0$ expression is
  681. often made of smaller expressions. Thus, the natural way to process an
  682. entire program is with a recursive function. As a first example of
  683. such a recursive function, we define \texttt{exp?} below, which takes
  684. an arbitrary value and determines whether or not it is an $R_0$
  685. expression.
  686. %
  687. When a recursive function is defined using a sequence of match clauses
  688. that correspond to a grammar, and the body of each clause makes a
  689. recursive call on each child node, then we say the function is defined
  690. by \emph{structural recursion}\footnote{This principle of structuring
  691. code according to the data definition is advocated in the book
  692. \emph{How to Design Programs}
  693. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  694. define a second function, named \code{R0?}, that determines whether a
  695. value is an $R_0$ program. In general we can expect to write one
  696. recursive function to handle each non-terminal in a grammar.
  697. \index{structural recursion}
  698. %
  699. \begin{center}
  700. \begin{minipage}{0.7\textwidth}
  701. \begin{lstlisting}
  702. (define (exp? ast)
  703. (match ast
  704. [(Int n) #t]
  705. [(Prim 'read '()) #t]
  706. [(Prim '- (list e)) (exp? e)]
  707. [(Prim '+ (list e1 e2))
  708. (and (exp? e1) (exp? e2))]
  709. [else #f]))
  710. (define (R0? ast)
  711. (match ast
  712. [(Program '() e) (exp? e)]
  713. [else #f]))
  714. (R0? (Program '() ast1.1)
  715. (R0? (Program '()
  716. (Prim '- (list (Prim 'read '())
  717. (Prim '+ (list (Num 8)))))))
  718. \end{lstlisting}
  719. \end{minipage}
  720. \vrule
  721. \begin{minipage}{0.25\textwidth}
  722. \begin{lstlisting}
  723. #t
  724. #f
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. You may be tempted to merge the two functions into one, like this:
  729. \begin{center}
  730. \begin{minipage}{0.5\textwidth}
  731. \begin{lstlisting}
  732. (define (R0? ast)
  733. (match ast
  734. [(Int n) #t]
  735. [(Prim 'read '()) #t]
  736. [(Prim '- (list e)) (R0? e)]
  737. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  738. [(Program '() e) (R0? e)]
  739. [else #f]))
  740. \end{lstlisting}
  741. \end{minipage}
  742. \end{center}
  743. %
  744. Sometimes such a trick will save a few lines of code, especially when
  745. it comes to the \code{Program} wrapper. Yet this style is generally
  746. \emph{not} recommended because it can get you into trouble.
  747. %
  748. For example, the above function is subtly wrong:
  749. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  750. will return true, when it should return false.
  751. %% NOTE FIXME - must check for consistency on this issue throughout.
  752. \section{Interpreters}
  753. \label{sec:interp-R0}
  754. \index{interpreter}
  755. The meaning, or semantics, of a program is typically defined in the
  756. specification of the language. For example, the Scheme language is
  757. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  758. defined in its reference manual~\citep{plt-tr}. In this book we use an
  759. interpreter to define the meaning of each language that we consider,
  760. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  761. interpreter that is designated (by some people) as the definition of a
  762. language is called a \emph{definitional interpreter}.
  763. \index{definitional interpreter}
  764. We warm up by creating a definitional interpreter for the $R_0$ language, which
  765. serves as a second example of structural recursion. The
  766. \texttt{interp-R0} function is defined in
  767. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  768. input program followed by a call to the \lstinline{interp-exp} helper
  769. function, which in turn has one match clause per grammar rule for
  770. $R_0$ expressions.
  771. \begin{figure}[tp]
  772. \begin{lstlisting}
  773. (define (interp-exp e)
  774. (match e
  775. [(Int n) n]
  776. [(Prim 'read '())
  777. (define r (read))
  778. (cond [(fixnum? r) r]
  779. [else (error 'interp-R0 "expected an integer" r)])]
  780. [(Prim '- (list e))
  781. (define v (interp-exp e))
  782. (fx- 0 v)]
  783. [(Prim '+ (list e1 e2))
  784. (define v1 (interp-exp e1))
  785. (define v2 (interp-exp e2))
  786. (fx+ v1 v2)]
  787. ))
  788. (define (interp-R0 p)
  789. (match p
  790. [(Program '() e) (interp-exp e)]
  791. ))
  792. \end{lstlisting}
  793. \caption{Interpreter for the $R_0$ language.}
  794. \label{fig:interp-R0}
  795. \end{figure}
  796. Let us consider the result of interpreting a few $R_0$ programs. The
  797. following program adds two integers.
  798. \begin{lstlisting}
  799. (+ 10 32)
  800. \end{lstlisting}
  801. The result is \key{42}. We wrote the above program in concrete syntax,
  802. whereas the parsed abstract syntax is:
  803. \begin{lstlisting}
  804. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  805. \end{lstlisting}
  806. The next example demonstrates that expressions may be nested within
  807. each other, in this case nesting several additions and negations.
  808. \begin{lstlisting}
  809. (+ 10 (- (+ 12 20)))
  810. \end{lstlisting}
  811. What is the result of the above program?
  812. As mentioned previously, the $R_0$ language does not support
  813. arbitrarily-large integers, but only $63$-bit integers, so we
  814. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  815. in Racket.
  816. Suppose
  817. \[
  818. n = 999999999999999999
  819. \]
  820. which indeed fits in $63$-bits. What happens when we run the
  821. following program in our interpreter?
  822. \begin{lstlisting}
  823. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  824. \end{lstlisting}
  825. It produces an error:
  826. \begin{lstlisting}
  827. fx+: result is not a fixnum
  828. \end{lstlisting}
  829. We establish the convention that if running the definitional
  830. interpreter on a program produces an error, then the meaning of that
  831. program is \emph{unspecified}. That means a compiler for the language
  832. is under no obligations regarding that program; it may or may not
  833. produce an executable, and if it does, that executable can do
  834. anything. This convention applies to the languages defined in this
  835. book, as a way to simplify the student's task of implementing them,
  836. but this convention is not applicable to all programming languages.
  837. \index{unspecified behavior}
  838. Moving on to the last feature of the $R_0$ language, the \key{read}
  839. operation prompts the user of the program for an integer. Recall that
  840. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  841. \code{8}. So if we run
  842. \begin{lstlisting}
  843. (interp-R0 (Program '() ast1.1))
  844. \end{lstlisting}
  845. and if the input is \code{50}, then we get the answer to life, the
  846. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  847. Guide to the Galaxy} by Douglas Adams.}
  848. We include the \key{read} operation in $R_0$ so a clever student
  849. cannot implement a compiler for $R_0$ that simply runs the interpreter
  850. during compilation to obtain the output and then generates the trivial
  851. code to produce the output. (Yes, a clever student did this in the
  852. first instance of this course.)
  853. The job of a compiler is to translate a program in one language into a
  854. program in another language so that the output program behaves the
  855. same way as the input program does according to its definitional
  856. interpreter. This idea is depicted in the following diagram. Suppose
  857. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  858. interpreter for each language. Suppose that the compiler translates
  859. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  860. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  861. respective interpreters with input $i$ should yield the same output
  862. $o$.
  863. \begin{equation} \label{eq:compile-correct}
  864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  865. \node (p1) at (0, 0) {$P_1$};
  866. \node (p2) at (3, 0) {$P_2$};
  867. \node (o) at (3, -2.5) {$o$};
  868. \path[->] (p1) edge [above] node {compile} (p2);
  869. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  870. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  871. \end{tikzpicture}
  872. \end{equation}
  873. In the next section we see our first example of a compiler.
  874. \section{Example Compiler: a Partial Evaluator}
  875. \label{sec:partial-evaluation}
  876. In this section we consider a compiler that translates $R_0$ programs
  877. into $R_0$ programs that may be more efficient, that is, this compiler
  878. is an optimizer. This optimizer eagerly computes the parts of the
  879. program that do not depend on any inputs, a process known as
  880. \emph{partial evaluation}~\cite{Jones:1993uq}.
  881. \index{partial evaluation}
  882. For example, given the following program
  883. \begin{lstlisting}
  884. (+ (read) (- (+ 5 3)))
  885. \end{lstlisting}
  886. our compiler will translate it into the program
  887. \begin{lstlisting}
  888. (+ (read) -8)
  889. \end{lstlisting}
  890. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  891. evaluator for the $R_0$ language. The output of the partial evaluator
  892. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  893. recursion over $\Exp$ is captured in the \code{pe-exp} function
  894. whereas the code for partially evaluating the negation and addition
  895. operations is factored into two separate helper functions:
  896. \code{pe-neg} and \code{pe-add}. The input to these helper
  897. functions is the output of partially evaluating the children.
  898. \begin{figure}[tp]
  899. \begin{lstlisting}
  900. (define (pe-neg r)
  901. (match r
  902. [(Int n) (Int (fx- 0 n))]
  903. [else (Prim '- (list r))]))
  904. (define (pe-add r1 r2)
  905. (match* (r1 r2)
  906. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  907. [(_ _) (Prim '+ (list r1 r2))]))
  908. (define (pe-exp e)
  909. (match e
  910. [(Int n) (Int n)]
  911. [(Prim 'read '()) (Prim 'read '())]
  912. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  913. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  914. ))
  915. (define (pe-R0 p)
  916. (match p
  917. [(Program '() e) (Program '() (pe-exp e))]
  918. ))
  919. \end{lstlisting}
  920. \caption{A partial evaluator for $R_0$ expressions.}
  921. \label{fig:pe-arith}
  922. \end{figure}
  923. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  924. arguments are integers and if they are, perform the appropriate
  925. arithmetic. Otherwise, they create an AST node for the operation
  926. (either negation or addition).
  927. To gain some confidence that the partial evaluator is correct, we can
  928. test whether it produces programs that get the same result as the
  929. input programs. That is, we can test whether it satisfies Diagram
  930. \eqref{eq:compile-correct}. The following code runs the partial
  931. evaluator on several examples and tests the output program. The
  932. \texttt{parse-program} and \texttt{assert} functions are defined in
  933. Appendix~\ref{appendix:utilities}.\\
  934. \begin{minipage}{1.0\textwidth}
  935. \begin{lstlisting}
  936. (define (test-pe p)
  937. (assert "testing pe-R0"
  938. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  939. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  940. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  941. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  942. \end{lstlisting}
  943. \end{minipage}
  944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  945. \chapter{Integers and Variables}
  946. \label{ch:int-exp}
  947. This chapter is about compiling the subset of Racket that includes
  948. integer arithmetic and local variable binding, which we name $R_1$, to
  949. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  950. to x86-64 simply as x86. The chapter begins with a description of the
  951. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  952. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  953. discuss only what is needed for compiling $R_1$. We introduce more of
  954. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  955. reflect on their differences and come up with a plan to break down the
  956. translation from $R_1$ to x86 into a handful of steps
  957. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  958. chapter give detailed hints regarding each step
  959. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  960. to give enough hints that the well-prepared reader, together with a
  961. few friends, can implement a compiler from $R_1$ to x86 in a couple
  962. weeks while at the same time leaving room for some fun and creativity.
  963. To give the reader a feeling for the scale of this first compiler, the
  964. instructor solution for the $R_1$ compiler is less than 500 lines of
  965. code.
  966. \section{The $R_1$ Language}
  967. \label{sec:s0}
  968. \index{variable}
  969. The $R_1$ language extends the $R_0$ language with variable
  970. definitions. The concrete syntax of the $R_1$ language is defined by
  971. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  972. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  973. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  974. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  975. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  976. \key{Program} struct to mark the top of the program.
  977. %% The $\itm{info}$
  978. %% field of the \key{Program} structure contains an \emph{association
  979. %% list} (a list of key-value pairs) that is used to communicate
  980. %% auxiliary data from one compiler pass the next.
  981. Despite the simplicity of the $R_1$ language, it is rich enough to
  982. exhibit several compilation techniques.
  983. \begin{figure}[tp]
  984. \centering
  985. \fbox{
  986. \begin{minipage}{0.96\textwidth}
  987. \[
  988. \begin{array}{rcl}
  989. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  990. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  991. R_1 &::=& \Exp
  992. \end{array}
  993. \]
  994. \end{minipage}
  995. }
  996. \caption{The concrete syntax of $R_1$.}
  997. \label{fig:r1-concrete-syntax}
  998. \end{figure}
  999. \begin{figure}[tp]
  1000. \centering
  1001. \fbox{
  1002. \begin{minipage}{0.96\textwidth}
  1003. \[
  1004. \begin{array}{rcl}
  1005. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1006. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1007. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1008. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{The abstract syntax of $R_1$.}
  1014. \label{fig:r1-syntax}
  1015. \end{figure}
  1016. Let us dive further into the syntax and semantics of the $R_1$
  1017. language. The \key{Let} feature defines a variable for use within its
  1018. body and initializes the variable with the value of an expression.
  1019. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1020. The concrete syntax for \key{Let} is
  1021. \begin{lstlisting}
  1022. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1023. \end{lstlisting}
  1024. For example, the following program initializes \code{x} to $32$ and then
  1025. evaluates the body \code{(+ 10 x)}, producing $42$.
  1026. \begin{lstlisting}
  1027. (let ([x (+ 12 20)]) (+ 10 x))
  1028. \end{lstlisting}
  1029. When there are multiple \key{let}'s for the same variable, the closest
  1030. enclosing \key{let} is used. That is, variable definitions overshadow
  1031. prior definitions. Consider the following program with two \key{let}'s
  1032. that define variables named \code{x}. Can you figure out the result?
  1033. \begin{lstlisting}
  1034. (let ([x 32]) (+ (let ([x 10]) x) x))
  1035. \end{lstlisting}
  1036. For the purposes of depicting which variable uses correspond to which
  1037. definitions, the following shows the \code{x}'s annotated with
  1038. subscripts to distinguish them. Double check that your answer for the
  1039. above is the same as your answer for this annotated version of the
  1040. program.
  1041. \begin{lstlisting}
  1042. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1043. \end{lstlisting}
  1044. The initializing expression is always evaluated before the body of the
  1045. \key{let}, so in the following, the \key{read} for \code{x} is
  1046. performed before the \key{read} for \code{y}. Given the input
  1047. $52$ then $10$, the following produces $42$ (not $-42$).
  1048. \begin{lstlisting}
  1049. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1050. \end{lstlisting}
  1051. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1052. \small
  1053. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1054. An \emph{association list} (alist) is a list of key-value pairs.
  1055. For example, we can map people to their ages with an alist.
  1056. \index{alist}\index{association list}
  1057. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1058. (define ages
  1059. '((jane . 25) (sam . 24) (kate . 45)))
  1060. \end{lstlisting}
  1061. The \emph{dictionary} interface is for mapping keys to values.
  1062. Every alist implements this interface. \index{dictionary} The package
  1063. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1064. provides many functions for working with dictionaries. Here
  1065. are a few of them:
  1066. \begin{description}
  1067. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1068. returns the value associated with the given $\itm{key}$.
  1069. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1070. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1071. but otherwise is the same as $\itm{dict}$.
  1072. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1073. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1074. of keys and values in $\itm{dict}$. For example, the following
  1075. creates a new alist in which the ages are incremented.
  1076. \end{description}
  1077. \vspace{-10pt}
  1078. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1079. (for/list ([(k v) (in-dict ages)])
  1080. (cons k (add1 v)))
  1081. \end{lstlisting}
  1082. \end{tcolorbox}
  1083. \end{wrapfigure}
  1084. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1085. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1086. \key{match} clauses for variables and for \key{let}. For \key{let},
  1087. we need a way to communicate the value of a variable to all the uses
  1088. of a variable. To accomplish this, we maintain a mapping from
  1089. variables to values. Throughout the compiler we often need to map
  1090. variables to information about them. We refer to these mappings as
  1091. \emph{environments}\index{environment}
  1092. \footnote{Another common term for environment in the compiler
  1093. literature is \emph{symbol table}\index{symbol table}.}.
  1094. For simplicity, we use an
  1095. association list (alist) to represent the environment. The sidebar to
  1096. the right gives a brief introduction to alists and the
  1097. \code{racket/dict} package. The \code{interp-R1} function takes the
  1098. current environment, \code{env}, as an extra parameter. When the
  1099. interpreter encounters a variable, it finds the corresponding value
  1100. using the \code{dict-ref} function. When the interpreter encounters a
  1101. \key{Let}, it evaluates the initializing expression, extends the
  1102. environment with the result value bound to the variable, using
  1103. \code{dict-set}, then evaluates the body of the \key{Let}.
  1104. \begin{figure}[tp]
  1105. \begin{lstlisting}
  1106. (define (interp-exp env)
  1107. (lambda (e)
  1108. (match e
  1109. [(Int n) n]
  1110. [(Prim 'read '())
  1111. (define r (read))
  1112. (cond [(fixnum? r) r]
  1113. [else (error 'interp-R1 "expected an integer" r)])]
  1114. [(Prim '- (list e))
  1115. (define v ((interp-exp env) e))
  1116. (fx- 0 v)]
  1117. [(Prim '+ (list e1 e2))
  1118. (define v1 ((interp-exp env) e1))
  1119. (define v2 ((interp-exp env) e2))
  1120. (fx+ v1 v2)]
  1121. [(Var x) (dict-ref env x)]
  1122. [(Let x e body)
  1123. (define new-env (dict-set env x ((interp-exp env) e)))
  1124. ((interp-exp new-env) body)]
  1125. )))
  1126. (define (interp-R1 p)
  1127. (match p
  1128. [(Program '() e) ((interp-exp '()) e)]
  1129. ))
  1130. \end{lstlisting}
  1131. \caption{Interpreter for the $R_1$ language.}
  1132. \label{fig:interp-R1}
  1133. \end{figure}
  1134. The goal for this chapter is to implement a compiler that translates
  1135. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1136. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1137. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1138. is, they both output the same integer $n$. We depict this correctness
  1139. criteria in the following diagram.
  1140. \[
  1141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1142. \node (p1) at (0, 0) {$P_1$};
  1143. \node (p2) at (4, 0) {$P_2$};
  1144. \node (o) at (4, -2) {$n$};
  1145. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1146. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1147. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1148. \end{tikzpicture}
  1149. \]
  1150. In the next section we introduce enough of the x86 assembly
  1151. language to compile $R_1$.
  1152. \section{The x86$_0$ Assembly Language}
  1153. \label{sec:x86}
  1154. \index{x86}
  1155. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1156. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1157. %
  1158. An x86 program begins with a \code{main} label followed by a sequence
  1159. of instructions. In the grammar, ellipses such as $\ldots$ are used to
  1160. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1161. instructions.\index{instruction}
  1162. %
  1163. An x86 program is stored in the computer's memory and the computer has
  1164. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1165. that points to the address of the next
  1166. instruction to be executed. For most instructions, once the
  1167. instruction is executed, the program counter is incremented to point
  1168. to the immediately following instruction in memory. Most x86
  1169. instructions take two operands, where each operand is either an
  1170. integer constant (called \emph{immediate value}\index{immediate value}),
  1171. a \emph{register}\index{register}, or a memory location.
  1172. A register is a special kind of variable. Each
  1173. one holds a 64-bit value; there are 16 registers in the computer and
  1174. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1175. as a mapping of 64-bit addresses to 64-bit values%
  1176. \footnote{This simple story suffices for describing how sequential
  1177. programs access memory but is not sufficient for multi-threaded
  1178. programs. However, multi-threaded execution is beyond the scope of
  1179. this book.}.
  1180. %
  1181. We use the AT\&T syntax expected by the GNU assembler, which comes
  1182. with the \key{gcc} compiler that we use for compiling assembly code to
  1183. machine code.
  1184. %
  1185. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1186. the x86 instructions used in this book.
  1187. % to do: finish treatment of imulq
  1188. % it's needed for vector's in R6/R7
  1189. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1190. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1191. && \key{r8} \mid \key{r9} \mid \key{r10}
  1192. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1193. \mid \key{r14} \mid \key{r15}}
  1194. \begin{figure}[tp]
  1195. \fbox{
  1196. \begin{minipage}{0.96\textwidth}
  1197. \[
  1198. \begin{array}{lcl}
  1199. \Reg &::=& \allregisters{} \\
  1200. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1201. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1202. \key{subq} \; \Arg\key{,} \Arg \mid
  1203. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1204. && \key{callq} \; \mathit{label} \mid
  1205. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1206. && \itm{label}\key{:}\; \Instr \\
  1207. x86_0 &::= & \key{.globl main}\\
  1208. & & \key{main:} \; \Instr\ldots
  1209. \end{array}
  1210. \]
  1211. \end{minipage}
  1212. }
  1213. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1214. \label{fig:x86-0-concrete}
  1215. \end{figure}
  1216. An immediate value is written using the notation \key{\$}$n$ where $n$
  1217. is an integer.
  1218. %
  1219. A register is written with a \key{\%} followed by the register name,
  1220. such as \key{\%rax}.
  1221. %
  1222. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1223. which obtains the address stored in register $r$ and then adds $n$
  1224. bytes to the address. The resulting address is used to either load or
  1225. store to memory depending on whether it occurs as a source or
  1226. destination argument of an instruction.
  1227. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1228. source $s$ and destination $d$, applies the arithmetic operation, then
  1229. writes the result back to the destination $d$.
  1230. %
  1231. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1232. stores the result in $d$.
  1233. %
  1234. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1235. specified by the label and $\key{retq}$ returns from a procedure to
  1236. its caller. The abstract syntax for \code{callq} includes an extra
  1237. integer field that represents the arity (number of parameters) of the
  1238. function being called.
  1239. %
  1240. We discuss procedure calls in more detail later in this
  1241. chapter and in Chapter~\ref{ch:functions}. The
  1242. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1243. the address of the instruction after the specified label.
  1244. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1245. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1246. \key{main} procedure is externally visible, which is necessary so
  1247. that the operating system can call it. The label \key{main:}
  1248. indicates the beginning of the \key{main} procedure which is where
  1249. the operating system starts executing this program. The instruction
  1250. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1251. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1252. $10$ in \key{rax} and puts the result, $42$, back into
  1253. \key{rax}.
  1254. %
  1255. The last instruction, \key{retq}, finishes the \key{main} function by
  1256. returning the integer in \key{rax} to the operating system. The
  1257. operating system interprets this integer as the program's exit
  1258. code. By convention, an exit code of 0 indicates that a program
  1259. completed successfully, and all other exit codes indicate various
  1260. errors. Nevertheless, we return the result of the program as the exit
  1261. code.
  1262. %\begin{wrapfigure}{r}{2.25in}
  1263. \begin{figure}[tbp]
  1264. \begin{lstlisting}
  1265. .globl main
  1266. main:
  1267. movq $10, %rax
  1268. addq $32, %rax
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p0-x86}
  1273. %\end{wrapfigure}
  1274. \end{figure}
  1275. Unfortunately, x86 varies in a couple ways depending on what operating
  1276. system it is assembled in. The code examples shown here are correct on
  1277. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1278. labels like \key{main} must be prefixed with an underscore, as in
  1279. \key{\_main}.
  1280. We exhibit the use of memory for storing intermediate results in the
  1281. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1282. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1283. memory called the \emph{procedure call stack} (or \emph{stack} for
  1284. short). \index{stack}\index{procedure call stack} The stack consists
  1285. of a separate \emph{frame}\index{frame} for each procedure call. The
  1286. memory layout for an individual frame is shown in
  1287. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1288. \emph{stack pointer}\index{stack pointer} and points to the item at
  1289. the top of the stack. The stack grows downward in memory, so we
  1290. increase the size of the stack by subtracting from the stack pointer.
  1291. In the context of a procedure call, the \emph{return
  1292. address}\index{return address} is the instruction after the call
  1293. instruction on the caller side. The function call instruction,
  1294. \code{callq}, pushes the return address onto the stack. The register
  1295. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1296. to access variables associated with the current procedure call. The
  1297. base pointer of the caller is pushed onto the stack after the return
  1298. address. We number the variables from $1$ to $n$. Variable $1$ is
  1299. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1300. $-16\key{(\%rbp)}$, etc.
  1301. \begin{figure}[tbp]
  1302. \begin{lstlisting}
  1303. start:
  1304. movq $10, -8(%rbp)
  1305. negq -8(%rbp)
  1306. movq -8(%rbp), %rax
  1307. addq $52, %rax
  1308. jmp conclusion
  1309. .globl main
  1310. main:
  1311. pushq %rbp
  1312. movq %rsp, %rbp
  1313. subq $16, %rsp
  1314. jmp start
  1315. conclusion:
  1316. addq $16, %rsp
  1317. popq %rbp
  1318. retq
  1319. \end{lstlisting}
  1320. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1321. \label{fig:p1-x86}
  1322. \end{figure}
  1323. \begin{figure}[tbp]
  1324. \centering
  1325. \begin{tabular}{|r|l|} \hline
  1326. Position & Contents \\ \hline
  1327. 8(\key{\%rbp}) & return address \\
  1328. 0(\key{\%rbp}) & old \key{rbp} \\
  1329. -8(\key{\%rbp}) & variable $1$ \\
  1330. -16(\key{\%rbp}) & variable $2$ \\
  1331. \ldots & \ldots \\
  1332. 0(\key{\%rsp}) & variable $n$\\ \hline
  1333. \end{tabular}
  1334. \caption{Memory layout of a frame.}
  1335. \label{fig:frame}
  1336. \end{figure}
  1337. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1338. control is transferred from the operating system to the \code{main}
  1339. function. The operating system issues a \code{callq main} instruction
  1340. which pushes its return address on the stack and then jumps to
  1341. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1342. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1343. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1344. alignment (because the \code{callq} pushed the return address). The
  1345. first three instructions are the typical \emph{prelude}\index{prelude}
  1346. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1347. pointer for the caller onto the stack and subtracts $8$ from the stack
  1348. pointer. At this point the stack pointer is back to being 16-byte
  1349. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1350. base pointer so that it points the location of the old base
  1351. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1352. pointer down to make enough room for storing variables. This program
  1353. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1354. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1355. we are ready to make calls to other functions. The last instruction of
  1356. the prelude is \code{jmp start}, which transfers control to the
  1357. instructions that were generated from the Racket expression \code{(+
  1358. 10 32)}.
  1359. The four instructions under the label \code{start} carry out the work
  1360. of computing \code{(+ 52 (- 10)))}.
  1361. %
  1362. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1363. variable $1$.
  1364. %
  1365. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1366. %
  1367. The following instruction moves the $-10$ from variable $1$ into the
  1368. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1369. the value in \code{rax}, updating its contents to $42$.
  1370. The three instructions under the label \code{conclusion} are the
  1371. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1372. two instructions are necessary to get the state of the machine back to
  1373. where it was at the beginning of the procedure. The instruction
  1374. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1375. old base pointer. The amount added here needs to match the amount that
  1376. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1377. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1378. pointer. The last instruction, \key{retq}, jumps back to the
  1379. procedure that called this one and adds 8 to the stack pointer, which
  1380. returns the stack pointer to where it was prior to the procedure call.
  1381. The compiler needs a convenient representation for manipulating x86
  1382. programs, so we define an abstract syntax for x86 in
  1383. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1384. a subscript $0$ because later we introduce extended versions of this
  1385. assembly language. The main difference compared to the concrete syntax
  1386. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1387. labeled instructions to appear anywhere, but instead organizes
  1388. instructions into a group called a
  1389. \emph{block}\index{block}\index{basic block} and associates a label
  1390. with every block, which is why the \key{CFG} struct (for control-flow
  1391. graph) includes an alist mapping labels to blocks. The reason for this
  1392. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1393. introduce conditional branching. The \code{Block} structure includes
  1394. an $\itm{info}$ field that is not needed for this chapter, but will
  1395. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1396. the $\itm{info}$ field should just contain an empty list. Also,
  1397. regarding the abstract syntax for \code{callq}, the \code{Callq}
  1398. struct includes an integer for representing the arity of the function,
  1399. i.e., the number of arguments, which is helpful to know during
  1400. register allocation (Chapter~\ref{ch:register-allocation-r1}).
  1401. \begin{figure}[tp]
  1402. \fbox{
  1403. \begin{minipage}{0.96\textwidth}
  1404. \small
  1405. \[
  1406. \begin{array}{lcl}
  1407. \Reg &::=& \allregisters{} \\
  1408. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1409. \mid \DEREF{\Reg}{\Int} \\
  1410. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1411. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1412. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1413. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1414. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1415. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1416. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1417. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1418. \end{array}
  1419. \]
  1420. \end{minipage}
  1421. }
  1422. \caption{The abstract syntax of x86$_0$ assembly.}
  1423. \label{fig:x86-0-ast}
  1424. \end{figure}
  1425. \section{Planning the trip to x86 via the $C_0$ language}
  1426. \label{sec:plan-s0-x86}
  1427. To compile one language to another it helps to focus on the
  1428. differences between the two languages because the compiler will need
  1429. to bridge those differences. What are the differences between $R_1$
  1430. and x86 assembly? Here are some of the most important ones:
  1431. \begin{enumerate}
  1432. \item[(a)] x86 arithmetic instructions typically have two arguments
  1433. and update the second argument in place. In contrast, $R_1$
  1434. arithmetic operations take two arguments and produce a new value.
  1435. An x86 instruction may have at most one memory-accessing argument.
  1436. Furthermore, some instructions place special restrictions on their
  1437. arguments.
  1438. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1439. whereas x86 instructions restrict their arguments to be integers
  1440. constants, registers, and memory locations.
  1441. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1442. sequence of instructions and jumps to labeled positions, whereas in
  1443. $R_1$ the order of evaluation is a left-to-right depth-first
  1444. traversal of the abstract syntax tree.
  1445. \item[(d)] An $R_1$ program can have any number of variables whereas
  1446. x86 has 16 registers and the procedure calls stack.
  1447. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1448. same name. The registers and memory locations of x86 all have unique
  1449. names or addresses.
  1450. \end{enumerate}
  1451. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1452. the problem into several steps, dealing with the above differences one
  1453. at a time. Each of these steps is called a \emph{pass} of the
  1454. compiler.\index{pass}\index{compiler pass}
  1455. %
  1456. This terminology comes from each step traverses (i.e. passes over) the
  1457. AST of the program.
  1458. %
  1459. We begin by sketching how we might implement each pass, and give them
  1460. names. We then figure out an ordering of the passes and the
  1461. input/output language for each pass. The very first pass has $R_1$ as
  1462. its input language and the last pass has x86 as its output
  1463. language. In between we can choose whichever language is most
  1464. convenient for expressing the output of each pass, whether that be
  1465. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1466. Finally, to implement each pass we write one recursive function per
  1467. non-terminal in the grammar of the input language of the pass.
  1468. \index{intermediate language}
  1469. \begin{description}
  1470. \item[Pass \key{select-instructions}] To handle the difference between
  1471. $R_1$ operations and x86 instructions we convert each $R_1$
  1472. operation to a short sequence of instructions that accomplishes the
  1473. same task.
  1474. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1475. subexpression (i.e. operator and operand, and hence the name
  1476. \key{opera*}) is an \emph{atomic} expression (a variable or
  1477. integer), we introduce temporary variables to hold the results
  1478. of subexpressions.\index{atomic expression}
  1479. \item[Pass \key{explicate-control}] To make the execution order of the
  1480. program explicit, we convert from the abstract syntax tree
  1481. representation into a control-flow graph in which each node
  1482. contains a sequence of statements and the edges between nodes say
  1483. where to go at the end of the sequence.
  1484. \item[Pass \key{assign-homes}] To handle the difference between the
  1485. variables in $R_1$ versus the registers and stack locations in x86,
  1486. we map each variable to a register or stack location.
  1487. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1488. by renaming every variable to a unique name, so that shadowing no
  1489. longer occurs.
  1490. \end{description}
  1491. The next question is: in what order should we apply these passes? This
  1492. question can be challenging because it is difficult to know ahead of
  1493. time which orders will be better (easier to implement, produce more
  1494. efficient code, etc.) so oftentimes trial-and-error is
  1495. involved. Nevertheless, we can try to plan ahead and make educated
  1496. choices regarding the ordering.
  1497. Let us consider the ordering of \key{uniquify} and
  1498. \key{remove-complex-opera*}. The assignment of subexpressions to
  1499. temporary variables involves introducing new variables and moving
  1500. subexpressions, which might change the shadowing of variables and
  1501. inadvertently change the behavior of the program. But if we apply
  1502. \key{uniquify} first, this will not be an issue. Of course, this means
  1503. that in \key{remove-complex-opera*}, we need to ensure that the
  1504. temporary variables that it creates are unique.
  1505. What should be the ordering of \key{explicate-control} with respect to
  1506. \key{uniquify}? The \key{uniquify} pass should come first because
  1507. \key{explicate-control} changes all the \key{let}-bound variables to
  1508. become local variables whose scope is the entire program, which would
  1509. confuse variables with the same name.
  1510. %
  1511. Likewise, we place \key{explicate-control} after
  1512. \key{remove-complex-opera*} because \key{explicate-control} removes
  1513. the \key{let} form, but it is convenient to use \key{let} in the
  1514. output of \key{remove-complex-opera*}.
  1515. %
  1516. Regarding \key{assign-homes}, it is helpful to place
  1517. \key{explicate-control} first because \key{explicate-control} changes
  1518. \key{let}-bound variables into program-scope variables. This means
  1519. that the \key{assign-homes} pass can read off the variables from the
  1520. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1521. entire program in search of \key{let}-bound variables.
  1522. Last, we need to decide on the ordering of \key{select-instructions}
  1523. and \key{assign-homes}. These two passes are intertwined, creating a
  1524. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1525. have already determined which instructions will be used, because x86
  1526. instructions have restrictions about which of their arguments can be
  1527. registers versus stack locations. One might want to give preferential
  1528. treatment to variables that occur in register-argument positions. On
  1529. the other hand, it may turn out to be impossible to make sure that all
  1530. such variables are assigned to registers, and then one must redo the
  1531. selection of instructions. Some compilers handle this problem by
  1532. iteratively repeating these two passes until a good solution is found.
  1533. We use a simpler approach in which \key{select-instructions}
  1534. comes first, followed by the \key{assign-homes}, then a third
  1535. pass named \key{patch-instructions} that uses a reserved register to
  1536. patch-up outstanding problems regarding instructions with too many
  1537. memory accesses. The disadvantage of this approach is some programs
  1538. may not execute as efficiently as they would if we used the iterative
  1539. approach and used all of the registers for variables.
  1540. \begin{figure}[tbp]
  1541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1542. \node (R1) at (0,2) {\large $R_1$};
  1543. \node (R1-2) at (3,2) {\large $R_1$};
  1544. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1545. %\node (C0-1) at (6,0) {\large $C_0$};
  1546. \node (C0-2) at (3,0) {\large $C_0$};
  1547. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1548. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1549. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1550. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1551. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1552. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1553. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1554. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1555. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1556. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1557. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1558. \end{tikzpicture}
  1559. \caption{Overview of the passes for compiling $R_1$. }
  1560. \label{fig:R1-passes}
  1561. \end{figure}
  1562. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1563. passes in the form of a graph. Each pass is an edge and the
  1564. input/output language of each pass is a node in the graph. The output
  1565. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1566. are still in the $R_1$ language, but the output of the pass
  1567. \key{explicate-control} is in a different language $C_0$ that is
  1568. designed to make the order of evaluation explicit in its syntax, which
  1569. we introduce in the next section. The \key{select-instruction} pass
  1570. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1571. \key{patch-instructions} passes input and output variants of x86
  1572. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1573. \key{print-x86}, which converts from the abstract syntax of
  1574. $\text{x86}_0$ to the concrete syntax of x86.
  1575. In the next sections we discuss the $C_0$ language and the
  1576. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1577. remainder of this chapter gives hints regarding the implementation of
  1578. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1579. \subsection{The $C_0$ Intermediate Language}
  1580. The output of \key{explicate-control} is similar to the $C$
  1581. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1582. categories for expressions and statements, so we name it $C_0$. The
  1583. concrete syntax for $C_0$ is defined in
  1584. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1585. is defined in Figure~\ref{fig:c0-syntax}.
  1586. %
  1587. The $C_0$ language supports the same operators as $R_1$ but the
  1588. arguments of operators are restricted to atomic expressions (variables
  1589. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1590. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1591. executed in sequence using the \key{Seq} form. A sequence of
  1592. statements always ends with \key{Return}, a guarantee that is baked
  1593. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1594. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1595. which refers to an expression that is the last one to execute within a
  1596. function. (An expression in tail position may contain subexpressions,
  1597. and those may or may not be in tail position depending on the kind of
  1598. expression.)
  1599. A $C_0$ program consists of a control-flow graph (represented as an
  1600. alist mapping labels to tails). This is more general than
  1601. necessary for the present chapter, as we do not yet need to introduce
  1602. \key{goto} for jumping to labels, but it saves us from having to
  1603. change the syntax of the program construct in
  1604. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1605. \key{start}, and the whole program is its tail.
  1606. %
  1607. The $\itm{info}$ field of the \key{Program} form, after the
  1608. \key{explicate-control} pass, contains a mapping from the symbol
  1609. \key{locals} to a list of variables, that is, a list of all the
  1610. variables used in the program. At the start of the program, these
  1611. variables are uninitialized; they become initialized on their first
  1612. assignment.
  1613. \begin{figure}[tbp]
  1614. \fbox{
  1615. \begin{minipage}{0.96\textwidth}
  1616. \[
  1617. \begin{array}{lcl}
  1618. \Atm &::=& \Int \mid \Var \\
  1619. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1620. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1621. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1622. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1623. \end{array}
  1624. \]
  1625. \end{minipage}
  1626. }
  1627. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1628. \label{fig:c0-concrete-syntax}
  1629. \end{figure}
  1630. \begin{figure}[tbp]
  1631. \fbox{
  1632. \begin{minipage}{0.96\textwidth}
  1633. \[
  1634. \begin{array}{lcl}
  1635. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1636. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1637. &\mid& \ADD{\Atm}{\Atm}\\
  1638. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1639. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1640. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1641. \end{array}
  1642. \]
  1643. \end{minipage}
  1644. }
  1645. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1646. \label{fig:c0-syntax}
  1647. \end{figure}
  1648. \subsection{The dialects of x86}
  1649. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1650. the pass \key{select-instructions}. It extends x86$_0$ with an
  1651. unbounded number of program-scope variables and has looser rules
  1652. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1653. output of \key{print-x86}, is the concrete syntax for x86.
  1654. \section{Uniquify Variables}
  1655. \label{sec:uniquify-s0}
  1656. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1657. programs in which every \key{let} uses a unique variable name. For
  1658. example, the \code{uniquify} pass should translate the program on the
  1659. left into the program on the right. \\
  1660. \begin{tabular}{lll}
  1661. \begin{minipage}{0.4\textwidth}
  1662. \begin{lstlisting}
  1663. (let ([x 32])
  1664. (+ (let ([x 10]) x) x))
  1665. \end{lstlisting}
  1666. \end{minipage}
  1667. &
  1668. $\Rightarrow$
  1669. &
  1670. \begin{minipage}{0.4\textwidth}
  1671. \begin{lstlisting}
  1672. (let ([x.1 32])
  1673. (+ (let ([x.2 10]) x.2) x.1))
  1674. \end{lstlisting}
  1675. \end{minipage}
  1676. \end{tabular} \\
  1677. %
  1678. The following is another example translation, this time of a program
  1679. with a \key{let} nested inside the initializing expression of another
  1680. \key{let}.\\
  1681. \begin{tabular}{lll}
  1682. \begin{minipage}{0.4\textwidth}
  1683. \begin{lstlisting}
  1684. (let ([x (let ([x 4])
  1685. (+ x 1))])
  1686. (+ x 2))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. &
  1690. $\Rightarrow$
  1691. &
  1692. \begin{minipage}{0.4\textwidth}
  1693. \begin{lstlisting}
  1694. (let ([x.2 (let ([x.1 4])
  1695. (+ x.1 1))])
  1696. (+ x.2 2))
  1697. \end{lstlisting}
  1698. \end{minipage}
  1699. \end{tabular}
  1700. We recommend implementing \code{uniquify} by creating a function named
  1701. \code{uniquify-exp} that is structurally recursive function and mostly
  1702. just copies the input program. However, when encountering a \key{let},
  1703. it should generate a unique name for the variable (the Racket function
  1704. \code{gensym} is handy for this) and associate the old name with the
  1705. new unique name in an alist. The \code{uniquify-exp}
  1706. function will need to access this alist when it gets to a
  1707. variable reference, so we add another parameter to \code{uniquify-exp}
  1708. for the alist.
  1709. The skeleton of the \code{uniquify-exp} function is shown in
  1710. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1711. convenient to partially apply it to a symbol table and then apply it
  1712. to different expressions, as in the last clause for primitive
  1713. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1714. form is useful for applying a function to each element of a list to produce
  1715. a new list.
  1716. \index{for/list}
  1717. \begin{exercise}
  1718. \normalfont % I don't like the italics for exercises. -Jeremy
  1719. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1720. implement the clauses for variables and for the \key{let} form.
  1721. \end{exercise}
  1722. \begin{figure}[tbp]
  1723. \begin{lstlisting}
  1724. (define (uniquify-exp symtab)
  1725. (lambda (e)
  1726. (match e
  1727. [(Var x) ___]
  1728. [(Int n) (Int n)]
  1729. [(Let x e body) ___]
  1730. [(Prim op es)
  1731. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1732. )))
  1733. (define (uniquify p)
  1734. (match p
  1735. [(Program '() e)
  1736. (Program '() ((uniquify-exp '()) e))]
  1737. )))
  1738. \end{lstlisting}
  1739. \caption{Skeleton for the \key{uniquify} pass.}
  1740. \label{fig:uniquify-s0}
  1741. \end{figure}
  1742. \begin{exercise}
  1743. \normalfont % I don't like the italics for exercises. -Jeremy
  1744. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1745. and checking whether the output programs produce the same result as
  1746. the input programs. The $R_1$ programs should be designed to test the
  1747. most interesting parts of the \key{uniquify} pass, that is, the
  1748. programs should include \key{let} forms, variables, and variables that
  1749. overshadow each other. The five programs should be in a subdirectory
  1750. named \key{tests} and they should have the same file name except for a
  1751. different integer at the end of the name, followed by the ending
  1752. \key{.rkt}. Use the \key{interp-tests} function
  1753. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1754. your \key{uniquify} pass on the example programs. See the
  1755. \key{run-tests.rkt} script in the support code for an example of how
  1756. to use \key{interp-tests}. The support code is in a \code{github}
  1757. repository at the following URL:
  1758. \begin{center}\footnotesize
  1759. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1760. \end{center}
  1761. \end{exercise}
  1762. \section{Remove Complex Operands}
  1763. \label{sec:remove-complex-opera-R1}
  1764. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1765. $R_1$ programs in which the arguments of operations are atomic
  1766. expressions. Put another way, this pass removes complex
  1767. operands\index{complex operand}, such as the expression \code{(- 10)}
  1768. in the program below. This is accomplished by introducing a new
  1769. \key{let}-bound variable, binding the complex operand to the new
  1770. variable, and then using the new variable in place of the complex
  1771. operand, as shown in the output of \code{remove-complex-opera*} on the
  1772. right.\\
  1773. \begin{tabular}{lll}
  1774. \begin{minipage}{0.4\textwidth}
  1775. % s0_19.rkt
  1776. \begin{lstlisting}
  1777. (+ 52 (- 10))
  1778. \end{lstlisting}
  1779. \end{minipage}
  1780. &
  1781. $\Rightarrow$
  1782. &
  1783. \begin{minipage}{0.4\textwidth}
  1784. \begin{lstlisting}
  1785. (let ([tmp.1 (- 10)])
  1786. (+ 52 tmp.1))
  1787. \end{lstlisting}
  1788. \end{minipage}
  1789. \end{tabular}
  1790. \begin{figure}[tp]
  1791. \centering
  1792. \fbox{
  1793. \begin{minipage}{0.96\textwidth}
  1794. \[
  1795. \begin{array}{rcl}
  1796. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1797. \Exp &::=& \Atm \mid \READ{} \\
  1798. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1799. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1800. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1801. \end{array}
  1802. \]
  1803. \end{minipage}
  1804. }
  1805. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1806. \label{fig:r1-anf-syntax}
  1807. \end{figure}
  1808. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1809. this pass, language $R_1^{\dagger}$. The main difference is that
  1810. operator arguments are required to be atomic expressions. In the
  1811. literature, this is called \emph{administrative normal form}, or ANF
  1812. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1813. \index{administrative normal form}
  1814. \index{ANF}
  1815. We recommend implementing this pass with two mutually recursive
  1816. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1817. \code{rco-atom} to subexpressions that are required to be atomic and
  1818. to apply \code{rco-exp} to subexpressions that can be atomic or
  1819. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1820. $R_1$ expression as input. The \code{rco-exp} function returns an
  1821. expression. The \code{rco-atom} function returns two things: an
  1822. atomic expression and alist mapping temporary variables to complex
  1823. subexpressions. You can return multiple things from a function using
  1824. Racket's \key{values} form and you can receive multiple things from a
  1825. function call using the \key{define-values} form. If you are not
  1826. familiar with these features, review the Racket documentation. Also,
  1827. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1828. form is useful for applying a function to each
  1829. element of a list, in the case where the function returns multiple
  1830. values.
  1831. \index{for/lists}
  1832. The following shows the output of \code{rco-atom} on the expression
  1833. \code{(- 10)} (using concrete syntax to be concise).
  1834. \begin{tabular}{lll}
  1835. \begin{minipage}{0.4\textwidth}
  1836. \begin{lstlisting}
  1837. (- 10)
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. &
  1841. $\Rightarrow$
  1842. &
  1843. \begin{minipage}{0.4\textwidth}
  1844. \begin{lstlisting}
  1845. tmp.1
  1846. ((tmp.1 . (- 10)))
  1847. \end{lstlisting}
  1848. \end{minipage}
  1849. \end{tabular}
  1850. Take special care of programs such as the next one that \key{let}-bind
  1851. variables with integers or other variables. You should leave them
  1852. unchanged, as shown in to the program on the right \\
  1853. \begin{tabular}{lll}
  1854. \begin{minipage}{0.4\textwidth}
  1855. % s0_20.rkt
  1856. \begin{lstlisting}
  1857. (let ([a 42])
  1858. (let ([b a])
  1859. b))
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. &
  1863. $\Rightarrow$
  1864. &
  1865. \begin{minipage}{0.4\textwidth}
  1866. \begin{lstlisting}
  1867. (let ([a 42])
  1868. (let ([b a])
  1869. b))
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \end{tabular} \\
  1873. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1874. produce the following output.\\
  1875. \begin{minipage}{0.4\textwidth}
  1876. \begin{lstlisting}
  1877. (let ([tmp.1 42])
  1878. (let ([a tmp.1])
  1879. (let ([tmp.2 a])
  1880. (let ([b tmp.2])
  1881. b))))
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \begin{exercise}
  1885. \normalfont Implement the \code{remove-complex-opera*} pass.
  1886. Test the new pass on all of the example programs that you created to test the
  1887. \key{uniquify} pass and create three new example programs that are
  1888. designed to exercise the interesting code in the
  1889. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1890. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1891. your passes on the example programs.
  1892. \end{exercise}
  1893. \section{Explicate Control}
  1894. \label{sec:explicate-control-r1}
  1895. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1896. programs that make the order of execution explicit in their
  1897. syntax. For now this amounts to flattening \key{let} constructs into a
  1898. sequence of assignment statements. For example, consider the following
  1899. $R_1$ program.\\
  1900. % s0_11.rkt
  1901. \begin{minipage}{0.96\textwidth}
  1902. \begin{lstlisting}
  1903. (let ([y (let ([x 20])
  1904. (+ x (let ([x 22]) x)))])
  1905. y)
  1906. \end{lstlisting}
  1907. \end{minipage}\\
  1908. %
  1909. The output of the previous pass and of \code{explicate-control} is
  1910. shown below. Recall that the right-hand-side of a \key{let} executes
  1911. before its body, so the order of evaluation for this program is to
  1912. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1913. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1914. output of \code{explicate-control} makes this ordering explicit.\\
  1915. \begin{tabular}{lll}
  1916. \begin{minipage}{0.4\textwidth}
  1917. \begin{lstlisting}
  1918. (let ([y (let ([x.1 20])
  1919. (let ([x.2 22])
  1920. (+ x.1 x.2)))])
  1921. y)
  1922. \end{lstlisting}
  1923. \end{minipage}
  1924. &
  1925. $\Rightarrow$
  1926. &
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. start:
  1930. x.1 = 20;
  1931. x.2 = 22;
  1932. y = (+ x.1 x.2);
  1933. return y;
  1934. \end{lstlisting}
  1935. \end{minipage}
  1936. \end{tabular}
  1937. We recommend implementing \code{explicate-control} using two mutually
  1938. recursive functions: \code{explicate-tail} and
  1939. \code{explicate-assign}. The first function should be applied to
  1940. expressions in tail position whereas the second should be applied to
  1941. expressions that occur on the right-hand-side of a \key{let}.
  1942. %
  1943. The \code{explicate-tail} function takes an $R_1$ expression as input
  1944. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}).
  1945. %
  1946. The \code{explicate-assign} function takes an $R_1$ expression, the
  1947. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1948. should come after the assignment (e.g., the code generated for the
  1949. body of the \key{let}) and returns a $\Tail$. The
  1950. \code{explicate-assign} function is in accumulator-passing style in
  1951. that its third parameter is some $C_0$ code that it adds to and
  1952. returns. The reader might be tempted to instead organize
  1953. \code{explicate-assign} in a more direct fashion, without the third
  1954. parameter and perhaps using \code{append} to combine statements. We
  1955. warn against that alternative because the accumulator-passing style is
  1956. key to how we generate high-quality code for conditional expressions
  1957. in Chapter~\ref{ch:bool-types}.
  1958. The top-level \code{explicate-control} function should invoke
  1959. \code{explicate-tail} on the body of the \key{Program} AST node.
  1960. \section{Select Instructions}
  1961. \label{sec:select-r1}
  1962. \index{instruction selection}
  1963. In the \code{select-instructions} pass we begin the work of
  1964. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1965. this pass is a variant of x86 that still uses variables, so we add an
  1966. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1967. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1968. \code{select-instructions} in terms of three auxiliary functions, one
  1969. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1970. The cases for $\Atm$ are straightforward, variables stay
  1971. the same and integer constants are changed to immediates:
  1972. $\INT{n}$ changes to $\IMM{n}$.
  1973. Next we consider the cases for $\Stmt$, starting with arithmetic
  1974. operations. For example, in $C_0$ an addition operation can take the
  1975. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1976. need to use the \key{addq} instruction which does an in-place
  1977. update. So we must first move \code{10} to \code{x}. \\
  1978. \begin{tabular}{lll}
  1979. \begin{minipage}{0.4\textwidth}
  1980. \begin{lstlisting}
  1981. x = (+ 10 32);
  1982. \end{lstlisting}
  1983. \end{minipage}
  1984. &
  1985. $\Rightarrow$
  1986. &
  1987. \begin{minipage}{0.4\textwidth}
  1988. \begin{lstlisting}
  1989. movq $10, x
  1990. addq $32, x
  1991. \end{lstlisting}
  1992. \end{minipage}
  1993. \end{tabular} \\
  1994. %
  1995. There are cases that require special care to avoid generating
  1996. needlessly complicated code. If one of the arguments of the addition
  1997. is the same as the left-hand side of the assignment, then there is no
  1998. need for the extra move instruction. For example, the following
  1999. assignment statement can be translated into a single \key{addq}
  2000. instruction.\\
  2001. \begin{tabular}{lll}
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}
  2004. x = (+ 10 x);
  2005. \end{lstlisting}
  2006. \end{minipage}
  2007. &
  2008. $\Rightarrow$
  2009. &
  2010. \begin{minipage}{0.4\textwidth}
  2011. \begin{lstlisting}
  2012. addq $10, x
  2013. \end{lstlisting}
  2014. \end{minipage}
  2015. \end{tabular} \\
  2016. The \key{read} operation does not have a direct counterpart in x86
  2017. assembly, so we have instead implemented this functionality in the C
  2018. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2019. in the file \code{runtime.c}. In general, we refer to all of the
  2020. functionality in this file as the \emph{runtime system}\index{runtime system},
  2021. or simply the \emph{runtime} for short. When compiling your generated x86
  2022. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2023. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2024. the executable. For our purposes of code generation, all you need to
  2025. do is translate an assignment of \key{read} into some variable
  2026. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2027. function followed by a move from \code{rax} to the left-hand side.
  2028. The move from \code{rax} is needed because the return value from
  2029. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2030. \begin{tabular}{lll}
  2031. \begin{minipage}{0.3\textwidth}
  2032. \begin{lstlisting}
  2033. |$\itm{var}$| = (read);
  2034. \end{lstlisting}
  2035. \end{minipage}
  2036. &
  2037. $\Rightarrow$
  2038. &
  2039. \begin{minipage}{0.3\textwidth}
  2040. \begin{lstlisting}
  2041. callq read_int
  2042. movq %rax, |$\itm{var}$|
  2043. \end{lstlisting}
  2044. \end{minipage}
  2045. \end{tabular} \\
  2046. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2047. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2048. assignment to the \key{rax} register followed by a jump to the
  2049. conclusion of the program (so the conclusion needs to be labeled).
  2050. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2051. recursively and append the resulting instructions.
  2052. \begin{exercise}
  2053. \normalfont
  2054. Implement the \key{select-instructions} pass and test it on all of the
  2055. example programs that you created for the previous passes and create
  2056. three new example programs that are designed to exercise all of the
  2057. interesting code in this pass. Use the \key{interp-tests} function
  2058. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2059. your passes on the example programs.
  2060. \end{exercise}
  2061. \section{Assign Homes}
  2062. \label{sec:assign-r1}
  2063. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2064. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2065. Thus, the \key{assign-homes} pass is responsible for placing all of
  2066. the program variables in registers or on the stack. For runtime
  2067. efficiency, it is better to place variables in registers, but as there
  2068. are only 16 registers, some programs must necessarily resort to
  2069. placing some variables on the stack. In this chapter we focus on the
  2070. mechanics of placing variables on the stack. We study an algorithm for
  2071. placing variables in registers in
  2072. Chapter~\ref{ch:register-allocation-r1}.
  2073. Consider again the following $R_1$ program.
  2074. % s0_20.rkt
  2075. \begin{lstlisting}
  2076. (let ([a 42])
  2077. (let ([b a])
  2078. b))
  2079. \end{lstlisting}
  2080. For reference, we repeat the output of \code{select-instructions} on
  2081. the left and show the output of \code{assign-homes} on the right.
  2082. %
  2083. %% Recall that \key{explicate-control} associated the list of
  2084. %% variables with the \code{locals} symbol in the program's $\itm{info}$
  2085. %% field, so \code{assign-homes} has convenient access to the them.
  2086. %
  2087. In this example, we assign variable \code{a} to stack location
  2088. \code{-8(\%rbp)} and variable \code{b} to location
  2089. \code{-16(\%rbp)}.\\
  2090. \begin{tabular}{l}
  2091. \begin{minipage}{0.4\textwidth}
  2092. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2093. locals-types:
  2094. a : 'Integer, b : 'Integer
  2095. start:
  2096. movq $42, a
  2097. movq a, b
  2098. movq b, %rax
  2099. jmp conclusion
  2100. \end{lstlisting}
  2101. \end{minipage}
  2102. {$\Rightarrow$}
  2103. \begin{minipage}{0.4\textwidth}
  2104. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2105. stack-space: 16
  2106. start:
  2107. movq $42, -8(%rbp)
  2108. movq -8(%rbp), -16(%rbp)
  2109. movq -16(%rbp), %rax
  2110. jmp conclusion
  2111. \end{lstlisting}
  2112. \end{minipage}
  2113. \end{tabular} \\
  2114. In the output of \code{select-instructions}, there is a entry for
  2115. \code{locals-types} in the $\itm{info}$ of the \code{Program} node,
  2116. which is needed here so that we have the list of variables that should
  2117. be assigned to homes. The support code computes the
  2118. \code{locals-types} entry. In particular, \code{type-check-C0}
  2119. installs it in the $\itm{info}$ field of the \code{Program} node.
  2120. When using \code{interp-tests} or \code{compiler-tests} (see Appendix,
  2121. Section~\ref{appendix:utilities}), specify \code{type-check-C0} as the
  2122. type checker to use after \code{explicate-control}.
  2123. In the process of assigning variables to stack locations, it is
  2124. convenient for you to compute and store the size of the frame (in
  2125. bytes) in the $\itm{info}$ field of the \key{Program} node, with the
  2126. key \code{stack-space}, which is needed later to generate the
  2127. conclusion of the \code{main} procedure. The x86-64 standard requires
  2128. the frame size to be a multiple of 16 bytes. \index{frame}
  2129. \begin{exercise}
  2130. \normalfont Implement the \key{assign-homes} pass and test it on all
  2131. of the example programs that you created for the previous passes pass.
  2132. We recommend that \key{assign-homes} take an extra parameter that is a
  2133. mapping of variable names to homes (stack locations for now). Use the
  2134. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2135. \key{utilities.rkt} to test your passes on the example programs.
  2136. \end{exercise}
  2137. \section{Patch Instructions}
  2138. \label{sec:patch-s0}
  2139. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2140. programs to $\text{x86}_0$ programs by making sure that each
  2141. instruction adheres to the restrictions of the x86 assembly language.
  2142. In particular, at most one argument of an instruction may be a memory
  2143. reference.
  2144. We return to the following running example.
  2145. % s0_20.rkt
  2146. \begin{lstlisting}
  2147. (let ([a 42])
  2148. (let ([b a])
  2149. b))
  2150. \end{lstlisting}
  2151. After the \key{assign-homes} pass, the above program has been translated to
  2152. the following. \\
  2153. \begin{minipage}{0.5\textwidth}
  2154. \begin{lstlisting}
  2155. stack-space: 16
  2156. start:
  2157. movq $42, -8(%rbp)
  2158. movq -8(%rbp), -16(%rbp)
  2159. movq -16(%rbp), %rax
  2160. jmp conclusion
  2161. \end{lstlisting}
  2162. \end{minipage}\\
  2163. The second \key{movq} instruction is problematic because both
  2164. arguments are stack locations. We suggest fixing this problem by
  2165. moving from the source location to the register \key{rax} and then
  2166. from \key{rax} to the destination location, as follows.
  2167. \begin{lstlisting}
  2168. movq -8(%rbp), %rax
  2169. movq %rax, -16(%rbp)
  2170. \end{lstlisting}
  2171. \begin{exercise}
  2172. \normalfont
  2173. Implement the \key{patch-instructions} pass and test it on all of the
  2174. example programs that you created for the previous passes and create
  2175. three new example programs that are designed to exercise all of the
  2176. interesting code in this pass. Use the \key{interp-tests} function
  2177. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2178. your passes on the example programs.
  2179. \end{exercise}
  2180. \section{Print x86}
  2181. \label{sec:print-x86}
  2182. The last step of the compiler from $R_1$ to x86 is to convert the
  2183. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2184. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2185. \key{format} and \key{string-append} functions are useful in this
  2186. regard. The main work that this step needs to perform is to create the
  2187. \key{main} function and the standard instructions for its prelude and
  2188. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2189. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2190. variables, so we suggest computing it in the \key{assign-homes} pass
  2191. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2192. of the \key{program} node.
  2193. %% Your compiled code should print the result of the program's execution
  2194. %% by using the \code{print\_int} function provided in
  2195. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2196. %% far, this final result should be stored in the \key{rax} register.
  2197. %% We'll talk more about how to perform function calls with arguments in
  2198. %% general later on, but for now, place the following after the compiled
  2199. %% code for the $R_1$ program but before the conclusion:
  2200. %% \begin{lstlisting}
  2201. %% movq %rax, %rdi
  2202. %% callq print_int
  2203. %% \end{lstlisting}
  2204. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2205. %% stores the first argument to be passed into \key{print\_int}.
  2206. If you want your program to run on Mac OS X, your code needs to
  2207. determine whether or not it is running on a Mac, and prefix
  2208. underscores to labels like \key{main}. You can determine the platform
  2209. with the Racket call \code{(system-type 'os)}, which returns
  2210. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2211. %% In addition to
  2212. %% placing underscores on \key{main}, you need to put them in front of
  2213. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2214. %% \_print\_int}).
  2215. \begin{exercise}
  2216. \normalfont Implement the \key{print-x86} pass and test it on all of
  2217. the example programs that you created for the previous passes. Use the
  2218. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2219. \key{utilities.rkt} to test your complete compiler on the example
  2220. programs. See the \key{run-tests.rkt} script in the student support
  2221. code for an example of how to use \key{compiler-tests}. Also, remember
  2222. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2223. \key{gcc}.
  2224. \end{exercise}
  2225. \section{Challenge: Partial Evaluator for $R_1$}
  2226. \label{sec:pe-R1}
  2227. \index{partial evaluation}
  2228. This section describes optional challenge exercises that involve
  2229. adapting and improving the partial evaluator for $R_0$ that was
  2230. introduced in Section~\ref{sec:partial-evaluation}.
  2231. \begin{exercise}\label{ex:pe-R1}
  2232. \normalfont
  2233. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2234. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2235. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2236. and variables to the $R_0$ language, so you will need to add cases for
  2237. them in the \code{pe-exp} function. Also, note that the \key{program}
  2238. form changes slightly to include an $\itm{info}$ field. Once
  2239. complete, add the partial evaluation pass to the front of your
  2240. compiler and make sure that your compiler still passes all of the
  2241. tests.
  2242. \end{exercise}
  2243. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2244. \begin{exercise}
  2245. \normalfont
  2246. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2247. \code{pe-add} auxiliary functions with functions that know more about
  2248. arithmetic. For example, your partial evaluator should translate
  2249. \begin{lstlisting}
  2250. (+ 1 (+ (read) 1))
  2251. \end{lstlisting}
  2252. into
  2253. \begin{lstlisting}
  2254. (+ 2 (read))
  2255. \end{lstlisting}
  2256. To accomplish this, the \code{pe-exp} function should produce output
  2257. in the form of the $\itm{residual}$ non-terminal of the following
  2258. grammar.
  2259. \[
  2260. \begin{array}{lcl}
  2261. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2262. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2263. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2264. \end{array}
  2265. \]
  2266. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2267. that their inputs are $\itm{residual}$ expressions and they should
  2268. return $\itm{residual}$ expressions. Once the improvements are
  2269. complete, make sure that your compiler still passes all of the tests.
  2270. After all, fast code is useless if it produces incorrect results!
  2271. \end{exercise}
  2272. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2273. \chapter{Register Allocation}
  2274. \label{ch:register-allocation-r1}
  2275. \index{register allocation}
  2276. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2277. make our life easier. However, we can improve the performance of the
  2278. generated code if we instead place some variables into registers. The
  2279. CPU can access a register in a single cycle, whereas accessing the
  2280. stack takes many cycles if the relevant data is in cache or many more
  2281. to access main memory if the data is not in cache.
  2282. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2283. serves as a running example. We show the source program and also the
  2284. output of instruction selection. At that point the program is almost
  2285. x86 assembly but not quite; it still contains variables instead of
  2286. stack locations or registers.
  2287. \begin{figure}
  2288. \begin{minipage}{0.45\textwidth}
  2289. Example $R_1$ program:
  2290. % s0_28.rkt
  2291. \begin{lstlisting}
  2292. (let ([v 1])
  2293. (let ([w 42])
  2294. (let ([x (+ v 7)])
  2295. (let ([y x])
  2296. (let ([z (+ x w)])
  2297. (+ z (- y)))))))
  2298. \end{lstlisting}
  2299. \end{minipage}
  2300. \begin{minipage}{0.45\textwidth}
  2301. After instruction selection:
  2302. \begin{lstlisting}
  2303. locals-types:
  2304. x : Integer, y : Integer,
  2305. z : Integer, t : Integer,
  2306. v : Integer, w : Integer
  2307. start:
  2308. movq $1, v
  2309. movq $42, w
  2310. movq v, x
  2311. addq $7, x
  2312. movq x, y
  2313. movq x, z
  2314. addq w, z
  2315. movq y, t
  2316. negq t
  2317. movq z, %rax
  2318. addq t, %rax
  2319. jmp conclusion
  2320. \end{lstlisting}
  2321. \end{minipage}
  2322. \caption{A running example program for register allocation.}
  2323. \label{fig:reg-eg}
  2324. \end{figure}
  2325. The goal of register allocation is to fit as many variables into
  2326. registers as possible. A program sometimes has more variables than
  2327. registers, so we cannot always map each variable to a different
  2328. register. Fortunately, it is common for different variables to be
  2329. needed during different periods of time during program execution, and
  2330. in such cases several variables can be mapped to the same register.
  2331. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2332. After the variable \code{x} is moved to \code{z} it is no longer
  2333. needed. Variable \code{y}, on the other hand, is used only after this
  2334. point, so \code{x} and \code{y} could share the same register. The
  2335. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2336. where a variable is needed. Once we have that information, we compute
  2337. which variables are needed at the same time, i.e., which ones
  2338. \emph{interfere} with each other, and represent this relation as an
  2339. undirected graph whose vertices are variables and edges indicate when
  2340. two variables interfere (Section~\ref{sec:build-interference}). We
  2341. then model register allocation as a graph coloring problem, which we
  2342. discuss in Section~\ref{sec:graph-coloring}.
  2343. If we run out of registers despite these efforts, we place the
  2344. remaining variables on the stack, similar to what we did in
  2345. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2346. for assigning a variable to a stack location. The decision to spill a
  2347. variable is handled as part of the graph coloring process described in
  2348. Section~\ref{sec:graph-coloring}.
  2349. We make the simplifying assumption that each variable is assigned to
  2350. one location (a register or stack address). A more sophisticated
  2351. approach is to assign a variable to one or more locations in different
  2352. regions of the program. For example, if a variable is used many times
  2353. in short sequence and then only used again after many other
  2354. instructions, it could be more efficient to assign the variable to a
  2355. register during the initial sequence and then move it to the stack for
  2356. the rest of its lifetime. We refer the interested reader to
  2357. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2358. about that approach.
  2359. % discuss prioritizing variables based on how much they are used.
  2360. \section{Registers and Calling Conventions}
  2361. \label{sec:calling-conventions}
  2362. \index{calling conventions}
  2363. As we perform register allocation, we need to be aware of the
  2364. \emph{calling conventions} \index{calling conventions} that govern how
  2365. functions calls are performed in x86. Function calls require
  2366. coordination between the caller and the callee, which is often
  2367. assembly code written by different programmers or generated by
  2368. different compilers. Here we follow the System V calling conventions
  2369. that are used by the \code{gcc} compiler on Linux and
  2370. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2371. %
  2372. Even though $R_1$ does not include programmer-defined functions, our
  2373. generated code will 1) include a \code{main} function that the
  2374. operating system will call to initiate execution, and 2) make calls to
  2375. the \code{read\_int} function in our runtime system.
  2376. The calling conventions include rules about how functions share the
  2377. use of registers. In particular, the caller is responsible for freeing
  2378. up some registers prior to the function call for use by the callee.
  2379. These are called the \emph{caller-saved registers}
  2380. \index{caller-saved registers}
  2381. and they are
  2382. \begin{lstlisting}
  2383. rax rcx rdx rsi rdi r8 r9 r10 r11
  2384. \end{lstlisting}
  2385. On the other hand, the callee is responsible for preserving the values
  2386. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2387. which are
  2388. \begin{lstlisting}
  2389. rsp rbp rbx r12 r13 r14 r15
  2390. \end{lstlisting}
  2391. We can think about this caller/callee convention from two points of
  2392. view, the caller view and the callee view:
  2393. \begin{itemize}
  2394. \item The caller should assume that all the caller-saved registers get
  2395. overwritten with arbitrary values by the callee. On the other hand,
  2396. the caller can safely assume that all the callee-saved registers
  2397. contain the same values after the call that they did before the
  2398. call.
  2399. \item The callee can freely use any of the caller-saved registers.
  2400. However, if the callee wants to use a callee-saved register, the
  2401. callee must arrange to put the original value back in the register
  2402. prior to returning to the caller, which is usually accomplished by
  2403. saving the value to the stack in the prelude of the function and
  2404. restoring the value in the conclusion of the function.
  2405. \end{itemize}
  2406. In x86, registers are also used for passing arguments to a function
  2407. and for the return value. In particular, the first six arguments of a
  2408. function are passed in the following six registers, in the order
  2409. given.
  2410. \begin{lstlisting}
  2411. rdi rsi rdx rcx r8 r9
  2412. \end{lstlisting}
  2413. If there are more than six arguments, then the convention is to use
  2414. space on the frame of the caller for the rest of the
  2415. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2416. need more than six arguments. For now, the only function we care about
  2417. is \code{read\_int} and it takes zero argument.
  2418. %
  2419. The register \code{rax} is for the return value of a function.
  2420. The next question is how these calling conventions impact register
  2421. allocation. Consider the $R_1$ program in
  2422. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2423. example from the caller point of view and then from the callee point
  2424. of view.
  2425. The program makes two calls to the \code{read} function. Also, the
  2426. variable \code{x} is in-use during the second call to \code{read}, so
  2427. we need to make sure that the value in \code{x} does not get
  2428. accidentally wiped out by the call to \code{read}. One obvious
  2429. approach is to save all the values in caller-saved registers to the
  2430. stack prior to each function call, and restore them after each
  2431. call. That way, if the register allocator chooses to assign \code{x}
  2432. to a caller-saved register, its value will be preserved across the
  2433. call to \code{read}. However, the disadvantage of this approach is
  2434. that saving and restoring to the stack is relatively slow. If \code{x}
  2435. is not used many times, it may be better to assign \code{x} to a stack
  2436. location in the first place. Or better yet, if we can arrange for
  2437. \code{x} to be placed in a callee-saved register, then it won't need
  2438. to be saved and restored during function calls.
  2439. The approach that we recommend for variables that are in-use during a
  2440. function call is to either assign them to callee-saved registers or to
  2441. spill them to the stack. On the other hand, for variables that are not
  2442. in-use during a function call, we try the following alternatives in
  2443. order 1) look for an available caller-saved register (to leave room
  2444. for other variables in the callee-saved register), 2) look for a
  2445. callee-saved register, and 3) spill the variable to the stack.
  2446. It is straightforward to implement this approach in a graph coloring
  2447. register allocator. First, we know which variables are in-use during
  2448. every function call because we compute that information for every
  2449. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2450. build the interference graph (Section~\ref{sec:build-interference}),
  2451. we can place an edge between each of these variables and the
  2452. caller-saved registers in the interference graph. This will prevent
  2453. the graph coloring algorithm from assigning those variables to
  2454. caller-saved registers.
  2455. Returning to the example in
  2456. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2457. generated x86 code on the right-hand side, focusing on the
  2458. \code{start} block. Notice that variable \code{x} is assigned to
  2459. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2460. place during the second call to \code{read\_int}. Next, notice that
  2461. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2462. because there are no function calls in the remainder of the block.
  2463. Next we analyze the example from the callee point of view, focusing on
  2464. the prelude and conclusion of the \code{main} function. As usual the
  2465. prelude begins with saving the \code{rbp} register to the stack and
  2466. setting the \code{rbp} to the current stack pointer. We now know why
  2467. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2468. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2469. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2470. variable (\code{x}). There are several more callee-saved register that
  2471. are not saved in the prelude because they were not assigned to
  2472. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2473. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2474. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2475. from the stack with a \code{popq} instruction.
  2476. \index{prelude}\index{conclusion}
  2477. \begin{figure}[tp]
  2478. \begin{minipage}{0.45\textwidth}
  2479. Example $R_1$ program:
  2480. %s0_14.rkt
  2481. \begin{lstlisting}
  2482. (let ([x (read)])
  2483. (let ([y (read)])
  2484. (+ (+ x y) 42)))
  2485. \end{lstlisting}
  2486. \end{minipage}
  2487. \begin{minipage}{0.45\textwidth}
  2488. Generated x86 assembly:
  2489. \begin{lstlisting}
  2490. start:
  2491. callq read_int
  2492. movq %rax, %rbx
  2493. callq read_int
  2494. movq %rax, %rcx
  2495. addq %rcx, %rbx
  2496. movq %rbx, %rax
  2497. addq $42, %rax
  2498. jmp _conclusion
  2499. .globl main
  2500. main:
  2501. pushq %rbp
  2502. movq %rsp, %rbp
  2503. pushq %rbx
  2504. subq $8, %rsp
  2505. jmp start
  2506. conclusion:
  2507. addq $8, %rsp
  2508. popq %rbx
  2509. popq %rbp
  2510. retq
  2511. \end{lstlisting}
  2512. \end{minipage}
  2513. \caption{An example with function calls.}
  2514. \label{fig:example-calling-conventions}
  2515. \end{figure}
  2516. \section{Liveness Analysis}
  2517. \label{sec:liveness-analysis-r1}
  2518. \index{liveness analysis}
  2519. A variable or register is \emph{live} at a program point if its
  2520. current value is used at some later point in the program. We
  2521. refer to variables and registers collectively as \emph{locations}.
  2522. %
  2523. Consider the following code fragment in which there are two writes to
  2524. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2525. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2526. movq $5, a
  2527. movq $30, b
  2528. movq a, c
  2529. movq $10, b
  2530. addq b, c
  2531. \end{lstlisting}
  2532. The answer is no because the integer \code{30} written to \code{b} on
  2533. line 2 is never used. The variable \code{b} is read on line 5 and
  2534. there is an intervening write to \code{b} on line 4, so the read on
  2535. line 5 receives the value written on line 4, not line 2.
  2536. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2537. \small
  2538. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2539. A \emph{set} is an unordered collection of elements without duplicates.
  2540. \index{set}
  2541. \begin{description}
  2542. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2543. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2544. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2545. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2546. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2547. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2548. \end{description}
  2549. \end{tcolorbox}
  2550. \end{wrapfigure}
  2551. The live locations can be computed by traversing the instruction
  2552. sequence back to front (i.e., backwards in execution order). Let
  2553. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2554. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2555. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2556. locations before instruction $I_k$. The live locations after an
  2557. instruction are always the same as the live locations before the next
  2558. instruction. \index{live-after} \index{live-before}
  2559. \begin{equation} \label{eq:live-after-before-next}
  2560. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2561. \end{equation}
  2562. To start things off, there are no live locations after the last
  2563. instruction\footnote{Technically, the \code{rax} register is live
  2564. but we do not use it for register allocation.}, so
  2565. \begin{equation}\label{eq:live-last-empty}
  2566. L_{\mathsf{after}}(n) = \emptyset
  2567. \end{equation}
  2568. We then apply the following rule repeatedly, traversing the
  2569. instruction sequence back to front.
  2570. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2571. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2572. \end{equation}
  2573. where $W(k)$ are the locations written to by instruction $I_k$ and
  2574. $R(k)$ are the locations read by instruction $I_k$.
  2575. There is a special case for \code{jmp} instructions. The locations
  2576. that are live before a \code{jmp} should be the locations that are
  2577. live before the instruction that follows the target label. So we
  2578. recommend maintaining an alist, perhaps called \code{label->live},
  2579. that maps each label to a set of such locations. Recall that for now,
  2580. the only \code{jmp} in a pseudo-x86 program is the one at the end, to
  2581. the \code{conclusion}. (For example, see Figure~\ref{fig:reg-eg}.) So
  2582. the alist should map \code{conclusion} to the set
  2583. $\{\ttm{rax},\ttm{rsp}\}$.
  2584. Let us walk through the above example, applying these formulas
  2585. starting with the instruction on line 5. We collect the answers in the
  2586. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2587. instruction is $\emptyset$ because it is the last instruction
  2588. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2589. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2590. variables \code{b} and \code{c}
  2591. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2592. \[
  2593. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2594. \]
  2595. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2596. the live-before set from line 5 to be the live-after set for this
  2597. instruction (formula~\ref{eq:live-after-before-next}).
  2598. \[
  2599. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2600. \]
  2601. This move instruction writes to \code{b} and does not read from any
  2602. variables, so we have the following live-before set
  2603. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2604. \[
  2605. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2606. \]
  2607. The live-before for instruction \code{movq a, c}
  2608. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2609. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2610. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2611. variable that is not live and does not read from a variable.
  2612. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2613. because it writes to variable \code{a}.
  2614. \begin{center}
  2615. \begin{minipage}{0.45\textwidth}
  2616. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2617. movq $5, a
  2618. movq $30, b
  2619. movq a, c
  2620. movq $10, b
  2621. addq b, c
  2622. \end{lstlisting}
  2623. \end{minipage}
  2624. \vrule\hspace{10pt}
  2625. \begin{minipage}{0.45\textwidth}
  2626. \begin{align*}
  2627. L_{\mathsf{before}}(1)= \emptyset,
  2628. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2629. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2630. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2631. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2632. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2633. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2634. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2635. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2636. L_{\mathsf{after}}(5)= \emptyset
  2637. \end{align*}
  2638. \end{minipage}
  2639. \end{center}
  2640. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2641. the running example program, with the live-before and live-after sets
  2642. shown between each instruction to make the figure easy to read.
  2643. \begin{figure}[tp]
  2644. \hspace{20pt}
  2645. \begin{minipage}{0.45\textwidth}
  2646. \begin{lstlisting}
  2647. |$\{\ttm{rsp}\}$|
  2648. movq $1, v
  2649. |$\{\ttm{v},\ttm{rsp}\}$|
  2650. movq $42, w
  2651. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2652. movq v, x
  2653. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2654. addq $7, x
  2655. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2656. movq x, y
  2657. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2658. movq x, z
  2659. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2660. addq w, z
  2661. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2662. movq y, t
  2663. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2664. negq t
  2665. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2666. movq z, %rax
  2667. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2668. addq t, %rax
  2669. |$\{\ttm{rax},\ttm{rsp}\}$|
  2670. jmp conclusion
  2671. \end{lstlisting}
  2672. \end{minipage}
  2673. \caption{The running example annotated with live-after sets.}
  2674. \label{fig:live-eg}
  2675. \end{figure}
  2676. \begin{exercise}\normalfont
  2677. Implement the compiler pass named \code{uncover-live} that computes
  2678. the live-after sets. We recommend storing the live-after sets (a list
  2679. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2680. structure.
  2681. %
  2682. We recommend organizing your code to use a helper function that takes
  2683. a list of instructions and an initial live-after set (typically empty)
  2684. and returns the list of live-after sets.
  2685. %
  2686. We recommend creating helper functions to 1) compute the set of
  2687. locations that appear in an argument (of an instruction), 2) compute
  2688. the locations read by an instruction which corresponds to the $R$
  2689. function discussed above, and 3) the locations written by an
  2690. instruction which corresponds to $W$. The \code{callq} instruction
  2691. should include all of the caller-saved registers in its write-set $W$
  2692. because the calling convention says that those registers may be
  2693. written to during the function call. Likewise, the \code{callq}
  2694. instruction should include the appropriate number of argument passing
  2695. registers in its read-set $R$, depending on the arity of the function
  2696. being called. (This is why the abstract syntax for \code{callq}
  2697. includes the arity.)
  2698. \end{exercise}
  2699. \section{Building the Interference Graph}
  2700. \label{sec:build-interference}
  2701. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2702. \small
  2703. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2704. A \emph{graph} is a collection of vertices and edges where each
  2705. edge connects two vertices. A graph is \emph{directed} if each
  2706. edge points from a source to a target. Otherwise the graph is
  2707. \emph{undirected}.
  2708. \index{graph}\index{directed graph}\index{undirected graph}
  2709. \begin{description}
  2710. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2711. directed graph from a list of edges. Each edge is a list
  2712. containing the source and target vertex.
  2713. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2714. undirected graph from a list of edges. Each edge is represented by
  2715. a list containing two vertices.
  2716. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2717. inserts a vertex into the graph.
  2718. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2719. inserts an edge between the two vertices into the graph.
  2720. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2721. returns a sequence of all the neighbors of the given vertex.
  2722. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2723. returns a sequence of all the vertices in the graph.
  2724. \end{description}
  2725. \end{tcolorbox}
  2726. \end{wrapfigure}
  2727. Based on the liveness analysis, we know where each location is used
  2728. (read from). However, during register allocation, we need to answer
  2729. questions of the specific form: are locations $u$ and $v$ live at the
  2730. same time? (And therefore cannot be assigned to the same register.)
  2731. To make this question easier to answer, we create an explicit data
  2732. structure, an \emph{interference graph}\index{interference graph}. An
  2733. interference graph is an undirected graph that has an edge between two
  2734. locations if they are live at the same time, that is, if they
  2735. interfere with each other.
  2736. The most obvious way to compute the interference graph is to look at
  2737. the set of live location between each statement in the program and add
  2738. an edge to the graph for every pair of variables in the same set.
  2739. This approach is less than ideal for two reasons. First, it can be
  2740. expensive because it takes $O(n^2)$ time to look at every pair in a
  2741. set of $n$ live locations. Second, there is a special case in which
  2742. two locations that are live at the same time do not actually interfere
  2743. with each other: when they both contain the same value because we have
  2744. assigned one to the other.
  2745. A better way to compute the interference graph is to focus on the
  2746. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2747. instruction to overwrite something in a live location. So for each
  2748. instruction, we create an edge between the locations being written to
  2749. and all the other live locations. (Except that one should not create
  2750. self edges.) Recall that for a \key{callq} instruction, we consider
  2751. all of the caller-saved registers as being written to, so an edge will
  2752. be added between every live variable and every caller-saved
  2753. register. For \key{movq}, we deal with the above-mentioned special
  2754. case by not adding an edge between a live variable $v$ and destination
  2755. $d$ if $v$ matches the source of the move. So we have the following
  2756. two rules.
  2757. \begin{enumerate}
  2758. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2759. $d$, then add the edge $(d,v)$ for every $v \in
  2760. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2761. \item For any other instruction $I_k$, for every $d \in W(k)$
  2762. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2763. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2764. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2765. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2766. %% \item If instruction $I_k$ is of the form \key{callq}
  2767. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2768. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2769. \end{enumerate}
  2770. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2771. the above rules to each instruction. We highlight a few of the
  2772. instructions and then refer the reader to
  2773. Figure~\ref{fig:interference-results} for all the interference
  2774. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2775. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2776. interference edges because the one live variable \code{v} is also the
  2777. destination of this instruction.
  2778. %
  2779. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2780. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2781. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2782. %
  2783. Next we skip forward to the instruction \lstinline{movq x, y}.
  2784. \begin{figure}[tbp]
  2785. \begin{quote}
  2786. \begin{tabular}{ll}
  2787. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2788. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2789. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2790. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2791. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2792. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2793. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2794. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2795. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2796. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2797. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2798. \lstinline!jmp conclusion!& no interference.
  2799. \end{tabular}
  2800. \end{quote}
  2801. \caption{Interference results for the running example.}
  2802. \label{fig:interference-results}
  2803. \end{figure}
  2804. The resulting interference graph is shown in
  2805. Figure~\ref{fig:interfere}.
  2806. \begin{figure}[tbp]
  2807. \large
  2808. \[
  2809. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2810. \node (rax) at (0,0) {$\ttm{rax}$};
  2811. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2812. \node (t1) at (0,2) {$\ttm{t}$};
  2813. \node (z) at (3,2) {$\ttm{z}$};
  2814. \node (x) at (6,2) {$\ttm{x}$};
  2815. \node (y) at (3,0) {$\ttm{y}$};
  2816. \node (w) at (6,0) {$\ttm{w}$};
  2817. \node (v) at (9,0) {$\ttm{v}$};
  2818. \draw (t1) to (rax);
  2819. \draw (t1) to (z);
  2820. \draw (z) to (y);
  2821. \draw (z) to (w);
  2822. \draw (x) to (w);
  2823. \draw (y) to (w);
  2824. \draw (v) to (w);
  2825. \draw (v) to (rsp);
  2826. \draw (w) to (rsp);
  2827. \draw (x) to (rsp);
  2828. \draw (y) to (rsp);
  2829. \path[-.,bend left=15] (z) edge node {} (rsp);
  2830. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2831. \draw (rax) to (rsp);
  2832. \end{tikzpicture}
  2833. \]
  2834. \caption{The interference graph of the example program.}
  2835. \label{fig:interfere}
  2836. \end{figure}
  2837. %% Our next concern is to choose a data structure for representing the
  2838. %% interference graph. There are many choices for how to represent a
  2839. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2840. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2841. %% data structure is to study the algorithm that uses the data structure,
  2842. %% determine what operations need to be performed, and then choose the
  2843. %% data structure that provide the most efficient implementations of
  2844. %% those operations. Often times the choice of data structure can have an
  2845. %% effect on the time complexity of the algorithm, as it does here. If
  2846. %% you skim the next section, you will see that the register allocation
  2847. %% algorithm needs to ask the graph for all of its vertices and, given a
  2848. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2849. %% correct choice of graph representation is that of an adjacency
  2850. %% list. There are helper functions in \code{utilities.rkt} for
  2851. %% representing graphs using the adjacency list representation:
  2852. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2853. %% (Appendix~\ref{appendix:utilities}).
  2854. %% %
  2855. %% \margincomment{\footnotesize To do: change to use the
  2856. %% Racket graph library. \\ --Jeremy}
  2857. %% %
  2858. %% In particular, those functions use a hash table to map each vertex to
  2859. %% the set of adjacent vertices, and the sets are represented using
  2860. %% Racket's \key{set}, which is also a hash table.
  2861. \begin{exercise}\normalfont
  2862. Implement the compiler pass named \code{build-interference} according
  2863. to the algorithm suggested above. We recommend using the \code{graph}
  2864. package to create and inspect the interference graph. The output
  2865. graph of this pass should be stored in the $\itm{info}$ field of the
  2866. program, under the key \code{conflicts}.
  2867. \end{exercise}
  2868. \section{Graph Coloring via Sudoku}
  2869. \label{sec:graph-coloring}
  2870. \index{graph coloring}
  2871. \index{Sudoku}
  2872. \index{color}
  2873. We come to the main event, mapping variables to registers (or to stack
  2874. locations in the event that we run out of registers). We need to make
  2875. sure that two variables do not get mapped to the same register if the
  2876. two variables interfere with each other. Thinking about the
  2877. interference graph, this means that adjacent vertices must be mapped
  2878. to different registers. If we think of registers as colors, the
  2879. register allocation problem becomes the widely-studied graph coloring
  2880. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2881. The reader may be more familiar with the graph coloring problem than he
  2882. or she realizes; the popular game of Sudoku is an instance of the
  2883. graph coloring problem. The following describes how to build a graph
  2884. out of an initial Sudoku board.
  2885. \begin{itemize}
  2886. \item There is one vertex in the graph for each Sudoku square.
  2887. \item There is an edge between two vertices if the corresponding squares
  2888. are in the same row, in the same column, or if the squares are in
  2889. the same $3\times 3$ region.
  2890. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2891. \item Based on the initial assignment of numbers to squares in the
  2892. Sudoku board, assign the corresponding colors to the corresponding
  2893. vertices in the graph.
  2894. \end{itemize}
  2895. If you can color the remaining vertices in the graph with the nine
  2896. colors, then you have also solved the corresponding game of Sudoku.
  2897. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2898. the corresponding graph with colored vertices. We map the Sudoku
  2899. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2900. sampling of the vertices (the colored ones) because showing edges for
  2901. all of the vertices would make the graph unreadable.
  2902. \begin{figure}[tbp]
  2903. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2904. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2905. \caption{A Sudoku game board and the corresponding colored graph.}
  2906. \label{fig:sudoku-graph}
  2907. \end{figure}
  2908. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2909. strategies to come up with an algorithm for allocating registers. For
  2910. example, one of the basic techniques for Sudoku is called Pencil
  2911. Marks. The idea is to use a process of elimination to determine what
  2912. numbers no longer make sense for a square and write down those
  2913. numbers in the square (writing very small). For example, if the number
  2914. $1$ is assigned to a square, then by process of elimination, you can
  2915. write the pencil mark $1$ in all the squares in the same row, column,
  2916. and region. Many Sudoku computer games provide automatic support for
  2917. Pencil Marks.
  2918. %
  2919. The Pencil Marks technique corresponds to the notion of
  2920. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2921. The saturation of a
  2922. vertex, in Sudoku terms, is the set of numbers that are no longer
  2923. available. In graph terminology, we have the following definition:
  2924. \begin{equation*}
  2925. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2926. \text{ and } \mathrm{color}(v) = c \}
  2927. \end{equation*}
  2928. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2929. edge with $u$.
  2930. Using the Pencil Marks technique leads to a simple strategy for
  2931. filling in numbers: if there is a square with only one possible number
  2932. left, then choose that number! But what if there are no squares with
  2933. only one possibility left? One brute-force approach is to try them
  2934. all: choose the first and if it ultimately leads to a solution,
  2935. great. If not, backtrack and choose the next possibility. One good
  2936. thing about Pencil Marks is that it reduces the degree of branching in
  2937. the search tree. Nevertheless, backtracking can be horribly time
  2938. consuming. One way to reduce the amount of backtracking is to use the
  2939. most-constrained-first heuristic. That is, when choosing a square,
  2940. always choose one with the fewest possibilities left (the vertex with
  2941. the highest saturation). The idea is that choosing highly constrained
  2942. squares earlier rather than later is better because later on there may
  2943. not be any possibilities left for those squares.
  2944. However, register allocation is easier than Sudoku because the
  2945. register allocator can map variables to stack locations when the
  2946. registers run out. Thus, it makes sense to drop backtracking in favor
  2947. of greedy search, that is, make the best choice at the time and keep
  2948. going. We still wish to minimize the number of colors needed, so
  2949. keeping the most-constrained-first heuristic is a good idea.
  2950. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2951. algorithm for register allocation based on saturation and the
  2952. most-constrained-first heuristic. It is roughly equivalent to the
  2953. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2954. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2955. Sudoku, the algorithm represents colors with integers. The integers
  2956. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2957. register allocation. The integers $k$ and larger correspond to stack
  2958. locations. The registers that are not used for register allocation,
  2959. such as \code{rax}, are assigned to negative integers. In particular,
  2960. we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  2961. One might wonder why we include registers at all in the liveness
  2962. analysis and interference graph, for example, we never allocate a
  2963. variable to \code{rax} and \code{rsp}, so it would be harmless to
  2964. leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  2965. to use register for passing arguments to functions, it will be
  2966. necessary for those registers to appear in the interference graph
  2967. because those registers will also be assigned to variables, and we
  2968. don't want those two uses to encroach on each other. Regarding
  2969. registers such as \code{rax} and \code{rsp} that are not used for
  2970. variables, we could omit them from the interference graph but that
  2971. would require adding special cases to our algorithm, which would
  2972. complicate the logic for little gain.
  2973. \begin{figure}[btp]
  2974. \centering
  2975. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2976. Algorithm: DSATUR
  2977. Input: a graph |$G$|
  2978. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2979. |$W \gets \mathrm{vertices}(G)$|
  2980. while |$W \neq \emptyset$| do
  2981. pick a vertex |$u$| from |$W$| with the highest saturation,
  2982. breaking ties randomly
  2983. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2984. |$\mathrm{color}[u] \gets c$|
  2985. |$W \gets W - \{u\}$|
  2986. \end{lstlisting}
  2987. \caption{The saturation-based greedy graph coloring algorithm.}
  2988. \label{fig:satur-algo}
  2989. \end{figure}
  2990. With the DSATUR algorithm in hand, let us return to the running
  2991. example and consider how to color the interference graph in
  2992. Figure~\ref{fig:interfere}.
  2993. %
  2994. We color the vertices for registers with their own color. For example,
  2995. \code{rax} is assigned the color $-1$ and \code{rsp} is assigned $-2$.
  2996. The vertices for variables are not yet colored, so they annotated with
  2997. a dash. We then update the saturation for vertices that are adjacent
  2998. to a register. For example, the saturation for \code{t} is $\{-1,-2\}$
  2999. because it interferes with both \code{rax} and \code{rsp}.
  3000. \[
  3001. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3002. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3003. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3004. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3005. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3006. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3007. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3008. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3009. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3010. \draw (t1) to (rax);
  3011. \draw (t1) to (z);
  3012. \draw (z) to (y);
  3013. \draw (z) to (w);
  3014. \draw (x) to (w);
  3015. \draw (y) to (w);
  3016. \draw (v) to (w);
  3017. \draw (v) to (rsp);
  3018. \draw (w) to (rsp);
  3019. \draw (x) to (rsp);
  3020. \draw (y) to (rsp);
  3021. \path[-.,bend left=15] (z) edge node {} (rsp);
  3022. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3023. \draw (rax) to (rsp);
  3024. \end{tikzpicture}
  3025. \]
  3026. The algorithm says to select a maximally saturated vertex. So we pick
  3027. $\ttm{t}$ and color it with the first available integer, which is
  3028. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3029. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3030. \[
  3031. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3032. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3033. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3034. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3035. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3036. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3037. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3038. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3039. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3040. \draw (t1) to (rax);
  3041. \draw (t1) to (z);
  3042. \draw (z) to (y);
  3043. \draw (z) to (w);
  3044. \draw (x) to (w);
  3045. \draw (y) to (w);
  3046. \draw (v) to (w);
  3047. \draw (v) to (rsp);
  3048. \draw (w) to (rsp);
  3049. \draw (x) to (rsp);
  3050. \draw (y) to (rsp);
  3051. \path[-.,bend left=15] (z) edge node {} (rsp);
  3052. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3053. \draw (rax) to (rsp);
  3054. \end{tikzpicture}
  3055. \]
  3056. We repeat the process, selecting another maximally saturated
  3057. vertex, which is \code{z}, and color it with the first available
  3058. number, which is $1$. We add $1$ to the saturation for the
  3059. neighboring vertices \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3060. \[
  3061. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3062. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3063. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3064. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3065. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3066. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3067. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3068. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3069. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3070. \draw (t1) to (rax);
  3071. \draw (t1) to (z);
  3072. \draw (z) to (y);
  3073. \draw (z) to (w);
  3074. \draw (x) to (w);
  3075. \draw (y) to (w);
  3076. \draw (v) to (w);
  3077. \draw (v) to (rsp);
  3078. \draw (w) to (rsp);
  3079. \draw (x) to (rsp);
  3080. \draw (y) to (rsp);
  3081. \path[-.,bend left=15] (z) edge node {} (rsp);
  3082. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3083. \draw (rax) to (rsp);
  3084. \end{tikzpicture}
  3085. \]
  3086. The most saturated vertices are now \code{w} and \code{y}. We color
  3087. \code{w} with the first available color, which is $0$.
  3088. \[
  3089. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3090. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3091. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3092. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3093. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3094. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3095. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3096. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3097. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3098. \draw (t1) to (rax);
  3099. \draw (t1) to (z);
  3100. \draw (z) to (y);
  3101. \draw (z) to (w);
  3102. \draw (x) to (w);
  3103. \draw (y) to (w);
  3104. \draw (v) to (w);
  3105. \draw (v) to (rsp);
  3106. \draw (w) to (rsp);
  3107. \draw (x) to (rsp);
  3108. \draw (y) to (rsp);
  3109. \path[-.,bend left=15] (z) edge node {} (rsp);
  3110. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3111. \draw (rax) to (rsp);
  3112. \end{tikzpicture}
  3113. \]
  3114. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3115. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3116. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3117. and \code{z}, whose colors are $0$ and $1$ respectively.
  3118. \[
  3119. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3120. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3121. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3122. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3123. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3124. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3125. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3126. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3127. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3128. \draw (t1) to (rax);
  3129. \draw (t1) to (z);
  3130. \draw (z) to (y);
  3131. \draw (z) to (w);
  3132. \draw (x) to (w);
  3133. \draw (y) to (w);
  3134. \draw (v) to (w);
  3135. \draw (v) to (rsp);
  3136. \draw (w) to (rsp);
  3137. \draw (x) to (rsp);
  3138. \draw (y) to (rsp);
  3139. \path[-.,bend left=15] (z) edge node {} (rsp);
  3140. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3141. \draw (rax) to (rsp);
  3142. \end{tikzpicture}
  3143. \]
  3144. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3145. \[
  3146. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3147. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3148. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3149. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3150. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3151. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3152. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3153. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3154. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3155. \draw (t1) to (rax);
  3156. \draw (t1) to (z);
  3157. \draw (z) to (y);
  3158. \draw (z) to (w);
  3159. \draw (x) to (w);
  3160. \draw (y) to (w);
  3161. \draw (v) to (w);
  3162. \draw (v) to (rsp);
  3163. \draw (w) to (rsp);
  3164. \draw (x) to (rsp);
  3165. \draw (y) to (rsp);
  3166. \path[-.,bend left=15] (z) edge node {} (rsp);
  3167. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3168. \draw (rax) to (rsp);
  3169. \end{tikzpicture}
  3170. \]
  3171. In the last step of the algorithm, we color \code{x} with $1$.
  3172. \[
  3173. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3174. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3175. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3176. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3177. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3178. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3179. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3180. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3181. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3182. \draw (t1) to (rax);
  3183. \draw (t1) to (z);
  3184. \draw (z) to (y);
  3185. \draw (z) to (w);
  3186. \draw (x) to (w);
  3187. \draw (y) to (w);
  3188. \draw (v) to (w);
  3189. \draw (v) to (rsp);
  3190. \draw (w) to (rsp);
  3191. \draw (x) to (rsp);
  3192. \draw (y) to (rsp);
  3193. \path[-.,bend left=15] (z) edge node {} (rsp);
  3194. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3195. \draw (rax) to (rsp);
  3196. \end{tikzpicture}
  3197. \]
  3198. With the coloring complete, we finalize the assignment of variables to
  3199. registers and stack locations. Recall that if we have $k$ registers to
  3200. use for allocation, we map the first $k$ colors to registers and the
  3201. rest to stack locations. Suppose for the moment that we have just one
  3202. register to use for register allocation, \key{rcx}. Then the following
  3203. maps of colors to registers and stack allocations.
  3204. \[
  3205. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3206. \]
  3207. Putting this mapping together with the above coloring of the
  3208. variables, we arrive at the following assignment.
  3209. \begin{gather*}
  3210. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3211. \ttm{w} \mapsto \key{\%rcx}, \,
  3212. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3213. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3214. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3215. \ttm{t} \mapsto \key{\%rcx} \}
  3216. \end{gather*}
  3217. Applying this assignment to our running example, on the left, yields
  3218. the program on the right.
  3219. % why frame size of 32? -JGS
  3220. \begin{center}
  3221. \begin{minipage}{0.3\textwidth}
  3222. \begin{lstlisting}
  3223. movq $1, v
  3224. movq $42, w
  3225. movq v, x
  3226. addq $7, x
  3227. movq x, y
  3228. movq x, z
  3229. addq w, z
  3230. movq y, t
  3231. negq t
  3232. movq z, %rax
  3233. addq t, %rax
  3234. jmp conclusion
  3235. \end{lstlisting}
  3236. \end{minipage}
  3237. $\Rightarrow\qquad$
  3238. \begin{minipage}{0.45\textwidth}
  3239. \begin{lstlisting}
  3240. movq $1, %rcx
  3241. movq $42, %rcx
  3242. movq %rcx, -8(%rbp)
  3243. addq $7, -8(%rbp)
  3244. movq -8(%rbp), -16(%rbp)
  3245. movq -8(%rbp), -8(%rbp)
  3246. addq %rcx, -8(%rbp)
  3247. movq -16(%rbp), %rcx
  3248. negq %rcx
  3249. movq -8(%rbp), %rax
  3250. addq %rcx, %rax
  3251. jmp conclusion
  3252. \end{lstlisting}
  3253. \end{minipage}
  3254. \end{center}
  3255. The resulting program is almost an x86 program. The remaining step is
  3256. the patch instructions pass. In this example, the trivial move of
  3257. \code{-8(\%rbp)} to itself is deleted and the addition of
  3258. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3259. \code{rax} as follows.
  3260. \begin{lstlisting}
  3261. movq -8(%rbp), %rax
  3262. addq %rax, -16(%rbp)
  3263. \end{lstlisting}
  3264. We recommend creating a helper function named \code{color-graph} that
  3265. takes an interference graph and a list of all the variables in the
  3266. program. This function should return a mapping of variables to their
  3267. colors (represented as natural numbers). By creating this helper
  3268. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3269. when you add support for functions. To prioritize the processing of
  3270. highly saturated nodes inside your \code{color-graph} function, we
  3271. recommend using the priority queue data structure (see the side bar on
  3272. the right). Note that you will also need to maintain a mapping from
  3273. variables to their ``handles'' in the priority queue so that you can
  3274. notify the priority queue when their saturation changes.
  3275. \begin{wrapfigure}[23]{r}[1.0in]{0.6\textwidth}
  3276. \small
  3277. \begin{tcolorbox}[title=Priority Queue]
  3278. A \emph{priority queue} is a collection of items in which the
  3279. removal of items is governed by priority. In a ``min'' queue,
  3280. lower priority items are removed first. An implementation is in
  3281. \code{priority\_queue.rkt} of the support code. \index{priority
  3282. queue} \index{minimum priority queue}
  3283. \begin{description}
  3284. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3285. priority queue that uses the $\itm{cmp}$ predicate to determine
  3286. whether its first argument has lower or equal priority to its
  3287. second argument.
  3288. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3289. items in the queue.
  3290. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3291. the item into the queue and returns a handle for the item in the
  3292. queue.
  3293. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3294. the lowest priority.
  3295. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3296. notifies the queue that the priority has decreased for the item
  3297. associated with the given handle.
  3298. \end{description}
  3299. \end{tcolorbox}
  3300. \end{wrapfigure}
  3301. Once you have obtained the coloring from \code{color-graph}, you can
  3302. assign the variables to registers or stack locations and then reuse
  3303. code from the \code{assign-homes} pass from
  3304. Section~\ref{sec:assign-r1} to replace the variables with their
  3305. assigned location.
  3306. \begin{exercise}\normalfont
  3307. Implement the compiler pass \code{allocate-registers}, which should
  3308. come after the \code{build-interference} pass. The three new passes
  3309. described in this chapter replace the \code{assign-homes} pass of
  3310. Section~\ref{sec:assign-r1}.
  3311. %
  3312. Test your updated compiler by creating new example programs that
  3313. exercise all of the register allocation algorithm, such as forcing
  3314. variables to be spilled to the stack.
  3315. \end{exercise}
  3316. \section{Print x86}
  3317. \label{sec:print-x86-reg-alloc}
  3318. \index{calling conventions}
  3319. \index{prelude}\index{conclusion}
  3320. Recall that the \code{print-x86} pass generates the prelude and
  3321. conclusion instructions for the \code{main} function.
  3322. %
  3323. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3324. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3325. reason for this is that our \code{main} function must adhere to the
  3326. x86 calling conventions that we described in
  3327. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3328. allocator assigned variables to other callee-saved registers
  3329. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3330. saved to the stack in the prelude and restored in the conclusion. The
  3331. simplest approach is to save and restore all of the callee-saved
  3332. registers. The more efficient approach is to keep track of which
  3333. callee-saved registers were used and only save and restore
  3334. them. Either way, make sure to take this use of stack space into
  3335. account when you are calculating the size of the frame and adjusting
  3336. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3337. frame needs to be a multiple of 16 bytes!
  3338. An overview of all of the passes involved in register allocation is
  3339. shown in Figure~\ref{fig:reg-alloc-passes}.
  3340. \begin{figure}[tbp]
  3341. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3342. \node (R1) at (0,2) {\large $R_1$};
  3343. \node (R1-2) at (3,2) {\large $R_1$};
  3344. \node (R1-3) at (6,2) {\large $R_1$};
  3345. \node (C0-1) at (3,0) {\large $C_0$};
  3346. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3347. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3348. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3349. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3350. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3351. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3352. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3353. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3354. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3355. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3356. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3357. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3358. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3359. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3360. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3361. \end{tikzpicture}
  3362. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3363. \label{fig:reg-alloc-passes}
  3364. \end{figure}
  3365. \section{Challenge: Move Biasing}
  3366. \label{sec:move-biasing}
  3367. \index{move biasing}
  3368. This section describes an optional enhancement to register allocation
  3369. for those students who are looking for an extra challenge or who have
  3370. a deeper interest in register allocation.
  3371. We return to the running example, but we remove the supposition that
  3372. we only have one register to use. So we have the following mapping of
  3373. color numbers to registers.
  3374. \[
  3375. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3376. \]
  3377. Using the same assignment of variables to color numbers that was
  3378. produced by the register allocator described in the last section, we
  3379. get the following program.
  3380. \begin{minipage}{0.3\textwidth}
  3381. \begin{lstlisting}
  3382. movq $1, v
  3383. movq $42, w
  3384. movq v, x
  3385. addq $7, x
  3386. movq x, y
  3387. movq x, z
  3388. addq w, z
  3389. movq y, t
  3390. negq t
  3391. movq z, %rax
  3392. addq t, %rax
  3393. jmp conclusion
  3394. \end{lstlisting}
  3395. \end{minipage}
  3396. $\Rightarrow\qquad$
  3397. \begin{minipage}{0.45\textwidth}
  3398. \begin{lstlisting}
  3399. movq $1, %rcx
  3400. movq $42, $rbx
  3401. movq %rcx, %rcx
  3402. addq $7, %rcx
  3403. movq %rcx, %rdx
  3404. movq %rcx, %rcx
  3405. addq %rbx, %rcx
  3406. movq %rdx, %rbx
  3407. negq %rbx
  3408. movq %rcx, %rax
  3409. addq %rbx, %rax
  3410. jmp conclusion
  3411. \end{lstlisting}
  3412. \end{minipage}
  3413. In the above output code there are two \key{movq} instructions that
  3414. can be removed because their source and target are the same. However,
  3415. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3416. register, we could instead remove three \key{movq} instructions. We
  3417. can accomplish this by taking into account which variables appear in
  3418. \key{movq} instructions with which other variables.
  3419. We say that two variables $p$ and $q$ are \emph{move
  3420. related}\index{move related} if they participate together in a
  3421. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3422. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3423. for a variable, it should prefer a color that has already been used
  3424. for a move-related variable (assuming that they do not interfere). Of
  3425. course, this preference should not override the preference for
  3426. registers over stack locations. This preference should be used as a
  3427. tie breaker when choosing between registers or when choosing between
  3428. stack locations.
  3429. We recommend representing the move relationships in a graph, similar
  3430. to how we represented interference. The following is the \emph{move
  3431. graph} for our running example.
  3432. \[
  3433. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3434. \node (rax) at (0,0) {$\ttm{rax}$};
  3435. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3436. \node (t) at (0,2) {$\ttm{t}$};
  3437. \node (z) at (3,2) {$\ttm{z}$};
  3438. \node (x) at (6,2) {$\ttm{x}$};
  3439. \node (y) at (3,0) {$\ttm{y}$};
  3440. \node (w) at (6,0) {$\ttm{w}$};
  3441. \node (v) at (9,0) {$\ttm{v}$};
  3442. \draw (v) to (x);
  3443. \draw (x) to (y);
  3444. \draw (x) to (z);
  3445. \draw (y) to (t);
  3446. \end{tikzpicture}
  3447. \]
  3448. Now we replay the graph coloring, pausing to see the coloring of
  3449. \code{y}. Recall the following configuration. The most saturated vertices
  3450. were \code{w} and \code{y}.
  3451. \[
  3452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3453. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3454. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3455. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3456. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3457. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3458. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3459. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3460. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3461. \draw (t1) to (rax);
  3462. \draw (t1) to (z);
  3463. \draw (z) to (y);
  3464. \draw (z) to (w);
  3465. \draw (x) to (w);
  3466. \draw (y) to (w);
  3467. \draw (v) to (w);
  3468. \draw (v) to (rsp);
  3469. \draw (w) to (rsp);
  3470. \draw (x) to (rsp);
  3471. \draw (y) to (rsp);
  3472. \path[-.,bend left=15] (z) edge node {} (rsp);
  3473. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3474. \draw (rax) to (rsp);
  3475. \end{tikzpicture}
  3476. \]
  3477. %
  3478. Last time we chose to color \code{w} with $0$. But this time we see
  3479. that \code{w} is not move related to any vertex, but \code{y} is move
  3480. related to \code{t}. So we choose to color \code{y} the same color as
  3481. \code{t}, $0$.
  3482. \[
  3483. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3484. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3485. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3486. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3487. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3488. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3489. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3490. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3491. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3492. \draw (t1) to (rax);
  3493. \draw (t1) to (z);
  3494. \draw (z) to (y);
  3495. \draw (z) to (w);
  3496. \draw (x) to (w);
  3497. \draw (y) to (w);
  3498. \draw (v) to (w);
  3499. \draw (v) to (rsp);
  3500. \draw (w) to (rsp);
  3501. \draw (x) to (rsp);
  3502. \draw (y) to (rsp);
  3503. \path[-.,bend left=15] (z) edge node {} (rsp);
  3504. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3505. \draw (rax) to (rsp);
  3506. \end{tikzpicture}
  3507. \]
  3508. Now \code{w} is the most saturated, so we color it $2$.
  3509. \[
  3510. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3511. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3512. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3513. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3514. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3515. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3516. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3517. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3518. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3519. \draw (t1) to (rax);
  3520. \draw (t1) to (z);
  3521. \draw (z) to (y);
  3522. \draw (z) to (w);
  3523. \draw (x) to (w);
  3524. \draw (y) to (w);
  3525. \draw (v) to (w);
  3526. \draw (v) to (rsp);
  3527. \draw (w) to (rsp);
  3528. \draw (x) to (rsp);
  3529. \draw (y) to (rsp);
  3530. \path[-.,bend left=15] (z) edge node {} (rsp);
  3531. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3532. \draw (rax) to (rsp);
  3533. \end{tikzpicture}
  3534. \]
  3535. At this point, vertices \code{x} and \code{v} are most saturated, but
  3536. \code{x} is move related to \code{y} and \code{z}, so we color
  3537. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3538. \[
  3539. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3540. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3541. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3542. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3543. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3544. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3545. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3546. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3547. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3548. \draw (t1) to (rax);
  3549. \draw (t) to (z);
  3550. \draw (z) to (y);
  3551. \draw (z) to (w);
  3552. \draw (x) to (w);
  3553. \draw (y) to (w);
  3554. \draw (v) to (w);
  3555. \draw (v) to (rsp);
  3556. \draw (w) to (rsp);
  3557. \draw (x) to (rsp);
  3558. \draw (y) to (rsp);
  3559. \path[-.,bend left=15] (z) edge node {} (rsp);
  3560. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3561. \draw (rax) to (rsp);
  3562. \end{tikzpicture}
  3563. \]
  3564. So we have the following assignment of variables to registers.
  3565. \begin{gather*}
  3566. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3567. \ttm{w} \mapsto \key{\%rdx}, \,
  3568. \ttm{x} \mapsto \key{\%rbx}, \,
  3569. \ttm{y} \mapsto \key{\%rbx}, \,
  3570. \ttm{z} \mapsto \key{\%rcx}, \,
  3571. \ttm{t} \mapsto \key{\%rbx} \}
  3572. \end{gather*}
  3573. We apply this register assignment to the running example, on the left,
  3574. to obtain the code in the middle. The \code{patch-instructions} then
  3575. removes the three trivial moves from \key{rbx} to \key{rbx} to obtain
  3576. the code on the right.
  3577. \begin{minipage}{0.25\textwidth}
  3578. \begin{lstlisting}
  3579. movq $1, v
  3580. movq $42, w
  3581. movq v, x
  3582. addq $7, x
  3583. movq x, y
  3584. movq x, z
  3585. addq w, z
  3586. movq y, t
  3587. negq t
  3588. movq z, %rax
  3589. addq t, %rax
  3590. jmp conclusion
  3591. \end{lstlisting}
  3592. \end{minipage}
  3593. $\Rightarrow\qquad$
  3594. \begin{minipage}{0.25\textwidth}
  3595. \begin{lstlisting}
  3596. movq $1, %rbx
  3597. movq $42, %rdx
  3598. movq %rbx, %rbx
  3599. addq $7, %rbx
  3600. movq %rbx, %rbx
  3601. movq %rbx, %rcx
  3602. addq %rdx, %rcx
  3603. movq %rbx, %rbx
  3604. negq %rbx
  3605. movq %rcx, %rax
  3606. addq %rbx, %rax
  3607. jmp conclusion
  3608. \end{lstlisting}
  3609. \end{minipage}
  3610. $\Rightarrow\qquad$
  3611. \begin{minipage}{0.25\textwidth}
  3612. \begin{lstlisting}
  3613. movq $1, %rbx
  3614. movq $42, %rdx
  3615. addq $7, %rbx
  3616. movq %rbx, %rcx
  3617. addq %rdx, %rcx
  3618. negq %rbx
  3619. movq %rcx, %rax
  3620. addq %rbx, %rax
  3621. jmp conclusion
  3622. \end{lstlisting}
  3623. \end{minipage}
  3624. \begin{exercise}\normalfont
  3625. Change your implementation of \code{allocate-registers} to take move
  3626. biasing into account. Make sure that your compiler still passes all of
  3627. the previous tests. Create two new tests that include at least one
  3628. opportunity for move biasing and visually inspect the output x86
  3629. programs to make sure that your move biasing is working properly.
  3630. \end{exercise}
  3631. \margincomment{\footnotesize To do: another neat challenge would be to do
  3632. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3633. \section{Output of the Running Example}
  3634. \label{sec:reg-alloc-output}
  3635. \index{prelude}\index{conclusion}
  3636. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3637. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3638. and move biasing. To demonstrate both the use of registers and the
  3639. stack, we have limited the register allocator to use just two
  3640. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3641. \code{main} function, we push \code{rbx} onto the stack because it is
  3642. a callee-saved register and it was assigned to variable by the
  3643. register allocator. We subtract \code{8} from the \code{rsp} at the
  3644. end of the prelude to reserve space for the one spilled variable.
  3645. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3646. Moving on the the \code{start} block, we see how the registers were
  3647. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3648. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3649. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3650. that the prelude saved the callee-save register \code{rbx} onto the
  3651. stack. The spilled variables must be placed lower on the stack than
  3652. the saved callee-save registers, so in this case \code{w} is placed at
  3653. \code{-16(\%rbp)}.
  3654. In the \code{conclusion}, we undo the work that was done in the
  3655. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3656. spilled variables), then we pop the old values of \code{rbx} and
  3657. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3658. return control to the operating system.
  3659. \begin{figure}[tbp]
  3660. % s0_28.rkt
  3661. % (use-minimal-set-of-registers! #t)
  3662. % and only rbx rcx
  3663. % tmp 0 rbx
  3664. % z 1 rcx
  3665. % y 0 rbx
  3666. % w 2 16(%rbp)
  3667. % v 0 rbx
  3668. % x 0 rbx
  3669. \begin{lstlisting}
  3670. start:
  3671. movq $1, %rbx
  3672. movq $42, -16(%rbp)
  3673. addq $7, %rbx
  3674. movq %rbx, %rcx
  3675. addq -16(%rbp), %rcx
  3676. negq %rbx
  3677. movq %rcx, %rax
  3678. addq %rbx, %rax
  3679. jmp conclusion
  3680. .globl main
  3681. main:
  3682. pushq %rbp
  3683. movq %rsp, %rbp
  3684. pushq %rbx
  3685. subq $8, %rsp
  3686. jmp start
  3687. conclusion:
  3688. addq $8, %rsp
  3689. popq %rbx
  3690. popq %rbp
  3691. retq
  3692. \end{lstlisting}
  3693. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3694. \label{fig:running-example-x86}
  3695. \end{figure}
  3696. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3697. \chapter{Booleans and Control Flow}
  3698. \label{ch:bool-types}
  3699. \index{Boolean}
  3700. \index{control flow}
  3701. \index{conditional expression}
  3702. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3703. integers. In this chapter we add a second kind of value, the Booleans,
  3704. to create the $R_2$ language. The Boolean values \emph{true} and
  3705. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3706. Racket. The $R_2$ language includes several operations that involve
  3707. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3708. conditional \key{if} expression. With the addition of \key{if}
  3709. expressions, programs can have non-trivial control flow which which
  3710. significantly impacts the \code{explicate-control} and the liveness
  3711. analysis for register allocation. Also, because we now have two kinds
  3712. of values, we need to handle programs that apply an operation to the
  3713. wrong kind of value, such as \code{(not 1)}.
  3714. There are two language design options for such situations. One option
  3715. is to signal an error and the other is to provide a wider
  3716. interpretation of the operation. The Racket language uses a mixture of
  3717. these two options, depending on the operation and the kind of
  3718. value. For example, the result of \code{(not 1)} in Racket is
  3719. \code{\#f} because Racket treats non-zero integers as if they were
  3720. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3721. error in Racket stating that \code{car} expects a pair.
  3722. The Typed Racket language makes similar design choices as Racket,
  3723. except much of the error detection happens at compile time instead of
  3724. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3725. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3726. reports a compile-time error because Typed Racket expects the type of
  3727. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3728. For the $R_2$ language we choose to be more like Typed Racket in that
  3729. we perform type checking during compilation. In
  3730. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3731. is, how to compile a dynamically typed language like Racket. The
  3732. $R_2$ language is a subset of Typed Racket but by no means includes
  3733. all of Typed Racket. For many operations we take a narrower
  3734. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3735. This chapter is organized as follows. We begin by defining the syntax
  3736. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3737. then introduce the idea of type checking and build a type checker for
  3738. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3739. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3740. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3741. how our compiler passes need to change to accommodate Booleans and
  3742. conditional control flow.
  3743. \section{The $R_2$ Language}
  3744. \label{sec:r2-lang}
  3745. The concrete syntax of the $R_2$ language is defined in
  3746. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3747. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3748. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3749. and the conditional \code{if} expression. Also, we expand the
  3750. operators to include
  3751. \begin{enumerate}
  3752. \item subtraction on integers,
  3753. \item the logical operators \key{and}, \key{or} and \key{not},
  3754. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3755. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3756. comparing integers.
  3757. \end{enumerate}
  3758. We reorganize the abstract syntax for the primitive operations in
  3759. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3760. them. This means that the grammar no longer checks whether the arity
  3761. of an operators matches the number of arguments. That responsibility
  3762. is moved to the type checker for $R_2$, which we introduce in
  3763. Section~\ref{sec:type-check-r2}.
  3764. \begin{figure}[tp]
  3765. \centering
  3766. \fbox{
  3767. \begin{minipage}{0.96\textwidth}
  3768. \[
  3769. \begin{array}{lcl}
  3770. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3771. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3772. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3773. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3774. &\mid& \itm{bool}
  3775. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3776. \mid (\key{not}\;\Exp) \\
  3777. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3778. R_2 &::=& \Exp
  3779. \end{array}
  3780. \]
  3781. \end{minipage}
  3782. }
  3783. \caption{The concrete syntax of $R_2$, extending $R_1$
  3784. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3785. \label{fig:r2-concrete-syntax}
  3786. \end{figure}
  3787. \begin{figure}[tp]
  3788. \centering
  3789. \fbox{
  3790. \begin{minipage}{0.96\textwidth}
  3791. \[
  3792. \begin{array}{lcl}
  3793. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3794. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3795. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3796. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3797. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3798. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3799. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3800. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3801. \end{array}
  3802. \]
  3803. \end{minipage}
  3804. }
  3805. \caption{The abstract syntax of $R_2$.}
  3806. \label{fig:r2-syntax}
  3807. \end{figure}
  3808. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3809. the parts that are the same as the interpreter for $R_1$
  3810. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3811. evaluate to the corresponding Boolean values. The conditional
  3812. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3813. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3814. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3815. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3816. you might expect, but note that the \code{and} operation is
  3817. short-circuiting. That is, given the expression
  3818. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3819. $e_1$ evaluates to \code{\#f}.
  3820. With the increase in the number of primitive operations, the
  3821. interpreter code for them could become repetitive without some
  3822. care. In Figure~\ref{fig:interp-R2} we factor out the different parts
  3823. of the code for primitive operations into the \code{interp-op}
  3824. function and the similar parts of the code into the match clause for
  3825. \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3826. \code{interp-op} for the \code{and} operation because of the
  3827. short-circuiting behavior in the order of evaluation of its arguments.
  3828. \begin{figure}[tbp]
  3829. \begin{lstlisting}
  3830. (define (interp-op op)
  3831. (match op
  3832. ...
  3833. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3834. ['eq? (lambda (v1 v2)
  3835. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3836. (and (boolean? v1) (boolean? v2)))
  3837. (eq? v1 v2)]))]
  3838. ['< (lambda (v1 v2)
  3839. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3840. ['<= (lambda (v1 v2)
  3841. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3842. ['> (lambda (v1 v2)
  3843. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3844. ['>= (lambda (v1 v2)
  3845. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3846. [else (error 'interp-op "unknown operator")]))
  3847. (define (interp-exp env)
  3848. (lambda (e)
  3849. (define recur (interp-exp env))
  3850. (match e
  3851. ...
  3852. [(Bool b) b]
  3853. [(If cnd thn els)
  3854. (define b (recur cnd))
  3855. (match b
  3856. [#t (recur thn)]
  3857. [#f (recur els)])]
  3858. [(Prim 'and (list e1 e2))
  3859. (define v1 (recur e1))
  3860. (match v1
  3861. [#t (match (recur e2) [#t #t] [#f #f])]
  3862. [#f #f])]
  3863. [(Prim op args)
  3864. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3865. )))
  3866. (define (interp-R2 p)
  3867. (match p
  3868. [(Program info e)
  3869. ((interp-exp '()) e)]
  3870. ))
  3871. \end{lstlisting}
  3872. \caption{Interpreter for the $R_2$ language.}
  3873. \label{fig:interp-R2}
  3874. \end{figure}
  3875. \section{Type Checking $R_2$ Programs}
  3876. \label{sec:type-check-r2}
  3877. \index{type checking}
  3878. \index{semantic analysis}
  3879. It is helpful to think about type checking in two complementary
  3880. ways. A type checker predicts the type of value that will be produced
  3881. by each expression in the program. For $R_2$, we have just two types,
  3882. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3883. \begin{lstlisting}
  3884. (+ 10 (- (+ 12 20)))
  3885. \end{lstlisting}
  3886. produces an \key{Integer} while
  3887. \begin{lstlisting}
  3888. (and (not #f) #t)
  3889. \end{lstlisting}
  3890. produces a \key{Boolean}.
  3891. Another way to think about type checking is that it enforces a set of
  3892. rules about which operators can be applied to which kinds of
  3893. values. For example, our type checker for $R_2$ will signal an error
  3894. for the below expression because, as we have seen above, the
  3895. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3896. checker enforces the rule that the argument of \code{not} must be a
  3897. \key{Boolean}.
  3898. \begin{lstlisting}
  3899. (not (+ 10 (- (+ 12 20))))
  3900. \end{lstlisting}
  3901. The type checker for $R_2$ is a structurally recursive function over
  3902. the AST. Figure~\ref{fig:type-check-R2} defines the
  3903. \code{type-check-exp} function. The code for the type checker is in
  3904. the file \code{type-check-R2.rkt} of the support code.
  3905. %
  3906. Given an input expression \code{e}, the type checker either returns a
  3907. type (\key{Integer} or \key{Boolean}) or it signals an error. The
  3908. type of an integer literal is \code{Integer} and the type of a Boolean
  3909. literal is \code{Boolean}. To handle variables, the type checker uses
  3910. the environment \code{env} to map variables to types. Consider the
  3911. clause for \key{let}. We type check the initializing expression to
  3912. obtain its type \key{T} and then associate type \code{T} with the
  3913. variable \code{x} in the environment used to type check the body of
  3914. the \key{let}. Thus, when the type checker encounters a use of
  3915. variable \code{x}, it can find its type in the environment.
  3916. \begin{figure}[tbp]
  3917. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3918. (define (type-check-exp env)
  3919. (lambda (e)
  3920. (match e
  3921. [(Var x)
  3922. (let ([t (dict-ref env x)])
  3923. (values (Var x) t))]
  3924. [(Int n) (values (Int n) 'Integer)]
  3925. [(Bool b) (values (Bool b) 'Boolean)]
  3926. [(Let x e body)
  3927. (define-values (e^ Te) ((type-check-exp env) e))
  3928. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  3929. (values (Let x e^ b) Tb)]
  3930. [(If cnd thn els)
  3931. (define-values (c Tc) ((type-check-exp env) cnd))
  3932. (define-values (t Tt) ((type-check-exp env) thn))
  3933. (define-values (e Te) ((type-check-exp env) els))
  3934. (unless (type-equal? Tc 'Boolean)
  3935. (error 'type-check-exp "condition should be Boolean, not ~a" Tc))
  3936. (unless (type-equal? Tt Te)
  3937. (error 'type-check-exp "types of branches not equal, ~a != ~a" Tt Te))
  3938. (values (If c t e) Te)]
  3939. [(Prim 'eq? (list e1 e2))
  3940. (define-values (e1^ T1) ((type-check-exp env) e1))
  3941. (define-values (e2^ T2) ((type-check-exp env) e2))
  3942. (unless (type-equal? T1 T2)
  3943. (error 'type-check-exp "argument types of eq?: ~a != ~a" T1 T2))
  3944. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  3945. [(Prim op es)
  3946. (define-values (new-es ts)
  3947. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  3948. (define t-ret (type-check-op op ts))
  3949. (values (Prim op new-es) t-ret)]
  3950. [else
  3951. (error 'type-check-exp "couldn't match" e)])))
  3952. (define (type-check-R2 e)
  3953. (match e
  3954. [(Program info body)
  3955. (define-values (body^ Tb) ((type-check-exp '()) body))
  3956. (unless (type-equal? Tb 'Integer)
  3957. (error 'type-check-R2 "result type must be Integer, not ~a" Tb))
  3958. (Program info body^)]
  3959. [else (error 'type-check-R2 "couldn't match ~a" e)]))
  3960. \end{lstlisting}
  3961. \caption{Type checker for the $R_2$ language.}
  3962. \label{fig:type-check-R2}
  3963. \end{figure}
  3964. Figure~\ref{fig:type-check-aux-R2} defines three auxiliary functions
  3965. that are used in the type checker. The \code{operator-types} function
  3966. defines a dictionary that maps the operator names to their parameter
  3967. and return types. The \code{type-equal?} function determines whether
  3968. two types are equal, which for now simply dispatches to \code{equal?}
  3969. (deep equality). The \code{type-check-op} function looks up the
  3970. operator in the \code{operator-types} dictionary and then checks
  3971. whether the argument types are equal to the parameter types. The
  3972. result is the return type of the operator.
  3973. \begin{figure}[tbp]
  3974. \begin{lstlisting}
  3975. (define (operator-types)
  3976. '((+ . ((Integer Integer) . Integer))
  3977. (- . ((Integer Integer) . Integer))
  3978. (and . ((Boolean Boolean) . Boolean))
  3979. (or . ((Boolean Boolean) . Boolean))
  3980. (< . ((Integer Integer) . Boolean))
  3981. (<= . ((Integer Integer) . Boolean))
  3982. (> . ((Integer Integer) . Boolean))
  3983. (>= . ((Integer Integer) . Boolean))
  3984. (- . ((Integer) . Integer))
  3985. (not . ((Boolean) . Boolean))
  3986. (read . (() . Integer))
  3987. ))
  3988. (define (type-equal? t1 t2)
  3989. (equal? t1 t2))
  3990. (define (type-check-op op arg-types)
  3991. (match (dict-ref (operator-types) op)
  3992. [`(,param-types . ,return-type)
  3993. (for ([at arg-types] [pt param-types])
  3994. (unless (type-equal? at pt)
  3995. (error 'type-check-op
  3996. "argument and parameter mismatch, ~a != ~a" at pt)))
  3997. return-type]
  3998. [else
  3999. (error 'type-check-op "unrecognized operator ~a" op)]))
  4000. \end{lstlisting}
  4001. \caption{Auxiliary functions for type checking.}
  4002. \label{fig:type-check-aux-R2}
  4003. \end{figure}
  4004. \begin{exercise}\normalfont
  4005. Create 10 new example programs in $R_2$. Half of the example programs
  4006. should have a type error. For those programs, to signal that a type
  4007. error is expected, create an empty file with the same base name but
  4008. with file extension \code{.tyerr}. For example, if the test
  4009. \code{r2\_14.rkt} is expected to error, then create an empty file
  4010. named \code{r2\_14.tyerr}. The other half of the example programs
  4011. should not have type errors. Note that if the type checker does not
  4012. signal an error for a program, then interpreting that program should
  4013. not encounter an error.
  4014. \end{exercise}
  4015. \section{Shrink the $R_2$ Language}
  4016. \label{sec:shrink-r2}
  4017. The $R_2$ language includes several operators that are easily
  4018. expressible in terms of other operators. For example, subtraction is
  4019. expressible in terms of addition and negation.
  4020. \[
  4021. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4022. \]
  4023. Several of the comparison operations are expressible in terms of
  4024. less-than and logical negation.
  4025. \[
  4026. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4027. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4028. \]
  4029. The \key{let} is needed in the above translation to ensure that
  4030. expression $e_1$ is evaluated before $e_2$.
  4031. By performing these translations near the front-end of the compiler,
  4032. the later passes of the compiler do not need to deal with these
  4033. constructs, making those passes shorter. On the other hand, sometimes
  4034. these translations make it more difficult to generate the most
  4035. efficient code with respect to the number of instructions. However,
  4036. these differences typically do not affect the number of accesses to
  4037. memory, which is the primary factor that determines execution time on
  4038. modern computer architectures.
  4039. \begin{exercise}\normalfont
  4040. Implement the pass \code{shrink} that removes subtraction,
  4041. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  4042. by translating them to other constructs in $R_2$. Create tests to
  4043. make sure that the behavior of all of these constructs stays the
  4044. same after translation.
  4045. \end{exercise}
  4046. \section{The x86$_1$ Language}
  4047. \label{sec:x86-1}
  4048. \index{x86}
  4049. To implement the new logical operations, the comparison operations,
  4050. and the \key{if} expression, we need to delve further into the x86
  4051. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  4052. the concrete and abstract syntax for a larger subset of x86 that
  4053. includes instructions for logical operations, comparisons, and
  4054. conditional jumps.
  4055. One small challenge is that x86 does not provide an instruction that
  4056. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  4057. However, the \code{xorq} instruction can be used to encode \code{not}.
  4058. The \key{xorq} instruction takes two arguments, performs a pairwise
  4059. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  4060. and writes the results into its second argument. Recall the truth
  4061. table for exclusive-or:
  4062. \begin{center}
  4063. \begin{tabular}{l|cc}
  4064. & 0 & 1 \\ \hline
  4065. 0 & 0 & 1 \\
  4066. 1 & 1 & 0
  4067. \end{tabular}
  4068. \end{center}
  4069. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4070. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4071. for the bit $1$, the result is the opposite of the second bit. Thus,
  4072. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4073. the first argument:
  4074. \[
  4075. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4076. \qquad\Rightarrow\qquad
  4077. \begin{array}{l}
  4078. \key{movq}~ \Arg\key{,} \Var\\
  4079. \key{xorq}~ \key{\$1,} \Var
  4080. \end{array}
  4081. \]
  4082. \begin{figure}[tp]
  4083. \fbox{
  4084. \begin{minipage}{0.96\textwidth}
  4085. \[
  4086. \begin{array}{lcl}
  4087. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4088. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4089. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4090. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4091. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4092. \key{subq} \; \Arg\key{,} \Arg \mid
  4093. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4094. && \gray{ \key{callq} \; \itm{label} \mid
  4095. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4096. && \gray{ \itm{label}\key{:}\; \Instr }
  4097. \mid \key{xorq}~\Arg\key{,}~\Arg
  4098. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4099. && \key{set}cc~\Arg
  4100. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4101. \mid \key{j}cc~\itm{label}
  4102. \\
  4103. x86_1 &::= & \gray{ \key{.globl main} }\\
  4104. & & \gray{ \key{main:} \; \Instr\ldots }
  4105. \end{array}
  4106. \]
  4107. \end{minipage}
  4108. }
  4109. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  4110. \label{fig:x86-1-concrete}
  4111. \end{figure}
  4112. \begin{figure}[tp]
  4113. \fbox{
  4114. \begin{minipage}{0.96\textwidth}
  4115. \small
  4116. \[
  4117. \begin{array}{lcl}
  4118. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4119. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4120. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4121. \mid \BYTEREG{\itm{bytereg}} \\
  4122. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4123. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4124. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4125. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4126. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4127. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4128. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4129. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4130. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4131. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4132. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4133. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4134. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4135. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4136. \end{array}
  4137. \]
  4138. \end{minipage}
  4139. }
  4140. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4141. \label{fig:x86-1}
  4142. \end{figure}
  4143. Next we consider the x86 instructions that are relevant for compiling
  4144. the comparison operations. The \key{cmpq} instruction compares its two
  4145. arguments to determine whether one argument is less than, equal, or
  4146. greater than the other argument. The \key{cmpq} instruction is unusual
  4147. regarding the order of its arguments and where the result is
  4148. placed. The argument order is backwards: if you want to test whether
  4149. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4150. \key{cmpq} is placed in the special EFLAGS register. This register
  4151. cannot be accessed directly but it can be queried by a number of
  4152. instructions, including the \key{set} instruction. The \key{set}
  4153. instruction puts a \key{1} or \key{0} into its destination depending
  4154. on whether the comparison came out according to the condition code
  4155. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4156. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4157. The \key{set} instruction has an annoying quirk in that its
  4158. destination argument must be single byte register, such as \code{al}
  4159. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4160. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4161. then be used to move from a single byte register to a normal 64-bit
  4162. register.
  4163. The x86 instruction for conditional jump are relevant to the
  4164. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4165. updates the program counter to point to the instruction after the
  4166. indicated label depending on whether the result in the EFLAGS register
  4167. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4168. instruction falls through to the next instruction. The abstract
  4169. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4170. that it separates the instruction name from the condition code. For
  4171. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4172. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4173. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4174. instruction to set the EFLAGS register.
  4175. \section{The $C_1$ Intermediate Language}
  4176. \label{sec:c1}
  4177. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4178. we need to grow that intermediate language to handle the new features
  4179. in $R_2$: Booleans and conditional expressions.
  4180. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4181. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4182. particular, we add logical and comparison operators to the $\Exp$
  4183. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4184. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4185. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4186. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4187. sequence of statements may now end with a \code{goto} or a conditional
  4188. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4189. depending on the outcome of the comparison. In
  4190. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4191. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4192. and \key{goto}'s.
  4193. \begin{figure}[tbp]
  4194. \fbox{
  4195. \begin{minipage}{0.96\textwidth}
  4196. \small
  4197. \[
  4198. \begin{array}{lcl}
  4199. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4200. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4201. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4202. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4203. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4204. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4205. \mid \key{goto}~\itm{label}\key{;}\\
  4206. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4207. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4208. \end{array}
  4209. \]
  4210. \end{minipage}
  4211. }
  4212. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4213. \label{fig:c1-concrete-syntax}
  4214. \end{figure}
  4215. \begin{figure}[tp]
  4216. \fbox{
  4217. \begin{minipage}{0.96\textwidth}
  4218. \small
  4219. \[
  4220. \begin{array}{lcl}
  4221. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4222. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4223. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4224. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4225. &\mid& \UNIOP{\key{'not}}{\Atm}
  4226. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4227. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4228. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4229. \mid \GOTO{\itm{label}} \\
  4230. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4231. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4232. \end{array}
  4233. \]
  4234. \end{minipage}
  4235. }
  4236. \caption{The abstract syntax of $C_1$, an extension of $C_0$
  4237. (Figure~\ref{fig:c0-syntax}).}
  4238. \label{fig:c1-syntax}
  4239. \end{figure}
  4240. \clearpage
  4241. \section{Remove Complex Operands}
  4242. \label{sec:remove-complex-opera-R2}
  4243. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4244. \code{rco-atom} functions according to the definition of the output
  4245. language for this pass, $R_2^{\dagger}$, the administrative normal
  4246. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4247. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4248. three sub-expressions of an \code{If} are allowed to be complex
  4249. expressions in the output of \code{remove-complex-opera*}, but the
  4250. operands of \code{not} and the comparisons must be atoms. Regarding
  4251. the \code{If} form, it is particularly important to \textbf{not}
  4252. replace its condition with a temporary variable because that would
  4253. interfere with the generation of high-quality output in the
  4254. \code{explicate-control} pass.
  4255. \begin{figure}[tp]
  4256. \centering
  4257. \fbox{
  4258. \begin{minipage}{0.96\textwidth}
  4259. \[
  4260. \begin{array}{rcl}
  4261. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4262. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4263. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4264. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4265. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4266. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4267. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4268. \end{array}
  4269. \]
  4270. \end{minipage}
  4271. }
  4272. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4273. \label{fig:r2-anf-syntax}
  4274. \end{figure}
  4275. \section{Explicate Control}
  4276. \label{sec:explicate-control-r2}
  4277. Recall that the purpose of \code{explicate-control} is to make the
  4278. order of evaluation explicit in the syntax of the program. With the
  4279. addition of \key{if} in $R_2$ this get more interesting.
  4280. As a motivating example, consider the following program that has an
  4281. \key{if} expression nested in the predicate of another \key{if}.
  4282. % s1_41.rkt
  4283. \begin{center}
  4284. \begin{minipage}{0.96\textwidth}
  4285. \begin{lstlisting}
  4286. (let ([x (read)])
  4287. (let ([y (read)])
  4288. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4289. (+ y 2)
  4290. (+ y 10))))
  4291. \end{lstlisting}
  4292. \end{minipage}
  4293. \end{center}
  4294. %
  4295. The naive way to compile \key{if} and the comparison would be to
  4296. handle each of them in isolation, regardless of their context. Each
  4297. comparison would be translated into a \key{cmpq} instruction followed
  4298. by a couple instructions to move the result from the EFLAGS register
  4299. into a general purpose register or stack location. Each \key{if} would
  4300. be translated into the combination of a \key{cmpq} and a conditional
  4301. jump. The generated code for the inner \key{if} in the above example
  4302. would be as follows.
  4303. \begin{center}
  4304. \begin{minipage}{0.96\textwidth}
  4305. \begin{lstlisting}
  4306. ...
  4307. cmpq $1, x ;; (< x 1)
  4308. setl %al
  4309. movzbq %al, tmp
  4310. cmpq $1, tmp ;; (if (< x 1) ...)
  4311. je then_branch_1
  4312. jmp else_branch_1
  4313. ...
  4314. \end{lstlisting}
  4315. \end{minipage}
  4316. \end{center}
  4317. However, if we take context into account we can do better and reduce
  4318. the use of \key{cmpq} and EFLAG-accessing instructions.
  4319. One idea is to try and reorganize the code at the level of $R_2$,
  4320. pushing the outer \key{if} inside the inner one. This would yield the
  4321. following code.
  4322. \begin{center}
  4323. \begin{minipage}{0.96\textwidth}
  4324. \begin{lstlisting}
  4325. (let ([x (read)])
  4326. (let ([y (read)])
  4327. (if (< x 1)
  4328. (if (eq? x 0)
  4329. (+ y 2)
  4330. (+ y 10))
  4331. (if (eq? x 2)
  4332. (+ y 2)
  4333. (+ y 10)))))
  4334. \end{lstlisting}
  4335. \end{minipage}
  4336. \end{center}
  4337. Unfortunately, this approach duplicates the two branches, and a
  4338. compiler must never duplicate code!
  4339. We need a way to perform the above transformation, but without
  4340. duplicating code. That is, we need a way for different parts of a
  4341. program to refer to the same piece of code, that is, to \emph{share}
  4342. code. At the level of x86 assembly this is straightforward because we
  4343. can label the code for each of the branches and insert jumps in all
  4344. the places that need to execute the branches. At the higher level of
  4345. our intermediate languages, we need to move away from abstract syntax
  4346. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4347. standard program representation called a \emph{control flow graph}
  4348. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4349. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4350. called a \emph{basic block}, and each edge represents a jump to
  4351. another block. The \key{Program} construct of $C_0$ and $C_1$ contains
  4352. a control flow graph represented as an alist mapping labels to basic
  4353. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4354. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4355. \code{remove-complex-opera*} pass and then the
  4356. \code{explicate-control} pass on the example program. We walk through
  4357. the output program and then discuss the algorithm.
  4358. %
  4359. Following the order of evaluation in the output of
  4360. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4361. and then the less-than-comparison to \code{1} in the predicate of the
  4362. inner \key{if}. In the output of \code{explicate-control}, in the
  4363. block labeled \code{start}, this becomes two assignment statements
  4364. followed by a conditional \key{goto} to label \code{block40} or
  4365. \code{block41}. The blocks associated with those labels contain the
  4366. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4367. respectively. Regarding the block labeled with \code{block40}, we
  4368. start with the comparison to \code{0} and then have a conditional
  4369. goto, either to label \code{block38} or label \code{block39}, which
  4370. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4371. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4372. similar.
  4373. \begin{figure}[tbp]
  4374. \begin{tabular}{lll}
  4375. \begin{minipage}{0.4\textwidth}
  4376. % s1_41.rkt
  4377. \begin{lstlisting}
  4378. (let ([x (read)])
  4379. (let ([y (read)])
  4380. (if (if (< x 1)
  4381. (eq? x 0)
  4382. (eq? x 2))
  4383. (+ y 2)
  4384. (+ y 10))))
  4385. \end{lstlisting}
  4386. \hspace{40pt}$\Downarrow$
  4387. \begin{lstlisting}
  4388. (let ([x (read)])
  4389. (let ([y (read)])
  4390. (if (if (< x 1)
  4391. (eq? x 0)
  4392. (eq? x 2))
  4393. (+ y 2)
  4394. (+ y 10))))
  4395. \end{lstlisting}
  4396. \end{minipage}
  4397. &
  4398. $\Rightarrow$
  4399. &
  4400. \begin{minipage}{0.55\textwidth}
  4401. \begin{lstlisting}
  4402. start:
  4403. x = (read);
  4404. y = (read);
  4405. if (< x 1)
  4406. goto block40;
  4407. else
  4408. goto block41;
  4409. block40:
  4410. if (eq? x 0)
  4411. goto block38;
  4412. else
  4413. goto block39;
  4414. block41:
  4415. if (eq? x 2)
  4416. goto block38;
  4417. else
  4418. goto block39;
  4419. block38:
  4420. return (+ y 2);
  4421. block39:
  4422. return (+ y 10);
  4423. \end{lstlisting}
  4424. \end{minipage}
  4425. \end{tabular}
  4426. \caption{Translation from $R_2$ to $C_1$
  4427. via the \code{explicate-control}.}
  4428. \label{fig:explicate-control-s1-38}
  4429. \end{figure}
  4430. %% The nice thing about the output of \code{explicate-control} is that
  4431. %% there are no unnecessary comparisons and every comparison is part of a
  4432. %% conditional jump.
  4433. %% The down-side of this output is that it includes
  4434. %% trivial blocks, such as the blocks labeled \code{block92} through
  4435. %% \code{block95}, that only jump to another block. We discuss a solution
  4436. %% to this problem in Section~\ref{sec:opt-jumps}.
  4437. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4438. \code{explicate-control} for $R_1$ using two mutually recursive
  4439. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4440. former function translates expressions in tail position whereas the
  4441. later function translates expressions on the right-hand-side of a
  4442. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4443. new kind of context to deal with: the predicate position of the
  4444. \key{if}. We need another function, \code{explicate-pred}, that takes
  4445. an $R_2$ expression and two blocks for the then-branch and
  4446. else-branch. The output of \code{explicate-pred} is a block.
  4447. %
  4448. %% Note that the three explicate functions need to construct a
  4449. %% control-flow graph, which we recommend they do via updates to a global
  4450. %% variable.
  4451. %
  4452. In the following paragraphs we discuss specific cases in the
  4453. \code{explicate-pred} function as well as the additions to the
  4454. \code{explicate-tail} and \code{explicate-assign} functions.
  4455. The function \code{explicate-pred} will need a case for every
  4456. expression that can have type \code{Boolean}. We detail a few cases
  4457. here and leave the rest for the reader. The input to this function is
  4458. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4459. the enclosing \key{if}, though some care will be needed regarding how
  4460. we represent the blocks. Suppose the expression is the Boolean
  4461. \code{\#t}. Then we can perform a kind of partial evaluation
  4462. \index{partial evaluation} and translate it to the ``then'' branch
  4463. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4464. \[
  4465. \key{\#t} \quad\Rightarrow\quad B_1,
  4466. \qquad\qquad\qquad
  4467. \key{\#f} \quad\Rightarrow\quad B_2
  4468. \]
  4469. These two cases demonstrate that we sometimes discard one of the
  4470. blocks that are input to \code{explicate-pred}. We will need to
  4471. arrange for the blocks that we actually use to appear in the resulting
  4472. control-flow graph, but not the discarded blocks.
  4473. The case for \key{if} in \code{explicate-pred} is particularly
  4474. illuminating as it deals with the challenges that we discussed above
  4475. regarding the example of the nested \key{if} expressions. The
  4476. ``then'' and ``else'' branches of the current \key{if} inherit their
  4477. context from the current one, that is, predicate context. So we
  4478. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4479. branches. For both of those recursive calls, we shall pass the blocks
  4480. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4481. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4482. duplicating code, we need to add these blocks to the control-flow
  4483. graph so that we can instead refer to them by name and execute them
  4484. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4485. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4486. we don't want to prematurely add them to the control-flow graph if
  4487. they end up being discarded.
  4488. The solution to this conundrum is to use \emph{lazy evaluation} to
  4489. delay adding the blocks to the control-flow graph until the points
  4490. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4491. evaluation} Racket provides support for lazy evaluation with the
  4492. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4493. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4494. \index{delay} creates a \emph{promise}\index{promise} in which the
  4495. evaluation of the expressions is postponed. When \key{(force}
  4496. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4497. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4498. $e_n$ is cached in the promise and returned. If \code{force} is
  4499. applied again to the same promise, then the cached result is returned.
  4500. We use lazy evaluation for the input and output blocks of the
  4501. functions \code{explicate-pred} and \code{explicate-assign} and for
  4502. the output block of \code{explicate-tail}. So instead of taking and
  4503. returning blocks, they take and return promised blocks. Furthermore,
  4504. when we come to a situation in which we a block might be used more
  4505. than once, as in the case for \code{if} above, we transform the
  4506. promise into a new promise that will add the block to the control-flow
  4507. graph and return a \code{goto}. The following auxiliary function
  4508. accomplishes this task. It begins with \code{delay} to create a
  4509. promise. When forced, this promise will force the input block. If that
  4510. block is already a \code{goto} (because it was already added to the
  4511. control-flow graph), then we return that \code{goto}. Otherwise we add
  4512. the block to the control-flow graph with another auxiliary function
  4513. named \code{add-node} that returns the new label, and then return the
  4514. \code{goto}.
  4515. \begin{lstlisting}
  4516. (define (block->goto block)
  4517. (delay
  4518. (define b (force block))
  4519. (match b
  4520. [(Goto label) (Goto label)]
  4521. [else (Goto (add-node b))]
  4522. )))
  4523. \end{lstlisting}
  4524. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4525. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4526. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4527. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4528. results from the two recursive calls. We complete the case for
  4529. \code{if} by recursively apply \code{explicate-pred} to the condition
  4530. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4531. the result $B_5$.
  4532. \[
  4533. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4534. \quad\Rightarrow\quad
  4535. B_5
  4536. \]
  4537. Next, consider the case for a less-than comparison in
  4538. \code{explicate-pred}. We translate it to an \code{if} statement,
  4539. whose two branches are required to be \code{goto}'s. So we apply
  4540. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4541. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4542. $G_2$. The translation of the less-than comparison is as follows.
  4543. \[
  4544. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4545. \begin{array}{l}
  4546. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4547. \key{else} \; G_2
  4548. \end{array}
  4549. \]
  4550. The \code{explicate-tail} function needs to be updated to use lazy
  4551. evaluation and it needs an additional case for \key{if}. Each of the
  4552. cases that return an AST node need use \code{delay} to instead return
  4553. a promise of an AST node. Recall that \code{explicate-tail} has an
  4554. accumulator parameter that is a block, which now becomes a promise of
  4555. a block, which we refer to as $B_0$.
  4556. In the case for \code{if} in \code{explicate-tail}, the two branches
  4557. inherit the current context, so they are in tail position. Thus, the
  4558. recursive calls on the ``then'' and ``else'' branch should be calls to
  4559. \code{explicate-tail}.
  4560. %
  4561. We need to pass $B_0$ as the accumulator argument for both of these
  4562. recursive calls, but we need to be careful not to duplicate $B_0$.
  4563. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4564. to the control-flow graph and obtain a promised goto $G_0$.
  4565. %
  4566. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4567. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4568. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4569. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4570. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4571. \[
  4572. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4573. \]
  4574. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4575. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4576. %% should not be confused with the labels for the blocks that appear in
  4577. %% the generated code. We initially construct unlabeled blocks; we only
  4578. %% attach labels to blocks when we add them to the control-flow graph, as
  4579. %% we see in the next case.
  4580. Next consider the case for \key{if} in the \code{explicate-assign}
  4581. function. The context of the \key{if} is an assignment to some
  4582. variable $x$ and then the control continues to some promised block
  4583. $B_1$. The code that we generate for both the ``then'' and ``else''
  4584. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4585. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4586. branches of the \key{if} inherit the current context, so they are in
  4587. assignment positions. Let $B_2$ be the result of applying
  4588. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4589. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4590. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4591. the result of applying \code{explicate-pred} to the predicate
  4592. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4593. translates to the promise $B_4$.
  4594. \[
  4595. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4596. \]
  4597. This completes the description of \code{explicate-control} for $R_2$.
  4598. The way in which the \code{shrink} pass transforms logical operations
  4599. such as \code{and} and \code{or} can impact the quality of code
  4600. generated by \code{explicate-control}. For example, consider the
  4601. following program.
  4602. % s1_21.rkt
  4603. \begin{lstlisting}
  4604. (if (and (eq? (read) 0) (eq? (read) 1))
  4605. 0
  4606. 42)
  4607. \end{lstlisting}
  4608. The \code{and} operation should transform into something that the
  4609. \code{explicate-pred} function can still analyze and descend through to
  4610. reach the underlying \code{eq?} conditions. Ideally, your
  4611. \code{explicate-control} pass should generate code similar to the
  4612. following for the above program.
  4613. \begin{center}
  4614. \begin{lstlisting}
  4615. start:
  4616. tmp1 = (read);
  4617. if (eq? tmp1 0)
  4618. goto block40;
  4619. else
  4620. goto block39;
  4621. block40:
  4622. tmp2 = (read);
  4623. if (eq? tmp2 1)
  4624. goto block38;
  4625. else
  4626. goto block39;
  4627. block38:
  4628. return 0;
  4629. block39:
  4630. return 42;
  4631. \end{lstlisting}
  4632. \end{center}
  4633. \begin{exercise}\normalfont
  4634. Implement the pass \code{explicate-control} by adding the cases for
  4635. \key{if} to the functions for tail and assignment contexts, and
  4636. implement \code{explicate-pred} for predicate contexts. Create test
  4637. cases that exercise all of the new cases in the code for this pass.
  4638. \end{exercise}
  4639. \section{Select Instructions}
  4640. \label{sec:select-r2}
  4641. \index{instruction selection}
  4642. Recall that the \code{select-instructions} pass lowers from our
  4643. $C$-like intermediate representation to the pseudo-x86 language, which
  4644. is suitable for conducting register allocation. The pass is
  4645. implemented using three auxiliary functions, one for each of the
  4646. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4647. For $\Atm$, we have new cases for the Booleans. We take the usual
  4648. approach of encoding them as integers, with true as 1 and false as 0.
  4649. \[
  4650. \key{\#t} \Rightarrow \key{1}
  4651. \qquad
  4652. \key{\#f} \Rightarrow \key{0}
  4653. \]
  4654. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4655. be implemented in terms of \code{xorq} as we discussed at the
  4656. beginning of this section. Given an assignment
  4657. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4658. if the left-hand side $\itm{var}$ is
  4659. the same as $\Atm$, then just the \code{xorq} suffices.
  4660. \[
  4661. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4662. \quad\Rightarrow\quad
  4663. \key{xorq}~\key{\$}1\key{,}~\Var
  4664. \]
  4665. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4666. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4667. x86. Then we have
  4668. \[
  4669. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4670. \quad\Rightarrow\quad
  4671. \begin{array}{l}
  4672. \key{movq}~\Arg\key{,}~\Var\\
  4673. \key{xorq}~\key{\$}1\key{,}~\Var
  4674. \end{array}
  4675. \]
  4676. Next consider the cases for \code{eq?} and less-than comparison.
  4677. Translating these operations to x86 is slightly involved due to the
  4678. unusual nature of the \key{cmpq} instruction discussed above. We
  4679. recommend translating an assignment from \code{eq?} into the following
  4680. sequence of three instructions. \\
  4681. \begin{tabular}{lll}
  4682. \begin{minipage}{0.4\textwidth}
  4683. \begin{lstlisting}
  4684. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4685. \end{lstlisting}
  4686. \end{minipage}
  4687. &
  4688. $\Rightarrow$
  4689. &
  4690. \begin{minipage}{0.4\textwidth}
  4691. \begin{lstlisting}
  4692. cmpq |$\Arg_2$|, |$\Arg_1$|
  4693. sete %al
  4694. movzbq %al, |$\Var$|
  4695. \end{lstlisting}
  4696. \end{minipage}
  4697. \end{tabular} \\
  4698. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4699. and conditional \key{goto}. Both are straightforward to handle. A
  4700. \key{goto} becomes a jump instruction.
  4701. \[
  4702. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4703. \]
  4704. A conditional \key{goto} becomes a compare instruction followed
  4705. by a conditional jump (for ``then'') and the fall-through is
  4706. to a regular jump (for ``else'').\\
  4707. \begin{tabular}{lll}
  4708. \begin{minipage}{0.4\textwidth}
  4709. \begin{lstlisting}
  4710. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4711. goto |$\ell_1$|;
  4712. else
  4713. goto |$\ell_2$|;
  4714. \end{lstlisting}
  4715. \end{minipage}
  4716. &
  4717. $\Rightarrow$
  4718. &
  4719. \begin{minipage}{0.4\textwidth}
  4720. \begin{lstlisting}
  4721. cmpq |$\Arg_2$|, |$\Arg_1$|
  4722. je |$\ell_1$|
  4723. jmp |$\ell_2$|
  4724. \end{lstlisting}
  4725. \end{minipage}
  4726. \end{tabular} \\
  4727. \begin{exercise}\normalfont
  4728. Expand your \code{select-instructions} pass to handle the new features
  4729. of the $R_2$ language. Test the pass on all the examples you have
  4730. created and make sure that you have some test programs that use the
  4731. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4732. the output using the \code{interp-x86} interpreter
  4733. (Appendix~\ref{appendix:interp}).
  4734. \end{exercise}
  4735. \section{Register Allocation}
  4736. \label{sec:register-allocation-r2}
  4737. \index{register allocation}
  4738. The changes required for $R_2$ affect liveness analysis, building the
  4739. interference graph, and assigning homes, but the graph coloring
  4740. algorithm itself does not change.
  4741. \subsection{Liveness Analysis}
  4742. \label{sec:liveness-analysis-r2}
  4743. \index{liveness analysis}
  4744. Recall that for $R_1$ we implemented liveness analysis for a single
  4745. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4746. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4747. produces many basic blocks arranged in a control-flow graph. We
  4748. recommend that you create a new auxiliary function named
  4749. \code{uncover-live-CFG} that applies liveness analysis to a
  4750. control-flow graph.
  4751. The first question we need to consider is: what order should we
  4752. process the basic blocks in the control-flow graph? To perform
  4753. liveness analysis on a basic block, we need to know its live-after
  4754. set. If a basic block has no successor blocks (i.e. no out-edges in
  4755. the control flow graph), then it has an empty live-after set and we
  4756. can immediately apply liveness analysis to it. If a basic block has
  4757. some successors, then we need to complete liveness analysis on those
  4758. blocks first. Thankfully, the control flow graph does not contain any
  4759. cycles because $R_2$ does not include loops. (In
  4760. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4761. the control-flow graph.)
  4762. %
  4763. Returning to the question of what order should we process the basic
  4764. blocks, the answer is reverse topological order. We recommend using
  4765. the \code{tsort} (topological sort) and \code{transpose} functions of
  4766. the Racket \code{graph} package to obtain this ordering.
  4767. \index{topological order}
  4768. \index{topological sort}
  4769. The next question is how to analyze the jump instructions. In
  4770. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4771. maintain an alist named \code{label->live} that maps each label to the
  4772. set of live locations at the beginning of the associated block. Now
  4773. that we have many basic blocks, the alist needs to be extended as we
  4774. process the blocks. In particular, after performing liveness analysis
  4775. on a block, we can take the live-before set for its first instruction
  4776. and associate that with the block's label in the alist.
  4777. %
  4778. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4779. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4780. mapping for $\itm{label}$ in \code{label->live}.
  4781. Now for $x86_1$ we also have the conditional jump
  4782. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4783. particularly interesting because during compilation we do not know, in
  4784. general, which way a conditional jump will go, so we do not know
  4785. whether to use the live-before set for the following instruction or
  4786. the live-before set for $\itm{label}$. The solution to this challenge
  4787. is based on the observation that there is no harm to the correctness
  4788. of the compiler if we classify more locations as live than the ones
  4789. that are truly live during a particular execution of the
  4790. instruction. Thus, we can take the union of the live-before sets from
  4791. the following instruction and from the mapping fro $\itm{label}$ in
  4792. \code{label->live}.
  4793. The helper functions for computing the variables in an instruction's
  4794. argument and for computing the variables read-from ($R$) or written-to
  4795. ($W$) by an instruction need to be updated to handle the new kinds of
  4796. arguments and instructions in x86$_1$.
  4797. \subsection{Build Interference}
  4798. \label{sec:build-interference-r2}
  4799. Many of the new instructions in x86$_1$ can be handled in the same way
  4800. as the instructions in x86$_0$. Thus, if your code was already quite
  4801. general, it will not need to be changed to handle the new
  4802. instructions. If you code is not general enough, I recommend that you
  4803. change your code to be more general. For example, you can factor out
  4804. the computing of the the read and write sets for each kind of
  4805. instruction into two auxiliary functions.
  4806. Note that the \key{movzbq} instruction requires some special care,
  4807. just like the \key{movq} instruction. See rule number 3 in
  4808. Section~\ref{sec:build-interference}.
  4809. %% \subsection{Assign Homes}
  4810. %% \label{sec:assign-homes-r2}
  4811. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4812. %% to be updated to handle the \key{if} statement, simply by recursively
  4813. %% processing the child nodes. Hopefully your code already handles the
  4814. %% other new instructions, but if not, you can generalize your code.
  4815. \begin{exercise}\normalfont
  4816. Update the \code{register-allocation} pass so that it works for $R_2$
  4817. and test your compiler using your previously created programs on the
  4818. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4819. \end{exercise}
  4820. \section{Patch Instructions}
  4821. The second argument of the \key{cmpq} instruction must not be an
  4822. immediate value (such as an integer). So if you are comparing two
  4823. immediates, we recommend inserting a \key{movq} instruction to put the
  4824. second argument in \key{rax}. Also, recall that instructions may have
  4825. at most one memory reference.
  4826. %
  4827. The second argument of the \key{movzbq} must be a register.
  4828. %
  4829. There are no special restrictions on the x86 instructions \key{JmpIf}
  4830. and \key{Jmp}.
  4831. \begin{exercise}\normalfont
  4832. Update \code{patch-instructions} to handle the new x86 instructions.
  4833. Test your compiler using your previously created programs on the
  4834. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4835. \end{exercise}
  4836. \begin{figure}[tbp]
  4837. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4838. \node (R2) at (0,2) {\large $R_2$};
  4839. \node (R2-2) at (3,2) {\large $R_2$};
  4840. \node (R2-3) at (6,2) {\large $R_2$};
  4841. \node (R2-4) at (9,2) {\large $R_2$};
  4842. \node (R2-5) at (12,2) {\large $R_2$};
  4843. \node (C1-1) at (3,0) {\large $C_1$};
  4844. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_1$};
  4845. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_1$};
  4846. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_1$};
  4847. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_1$};
  4848. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_1$};
  4849. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_1$};
  4850. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4851. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4852. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4853. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4854. \path[->,bend left=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4855. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4856. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4857. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4858. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4859. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4860. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4861. \end{tikzpicture}
  4862. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4863. \label{fig:R2-passes}
  4864. \end{figure}
  4865. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4866. compilation of $R_2$.
  4867. \section{An Example Translation}
  4868. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4869. $R_2$ translated to x86, showing the results of
  4870. \code{explicate-control}, \code{select-instructions}, and the final
  4871. x86 assembly code.
  4872. \begin{figure}[tbp]
  4873. \begin{tabular}{lll}
  4874. \begin{minipage}{0.5\textwidth}
  4875. % s1_20.rkt
  4876. \begin{lstlisting}
  4877. (if (eq? (read) 1) 42 0)
  4878. \end{lstlisting}
  4879. $\Downarrow$
  4880. \begin{lstlisting}
  4881. start:
  4882. tmp7951 = (read);
  4883. if (eq? tmp7951 1) then
  4884. goto block7952;
  4885. else
  4886. goto block7953;
  4887. block7952:
  4888. return 42;
  4889. block7953:
  4890. return 0;
  4891. \end{lstlisting}
  4892. $\Downarrow$
  4893. \begin{lstlisting}
  4894. start:
  4895. callq read_int
  4896. movq %rax, tmp7951
  4897. cmpq $1, tmp7951
  4898. je block7952
  4899. jmp block7953
  4900. block7953:
  4901. movq $0, %rax
  4902. jmp conclusion
  4903. block7952:
  4904. movq $42, %rax
  4905. jmp conclusion
  4906. \end{lstlisting}
  4907. \end{minipage}
  4908. &
  4909. $\Rightarrow\qquad$
  4910. \begin{minipage}{0.4\textwidth}
  4911. \begin{lstlisting}
  4912. start:
  4913. callq read_int
  4914. movq %rax, %rcx
  4915. cmpq $1, %rcx
  4916. je block7952
  4917. jmp block7953
  4918. block7953:
  4919. movq $0, %rax
  4920. jmp conclusion
  4921. block7952:
  4922. movq $42, %rax
  4923. jmp conclusion
  4924. .globl main
  4925. main:
  4926. pushq %rbp
  4927. movq %rsp, %rbp
  4928. pushq %r13
  4929. pushq %r12
  4930. pushq %rbx
  4931. pushq %r14
  4932. subq $0, %rsp
  4933. jmp start
  4934. conclusion:
  4935. addq $0, %rsp
  4936. popq %r14
  4937. popq %rbx
  4938. popq %r12
  4939. popq %r13
  4940. popq %rbp
  4941. retq
  4942. \end{lstlisting}
  4943. \end{minipage}
  4944. \end{tabular}
  4945. \caption{Example compilation of an \key{if} expression to x86.}
  4946. \label{fig:if-example-x86}
  4947. \end{figure}
  4948. \section{Challenge: Remove Jumps}
  4949. \label{sec:opt-jumps}
  4950. %% Recall that in the example output of \code{explicate-control} in
  4951. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4952. %% \code{block60} are trivial blocks, they do nothing but jump to another
  4953. %% block. The first goal of this challenge assignment is to remove those
  4954. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4955. %% \code{explicate-control} on the left and shows the result of bypassing
  4956. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  4957. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  4958. %% \code{block55}. The optimized code on the right of
  4959. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4960. %% \code{then} branch jumping directly to \code{block55}. The story is
  4961. %% similar for the \code{else} branch, as well as for the two branches in
  4962. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  4963. %% have been optimized in this way, there are no longer any jumps to
  4964. %% blocks \code{block57} through \code{block60}, so they can be removed.
  4965. %% \begin{figure}[tbp]
  4966. %% \begin{tabular}{lll}
  4967. %% \begin{minipage}{0.4\textwidth}
  4968. %% \begin{lstlisting}
  4969. %% block62:
  4970. %% tmp54 = (read);
  4971. %% if (eq? tmp54 2) then
  4972. %% goto block59;
  4973. %% else
  4974. %% goto block60;
  4975. %% block61:
  4976. %% tmp53 = (read);
  4977. %% if (eq? tmp53 0) then
  4978. %% goto block57;
  4979. %% else
  4980. %% goto block58;
  4981. %% block60:
  4982. %% goto block56;
  4983. %% block59:
  4984. %% goto block55;
  4985. %% block58:
  4986. %% goto block56;
  4987. %% block57:
  4988. %% goto block55;
  4989. %% block56:
  4990. %% return (+ 700 77);
  4991. %% block55:
  4992. %% return (+ 10 32);
  4993. %% start:
  4994. %% tmp52 = (read);
  4995. %% if (eq? tmp52 1) then
  4996. %% goto block61;
  4997. %% else
  4998. %% goto block62;
  4999. %% \end{lstlisting}
  5000. %% \end{minipage}
  5001. %% &
  5002. %% $\Rightarrow$
  5003. %% &
  5004. %% \begin{minipage}{0.55\textwidth}
  5005. %% \begin{lstlisting}
  5006. %% block62:
  5007. %% tmp54 = (read);
  5008. %% if (eq? tmp54 2) then
  5009. %% goto block55;
  5010. %% else
  5011. %% goto block56;
  5012. %% block61:
  5013. %% tmp53 = (read);
  5014. %% if (eq? tmp53 0) then
  5015. %% goto block55;
  5016. %% else
  5017. %% goto block56;
  5018. %% block56:
  5019. %% return (+ 700 77);
  5020. %% block55:
  5021. %% return (+ 10 32);
  5022. %% start:
  5023. %% tmp52 = (read);
  5024. %% if (eq? tmp52 1) then
  5025. %% goto block61;
  5026. %% else
  5027. %% goto block62;
  5028. %% \end{lstlisting}
  5029. %% \end{minipage}
  5030. %% \end{tabular}
  5031. %% \caption{Optimize jumps by removing trivial blocks.}
  5032. %% \label{fig:optimize-jumps}
  5033. %% \end{figure}
  5034. %% The name of this pass is \code{optimize-jumps}. We recommend
  5035. %% implementing this pass in two phases. The first phrase builds a hash
  5036. %% table that maps labels to possibly improved labels. The second phase
  5037. %% changes the target of each \code{goto} to use the improved label. If
  5038. %% the label is for a trivial block, then the hash table should map the
  5039. %% label to the first non-trivial block that can be reached from this
  5040. %% label by jumping through trivial blocks. If the label is for a
  5041. %% non-trivial block, then the hash table should map the label to itself;
  5042. %% we do not want to change jumps to non-trivial blocks.
  5043. %% The first phase can be accomplished by constructing an empty hash
  5044. %% table, call it \code{short-cut}, and then iterating over the control
  5045. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5046. %% then update the hash table, mapping the block's source to the target
  5047. %% of the \code{goto}. Also, the hash table may already have mapped some
  5048. %% labels to the block's source, to you must iterate through the hash
  5049. %% table and update all of those so that they instead map to the target
  5050. %% of the \code{goto}.
  5051. %% For the second phase, we recommend iterating through the $\Tail$ of
  5052. %% each block in the program, updating the target of every \code{goto}
  5053. %% according to the mapping in \code{short-cut}.
  5054. %% \begin{exercise}\normalfont
  5055. %% Implement the \code{optimize-jumps} pass as a transformation from
  5056. %% $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  5057. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5058. %% example programs. Then check that your compiler still passes all of
  5059. %% your tests.
  5060. %% \end{exercise}
  5061. There is an opportunity for optimizing jumps that is apparent in the
  5062. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5063. with a jump to \code{block7953} and there are no other jumps to
  5064. \code{block7953} in the rest of the program. In this situation we can
  5065. avoid the runtime overhead of this jump by merging \code{block7953}
  5066. into the preceding block, in this case the \code{start} block.
  5067. Figure~\ref{fig:remove-jumps} shows the output of
  5068. \code{select-instructions} on the left and the result of this
  5069. optimization on the right.
  5070. \begin{figure}[tbp]
  5071. \begin{tabular}{lll}
  5072. \begin{minipage}{0.5\textwidth}
  5073. % s1_20.rkt
  5074. \begin{lstlisting}
  5075. start:
  5076. callq read_int
  5077. movq %rax, tmp7951
  5078. cmpq $1, tmp7951
  5079. je block7952
  5080. jmp block7953
  5081. block7953:
  5082. movq $0, %rax
  5083. jmp conclusion
  5084. block7952:
  5085. movq $42, %rax
  5086. jmp conclusion
  5087. \end{lstlisting}
  5088. \end{minipage}
  5089. &
  5090. $\Rightarrow\qquad$
  5091. \begin{minipage}{0.4\textwidth}
  5092. \begin{lstlisting}
  5093. start:
  5094. callq read_int
  5095. movq %rax, tmp7951
  5096. cmpq $1, tmp7951
  5097. je block7952
  5098. movq $0, %rax
  5099. jmp conclusion
  5100. block7952:
  5101. movq $42, %rax
  5102. jmp conclusion
  5103. \end{lstlisting}
  5104. \end{minipage}
  5105. \end{tabular}
  5106. \caption{Merging basic blocks by removing unnecessary jumps.}
  5107. \label{fig:remove-jumps}
  5108. \end{figure}
  5109. \begin{exercise}\normalfont
  5110. Implement a pass named \code{remove-jumps} that merges basic blocks
  5111. into their preceding basic block, when there is only one preceding
  5112. block. The pass should translate from pseudo $x86_1$ to pseudo
  5113. $x86_1$ and it should come immediately after
  5114. \code{select-instructions}. Check that \code{remove-jumps}
  5115. accomplishes the goal of merging basic blocks on several test
  5116. programs and check that your compiler passes all of your tests.
  5117. \end{exercise}
  5118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5119. \chapter{Tuples and Garbage Collection}
  5120. \label{ch:tuples}
  5121. \index{tuple}
  5122. \index{vector}
  5123. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5124. add simple structures. \\ --Jeremy}
  5125. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5126. things to discuss in this chapter. \\ --Jeremy}
  5127. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5128. all the IR grammars are spelled out! \\ --Jeremy}
  5129. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5130. but keep type annotations on vector creation and local variables, function
  5131. parameters, etc. \\ --Jeremy}
  5132. \margincomment{\scriptsize Be more explicit about how to deal with
  5133. the root stack. \\ --Jeremy}
  5134. In this chapter we study the implementation of mutable tuples (called
  5135. ``vectors'' in Racket). This language feature is the first to use the
  5136. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5137. indefinite, that is, a tuple lives forever from the programmer's
  5138. viewpoint. Of course, from an implementer's viewpoint, it is important
  5139. to reclaim the space associated with a tuple when it is no longer
  5140. needed, which is why we also study \emph{garbage collection}
  5141. \emph{garbage collection}
  5142. techniques in this chapter.
  5143. Section~\ref{sec:r3} introduces the $R_3$ language including its
  5144. interpreter and type checker. The $R_3$ language extends the $R_2$
  5145. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5146. \code{void} value. The reason for including the later is that the
  5147. \code{vector-set!} operation returns a value of type
  5148. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5149. called the \code{Unit} type in the programming languages
  5150. literature. Racket's \code{Void} type is inhabited by a single value
  5151. \code{void} which corresponds to \code{unit} or \code{()} in the
  5152. literature~\citep{Pierce:2002hj}.}.
  5153. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5154. copying live objects back and forth between two halves of the
  5155. heap. The garbage collector requires coordination with the compiler so
  5156. that it can see all of the \emph{root} pointers, that is, pointers in
  5157. registers or on the procedure call stack.
  5158. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5159. discuss all the necessary changes and additions to the compiler
  5160. passes, including a new compiler pass named \code{expose-allocation}.
  5161. \section{The $R_3$ Language}
  5162. \label{sec:r3}
  5163. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5164. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5165. $R_3$ language includes three new forms: \code{vector} for creating a
  5166. tuple, \code{vector-ref} for reading an element of a tuple, and
  5167. \code{vector-set!} for writing to an element of a tuple. The program
  5168. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5169. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5170. the 3-tuple, demonstrating that tuples are first-class values. The
  5171. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5172. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5173. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5174. 1-tuple. So the result of the program is \code{42}.
  5175. \begin{figure}[tbp]
  5176. \centering
  5177. \fbox{
  5178. \begin{minipage}{0.96\textwidth}
  5179. \[
  5180. \begin{array}{lcl}
  5181. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5182. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  5183. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5184. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5185. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5186. \mid (\key{and}\;\Exp\;\Exp)
  5187. \mid (\key{or}\;\Exp\;\Exp)
  5188. \mid (\key{not}\;\Exp) } \\
  5189. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5190. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5191. &\mid& (\key{vector}\;\Exp\ldots)
  5192. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  5193. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  5194. \mid (\key{vector-length}\;\Exp) \\
  5195. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  5196. R_3 &::=& \Exp
  5197. \end{array}
  5198. \]
  5199. \end{minipage}
  5200. }
  5201. \caption{The concrete syntax of $R_3$, extending $R_2$
  5202. (Figure~\ref{fig:r2-concrete-syntax}).}
  5203. \label{fig:r3-concrete-syntax}
  5204. \end{figure}
  5205. \begin{figure}[tbp]
  5206. \begin{lstlisting}
  5207. (let ([t (vector 40 #t (vector 2))])
  5208. (if (vector-ref t 1)
  5209. (+ (vector-ref t 0)
  5210. (vector-ref (vector-ref t 2) 0))
  5211. 44))
  5212. \end{lstlisting}
  5213. \caption{Example program that creates tuples and reads from them.}
  5214. \label{fig:vector-eg}
  5215. \end{figure}
  5216. \begin{figure}[tp]
  5217. \centering
  5218. \fbox{
  5219. \begin{minipage}{0.96\textwidth}
  5220. \[
  5221. \begin{array}{lcl}
  5222. \itm{op} &::=& \ldots
  5223. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5224. \mid \code{vector-length} \\
  5225. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5226. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5227. \mid \BOOL{\itm{bool}}
  5228. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5229. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5230. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5231. \end{array}
  5232. \]
  5233. \end{minipage}
  5234. }
  5235. \caption{The abstract syntax of $R_3$.}
  5236. \label{fig:r3-syntax}
  5237. \end{figure}
  5238. \index{allocate}
  5239. \index{heap allocate}
  5240. Tuples are our first encounter with heap-allocated data, which raises
  5241. several interesting issues. First, variable binding performs a
  5242. shallow-copy when dealing with tuples, which means that different
  5243. variables can refer to the same tuple, that is, different variables
  5244. can be \emph{aliases} for the same entity. Consider the following
  5245. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5246. Thus, the mutation through \code{t2} is visible when referencing the
  5247. tuple from \code{t1}, so the result of this program is \code{42}.
  5248. \index{alias}\index{mutation}
  5249. \begin{center}
  5250. \begin{minipage}{0.96\textwidth}
  5251. \begin{lstlisting}
  5252. (let ([t1 (vector 3 7)])
  5253. (let ([t2 t1])
  5254. (let ([_ (vector-set! t2 0 42)])
  5255. (vector-ref t1 0))))
  5256. \end{lstlisting}
  5257. \end{minipage}
  5258. \end{center}
  5259. The next issue concerns the lifetime of tuples. Of course, they are
  5260. created by the \code{vector} form, but when does their lifetime end?
  5261. Notice that $R_3$ does not include an operation for deleting
  5262. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5263. of static scoping. For example, the following program returns
  5264. \code{42} even though the variable \code{w} goes out of scope prior to
  5265. the \code{vector-ref} that reads from the vector it was bound to.
  5266. \begin{center}
  5267. \begin{minipage}{0.96\textwidth}
  5268. \begin{lstlisting}
  5269. (let ([v (vector (vector 44))])
  5270. (let ([x (let ([w (vector 42)])
  5271. (let ([_ (vector-set! v 0 w)])
  5272. 0))])
  5273. (+ x (vector-ref (vector-ref v 0) 0))))
  5274. \end{lstlisting}
  5275. \end{minipage}
  5276. \end{center}
  5277. From the perspective of programmer-observable behavior, tuples live
  5278. forever. Of course, if they really lived forever, then many programs
  5279. would run out of memory.\footnote{The $R_3$ language does not have
  5280. looping or recursive functions, so it is nigh impossible to write a
  5281. program in $R_3$ that will run out of memory. However, we add
  5282. recursive functions in the next Chapter!} A Racket implementation
  5283. must therefore perform automatic garbage collection.
  5284. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5285. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5286. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5287. operations in Racket. One subtle point is that the \code{vector-set!}
  5288. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5289. can be passed around just like other values inside an $R_3$ program
  5290. and a \code{\#<void>} value can be compared for equality with another
  5291. \code{\#<void>} value. However, there are no other operations specific
  5292. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5293. the \code{void?} predicate that returns \code{\#t} when applied to
  5294. \code{\#<void>} and \code{\#f} otherwise.
  5295. \begin{figure}[tbp]
  5296. \begin{lstlisting}
  5297. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5298. (define (interp-op op)
  5299. (match op
  5300. ...
  5301. ['vector vector]
  5302. ['vector-ref vector-ref]
  5303. ['vector-set! vector-set!]
  5304. [else (error 'interp-op "unknown operator")]))
  5305. (define (interp-exp env)
  5306. (lambda (e)
  5307. (define recur (interp-exp env))
  5308. (match e
  5309. ...
  5310. )))
  5311. (define (interp-R3 p)
  5312. (match p
  5313. [(Program '() e)
  5314. ((interp-exp '()) e)]
  5315. ))
  5316. \end{lstlisting}
  5317. \caption{Interpreter for the $R_3$ language.}
  5318. \label{fig:interp-R3}
  5319. \end{figure}
  5320. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5321. deserves some explanation. When allocating a vector, we need to know
  5322. which elements of the vector are pointers (i.e. are also vectors). We
  5323. can obtain this information during type checking. The type checker in
  5324. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5325. expression, it also wraps every \key{vector} creation with the form
  5326. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5327. %
  5328. To create the s-expression for the \code{Vector} type in
  5329. Figure~\ref{fig:type-check-R3}, we use the
  5330. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5331. operator} \code{,@} to insert the list \code{t*} without its usual
  5332. start and end parentheses. \index{unquote-slicing}
  5333. \begin{figure}[tp]
  5334. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5335. (define (type-check-exp env)
  5336. (lambda (e)
  5337. (define recur (type-check-exp env))
  5338. (match e
  5339. ...
  5340. [(Void) (values (Void) 'Void)]
  5341. [(Prim 'vector es)
  5342. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5343. (let ([t `(Vector ,@t*)])
  5344. (values (HasType (Prim 'vector e*) t) t))]
  5345. [(Prim 'vector-ref (list e (Int i)))
  5346. (define-values (e^ t) (recur e))
  5347. (match t
  5348. [`(Vector ,ts ...)
  5349. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5350. (error 'type-check-exp "invalid index ~a" i))
  5351. (let ([t (list-ref ts i)])
  5352. (values (Prim 'vector-ref (list e^ (Int i))) t))]
  5353. [else (error 'type-check-exp
  5354. "expected a vector in vector-ref, not ~a" t)])]
  5355. [(Prim 'vector-set! (list e (Int i) arg) )
  5356. (define-values (e-vec t-vec) (recur e))
  5357. (define-values (e-arg^ t-arg) (recur arg))
  5358. (match t-vec
  5359. [`(Vector ,ts ...)
  5360. (unless (and (exact-nonnegative-integer? i) (i . < . (length ts)))
  5361. (error 'type-check-exp "invalid index ~a" i))
  5362. (unless (type-equal? (list-ref ts i) t-arg)
  5363. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  5364. (list-ref ts i) t-arg))
  5365. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5366. [else (error 'type-check-exp
  5367. "expected a vector in vector-set!, not ~a" t-vec)])]
  5368. [(Prim 'vector-length (list e))
  5369. (define-values (e^ t) (recur e))
  5370. (match t
  5371. [`(Vector ,ts ...)
  5372. (values (Prim 'vector-length (list e^)) 'Integer)]
  5373. [else (error 'type-check-exp
  5374. "expected a vector in vector-length, not ~a" t)])]
  5375. [(Prim 'eq? (list arg1 arg2))
  5376. (define-values (e1 t1) (recur arg1))
  5377. (define-values (e2 t2) (recur arg2))
  5378. (match* (t1 t2)
  5379. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5380. [(other wise)
  5381. (unless (type-equal? t1 t2)
  5382. (error 'type-check-exp
  5383. "type error: different argument types of eq?: ~a != ~a" t1 t2))])
  5384. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5385. [(HasType (Prim 'vector es) t)
  5386. ((type-check-exp env) (Prim 'vector es))]
  5387. [(HasType e t)
  5388. (define-values (e^ t^) (recur e))
  5389. (unless (type-equal? t t^)
  5390. (error 'type-check-exp "type mismatch in HasType" t t^))
  5391. (values (HasType e^ t) t)]
  5392. ...
  5393. [else (error 'type-check-exp "R3/unmatched ~a" e)]
  5394. )))
  5395. \end{lstlisting}
  5396. \caption{Type checker for the $R_3$ language.}
  5397. \label{fig:type-check-R3}
  5398. \end{figure}
  5399. \section{Garbage Collection}
  5400. \label{sec:GC}
  5401. Here we study a relatively simple algorithm for garbage collection
  5402. that is the basis of state-of-the-art garbage
  5403. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5404. particular, we describe a two-space copying
  5405. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5406. perform the
  5407. copy~\citep{Cheney:1970aa}.
  5408. \index{copying collector}
  5409. \index{two-space copying collector}
  5410. Figure~\ref{fig:copying-collector} gives a
  5411. coarse-grained depiction of what happens in a two-space collector,
  5412. showing two time steps, prior to garbage collection (on the top) and
  5413. after garbage collection (on the bottom). In a two-space collector,
  5414. the heap is divided into two parts named the FromSpace and the
  5415. ToSpace. Initially, all allocations go to the FromSpace until there is
  5416. not enough room for the next allocation request. At that point, the
  5417. garbage collector goes to work to make more room.
  5418. \index{ToSpace}
  5419. \index{FromSpace}
  5420. The garbage collector must be careful not to reclaim tuples that will
  5421. be used by the program in the future. Of course, it is impossible in
  5422. general to predict what a program will do, but we can over approximate
  5423. the will-be-used tuples by preserving all tuples that could be
  5424. accessed by \emph{any} program given the current computer state. A
  5425. program could access any tuple whose address is in a register or on
  5426. the procedure call stack. These addresses are called the \emph{root
  5427. set}\index{root set}. In addition, a program could access any tuple that is
  5428. transitively reachable from the root set. Thus, it is safe for the
  5429. garbage collector to reclaim the tuples that are not reachable in this
  5430. way.
  5431. So the goal of the garbage collector is twofold:
  5432. \begin{enumerate}
  5433. \item preserve all tuple that are reachable from the root set via a
  5434. path of pointers, that is, the \emph{live} tuples, and
  5435. \item reclaim the memory of everything else, that is, the
  5436. \emph{garbage}.
  5437. \end{enumerate}
  5438. A copying collector accomplishes this by copying all of the live
  5439. objects from the FromSpace into the ToSpace and then performs a slight
  5440. of hand, treating the ToSpace as the new FromSpace and the old
  5441. FromSpace as the new ToSpace. In the example of
  5442. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5443. root set, one in a register and two on the stack. All of the live
  5444. objects have been copied to the ToSpace (the right-hand side of
  5445. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5446. pointer relationships. For example, the pointer in the register still
  5447. points to a 2-tuple whose first element is a 3-tuple and whose second
  5448. element is a 2-tuple. There are four tuples that are not reachable
  5449. from the root set and therefore do not get copied into the ToSpace.
  5450. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5451. created by a well-typed program in $R_3$ because it contains a
  5452. cycle. However, creating cycles will be possible once we get to $R_6$.
  5453. We design the garbage collector to deal with cycles to begin with so
  5454. we will not need to revisit this issue.
  5455. \begin{figure}[tbp]
  5456. \centering
  5457. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5458. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5459. \caption{A copying collector in action.}
  5460. \label{fig:copying-collector}
  5461. \end{figure}
  5462. There are many alternatives to copying collectors (and their bigger
  5463. siblings, the generational collectors) when its comes to garbage
  5464. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5465. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5466. collectors are that allocation is fast (just a comparison and pointer
  5467. increment), there is no fragmentation, cyclic garbage is collected,
  5468. and the time complexity of collection only depends on the amount of
  5469. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5470. main disadvantages of a two-space copying collector is that it uses a
  5471. lot of space and takes a long time to perform the copy, though these
  5472. problems are ameliorated in generational collectors. Racket and
  5473. Scheme programs tend to allocate many small objects and generate a lot
  5474. of garbage, so copying and generational collectors are a good fit.
  5475. Garbage collection is an active research topic, especially concurrent
  5476. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5477. developing new techniques and revisiting old
  5478. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5479. meet every year at the International Symposium on Memory Management to
  5480. present these findings.
  5481. \subsection{Graph Copying via Cheney's Algorithm}
  5482. \label{sec:cheney}
  5483. \index{Cheney's algorithm}
  5484. Let us take a closer look at the copying of the live objects. The
  5485. allocated objects and pointers can be viewed as a graph and we need to
  5486. copy the part of the graph that is reachable from the root set. To
  5487. make sure we copy all of the reachable vertices in the graph, we need
  5488. an exhaustive graph traversal algorithm, such as depth-first search or
  5489. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5490. such algorithms take into account the possibility of cycles by marking
  5491. which vertices have already been visited, so as to ensure termination
  5492. of the algorithm. These search algorithms also use a data structure
  5493. such as a stack or queue as a to-do list to keep track of the vertices
  5494. that need to be visited. We use breadth-first search and a trick
  5495. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5496. and copying tuples into the ToSpace.
  5497. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5498. copy progresses. The queue is represented by a chunk of contiguous
  5499. memory at the beginning of the ToSpace, using two pointers to track
  5500. the front and the back of the queue. The algorithm starts by copying
  5501. all tuples that are immediately reachable from the root set into the
  5502. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5503. old tuple to indicate that it has been visited. We discuss how this
  5504. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5505. pointers inside the copied tuples in the queue still point back to the
  5506. FromSpace. Once the initial queue has been created, the algorithm
  5507. enters a loop in which it repeatedly processes the tuple at the front
  5508. of the queue and pops it off the queue. To process a tuple, the
  5509. algorithm copies all the tuple that are directly reachable from it to
  5510. the ToSpace, placing them at the back of the queue. The algorithm then
  5511. updates the pointers in the popped tuple so they point to the newly
  5512. copied tuples.
  5513. \begin{figure}[tbp]
  5514. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5515. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5516. \label{fig:cheney}
  5517. \end{figure}
  5518. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5519. tuple whose second element is $42$ to the back of the queue. The other
  5520. pointer goes to a tuple that has already been copied, so we do not
  5521. need to copy it again, but we do need to update the pointer to the new
  5522. location. This can be accomplished by storing a \emph{forwarding
  5523. pointer} to the new location in the old tuple, back when we initially
  5524. copied the tuple into the ToSpace. This completes one step of the
  5525. algorithm. The algorithm continues in this way until the front of the
  5526. queue is empty, that is, until the front catches up with the back.
  5527. \subsection{Data Representation}
  5528. \label{sec:data-rep-gc}
  5529. The garbage collector places some requirements on the data
  5530. representations used by our compiler. First, the garbage collector
  5531. needs to distinguish between pointers and other kinds of data. There
  5532. are several ways to accomplish this.
  5533. \begin{enumerate}
  5534. \item Attached a tag to each object that identifies what type of
  5535. object it is~\citep{McCarthy:1960dz}.
  5536. \item Store different types of objects in different
  5537. regions~\citep{Steele:1977ab}.
  5538. \item Use type information from the program to either generate
  5539. type-specific code for collecting or to generate tables that can
  5540. guide the
  5541. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5542. \end{enumerate}
  5543. Dynamically typed languages, such as Lisp, need to tag objects
  5544. anyways, so option 1 is a natural choice for those languages.
  5545. However, $R_3$ is a statically typed language, so it would be
  5546. unfortunate to require tags on every object, especially small and
  5547. pervasive objects like integers and Booleans. Option 3 is the
  5548. best-performing choice for statically typed languages, but comes with
  5549. a relatively high implementation complexity. To keep this chapter
  5550. within a 2-week time budget, we recommend a combination of options 1
  5551. and 2, using separate strategies for the stack and the heap.
  5552. Regarding the stack, we recommend using a separate stack for pointers,
  5553. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5554. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5555. is, when a local variable needs to be spilled and is of type
  5556. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5557. stack instead of the normal procedure call stack. Furthermore, we
  5558. always spill vector-typed variables if they are live during a call to
  5559. the collector, thereby ensuring that no pointers are in registers
  5560. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5561. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5562. the data layout using a root stack. The root stack contains the two
  5563. pointers from the regular stack and also the pointer in the second
  5564. register.
  5565. \begin{figure}[tbp]
  5566. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5567. \caption{Maintaining a root stack to facilitate garbage collection.}
  5568. \label{fig:shadow-stack}
  5569. \end{figure}
  5570. The problem of distinguishing between pointers and other kinds of data
  5571. also arises inside of each tuple on the heap. We solve this problem by
  5572. attaching a tag, an extra 64-bits, to each
  5573. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5574. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5575. that we have drawn the bits in a big-endian way, from right-to-left,
  5576. with bit location 0 (the least significant bit) on the far right,
  5577. which corresponds to the direction of the x86 shifting instructions
  5578. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5579. is dedicated to specifying which elements of the tuple are pointers,
  5580. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5581. indicates there is a pointer and a 0 bit indicates some other kind of
  5582. data. The pointer mask starts at bit location 7. We have limited
  5583. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5584. the pointer mask. The tag also contains two other pieces of
  5585. information. The length of the tuple (number of elements) is stored in
  5586. bits location 1 through 6. Finally, the bit at location 0 indicates
  5587. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5588. value 1, then this tuple has not yet been copied. If the bit has
  5589. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5590. of a pointer are always zero anyways because our tuples are 8-byte
  5591. aligned.)
  5592. \begin{figure}[tbp]
  5593. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5594. \caption{Representation of tuples in the heap.}
  5595. \label{fig:tuple-rep}
  5596. \end{figure}
  5597. \subsection{Implementation of the Garbage Collector}
  5598. \label{sec:organize-gz}
  5599. \index{prelude}
  5600. An implementation of the copying collector is provided in the
  5601. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5602. interface to the garbage collector that is used by the compiler. The
  5603. \code{initialize} function creates the FromSpace, ToSpace, and root
  5604. stack and should be called in the prelude of the \code{main}
  5605. function. The arguments of \code{initialize} are the root stack size
  5606. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5607. good choice for both. The \code{initialize} function puts the address
  5608. of the beginning of the FromSpace into the global variable
  5609. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5610. the address that is 1-past the last element of the FromSpace. (We use
  5611. half-open intervals to represent chunks of
  5612. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5613. points to the first element of the root stack.
  5614. As long as there is room left in the FromSpace, your generated code
  5615. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5616. %
  5617. The amount of room left in FromSpace is the difference between the
  5618. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5619. function should be called when there is not enough room left in the
  5620. FromSpace for the next allocation. The \code{collect} function takes
  5621. a pointer to the current top of the root stack (one past the last item
  5622. that was pushed) and the number of bytes that need to be
  5623. allocated. The \code{collect} function performs the copying collection
  5624. and leaves the heap in a state such that the next allocation will
  5625. succeed.
  5626. \begin{figure}[tbp]
  5627. \begin{lstlisting}
  5628. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5629. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5630. int64_t* free_ptr;
  5631. int64_t* fromspace_begin;
  5632. int64_t* fromspace_end;
  5633. int64_t** rootstack_begin;
  5634. \end{lstlisting}
  5635. \caption{The compiler's interface to the garbage collector.}
  5636. \label{fig:gc-header}
  5637. \end{figure}
  5638. %% \begin{exercise}
  5639. %% In the file \code{runtime.c} you will find the implementation of
  5640. %% \code{initialize} and a partial implementation of \code{collect}.
  5641. %% The \code{collect} function calls another function, \code{cheney},
  5642. %% to perform the actual copy, and that function is left to the reader
  5643. %% to implement. The following is the prototype for \code{cheney}.
  5644. %% \begin{lstlisting}
  5645. %% static void cheney(int64_t** rootstack_ptr);
  5646. %% \end{lstlisting}
  5647. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5648. %% rootstack (which is an array of pointers). The \code{cheney} function
  5649. %% also communicates with \code{collect} through the global
  5650. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5651. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5652. %% the ToSpace:
  5653. %% \begin{lstlisting}
  5654. %% static int64_t* tospace_begin;
  5655. %% static int64_t* tospace_end;
  5656. %% \end{lstlisting}
  5657. %% The job of the \code{cheney} function is to copy all the live
  5658. %% objects (reachable from the root stack) into the ToSpace, update
  5659. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5660. %% update the root stack so that it points to the objects in the
  5661. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5662. %% and ToSpace.
  5663. %% \end{exercise}
  5664. %% \section{Compiler Passes}
  5665. %% \label{sec:code-generation-gc}
  5666. The introduction of garbage collection has a non-trivial impact on our
  5667. compiler passes. We introduce a new compiler pass named
  5668. \code{expose-allocation}. We make
  5669. significant changes to \code{select-instructions},
  5670. \code{build-interference}, \code{allocate-registers}, and
  5671. \code{print-x86} and make minor changes in several more passes. The
  5672. following program will serve as our running example. It creates two
  5673. tuples, one nested inside the other. Both tuples have length one. The
  5674. program accesses the element in the inner tuple tuple via two vector
  5675. references.
  5676. % tests/s2_17.rkt
  5677. \begin{lstlisting}
  5678. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5679. \end{lstlisting}
  5680. \section{Shrink}
  5681. \label{sec:shrink-R3}
  5682. Recall that the \code{shrink} pass translates the primitives operators
  5683. into a smaller set of primitives. Because this pass comes after type
  5684. checking, but before the passes that require the type information in
  5685. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5686. to wrap \code{HasType} around each AST node that it generates.
  5687. \section{Expose Allocation}
  5688. \label{sec:expose-allocation}
  5689. The pass \code{expose-allocation} lowers the \code{vector} creation
  5690. form into a conditional call to the collector followed by the
  5691. allocation. We choose to place the \code{expose-allocation} pass
  5692. before \code{remove-complex-opera*} because the code generated by
  5693. \code{expose-allocation} contains complex operands. We also place
  5694. \code{expose-allocation} before \code{explicate-control} because
  5695. \code{expose-allocation} introduces new variables using \code{let},
  5696. but \code{let} is gone after \code{explicate-control}.
  5697. The output of \code{expose-allocation} is a language $R'_3$ that
  5698. extends $R_3$ with the three new forms that we use in the translation
  5699. of the \code{vector} form.
  5700. \[
  5701. \begin{array}{lcl}
  5702. \Exp &::=& \cdots
  5703. \mid (\key{collect} \,\itm{int})
  5704. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5705. \mid (\key{global-value} \,\itm{name})
  5706. \end{array}
  5707. \]
  5708. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5709. $n$ bytes. It will become a call to the \code{collect} function in
  5710. \code{runtime.c} in \code{select-instructions}. The
  5711. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5712. \index{allocate}
  5713. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5714. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5715. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5716. a global variable, such as \code{free\_ptr}.
  5717. In the following, we show the transformation for the \code{vector}
  5718. form into 1) a sequence of let-bindings for the initializing
  5719. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5720. \code{allocate}, and 4) the initialization of the vector. In the
  5721. following, \itm{len} refers to the length of the vector and
  5722. \itm{bytes} is how many total bytes need to be allocated for the
  5723. vector, which is 8 for the tag plus \itm{len} times 8.
  5724. \begin{lstlisting}
  5725. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5726. |$\Longrightarrow$|
  5727. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5728. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5729. (global-value fromspace_end))
  5730. (void)
  5731. (collect |\itm{bytes}|))])
  5732. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5733. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5734. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5735. |$v$|) ... )))) ...)
  5736. \end{lstlisting}
  5737. In the above, we suppressed all of the \code{has-type} forms in the
  5738. output for the sake of readability. The placement of the initializing
  5739. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5740. sequence of \code{vector-set!} is important, as those expressions may
  5741. trigger garbage collection and we cannot have an allocated but
  5742. uninitialized tuple on the heap during a collection.
  5743. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5744. \code{expose-allocation} pass on our running example.
  5745. \begin{figure}[tbp]
  5746. % tests/s2_17.rkt
  5747. \begin{lstlisting}
  5748. (vector-ref
  5749. (vector-ref
  5750. (let ([vecinit7976
  5751. (let ([vecinit7972 42])
  5752. (let ([collectret7974
  5753. (if (< (+ (global-value free_ptr) 16)
  5754. (global-value fromspace_end))
  5755. (void)
  5756. (collect 16)
  5757. )])
  5758. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5759. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5760. alloc7971)
  5761. )
  5762. )
  5763. )
  5764. ])
  5765. (let ([collectret7978
  5766. (if (< (+ (global-value free_ptr) 16)
  5767. (global-value fromspace_end))
  5768. (void)
  5769. (collect 16)
  5770. )])
  5771. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5772. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5773. alloc7975)
  5774. )
  5775. )
  5776. )
  5777. 0)
  5778. 0)
  5779. \end{lstlisting}
  5780. \caption{Output of the \code{expose-allocation} pass, minus
  5781. all of the \code{has-type} forms.}
  5782. \label{fig:expose-alloc-output}
  5783. \end{figure}
  5784. \section{Remove Complex Operands}
  5785. \label{sec:remove-complex-opera-R3}
  5786. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5787. should all be treated as complex operands.
  5788. %% A new case for
  5789. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5790. %% handled carefully to prevent the \code{Prim} node from being separated
  5791. %% from its enclosing \code{HasType}.
  5792. Figure~\ref{fig:r3-anf-syntax}
  5793. shows the grammar for the output language $R_3^{\dagger}$ of this
  5794. pass, which is $R_3$ in administrative normal form.
  5795. \begin{figure}[tp]
  5796. \centering
  5797. \fbox{
  5798. \begin{minipage}{0.96\textwidth}
  5799. \small
  5800. \[
  5801. \begin{array}{rcl}
  5802. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5803. \mid \VOID{} \\
  5804. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5805. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5806. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5807. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5808. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5809. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5810. \mid \LP\key{GlobalValue}~\Var\RP\\
  5811. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5812. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5813. \end{array}
  5814. \]
  5815. \end{minipage}
  5816. }
  5817. \caption{$R_3^{\dagger}$ is $R_3$ in administrative normal form (ANF).}
  5818. \label{fig:r3-anf-syntax}
  5819. \end{figure}
  5820. \section{Explicate Control and the $C_2$ language}
  5821. \label{sec:explicate-control-r3}
  5822. \begin{figure}[tbp]
  5823. \fbox{
  5824. \begin{minipage}{0.96\textwidth}
  5825. \small
  5826. \[
  5827. \begin{array}{lcl}
  5828. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5829. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5830. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5831. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5832. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5833. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5834. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5835. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5836. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5837. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5838. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5839. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5840. \end{array}
  5841. \]
  5842. \end{minipage}
  5843. }
  5844. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5845. \label{fig:c2-concrete-syntax}
  5846. \end{figure}
  5847. \begin{figure}[tp]
  5848. \fbox{
  5849. \begin{minipage}{0.96\textwidth}
  5850. \small
  5851. \[
  5852. \begin{array}{lcl}
  5853. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5854. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5855. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5856. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5857. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5858. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5859. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5860. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5861. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5862. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5863. \mid (\key{Collect} \,\itm{int}) \\
  5864. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5865. \mid \GOTO{\itm{label}} } \\
  5866. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5867. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5868. \end{array}
  5869. \]
  5870. \end{minipage}
  5871. }
  5872. \caption{The abstract syntax of $C_2$, extending $C_1$
  5873. (Figure~\ref{fig:c1-syntax}).}
  5874. \label{fig:c2-syntax}
  5875. \end{figure}
  5876. The output of \code{explicate-control} is a program in the
  5877. intermediate language $C_2$, whose concrete syntax is defined in
  5878. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5879. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5880. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5881. \key{global-value} expressions and the \code{collect} statement. The
  5882. \code{explicate-control} pass can treat these new forms much like the
  5883. other expression forms that we've already encoutered.
  5884. \section{Select Instructions and the x86$_2$ Language}
  5885. \label{sec:select-instructions-gc}
  5886. \index{instruction selection}
  5887. %% void (rep as zero)
  5888. %% allocate
  5889. %% collect (callq collect)
  5890. %% vector-ref
  5891. %% vector-set!
  5892. %% global (postpone)
  5893. In this pass we generate x86 code for most of the new operations that
  5894. were needed to compile tuples, including \code{Allocate},
  5895. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5896. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5897. the later has a different concrete syntax (see
  5898. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5899. \index{x86}
  5900. The \code{vector-ref} and \code{vector-set!} forms translate into
  5901. \code{movq} instructions. (The plus one in the offset is to get past
  5902. the tag at the beginning of the tuple representation.)
  5903. \begin{lstlisting}
  5904. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5905. |$\Longrightarrow$|
  5906. movq |$\itm{vec}'$|, %r11
  5907. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5908. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5909. |$\Longrightarrow$|
  5910. movq |$\itm{vec}'$|, %r11
  5911. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5912. movq $0, |$\itm{lhs'}$|
  5913. \end{lstlisting}
  5914. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5915. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5916. register \code{r11} ensures that offset expression
  5917. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5918. removing \code{r11} from consideration by the register allocating.
  5919. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5920. \code{rax}. Then the generated code for \code{vector-set!} would be
  5921. \begin{lstlisting}
  5922. movq |$\itm{vec}'$|, %rax
  5923. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5924. movq $0, |$\itm{lhs}'$|
  5925. \end{lstlisting}
  5926. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5927. \code{patch-instructions} would insert a move through \code{rax}
  5928. as follows.
  5929. \begin{lstlisting}
  5930. movq |$\itm{vec}'$|, %rax
  5931. movq |$\itm{arg}'$|, %rax
  5932. movq %rax, |$8(n+1)$|(%rax)
  5933. movq $0, |$\itm{lhs}'$|
  5934. \end{lstlisting}
  5935. But the above sequence of instructions does not work because we're
  5936. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5937. $\itm{arg}'$) at the same time!
  5938. We compile the \code{allocate} form to operations on the
  5939. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5940. is the next free address in the FromSpace, so we copy it into
  5941. \code{r11} and then move it forward by enough space for the tuple
  5942. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5943. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5944. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5945. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5946. tag is organized. We recommend using the Racket operations
  5947. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5948. during compilation. The type annotation in the \code{vector} form is
  5949. used to determine the pointer mask region of the tag.
  5950. \begin{lstlisting}
  5951. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5952. |$\Longrightarrow$|
  5953. movq free_ptr(%rip), %r11
  5954. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5955. movq $|$\itm{tag}$|, 0(%r11)
  5956. movq %r11, |$\itm{lhs}'$|
  5957. \end{lstlisting}
  5958. The \code{collect} form is compiled to a call to the \code{collect}
  5959. function in the runtime. The arguments to \code{collect} are 1) the
  5960. top of the root stack and 2) the number of bytes that need to be
  5961. allocated. We use another dedicated register, \code{r15}, to
  5962. store the pointer to the top of the root stack. So \code{r15} is not
  5963. available for use by the register allocator.
  5964. \begin{lstlisting}
  5965. (collect |$\itm{bytes}$|)
  5966. |$\Longrightarrow$|
  5967. movq %r15, %rdi
  5968. movq $|\itm{bytes}|, %rsi
  5969. callq collect
  5970. \end{lstlisting}
  5971. \begin{figure}[tp]
  5972. \fbox{
  5973. \begin{minipage}{0.96\textwidth}
  5974. \[
  5975. \begin{array}{lcl}
  5976. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5977. x86_1 &::= & \gray{ \key{.globl main} }\\
  5978. & & \gray{ \key{main:} \; \Instr\ldots }
  5979. \end{array}
  5980. \]
  5981. \end{minipage}
  5982. }
  5983. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5984. \label{fig:x86-2-concrete}
  5985. \end{figure}
  5986. \begin{figure}[tp]
  5987. \fbox{
  5988. \begin{minipage}{0.96\textwidth}
  5989. \small
  5990. \[
  5991. \begin{array}{lcl}
  5992. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5993. \mid \BYTEREG{\Reg}} \\
  5994. &\mid& (\key{Global}~\Var) \\
  5995. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5996. \end{array}
  5997. \]
  5998. \end{minipage}
  5999. }
  6000. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  6001. \label{fig:x86-2}
  6002. \end{figure}
  6003. The concrete and abstract syntax of the $x86_2$ language is defined in
  6004. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  6005. x86$_1$ just in the addition of the form for global variables.
  6006. %
  6007. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6008. \code{select-instructions} pass on the running example.
  6009. \begin{figure}[tbp]
  6010. \centering
  6011. % tests/s2_17.rkt
  6012. \begin{minipage}[t]{0.5\textwidth}
  6013. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6014. block35:
  6015. movq free_ptr(%rip), alloc9024
  6016. addq $16, free_ptr(%rip)
  6017. movq alloc9024, %r11
  6018. movq $131, 0(%r11)
  6019. movq alloc9024, %r11
  6020. movq vecinit9025, 8(%r11)
  6021. movq $0, initret9026
  6022. movq alloc9024, %r11
  6023. movq 8(%r11), tmp9034
  6024. movq tmp9034, %r11
  6025. movq 8(%r11), %rax
  6026. jmp conclusion
  6027. block36:
  6028. movq $0, collectret9027
  6029. jmp block35
  6030. block38:
  6031. movq free_ptr(%rip), alloc9020
  6032. addq $16, free_ptr(%rip)
  6033. movq alloc9020, %r11
  6034. movq $3, 0(%r11)
  6035. movq alloc9020, %r11
  6036. movq vecinit9021, 8(%r11)
  6037. movq $0, initret9022
  6038. movq alloc9020, vecinit9025
  6039. movq free_ptr(%rip), tmp9031
  6040. movq tmp9031, tmp9032
  6041. addq $16, tmp9032
  6042. movq fromspace_end(%rip), tmp9033
  6043. cmpq tmp9033, tmp9032
  6044. jl block36
  6045. jmp block37
  6046. block37:
  6047. movq %r15, %rdi
  6048. movq $16, %rsi
  6049. callq 'collect
  6050. jmp block35
  6051. block39:
  6052. movq $0, collectret9023
  6053. jmp block38
  6054. \end{lstlisting}
  6055. \end{minipage}
  6056. \begin{minipage}[t]{0.45\textwidth}
  6057. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6058. start:
  6059. movq $42, vecinit9021
  6060. movq free_ptr(%rip), tmp9028
  6061. movq tmp9028, tmp9029
  6062. addq $16, tmp9029
  6063. movq fromspace_end(%rip), tmp9030
  6064. cmpq tmp9030, tmp9029
  6065. jl block39
  6066. jmp block40
  6067. block40:
  6068. movq %r15, %rdi
  6069. movq $16, %rsi
  6070. callq 'collect
  6071. jmp block38
  6072. \end{lstlisting}
  6073. \end{minipage}
  6074. \caption{Output of the \code{select-instructions} pass.}
  6075. \label{fig:select-instr-output-gc}
  6076. \end{figure}
  6077. \clearpage
  6078. \section{Register Allocation}
  6079. \label{sec:reg-alloc-gc}
  6080. \index{register allocation}
  6081. As discussed earlier in this chapter, the garbage collector needs to
  6082. access all the pointers in the root set, that is, all variables that
  6083. are vectors. It will be the responsibility of the register allocator
  6084. to make sure that:
  6085. \begin{enumerate}
  6086. \item the root stack is used for spilling vector-typed variables, and
  6087. \item if a vector-typed variable is live during a call to the
  6088. collector, it must be spilled to ensure it is visible to the
  6089. collector.
  6090. \end{enumerate}
  6091. The later responsibility can be handled during construction of the
  6092. interference graph, by adding interference edges between the call-live
  6093. vector-typed variables and all the callee-saved registers. (They
  6094. already interfere with the caller-saved registers.) The type
  6095. information for variables is in the \code{Program} form, so we
  6096. recommend adding another parameter to the \code{build-interference}
  6097. function to communicate this alist.
  6098. The spilling of vector-typed variables to the root stack can be
  6099. handled after graph coloring, when choosing how to assign the colors
  6100. (integers) to registers and stack locations. The \code{Program} output
  6101. of this pass changes to also record the number of spills to the root
  6102. stack.
  6103. % build-interference
  6104. %
  6105. % callq
  6106. % extra parameter for var->type assoc. list
  6107. % update 'program' and 'if'
  6108. % allocate-registers
  6109. % allocate spilled vectors to the rootstack
  6110. % don't change color-graph
  6111. \section{Print x86}
  6112. \label{sec:print-x86-gc}
  6113. \index{prelude}\index{conclusion}
  6114. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6115. \code{print-x86} pass on the running example. In the prelude and
  6116. conclusion of the \code{main} function, we treat the root stack very
  6117. much like the regular stack in that we move the root stack pointer
  6118. (\code{r15}) to make room for the spills to the root stack, except
  6119. that the root stack grows up instead of down. For the running
  6120. example, there was just one spill so we increment \code{r15} by 8
  6121. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6122. One issue that deserves special care is that there may be a call to
  6123. \code{collect} prior to the initializing assignments for all the
  6124. variables in the root stack. We do not want the garbage collector to
  6125. accidentally think that some uninitialized variable is a pointer that
  6126. needs to be followed. Thus, we zero-out all locations on the root
  6127. stack in the prelude of \code{main}. In
  6128. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6129. %
  6130. \lstinline{movq $0, (%r15)}
  6131. %
  6132. accomplishes this task. The garbage collector tests each root to see
  6133. if it is null prior to dereferencing it.
  6134. \begin{figure}[htbp]
  6135. \begin{minipage}[t]{0.5\textwidth}
  6136. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6137. block35:
  6138. movq free_ptr(%rip), %rcx
  6139. addq $16, free_ptr(%rip)
  6140. movq %rcx, %r11
  6141. movq $131, 0(%r11)
  6142. movq %rcx, %r11
  6143. movq -8(%r15), %rax
  6144. movq %rax, 8(%r11)
  6145. movq $0, %rdx
  6146. movq %rcx, %r11
  6147. movq 8(%r11), %rcx
  6148. movq %rcx, %r11
  6149. movq 8(%r11), %rax
  6150. jmp conclusion
  6151. block36:
  6152. movq $0, %rcx
  6153. jmp block35
  6154. block38:
  6155. movq free_ptr(%rip), %rcx
  6156. addq $16, free_ptr(%rip)
  6157. movq %rcx, %r11
  6158. movq $3, 0(%r11)
  6159. movq %rcx, %r11
  6160. movq %rbx, 8(%r11)
  6161. movq $0, %rdx
  6162. movq %rcx, -8(%r15)
  6163. movq free_ptr(%rip), %rcx
  6164. addq $16, %rcx
  6165. movq fromspace_end(%rip), %rdx
  6166. cmpq %rdx, %rcx
  6167. jl block36
  6168. movq %r15, %rdi
  6169. movq $16, %rsi
  6170. callq collect
  6171. jmp block35
  6172. block39:
  6173. movq $0, %rcx
  6174. jmp block38
  6175. \end{lstlisting}
  6176. \end{minipage}
  6177. \begin{minipage}[t]{0.45\textwidth}
  6178. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6179. start:
  6180. movq $42, %rbx
  6181. movq free_ptr(%rip), %rdx
  6182. addq $16, %rdx
  6183. movq fromspace_end(%rip), %rcx
  6184. cmpq %rcx, %rdx
  6185. jl block39
  6186. movq %r15, %rdi
  6187. movq $16, %rsi
  6188. callq collect
  6189. jmp block38
  6190. .globl main
  6191. main:
  6192. pushq %rbp
  6193. movq %rsp, %rbp
  6194. pushq %r13
  6195. pushq %r12
  6196. pushq %rbx
  6197. pushq %r14
  6198. subq $0, %rsp
  6199. movq $16384, %rdi
  6200. movq $16384, %rsi
  6201. callq initialize
  6202. movq rootstack_begin(%rip), %r15
  6203. movq $0, (%r15)
  6204. addq $8, %r15
  6205. jmp start
  6206. conclusion:
  6207. subq $8, %r15
  6208. addq $0, %rsp
  6209. popq %r14
  6210. popq %rbx
  6211. popq %r12
  6212. popq %r13
  6213. popq %rbp
  6214. retq
  6215. \end{lstlisting}
  6216. \end{minipage}
  6217. \caption{Output of the \code{print-x86} pass.}
  6218. \label{fig:print-x86-output-gc}
  6219. \end{figure}
  6220. \begin{figure}[p]
  6221. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6222. \node (R3) at (0,2) {\large $R_3$};
  6223. \node (R3-2) at (3,2) {\large $R_3$};
  6224. \node (R3-3) at (6,2) {\large $R_3$};
  6225. \node (R3-4) at (9,2) {\large $R_3$};
  6226. \node (R3-5) at (12,2) {\large $R'_3$};
  6227. \node (C2-4) at (3,0) {\large $C_2$};
  6228. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  6229. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  6230. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  6231. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  6232. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  6233. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  6234. %\path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6235. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize shrink} (R3-2);
  6236. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  6237. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  6238. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  6239. \path[->,bend left=20] (R3-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6240. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6241. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6242. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6243. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6244. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6245. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6246. \end{tikzpicture}
  6247. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6248. \label{fig:R3-passes}
  6249. \end{figure}
  6250. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6251. for the compilation of $R_3$.
  6252. \section{Challenge: Simple Structures}
  6253. \label{sec:simple-structures}
  6254. \index{struct}
  6255. \index{structure}
  6256. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6257. $R^s_3$, which extends $R^3$ with support for simple structures.
  6258. Recall that a \code{struct} in Typed Racket is a user-defined data
  6259. type that contains named fields and that is heap allocated, similar to
  6260. a vector. The following is an example of a structure definition, in
  6261. this case the definition of a \code{point} type.
  6262. \begin{lstlisting}
  6263. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6264. \end{lstlisting}
  6265. \begin{figure}[tbp]
  6266. \centering
  6267. \fbox{
  6268. \begin{minipage}{0.96\textwidth}
  6269. \[
  6270. \begin{array}{lcl}
  6271. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6272. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6273. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6274. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6275. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6276. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6277. \mid (\key{and}\;\Exp\;\Exp)
  6278. \mid (\key{or}\;\Exp\;\Exp)
  6279. \mid (\key{not}\;\Exp) } \\
  6280. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6281. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6282. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6283. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6284. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6285. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6286. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6287. R_3 &::=& \Def \ldots \; \Exp
  6288. \end{array}
  6289. \]
  6290. \end{minipage}
  6291. }
  6292. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6293. (Figure~\ref{fig:r3-concrete-syntax}).}
  6294. \label{fig:r3s-concrete-syntax}
  6295. \end{figure}
  6296. An instance of a structure is created using function call syntax, with
  6297. the name of the structure in the function position:
  6298. \begin{lstlisting}
  6299. (point 7 12)
  6300. \end{lstlisting}
  6301. Function-call syntax is also used to read the value in a field of a
  6302. structure. The function name is formed by the structure name, a dash,
  6303. and the field name. The following example uses \code{point-x} and
  6304. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6305. instances.
  6306. \begin{center}
  6307. \begin{lstlisting}
  6308. (let ([pt1 (point 7 12)])
  6309. (let ([pt2 (point 4 3)])
  6310. (+ (- (point-x pt1) (point-x pt2))
  6311. (- (point-y pt1) (point-y pt2)))))
  6312. \end{lstlisting}
  6313. \end{center}
  6314. Similarly, to write to a field of a structure, use its set function,
  6315. whose name starts with \code{set-}, followed by the structure name,
  6316. then a dash, then the field name, and concluded with an exclamation
  6317. mark. The following example uses \code{set-point-x!} to change the
  6318. \code{x} field from \code{7} to \code{42}.
  6319. \begin{center}
  6320. \begin{lstlisting}
  6321. (let ([pt (point 7 12)])
  6322. (let ([_ (set-point-x! pt 42)])
  6323. (point-x pt)))
  6324. \end{lstlisting}
  6325. \end{center}
  6326. \begin{exercise}\normalfont
  6327. Extend your compiler with support for simple structures, compiling
  6328. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6329. structures and test your compiler.
  6330. \end{exercise}
  6331. \section{Challenge: Generational Collection}
  6332. The copying collector described in Section~\ref{sec:GC} can incur
  6333. significant runtime overhead because the call to \code{collect} takes
  6334. time proportional to all of the live data. One way to reduce this
  6335. overhead is to reduce how much data is inspected in each call to
  6336. \code{collect}. In particular, researchers have observed that recently
  6337. allocated data is more likely to become garbage then data that has
  6338. survived one or more previous calls to \code{collect}. This insight
  6339. motivated the creation of \emph{generational garbage collectors}
  6340. \index{generational garbage collector} that
  6341. 1) segregates data according to its age into two or more generations,
  6342. 2) allocates less space for younger generations, so collecting them is
  6343. faster, and more space for the older generations, and 3) performs
  6344. collection on the younger generations more frequently then for older
  6345. generations~\citep{Wilson:1992fk}.
  6346. For this challenge assignment, the goal is to adapt the copying
  6347. collector implemented in \code{runtime.c} to use two generations, one
  6348. for young data and one for old data. Each generation consists of a
  6349. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6350. \code{collect} function to use the two generations.
  6351. \begin{enumerate}
  6352. \item Copy the young generation's FromSpace to its ToSpace then switch
  6353. the role of the ToSpace and FromSpace
  6354. \item If there is enough space for the requested number of bytes in
  6355. the young FromSpace, then return from \code{collect}.
  6356. \item If there is not enough space in the young FromSpace for the
  6357. requested bytes, then move the data from the young generation to the
  6358. old one with the following steps:
  6359. \begin{enumerate}
  6360. \item If there is enough room in the old FromSpace, copy the young
  6361. FromSpace to the old FromSpace and then return.
  6362. \item If there is not enough room in the old FromSpace, then collect
  6363. the old generation by copying the old FromSpace to the old ToSpace
  6364. and swap the roles of the old FromSpace and ToSpace.
  6365. \item If there is enough room now, copy the young FromSpace to the
  6366. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6367. and ToSpace for the old generation. Copy the young FromSpace and
  6368. the old FromSpace into the larger FromSpace for the old
  6369. generation and then return.
  6370. \end{enumerate}
  6371. \end{enumerate}
  6372. We recommend that you generalize the \code{cheney} function so that it
  6373. can be used for all the copies mentioned above: between the young
  6374. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6375. between the young FromSpace and old FromSpace. This can be
  6376. accomplished by adding parameters to \code{cheney} that replace its
  6377. use of the global variables \code{fromspace\_begin},
  6378. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6379. Note that the collection of the young generation does not traverse the
  6380. old generation. This introduces a potential problem: there may be
  6381. young data that is only reachable through pointers in the old
  6382. generation. If these pointers are not taken into account, the
  6383. collector could throw away young data that is live! One solution,
  6384. called \emph{pointer recording}, is to maintain a set of all the
  6385. pointers from the old generation into the new generation and consider
  6386. this set as part of the root set. To maintain this set, the compiler
  6387. must insert extra instructions around every \code{vector-set!}. If the
  6388. vector being modified is in the old generation, and if the value being
  6389. written is a pointer into the new generation, than that pointer must
  6390. be added to the set. Also, if the value being overwritten was a
  6391. pointer into the new generation, then that pointer should be removed
  6392. from the set.
  6393. \begin{exercise}\normalfont
  6394. Adapt the \code{collect} function in \code{runtime.c} to implement
  6395. generational garbage collection, as outlined in this section.
  6396. Update the code generation for \code{vector-set!} to implement
  6397. pointer recording. Make sure that your new compiler and runtime
  6398. passes your test suite.
  6399. \end{exercise}
  6400. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6401. \chapter{Functions}
  6402. \label{ch:functions}
  6403. \index{function}
  6404. This chapter studies the compilation of functions similar to those
  6405. found in the C language. This corresponds to a subset of Typed Racket
  6406. in which only top-level function definitions are allowed. This kind of
  6407. function is an important stepping stone to implementing
  6408. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6409. is the topic of Chapter~\ref{ch:lambdas}.
  6410. \section{The $R_4$ Language}
  6411. The concrete and abstract syntax for function definitions and function
  6412. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6413. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6414. $R_4$ begin with zero or more function definitions. The function
  6415. names from these definitions are in-scope for the entire program,
  6416. including all other function definitions (so the ordering of function
  6417. definitions does not matter). The concrete syntax for function
  6418. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6419. where the first expression must
  6420. evaluate to a function and the rest are the arguments.
  6421. The abstract syntax for function application is
  6422. $\APPLY{\Exp}{\Exp\ldots}$.
  6423. %% The syntax for function application does not include an explicit
  6424. %% keyword, which is error prone when using \code{match}. To alleviate
  6425. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6426. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6427. Functions are first-class in the sense that a function pointer
  6428. \index{function pointer} is data and can be stored in memory or passed
  6429. as a parameter to another function. Thus, we introduce a function
  6430. type, written
  6431. \begin{lstlisting}
  6432. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6433. \end{lstlisting}
  6434. for a function whose $n$ parameters have the types $\Type_1$ through
  6435. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6436. these functions (with respect to Racket functions) is that they are
  6437. not lexically scoped. That is, the only external entities that can be
  6438. referenced from inside a function body are other globally-defined
  6439. functions. The syntax of $R_4$ prevents functions from being nested
  6440. inside each other.
  6441. \begin{figure}[tp]
  6442. \centering
  6443. \fbox{
  6444. \begin{minipage}{0.96\textwidth}
  6445. \small
  6446. \[
  6447. \begin{array}{lcl}
  6448. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6449. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6450. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6451. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6452. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6453. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6454. \mid (\key{and}\;\Exp\;\Exp)
  6455. \mid (\key{or}\;\Exp\;\Exp)
  6456. \mid (\key{not}\;\Exp)} \\
  6457. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6458. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6459. (\key{vector-ref}\;\Exp\;\Int)} \\
  6460. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6461. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6462. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6463. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6464. R_4 &::=& \Def \ldots \; \Exp
  6465. \end{array}
  6466. \]
  6467. \end{minipage}
  6468. }
  6469. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6470. \label{fig:r4-concrete-syntax}
  6471. \end{figure}
  6472. \begin{figure}[tp]
  6473. \centering
  6474. \fbox{
  6475. \begin{minipage}{0.96\textwidth}
  6476. \small
  6477. \[
  6478. \begin{array}{lcl}
  6479. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6480. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6481. &\mid& \gray{ \BOOL{\itm{bool}}
  6482. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6483. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6484. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6485. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6486. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6487. \end{array}
  6488. \]
  6489. \end{minipage}
  6490. }
  6491. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6492. \label{fig:r4-syntax}
  6493. \end{figure}
  6494. The program in Figure~\ref{fig:r4-function-example} is a
  6495. representative example of defining and using functions in $R_4$. We
  6496. define a function \code{map-vec} that applies some other function
  6497. \code{f} to both elements of a vector and returns a new
  6498. vector containing the results. We also define a function \code{add1}.
  6499. The program applies
  6500. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6501. \code{(vector 1 42)}, from which we return the \code{42}.
  6502. \begin{figure}[tbp]
  6503. \begin{lstlisting}
  6504. (define (map-vec [f : (Integer -> Integer)]
  6505. [v : (Vector Integer Integer)])
  6506. : (Vector Integer Integer)
  6507. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6508. (define (add1 [x : Integer]) : Integer
  6509. (+ x 1))
  6510. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6511. \end{lstlisting}
  6512. \caption{Example of using functions in $R_4$.}
  6513. \label{fig:r4-function-example}
  6514. \end{figure}
  6515. The definitional interpreter for $R_4$ is in
  6516. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6517. responsible for setting up the mutual recursion between the top-level
  6518. function definitions. We use the classic back-patching \index{back-patching}
  6519. approach that uses mutable variables and makes two passes over the function
  6520. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6521. top-level environment using a mutable cons cell for each function
  6522. definition. Note that the \code{lambda} value for each function is
  6523. incomplete; it does not yet include the environment. Once the
  6524. top-level environment is constructed, we then iterate over it and
  6525. update the \code{lambda} values to use the top-level environment.
  6526. \begin{figure}[tp]
  6527. \begin{lstlisting}
  6528. (define (interp-exp env)
  6529. (lambda (e)
  6530. (define recur (interp-exp env))
  6531. (match e
  6532. ...
  6533. [(Apply fun args)
  6534. (define fun-val (recur fun))
  6535. (define arg-vals (for/list ([e args]) (recur e)))
  6536. (match fun-val
  6537. [`(function (,xs ...) ,body ,fun-env)
  6538. (define new-env (append (map cons xs arg-vals) fun-env))
  6539. ((interp-exp new-env) body)])]
  6540. ...
  6541. )))
  6542. (define (interp-def d)
  6543. (match d
  6544. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6545. (mcons f `(function ,xs ,body ()))]
  6546. ))
  6547. (define (interp-R4 p)
  6548. (match p
  6549. [(ProgramDefsExp info ds body)
  6550. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6551. (for/list ([b top-level])
  6552. (set-mcdr! b (match (mcdr b)
  6553. [`(function ,xs ,body ())
  6554. `(function ,xs ,body ,top-level)])))
  6555. ((interp-exp top-level) body))]
  6556. ))
  6557. \end{lstlisting}
  6558. \caption{Interpreter for the $R_4$ language.}
  6559. \label{fig:interp-R4}
  6560. \end{figure}
  6561. \margincomment{TODO: explain type checker}
  6562. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6563. \begin{figure}[tp]
  6564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6565. (define (fun-def-name d)
  6566. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6567. (define (fun-def-type d)
  6568. (match d
  6569. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6570. (define (type-check-exp env)
  6571. (lambda (e)
  6572. (match e
  6573. ...
  6574. [(Apply e es)
  6575. (define-values (e^ ty) ((type-check-exp env) e))
  6576. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6577. ((type-check-exp env) e)))
  6578. (match ty
  6579. [`(,ty^* ... -> ,rt)
  6580. (for ([arg-ty ty*] [prm-ty ty^*])
  6581. (unless (equal? arg-ty prm-ty)
  6582. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6583. (values (HasType (Apply e^ e*) rt) rt)]
  6584. [else (error "expected a function, not" ty)])])))
  6585. (define (type-check-def env)
  6586. (lambda (e)
  6587. (match e
  6588. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6589. (define new-env (append (map cons xs ps) env))
  6590. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6591. (unless (equal? ty^ rt)
  6592. (error "body type ~a not equal to return type ~a" ty^ rt))
  6593. (Def f p:t* rt info body^)])))
  6594. (define (type-check env)
  6595. (lambda (e)
  6596. (match e
  6597. [(ProgramDefsExp info ds body)
  6598. (define new-env (for/list ([d ds])
  6599. (cons (fun-def-name d) (fun-def-type d))))
  6600. (define ds^ (for/list ([d ds])
  6601. ((type-check-def new-env) d)))
  6602. (define-values (body^ ty) ((type-check-exp new-env) body))
  6603. (unless (equal? ty 'Integer)
  6604. (error "result of the program must be an integer, not " ty))
  6605. (ProgramDefsExp info ds^ body^)]
  6606. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6607. \end{lstlisting}
  6608. \caption{Type checker for the $R_4$ language.}
  6609. \label{fig:type-check-R4}
  6610. \end{figure}
  6611. \section{Functions in x86}
  6612. \label{sec:fun-x86}
  6613. \margincomment{\tiny Make sure callee-saved registers are discussed
  6614. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6615. \margincomment{\tiny Talk about the return address on the
  6616. stack and what callq and retq does.\\ --Jeremy }
  6617. The x86 architecture provides a few features to support the
  6618. implementation of functions. We have already seen that x86 provides
  6619. labels so that one can refer to the location of an instruction, as is
  6620. needed for jump instructions. Labels can also be used to mark the
  6621. beginning of the instructions for a function. Going further, we can
  6622. obtain the address of a label by using the \key{leaq} instruction and
  6623. PC-relative addressing. For example, the following puts the
  6624. address of the \code{add1} label into the \code{rbx} register.
  6625. \begin{lstlisting}
  6626. leaq add1(%rip), %rbx
  6627. \end{lstlisting}
  6628. The instruction pointer register \key{rip} (aka. the program counter
  6629. \index{program counter}) always points to the next instruction to be
  6630. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6631. linker computes the distance $d$ between the address of \code{add1}
  6632. and where the \code{rip} would be at that moment and then changes
  6633. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6634. the address of \code{add1}.
  6635. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6636. jump to a function whose location is given by a label. To support
  6637. function calls in this chapter we instead will be jumping to a
  6638. function whose location is given by an address in a register, that is,
  6639. we need to make an \emph{indirect function call}. The x86 syntax for
  6640. this is a \code{callq} instruction but with an asterisk before the
  6641. register name.\index{indirect function call}
  6642. \begin{lstlisting}
  6643. callq *%rbx
  6644. \end{lstlisting}
  6645. \subsection{Calling Conventions}
  6646. \index{calling conventions}
  6647. The \code{callq} instruction provides partial support for implementing
  6648. functions: it pushes the return address on the stack and it jumps to
  6649. the target. However, \code{callq} does not handle
  6650. \begin{enumerate}
  6651. \item parameter passing,
  6652. \item pushing frames on the procedure call stack and popping them off,
  6653. or
  6654. \item determining how registers are shared by different functions.
  6655. \end{enumerate}
  6656. Regarding (1) parameter passing, recall that the following six
  6657. registers are used to pass arguments to a function, in this order.
  6658. \begin{lstlisting}
  6659. rdi rsi rdx rcx r8 r9
  6660. \end{lstlisting}
  6661. If there are
  6662. more than six arguments, then the convention is to use space on the
  6663. frame of the caller for the rest of the arguments. However, to ease
  6664. the implementation of efficient tail calls
  6665. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6666. arguments.
  6667. %
  6668. Also recall that the register \code{rax} is for the return value of
  6669. the function.
  6670. \index{prelude}\index{conclusion}
  6671. Regarding (2) frames \index{frame} and the procedure call stack,
  6672. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6673. the stack grows down, with each function call using a chunk of space
  6674. called a frame. The caller sets the stack pointer, register
  6675. \code{rsp}, to the last data item in its frame. The callee must not
  6676. change anything in the caller's frame, that is, anything that is at or
  6677. above the stack pointer. The callee is free to use locations that are
  6678. below the stack pointer.
  6679. Recall that we are storing variables of vector type on the root stack.
  6680. So the prelude needs to move the root stack pointer \code{r15} up and
  6681. the conclusion needs to move the root stack pointer back down. Also,
  6682. the prelude must initialize to \code{0} this frame's slots in the root
  6683. stack to signal to the garbage collector that those slots do not yet
  6684. contain a pointer to a vector. Otherwise the garbage collector will
  6685. interpret the garbage bits in those slots as memory addresses and try
  6686. to traverse them, causing serious mayhem!
  6687. Regarding (3) the sharing of registers between different functions,
  6688. recall from Section~\ref{sec:calling-conventions} that the registers
  6689. are divided into two groups, the caller-saved registers and the
  6690. callee-saved registers. The caller should assume that all the
  6691. caller-saved registers get overwritten with arbitrary values by the
  6692. callee. That is why we recommend in
  6693. Section~\ref{sec:calling-conventions} that variables that are live
  6694. during a function call should not be assigned to caller-saved
  6695. registers.
  6696. On the flip side, if the callee wants to use a callee-saved register,
  6697. the callee must save the contents of those registers on their stack
  6698. frame and then put them back prior to returning to the caller. That
  6699. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6700. the register allocator assigns a variable to a callee-saved register,
  6701. then the prelude of the \code{main} function must save that register
  6702. to the stack and the conclusion of \code{main} must restore it. This
  6703. recommendation now generalizes to all functions.
  6704. Also recall that the base pointer, register \code{rbp}, is used as a
  6705. point-of-reference within a frame, so that each local variable can be
  6706. accessed at a fixed offset from the base pointer
  6707. (Section~\ref{sec:x86}).
  6708. %
  6709. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6710. and callee frames.
  6711. \begin{figure}[tbp]
  6712. \centering
  6713. \begin{tabular}{r|r|l|l} \hline
  6714. Caller View & Callee View & Contents & Frame \\ \hline
  6715. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6716. 0(\key{\%rbp}) & & old \key{rbp} \\
  6717. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6718. \ldots & & \ldots \\
  6719. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6720. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6721. \ldots & & \ldots \\
  6722. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6723. %% & & \\
  6724. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6725. %% & \ldots & \ldots \\
  6726. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6727. \hline
  6728. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6729. & 0(\key{\%rbp}) & old \key{rbp} \\
  6730. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6731. & \ldots & \ldots \\
  6732. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6733. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6734. & \ldots & \ldots \\
  6735. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6736. \end{tabular}
  6737. \caption{Memory layout of caller and callee frames.}
  6738. \label{fig:call-frames}
  6739. \end{figure}
  6740. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6741. %% local variables and for storing the values of callee-saved registers
  6742. %% (we shall refer to all of these collectively as ``locals''), and that
  6743. %% at the beginning of a function we move the stack pointer \code{rsp}
  6744. %% down to make room for them.
  6745. %% We recommend storing the local variables
  6746. %% first and then the callee-saved registers, so that the local variables
  6747. %% can be accessed using \code{rbp} the same as before the addition of
  6748. %% functions.
  6749. %% To make additional room for passing arguments, we shall
  6750. %% move the stack pointer even further down. We count how many stack
  6751. %% arguments are needed for each function call that occurs inside the
  6752. %% body of the function and find their maximum. Adding this number to the
  6753. %% number of locals gives us how much the \code{rsp} should be moved at
  6754. %% the beginning of the function. In preparation for a function call, we
  6755. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6756. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6757. %% so on.
  6758. %% Upon calling the function, the stack arguments are retrieved by the
  6759. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6760. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6761. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6762. %% the layout of the caller and callee frames. Notice how important it is
  6763. %% that we correctly compute the maximum number of arguments needed for
  6764. %% function calls; if that number is too small then the arguments and
  6765. %% local variables will smash into each other!
  6766. \subsection{Efficient Tail Calls}
  6767. \label{sec:tail-call}
  6768. In general, the amount of stack space used by a program is determined
  6769. by the longest chain of nested function calls. That is, if function
  6770. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6771. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6772. $n$ can grow quite large in the case of recursive or mutually
  6773. recursive functions. However, in some cases we can arrange to use only
  6774. constant space, i.e. $O(1)$, instead of $O(n)$.
  6775. If a function call is the last action in a function body, then that
  6776. call is said to be a \emph{tail call}\index{tail call}.
  6777. For example, in the following
  6778. program, the recursive call to \code{tail-sum} is a tail call.
  6779. \begin{center}
  6780. \begin{lstlisting}
  6781. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6782. (if (eq? n 0)
  6783. r
  6784. (tail-sum (- n 1) (+ n r))))
  6785. (+ (tail-sum 5 0) 27)
  6786. \end{lstlisting}
  6787. \end{center}
  6788. At a tail call, the frame of the caller is no longer needed, so we
  6789. can pop the caller's frame before making the tail call. With this
  6790. approach, a recursive function that only makes tail calls will only
  6791. use $O(1)$ stack space. Functional languages like Racket typically
  6792. rely heavily on recursive functions, so they typically guarantee that
  6793. all tail calls will be optimized in this way.
  6794. \index{frame}
  6795. However, some care is needed with regards to argument passing in tail
  6796. calls. As mentioned above, for arguments beyond the sixth, the
  6797. convention is to use space in the caller's frame for passing
  6798. arguments. But for a tail call we pop the caller's frame and can no
  6799. longer use it. Another alternative is to use space in the callee's
  6800. frame for passing arguments. However, this option is also problematic
  6801. because the caller and callee's frame overlap in memory. As we begin
  6802. to copy the arguments from their sources in the caller's frame, the
  6803. target locations in the callee's frame might overlap with the sources
  6804. for later arguments! We solve this problem by not using the stack for
  6805. passing more than six arguments but instead using the heap, as we
  6806. describe in the Section~\ref{sec:limit-functions-r4}.
  6807. As mentioned above, for a tail call we pop the caller's frame prior to
  6808. making the tail call. The instructions for popping a frame are the
  6809. instructions that we usually place in the conclusion of a
  6810. function. Thus, we also need to place such code immediately before
  6811. each tail call. These instructions include restoring the callee-saved
  6812. registers, so it is good that the argument passing registers are all
  6813. caller-saved registers.
  6814. One last note regarding which instruction to use to make the tail
  6815. call. When the callee is finished, it should not return to the current
  6816. function, but it should return to the function that called the current
  6817. one. Thus, the return address that is already on the stack is the
  6818. right one, and we should not use \key{callq} to make the tail call, as
  6819. that would unnecessarily overwrite the return address. Instead we can
  6820. simply use the \key{jmp} instruction. Like the indirect function call,
  6821. we write an \emph{indirect jump}\index{indirect jump} with a register
  6822. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6823. jump target because the preceding conclusion overwrites just about
  6824. everything else.
  6825. \begin{lstlisting}
  6826. jmp *%rax
  6827. \end{lstlisting}
  6828. \section{Shrink $R_4$}
  6829. \label{sec:shrink-r4}
  6830. The \code{shrink} pass performs a minor modification to ease the
  6831. later passes. This pass introduces an explicit \code{main} function
  6832. and changes the top \code{ProgramDefsExp} form to
  6833. \code{ProgramDefs} as follows.
  6834. \begin{lstlisting}
  6835. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6836. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6837. \end{lstlisting}
  6838. where $\itm{mainDef}$ is
  6839. \begin{lstlisting}
  6840. (Def 'main '() 'Integer '() |$\Exp'$|)
  6841. \end{lstlisting}
  6842. \section{Reveal Functions and the $F_1$ language}
  6843. \label{sec:reveal-functions-r4}
  6844. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6845. respect: it conflates the use of function names and local
  6846. variables. This is a problem because we need to compile the use of a
  6847. function name differently than the use of a local variable; we need to
  6848. use \code{leaq} to convert the function name (a label in x86) to an
  6849. address in a register. Thus, it is a good idea to create a new pass
  6850. that changes function references from just a symbol $f$ to
  6851. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6852. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6853. The concrete syntax for a function reference is $\CFUNREF{f}$.
  6854. \begin{figure}[tp]
  6855. \centering
  6856. \fbox{
  6857. \begin{minipage}{0.96\textwidth}
  6858. \[
  6859. \begin{array}{lcl}
  6860. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  6861. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6862. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6863. \end{array}
  6864. \]
  6865. \end{minipage}
  6866. }
  6867. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6868. (Figure~\ref{fig:r4-syntax}).}
  6869. \label{fig:f1-syntax}
  6870. \end{figure}
  6871. %% Distinguishing between calls in tail position and non-tail position
  6872. %% requires the pass to have some notion of context. We recommend using
  6873. %% two mutually recursive functions, one for processing expressions in
  6874. %% tail position and another for the rest.
  6875. Placing this pass after \code{uniquify} will make sure that there are
  6876. no local variables and functions that share the same name. On the
  6877. other hand, \code{reveal-functions} needs to come before the
  6878. \code{explicate-control} pass because that pass helps us compile
  6879. \code{FunRef} forms into assignment statements.
  6880. \section{Limit Functions}
  6881. \label{sec:limit-functions-r4}
  6882. Recall that we wish to limit the number of function parameters to six
  6883. so that we do not need to use the stack for argument passing, which
  6884. makes it easier to implement efficient tail calls. However, because
  6885. the input language $R_4$ supports arbitrary numbers of function
  6886. arguments, we have some work to do!
  6887. This pass transforms functions and function calls that involve more
  6888. than six arguments to pass the first five arguments as usual, but it
  6889. packs the rest of the arguments into a vector and passes it as the
  6890. sixth argument.
  6891. Each function definition with too many parameters is transformed as
  6892. follows.
  6893. \begin{lstlisting}
  6894. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6895. |$\Rightarrow$|
  6896. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6897. \end{lstlisting}
  6898. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6899. the occurrences of the later parameters with vector references.
  6900. \begin{lstlisting}
  6901. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6902. \end{lstlisting}
  6903. For function calls with too many arguments, the \code{limit-functions}
  6904. pass transforms them in the following way.
  6905. \begin{tabular}{lll}
  6906. \begin{minipage}{0.2\textwidth}
  6907. \begin{lstlisting}
  6908. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6909. \end{lstlisting}
  6910. \end{minipage}
  6911. &
  6912. $\Rightarrow$
  6913. &
  6914. \begin{minipage}{0.4\textwidth}
  6915. \begin{lstlisting}
  6916. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6917. \end{lstlisting}
  6918. \end{minipage}
  6919. \end{tabular}
  6920. \section{Remove Complex Operands}
  6921. \label{sec:rco-r4}
  6922. The primary decisions to make for this pass is whether to classify
  6923. \code{FunRef} and \code{Apply} as either atomic or complex
  6924. expressions. Recall that a simple expression will eventually end up as
  6925. just an immediate argument of an x86 instruction. Function
  6926. application will be translated to a sequence of instructions, so
  6927. \code{Apply} must be classified as complex expression.
  6928. On the other hand, the arguments of \code{Apply} should be
  6929. atomic expressions.
  6930. %
  6931. Regarding \code{FunRef}, as discussed above, the function label needs
  6932. to be converted to an address using the \code{leaq} instruction. Thus,
  6933. even though \code{FunRef} seems rather simple, it needs to be
  6934. classified as a complex expression so that we generate an assignment
  6935. statement with a left-hand side that can serve as the target of the
  6936. \code{leaq}. Figure~\ref{fig:r4-anf-syntax} defines the
  6937. output language $R_4^{\dagger}$ of this pass.
  6938. \begin{figure}[tp]
  6939. \centering
  6940. \fbox{
  6941. \begin{minipage}{0.96\textwidth}
  6942. \small
  6943. \[
  6944. \begin{array}{rcl}
  6945. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  6946. \mid \VOID{} } \\
  6947. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6948. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6949. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6950. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6951. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6952. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6953. \mid \LP\key{GlobalValue}~\Var\RP }\\
  6954. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  6955. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6956. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  6957. \end{array}
  6958. \]
  6959. \end{minipage}
  6960. }
  6961. \caption{$R_4^{\dagger}$ is $R_4$ in administrative normal form (ANF).}
  6962. \label{fig:r4-anf-syntax}
  6963. \end{figure}
  6964. \section{Explicate Control and the $C_3$ language}
  6965. \label{sec:explicate-control-r4}
  6966. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6967. the concrete and abstract syntax for $C_3$, the output of
  6968. \key{explicate-control}. The auxiliary functions for assignment and
  6969. tail contexts should be updated with cases for \code{Apply} and
  6970. \code{FunRef} and the function for predicate context should be updated
  6971. for \code{Apply} but not \code{FunRef}. (A \code{FunRef} can't be a
  6972. Boolean.) In assignment and predicate contexts, \code{Apply} becomes
  6973. \code{Call}, whereas in tail position \code{Apply} becomes
  6974. \code{TailCall}. We recommend defining a new auxiliary function for
  6975. processing function definitions. This code is similar to the case for
  6976. \code{Program} in $R_3$. The top-level \code{explicate-control}
  6977. function that handles the \code{ProgramDefs} form of $R_4$ can then
  6978. apply this new function to all the function definitions.
  6979. \begin{figure}[tp]
  6980. \fbox{
  6981. \begin{minipage}{0.96\textwidth}
  6982. \small
  6983. \[
  6984. \begin{array}{lcl}
  6985. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6986. \\
  6987. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6988. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  6989. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  6990. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  6991. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  6992. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  6993. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  6994. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6995. \mid \LP\key{collect} \,\itm{int}\RP }\\
  6996. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  6997. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  6998. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  6999. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  7000. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  7001. C_3 & ::= & \Def\ldots
  7002. \end{array}
  7003. \]
  7004. \end{minipage}
  7005. }
  7006. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  7007. \label{fig:c3-concrete-syntax}
  7008. \end{figure}
  7009. \begin{figure}[tp]
  7010. \fbox{
  7011. \begin{minipage}{0.96\textwidth}
  7012. \small
  7013. \[
  7014. \begin{array}{lcl}
  7015. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7016. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7017. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7018. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7019. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7020. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7021. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7022. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7023. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7024. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7025. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7026. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7027. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7028. \mid \GOTO{\itm{label}} } \\
  7029. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7030. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7031. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7032. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7033. \end{array}
  7034. \]
  7035. \end{minipage}
  7036. }
  7037. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  7038. \label{fig:c3-syntax}
  7039. \end{figure}
  7040. \section{Select Instructions and the x86$_3$ Language}
  7041. \label{sec:select-r4}
  7042. \index{instruction selection}
  7043. The output of select instructions is a program in the x86$_3$
  7044. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7045. \index{x86}
  7046. \begin{figure}[tp]
  7047. \fbox{
  7048. \begin{minipage}{0.96\textwidth}
  7049. \small
  7050. \[
  7051. \begin{array}{lcl}
  7052. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7053. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7054. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7055. \Instr &::=& \ldots
  7056. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7057. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7058. \Block &::= & \Instr\ldots \\
  7059. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7060. x86_3 &::= & \Def\ldots
  7061. \end{array}
  7062. \]
  7063. \end{minipage}
  7064. }
  7065. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2-concrete}).}
  7066. \label{fig:x86-3-concrete}
  7067. \end{figure}
  7068. \begin{figure}[tp]
  7069. \fbox{
  7070. \begin{minipage}{0.96\textwidth}
  7071. \small
  7072. \[
  7073. \begin{array}{lcl}
  7074. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7075. \mid \BYTEREG{\Reg} } \\
  7076. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7077. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7078. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7079. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7080. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7081. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7082. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7083. \end{array}
  7084. \]
  7085. \end{minipage}
  7086. }
  7087. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  7088. \label{fig:x86-3}
  7089. \end{figure}
  7090. An assignment of a function reference to a variable becomes a
  7091. load-effective-address instruction as follows: \\
  7092. \begin{tabular}{lcl}
  7093. \begin{minipage}{0.35\textwidth}
  7094. \begin{lstlisting}
  7095. |$\itm{lhs}$| = (fun-ref |$f$|);
  7096. \end{lstlisting}
  7097. \end{minipage}
  7098. &
  7099. $\Rightarrow$\qquad\qquad
  7100. &
  7101. \begin{minipage}{0.3\textwidth}
  7102. \begin{lstlisting}
  7103. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7104. \end{lstlisting}
  7105. \end{minipage}
  7106. \end{tabular} \\
  7107. Regarding function definitions, we need to remove the parameters and
  7108. instead perform parameter passing using the conventions discussed in
  7109. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7110. registers. We recommend turning the parameters into local variables
  7111. and generating instructions at the beginning of the function to move
  7112. from the argument passing registers to these local variables.
  7113. \begin{lstlisting}
  7114. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7115. |$\Rightarrow$|
  7116. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7117. \end{lstlisting}
  7118. The $G'$ control-flow graph is the same as $G$ except that the
  7119. \code{start} block is modified to add the instructions for moving from
  7120. the argument registers to the parameter variables. So the \code{start}
  7121. block of $G$ shown on the left is changed to the code on the right.
  7122. \begin{center}
  7123. \begin{minipage}{0.3\textwidth}
  7124. \begin{lstlisting}
  7125. start:
  7126. |$\itm{instr}_1$|
  7127. |$\vdots$|
  7128. |$\itm{instr}_n$|
  7129. \end{lstlisting}
  7130. \end{minipage}
  7131. $\Rightarrow$
  7132. \begin{minipage}{0.3\textwidth}
  7133. \begin{lstlisting}
  7134. start:
  7135. movq %rdi, |$x_1$|
  7136. movq %rsi, |$x_2$|
  7137. |$\vdots$|
  7138. |$\itm{instr}_1$|
  7139. |$\vdots$|
  7140. |$\itm{instr}_n$|
  7141. \end{lstlisting}
  7142. \end{minipage}
  7143. \end{center}
  7144. By changing the parameters to local variables, we are giving the
  7145. register allocator control over which registers or stack locations to
  7146. use for them. If you implemented the move-biasing challenge
  7147. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7148. assign the parameter variables to the corresponding argument register,
  7149. in which case the \code{patch-instructions} pass will remove the
  7150. \code{movq} instruction. This happens in the example translation in
  7151. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7152. the \code{add} function.
  7153. %
  7154. Also, note that the register allocator will perform liveness analysis
  7155. on this sequence of move instructions and build the interference
  7156. graph. So, for example, $x_1$ will be marked as interfering with
  7157. \code{rsi} and that will prevent the assignment of $x_1$ to
  7158. \code{rsi}, which is good, because that would overwrite the argument
  7159. that needs to move into $x_2$.
  7160. Next, consider the compilation of function calls. In the mirror image
  7161. of handling the parameters of function definitions, the arguments need
  7162. to be moved to the argument passing registers. The function call
  7163. itself is performed with an indirect function call. The return value
  7164. from the function is stored in \code{rax}, so it needs to be moved
  7165. into the \itm{lhs}.
  7166. \begin{lstlisting}
  7167. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7168. |$\Rightarrow$|
  7169. movq |$\itm{arg}_1$|, %rdi
  7170. movq |$\itm{arg}_2$|, %rsi
  7171. |$\vdots$|
  7172. callq *|\itm{fun}|
  7173. movq %rax, |\itm{lhs}|
  7174. \end{lstlisting}
  7175. The \code{IndirectCallq} AST node includes an integer for the arity of
  7176. the function, i.e., the number of parameters. That information is
  7177. useful in the \code{uncover-live} pass for determining which
  7178. argument-passing registers are potentially read during the call.
  7179. For tail calls, the parameter passing is the same as non-tail calls:
  7180. generate instructions to move the arguments into to the argument
  7181. passing registers. After that we need to pop the frame from the
  7182. procedure call stack. However, we do not yet know how big the frame
  7183. is; that gets determined during register allocation. So instead of
  7184. generating those instructions here, we invent a new instruction that
  7185. means ``pop the frame and then do an indirect jump'', which we name
  7186. \code{TailJmp}. The abstract syntax for this instruction includes an
  7187. argument that specifies where to jump and an integer that represents
  7188. the arity of the function being called.
  7189. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7190. using the label \code{start} for the initial block of a program, and
  7191. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7192. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7193. can be compiled to an assignment to \code{rax} followed by a jump to
  7194. \code{conclusion}. With the addition of function definitions, we will
  7195. have a starting block and conclusion for each function, but their
  7196. labels need to be unique. We recommend prepending the function's name
  7197. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7198. labels. (Alternatively, one could \code{gensym} labels for the start
  7199. and conclusion and store them in the $\itm{info}$ field of the
  7200. function definition.)
  7201. \section{Register Allocation}
  7202. \label{sec:register-allocation-r4}
  7203. \subsection{Liveness Analysis}
  7204. \label{sec:liveness-analysis-r4}
  7205. \index{liveness analysis}
  7206. %% The rest of the passes need only minor modifications to handle the new
  7207. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7208. %% \code{leaq}.
  7209. The \code{IndirectCallq} instruction should be treated like
  7210. \code{Callq} regarding its written locations $W$, in that they should
  7211. include all the caller-saved registers. Recall that the reason for
  7212. that is to force call-live variables to be assigned to callee-saved
  7213. registers or to be spilled to the stack.
  7214. Regarding the set of read locations $R$ the arity field of
  7215. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7216. argument-passing registers should be considered as read by those
  7217. instructions.
  7218. \subsection{Build Interference Graph}
  7219. \label{sec:build-interference-r4}
  7220. With the addition of function definitions, we compute an interference
  7221. graph for each function (not just one for the whole program).
  7222. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7223. spill vector-typed variables that are live during a call to the
  7224. \code{collect}. With the addition of functions to our language, we
  7225. need to revisit this issue. Many functions perform allocation and
  7226. therefore have calls to the collector inside of them. Thus, we should
  7227. not only spill a vector-typed variable when it is live during a call
  7228. to \code{collect}, but we should spill the variable if it is live
  7229. during any function call. Thus, in the \code{build-interference} pass,
  7230. we recommend adding interference edges between call-live vector-typed
  7231. variables and the callee-saved registers (in addition to the usual
  7232. addition of edges between call-live variables and the caller-saved
  7233. registers).
  7234. \subsection{Allocate Registers}
  7235. The primary change to the \code{allocate-registers} pass is adding an
  7236. auxiliary function for handling definitions (the \Def{} non-terminal
  7237. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7238. logic is the same as described in
  7239. Chapter~\ref{ch:register-allocation-r1}, except now register
  7240. allocation is performed many times, once for each function definition,
  7241. instead of just once for the whole program.
  7242. \section{Patch Instructions}
  7243. In \code{patch-instructions}, you should deal with the x86
  7244. idiosyncrasy that the destination argument of \code{leaq} must be a
  7245. register. Additionally, you should ensure that the argument of
  7246. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7247. code generation more convenient, because we trample many registers
  7248. before the tail call (as explained in the next section).
  7249. \section{Print x86}
  7250. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7251. \code{IndirectCallq} are straightforward: output their concrete
  7252. syntax.
  7253. \begin{lstlisting}
  7254. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7255. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7256. \end{lstlisting}
  7257. The \code{TailJmp} node requires a bit work. A straightforward
  7258. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7259. before the jump we need to pop the current frame. This sequence of
  7260. instructions is the same as the code for the conclusion of a function,
  7261. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7262. Regarding function definitions, you will need to generate a prelude
  7263. and conclusion for each one. This code is similar to the prelude and
  7264. conclusion that you generated for the \code{main} function in
  7265. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7266. should carry out the following steps.
  7267. \begin{enumerate}
  7268. \item Start with \code{.global} and \code{.align} directives followed
  7269. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7270. example.)
  7271. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7272. pointer.
  7273. \item Push to the stack all of the callee-saved registers that were
  7274. used for register allocation.
  7275. \item Move the stack pointer \code{rsp} down by the size of the stack
  7276. frame for this function, which depends on the number of regular
  7277. spills. (Aligned to 16 bytes.)
  7278. \item Move the root stack pointer \code{r15} up by the size of the
  7279. root-stack frame for this function, which depends on the number of
  7280. spilled vectors. \label{root-stack-init}
  7281. \item Initialize to zero all of the entries in the root-stack frame.
  7282. \item Jump to the start block.
  7283. \end{enumerate}
  7284. The prelude of the \code{main} function has one additional task: call
  7285. the \code{initialize} function to set up the garbage collector and
  7286. move the value of the global \code{rootstack\_begin} in
  7287. \code{r15}. This should happen before step \ref{root-stack-init}
  7288. above, which depends on \code{r15}.
  7289. The conclusion of every function should do the following.
  7290. \begin{enumerate}
  7291. \item Move the stack pointer back up by the size of the stack frame
  7292. for this function.
  7293. \item Restore the callee-saved registers by popping them from the
  7294. stack.
  7295. \item Move the root stack pointer back down by the size of the
  7296. root-stack frame for this function.
  7297. \item Restore \code{rbp} by popping it from the stack.
  7298. \item Return to the caller with the \code{retq} instruction.
  7299. \end{enumerate}
  7300. \begin{exercise}\normalfont
  7301. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7302. Create 5 new programs that use functions, including examples that pass
  7303. functions and return functions from other functions, recursive
  7304. functions, functions that create vectors, and functions that make tail
  7305. calls. Test your compiler on these new programs and all of your
  7306. previously created test programs.
  7307. \end{exercise}
  7308. \begin{figure}[tbp]
  7309. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7310. \node (R4) at (0,2) {\large $R_4$};
  7311. \node (R4-2) at (3,2) {\large $R_4$};
  7312. %\node (R4-3) at (6,2) {\large $R_4$};
  7313. \node (F1-1) at (12,0) {\large $F_1$};
  7314. \node (F1-2) at (9,0) {\large $F_1$};
  7315. \node (F1-3) at (6,0) {\large $F_1$};
  7316. \node (F1-4) at (3,0) {\large $F_1$};
  7317. \node (C3-2) at (3,-2) {\large $C_3$};
  7318. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7319. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7320. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7321. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7322. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7323. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7324. %\path[->,bend left=15] (R4) edge [above] node
  7325. % {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7326. \path[->,bend left=15] (R4) edge [above] node
  7327. {\ttfamily\footnotesize uniquify} (R4-2);
  7328. \path[->,bend left=15] (R4-2) edge [right] node
  7329. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7330. \path[->,bend left=15] (F1-1) edge [below] node
  7331. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7332. \path[->,bend right=15] (F1-2) edge [above] node
  7333. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7334. \path[->,bend right=15] (F1-3) edge [above] node
  7335. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7336. \path[->,bend left=15] (F1-4) edge [right] node
  7337. {\ttfamily\footnotesize\color{red} explicate-control} (C3-2);
  7338. \path[->,bend right=15] (C3-2) edge [left] node
  7339. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7340. \path[->,bend left=15] (x86-2) edge [left] node
  7341. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7342. \path[->,bend right=15] (x86-2-1) edge [below] node
  7343. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7344. \path[->,bend right=15] (x86-2-2) edge [left] node
  7345. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7346. \path[->,bend left=15] (x86-3) edge [above] node
  7347. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7348. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7349. \end{tikzpicture}
  7350. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7351. \label{fig:R4-passes}
  7352. \end{figure}
  7353. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7354. compiling $R_4$ to x86.
  7355. \section{An Example Translation}
  7356. \label{sec:functions-example}
  7357. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7358. function in $R_4$ to x86. The figure also includes the results of the
  7359. \code{explicate-control} and \code{select-instructions} passes.
  7360. \begin{figure}[htbp]
  7361. \begin{tabular}{ll}
  7362. \begin{minipage}{0.5\textwidth}
  7363. % s3_2.rkt
  7364. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7365. (define (add [x : Integer] [y : Integer])
  7366. : Integer
  7367. (+ x y))
  7368. (add 40 2)
  7369. \end{lstlisting}
  7370. $\Downarrow$
  7371. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7372. (define (add86 [x87 : Integer]
  7373. [y88 : Integer]) : Integer
  7374. add86start:
  7375. return (+ x87 y88);
  7376. )
  7377. (define (main) : Integer ()
  7378. mainstart:
  7379. tmp89 = (fun-ref add86);
  7380. (tail-call tmp89 40 2)
  7381. )
  7382. \end{lstlisting}
  7383. \end{minipage}
  7384. &
  7385. $\Rightarrow$
  7386. \begin{minipage}{0.5\textwidth}
  7387. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7388. (define (add86) : Integer
  7389. add86start:
  7390. movq %rdi, x87
  7391. movq %rsi, y88
  7392. movq x87, %rax
  7393. addq y88, %rax
  7394. jmp add11389conclusion
  7395. )
  7396. (define (main) : Integer
  7397. mainstart:
  7398. leaq (fun-ref add86), tmp89
  7399. movq $40, %rdi
  7400. movq $2, %rsi
  7401. tail-jmp tmp89
  7402. )
  7403. \end{lstlisting}
  7404. $\Downarrow$
  7405. \end{minipage}
  7406. \end{tabular}
  7407. \begin{tabular}{ll}
  7408. \begin{minipage}{0.3\textwidth}
  7409. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7410. .globl add86
  7411. .align 16
  7412. add86:
  7413. pushq %rbp
  7414. movq %rsp, %rbp
  7415. jmp add86start
  7416. add86start:
  7417. movq %rdi, %rax
  7418. addq %rsi, %rax
  7419. jmp add86conclusion
  7420. add86conclusion:
  7421. popq %rbp
  7422. retq
  7423. \end{lstlisting}
  7424. \end{minipage}
  7425. &
  7426. \begin{minipage}{0.5\textwidth}
  7427. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7428. .globl main
  7429. .align 16
  7430. main:
  7431. pushq %rbp
  7432. movq %rsp, %rbp
  7433. movq $16384, %rdi
  7434. movq $16384, %rsi
  7435. callq initialize
  7436. movq rootstack_begin(%rip), %r15
  7437. jmp mainstart
  7438. mainstart:
  7439. leaq add86(%rip), %rcx
  7440. movq $40, %rdi
  7441. movq $2, %rsi
  7442. movq %rcx, %rax
  7443. popq %rbp
  7444. jmp *%rax
  7445. mainconclusion:
  7446. popq %rbp
  7447. retq
  7448. \end{lstlisting}
  7449. \end{minipage}
  7450. \end{tabular}
  7451. \caption{Example compilation of a simple function to x86.}
  7452. \label{fig:add-fun}
  7453. \end{figure}
  7454. % Challenge idea: inlining! (simple version)
  7455. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7456. \chapter{Lexically Scoped Functions}
  7457. \label{ch:lambdas}
  7458. \index{lambda}
  7459. \index{lexical scoping}
  7460. This chapter studies lexically scoped functions as they appear in
  7461. functional languages such as Racket. By lexical scoping we mean that a
  7462. function's body may refer to variables whose binding site is outside
  7463. of the function, in an enclosing scope.
  7464. %
  7465. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7466. $R_5$, which extends $R_4$ with anonymous functions using the
  7467. \key{lambda} form. The body of the \key{lambda}, refers to three
  7468. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7469. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7470. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7471. parameter of function \code{f}. The \key{lambda} is returned from the
  7472. function \code{f}. The main expression of the program includes two
  7473. calls to \code{f} with different arguments for \code{x}, first
  7474. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7475. to variables \code{g} and \code{h}. Even though these two functions
  7476. were created by the same \code{lambda}, they are really different
  7477. functions because they use different values for \code{x}. Applying
  7478. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7479. \code{15} produces \code{22}. The result of this program is \code{42}.
  7480. \begin{figure}[btp]
  7481. % s4_6.rkt
  7482. \begin{lstlisting}
  7483. (define (f [x : Integer]) : (Integer -> Integer)
  7484. (let ([y 4])
  7485. (lambda: ([z : Integer]) : Integer
  7486. (+ x (+ y z)))))
  7487. (let ([g (f 5)])
  7488. (let ([h (f 3)])
  7489. (+ (g 11) (h 15))))
  7490. \end{lstlisting}
  7491. \caption{Example of a lexically scoped function.}
  7492. \label{fig:lexical-scoping}
  7493. \end{figure}
  7494. The approach that we take for implementing lexically scoped
  7495. functions is to compile them into top-level function definitions,
  7496. translating from $R_5$ into $R_4$. However, the compiler will need to
  7497. provide special treatment for variable occurrences such as \code{x}
  7498. and \code{y} in the body of the \code{lambda} of
  7499. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7500. refer to variables defined outside of it. To identify such variable
  7501. occurrences, we review the standard notion of free variable.
  7502. \begin{definition}
  7503. A variable is \emph{free in expression} $e$ if the variable occurs
  7504. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7505. variable}
  7506. \end{definition}
  7507. For example, in the expression \code{(+ x (+ y z))} the variables
  7508. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7509. only \code{x} and \code{y} are free in the following expression
  7510. because \code{z} is bound by the \code{lambda}.
  7511. \begin{lstlisting}
  7512. (lambda: ([z : Integer]) : Integer
  7513. (+ x (+ y z)))
  7514. \end{lstlisting}
  7515. So the free variables of a \code{lambda} are the ones that will need
  7516. special treatment. We need to arrange for some way to transport, at
  7517. runtime, the values of those variables from the point where the
  7518. \code{lambda} was created to the point where the \code{lambda} is
  7519. applied. An efficient solution to the problem, due to
  7520. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7521. free variables together with the function pointer for the lambda's
  7522. code, an arrangement called a \emph{flat closure} (which we shorten to
  7523. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7524. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7525. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7526. pointers. The function pointer resides at index $0$ and the
  7527. values for the free variables will fill in the rest of the vector.
  7528. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7529. how closures work. It's a three-step dance. The program first calls
  7530. function \code{f}, which creates a closure for the \code{lambda}. The
  7531. closure is a vector whose first element is a pointer to the top-level
  7532. function that we will generate for the \code{lambda}, the second
  7533. element is the value of \code{x}, which is \code{5}, and the third
  7534. element is \code{4}, the value of \code{y}. The closure does not
  7535. contain an element for \code{z} because \code{z} is not a free
  7536. variable of the \code{lambda}. Creating the closure is step 1 of the
  7537. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7538. shown in Figure~\ref{fig:closures}.
  7539. %
  7540. The second call to \code{f} creates another closure, this time with
  7541. \code{3} in the second slot (for \code{x}). This closure is also
  7542. returned from \code{f} but bound to \code{h}, which is also shown in
  7543. Figure~\ref{fig:closures}.
  7544. \begin{figure}[tbp]
  7545. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7546. \caption{Example closure representation for the \key{lambda}'s
  7547. in Figure~\ref{fig:lexical-scoping}.}
  7548. \label{fig:closures}
  7549. \end{figure}
  7550. Continuing with the example, consider the application of \code{g} to
  7551. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7552. obtain the function pointer in the first element of the closure and
  7553. call it, passing in the closure itself and then the regular arguments,
  7554. in this case \code{11}. This technique for applying a closure is step
  7555. 2 of the dance.
  7556. %
  7557. But doesn't this \code{lambda} only take 1 argument, for parameter
  7558. \code{z}? The third and final step of the dance is generating a
  7559. top-level function for a \code{lambda}. We add an additional
  7560. parameter for the closure and we insert a \code{let} at the beginning
  7561. of the function for each free variable, to bind those variables to the
  7562. appropriate elements from the closure parameter.
  7563. %
  7564. This three-step dance is known as \emph{closure conversion}. We
  7565. discuss the details of closure conversion in
  7566. Section~\ref{sec:closure-conversion} and the code generated from the
  7567. example in Section~\ref{sec:example-lambda}. But first we define the
  7568. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7569. \section{The $R_5$ Language}
  7570. \label{sec:r5}
  7571. The concrete and abstract syntax for $R_5$, a language with anonymous
  7572. functions and lexical scoping, is defined in
  7573. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7574. the \key{lambda} form to the grammar for $R_4$, which already has
  7575. syntax for function application.
  7576. \begin{figure}[tp]
  7577. \centering
  7578. \fbox{
  7579. \begin{minipage}{0.96\textwidth}
  7580. \small
  7581. \[
  7582. \begin{array}{lcl}
  7583. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7584. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7585. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7586. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7587. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7588. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7589. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7590. \mid (\key{and}\;\Exp\;\Exp)
  7591. \mid (\key{or}\;\Exp\;\Exp)
  7592. \mid (\key{not}\;\Exp) } \\
  7593. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7594. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7595. (\key{vector-ref}\;\Exp\;\Int)} \\
  7596. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7597. \mid (\Exp \; \Exp\ldots) } \\
  7598. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7599. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7600. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7601. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7602. \end{array}
  7603. \]
  7604. \end{minipage}
  7605. }
  7606. \caption{The concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-concrete-syntax})
  7607. with \key{lambda}.}
  7608. \label{fig:r5-concrete-syntax}
  7609. \end{figure}
  7610. \begin{figure}[tp]
  7611. \centering
  7612. \fbox{
  7613. \begin{minipage}{0.96\textwidth}
  7614. \small
  7615. \[
  7616. \begin{array}{lcl}
  7617. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7618. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7619. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7620. &\mid& \gray{ \BOOL{\itm{bool}}
  7621. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7622. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7623. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7624. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7625. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7626. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7627. \end{array}
  7628. \]
  7629. \end{minipage}
  7630. }
  7631. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7632. \label{fig:r5-syntax}
  7633. \end{figure}
  7634. \index{interpreter}
  7635. \label{sec:interp-R5}
  7636. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7637. $R_5$. The clause for \key{lambda} saves the current environment
  7638. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7639. the environment from the \key{lambda}, the \code{lam-env}, when
  7640. interpreting the body of the \key{lambda}. The \code{lam-env}
  7641. environment is extended with the mapping of parameters to argument
  7642. values.
  7643. \begin{figure}[tbp]
  7644. \begin{lstlisting}
  7645. UPDATE ME
  7646. \end{lstlisting}
  7647. \caption{Interpreter for $R_5$.}
  7648. \label{fig:interp-R5}
  7649. \end{figure}
  7650. \label{sec:type-check-r5}
  7651. \index{type checking}
  7652. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7653. \key{lambda} form. The body of the \key{lambda} is checked in an
  7654. environment that includes the current environment (because it is
  7655. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7656. require the body's type to match the declared return type.
  7657. \begin{figure}[tbp]
  7658. \begin{lstlisting}
  7659. (define (type-check-R5 env)
  7660. (lambda (e)
  7661. (match e
  7662. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7663. (define-values (new-body bodyT)
  7664. ((type-check-exp (append (map cons xs Ts) env)) body))
  7665. (define ty `(,@Ts -> ,rT))
  7666. (cond
  7667. [(equal? rT bodyT)
  7668. (values (HasType (Lambda params rT new-body) ty) ty)]
  7669. [else
  7670. (error "mismatch in return type" bodyT rT)])]
  7671. ...
  7672. )))
  7673. \end{lstlisting}
  7674. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7675. \label{fig:type-check-R5}
  7676. \end{figure}
  7677. \section{Reveal Functions and the $F_2$ language}
  7678. \label{sec:reveal-functions-r5}
  7679. To support the \code{procedure-arity} operator we need to communicate
  7680. the arity of a function to the point of closure creation. We can
  7681. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7682. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7683. output of this pass is the language $F_2$, whose syntax is defined in
  7684. Figure~\ref{fig:f2-syntax}.
  7685. \begin{figure}[tp]
  7686. \centering
  7687. \fbox{
  7688. \begin{minipage}{0.96\textwidth}
  7689. \[
  7690. \begin{array}{lcl}
  7691. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7692. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7693. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7694. \end{array}
  7695. \]
  7696. \end{minipage}
  7697. }
  7698. \caption{The abstract syntax $F_2$, an extension of $R_5$
  7699. (Figure~\ref{fig:r5-syntax}).}
  7700. \label{fig:f2-syntax}
  7701. \end{figure}
  7702. \section{Closure Conversion}
  7703. \label{sec:closure-conversion}
  7704. \index{closure conversion}
  7705. The compiling of lexically-scoped functions into top-level function
  7706. definitions is accomplished in the pass \code{convert-to-closures}
  7707. that comes after \code{reveal-functions} and before
  7708. \code{limit-functions}.
  7709. As usual, we implement the pass as a recursive function over the
  7710. AST. All of the action is in the clauses for \key{Lambda} and
  7711. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7712. that creates a closure, that is, a vector whose first element is a
  7713. function pointer and the rest of the elements are the free variables
  7714. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7715. using \code{vector} so that we can distinguish closures from vectors
  7716. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7717. the generated code below, the \itm{name} is a unique symbol generated
  7718. to identify the function and the \itm{arity} is the number of
  7719. parameters (the length of \itm{ps}).
  7720. \begin{lstlisting}
  7721. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7722. |$\Rightarrow$|
  7723. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7724. \end{lstlisting}
  7725. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7726. create a top-level function definition for each \key{Lambda}, as
  7727. shown below.\\
  7728. \begin{minipage}{0.8\textwidth}
  7729. \begin{lstlisting}
  7730. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7731. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7732. ...
  7733. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7734. |\itm{body'}|)...))
  7735. \end{lstlisting}
  7736. \end{minipage}\\
  7737. The \code{clos} parameter refers to the closure. Translate the type
  7738. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7739. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7740. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7741. underscore \code{\_} is a dummy type that we use because it is rather
  7742. difficult to give a type to the function in the closure's
  7743. type.\footnote{To give an accurate type to a closure, we would need to
  7744. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7745. The dummy type is considered to be equal to any other type during type
  7746. checking. The sequence of \key{Let} forms bind the free variables to
  7747. their values obtained from the closure.
  7748. Closure conversion turns functions into vectors, so the type
  7749. annotations in the program must also be translated. We recommend
  7750. defining a auxiliary recursive function for this purpose. Function
  7751. types should be translated as follows.
  7752. \begin{lstlisting}
  7753. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7754. |$\Rightarrow$|
  7755. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7756. \end{lstlisting}
  7757. The above type says that the first thing in the vector is a function
  7758. pointer. The first parameter of the function pointer is a vector (a
  7759. closure) and the rest of the parameters are the ones from the original
  7760. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7761. the closure omits the types of the free variables because 1) those
  7762. types are not available in this context and 2) we do not need them in
  7763. the code that is generated for function application.
  7764. We transform function application into code that retrieves the
  7765. function pointer from the closure and then calls the function, passing
  7766. in the closure as the first argument. We bind $e'$ to a temporary
  7767. variable to avoid code duplication.
  7768. \begin{lstlisting}
  7769. (Apply |$e$| |\itm{es}|)
  7770. |$\Rightarrow$|
  7771. (Let |\itm{tmp}| |$e'$|
  7772. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7773. \end{lstlisting}
  7774. There is also the question of what to do with references top-level
  7775. function definitions. To maintain a uniform translation of function
  7776. application, we turn function references into closures.
  7777. \begin{tabular}{lll}
  7778. \begin{minipage}{0.3\textwidth}
  7779. \begin{lstlisting}
  7780. (FunRefArity |$f$| |$n$|)
  7781. \end{lstlisting}
  7782. \end{minipage}
  7783. &
  7784. $\Rightarrow$
  7785. &
  7786. \begin{minipage}{0.5\textwidth}
  7787. \begin{lstlisting}
  7788. (Closure |$n$| (FunRef |$f$|) '())
  7789. \end{lstlisting}
  7790. \end{minipage}
  7791. \end{tabular} \\
  7792. %
  7793. The top-level function definitions need to be updated as well to take
  7794. an extra closure parameter.
  7795. \section{An Example Translation}
  7796. \label{sec:example-lambda}
  7797. Figure~\ref{fig:lexical-functions-example} shows the result of
  7798. \code{reveal-functions} and \code{convert-to-closures} for the example
  7799. program demonstrating lexical scoping that we discussed at the
  7800. beginning of this chapter.
  7801. \begin{figure}[tbp]
  7802. \begin{minipage}{0.8\textwidth}
  7803. % tests/lambda_test_6.rkt
  7804. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7805. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  7806. (let ([y8 4])
  7807. (lambda: ([z9 : Integer]) : Integer
  7808. (+ x7 (+ y8 z9)))))
  7809. (define (main) : Integer
  7810. (let ([g0 ((fun-ref-arity f6 1) 5)])
  7811. (let ([h1 ((fun-ref-arity f6 1) 3)])
  7812. (+ (g0 11) (h1 15)))))
  7813. \end{lstlisting}
  7814. $\Rightarrow$
  7815. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7816. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7817. (let ([y8 4])
  7818. (closure 1 (list (fun-ref lambda2) x7 y8))))
  7819. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  7820. (let ([x7 (vector-ref fvs3 1)])
  7821. (let ([y8 (vector-ref fvs3 2)])
  7822. (+ x7 (+ y8 z9)))))
  7823. (define (main) : Integer
  7824. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  7825. ((vector-ref clos5 0) clos5 5))])
  7826. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  7827. ((vector-ref clos6 0) clos6 3))])
  7828. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  7829. \end{lstlisting}
  7830. \end{minipage}
  7831. \caption{Example of closure conversion.}
  7832. \label{fig:lexical-functions-example}
  7833. \end{figure}
  7834. \begin{exercise}\normalfont
  7835. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7836. Create 5 new programs that use \key{lambda} functions and make use of
  7837. lexical scoping. Test your compiler on these new programs and all of
  7838. your previously created test programs.
  7839. \end{exercise}
  7840. \section{Expose Allocation}
  7841. \label{sec:expose-allocation-r5}
  7842. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  7843. that allocates and initializes a vector, similar to the translation of
  7844. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  7845. The only difference is replacing the use of
  7846. \ALLOC{\itm{len}}{\itm{type}} with
  7847. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  7848. \section{Explicate Control and $C_4$}
  7849. \label{sec:explicate-r5}
  7850. The output language of \code{explicate-control} is $C_4$ whose
  7851. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  7852. difference with respect to $C_3$ is the addition of the
  7853. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  7854. of \code{AllocateClosure} in the \code{explicate-control} pass is
  7855. similar to the handling of other expressions such as primitive
  7856. operators.
  7857. \begin{figure}[tp]
  7858. \fbox{
  7859. \begin{minipage}{0.96\textwidth}
  7860. \small
  7861. \[
  7862. \begin{array}{lcl}
  7863. \Exp &::= & \ldots
  7864. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  7865. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7866. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7867. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7868. \mid \GOTO{\itm{label}} } \\
  7869. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7870. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  7871. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  7872. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  7873. \end{array}
  7874. \]
  7875. \end{minipage}
  7876. }
  7877. \caption{The abstract syntax of $C_4$, extending $C_3$ (Figure~\ref{fig:c3-syntax}).}
  7878. \label{fig:c4-syntax}
  7879. \end{figure}
  7880. \section{Select Instructions}
  7881. \label{sec:select-instructions-R5}
  7882. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  7883. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  7884. (Section~\ref{sec:select-instructions-gc}). The only difference is
  7885. that you should place the \itm{arity} in the tag that is stored at
  7886. position $0$ of the vector. Recall that in
  7887. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  7888. of the 64-bit tag, but that the rest were unused. So the arity goes
  7889. into the tag in bit positions $57$ through $63$.
  7890. Compile the \code{procedure-arity} operator into a sequence of
  7891. instructions that access the tag from position $0$ of the vector and
  7892. shift it by $57$ bits to the right.
  7893. \begin{figure}[p]
  7894. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7895. \node (R4) at (0,2) {\large $R_4$};
  7896. \node (R4-2) at (3,2) {\large $R_4$};
  7897. \node (R4-3) at (6,2) {\large $R_4$};
  7898. \node (F1-1) at (12,0) {\large $F_1$};
  7899. \node (F1-2) at (9,0) {\large $F_1$};
  7900. \node (F1-3) at (6,0) {\large $F_1$};
  7901. \node (F1-4) at (3,0) {\large $F_1$};
  7902. \node (F1-5) at (0,0) {\large $F_1$};
  7903. \node (C3-2) at (3,-2) {\large $C_3$};
  7904. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7905. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7906. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7907. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7908. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7909. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7910. \path[->,bend left=15] (R4) edge [above] node
  7911. {\ttfamily\footnotesize shrink} (R4-2);
  7912. \path[->,bend left=15] (R4-2) edge [above] node
  7913. {\ttfamily\footnotesize uniquify} (R4-3);
  7914. \path[->,bend left=15] (R4-3) edge [right] node
  7915. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7916. \path[->,bend left=15] (F1-1) edge [below] node
  7917. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7918. \path[->,bend right=15] (F1-2) edge [above] node
  7919. {\ttfamily\footnotesize limit-fun.} (F1-3);
  7920. \path[->,bend right=15] (F1-3) edge [above] node
  7921. {\ttfamily\footnotesize\color{red} expose-alloc.} (F1-4);
  7922. \path[->,bend right=15] (F1-4) edge [above] node
  7923. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7924. \path[->,bend right=15] (F1-5) edge [right] node
  7925. {\ttfamily\footnotesize explicate-control} (C3-2);
  7926. \path[->,bend left=15] (C3-2) edge [left] node
  7927. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7928. \path[->,bend right=15] (x86-2) edge [left] node
  7929. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7930. \path[->,bend right=15] (x86-2-1) edge [below] node
  7931. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7932. \path[->,bend right=15] (x86-2-2) edge [left] node
  7933. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7934. \path[->,bend left=15] (x86-3) edge [above] node
  7935. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7936. \path[->,bend left=15] (x86-4) edge [right] node
  7937. {\ttfamily\footnotesize print-x86} (x86-5);
  7938. \end{tikzpicture}
  7939. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7940. functions.}
  7941. \label{fig:R5-passes}
  7942. \end{figure}
  7943. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7944. for the compilation of $R_5$.
  7945. \clearpage
  7946. \section{Challenge: Optimize Closures}
  7947. \label{sec:optimize-closures}
  7948. In this chapter we compiled lexically-scoped functions into a
  7949. relatively efficient representation: flat closures. However, even this
  7950. representation comes with some overhead. For example, consider the
  7951. following program with a function \code{tail-sum} that does not have
  7952. any free variables and where all the uses of \code{tail-sum} are in
  7953. applications where we know that only \code{tail-sum} is being applied
  7954. (and not any other functions).
  7955. \begin{center}
  7956. \begin{minipage}{0.95\textwidth}
  7957. \begin{lstlisting}
  7958. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7959. (if (eq? n 0)
  7960. r
  7961. (tail-sum (- n 1) (+ n r))))
  7962. (+ (tail-sum 5 0) 27)
  7963. \end{lstlisting}
  7964. \end{minipage}
  7965. \end{center}
  7966. As described in this chapter, we uniformly apply closure conversion to
  7967. all functions, obtaining the following output for this program.
  7968. \begin{center}
  7969. \begin{minipage}{0.95\textwidth}
  7970. \begin{lstlisting}
  7971. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  7972. (if (eq? n2 0)
  7973. r3
  7974. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  7975. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  7976. (define (main) : Integer
  7977. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  7978. ((vector-ref clos6 0) clos6 5 0)) 27))
  7979. \end{lstlisting}
  7980. \end{minipage}
  7981. \end{center}
  7982. In the previous Chapter, there would be no allocation in the program
  7983. and the calls to \code{tail-sum} would be direct calls. In contrast,
  7984. the above program allocates memory for each \code{closure} and the
  7985. calls to \code{tail-sum} are indirect. These two differences incur
  7986. considerable overhead in a program such as this one, where the
  7987. allocations and indirect calls occur inside a tight loop.
  7988. One might think that this problem is trivial to solve: can't we just
  7989. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  7990. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  7991. e'_n$)} instead of treating it like a call to a closure? We would
  7992. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  7993. %
  7994. However, this problem is not so trivial because a global function may
  7995. ``escape'' and become involved in applications that also involve
  7996. closures. Consider the following example in which the application
  7997. \code{(f 41)} needs to be compiled into a closure application, because
  7998. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  7999. function might also get bound to \code{f}.
  8000. \begin{lstlisting}
  8001. (define (add1 [x : Integer]) : Integer
  8002. (+ x 1))
  8003. (let ([y (read)])
  8004. (let ([f (if (eq? (read) 0)
  8005. add1
  8006. (lambda: ([x : Integer]) : Integer (- x y)))])
  8007. (f 41)))
  8008. \end{lstlisting}
  8009. If a global function name is used in any way other than as the
  8010. operator in a direct call, then we say that the function
  8011. \emph{escapes}. If a global function does not escape, then we do not
  8012. need to perform closure conversion on the function.
  8013. \begin{exercise}\normalfont
  8014. Implement an auxiliary function for detecting which global
  8015. functions escape. Using that function, implement an improved version
  8016. of closure conversion that does not apply closure conversion to
  8017. global functions that do not escape but instead compiles them as
  8018. regular functions. Create several new test cases that check whether
  8019. you properly detect whether global functions escape or not.
  8020. \end{exercise}
  8021. So far we have reduced the overhead of calling global functions, but
  8022. it would also be nice to reduce the overhead of calling a
  8023. \code{lambda} when we can determine at compile time which
  8024. \code{lambda} will be called. We refer to such calls as \emph{known
  8025. calls}. Consider the following example in which a \code{lambda} is
  8026. bound to \code{f} and then applied.
  8027. \begin{lstlisting}
  8028. (let ([y (read)])
  8029. (let ([f (lambda: ([x : Integer]) : Integer
  8030. (+ x y))])
  8031. (f 21)))
  8032. \end{lstlisting}
  8033. Closure conversion compiles \code{(f 21)} into an indirect call:
  8034. \begin{lstlisting}
  8035. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8036. (let ([y2 (vector-ref fvs6 1)])
  8037. (+ x3 y2)))
  8038. (define (main) : Integer
  8039. (let ([y2 (read)])
  8040. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8041. ((vector-ref f4 0) f4 21))))
  8042. \end{lstlisting}
  8043. but we can instead compile the application \code{(f 21)} into a direct call
  8044. to \code{lambda5}:
  8045. \begin{lstlisting}
  8046. (define (main) : Integer
  8047. (let ([y2 (read)])
  8048. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8049. ((fun-ref lambda5) f4 21))))
  8050. \end{lstlisting}
  8051. The problem of determining which lambda will be called from a
  8052. particular application is quite challenging in general and the topic
  8053. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8054. following exercise we recommend that you compile an application to a
  8055. direct call when the operator is a variable and the variable is
  8056. \code{let}-bound to a closure. This can be accomplished by maintaining
  8057. an environment mapping \code{let}-bound variables to function names.
  8058. Extend the environment whenever you encounter a closure on the
  8059. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8060. to the name of the global function for the closure. This pass should
  8061. come after closure conversion.
  8062. \begin{exercise}\normalfont
  8063. Implement a compiler pass, named \code{optimize-known-calls}, that
  8064. compiles known calls into direct calls. Verify that your compiler is
  8065. successful in this regard on several example programs.
  8066. \end{exercise}
  8067. These exercises only scratches the surface of optimizing of
  8068. closures. A good next step for the interested reader is to look at the
  8069. work of \citet{Keep:2012ab}.
  8070. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8071. \chapter{Loops and Assignment}
  8072. \label{ch:loop}
  8073. In this chapter we study two features that are the hallmarks of
  8074. imperative programming languages: loops and assignments to local
  8075. variables. The following example demonstrates these new features by
  8076. computing the sum of the first five positive integers.
  8077. % similar to loop_test_1.rkt
  8078. \begin{lstlisting}
  8079. (let ([sum 0])
  8080. (let ([i 5])
  8081. (begin
  8082. (while (> i 0)
  8083. (begin
  8084. (set! sum (+ sum i))
  8085. (set! i (- i 1))))
  8086. sum)))
  8087. \end{lstlisting}
  8088. The \code{while} loop consists of a condition and a body.
  8089. %
  8090. The \code{set!} consists of a variable and a right-hand-side expression.
  8091. %
  8092. The primary purpose of both the \code{while} loop and \code{set!} is
  8093. to cause side effects, so it is convenient to also include in $R_8$ a
  8094. language feature for sequencing side effects: the \code{begin}
  8095. expression. It consists of one or more subexpressions that are
  8096. evaluated left-to-right.
  8097. %
  8098. The concrete syntax of $R_8$ is defined in
  8099. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  8100. in Figure~\ref{fig:r8-syntax}.
  8101. \begin{figure}[tp]
  8102. \centering
  8103. \fbox{
  8104. \begin{minipage}{0.96\textwidth}
  8105. \small
  8106. \[
  8107. \begin{array}{lcl}
  8108. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8109. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8110. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8111. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8112. \mid (\key{and}\;\Exp\;\Exp)
  8113. \mid (\key{or}\;\Exp\;\Exp)
  8114. \mid (\key{not}\;\Exp) } \\
  8115. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8116. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8117. (\key{vector-ref}\;\Exp\;\Int)} \\
  8118. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8119. \mid (\Exp \; \Exp\ldots) } \\
  8120. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  8121. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  8122. &\mid& \CSETBANG{\Var}{\Exp}
  8123. \mid \CBEGIN{\Exp\ldots}{\Exp}
  8124. \mid \CWHILE{\Exp}{\Exp} \\
  8125. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8126. R_8 &::=& \gray{\Def\ldots \; \Exp}
  8127. \end{array}
  8128. \]
  8129. \end{minipage}
  8130. }
  8131. \caption{The concrete syntax of $R_8$, extending $R_5$ (Figure~\ref{fig:r5-concrete-syntax})
  8132. with \key{lambda}.}
  8133. \label{fig:r8-concrete-syntax}
  8134. \end{figure}
  8135. \begin{figure}[tp]
  8136. \centering
  8137. \fbox{
  8138. \begin{minipage}{0.96\textwidth}
  8139. \small
  8140. \[
  8141. \begin{array}{lcl}
  8142. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8143. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8144. &\mid& \gray{ \BOOL{\itm{bool}}
  8145. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8146. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8147. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8148. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  8149. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8150. \mid \WHILE{\Exp}{\Exp} \\
  8151. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8152. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8153. \end{array}
  8154. \]
  8155. \end{minipage}
  8156. }
  8157. \caption{The abstract syntax of $R_8$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  8158. \label{fig:r8-syntax}
  8159. \end{figure}
  8160. The definitional interpreter for $R_8$ is shown in
  8161. Figure~\ref{fig:interp-R8}. We add three new cases for \code{SetBang},
  8162. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  8163. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  8164. support assignment to variables and to make their lifetimes indefinite
  8165. (see the second example in Section~\ref{sec:assignment-scoping}), we
  8166. box the value that is bound to each variable (in \code{Let}) and
  8167. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  8168. the value.
  8169. %
  8170. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8171. variable in the environment to obtain a boxed value and then we change
  8172. it using \code{set-box!} to the result of evaluating the right-hand
  8173. side. The result value of a \code{SetBang} is \code{void}.
  8174. %
  8175. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8176. if the result is true, 2) evaluate the body.
  8177. The result value of a \code{while} loop is also \code{void}.
  8178. %
  8179. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8180. subexpressions \itm{es} for their effects and then evaluates
  8181. and returns the result from \itm{body}.
  8182. \begin{figure}[tbp]
  8183. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8184. (define (interp-exp env)
  8185. (lambda (e)
  8186. (define recur (interp-exp env))
  8187. (match e
  8188. [(Var x) (unbox (lookup x env))]
  8189. [(Let x e body)
  8190. (define new-env (cons (cons x (box (recur e))) env))
  8191. ((interp-exp new-env) body)]
  8192. [(Apply fun args)
  8193. (define fun-val (recur fun))
  8194. (define arg-vals (map recur args))
  8195. (match fun-val
  8196. [`(function (,xs ...) ,body ,lam-env)
  8197. (define new-env (append (for/list ([x xs] [arg arg-vals])
  8198. (cons x (box arg)))
  8199. lam-env))
  8200. ((interp-exp new-env) body)])]
  8201. [(SetBang x rhs)
  8202. (set-box! (lookup x env) (recur rhs))]
  8203. [(WhileLoop cnd body)
  8204. (define (loop)
  8205. (cond [(recur cnd) (recur body) (loop)]
  8206. [else (void)]))
  8207. (loop)]
  8208. [(Begin es body)
  8209. (for ([e es]) (recur e))
  8210. (recur body)]
  8211. ...
  8212. [else (error 'interp-exp "unrecognized expression ~a" e)]
  8213. )))
  8214. \end{lstlisting}
  8215. \caption{Interpreter for $R_8$.}
  8216. \label{fig:interp-R8}
  8217. \end{figure}
  8218. The type checker for $R_8$ is define in
  8219. Figure~\ref{fig:type-check-R8}. For \code{SetBang}, the type of the
  8220. variable and the right-hand-side must agree. The result type is
  8221. \code{Void}. For the \code{WhileLoop}, the condition must be a
  8222. \code{Boolean}. The result type is also \code{Void}. For
  8223. \code{Begin}, the result type is the type of its last subexpression.
  8224. \begin{figure}[tbp]
  8225. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8226. (define (type-check-R8 env)
  8227. (lambda (e)
  8228. (match e
  8229. [(SetBang x rhs)
  8230. (define-values (rhs^ rhsT) (recur rhs))
  8231. (define varT (dict-ref env x))
  8232. (unless (type-equal? rhsT varT)
  8233. (error 'type-check-exp
  8234. "variable and RHS of set! have different type, ~a != ~a"
  8235. varT rhsT))
  8236. (values (SetBang x rhs^) 'Void)]
  8237. [(WhileLoop cnd body)
  8238. (define-values (cnd^ Tc) (recur cnd))
  8239. (unless (type-equal? Tc 'Boolean)
  8240. (error 'type-check-exp
  8241. "expected Boolean in condition of if, not ~a" Tc))
  8242. (define-values (body^ Tbody) ((type-check-exp env) body))
  8243. (values (WhileLoop cnd^ body^) 'Void)]
  8244. [(Begin es body)
  8245. (define-values (es^ ts)
  8246. (for/lists (l1 l2) ([e es]) (recur e)))
  8247. (define-values (body^ Tbody) (recur body))
  8248. (values (Begin es^ body^) Tbody)]
  8249. ...
  8250. )))
  8251. \end{lstlisting}
  8252. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  8253. and \code{Begin} in $R_8$.}
  8254. \label{fig:type-check-R8}
  8255. \end{figure}
  8256. At first glance, the translation of these language features to x86
  8257. seems straightforward because the $C_3$ intermediate language already
  8258. supports all of the ingredients that we need: assignment, \code{goto},
  8259. conditional branching, and sequencing. However, there are two
  8260. complications that arise which we discuss in the next two
  8261. sections. After that we introduce one new compiler pass and the
  8262. changes necessary to the existing passes.
  8263. \section{Assignment and Lexically Scoped Functions}
  8264. \label{sec:assignment-scoping}
  8265. The addition of assignment raises a problem with our approach to
  8266. implementing lexically-scoped functions. Consider the following
  8267. example in which function \code{f} has a free variable \code{x} that
  8268. is changed after \code{f} is created but before the call to \code{f}.
  8269. % loop_test_11.rkt
  8270. \begin{lstlisting}
  8271. (let ([x 0])
  8272. (let ([y 0])
  8273. (let ([z 20])
  8274. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8275. (begin
  8276. (set! x 10)
  8277. (set! y 12)
  8278. (f y))))))
  8279. \end{lstlisting}
  8280. The correct output for this example is \code{42} because the call to
  8281. \code{f} is required to use the current value of \code{x} (which is
  8282. \code{10}). Unfortunately, the closure conversion pass
  8283. (Section~\ref{sec:closure-conversion}) generates code for the
  8284. \code{lambda} that copies the old value of \code{x} into a
  8285. closure. Thus, if we naively add support for assignment to our current
  8286. compiler, the output of this program would be \code{32}.
  8287. A first attempt at solving this problem would be to save a pointer to
  8288. \code{x} in the closure and change the occurrences of \code{x} inside
  8289. the lambda to dereference the pointer. Of course, this would require
  8290. assigning \code{x} to the stack and not to a register. However, the
  8291. problem goes a bit deeper. Consider the following example in which we
  8292. create a counter abstraction by creating a pair of functions that
  8293. share the free variable \code{x}.
  8294. % similar to loop_test_10.rkt
  8295. \begin{lstlisting}
  8296. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  8297. (vector
  8298. (lambda: () : Integer x)
  8299. (lambda: () : Void (set! x (+ 1 x)))))
  8300. (let ([counter (f 0)])
  8301. (let ([get (vector-ref counter 0)])
  8302. (let ([inc (vector-ref counter 1)])
  8303. (begin
  8304. (inc)
  8305. (get)))))
  8306. \end{lstlisting}
  8307. In this example, the lifetime of \code{x} extends beyond the lifetime
  8308. of the call to \code{f}. Thus, if we were to store \code{x} on the
  8309. stack frame for the call to \code{f}, it would be gone by the time we
  8310. call \code{inc} and \code{get}, leaving us with dangling pointers for
  8311. \code{x}. This example demonstrates that when a variable occurs free
  8312. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  8313. value of the variable needs to live on the heap. The verb ``box'' is
  8314. often used for allocating a single value on the heap, producing a
  8315. pointer, and ``unbox'' for dereferencing the pointer.
  8316. We recommend solving these problems by ``boxing'' the local variables
  8317. that are in the intersection of 1) variables that appear on the
  8318. left-hand-side of a \code{set!} and 2) variables that occur free
  8319. inside a \code{lambda}. We shall introduce a new pass named
  8320. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  8321. perform this translation. But before diving into the compiler passes,
  8322. we one more problem to discuss.
  8323. \section{Cyclic Control Flow and Dataflow Analysis}
  8324. \label{sec:dataflow-analysis}
  8325. Up until this point the control-flow graphs generated in
  8326. \code{explicate-control} were guaranteed to be acyclic. However, each
  8327. \code{while} loop introduces a cycle in the control-flow graph.
  8328. But does that matter?
  8329. %
  8330. Indeed it does. Recall that for register allocation, the compiler
  8331. performs liveness analysis to determine which variables can share the
  8332. same register. In Section~\ref{sec:liveness-analysis-r2} we analyze
  8333. the control-flow graph in reverse topological order, but topological
  8334. order is only well-defined for acyclic graphs.
  8335. Let us return to the example of computing the sum of the first five
  8336. positive integers. Here is the program after instruction selection but
  8337. before register allocation.
  8338. \begin{center}
  8339. \begin{minipage}{0.45\textwidth}
  8340. \begin{lstlisting}
  8341. (define (main) : Integer
  8342. mainstart:
  8343. movq $0, sum1
  8344. movq $5, i2
  8345. jmp block5
  8346. block5:
  8347. movq i2, tmp3
  8348. cmpq tmp3, $0
  8349. jl block7
  8350. jmp block8
  8351. \end{lstlisting}
  8352. \end{minipage}
  8353. \begin{minipage}{0.45\textwidth}
  8354. \begin{lstlisting}
  8355. block7:
  8356. addq i2, sum1
  8357. movq $1, tmp4
  8358. negq tmp4
  8359. addq tmp4, i2
  8360. jmp block5
  8361. block8:
  8362. movq $27, %rax
  8363. addq sum1, %rax
  8364. jmp mainconclusion
  8365. )
  8366. \end{lstlisting}
  8367. \end{minipage}
  8368. \end{center}
  8369. Recall that liveness analysis works backwards, starting at the end
  8370. of each function. For this example we could start with \code{block8}
  8371. because we know what is live at the beginning of the conclusion,
  8372. just \code{rax} and \code{rsp}. So the live-before set
  8373. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  8374. %
  8375. Next we might try to analyze \code{block5} or \code{block7}, but
  8376. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  8377. we are stuck.
  8378. The way out of this impasse comes from the realization that one can
  8379. perform liveness analysis starting with an empty live-after set to
  8380. compute an under-approximation of the live-before set. By
  8381. \emph{under-approximation}, we mean that the set only contains
  8382. variables that are really live, but it may be missing some. Next, the
  8383. under-approximations for each block can be improved by 1) updating the
  8384. live-after set for each block using the approximate live-before sets
  8385. from the other blocks and 2) perform liveness analysis again on each
  8386. block. In fact, by iterating this process, the under-approximations
  8387. eventually become the correct solutions!
  8388. %
  8389. This approach of iteratively analyzing a control-flow graph is
  8390. applicable to many static analysis problems and goes by the name
  8391. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  8392. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  8393. Washington.
  8394. Let us apply this approach to the above example. We use the empty set
  8395. for the initial live-before set for each block. Let $m_0$ be the
  8396. following mapping from label names to sets of locations (variables and
  8397. registers).
  8398. \begin{center}
  8399. \begin{lstlisting}
  8400. mainstart: {}
  8401. block5: {}
  8402. block7: {}
  8403. block8: {}
  8404. \end{lstlisting}
  8405. \end{center}
  8406. Using the above live-before approximations, we determine the
  8407. live-after for each block and then apply liveness analysis to each
  8408. block. This produces our next approximation $m_1$ of the live-before
  8409. sets.
  8410. \begin{center}
  8411. \begin{lstlisting}
  8412. mainstart: {}
  8413. block5: {i2}
  8414. block7: {i2, sum1}
  8415. block8: {rsp, sum1}
  8416. \end{lstlisting}
  8417. \end{center}
  8418. For the second round, the live-after for \code{mainstart} is the
  8419. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  8420. liveness analysis for \code{mainstart} computes the empty set. The
  8421. live-after for \code{block5} is the union of the live-before sets for
  8422. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  8423. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  8424. sum1\}}. The live-after for \code{block7} is the live-before for
  8425. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  8426. So the liveness analysis for \code{block7} remains \code{\{i2,
  8427. sum1\}}. Together these yield the following approximation $m_2$ of
  8428. the live-before sets.
  8429. \begin{center}
  8430. \begin{lstlisting}
  8431. mainstart: {}
  8432. block5: {i2, rsp, sum1}
  8433. block7: {i2, sum1}
  8434. block8: {rsp, sum1}
  8435. \end{lstlisting}
  8436. \end{center}
  8437. In the preceding iteration, only \code{block5} changed, so we can
  8438. limit our attention to \code{mainstart} and \code{block7}, the two
  8439. blocks that jump to \code{block5}. As a result, the live-before sets
  8440. for \code{mainstart} and \code{block7} are updated to include
  8441. \code{rsp}, yielding the following approximation $m_3$.
  8442. \begin{center}
  8443. \begin{lstlisting}
  8444. mainstart: {rsp}
  8445. block5: {i2, rsp, sum1}
  8446. block7: {i2, rsp, sum1}
  8447. block8: {rsp, sum1}
  8448. \end{lstlisting}
  8449. \end{center}
  8450. Because \code{block7} changed, we analyze \code{block5} once more, but
  8451. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  8452. our approximations have converged, so $m_3$ is the solution.
  8453. This iteration process is guaranteed to converge to a solution by the
  8454. Kleene Fixed-Point Theorem, a general theorem about functions on
  8455. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  8456. any collection that comes with a partial ordering $\sqsubseteq$ on its
  8457. elements, a least element $\bot$ (pronounced bottom), and a join
  8458. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  8459. ordering}\index{join}\footnote{Technically speaking, we will be
  8460. working with join semi-lattices.} When two elements are ordered $m_i
  8461. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  8462. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  8463. approximation than $m_i$. The bottom element $\bot$ represents the
  8464. complete lack of information, i.e., the worst approximation. The join
  8465. operator takes two lattice elements and combines their information,
  8466. i.e., it produces the least upper bound of the two.\index{least upper
  8467. bound}
  8468. A dataflow analysis typically involves two lattices: one lattice to
  8469. represent abstract states and another lattice that aggregates the
  8470. abstract states of all the blocks in the control-flow graph. For
  8471. liveness analysis, an abstract state is a set of locations. We form
  8472. the lattice $L$ by taking its elements to be sets of locations, the
  8473. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  8474. set, and the join operator to be set union.
  8475. %
  8476. We form a second lattice $M$ by taking its elements to be mappings
  8477. from the block labels to sets of locations (elements of $L$). We
  8478. order the mappings point-wise, using the ordering of $L$. So given any
  8479. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  8480. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  8481. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  8482. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  8483. We can think of one iteration of liveness analysis as being a function
  8484. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  8485. mapping.
  8486. \[
  8487. f(m_i) = m_{i+1}
  8488. \]
  8489. Next let us think for a moment about what a final solution $m_s$
  8490. should look like. If we perform liveness analysis using the solution
  8491. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  8492. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  8493. \[
  8494. f(m_s) = m_s
  8495. \]
  8496. Furthermore, the solution should only include locations that are
  8497. forced to be there by performing liveness analysis on the program, so
  8498. the solution should be the \emph{least} fixed point.\index{least fixed point}
  8499. The Kleene Fixed-Point Theorem states that if a function $f$ is
  8500. monotone (better inputs produce better outputs), then the least fixed
  8501. point of $f$ is the least upper bound of the \emph{ascending Kleene
  8502. chain} obtained by starting at $\bot$ and iterating $f$ as
  8503. follows.\index{Kleene Fixed-Point Theorem}
  8504. \[
  8505. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8506. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  8507. \]
  8508. When a lattice contains only finitely-long ascending chains, then
  8509. every Kleene chain tops out at some fixed point after a number of
  8510. iterations of $f$. So that fixed point is also a least upper
  8511. bound of the chain.
  8512. \[
  8513. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8514. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  8515. \]
  8516. The liveness analysis is indeed a monotone function and the lattice
  8517. $M$ only has finitely-long ascending chains because there are only a
  8518. finite number of variables and blocks in the program. Thus we are
  8519. guaranteed that iteratively applying liveness analysis to all blocks
  8520. in the program will eventually produce the least fixed point solution.
  8521. Next let us consider dataflow analysis in general and discuss the
  8522. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  8523. %
  8524. The algorithm has four parameters: the control-flow graph \code{G}, a
  8525. function \code{transfer} that applies the analysis to one block, the
  8526. \code{bottom} and \code{join} operator for the lattice of abstract
  8527. states. The algorithm begins by creating the bottom mapping,
  8528. represented by a hash table. It then pushes all of the nodes in the
  8529. control-flow graph onto the work list (a queue). The algorithm repeats
  8530. the \code{while} loop as long as there are items in the work list. In
  8531. each iteration, a node is popped from the work list and processed. The
  8532. \code{input} for the node is computed by taking the join of the
  8533. abstract states of all the predecessor nodes. The \code{transfer}
  8534. function is then applied to obtain the \code{output} abstract
  8535. state. If the output differs from the previous state for this block,
  8536. the mapping for this block is updated and its successor nodes are
  8537. pushed onto the work list.
  8538. \begin{figure}[tb]
  8539. \begin{lstlisting}
  8540. (define (analyze-dataflow G transfer bottom join)
  8541. (define mapping (make-hash))
  8542. (for ([v (in-vertices G)])
  8543. (dict-set! mapping v bottom))
  8544. (define worklist (make-queue))
  8545. (for ([v (in-vertices G)])
  8546. (enqueue! worklist v))
  8547. (define trans-G (transpose G))
  8548. (while (not (queue-empty? worklist))
  8549. (define node (dequeue! worklist))
  8550. (define input (for/fold ([state bottom])
  8551. ([pred (in-neighbors trans-G node)])
  8552. (join state (dict-ref mapping pred))))
  8553. (define output (transfer node input))
  8554. (cond [(not (equal? output (dict-ref mapping node)))
  8555. (dict-set! mapping node output)
  8556. (for ([v (in-neighbors G node)])
  8557. (enqueue! worklist v))]))
  8558. mapping)
  8559. \end{lstlisting}
  8560. \caption{Generic work list algorithm for dataflow analysis}
  8561. \label{fig:generic-dataflow}
  8562. \end{figure}
  8563. Having discussed the two complications that arise from adding support
  8564. for assignment and loops, we turn to discussing the one new compiler
  8565. pass and the significant changes to existing passes.
  8566. \section{Convert Assignments}
  8567. \label{sec:convert-assignments}
  8568. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  8569. the combination of assignments and lexically-scoped functions requires
  8570. that we box those variables that are both assigned-to and that appear
  8571. free inside a \code{lambda}. The purpose of the
  8572. \code{convert-assignments} pass is to carry out that transformation.
  8573. We recommend placing this pass after \code{uniquify} but before
  8574. \code{reveal-functions}.
  8575. Consider again the first example from
  8576. Section~\ref{sec:assignment-scoping}:
  8577. \begin{lstlisting}
  8578. (let ([x 0])
  8579. (let ([y 0])
  8580. (let ([z 20])
  8581. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8582. (begin
  8583. (set! x 10)
  8584. (set! y 12)
  8585. (f y))))))
  8586. \end{lstlisting}
  8587. The variables \code{x} and \code{y} are assigned-to. The variables
  8588. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  8589. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  8590. The boxing of \code{x} consists of three transformations: initialize
  8591. \code{x} with a vector, replace reads from \code{x} with
  8592. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  8593. \code{vector-set!}. The output of \code{convert-assignments} for this
  8594. example is as follows.
  8595. \begin{lstlisting}
  8596. (define (main) : Integer
  8597. (let ([x0 (vector 0)])
  8598. (let ([y1 0])
  8599. (let ([z2 20])
  8600. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  8601. (+ a3 (+ (vector-ref x0 0) z2)))])
  8602. (begin
  8603. (vector-set! x0 0 10)
  8604. (set! y1 12)
  8605. (f4 y1)))))))
  8606. \end{lstlisting}
  8607. \paragraph{Assigned \& Free}
  8608. We recommend defining an auxiliary function named
  8609. \code{assigned\&free} that takes an expression and simultaneously
  8610. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  8611. that occur free within lambda's, and 3) a new version of the
  8612. expression that records which bound variables occurred in the
  8613. intersection of $A$ and $F$. You can use the struct
  8614. \code{AssignedFree} to do this. Consider the case for
  8615. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  8616. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  8617. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  8618. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  8619. \begin{lstlisting}
  8620. (Let |$x$| |$rhs$| |$body$|)
  8621. |$\Rightarrow$|
  8622. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  8623. \end{lstlisting}
  8624. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  8625. The set of assigned variables for this \code{Let} is
  8626. $A_r \cup (A_b - \{x\})$
  8627. and the set of variables free in lambda's is
  8628. $F_r \cup (F_b - \{x\})$.
  8629. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  8630. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  8631. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  8632. and $F_r$.
  8633. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  8634. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  8635. recursively processing \itm{body}. Wrap each of parameter that occurs
  8636. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  8637. Let $P$ be the set of parameter names in \itm{params}. The result is
  8638. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  8639. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  8640. variables of an expression (see Chapter~\ref{ch:lambdas}).
  8641. \paragraph{Convert Assignments}
  8642. Next we discuss the \code{convert-assignment} pass with its auxiliary
  8643. functions for expressions and definitions. The function for
  8644. expressions, \code{cnvt-assign-exp}, should take an expression and a
  8645. set of assigned-and-free variables (obtained from the result of
  8646. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  8647. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  8648. \code{vector-ref}.
  8649. \begin{lstlisting}
  8650. (Var |$x$|)
  8651. |$\Rightarrow$|
  8652. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  8653. \end{lstlisting}
  8654. %
  8655. In the case for $\LET{\LP\code{AssignedFree}\,
  8656. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  8657. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  8658. \itm{body'} but with $x$ added to the set of assigned-and-free
  8659. variables. Translate the let-expression as follows to bind $x$ to a
  8660. boxed value.
  8661. \begin{lstlisting}
  8662. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  8663. |$\Rightarrow$|
  8664. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  8665. \end{lstlisting}
  8666. %
  8667. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  8668. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  8669. variables, translate the \code{set!} into a \code{vector-set!}
  8670. as follows.
  8671. \begin{lstlisting}
  8672. (SetBang |$x$| |$\itm{rhs}$|)
  8673. |$\Rightarrow$|
  8674. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  8675. \end{lstlisting}
  8676. %
  8677. The case for \code{Lambda} is non-trivial, but it is similar to the
  8678. case for function definitions, which we discuss next.
  8679. The auxiliary function for definitions, \code{cnvt-assign-def},
  8680. applies assignment conversion to function definitions.
  8681. We translate a function definition as follows.
  8682. \begin{lstlisting}
  8683. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  8684. |$\Rightarrow$|
  8685. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  8686. \end{lstlisting}
  8687. So it remains to explain \itm{params'} and $\itm{body}_4$.
  8688. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  8689. \code{assigned\&free} on $\itm{body_1}$.
  8690. Let $P$ be the parameter names in \itm{params}.
  8691. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  8692. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  8693. as the set of assigned-and-free variables.
  8694. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  8695. in a sequence of let-expressions that box the parameters
  8696. that are in $A_b \cap F_b$.
  8697. %
  8698. Regarding \itm{params'}, change the names of the parameters that are
  8699. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  8700. variables can retain the original names). Recall the second example in
  8701. Section~\ref{sec:assignment-scoping} involving a counter
  8702. abstraction. The following is the output of assignment version for
  8703. function \code{f}.
  8704. \begin{lstlisting}
  8705. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  8706. (vector
  8707. (lambda: () : Integer x1)
  8708. (lambda: () : Void (set! x1 (+ 1 x1)))))
  8709. |$\Rightarrow$|
  8710. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  8711. (let ([x1 (vector param_x1)])
  8712. (vector (lambda: () : Integer (vector-ref x1 0))
  8713. (lambda: () : Void
  8714. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  8715. \end{lstlisting}
  8716. \section{Remove Complex Operands}
  8717. \label{sec:rco-loop}
  8718. The three new language forms, \code{while}, \code{set!}, and
  8719. \code{begin} are all complex expressions and their subexpressions are
  8720. allowed to be complex. Figure~\ref{fig:r4-anf-syntax} defines the
  8721. output language $R_4^{\dagger}$ of this pass.
  8722. \begin{figure}[tp]
  8723. \centering
  8724. \fbox{
  8725. \begin{minipage}{0.96\textwidth}
  8726. \small
  8727. \[
  8728. \begin{array}{rcl}
  8729. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  8730. \mid \VOID{} } \\
  8731. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8732. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  8733. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  8734. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8735. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8736. \end{array}
  8737. \]
  8738. \end{minipage}
  8739. }
  8740. \caption{$R_8^{\dagger}$ is $R_8$ in administrative normal form (ANF).}
  8741. \label{fig:r8-anf-syntax}
  8742. \end{figure}
  8743. As usual, when a complex expression appears in a grammar position that
  8744. needs to be atomic, such as the argument of a primitive operator, we
  8745. must introduce a temporary variable and bind it to the complex
  8746. expression. This approach applies, unchanged, to handle the new
  8747. language forms. For example, in the following code there are two
  8748. \code{begin} expressions appearing as arguments to \code{+}. The
  8749. output of \code{rco-exp} is shown below, in which the \code{begin}
  8750. expressions have been bound to temporary variables. Recall that
  8751. \code{let} expressions in $R_8^{\dagger}$ are allowed to have
  8752. arbitrary expressions in their right-hand-side expression, so it is
  8753. fine to place \code{begin} there.
  8754. \begin{lstlisting}
  8755. (let ([x0 10])
  8756. (let ([y1 0])
  8757. (+ (+ (begin (set! y1 (read)) x0)
  8758. (begin (set! x0 (read)) y1))
  8759. x0)))
  8760. |$\Rightarrow$|
  8761. (let ([x0 10])
  8762. (let ([y1 0])
  8763. (let ([tmp2 (begin (set! y1 (read)) x0)])
  8764. (let ([tmp3 (begin (set! x0 (read)) y1)])
  8765. (let ([tmp4 (+ tmp2 tmp3)])
  8766. (+ tmp4 x0))))))
  8767. \end{lstlisting}
  8768. \section{Explicate Control and $C_7$}
  8769. \label{sec:explicate-loop}
  8770. Recall that in the \code{explicate-control} pass we define one helper
  8771. function for each kind of position in the program. For the $R_1$
  8772. language of integers and variables we needed kinds of positions:
  8773. assignment and tail. The \code{if} expressions of $R_2$ introduced
  8774. predicate positions. For $R_8$, the \code{begin} expression introduces
  8775. yet another kind of position: effect position. Except for the last
  8776. subexpression, the subexpressions inside a \code{begin} are evaluated
  8777. only for their effect. Their result values are discarded. We can
  8778. generate better code by taking this fact into account.
  8779. The output language of \code{explicate-control} is $C_7$
  8780. (Figure~\ref{fig:c7-syntax}), which is nearly identical to $C_3$. The
  8781. only difference is that \code{Call}, \code{vector-set!}, and
  8782. \code{read} may also appear as statements.
  8783. \begin{figure}[tp]
  8784. \fbox{
  8785. \begin{minipage}{0.96\textwidth}
  8786. \small
  8787. \[
  8788. \begin{array}{lcl}
  8789. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8790. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8791. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  8792. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  8793. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8794. C_7 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8795. \end{array}
  8796. \]
  8797. \end{minipage}
  8798. }
  8799. \caption{The abstract syntax of $C_7$, extending $C_3$ (Figure~\ref{fig:c3-syntax}).}
  8800. \label{fig:c7-syntax}
  8801. \end{figure}
  8802. The new auxiliary function \code{explicate-effect} takes an expression
  8803. (in an effect position) and a promise of a continuation block. The
  8804. function returns a promise for a $\Tail$ that includes the generated
  8805. code for the input expression followed by the continuation block. If
  8806. the expression is obviously pure, that is, never causes side effects,
  8807. then the expression can be removed, so the result is just the
  8808. continuation block.
  8809. %
  8810. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  8811. case. First, you will need a fresh label $\itm{loop}$ for the top of
  8812. the loop. Recursively process the \itm{body} (in effect position)
  8813. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  8814. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  8815. \itm{body'} as the then-branch and the continuation block as the
  8816. else-branch. The result should be added to the control-flow graph with
  8817. the label \itm{loop}. The result for the whole \code{while} loop is a
  8818. \code{goto} to the \itm{loop} label. Note that the loop should only be
  8819. added to the control-flow graph if the loop is indeed used, which can
  8820. be accomplished using \code{delay}.
  8821. The auxiliary functions for tail, assignment, and predicate positions
  8822. need to be updated. The three new language forms, \code{while},
  8823. \code{set!}, and \code{begin}, can appear in assignment and tail
  8824. positions. Only \code{begin} may appear in predicate positions; the
  8825. other two have result type \code{Void}.
  8826. \section{Select Instructions}
  8827. \label{sec:select-instructions-loop}
  8828. Only three small additions are needed in the
  8829. \code{select-instructions} pass to handle the changes to $C_7$. That
  8830. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  8831. stand-alone statements instead of only appearing on the right-hand
  8832. side of an assignment statement. The code generation is nearly
  8833. identical; just leave off the instruction for moving the result into
  8834. the left-hand side.
  8835. \section{Register Allocation}
  8836. \label{sec:register-allocation-loop}
  8837. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  8838. loops in $R_8$ means that the control-flow graphs may contain cycles,
  8839. which complicates the liveness analysis needed for register
  8840. allocation.
  8841. \subsection{Liveness Analysis}
  8842. \label{sec:liveness-analysis-r8}
  8843. We recommend using the generic \code{analyze-dataflow} function that
  8844. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  8845. perform liveness analysis, replacing the code in
  8846. \code{uncover-live-CFG} that processed the basic blocks in topological
  8847. order (Section~\ref{sec:liveness-analysis-r2}).
  8848. The \code{analyze-dataflow} function has four parameters.
  8849. \begin{enumerate}
  8850. \item The first parameter \code{G} should be a directed graph from the
  8851. \code{racket/graph} package (see the sidebar in
  8852. Section~\ref{sec:build-interference}) that represents the
  8853. control-flow graph.
  8854. \item The second parameter \code{transfer} is a function that applies
  8855. liveness analysis to a basic block. It takes two parameters: the
  8856. label for the block to analyze and the live-after set for that
  8857. block. The transfer function should return the live-before set for
  8858. the block. Also, as a side-effect, it should update the block's
  8859. $\itm{info}$ with the liveness information for each instruction. To
  8860. implement the \code{transfer} function, you should be able to reuse
  8861. the code you already have for analyzing basic blocks.
  8862. \item The third and fourth parameters of \code{analyze-dataflow} are
  8863. \code{bottom} and \code{join} for the lattice of abstract states,
  8864. i.e. sets of locations. The bottom of the lattice is the empty set
  8865. \code{(set)} and the join operator is \code{set-union}.
  8866. \end{enumerate}
  8867. \begin{figure}[p]
  8868. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8869. \node (R4) at (0,2) {\large $R_8$};
  8870. \node (R4-2) at (3,2) {\large $R_8$};
  8871. \node (R4-3) at (6,2) {\large $R_8$};
  8872. \node (R4-4) at (9,2) {\large $R_8$};
  8873. \node (F1-1) at (12,0) {\large $F_1$};
  8874. \node (F1-2) at (9,0) {\large $F_1$};
  8875. \node (F1-3) at (6,0) {\large $F_1$};
  8876. \node (F1-4) at (3,0) {\large $F_1$};
  8877. \node (F1-5) at (0,0) {\large $F_1$};
  8878. \node (C3-2) at (3,-2) {\large $C_3$};
  8879. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  8880. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  8881. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  8882. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  8883. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  8884. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  8885. %% \path[->,bend left=15] (R4) edge [above] node
  8886. %% {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  8887. \path[->,bend left=15] (R4) edge [above] node
  8888. {\ttfamily\footnotesize shrink} (R4-2);
  8889. \path[->,bend left=15] (R4-2) edge [above] node
  8890. {\ttfamily\footnotesize uniquify} (R4-3);
  8891. \path[->,bend left=15] (R4-3) edge [above] node
  8892. {\ttfamily\footnotesize\color{red} convert-assignments} (R4-4);
  8893. \path[->,bend left=15] (R4-4) edge [left] node
  8894. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8895. \path[->,bend left=15] (F1-1) edge [below] node
  8896. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8897. \path[->,bend right=15] (F1-2) edge [above] node
  8898. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8899. \path[->,bend right=15] (F1-3) edge [above] node
  8900. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8901. \path[->,bend right=15] (F1-4) edge [above] node
  8902. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-5);
  8903. \path[->,bend right=15] (F1-5) edge [right] node
  8904. {\ttfamily\footnotesize\color{red} explicate-control} (C3-2);
  8905. \path[->,bend left=15] (C3-2) edge [left] node
  8906. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  8907. \path[->,bend right=15] (x86-2) edge [left] node
  8908. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  8909. \path[->,bend right=15] (x86-2-1) edge [below] node
  8910. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8911. \path[->,bend right=15] (x86-2-2) edge [left] node
  8912. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8913. \path[->,bend left=15] (x86-3) edge [above] node
  8914. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8915. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  8916. \end{tikzpicture}
  8917. \caption{Diagram of the passes for $R_8$ (loops and assignment).}
  8918. \label{fig:R8-passes}
  8919. \end{figure}
  8920. Figure~\ref{fig:R8-passes} provides an overview of all the passes needed
  8921. for the compilation of $R_8$.
  8922. % TODO: challenge assignment
  8923. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8924. \chapter{Dynamic Typing}
  8925. \label{ch:type-dynamic}
  8926. \index{dynamic typing}
  8927. In this chapter we discuss the compilation of $R_7$, a dynamically
  8928. typed language and a subset of the Racket language. In contrast, the
  8929. previous chapters have studies the compilation of Typed Racket. In
  8930. dynamically typed languages, a given expression may produce a value of
  8931. a different type each time it is executed. Consider the following
  8932. example with a conditional \code{if} expression that may return a
  8933. Boolean or an integer depending on the input to the program.
  8934. \begin{lstlisting}
  8935. (not (if (eq? (read) 1) #f 0))
  8936. \end{lstlisting}
  8937. Languages that allow expressions to produce different kinds of values
  8938. are called \emph{polymorphic}, a word composed of the Greek roots
  8939. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8940. are several kinds of polymorphism in programming languages, such as
  8941. subtype polymorphism and parametric
  8942. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8943. study in this chapter does not have a special name but it is the kind
  8944. that arises in dynamically typed languages.
  8945. Another characteristic of dynamically typed languages is that
  8946. primitive operations, such as \code{not}, are often defined to operate
  8947. on many different types of values. In fact, in Racket, the \code{not}
  8948. operator produces a result for any kind of value: given \code{\#f} it
  8949. returns \code{\#t} and given anything else it returns \code{\#f}.
  8950. Furthermore, even when primitive operations restrict their inputs to
  8951. values of a certain type, this restriction is enforced at runtime
  8952. instead of during compilation. For example, the following vector
  8953. reference results in a run-time contract violation because the index
  8954. must be in integer, not a Boolean such as \code{\#t}.
  8955. \begin{lstlisting}
  8956. (vector-ref (vector 42) #t)
  8957. \end{lstlisting}
  8958. \begin{figure}[tp]
  8959. \centering
  8960. \fbox{
  8961. \begin{minipage}{0.97\textwidth}
  8962. \[
  8963. \begin{array}{rcl}
  8964. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8965. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8966. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8967. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8968. &\mid& \key{\#t} \mid \key{\#f}
  8969. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8970. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8971. \mid \CUNIOP{\key{not}}{\Exp} \\
  8972. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8973. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8974. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8975. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8976. &\mid& \LP\Exp \; \Exp\ldots\RP
  8977. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8978. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8979. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8980. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8981. R_7 &::=& \Def\ldots\; \Exp
  8982. \end{array}
  8983. \]
  8984. \end{minipage}
  8985. }
  8986. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  8987. \label{fig:r7-concrete-syntax}
  8988. \end{figure}
  8989. \begin{figure}[tp]
  8990. \centering
  8991. \fbox{
  8992. \begin{minipage}{0.96\textwidth}
  8993. \small
  8994. \[
  8995. \begin{array}{lcl}
  8996. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8997. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8998. &\mid& \BOOL{\itm{bool}}
  8999. \mid \IF{\Exp}{\Exp}{\Exp} \\
  9000. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  9001. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  9002. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  9003. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  9004. \end{array}
  9005. \]
  9006. \end{minipage}
  9007. }
  9008. \caption{The abstract syntax of $R_7$.}
  9009. \label{fig:r7-syntax}
  9010. \end{figure}
  9011. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  9012. defined in Figures~\ref{fig:r7-concrete-syntax} and
  9013. \ref{fig:r7-syntax}.
  9014. %
  9015. There is no type checker for $R_7$ because it is not a statically
  9016. typed language (it's dynamically typed!).
  9017. %
  9018. The definitional interpreter for $R_7$ is presented in
  9019. Figure~\ref{fig:interp-R7}.
  9020. \begin{figure}[tbp]
  9021. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9022. (define (interp-R7-exp env)
  9023. (lambda (ast)
  9024. (define recur (interp-R7-exp env))
  9025. (match ast
  9026. [(Var x) (lookup x env)]
  9027. [(Int n) `(tagged ,n Integer)]
  9028. [(Bool b) `(tagged ,b Boolean)]
  9029. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  9030. [(Lambda xs rt body)
  9031. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  9032. [(Prim 'vector es)
  9033. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  9034. (Vector ,@(for/list ([e es]) 'Any)))]
  9035. [(Prim 'vector-set! (list e1 n e2))
  9036. (define vec (value-of-any (recur e1)))
  9037. (define i (value-of-any (recur n)))
  9038. (vector-set! vec i (recur e2))
  9039. `(tagged ,(void) Void)]
  9040. [(Prim 'vector-ref (list e1 n))
  9041. (define vec (value-of-any (recur e1)))
  9042. (define i (value-of-any (recur n)))
  9043. (vector-ref vec i)]
  9044. [(Let x e body)
  9045. (define v (recur e))
  9046. ((interp-R7-exp (cons (cons x v) env)) body)]
  9047. [(Prim 'and (list e1 e2))
  9048. (recur (If e1 e2 (Bool #f)))]
  9049. [(Prim 'or (list e1 e2))
  9050. (define v1 (recur e1))
  9051. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  9052. [(Prim 'eq? (list l r))
  9053. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  9054. [(If q t f)
  9055. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  9056. [(Prim op es)
  9057. (tag-value
  9058. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  9059. [(Apply f es)
  9060. (define new-args (map recur es))
  9061. (let ([f-val (value-of-any (recur f))])
  9062. (match f-val
  9063. [`(function (,xs ...) ,body ,lam-env)
  9064. (define new-env (append (map cons xs new-args) lam-env))
  9065. ((interp-R7-exp new-env) body)]
  9066. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  9067. )))
  9068. \end{lstlisting}
  9069. \caption{Interpreter for the $R_7$ language.}
  9070. \label{fig:interp-R7}
  9071. \end{figure}
  9072. Let us consider how we might compile $R_7$ to x86, thinking about the
  9073. first example above. Our bit-level representation of the Boolean
  9074. \code{\#f} is zero and similarly for the integer \code{0}. However,
  9075. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  9076. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  9077. general, cannot be determined at compile time, but depends on the
  9078. runtime type of its input, as in the example above that depends on the
  9079. result of \code{(read)}.
  9080. The way around this problem is to include information about a value's
  9081. runtime type in the value itself, so that this information can be
  9082. inspected by operators such as \code{not}. In particular, we
  9083. steal the 3 right-most bits from our 64-bit values to encode the
  9084. runtime type. We use $001$ to identify integers, $100$ for
  9085. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  9086. void value. We refer to these 3 bits as the \emph{tag} and we
  9087. define the following auxiliary function.
  9088. \begin{align*}
  9089. \itm{tagof}(\key{Integer}) &= 001 \\
  9090. \itm{tagof}(\key{Boolean}) &= 100 \\
  9091. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9092. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  9093. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9094. \itm{tagof}(\key{Void}) &= 101
  9095. \end{align*}
  9096. (We say more about the new \key{Vectorof} type shortly.)
  9097. This stealing of 3 bits comes at some
  9098. price: our integers are reduced to ranging from $-2^{60}$ to
  9099. $2^{60}$. The stealing does not adversely affect vectors and
  9100. procedures because those values are addresses, and our addresses are
  9101. 8-byte aligned so the rightmost 3 bits are unused, they are always
  9102. $000$. Thus, we do not lose information by overwriting the rightmost 3
  9103. bits with the tag and we can simply zero-out the tag to recover the
  9104. original address.
  9105. In some sense, these tagged values are a new kind of value. Indeed,
  9106. we can extend our \emph{typed} language with tagged values by adding a
  9107. new type to classify them, called \key{Any}, and with operations for
  9108. creating and using tagged values, yielding the $R_6$ language that we
  9109. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  9110. fundamental support for polymorphism and runtime types that we need to
  9111. support dynamic typing.
  9112. There is an interesting interaction between tagged values and garbage
  9113. collection. A variable of type \code{Any} might refer to a vector and
  9114. therefore it might be a root that needs to be inspected and copied
  9115. during garbage collection. Thus, we need to treat variables of type
  9116. \code{Any} in a similar way to variables of type \code{Vector} for
  9117. purposes of register allocation, which we discuss in
  9118. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  9119. variable of type \code{Any} is spilled, it must be spilled to the root
  9120. stack. But this means that the garbage collector needs to be able to
  9121. differentiate between (1) plain old pointers to tuples, (2) a tagged
  9122. value that points to a tuple, and (3) a tagged value that is not a
  9123. tuple. We enable this differentiation by choosing not to use the tag
  9124. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  9125. identifying plain old pointers to tuples. That way, if one of the
  9126. first three bits is set, then we have a tagged value and inspecting
  9127. the tag can differentiation between vectors ($010$) and the other
  9128. kinds of values.
  9129. We implement our untyped language $R_7$ by compiling it to $R_6$
  9130. (Section~\ref{sec:compile-r7}), but first we describe the how to
  9131. extend our compiler to handle the new features of $R_6$
  9132. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  9133. \ref{sec:register-allocation-r6}).
  9134. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  9135. \label{sec:r6-lang}
  9136. \begin{figure}[tp]
  9137. \centering
  9138. \fbox{
  9139. \begin{minipage}{0.97\textwidth}\small
  9140. \[
  9141. \begin{array}{lcl}
  9142. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  9143. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  9144. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  9145. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  9146. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  9147. \Exp &::=& \ldots
  9148. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  9149. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  9150. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  9151. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9152. R_6 &::=& \gray{\Def\ldots \; \Exp}
  9153. \end{array}
  9154. \]
  9155. \end{minipage}
  9156. }
  9157. \caption{The concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  9158. with \key{Any}.}
  9159. \label{fig:r6-concrete-syntax}
  9160. \end{figure}
  9161. \begin{figure}[tp]
  9162. \centering
  9163. \fbox{
  9164. \begin{minipage}{0.96\textwidth}
  9165. \small
  9166. \[
  9167. \begin{array}{lcl}
  9168. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  9169. \mid \code{procedure?} \mid \code{void?} \\
  9170. \Exp &::=& \ldots
  9171. \mid \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  9172. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9173. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9174. \end{array}
  9175. \]
  9176. \end{minipage}
  9177. }
  9178. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  9179. \label{fig:r6-syntax}
  9180. \end{figure}
  9181. The concrete and abstract syntax of $R_6$ is defined in
  9182. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  9183. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  9184. expression $e$ of type $T$ into a tagged value. The
  9185. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  9186. expression $e$ into a value of type $T$ or else halts the program if
  9187. the type tag is not equivalent to $T$. We treat
  9188. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  9189. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  9190. %
  9191. Note that in both \key{inject} and \key{project}, the type $T$ is
  9192. restricted to the flat types $\FType$, which simplifies the
  9193. implementation and corresponds with what is needed for compiling
  9194. untyped Racket.
  9195. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  9196. expression $e$ to produce a tagged value; they return \key{\#t} if the
  9197. tag corresponds to the predicate and they return \key{\#f} otherwise.
  9198. The type checker for $R_6$ is shown in Figures~\ref{fig:type-check-R6-part-1}
  9199. and \ref{fig:type-check-R6-part-2}.
  9200. The interpreter for $R_6$ is in Figure~\ref{fig:interp-R6}.
  9201. \begin{figure}[btp]
  9202. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9203. (define (operator-types)
  9204. '(...
  9205. (integer? . ((Any) . Boolean))
  9206. (vector? . ((Any) . Boolean))
  9207. (procedure? . ((Any) . Boolean))
  9208. (void? . ((Any) . Boolean))
  9209. ))
  9210. (define (type-check-exp env)
  9211. (lambda (e)
  9212. (define recur (type-check-exp env))
  9213. (match e
  9214. ...
  9215. [(Inject e ty)
  9216. (unless (flat-ty? ty)
  9217. (error 'type-check-exp
  9218. "may only inject a value of flat type, not ~a" ty))
  9219. (define-values (new-e e-ty) (recur e))
  9220. (cond
  9221. [(type-equal? e-ty ty)
  9222. (values (Inject new-e ty) 'Any)]
  9223. [else
  9224. (error 'type-check-exp
  9225. "injected expression does not have expected type"
  9226. e e-ty ty)])]
  9227. [(Project e ty)
  9228. (unless (flat-ty? ty)
  9229. (error 'type-check-exp
  9230. "may only project to a flat type, not ~a" ty))
  9231. (define-values (new-e e-ty) (recur e))
  9232. (cond
  9233. [(type-equal? e-ty 'Any)
  9234. (values (Project new-e ty) ty)]
  9235. [else
  9236. (error 'type-check-exp
  9237. "project expression does not have type Any" e)])]
  9238. [(Prim pred (list e))
  9239. #:when (set-member? type-predicates pred)
  9240. (define-values (new-e e-ty) (recur e))
  9241. (cond
  9242. [(type-equal? e-ty 'Any)
  9243. (values (Prim pred (list new-e)) 'Boolean)]
  9244. [else
  9245. (error 'type-check-exp
  9246. "type predicate expected argument of type Any, not ~a" e-ty)])]
  9247. ...
  9248. \end{lstlisting}
  9249. \caption{Type checker for the $R_6$ language, part 1.}
  9250. \label{fig:type-check-R6-part-1}
  9251. \end{figure}
  9252. \begin{figure}[btp]
  9253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9254. [(Prim 'vector-ref (list e ei))
  9255. (define-values (e^ t) (recur e))
  9256. (define-values (i it) (recur ei))
  9257. (unless (type-equal? it 'Integer)
  9258. (error 'type-check-exp "vector-ref: index not Integer: ~a" it))
  9259. (match (list t i)
  9260. [(list `(Vector ,ts ...) (Int i^))
  9261. (unless (and (exact-nonnegative-integer? i^)
  9262. (i^ . < . (length ts)))
  9263. (error 'type-check-exp "invalid index ~a in ~a" i^ e))
  9264. (let ([t (list-ref ts i^)])
  9265. (values (Prim 'vector-ref (list e^ (Int i^))) t))]
  9266. [(list `(Vectorof ,t) i)
  9267. (values (Prim 'vector-ref (list e^ i)) t)]
  9268. [else (error "expected a vector in vector-ref, not" t)])]
  9269. [(Prim 'vector-set! (list e-vec e-i e-arg))
  9270. (define-values (e-vec^ t-vec) (recur e-vec))
  9271. (define-values (i it) (recur e-i))
  9272. (define-values (e-arg^ t-arg) (recur e-arg))
  9273. (unless (type-equal? it 'Integer)
  9274. (error 'type-check-exp "vector-set!: index not Integer: ~a" it))
  9275. (match (list t-vec i)
  9276. [(list `(Vector ,ts ...) (Int i^))
  9277. (unless (and (exact-nonnegative-integer? i^)
  9278. (i^ . < . (length ts)))
  9279. (error 'type-check-exp "invalid index ~a in ~a" i^ e))
  9280. (unless (type-equal? (list-ref ts i^) t-arg)
  9281. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  9282. (list-ref ts i^) t-arg))
  9283. (values (Prim 'vector-set! (list e-vec^ (Int i^) e-arg^)) 'Void)]
  9284. [(list `(Vectorof ,t) i)
  9285. (unless (type-equal? t t-arg)
  9286. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  9287. t t-arg))
  9288. (values (Prim 'vector-set! (list e-vec^ i e-arg^)) 'Void)]
  9289. [else
  9290. (error 'type-check-exp "expected a vector in vector-set!, not ~a"
  9291. t-vec)])]
  9292. ...
  9293. [else
  9294. (error 'type-check-exp "R6/unmatched ~a" e)]
  9295. )))
  9296. \end{lstlisting}
  9297. \caption{Type checker for the $R_6$ language, part 2.}
  9298. \label{fig:type-check-R6-part-2}
  9299. \end{figure}
  9300. % to do: add rules for vector-ref, etc. for Vectorof
  9301. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  9302. \begin{figure}[btp]
  9303. \begin{lstlisting}
  9304. (define (interp-op op)
  9305. (match op
  9306. ...
  9307. ['boolean? (lambda (v)
  9308. (match v
  9309. [`(tagged ,v1 ,tg)
  9310. (equal? tg (any-tag 'Boolean))]
  9311. [else #f]))]
  9312. ['integer? (lambda (v)
  9313. (match v
  9314. [`(tagged ,v1 ,tg)
  9315. (equal? tg (any-tag 'Integer))]
  9316. [else #f]))]
  9317. ['vector? (lambda (v)
  9318. (match v
  9319. [`(tagged ,v1 ,tg)
  9320. (equal? tg (any-tag `(Vector Any)))]
  9321. [else #f]))]
  9322. ['procedure? (lambda (v)
  9323. (match v
  9324. [`(tagged ,v1 ,tg)
  9325. (equal? tg (any-tag `(Any -> Any)))]
  9326. [else #f]))]
  9327. ...
  9328. ))
  9329. (define (interp-exp env)
  9330. (lambda (e)
  9331. (define recur (interp-exp env))
  9332. (let ([ret
  9333. (match e
  9334. ...
  9335. [(Inject e ty)
  9336. (apply-inject ((interp-exp env) e) (any-tag ty))]
  9337. [(Project e ty2)
  9338. (define v (recur e))
  9339. (apply-project v ty2)]
  9340. [(Exit)
  9341. (error 'interp-exp "exiting")]
  9342. [else (error 'interp-exp "unrecognized expression ~a" e)]
  9343. )])
  9344. (verbose "R6/interp-exp ==>" ret)
  9345. ret)))
  9346. \end{lstlisting}
  9347. \caption{Interpreter for $R_6$.}
  9348. \label{fig:interp-R6}
  9349. \end{figure}
  9350. %\clearpage
  9351. \section{Shrinking $R_6$}
  9352. \label{sec:shrink-r6}
  9353. % TODO: define R'_6
  9354. In the \code{shrink} pass we recommend compiling \code{project} into
  9355. an \code{if} expression that checks whether the value's tag matches
  9356. the target type; if it does, the value is converted to a value of the
  9357. target type by removing the tag; if it does not, the program exits.
  9358. To perform these actions we need a new primitive operation,
  9359. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9360. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9361. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9362. underlying value from a tagged value. The \code{ValueOf} form
  9363. includes the type for the underlying value which is used by the type
  9364. checker. Finally, the \code{Exit} form ends the execution of the
  9365. program.
  9366. If the target type of the projection is \code{Boolean} or
  9367. \code{Integer}, then \code{Project} can be translated as follows.
  9368. \begin{center}
  9369. \begin{minipage}{1.0\textwidth}
  9370. \begin{lstlisting}
  9371. (Project |$e$| |$\FType$|)
  9372. |$\Rightarrow$|
  9373. (Let |$\itm{tmp}$| |$e'$|
  9374. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9375. (Int |$\itm{tagof}(\FType)$|)))
  9376. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9377. (Exit)))
  9378. \end{lstlisting}
  9379. \end{minipage}
  9380. \end{center}
  9381. If the target type of the projection is a vector or function type,
  9382. then there is a bit more work to do. For vectors, check that the
  9383. length of the vector type matches the length of the vector (using the
  9384. \code{vector-length} primitive). For functions, check that the number
  9385. of parameters in the function type matches the function's arity (using
  9386. \code{procedure-arity}).
  9387. Regarding \code{inject}, we recommend compiling it to a slightly
  9388. lower-level primitive operation named \code{make-any}. This operation
  9389. takes a tag instead of a type. \\
  9390. \begin{center}
  9391. \begin{minipage}{1.0\textwidth}
  9392. \begin{lstlisting}
  9393. (Inject |$e$| |$\FType$|)
  9394. |$\Rightarrow$|
  9395. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9396. \end{lstlisting}
  9397. \end{minipage}
  9398. \end{center}
  9399. We recommend translating the type predicates (\code{boolean?}, etc.)
  9400. into uses of \code{tag-of-any} and \code{eq?}.
  9401. \section{Remove Complex Operands}
  9402. \label{sec:rco-r6}
  9403. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9404. The subexpression of \code{ValueOf} must be atomic.
  9405. \section{Explicate Control and $C_5$}
  9406. \label{sec:explicate-r6}
  9407. The output of \code{explicate-control} is the $C_5$ language whose
  9408. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9409. form that we added to $R_6$ remains an expression and the \code{Exit}
  9410. expression becomes a statement.
  9411. \begin{figure}[tp]
  9412. \fbox{
  9413. \begin{minipage}{0.96\textwidth}
  9414. \small
  9415. \[
  9416. \begin{array}{lcl}
  9417. \Exp &::= & \ldots
  9418. \mid \VALUEOF{\Exp}{\FType} \\
  9419. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9420. \mid \LP\key{Collect} \,\itm{int}\RP }
  9421. \mid \LP\key{Exit}\RP \\
  9422. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9423. \mid \GOTO{\itm{label}} } \\
  9424. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9425. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  9426. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9427. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9428. \end{array}
  9429. \]
  9430. \end{minipage}
  9431. }
  9432. \caption{The abstract syntax of $C_5$, extending $C_4$ (Figure~\ref{fig:c4-syntax}).}
  9433. \label{fig:c5-syntax}
  9434. \end{figure}
  9435. \section{Select Instructions}
  9436. \label{sec:select-r6}
  9437. \paragraph{Make-any}
  9438. We recommend compiling the \key{make-any} primitive as follows if the
  9439. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9440. shifts the destination to the left by the number of bits specified its
  9441. source argument (in this case $3$, the length of the tag) and it
  9442. preserves the sign of the integer. We use the \key{orq} instruction to
  9443. combine the tag and the value to form the tagged value. \\
  9444. \begin{lstlisting}
  9445. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9446. |$\Rightarrow$|
  9447. movq |$e'$|, |\itm{lhs'}|
  9448. salq $3, |\itm{lhs'}|
  9449. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9450. \end{lstlisting}
  9451. The instruction selection for vectors and procedures is different
  9452. because their is no need to shift them to the left. The rightmost 3
  9453. bits are already zeros as described above. So we just combine the
  9454. value and the tag using \key{orq}. \\
  9455. \begin{lstlisting}
  9456. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9457. |$\Rightarrow$|
  9458. movq |$e'$|, |\itm{lhs'}|
  9459. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9460. \end{lstlisting}
  9461. \paragraph{Tag-of-any}
  9462. Recall that the \code{tag-of-any} operation extracts the type tag from
  9463. a value of type \code{Any}. The type tag is the bottom three bits, so
  9464. we obtain the tag by taking the bitwise-and of the value with $111$
  9465. ($7$ in decimal).
  9466. \begin{lstlisting}
  9467. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9468. |$\Rightarrow$|
  9469. movq |$e'$|, |\itm{lhs'}|
  9470. andq $7, |\itm{lhs'}|
  9471. \end{lstlisting}
  9472. \paragraph{ValueOf}
  9473. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9474. depending on whether the type $T$ is a pointer (vector or procedure)
  9475. or not (Integer or Boolean). The following shows the instruction
  9476. selection for Integer and Boolean. We produce an untagged value by
  9477. shifting it to the right by 3 bits.
  9478. \begin{lstlisting}
  9479. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9480. |$\Rightarrow$|
  9481. movq |$e'$|, |\itm{lhs'}|
  9482. sarq $3, |\itm{lhs'}|
  9483. \end{lstlisting}
  9484. %
  9485. In the case for vectors and procedures, there is no need to
  9486. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9487. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9488. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9489. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9490. then apply \code{andq} with the tagged value to get the desired
  9491. result. \\
  9492. \begin{lstlisting}
  9493. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9494. |$\Rightarrow$|
  9495. movq $|$-8$|, |\itm{lhs'}|
  9496. andq |$e'$|, |\itm{lhs'}|
  9497. \end{lstlisting}
  9498. %% \paragraph{Type Predicates} We leave it to the reader to
  9499. %% devise a sequence of instructions to implement the type predicates
  9500. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9501. \section{Register Allocation for $R_6$}
  9502. \label{sec:register-allocation-r6}
  9503. \index{register allocation}
  9504. As mentioned above, a variable of type \code{Any} might refer to a
  9505. vector. Thus, the register allocator for $R_6$ needs to treat variable
  9506. of type \code{Any} in the same way that it treats variables of type
  9507. \code{Vector} for purposes of garbage collection. In particular,
  9508. \begin{itemize}
  9509. \item If a variable of type \code{Any} is live during a function call,
  9510. then it must be spilled. One way to accomplish this is to augment
  9511. \code{build-interference} to mark all variables that are live after
  9512. a \code{callq} as interfering with all the registers.
  9513. \item If a variable of type \code{Any} is spilled, it must be spilled
  9514. to the root stack instead of the normal procedure call stack.
  9515. \end{itemize}
  9516. \begin{exercise}\normalfont
  9517. Expand your compiler to handle $R_6$ as discussed in the last few
  9518. sections. Create 5 new programs that use the \code{Any} type and the
  9519. new operations (\code{inject}, \code{project}, \code{boolean?},
  9520. etc.). Test your compiler on these new programs and all of your
  9521. previously created test programs.
  9522. \end{exercise}
  9523. \section{Compiling $R_7$ to $R_6$}
  9524. \label{sec:compile-r7}
  9525. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  9526. $R_7$ forms into $R_6$. An important invariant of this pass is that
  9527. given a subexpression $e$ in the $R_7$ program, the pass will produce
  9528. an expression $e'$ in $R_6$ that has type \key{Any}. For example, the
  9529. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  9530. the Boolean \code{\#t}, which must be injected to produce an
  9531. expression of type \key{Any}.
  9532. %
  9533. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  9534. addition, is representative of compilation for many primitive
  9535. operations: the arguments have type \key{Any} and must be projected to
  9536. \key{Integer} before the addition can be performed.
  9537. The compilation of \key{lambda} (third row of
  9538. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  9539. produce type annotations: we simply use \key{Any}.
  9540. %
  9541. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9542. has to account for some differences in behavior between $R_7$ and
  9543. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  9544. kind of values can be used in various places. For example, the
  9545. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9546. the arguments need not be of the same type (in that case the
  9547. result is \code{\#f}).
  9548. \begin{figure}[btp]
  9549. \centering
  9550. \begin{tabular}{|lll|} \hline
  9551. \begin{minipage}{0.27\textwidth}
  9552. \begin{lstlisting}
  9553. #t
  9554. \end{lstlisting}
  9555. \end{minipage}
  9556. &
  9557. $\Rightarrow$
  9558. &
  9559. \begin{minipage}{0.6\textwidth}
  9560. \begin{lstlisting}
  9561. (inject #t Boolean)
  9562. \end{lstlisting}
  9563. \end{minipage}
  9564. \\[2ex]\hline
  9565. \begin{minipage}{0.27\textwidth}
  9566. \begin{lstlisting}
  9567. (+ |$e_1$| |$e_2$|)
  9568. \end{lstlisting}
  9569. \end{minipage}
  9570. &
  9571. $\Rightarrow$
  9572. &
  9573. \begin{minipage}{0.6\textwidth}
  9574. \begin{lstlisting}
  9575. (inject
  9576. (+ (project |$e'_1$| Integer)
  9577. (project |$e'_2$| Integer))
  9578. Integer)
  9579. \end{lstlisting}
  9580. \end{minipage}
  9581. \\[2ex]\hline
  9582. \begin{minipage}{0.27\textwidth}
  9583. \begin{lstlisting}
  9584. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9585. \end{lstlisting}
  9586. \end{minipage}
  9587. &
  9588. $\Rightarrow$
  9589. &
  9590. \begin{minipage}{0.6\textwidth}
  9591. \begin{lstlisting}
  9592. (inject
  9593. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9594. (Any|$\ldots$|Any -> Any))
  9595. \end{lstlisting}
  9596. \end{minipage}
  9597. \\[2ex]\hline
  9598. \begin{minipage}{0.27\textwidth}
  9599. \begin{lstlisting}
  9600. (|$e_0$| |$e_1 \ldots e_n$|)
  9601. \end{lstlisting}
  9602. \end{minipage}
  9603. &
  9604. $\Rightarrow$
  9605. &
  9606. \begin{minipage}{0.6\textwidth}
  9607. \begin{lstlisting}
  9608. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9609. \end{lstlisting}
  9610. \end{minipage}
  9611. \\[2ex]\hline
  9612. \begin{minipage}{0.27\textwidth}
  9613. \begin{lstlisting}
  9614. (vector-ref |$e_1$| |$e_2$|)
  9615. \end{lstlisting}
  9616. \end{minipage}
  9617. &
  9618. $\Rightarrow$
  9619. &
  9620. \begin{minipage}{0.6\textwidth}
  9621. \begin{lstlisting}
  9622. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  9623. (let ([tmp2 (project |$e'_2$| Integer)])
  9624. (vector-ref tmp1 tmp2)))
  9625. \end{lstlisting}
  9626. \end{minipage}
  9627. \\[2ex]\hline
  9628. \begin{minipage}{0.27\textwidth}
  9629. \begin{lstlisting}
  9630. (if |$e_1$| |$e_2$| |$e_3$|)
  9631. \end{lstlisting}
  9632. \end{minipage}
  9633. &
  9634. $\Rightarrow$
  9635. &
  9636. \begin{minipage}{0.6\textwidth}
  9637. \begin{lstlisting}
  9638. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9639. \end{lstlisting}
  9640. \end{minipage}
  9641. \\[2ex]\hline
  9642. \begin{minipage}{0.27\textwidth}
  9643. \begin{lstlisting}
  9644. (eq? |$e_1$| |$e_2$|)
  9645. \end{lstlisting}
  9646. \end{minipage}
  9647. &
  9648. $\Rightarrow$
  9649. &
  9650. \begin{minipage}{0.6\textwidth}
  9651. \begin{lstlisting}
  9652. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9653. \end{lstlisting}
  9654. \end{minipage}
  9655. \\[2ex]\hline
  9656. \end{tabular}
  9657. \caption{Compiling $R_7$ to $R_6$.}
  9658. \label{fig:compile-r7-r6}
  9659. \end{figure}
  9660. \begin{exercise}\normalfont
  9661. Expand your compiler to handle $R_7$ as outlined in this chapter.
  9662. Create tests for $R_7$ by adapting ten of your previous test programs
  9663. by removing type annotations. Add 5 more tests programs that
  9664. specifically rely on the language being dynamically typed. That is,
  9665. they should not be legal programs in a statically typed language, but
  9666. nevertheless, they should be valid $R_7$ programs that run to
  9667. completion without error.
  9668. \end{exercise}
  9669. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9670. \chapter{Gradual Typing}
  9671. \label{ch:gradual-typing}
  9672. \index{gradual typing}
  9673. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  9674. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9675. \chapter{Parametric Polymorphism}
  9676. \label{ch:parametric-polymorphism}
  9677. \index{parametric polymorphism}
  9678. \index{generics}
  9679. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  9680. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  9681. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9682. %% \chapter{High-level Optimization}
  9683. %% \label{ch:high-level-optimization}
  9684. %% This chapter will present a procedure inlining pass based on the
  9685. %% algorithm of \citet{Waddell:1997fk}.
  9686. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9687. \chapter{Appendix}
  9688. \section{Interpreters}
  9689. \label{appendix:interp}
  9690. \index{interpreter}
  9691. We provide interpreters for each of the source languages $R_0$, $R_1$,
  9692. $\ldots$ in the files \code{interp-R0.rkt}, \code{interp-R1.rkt}, etc.
  9693. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  9694. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  9695. $C_2$, $C_3$, pseudo-x86, and x86 are in the \key{interp.rkt} file.
  9696. \section{Utility Functions}
  9697. \label{appendix:utilities}
  9698. The utility functions described in this section are in the
  9699. \key{utilities.rkt} file of the support code.
  9700. \paragraph{\code{interp-tests}}
  9701. The \key{interp-tests} function runs the compiler passes and the
  9702. interpreters on each of the specified tests to check whether each pass
  9703. is correct. The \key{interp-tests} function has the following
  9704. parameters:
  9705. \begin{description}
  9706. \item[name (a string)] a name to identify the compiler,
  9707. \item[typechecker] a function of exactly one argument that either
  9708. raises an error using the \code{error} function when it encounters a
  9709. type error, or returns \code{\#f} when it encounters a type
  9710. error. If there is no type error, the type checker returns the
  9711. program.
  9712. \item[passes] a list with one entry per pass. An entry is a list with
  9713. four things:
  9714. \begin{enumerate}
  9715. \item a string giving the name of the pass,
  9716. \item the function that implements the pass (a translator from AST
  9717. to AST),
  9718. \item a function that implements the interpreter (a function from
  9719. AST to result value) for the output language,
  9720. \item and a type checker for the output language. Type checkers for
  9721. the $R$ and $C$ languages are provided in the support code. For
  9722. example, the type checkers for $R_1$ and $C_0$ are in
  9723. \code{type-check-R1.rkt}. The type checker entry is optional. The
  9724. support code does not provide type checkers for the x86 languages.
  9725. \end{enumerate}
  9726. \item[source-interp] an interpreter for the source language. The
  9727. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  9728. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  9729. \item[tests] a list of test numbers that specifies which tests to
  9730. run. (see below)
  9731. \end{description}
  9732. %
  9733. The \key{interp-tests} function assumes that the subdirectory
  9734. \key{tests} has a collection of Racket programs whose names all start
  9735. with the family name, followed by an underscore and then the test
  9736. number, ending with the file extension \key{.rkt}. Also, for each test
  9737. program that calls \code{read} one or more times, there is a file with
  9738. the same name except that the file extension is \key{.in} that
  9739. provides the input for the Racket program. If the test program is
  9740. expected to fail type checking, then there should be an empty file of
  9741. the same name but with extension \key{.tyerr}.
  9742. \paragraph{\code{compiler-tests}}
  9743. runs the compiler passes to generate x86 (a \key{.s} file) and then
  9744. runs the GNU C compiler (gcc) to generate machine code. It runs the
  9745. machine code and checks that the output is $42$. The parameters to the
  9746. \code{compiler-tests} function are similar to those of the
  9747. \code{interp-tests} function, and consist of
  9748. \begin{itemize}
  9749. \item a compiler name (a string),
  9750. \item a type checker,
  9751. \item description of the passes,
  9752. \item name of a test-family, and
  9753. \item a list of test numbers.
  9754. \end{itemize}
  9755. \paragraph{\code{compile-file}}
  9756. takes a description of the compiler passes (see the comment for
  9757. \key{interp-tests}) and returns a function that, given a program file
  9758. name (a string ending in \key{.rkt}), applies all of the passes and
  9759. writes the output to a file whose name is the same as the program file
  9760. name but with \key{.rkt} replaced with \key{.s}.
  9761. \paragraph{\code{read-program}}
  9762. takes a file path and parses that file (it must be a Racket program)
  9763. into an abstract syntax tree.
  9764. \paragraph{\code{parse-program}}
  9765. takes an S-expression representation of an abstract syntax tree and converts it into
  9766. the struct-based representation.
  9767. \paragraph{\code{assert}}
  9768. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  9769. and displays the message \key{msg} if the Boolean \key{bool} is false.
  9770. \paragraph{\code{lookup}}
  9771. % remove discussion of lookup? -Jeremy
  9772. takes a key and an alist, and returns the first value that is
  9773. associated with the given key, if there is one. If not, an error is
  9774. triggered. The alist may contain both immutable pairs (built with
  9775. \key{cons}) and mutable pairs (built with \key{mcons}).
  9776. %The \key{map2} function ...
  9777. \section{x86 Instruction Set Quick-Reference}
  9778. \label{sec:x86-quick-reference}
  9779. \index{x86}
  9780. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  9781. do. We write $A \to B$ to mean that the value of $A$ is written into
  9782. location $B$. Address offsets are given in bytes. The instruction
  9783. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  9784. registers (such as \code{\%rax}), or memory references (such as
  9785. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  9786. reference per instruction. Other operands must be immediates or
  9787. registers.
  9788. \begin{table}[tbp]
  9789. \centering
  9790. \begin{tabular}{l|l}
  9791. \textbf{Instruction} & \textbf{Operation} \\ \hline
  9792. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  9793. \texttt{negq} $A$ & $- A \to A$ \\
  9794. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  9795. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  9796. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  9797. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  9798. \texttt{retq} & Pops the return address and jumps to it \\
  9799. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  9800. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  9801. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  9802. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  9803. be an immediate) \\
  9804. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  9805. matches the condition code of the instruction, otherwise go to the
  9806. next instructions. The condition codes are \key{e} for ``equal'',
  9807. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  9808. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  9809. \texttt{jl} $L$ & \\
  9810. \texttt{jle} $L$ & \\
  9811. \texttt{jg} $L$ & \\
  9812. \texttt{jge} $L$ & \\
  9813. \texttt{jmp} $L$ & Jump to label $L$ \\
  9814. \texttt{movq} $A$, $B$ & $A \to B$ \\
  9815. \texttt{movzbq} $A$, $B$ &
  9816. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  9817. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  9818. and the extra bytes of $B$ are set to zero.} \\
  9819. & \\
  9820. & \\
  9821. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  9822. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  9823. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  9824. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  9825. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  9826. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  9827. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  9828. description of the condition codes. $A$ must be a single byte register
  9829. (e.g., \texttt{al} or \texttt{cl}).} \\
  9830. \texttt{setl} $A$ & \\
  9831. \texttt{setle} $A$ & \\
  9832. \texttt{setg} $A$ & \\
  9833. \texttt{setge} $A$ &
  9834. \end{tabular}
  9835. \vspace{5pt}
  9836. \caption{Quick-reference for the x86 instructions used in this book.}
  9837. \label{tab:x86-instr}
  9838. \end{table}
  9839. \cleardoublepage
  9840. \addcontentsline{toc}{chapter}{Index}
  9841. \printindex
  9842. \cleardoublepage
  9843. \bibliographystyle{plainnat}
  9844. \bibliography{all}
  9845. \addcontentsline{toc}{chapter}{Bibliography}
  9846. \end{document}
  9847. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  9848. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  9849. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  9850. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  9851. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  9852. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  9853. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  9854. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  9855. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  9856. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  9857. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  9858. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  9859. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  9860. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  9861. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  9862. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  9863. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  9864. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  9865. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  9866. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  9867. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  9868. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  9869. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  9870. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  9871. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  9872. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  9873. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  9874. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  9875. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  9876. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  9877. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  9878. % LocalWords: struct symtab Friedman's MacOS Nystrom alist sam kate
  9879. % LocalWords: alists arity github unordered pqueue exprs ret param
  9880. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  9881. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  9882. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  9883. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  9884. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  9885. % LocalWords: ValueOf typechecker