book.tex 249 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. \usepackage{color}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. %% For pictures
  23. \usepackage{tikz}
  24. \usetikzlibrary{arrows.meta}
  25. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  26. % Computer Modern is already the default. -Jeremy
  27. %\renewcommand{\ttdefault}{cmtt}
  28. % Peanut gallery comments:
  29. \definecolor{comment-red}{rgb}{0.8,0,0}
  30. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  31. \lstset{%
  32. language=Lisp,
  33. basicstyle=\ttfamily\small,
  34. escapechar=|,
  35. columns=flexible,
  36. moredelim=[is][\color{red}]{~}{~}
  37. }
  38. \newtheorem{theorem}{Theorem}
  39. \newtheorem{lemma}[theorem]{Lemma}
  40. \newtheorem{corollary}[theorem]{Corollary}
  41. \newtheorem{proposition}[theorem]{Proposition}
  42. \newtheorem{constraint}[theorem]{Constraint}
  43. \newtheorem{definition}[theorem]{Definition}
  44. \newtheorem{exercise}[theorem]{Exercise}
  45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  46. % 'dedication' environment: To add a dedication paragraph at the start of book %
  47. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  48. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  49. \newenvironment{dedication}
  50. {
  51. \cleardoublepage
  52. \thispagestyle{empty}
  53. \vspace*{\stretch{1}}
  54. \hfill\begin{minipage}[t]{0.66\textwidth}
  55. \raggedright
  56. }
  57. {
  58. \end{minipage}
  59. \vspace*{\stretch{3}}
  60. \clearpage
  61. }
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63. % Chapter quote at the start of chapter %
  64. % Source: http://tex.stackexchange.com/a/53380 %
  65. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  66. \makeatletter
  67. \renewcommand{\@chapapp}{}% Not necessary...
  68. \newenvironment{chapquote}[2][2em]
  69. {\setlength{\@tempdima}{#1}%
  70. \def\chapquote@author{#2}%
  71. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  72. \itshape}
  73. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  74. \makeatother
  75. \input{defs}
  76. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  77. \title{\Huge \textbf{Essentials of Compilation} \\
  78. \huge An Incremental Approach}
  79. \author{\textsc{Jeremy G. Siek} \\
  80. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  81. Indiana University \\
  82. \\
  83. with contributions from: \\
  84. Carl Factora \\
  85. Andre Kuhlenschmidt \\
  86. Michael M. Vitousek \\
  87. Cameron Swords
  88. }
  89. \begin{document}
  90. \frontmatter
  91. \maketitle
  92. \begin{dedication}
  93. This book is dedicated to the programming language wonks at Indiana
  94. University.
  95. \end{dedication}
  96. \tableofcontents
  97. \listoffigures
  98. %\listoftables
  99. \mainmatter
  100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  101. \chapter*{Preface}
  102. The tradition of compiler writing at Indiana University goes back to
  103. programming language research and courses taught by Daniel Friedman in
  104. the 1970's and 1980's. Dan had conducted research on lazy evaluation
  105. in the context of Lisp~\citep{McCarthy:1960dz} and then studied
  106. continuations and macros in the context of the
  107. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of students of
  108. those courses, Kent Dybvig, went on to build Chez
  109. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  110. compiler for Scheme. After completing his Ph.D. at the University of
  111. North Carolina, Kent returned to teach at Indiana University.
  112. Throughout the 1990's and 2000's, Kent continued development of
  113. Chez Scheme and taught the compiler course.
  114. The compiler course evolved to incorporate novel pedagogical ideas
  115. while also including elements of effective real-world compilers. One
  116. of Dan's ideas was to split the compiler into many small passes over
  117. the input program and subsequent intermediate representations, so that
  118. the code for each pass would be easy to understood in isolation. (In
  119. contrast, most compilers of the time were organized into only a few
  120. monolithic passes for reasons of compile-time efficiency.) Kent and
  121. his students, Dipanwita Sarkar and Andrew Keep, developed
  122. infrastructure to support this approach and evolved the course, first
  123. to use micro-sized passes and then into even smaller nano
  124. passes~\citep{Sarkar:2004fk,Keep:2012aa}. I took this compiler course
  125. in the early 2000's, as part of my Ph.D. studies at Indiana
  126. University. Needless to say, I enjoyed the course immensely.
  127. \rn{I think that 1999 when I took it was the first micropass semester, and that
  128. that approach preceded the infrastructure work by Dipa.}
  129. One of my classmates, Abdulaziz Ghuloum, observed that the
  130. front-to-back organization of the course made it difficult for
  131. students to understand the rationale for the compiler
  132. design. Abdulaziz proposed an incremental approach in which the
  133. students build the compiler in stages; they start by implementing a
  134. complete compiler for a very small subset of the input language, then
  135. in each subsequent stage they add a feature to the input language and
  136. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  137. In this way, the students see how the language features motivate
  138. aspects of the compiler design.
  139. After graduating from Indiana University in 2005, I went on to teach
  140. at the University of Colorado. I adapted the nano pass and incremental
  141. approaches to compiling a subset of the Python
  142. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  143. on the surface but there is a large overlap in the compiler techniques
  144. required for the two languages. Thus, I was able to teach much of the
  145. same content from the Indiana compiler course. I very much enjoyed
  146. teaching the course organized in this way, and even better, many of
  147. the students learned a lot and got excited about compilers.
  148. It is now 2016 and I too have returned to teach at Indiana University.
  149. In my absence the compiler course had switched from the front-to-back
  150. organization to a back-to-front organization. Seeing how well the
  151. incremental approach worked at Colorado, I started porting and
  152. adapting the structure of the Colorado course back into the land of
  153. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  154. the course is now about compiling a subset of Racket to the x86
  155. assembly language and the compiler is implemented in
  156. Racket~\citep{plt-tr}.
  157. This is the textbook for the incremental version of the compiler
  158. course at Indiana University (Spring 2016) and it is the first
  159. textbook for an Indiana compiler course. With this book I hope to
  160. make the Indiana compiler course available to people that have not had
  161. the chance to study in Bloomington in person. Many of the compiler
  162. design decisions in this book are drawn from the assignment
  163. descriptions of \cite{Dybvig:2010aa}. I have captured what I think are
  164. the most important topics from \cite{Dybvig:2010aa} but I have omitted
  165. topics that I think are less interesting conceptually and I have made
  166. simplifications to reduce complexity. In this way, this book leans
  167. more towards pedagogy than towards the absolute efficiency of the
  168. generated code. Also, the book differs in places where I saw the
  169. opportunity to make the topics more fun, such as in relating register
  170. allocation to Sudoku (Chapter~\ref{ch:register-allocation}).
  171. \section*{Prerequisites}
  172. The material in this book is challenging but rewarding. It is meant to
  173. prepare students for a lifelong career in programming languages. I do
  174. not recommend this book for students who want to dabble in programming
  175. languages. Because the book uses the Racket language both for the
  176. implementation of the compiler and for the language that is compiled,
  177. a student should be proficient with Racket (or Scheme) prior to
  178. reading this book. There are many other excellent resources for
  179. learning Scheme and
  180. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  181. is helpful but not necessary for the student to have prior exposure to
  182. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  183. obtain from a computer systems
  184. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  185. parts of x86-64 assembly language that are needed.
  186. %\section*{Structure of book}
  187. % You might want to add short description about each chapter in this book.
  188. %\section*{About the companion website}
  189. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  190. %\begin{itemize}
  191. % \item A link to (freely downlodable) latest version of this document.
  192. % \item Link to download LaTeX source for this document.
  193. % \item Miscellaneous material (e.g. suggested readings etc).
  194. %\end{itemize}
  195. \section*{Acknowledgments}
  196. Need to give thanks to
  197. \begin{itemize}
  198. \item Bor-Yuh Evan Chang
  199. \item Kent Dybvig
  200. \item Daniel P. Friedman
  201. \item Ronald Garcia
  202. \item Abdulaziz Ghuloum
  203. \item Ryan Newton
  204. \item Dipanwita Sarkar
  205. \item Andrew Keep
  206. \item Oscar Waddell
  207. \end{itemize}
  208. \mbox{}\\
  209. \noindent Jeremy G. Siek \\
  210. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  211. \noindent Spring 2016
  212. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  213. \chapter{Preliminaries}
  214. \label{ch:trees-recur}
  215. In this chapter, we review the basic tools that are needed for
  216. implementing a compiler. We use abstract syntax trees (ASTs) in the
  217. form of S-expressions to represent programs (Section~\ref{sec:ast})
  218. and pattern matching to inspect individual nodes in an AST
  219. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  220. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  221. \section{Abstract Syntax Trees}
  222. \label{sec:ast}
  223. The primary data structure that is commonly used for representing
  224. programs is the \emph{abstract syntax tree} (AST). When considering
  225. some part of a program, a compiler needs to ask what kind of part it
  226. is and what sub-parts it has. For example, the program on the left is
  227. represented by the AST on the right.
  228. \begin{center}
  229. \begin{minipage}{0.4\textwidth}
  230. \begin{lstlisting}
  231. (+ (read) (- 8))
  232. \end{lstlisting}
  233. \end{minipage}
  234. \begin{minipage}{0.4\textwidth}
  235. \begin{equation}
  236. \begin{tikzpicture}
  237. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  238. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  239. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  240. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  241. \draw[->] (plus) to (read);
  242. \draw[->] (plus) to (minus);
  243. \draw[->] (minus) to (8);
  244. \end{tikzpicture}
  245. \label{eq:arith-prog}
  246. \end{equation}
  247. \end{minipage}
  248. \end{center}
  249. We shall use the standard terminology for trees: each circle above is
  250. called a \emph{node}. The arrows connect a node to its \emph{children}
  251. (which are also nodes). The top-most node is the \emph{root}. Every
  252. node except for the root has a \emph{parent} (the node it is the child
  253. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  254. it is an \emph{internal} node.
  255. When deciding how to compile the above program, we need to know that
  256. the root node operation is addition and that it has two children:
  257. \texttt{read} and a negation. The abstract syntax tree data structure
  258. directly supports these queries and hence is a good choice. In this
  259. book, we will often write down the textual representation of a program
  260. even when we really have in mind the AST because the textual
  261. representation is more concise. We recommend that, in your mind, you
  262. always interpret programs as abstract syntax trees.
  263. \section{Grammars}
  264. \label{sec:grammar}
  265. A programming language can be thought of as a \emph{set} of programs.
  266. The set is typically infinite (one can always create larger and larger
  267. programs), so one cannot simply describe a language by listing all of
  268. the programs in the language. Instead we write down a set of rules, a
  269. \emph{grammar}, for building programs. We shall write our rules in a
  270. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  271. As an example, we describe a small language, named $R_0$, of
  272. integers and arithmetic operations. The first rule says that any
  273. integer is an expression, $\Exp$, in the language:
  274. \begin{equation}
  275. \Exp ::= \Int \label{eq:arith-int}
  276. \end{equation}
  277. Each rule has a left-hand-side and a right-hand-side. The way to read
  278. a rule is that if you have all the program parts on the
  279. right-hand-side, then you can create an AST node and categorize it
  280. according to the left-hand-side. (We do not define $\Int$ because the
  281. reader already knows what an integer is.) We make the simplifying
  282. design decision that all of the languages in this book only handle
  283. machine-representable integers (those representable with 64-bits,
  284. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  285. \texttt{fixnum} datatype in Racket. A name such as $\Exp$ that is
  286. defined by the grammar rules is a \emph{non-terminal}.
  287. The second grammar rule is the \texttt{read} operation that receives
  288. an input integer from the user of the program.
  289. \begin{equation}
  290. \Exp ::= (\key{read}) \label{eq:arith-read}
  291. \end{equation}
  292. The third rule says that, given an $\Exp$ node, you can build another
  293. $\Exp$ node by negating it.
  294. \begin{equation}
  295. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  296. \end{equation}
  297. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  298. and must literally appear in the program for the rule to be
  299. applicable.
  300. We can apply the rules to build ASTs in the $R_0$
  301. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  302. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  303. an $\Exp$.
  304. \begin{center}
  305. \begin{minipage}{0.25\textwidth}
  306. \begin{lstlisting}
  307. (- 8)
  308. \end{lstlisting}
  309. \end{minipage}
  310. \begin{minipage}{0.25\textwidth}
  311. \begin{equation}
  312. \begin{tikzpicture}
  313. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  314. \node[draw, circle] (8) at (0, -1.2) {$8$};
  315. \draw[->] (minus) to (8);
  316. \end{tikzpicture}
  317. \label{eq:arith-neg8}
  318. \end{equation}
  319. \end{minipage}
  320. \end{center}
  321. The following grammar rule defines addition expressions:
  322. \begin{equation}
  323. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  324. \end{equation}
  325. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  326. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  327. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  328. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  329. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  330. If you have an AST for which the above rules do not apply, then the
  331. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  332. not in $R_0$ because there are no rules for \key{+} with only one
  333. argument, nor for \key{-} with two arguments. Whenever we define a
  334. language with a grammar, we implicitly mean for the language to be the
  335. smallest set of programs that are justified by the rules. That is, the
  336. language only includes those programs that the rules allow.
  337. The last grammar for $R_0$ states that there is a \key{program} node
  338. to mark the top of the whole program:
  339. \[
  340. R_0 ::= (\key{program} \; \Exp)
  341. \]
  342. The \code{read-program} function provided in \code{utilities.rkt}
  343. reads programs in from a file (the sequence of characters in the
  344. concrete syntax of Racket) and parses them into the abstract syntax
  345. tree. The concrete syntax does not include a \key{program} form; that
  346. is added by the \code{read-program} function as it creates the
  347. AST. See the description of \code{read-program} in
  348. Appendix~\ref{appendix:utilities} for more details.
  349. It is common to have many rules with the same left-hand side, such as
  350. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  351. for gathering several rules, as shown in
  352. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  353. called an {\em alternative}.
  354. \begin{figure}[tp]
  355. \fbox{
  356. \begin{minipage}{0.96\textwidth}
  357. \[
  358. \begin{array}{rcl}
  359. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  360. (\key{+} \; \Exp \; \Exp) \\
  361. R_0 &::=& (\key{program} \; \Exp)
  362. \end{array}
  363. \]
  364. \end{minipage}
  365. }
  366. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  367. \label{fig:r0-syntax}
  368. \end{figure}
  369. \section{S-Expressions}
  370. \label{sec:s-expr}
  371. Racket, as a descendant of Lisp, has
  372. convenient support for creating and manipulating abstract syntax trees
  373. with its \emph{symbolic expression} feature, or S-expression for
  374. short. We can create an S-expression simply by writing a backquote
  375. followed by the textual representation of the AST. (Technically
  376. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  377. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  378. by the following Racket expression:
  379. \begin{center}
  380. \texttt{`(+ (read) (- 8))}
  381. \end{center}
  382. To build larger S-expressions one often needs to splice together
  383. several smaller S-expressions. Racket provides the comma operator to
  384. splice an S-expression into a larger one. For example, instead of
  385. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  386. we could have first created an S-expression for AST
  387. \eqref{eq:arith-neg8} and then spliced that into the addition
  388. S-expression.
  389. \begin{lstlisting}
  390. (define ast1.4 `(- 8))
  391. (define ast1.1 `(+ (read) ,ast1.4))
  392. \end{lstlisting}
  393. In general, the Racket expression that follows the comma (splice)
  394. can be any expression that computes an S-expression.
  395. \section{Pattern Matching}
  396. \label{sec:pattern-matching}
  397. As mentioned above, one of the operations that a compiler needs to
  398. perform on an AST is to access the children of a node. Racket
  399. provides the \texttt{match} form to access the parts of an
  400. S-expression. Consider the following example and the output on the
  401. right.
  402. \begin{center}
  403. \begin{minipage}{0.5\textwidth}
  404. \begin{lstlisting}
  405. (match ast1.1
  406. [`(,op ,child1 ,child2)
  407. (print op) (newline)
  408. (print child1) (newline)
  409. (print child2)])
  410. \end{lstlisting}
  411. \end{minipage}
  412. \vrule
  413. \begin{minipage}{0.25\textwidth}
  414. \begin{lstlisting}
  415. '+
  416. '(read)
  417. '(- 8)
  418. \end{lstlisting}
  419. \end{minipage}
  420. \end{center}
  421. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  422. parts to the three variables \texttt{op}, \texttt{child1}, and
  423. \texttt{child2}. In general, a match clause consists of a
  424. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  425. that may contain pattern-variables (preceded by a comma). The body
  426. may contain any Racket code.
  427. A \texttt{match} form may contain several clauses, as in the following
  428. function \texttt{leaf?} that recognizes when an $R_0$ node is
  429. a leaf. The \texttt{match} proceeds through the clauses in order,
  430. checking whether the pattern can match the input S-expression. The
  431. body of the first clause that matches is executed. The output of
  432. \texttt{leaf?} for several S-expressions is shown on the right. In the
  433. below \texttt{match}, we see another form of pattern: the \texttt{(?
  434. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  435. S-expression to see if it is a machine-representable integer.
  436. \begin{center}
  437. \begin{minipage}{0.5\textwidth}
  438. \begin{lstlisting}
  439. (define (leaf? arith)
  440. (match arith
  441. [(? fixnum?) #t]
  442. [`(read) #t]
  443. [`(- ,c1) #f]
  444. [`(+ ,c1 ,c2) #f]))
  445. (leaf? `(read))
  446. (leaf? `(- 8))
  447. (leaf? `(+ (read) (- 8)))
  448. \end{lstlisting}
  449. \end{minipage}
  450. \vrule
  451. \begin{minipage}{0.25\textwidth}
  452. \begin{lstlisting}
  453. #t
  454. #f
  455. #f
  456. \end{lstlisting}
  457. \end{minipage}
  458. \end{center}
  459. \section{Recursion}
  460. \label{sec:recursion}
  461. Programs are inherently recursive in that an $R_0$ AST is made
  462. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  463. entire program is with a recursive function. As a first example of
  464. such a function, we define \texttt{R0?} below, which takes an
  465. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  466. sexp} is in {\tt arith}. Note that each match clause corresponds to
  467. one grammar rule for $R_0$ and the body of each clause makes a
  468. recursive call for each child node. This pattern of recursive function
  469. is so common that it has a name, \emph{structural recursion}. In
  470. general, when a recursive function is defined using a sequence of
  471. match clauses that correspond to a grammar, and each clause body makes
  472. a recursive call on each child node, then we say the function is
  473. defined by structural recursion.
  474. \begin{center}
  475. \begin{minipage}{0.7\textwidth}
  476. \begin{lstlisting}
  477. (define (R0? sexp)
  478. (match sexp
  479. [(? fixnum?) #t]
  480. [`(read) #t]
  481. [`(- ,e) (R0? e)]
  482. [`(+ ,e1 ,e2)
  483. (and (R0? e1) (R0? e2))]
  484. [`(program ,e) (R0? e)]
  485. [else #f]))
  486. (R0? `(+ (read) (- 8)))
  487. (R0? `(- (read) (+ 8)))
  488. \end{lstlisting}
  489. \end{minipage}
  490. \vrule
  491. \begin{minipage}{0.25\textwidth}
  492. \begin{lstlisting}
  493. #t
  494. #f
  495. \end{lstlisting}
  496. \end{minipage}
  497. \end{center}
  498. \section{Interpreters}
  499. \label{sec:interp-R0}
  500. The meaning, or semantics, of a program is typically defined in the
  501. specification of the language. For example, the Scheme language is
  502. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  503. defined in its reference manual~\citep{plt-tr}. In this book we use an
  504. interpreter to define the meaning of each language that we consider,
  505. following Reynold's advice in this
  506. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  507. an interpreter for the $R_0$ language, which will also serve as a
  508. second example of structural recursion. The \texttt{interp-R0}
  509. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  510. function is a match on the input expression \texttt{e} and there is
  511. one clause per grammar rule for $R_0$. The clauses for internal AST
  512. nodes make recursive calls to \texttt{interp-R0} on each child
  513. node. Here we make use of the \key{app} feature of Racket's
  514. \key{match} to concisely apply a function and bind the result. For
  515. example, in the case for negation, we use \key{app} to recursively
  516. apply \texttt{interp-R0} to the child node and bind the result value
  517. to variable \texttt{v}.
  518. \begin{figure}[tbp]
  519. \begin{lstlisting}
  520. (define (interp-R0 e)
  521. (match e
  522. [(? fixnum?) e]
  523. [`(read)
  524. (let ([r (read)])
  525. (cond [(fixnum? r) r]
  526. [else (error 'interp-R0 "input not an integer" r)]))]
  527. [`(- ,(app interp-R0 v))
  528. (fx- 0 v)]
  529. [`(+ ,(app interp-R0 v1) ,(app interp-R0 v2))
  530. (fx+ v1 v2)]
  531. [`(program ,(app interp-R0 v)) v]
  532. ))
  533. \end{lstlisting}
  534. \caption{Interpreter for the $R_0$ language.}
  535. \label{fig:interp-R0}
  536. \end{figure}
  537. Let us consider the result of interpreting some example $R_0$
  538. programs. The following program simply adds two integers.
  539. \begin{lstlisting}
  540. (+ 10 32)
  541. \end{lstlisting}
  542. The result is \key{42}, as you might have expected.
  543. %
  544. The next example demonstrates that expressions may be nested within
  545. each other, in this case nesting several additions and negations.
  546. \begin{lstlisting}
  547. (+ 10 (- (+ 12 20)))
  548. \end{lstlisting}
  549. What is the result of the above program?
  550. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  551. \texttt{50}
  552. \begin{lstlisting}
  553. (interp-R0 ast1.1)
  554. \end{lstlisting}
  555. we get the answer to life, the universe, and everything:
  556. \begin{lstlisting}
  557. 42
  558. \end{lstlisting}
  559. Moving on, the \key{read} operation prompts the user of the program
  560. for an integer. Given an input of \key{10}, the following program
  561. produces \key{42}.
  562. \begin{lstlisting}
  563. (+ (read) 32)
  564. \end{lstlisting}
  565. We include the \key{read} operation in $R_1$ so that a compiler for
  566. $R_1$ cannot be implemented simply by running the interpreter at
  567. compilation time to obtain the output and then generating the trivial
  568. code to return the output. (A clever student at Colorado did this the
  569. first time I taught the course.)
  570. The job of a compiler is to translate a program in one language into a
  571. program in another language so that the output program behaves the
  572. same way as the input program. This idea is depicted in the following
  573. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  574. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  575. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  576. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  577. and $P_2$ on their respective interpreters with input $i$ should yield
  578. the same output $o$.
  579. \begin{equation} \label{eq:compile-correct}
  580. \begin{tikzpicture}[baseline=(current bounding box.center)]
  581. \node (p1) at (0, 0) {$P_1$};
  582. \node (p2) at (3, 0) {$P_2$};
  583. \node (o) at (3, -2.5) {$o$};
  584. \path[->] (p1) edge [above] node {compile} (p2);
  585. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  586. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  587. \end{tikzpicture}
  588. \end{equation}
  589. In the next section we see our first example of a compiler, which is
  590. another example of structural recursion.
  591. \section{Example Compiler: a Partial Evaluator}
  592. \label{sec:partial-evaluation}
  593. In this section we consider a compiler that translates $R_0$
  594. programs into $R_0$ programs that are more efficient, that is,
  595. this compiler is an optimizer. Our optimizer will accomplish this by
  596. trying to eagerly compute the parts of the program that do not depend
  597. on any inputs. For example, given the following program
  598. \begin{lstlisting}
  599. (+ (read) (- (+ 5 3)))
  600. \end{lstlisting}
  601. our compiler will translate it into the program
  602. \begin{lstlisting}
  603. (+ (read) -8)
  604. \end{lstlisting}
  605. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  606. evaluator for the $R_0$ language. The output of the partial evaluator
  607. is an $R_0$ program, which we build up using a combination of
  608. quasiquotes and commas. (Though no quasiquote is necessary for
  609. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  610. recursion is captured in the main \texttt{pe-arith} function whereas
  611. the code for partially evaluating negation and addition is factored
  612. into two separate helper functions: \texttt{pe-neg} and
  613. \texttt{pe-add}. The input to these helper functions is the output of
  614. partially evaluating the children nodes.
  615. \begin{figure}[tbp]
  616. \begin{lstlisting}
  617. (define (pe-neg r)
  618. (cond [(fixnum? r) (fx- 0 r)]
  619. [else `(- ,r)]))
  620. (define (pe-add r1 r2)
  621. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  622. [else `(+ ,r1 ,r2)]))
  623. (define (pe-arith e)
  624. (match e
  625. [(? fixnum?) e]
  626. [`(read) `(read)]
  627. [`(- ,(app pe-arith r1))
  628. (pe-neg r1)]
  629. [`(+ ,(app pe-arith r1) ,(app pe-arith r2))
  630. (pe-add r1 r2)]))
  631. \end{lstlisting}
  632. \caption{A partial evaluator for the $R_0$ language.}
  633. \label{fig:pe-arith}
  634. \end{figure}
  635. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  636. idea of checking whether the inputs are integers and if they are, to
  637. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  638. create an AST node for the appropriate operation (either negation or
  639. addition) and use comma to splice in the child nodes.
  640. To gain some confidence that the partial evaluator is correct, we can
  641. test whether it produces programs that get the same result as the
  642. input program. That is, we can test whether it satisfies Diagram
  643. \eqref{eq:compile-correct}. The following code runs the partial
  644. evaluator on several examples and tests the output program. The
  645. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  646. \begin{lstlisting}
  647. (define (test-pe p)
  648. (assert "testing pe-arith"
  649. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  650. (test-pe `(+ (read) (- (+ 5 3))))
  651. (test-pe `(+ 1 (+ (read) 1)))
  652. (test-pe `(- (+ (read) (- 5))))
  653. \end{lstlisting}
  654. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  655. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  656. \begin{exercise}
  657. \normalfont % I don't like the italics for exercises. -Jeremy
  658. We challenge the reader to improve on the simple partial evaluator in
  659. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  660. \texttt{pe-add} helper functions with functions that know more about
  661. arithmetic. For example, your partial evaluator should translate
  662. \begin{lstlisting}
  663. (+ 1 (+ (read) 1))
  664. \end{lstlisting}
  665. into
  666. \begin{lstlisting}
  667. (+ 2 (read))
  668. \end{lstlisting}
  669. To accomplish this, we recommend that your partial evaluator produce
  670. output that takes the form of the $\itm{residual}$ non-terminal in the
  671. following grammar.
  672. \[
  673. \begin{array}{lcl}
  674. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  675. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  676. \end{array}
  677. \]
  678. \end{exercise}
  679. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  680. \chapter{Compiling Integers and Variables}
  681. \label{ch:int-exp}
  682. This chapter concerns the challenge of compiling a subset of Racket,
  683. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}.
  684. (Henceforth we shall refer to x86-64 simply as x86). The chapter
  685. begins with a description of the $R_1$ language (Section~\ref{sec:s0})
  686. and then a description of x86 (Section~\ref{sec:x86}). The
  687. x86 assembly language is quite large, so we only discuss what is
  688. needed for compiling $R_1$. We introduce more of x86 in later
  689. chapters. Once we have introduced $R_1$ and x86, we reflect on
  690. their differences and come up with a plan breaking down the
  691. translation from $R_1$ to x86 into a handful of steps
  692. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  693. Chapter give detailed hints regarding each step
  694. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  695. to give enough hints that the well-prepared reader can implement a
  696. compiler from $R_1$ to x86 while at the same time leaving room for
  697. some fun and creativity.
  698. \section{The $R_1$ Language}
  699. \label{sec:s0}
  700. The $R_1$ language extends the $R_0$ language
  701. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  702. the $R_1$ language is defined by the grammar in
  703. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  704. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  705. a unary operator, and \key{+} is a binary operator. In addition to
  706. variable definitions, the $R_1$ language includes the \key{program}
  707. form to mark the top of the program, which is helpful in some of the
  708. compiler passes. The $R_1$ language is rich enough to exhibit several
  709. compilation techniques but simple enough so that the reader can
  710. implement a compiler for it in a week of part-time work. To give the
  711. reader a feeling for the scale of this first compiler, the instructor
  712. solution for the $R_1$ compiler consists of 6 recursive functions and
  713. a few small helper functions that together span 256 lines of code.
  714. \begin{figure}[btp]
  715. \centering
  716. \fbox{
  717. \begin{minipage}{0.96\textwidth}
  718. \[
  719. \begin{array}{rcl}
  720. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  721. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  722. R_1 &::=& (\key{program} \; \Exp)
  723. \end{array}
  724. \]
  725. \end{minipage}
  726. }
  727. \caption{The syntax of $R_1$, a language of integers and variables.}
  728. \label{fig:r1-syntax}
  729. \end{figure}
  730. The \key{let} construct defines a variable for use within its body
  731. and initializes the variable with the value of an expression. So the
  732. following program initializes \code{x} to \code{32} and then evaluates
  733. the body \code{(+ 10 x)}, producing \code{42}.
  734. \begin{lstlisting}
  735. (program
  736. (let ([x (+ 12 20)]) (+ 10 x)))
  737. \end{lstlisting}
  738. When there are multiple \key{let}'s for the same variable, the closest
  739. enclosing \key{let} is used. That is, variable definitions overshadow
  740. prior definitions. Consider the following program with two \key{let}'s
  741. that define variables named \code{x}. Can you figure out the result?
  742. \begin{lstlisting}
  743. (program
  744. (let ([x 32]) (+ (let ([x 10]) x) x)))
  745. \end{lstlisting}
  746. For the purposes of showing which variable uses correspond to which
  747. definitions, the following shows the \code{x}'s annotated with subscripts
  748. to distinguish them. Double check that your answer for the above is
  749. the same as your answer for this annotated version of the program.
  750. \begin{lstlisting}
  751. (program
  752. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  753. \end{lstlisting}
  754. The initializing expression is always evaluated before the body of the
  755. \key{let}, so in the following, the \key{read} for \code{x} is
  756. performed before the \key{read} for \code{y}. Given the input
  757. \code{52} then \code{10}, the following produces \code{42} (and not
  758. \code{-42}).
  759. \begin{lstlisting}
  760. (program
  761. (let ([x (read)]) (let ([y (read)]) (- x y))))
  762. \end{lstlisting}
  763. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  764. language. It extends the interpreter for $R_0$ with two new
  765. \key{match} clauses for variables and for \key{let}. For \key{let},
  766. we will need a way to communicate the initializing value of a variable
  767. to all the uses of a variable. To accomplish this, we maintain a
  768. mapping from variables to values, which is traditionally called an
  769. \emph{environment}. For simplicity, here we use an association list to
  770. represent the environment. The \code{interp-R1} function takes the
  771. current environment, \code{env}, as an extra parameter. When the
  772. interpreter encounters a variable, it finds the corresponding value
  773. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  774. When the interpreter encounters a \key{let}, it evaluates the
  775. initializing expression, extends the environment with the result bound
  776. to the variable, then evaluates the body of the \key{let}.
  777. \begin{figure}[tbp]
  778. \begin{lstlisting}
  779. (define (interp-R1 env)
  780. (lambda (e)
  781. (define recur (interp-R1 env))
  782. (match e
  783. [(? symbol?) (lookup e env)]
  784. [`(let ([,x ,(app recur v)]) ,body)
  785. (define new-env (cons (cons x v) env))
  786. ((interp-R1 new-env) body)]
  787. [(? fixnum?) e]
  788. [`(read)
  789. (define r (read))
  790. (cond [(fixnum? r) r]
  791. [else (error 'interp-R1 "expected an integer" r)])]
  792. [`(- ,(app recur v))
  793. (fx- 0 v)]
  794. [`(+ ,(app recur v1) ,(app recur v2))
  795. (fx+ v1 v2)]
  796. [`(program ,e) ((interp-R1 '()) e)]
  797. )))
  798. \end{lstlisting}
  799. \caption{Interpreter for the $R_1$ language.}
  800. \label{fig:interp-R1}
  801. \end{figure}
  802. The goal for this chapter is to implement a compiler that translates
  803. any program $P_1$ in the $R_1$ language into an x86 assembly
  804. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  805. computer as the $R_1$ program running in a Racket implementation.
  806. That is, they both output the same integer $n$.
  807. \[
  808. \begin{tikzpicture}[baseline=(current bounding box.center)]
  809. \node (p1) at (0, 0) {$P_1$};
  810. \node (p2) at (4, 0) {$P_2$};
  811. \node (o) at (4, -2) {$n$};
  812. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  813. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  814. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  815. \end{tikzpicture}
  816. \]
  817. In the next section we introduce enough of the x86 assembly
  818. language to compile $R_1$.
  819. \section{The x86 Assembly Language}
  820. \label{sec:x86}
  821. An x86 program is a sequence of instructions. The program is stored in
  822. the computer's memory and the \emph{program counter} points to the
  823. address of the next instruction to be executed. For most instructions,
  824. once the instruction is executed, the program counter is incremented
  825. to point to the immediately following instruction in the program.
  826. Each instruction may refer to integer constants (called
  827. \emph{immediate values}), variables called \emph{registers}, and
  828. instructions may load and store values into memory. For our purposes,
  829. we can think of the computer's memory as a mapping of 64-bit addresses
  830. to 64-bit values. Figure~\ref{fig:x86-a} defines the syntax for the
  831. subset of the x86 assembly language needed for this chapter. (We use
  832. the AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  833. Also, Appendix~\ref{sec:x86-quick-reference} includes a
  834. quick-reference of all the x86 instructions used in this book and a
  835. short explanation of what they do.
  836. % to do: finish treatment of imulq
  837. % it's needed for vector's in R6/R7
  838. \begin{figure}[tp]
  839. \fbox{
  840. \begin{minipage}{0.96\textwidth}
  841. \[
  842. \begin{array}{lcl}
  843. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  844. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  845. && \key{r8} \mid \key{r9} \mid \key{r10}
  846. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  847. \mid \key{r14} \mid \key{r15} \\
  848. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  849. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  850. \key{subq} \; \Arg, \Arg \mid
  851. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  852. && \key{callq} \; \mathit{label} \mid
  853. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  854. \Prog &::= & \key{.globl main}\\
  855. & & \key{main:} \; \Instr^{+}
  856. \end{array}
  857. \]
  858. \end{minipage}
  859. }
  860. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  861. \label{fig:x86-a}
  862. \end{figure}
  863. An immediate value is written using the notation \key{\$}$n$ where $n$
  864. is an integer.
  865. %
  866. A register is written with a \key{\%} followed by the register name,
  867. such as \key{\%rax}.
  868. %
  869. An access to memory is specified using the syntax $n(\key{\%}r)$,
  870. which reads register $r$ and then offsets the address by $n$ bytes
  871. (8 bits). The address is then used to either load or store to memory
  872. depending on whether it occurs as a source or destination argument of
  873. an instruction.
  874. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  875. source $s$ and destination $d$, applies the arithmetic operation, then
  876. writes the result in $d$.
  877. %
  878. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  879. result in $d$.
  880. %
  881. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  882. specified by the label.
  883. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  884. to \code{(+ 10 32)}. The \key{globl} directive says that the
  885. \key{main} procedure is externally visible, which is necessary so
  886. that the operating system can call it. The label \key{main:}
  887. indicates the beginning of the \key{main} procedure which is where
  888. the operating system starts executing this program. The instruction
  889. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  890. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  891. $10$ in \key{rax} and puts the result, $42$, back into
  892. \key{rax}. The instruction \lstinline{movq %rax, %rdi} moves the value
  893. in \key{rax} into another register, \key{rdi}, and
  894. \lstinline{callq print_int} calls the external function \code{print\_int}, which
  895. prints the value in \key{rdi}.
  896. The instruction \key{retq} finishes the \key{main}
  897. function by returning the integer in \key{rax} to the
  898. operating system.
  899. %\begin{wrapfigure}{r}{2.25in}
  900. \begin{figure}[tbp]
  901. \begin{lstlisting}
  902. .globl main
  903. main:
  904. movq $10, %rax
  905. addq $32, %rax
  906. movq %rax, %rdi
  907. callq print_int
  908. retq
  909. \end{lstlisting}
  910. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  911. \label{fig:p0-x86}
  912. %\end{wrapfigure}
  913. \end{figure}
  914. %% \marginpar{Consider using italics for the texts in these figures.
  915. %% It can get confusing to differentiate them from the main text.}
  916. %% It looks pretty ugly in italics.-Jeremy
  917. Unfortunately, x86 varies in a couple ways depending on what
  918. operating system it is assembled in. The code examples shown here are
  919. correct on the Unix platform, but when assembled on Mac OS X, labels
  920. like \key{main} must be prefixed with an underscore. So the correct
  921. output for the above program on Mac would begin with:
  922. \begin{lstlisting}
  923. .globl _main
  924. _main:
  925. ...
  926. \end{lstlisting}
  927. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  928. lists an x86 program that is equivalent to $\BINOP{+}{52}{
  929. \UNIOP{-}{10} }$. To understand how this x86 program works, we
  930. need to explain a region of memory called the \emph{procedure call
  931. stack} (or \emph{stack} for short). The stack consists of a separate
  932. \emph{frame} for each procedure call. The memory layout for an
  933. individual frame is shown in Figure~\ref{fig:frame}. The register
  934. \key{rsp} is called the \emph{stack pointer} and points to the item at
  935. the top of the stack. The stack grows downward in memory, so we
  936. increase the size of the stack by subtracting from the stack
  937. pointer. The frame size is required to be a multiple of 16 bytes. The
  938. register \key{rbp} is the \emph{base pointer} which serves two
  939. purposes: 1) it saves the location of the stack pointer for the
  940. procedure that called the current one and 2) it is used to access
  941. variables associated with the current procedure. We number the
  942. variables from $1$ to $n$. Variable $1$ is stored at address
  943. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  944. %\begin{wrapfigure}{r}{2.1in}
  945. \begin{figure}[tbp]
  946. \begin{lstlisting}
  947. .globl main
  948. main:
  949. pushq %rbp
  950. movq %rsp, %rbp
  951. subq $16, %rsp
  952. movq $10, -8(%rbp)
  953. negq -8(%rbp)
  954. movq $52, %rax
  955. addq -8(%rbp), %rax
  956. movq %rax, %rdi
  957. callq print_int
  958. addq $16, %rsp
  959. popq %rbp
  960. retq
  961. \end{lstlisting}
  962. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  963. \label{fig:p1-x86}
  964. \end{figure}
  965. %\end{wrapfigure}
  966. \begin{figure}[tbp]
  967. \centering
  968. \begin{tabular}{|r|l|} \hline
  969. Position & Contents \\ \hline
  970. 8(\key{\%rbp}) & return address \\
  971. 0(\key{\%rbp}) & old \key{rbp} \\
  972. -8(\key{\%rbp}) & variable $1$ \\
  973. -16(\key{\%rbp}) & variable $2$ \\
  974. \ldots & \ldots \\
  975. 0(\key{\%rsp}) & variable $n$\\ \hline
  976. \end{tabular}
  977. \caption{Memory layout of a frame.}
  978. \label{fig:frame}
  979. \end{figure}
  980. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  981. three instructions are the typical \emph{prelude} for a procedure.
  982. The instruction \key{pushq \%rbp} saves the base pointer for the
  983. procedure that called the current one onto the stack and subtracts $8$
  984. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  985. changes the base pointer to the top of the stack. The instruction
  986. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  987. room for storing variables. This program just needs one variable ($8$
  988. bytes) but because the frame size is required to be a multiple of 16
  989. bytes, it rounds to 16 bytes.
  990. The next four instructions carry out the work of computing
  991. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  992. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  993. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  994. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  995. adds the contents of variable $1$ to \key{rax}, at which point
  996. \key{rax} contains $42$.
  997. The last five instructions are the typical \emph{conclusion} of a
  998. procedure. The first two print the final result of the program. The
  999. latter three are necessary to get the state of the machine back to
  1000. where it was before the current procedure was called. The \key{addq
  1001. \$16, \%rsp} instruction moves the stack pointer back to point at
  1002. the old base pointer. The amount added here needs to match the amount
  1003. that was subtracted in the prelude of the procedure. Then \key{popq
  1004. \%rbp} returns the old base pointer to \key{rbp} and adds $8$ to the
  1005. stack pointer. The \key{retq} instruction jumps back to the procedure
  1006. that called this one and subtracts 8 from the stack pointer.
  1007. The compiler will need a convenient representation for manipulating
  1008. x86 programs, so we define an abstract syntax for x86 in
  1009. Figure~\ref{fig:x86-ast-a}. The $\Int$ field of the \key{program} AST
  1010. node is number of bytes of stack space needed for variables in the
  1011. program. (Some of the intermediate languages will store other
  1012. information in that location for the purposes of communicating
  1013. auxiliary data from one step of the compiler to the next. )
  1014. \begin{figure}[tp]
  1015. \fbox{
  1016. \begin{minipage}{0.96\textwidth}
  1017. \[
  1018. \begin{array}{lcl}
  1019. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1020. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1021. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1022. (\key{subq} \; \Arg\; \Arg) \mid
  1023. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  1024. &\mid& (\key{callq} \; \mathit{label}) \mid
  1025. (\key{pushq}\;\Arg) \mid
  1026. (\key{popq}\;\Arg) \mid
  1027. (\key{retq}) \\
  1028. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1029. \end{array}
  1030. \]
  1031. \end{minipage}
  1032. }
  1033. \caption{Abstract syntax for x86 assembly.}
  1034. \label{fig:x86-ast-a}
  1035. \end{figure}
  1036. \section{Planning the trip to x86 via the $C_0$ language}
  1037. \label{sec:plan-s0-x86}
  1038. To compile one language to another it helps to focus on the
  1039. differences between the two languages. It is these differences that
  1040. the compiler will need to bridge. What are the differences between
  1041. $R_1$ and x86 assembly? Here we list some of the most important the
  1042. differences.
  1043. \begin{enumerate}
  1044. \item x86 arithmetic instructions typically take two arguments and
  1045. update the second argument in place. In contrast, $R_1$ arithmetic
  1046. operations only read their arguments and produce a new value.
  1047. \item An argument to an $R_1$ operator can be any expression, whereas
  1048. x86 instructions restrict their arguments to integers, registers,
  1049. and memory locations.
  1050. \item An $R_1$ program can have any number of variables whereas x86
  1051. has only 16 registers.
  1052. \item Variables in $R_1$ can overshadow other variables with the same
  1053. name. The registers and memory locations of x86 all have unique
  1054. names.
  1055. \end{enumerate}
  1056. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1057. the problem into several steps, dealing with the above differences one
  1058. at a time. The main question then becomes: in what order do we tackle
  1059. these differences? This is often one of the most challenging questions
  1060. that a compiler writer must answer because some orderings may be much
  1061. more difficult to implement than others. It is difficult to know ahead
  1062. of time which orders will be better so often some trial-and-error is
  1063. involved. However, we can try to plan ahead and choose the orderings
  1064. based on this planning.
  1065. For example, to handle difference \#2 (nested expressions), we shall
  1066. introduce new variables and pull apart the nested expressions into a
  1067. sequence of assignment statements. To deal with difference \#3 we
  1068. will be replacing variables with registers and/or stack
  1069. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1070. \#3 can replace both the original variables and the new ones. Next,
  1071. consider where \#1 should fit in. Because it has to do with the format
  1072. of x86 instructions, it makes more sense after we have flattened the
  1073. nested expressions (\#2). Finally, when should we deal with \#4
  1074. (variable overshadowing)? We shall solve this problem by renaming
  1075. variables to make sure they have unique names. Recall that our plan
  1076. for \#2 involves moving nested expressions, which could be problematic
  1077. if it changes the shadowing of variables. However, if we deal with \#4
  1078. first, then it will not be an issue. Thus, we arrive at the following
  1079. ordering.
  1080. \[
  1081. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1082. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1083. {
  1084. \node (\i) at (\p*1.5,0) {$\i$};
  1085. }
  1086. \foreach \x/\y in {4/2,2/1,1/3}
  1087. {
  1088. \draw[->] (\x) to (\y);
  1089. }
  1090. \end{tikzpicture}
  1091. \]
  1092. We further simplify the translation from $R_1$ to x86 by identifying
  1093. an intermediate language named $C_0$, roughly half-way between $R_1$
  1094. and x86, to provide a rest stop along the way. We name the language
  1095. $C_0$ because it is vaguely similar to the $C$
  1096. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1097. regarding variables and nested expressions, will be handled by two
  1098. steps, \key{uniquify} and \key{flatten}, which bring us to
  1099. $C_0$.
  1100. \[
  1101. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1102. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1103. {
  1104. \node (\p) at (\p*3,0) {\large $\i$};
  1105. }
  1106. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1107. {
  1108. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1109. }
  1110. \end{tikzpicture}
  1111. \]
  1112. Each of these steps in the compiler is implemented by a function,
  1113. typically a structurally recursive function that translates an input
  1114. AST into an output AST. We refer to such a function as a \emph{pass}
  1115. because it makes a pass over, i.e. it traverses the entire AST.
  1116. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1117. $C_0$ language supports the same operators as $R_1$ but the arguments
  1118. of operators are now restricted to just variables and integers. The
  1119. \key{let} construct of $R_1$ is replaced by an assignment statement
  1120. and there is a \key{return} construct to specify the return value of
  1121. the program. A program consists of a sequence of statements that
  1122. include at least one \key{return} statement. Each program is also
  1123. annotated with a list of variables (viz. {\tt (var*)}). At the start
  1124. of the program, these variables are uninitialized (they contain garbage)
  1125. and each variable becomes initialized on its first assignment. All of
  1126. the variables used in the program must be present in this list.
  1127. \begin{figure}[tp]
  1128. \fbox{
  1129. \begin{minipage}{0.96\textwidth}
  1130. \[
  1131. \begin{array}{lcl}
  1132. \Arg &::=& \Int \mid \Var \\
  1133. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1134. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1135. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1136. \end{array}
  1137. \]
  1138. \end{minipage}
  1139. }
  1140. \caption{The $C_0$ intermediate language.}
  1141. \label{fig:c0-syntax}
  1142. \end{figure}
  1143. To get from $C_0$ to x86 assembly it remains for us to handle
  1144. difference \#1 (the format of instructions) and difference \#3
  1145. (variables versus registers). These two differences are intertwined,
  1146. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1147. map some variables to registers (there are only 16 registers) and the
  1148. remaining variables to locations on the stack (which is unbounded). To
  1149. make good decisions regarding this mapping, we need the program to be
  1150. close to its final form (in x86 assembly) so we know exactly when
  1151. which variables are used. After all, variables that are used in
  1152. disjoint parts of the program can be assigned to the same register.
  1153. However, our choice of x86 instructions depends on whether the
  1154. variables are mapped to registers or stack locations, so we have a
  1155. circular dependency. We cut this knot by doing an optimistic selection
  1156. of instructions in the \key{select-instructions} pass, followed by the
  1157. \key{assign-homes} pass to map variables to registers or stack
  1158. locations, and conclude by finalizing the instruction selection in the
  1159. \key{patch-instructions} pass.
  1160. \[
  1161. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1162. \node (1) at (0,0) {\large $C_0$};
  1163. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1164. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1165. \node (4) at (9,0) {\large $\text{x86}$};
  1166. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1167. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1168. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1169. \end{tikzpicture}
  1170. \]
  1171. The \key{select-instructions} pass is optimistic in the sense that it
  1172. treats variables as if they were all mapped to registers. The
  1173. \key{select-instructions} pass generates a program that consists of
  1174. x86 instructions but that still uses variables, so it is an
  1175. intermediate language that is technically different than x86, which
  1176. explains the asterisks in the diagram above.
  1177. In this Chapter we shall take the easy road to implementing
  1178. \key{assign-homes} and simply map all variables to stack locations.
  1179. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1180. smarter approach in which we make a best-effort to map variables to
  1181. registers, resorting to the stack only when necessary.
  1182. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1183. %% After all, that selects the x86 instructions. Even if it is separate,
  1184. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1185. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1186. %% Cam}
  1187. Once variables have been assigned to their homes, we can finalize the
  1188. instruction selection by dealing with an idiosyncrasy of x86
  1189. assembly. Many x86 instructions have two arguments but only one of the
  1190. arguments may be a memory reference (and the stack is a part of
  1191. memory). Because some variables may get mapped to stack locations,
  1192. some of our generated instructions may violate this restriction. The
  1193. purpose of the \key{patch-instructions} pass is to fix this problem by
  1194. replacing every violating instruction with a short sequence of
  1195. instructions that use the \key{rax} register. Once we have implemented
  1196. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1197. need to patch instructions will be relatively rare.
  1198. \section{Uniquify Variables}
  1199. \label{sec:uniquify-s0}
  1200. The purpose of this pass is to make sure that each \key{let} uses a
  1201. unique variable name. For example, the \code{uniquify} pass should
  1202. translate the program on the left into the program on the right. \\
  1203. \begin{tabular}{lll}
  1204. \begin{minipage}{0.4\textwidth}
  1205. \begin{lstlisting}
  1206. (program
  1207. (let ([x 32])
  1208. (+ (let ([x 10]) x) x)))
  1209. \end{lstlisting}
  1210. \end{minipage}
  1211. &
  1212. $\Rightarrow$
  1213. &
  1214. \begin{minipage}{0.4\textwidth}
  1215. \begin{lstlisting}
  1216. (program
  1217. (let ([x.1 32])
  1218. (+ (let ([x.2 10]) x.2) x.1)))
  1219. \end{lstlisting}
  1220. \end{minipage}
  1221. \end{tabular} \\
  1222. %
  1223. The following is another example translation, this time of a program
  1224. with a \key{let} nested inside the initializing expression of another
  1225. \key{let}.\\
  1226. \begin{tabular}{lll}
  1227. \begin{minipage}{0.4\textwidth}
  1228. \begin{lstlisting}
  1229. (program
  1230. (let ([x (let ([x 4])
  1231. (+ x 1))])
  1232. (+ x 2)))
  1233. \end{lstlisting}
  1234. \end{minipage}
  1235. &
  1236. $\Rightarrow$
  1237. &
  1238. \begin{minipage}{0.4\textwidth}
  1239. \begin{lstlisting}
  1240. (program
  1241. (let ([x.2 (let ([x.1 4])
  1242. (+ x.1 1))])
  1243. (+ x.2 2)))
  1244. \end{lstlisting}
  1245. \end{minipage}
  1246. \end{tabular}
  1247. We recommend implementing \code{uniquify} as a structurally recursive
  1248. function that mostly copies the input program. However, when
  1249. encountering a \key{let}, it should generate a unique name for the
  1250. variable (the Racket function \code{gensym} is handy for this) and
  1251. associate the old name with the new unique name in an association
  1252. list. The \code{uniquify} function will need to access this
  1253. association list when it gets to a variable reference, so we add
  1254. another parameter to \code{uniquify} for the association list. It is
  1255. quite common for a compiler pass to need a map to store extra
  1256. information about variables. Such maps are often called \emph{symbol
  1257. tables}.
  1258. The skeleton of the \code{uniquify} function is shown in
  1259. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1260. convenient to partially apply it to an association list and then apply
  1261. it to different expressions, as in the last clause for primitive
  1262. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1263. clause for the primitive operators, note the use of the comma-@
  1264. operator to splice a list of S-expressions into an enclosing
  1265. S-expression.
  1266. \begin{exercise}
  1267. \normalfont % I don't like the italics for exercises. -Jeremy
  1268. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1269. implement the clauses for variables and for the \key{let} construct.
  1270. \end{exercise}
  1271. \begin{figure}[tbp]
  1272. \begin{lstlisting}
  1273. (define (uniquify alist)
  1274. (lambda (e)
  1275. (match e
  1276. [(? symbol?) ___]
  1277. [(? integer?) e]
  1278. [`(let ([,x ,e]) ,body) ___]
  1279. [`(program ,e)
  1280. `(program ,((uniquify alist) e))]
  1281. [`(,op ,es ...)
  1282. `(,op ,@(map (uniquify alist) es))]
  1283. )))
  1284. \end{lstlisting}
  1285. \caption{Skeleton for the \key{uniquify} pass.}
  1286. \label{fig:uniquify-s0}
  1287. \end{figure}
  1288. \begin{exercise}
  1289. \normalfont % I don't like the italics for exercises. -Jeremy
  1290. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1291. and checking whether the output programs produce the same result as
  1292. the input programs. The $R_1$ programs should be designed to test the
  1293. most interesting parts of the \key{uniquify} pass, that is, the
  1294. programs should include \key{let} constructs, variables, and variables
  1295. that overshadow each other. The five programs should be in a
  1296. subdirectory named \key{tests} and they should have the same file name
  1297. except for a different integer at the end of the name, followed by the
  1298. ending \key{.rkt}. Use the \key{interp-tests} function
  1299. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1300. your \key{uniquify} pass on the example programs.
  1301. \end{exercise}
  1302. \section{Flatten Expressions}
  1303. \label{sec:flatten-r1}
  1304. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1305. programs. In particular, the purpose of the \code{flatten} pass is to
  1306. get rid of nested expressions, such as the \code{(- 10)} in the program
  1307. below. This can be accomplished by introducing a new variable,
  1308. assigning the nested expression to the new variable, and then using
  1309. the new variable in place of the nested expressions, as shown in the
  1310. output of \code{flatten} on the right.\\
  1311. \begin{tabular}{lll}
  1312. \begin{minipage}{0.4\textwidth}
  1313. \begin{lstlisting}
  1314. (program
  1315. (+ 52 (- 10)))
  1316. \end{lstlisting}
  1317. \end{minipage}
  1318. &
  1319. $\Rightarrow$
  1320. &
  1321. \begin{minipage}{0.4\textwidth}
  1322. \begin{lstlisting}
  1323. (program (tmp.1 tmp.2)
  1324. (assign tmp.1 (- 10))
  1325. (assign tmp.2 (+ 52 tmp.1))
  1326. (return tmp.2))
  1327. \end{lstlisting}
  1328. \end{minipage}
  1329. \end{tabular}
  1330. The clause of \code{flatten} for \key{let} is straightforward to
  1331. implement as it just requires the generation of an assignment
  1332. statement for the \key{let}-bound variable. The following shows the
  1333. result of \code{flatten} for a \key{let}. \\
  1334. \begin{tabular}{lll}
  1335. \begin{minipage}{0.4\textwidth}
  1336. \begin{lstlisting}
  1337. (program
  1338. (let ([x (+ (- 10) 11)])
  1339. (+ x 41)))
  1340. \end{lstlisting}
  1341. \end{minipage}
  1342. &
  1343. $\Rightarrow$
  1344. &
  1345. \begin{minipage}{0.4\textwidth}
  1346. \begin{lstlisting}
  1347. (program (tmp.1 x tmp.2)
  1348. (assign tmp.1 (- 10))
  1349. (assign x (+ tmp.1 11))
  1350. (assign tmp.2 (+ x 41))
  1351. (return tmp.2))
  1352. \end{lstlisting}
  1353. \end{minipage}
  1354. \end{tabular}
  1355. We recommend implementing \key{flatten} as a structurally recursive
  1356. function that returns three things, 1) the newly flattened expression,
  1357. 2) a list of assignment statements, one for each of the new variables
  1358. introduced during the flattening the expression, and 3) a list of all
  1359. the variables including both let-bound variables and the generated
  1360. temporary variables. The newly flattened expression should be an
  1361. $\Arg$ in the $C_0$ syntax (Figure~\ref{fig:c0-syntax}), that is, it
  1362. should be an integer or a variable. You can return multiple things
  1363. from a function using the \key{values} form and you can receive
  1364. multiple things from a function call using the \key{define-values}
  1365. form. If you are not familiar with these constructs, the Racket
  1366. documentation will be of help. Also, the \key{map3} function
  1367. (Appendix~\ref{appendix:utilities}) is useful for applying a function
  1368. to each element of a list, in the case where the function returns
  1369. three values. The result of \key{map3} is three lists.
  1370. The clause of \key{flatten} for the \key{program} node needs to
  1371. recursively flatten the body of the program and the newly flattened
  1372. expression should be placed in a \key{return} statement. The
  1373. \key{flatten} pass should also compute the list of variables used in
  1374. the program. I recommend traversing the statements in the body of the
  1375. program (after it has been flattened) and collect all variables that
  1376. appear on the left-hand-side of an assignment. Note that each variable
  1377. should only occur once in the list of variables that you place in the
  1378. \key{program} form.
  1379. Take special care for programs such as the following that initialize
  1380. variables with integers or other variables. It should be translated
  1381. to the program on the right \\
  1382. \begin{tabular}{lll}
  1383. \begin{minipage}{0.4\textwidth}
  1384. \begin{lstlisting}
  1385. (let ([a 42])
  1386. (let ([b a])
  1387. b))
  1388. \end{lstlisting}
  1389. \end{minipage}
  1390. &
  1391. $\Rightarrow$
  1392. &
  1393. \begin{minipage}{0.4\textwidth}
  1394. \begin{lstlisting}
  1395. (program (a b)
  1396. (assign a 42)
  1397. (assign b a)
  1398. (return b))
  1399. \end{lstlisting}
  1400. \end{minipage}
  1401. \end{tabular} \\
  1402. and not to the following, which could result from a naive
  1403. implementation of \key{flatten}.
  1404. \begin{lstlisting}
  1405. (program (tmp.1 a tmp.2 b)
  1406. (assign tmp.1 42)
  1407. (assign a tmp.1)
  1408. (assign tmp.2 a)
  1409. (assign b tmp.2)
  1410. (return b))
  1411. \end{lstlisting}
  1412. \begin{exercise}
  1413. \normalfont
  1414. Implement the \key{flatten} pass and test it on all of the example
  1415. programs that you created to test the \key{uniquify} pass and create
  1416. three new example programs that are designed to exercise all of the
  1417. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1418. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1419. test your passes on the example programs.
  1420. \end{exercise}
  1421. \section{Select Instructions}
  1422. \label{sec:select-s0}
  1423. In the \key{select-instructions} pass we begin the work of translating
  1424. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1425. language that still uses variables, so we add an AST node of the form
  1426. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1427. form should still list the variables (similar to $C_0$):
  1428. \[
  1429. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1430. \]
  1431. The \key{select-instructions} pass deals with the differing format of
  1432. arithmetic operations. For example, in $C_0$ an addition operation can
  1433. take the form below. To translate to x86, we need to use the
  1434. \key{addq} instruction which does an in-place update. So we must first
  1435. move \code{10} to \code{x}. \\
  1436. \begin{tabular}{lll}
  1437. \begin{minipage}{0.4\textwidth}
  1438. \begin{lstlisting}
  1439. (assign x (+ 10 32))
  1440. \end{lstlisting}
  1441. \end{minipage}
  1442. &
  1443. $\Rightarrow$
  1444. &
  1445. \begin{minipage}{0.4\textwidth}
  1446. \begin{lstlisting}
  1447. (movq (int 10) (var x))
  1448. (addq (int 32) (var x))
  1449. \end{lstlisting}
  1450. \end{minipage}
  1451. \end{tabular} \\
  1452. There are some cases that require special care to avoid generating
  1453. needlessly complicated code. If one of the arguments is the same as
  1454. the left-hand side of the assignment, then there is no need for the
  1455. extra move instruction. For example, the following assignment
  1456. statement can be translated into a single \key{addq} instruction.\\
  1457. \begin{tabular}{lll}
  1458. \begin{minipage}{0.4\textwidth}
  1459. \begin{lstlisting}
  1460. (assign x (+ 10 x))
  1461. \end{lstlisting}
  1462. \end{minipage}
  1463. &
  1464. $\Rightarrow$
  1465. &
  1466. \begin{minipage}{0.4\textwidth}
  1467. \begin{lstlisting}
  1468. (addq (int 10) (var x))
  1469. \end{lstlisting}
  1470. \end{minipage}
  1471. \end{tabular} \\
  1472. The \key{read} operation does not have a direct counterpart in x86
  1473. assembly, so we have instead implemented this functionality in the C
  1474. language, with the function \code{read\_int} in the file
  1475. \code{runtime.c}. In general, we refer to all of the functionality in
  1476. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1477. for short. When compiling your generated x86 assembly code, you
  1478. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1479. file'', using \code{gcc} option \code{-c}) and link it into the final
  1480. executable. For our purposes of code generation, all you need to do is
  1481. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1482. (for left-hand side) into a call to the \code{read\_int} function
  1483. followed by a move from \code{rax} to the left-hand side. The move
  1484. from \code{rax} is needed because the return value from
  1485. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1486. \begin{tabular}{lll}
  1487. \begin{minipage}{0.4\textwidth}
  1488. \begin{lstlisting}
  1489. (assign |$\itm{lhs}$| (read))
  1490. \end{lstlisting}
  1491. \end{minipage}
  1492. &
  1493. $\Rightarrow$
  1494. &
  1495. \begin{minipage}{0.4\textwidth}
  1496. \begin{lstlisting}
  1497. (callq read_int)
  1498. (movq (reg rax) (var |$\itm{lhs}$|))
  1499. \end{lstlisting}
  1500. \end{minipage}
  1501. \end{tabular} \\
  1502. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1503. as an assignment to the \key{rax} register and let the procedure
  1504. conclusion handle the transfer of control back to the calling
  1505. procedure.
  1506. \begin{exercise}
  1507. \normalfont
  1508. Implement the \key{select-instructions} pass and test it on all of the
  1509. example programs that you created for the previous passes and create
  1510. three new example programs that are designed to exercise all of the
  1511. interesting code in this pass. Use the \key{interp-tests} function
  1512. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1513. your passes on the example programs.
  1514. \end{exercise}
  1515. \section{Assign Homes}
  1516. \label{sec:assign-s0}
  1517. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1518. \key{assign-homes} pass places all of the variables on the stack.
  1519. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1520. which after \key{select-instructions} looks like the following.
  1521. \begin{lstlisting}
  1522. (movq (int 10) (var tmp.1))
  1523. (negq (var tmp.1))
  1524. (movq (var tmp.1) (var tmp.2))
  1525. (addq (int 52) (var tmp.2))
  1526. (movq (var tmp.2) (reg rax)))
  1527. \end{lstlisting}
  1528. The variable \code{tmp.1} is assigned to stack location
  1529. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1530. the \code{assign-homes} pass translates the above to
  1531. \begin{lstlisting}
  1532. (movq (int 10) (deref rbp -16))
  1533. (negq (deref rbp -16))
  1534. (movq (deref rbp -16) (deref rbp -8))
  1535. (addq (int 52) (deref rbp -8))
  1536. (movq (deref rbp -8) (reg rax)))
  1537. \end{lstlisting}
  1538. In the process of assigning stack locations to variables, it is
  1539. convenient to compute and store the size of the frame (in bytes) in
  1540. the first field of the \key{program} node which will be needed later
  1541. to generate the procedure conclusion.
  1542. \[
  1543. (\key{program}\;\Int\;\Instr^{+})
  1544. \]
  1545. Some operating systems place restrictions on
  1546. the frame size. For example, Mac OS X requires the frame size to be a
  1547. multiple of 16 bytes.
  1548. \begin{exercise}
  1549. \normalfont Implement the \key{assign-homes} pass and test it on all
  1550. of the example programs that you created for the previous passes pass.
  1551. I recommend that \key{assign-homes} take an extra parameter that is a
  1552. mapping of variable names to homes (stack locations for now). Use the
  1553. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1554. \key{utilities.rkt} to test your passes on the example programs.
  1555. \end{exercise}
  1556. \section{Patch Instructions}
  1557. \label{sec:patch-s0}
  1558. The purpose of this pass is to make sure that each instruction adheres
  1559. to the restrictions regarding which arguments can be memory
  1560. references. For most instructions, the rule is that at most one
  1561. argument may be a memory reference.
  1562. Consider again the following example.
  1563. \begin{lstlisting}
  1564. (let ([a 42])
  1565. (let ([b a])
  1566. b))
  1567. \end{lstlisting}
  1568. After \key{assign-homes} pass, the above has been translated to
  1569. \begin{lstlisting}
  1570. (movq (int 42) (deref rbp -8))
  1571. (movq (deref rbp -8) (deref rbp -16))
  1572. (movq (deref rbp -16) (reg rax))
  1573. \end{lstlisting}
  1574. The second \key{movq} instruction is problematic because both
  1575. arguments are stack locations. We suggest fixing this problem by
  1576. moving from the source to the register \key{rax} and then from
  1577. \key{rax} to the destination, as follows.
  1578. \begin{lstlisting}
  1579. (movq (int 42) (deref rbp -8))
  1580. (movq (deref rbp -8) (reg rax))
  1581. (movq (reg rax) (deref rbp -16))
  1582. (movq (deref rbp -16) (reg rax))
  1583. \end{lstlisting}
  1584. \begin{exercise}
  1585. \normalfont
  1586. Implement the \key{patch-instructions} pass and test it on all of the
  1587. example programs that you created for the previous passes and create
  1588. three new example programs that are designed to exercise all of the
  1589. interesting code in this pass. Use the \key{interp-tests} function
  1590. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1591. your passes on the example programs.
  1592. \end{exercise}
  1593. \section{Print x86}
  1594. \label{sec:print-x86}
  1595. The last step of the compiler from $R_1$ to x86 is to convert the
  1596. x86 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1597. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1598. \key{format} and \key{string-append} functions are useful in this
  1599. regard. The main work that this step needs to perform is to create the
  1600. \key{main} function and the standard instructions for its prelude
  1601. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1602. Section~\ref{sec:x86}. You need to know the number of
  1603. stack-allocated variables, for which it is suggest that you compute in
  1604. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1605. the $\itm{info}$ field of the \key{program} node.
  1606. Your compiled code should print the result of the program's execution by using the
  1607. \code{print\_int} function provided in \code{runtime.c}. If your compiler has been implemented correctly so far, this final result should be stored in the \key{rax} register.
  1608. We'll talk more about
  1609. how to perform function calls with arguments in general later on, but
  1610. for now, make sure that your x86 printer includes the following code as part of the conclusion:
  1611. \begin{lstlisting}
  1612. movq %rax, %rdi
  1613. callq print_int
  1614. \end{lstlisting}
  1615. These lines move the value in \key{rax} into the \key{rdi} register, which
  1616. stores the first argument to be passed into \key{print\_int}.
  1617. If you want your program to run on Mac OS X, your code needs to
  1618. determine whether or not it is running on a Mac, and prefix
  1619. underscores to labels like \key{main}. You can determine the platform
  1620. with the Racket call \code{(system-type 'os)}, which returns
  1621. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1622. placing underscores on \key{main}, you need to put them in front of
  1623. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1624. \_print\_int}).
  1625. \begin{exercise}
  1626. \normalfont Implement the \key{print-x86} pass and test it on all of
  1627. the example programs that you created for the previous passes. Use the
  1628. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1629. \key{utilities.rkt} to test your complete compiler on the example
  1630. programs.
  1631. % The following is specific to P423/P523. -Jeremy
  1632. %Mac support is optional, but your compiler has to output
  1633. %valid code for Unix machines.
  1634. \end{exercise}
  1635. \begin{figure}[p]
  1636. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1637. \node (R1) at (0,2) {\large $R_1$};
  1638. \node (R1-2) at (3,2) {\large $R_1$};
  1639. \node (C0-1) at (3,0) {\large $C_0$};
  1640. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  1641. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  1642. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  1643. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  1644. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1645. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  1646. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1647. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1648. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1649. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1650. \end{tikzpicture}
  1651. \caption{Overview of the passes for compiling $R_1$. }
  1652. \label{fig:R1-passes}
  1653. \end{figure}
  1654. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1655. passes described in this Chapter. The x86$^{*}$ language extends x86
  1656. with variables and looser rules regarding instruction arguments. The
  1657. x86$^{\dagger}$ language is the concrete syntax (string) for x86.
  1658. \marginpar{\footnotesize To do: add a challenge section. Perhaps
  1659. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1661. \chapter{Register Allocation}
  1662. \label{ch:register-allocation}
  1663. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1664. assembly by placing all variables on the stack. We can improve the
  1665. performance of the generated code considerably if we instead try to
  1666. place as many variables as possible into registers. The CPU can
  1667. access a register in a single cycle, whereas accessing the stack takes
  1668. many cycles to go to cache or many more to access main memory.
  1669. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1670. serves as a running example. We show the source program and also the
  1671. output of instruction selection. At that point the program is almost
  1672. x86 assembly but not quite; it still contains variables instead of
  1673. stack locations or registers.
  1674. \begin{figure}
  1675. \begin{minipage}{0.45\textwidth}
  1676. Source program:
  1677. \begin{lstlisting}
  1678. (program
  1679. (let ([v 1])
  1680. (let ([w 46])
  1681. (let ([x (+ v 7)])
  1682. (let ([y (+ 4 x)])
  1683. (let ([z (+ x w)])
  1684. (+ z (- y))))))))
  1685. \end{lstlisting}
  1686. \end{minipage}
  1687. \begin{minipage}{0.45\textwidth}
  1688. After instruction selection:
  1689. \begin{lstlisting}
  1690. (program (v w x y z t.1 t.2)
  1691. (movq (int 1) (var v))
  1692. (movq (int 46) (var w))
  1693. (movq (var v) (var x))
  1694. (addq (int 7) (var x))
  1695. (movq (var x) (var y))
  1696. (addq (int 4) (var y))
  1697. (movq (var x) (var z))
  1698. (addq (var w) (var z))
  1699. (movq (var y) (var t.1))
  1700. (negq (var t.1))
  1701. (movq (var z) (var t.2))
  1702. (addq (var t.1) (var t.2))
  1703. (movq (var t.2) (reg rax)))
  1704. \end{lstlisting}
  1705. \end{minipage}
  1706. \caption{An example program for register allocation.}
  1707. \label{fig:reg-eg}
  1708. \end{figure}
  1709. The goal of register allocation is to fit as many variables into
  1710. registers as possible. It is often the case that we have more
  1711. variables than registers, so we cannot map each variable to a
  1712. different register. Fortunately, it is common for different variables
  1713. to be needed during different periods of time, and in such cases
  1714. several variables can be mapped to the same register. Consider
  1715. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1716. variable \code{x} is moved to \code{z} it is no longer needed.
  1717. Variable \code{y}, on the other hand, is used only after this point,
  1718. so \code{x} and \code{y} could share the same register. The topic of
  1719. Section~\ref{sec:liveness-analysis} is how we compute where a variable
  1720. is needed. Once we have that information, we compute which variables
  1721. are needed at the same time, i.e., which ones \emph{interfere}, and
  1722. represent this relation as graph whose vertices are variables and
  1723. edges indicate when two variables interfere with eachother
  1724. (Section~\ref{sec:build-interference}). We then model register
  1725. allocation as a graph coloring problem, which we discuss in
  1726. Section~\ref{sec:graph-coloring}.
  1727. In the event that we run out of registers despite these efforts, we
  1728. place the remaining variables on the stack, similar to what we did in
  1729. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1730. that is assigned to a stack location, it has been \emph{spilled}. The
  1731. process of spilling variables is handled as part of the graph coloring
  1732. process described in \ref{sec:graph-coloring}.
  1733. \section{Liveness Analysis}
  1734. \label{sec:liveness-analysis}
  1735. A variable is \emph{live} if the variable is used at some later point
  1736. in the program and there is not an intervening assignment to the
  1737. variable.
  1738. %
  1739. To understand the latter condition, consider the following code
  1740. fragment in which there are two writes to \code{b}. Are \code{a} and
  1741. \code{b} both live at the same time?
  1742. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1743. (movq (int 5) (var a))
  1744. (movq (int 30) (var b))
  1745. (movq (var a) (var c))
  1746. (movq (int 10) (var b))
  1747. (addq (var b) (var c))
  1748. \end{lstlisting}
  1749. The answer is no because the value \code{30} written to \code{b} on
  1750. line 2 is never used. The variable \code{b} is read on line 5 and
  1751. there is an intervening write to \code{b} on line 4, so the read on
  1752. line 5 receives the value written on line 4, not line 2.
  1753. The live variables can be computed by traversing the instruction
  1754. sequence back to front (i.e., backwards in execution order). Let
  1755. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1756. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1757. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1758. variables before instruction $I_k$. The live variables after an
  1759. instruction are always the same as the live variables before the next
  1760. instruction.
  1761. \begin{equation*}
  1762. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1763. \end{equation*}
  1764. To start things off, there are no live variables after the last
  1765. instruction, so
  1766. \begin{equation*}
  1767. L_{\mathsf{after}}(n) = \emptyset
  1768. \end{equation*}
  1769. We then apply the following rule repeatedly, traversing the
  1770. instruction sequence back to front.
  1771. \begin{equation*}
  1772. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1773. \end{equation*}
  1774. where $W(k)$ are the variables written to by instruction $I_k$ and
  1775. $R(k)$ are the variables read by instruction $I_k$.
  1776. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1777. for the running example, with each instruction aligned with its
  1778. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1779. \marginpar{JM: I think you should walk through the explanation of this formula,
  1780. connecting it back to the example from before. \\
  1781. JS: Agreed.}
  1782. \begin{figure}[tbp]
  1783. \hspace{20pt}
  1784. \begin{minipage}{0.45\textwidth}
  1785. \begin{lstlisting}[numbers=left]
  1786. (program (v w x y z t.1 t.2)
  1787. (movq (int 1) (var v))
  1788. (movq (int 46) (var w))
  1789. (movq (var v) (var x))
  1790. (addq (int 7) (var x))
  1791. (movq (var x) (var y))
  1792. (addq (int 4) (var y))
  1793. (movq (var x) (var z))
  1794. (addq (var w) (var z))
  1795. (movq (var y) (var t.1))
  1796. (negq (var t.1))
  1797. (movq (var z) (var t.2))
  1798. (addq (var t.1) (var t.2))
  1799. (movq (var t.2) (reg rax)))
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. \vrule\hspace{10pt}
  1803. \begin{minipage}{0.45\textwidth}
  1804. \begin{lstlisting}
  1805. |$\{ v \}$|
  1806. |$\{ v, w \}$|
  1807. |$\{ w, x \}$|
  1808. |$\{ w, x \}$|
  1809. |$\{ w, x, y\}$|
  1810. |$\{ w, x, y \}$|
  1811. |$\{ w, y, z \}$|
  1812. |$\{ y, z \}$|
  1813. |$\{ t.1, z \}$|
  1814. |$\{ t.1, z \}$|
  1815. |$\{t.1,t.2\}$|
  1816. |$\{t.2\}$|
  1817. |$\{\}$|
  1818. \end{lstlisting}
  1819. \end{minipage}
  1820. \caption{An example program annotated with live-after sets.}
  1821. \label{fig:live-eg}
  1822. \end{figure}
  1823. \begin{exercise}\normalfont
  1824. Implement the compiler pass named \code{uncover-live} that computes
  1825. the live-after sets. We recommend storing the live-after sets (a list
  1826. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1827. node alongside the list of variables as follows.
  1828. \begin{lstlisting}
  1829. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1830. \end{lstlisting}
  1831. I recommend organizing your code to use a helper function that takes a
  1832. list of statements and an initial live-after set (typically empty) and
  1833. returns the list of statements and the list of live-after sets. For
  1834. this chapter, returning the list of statements is unnecessary, as they
  1835. awill be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1836. \key{if} statements and will need to annotate them with the live-after
  1837. sets of the two branches.
  1838. I recommend creating helper functions to 1) compute the set of
  1839. variables that appear in an argument (of an instruction), 2) compute
  1840. the variables read by an instruction which corresponds to the $R$
  1841. function discussed above, and 3) the variables written by an
  1842. instruction which corresponds to $W$.
  1843. \end{exercise}
  1844. \section{Building the Interference Graph}
  1845. \label{sec:build-interference}
  1846. Based on the liveness analysis, we know where each variable is needed.
  1847. However, during register allocation, we need to answer questions of
  1848. the specific form: are variables $u$ and $v$ live at the same time?
  1849. (And therefore cannot be assigned to the same register.) To make this
  1850. question easier to answer, we create an explicit data structure, an
  1851. \emph{interference graph}. An interference graph is an undirected
  1852. graph that has an edge between two variables if they are live at the
  1853. same time, that is, if they interfere with each other.
  1854. The most obvious way to compute the interference graph is to look at
  1855. the set of live variables between each statement in the program, and
  1856. add an edge to the graph for every pair of variables in the same set.
  1857. This approach is less than ideal for two reasons. First, it can be
  1858. rather expensive because it takes $O(n^2)$ time to look at every pair
  1859. in a set of $n$ live variables. Second, there is a special case in
  1860. which two variables that are live at the same time do not actually
  1861. interfere with each other: when they both contain the same value
  1862. because we have assigned one to the other.
  1863. A better way to compute the interference graph is given by the
  1864. following.
  1865. \begin{itemize}
  1866. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1867. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1868. d$ or $v = s$.
  1869. \item If instruction $I_k$ is not a move but some other arithmetic
  1870. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1871. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1872. \item If instruction $I_k$ is of the form (\key{callq}
  1873. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1874. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1875. \end{itemize}
  1876. \marginpar{JM: I think you could give examples of each one of these
  1877. using the example program and use those to help explain why these
  1878. rules are correct.\\
  1879. JS: Agreed.}
  1880. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  1881. the following interference for the instruction at the specified line
  1882. number.
  1883. \begin{quote}
  1884. Line 2: no interference,\\
  1885. Line 3: $w$ interferes with $v$,\\
  1886. Line 4: $x$ interferes with $w$,\\
  1887. Line 5: $x$ interferes with $w$,\\
  1888. Line 6: $y$ interferes with $w$,\\
  1889. Line 7: $y$ interferes with $w$ and $x$,\\
  1890. Line 8: $z$ interferes with $w$ and $y$,\\
  1891. Line 9: $z$ interferes with $y$, \\
  1892. Line 10: $t.1$ interferes with $z$, \\
  1893. Line 11: $t.1$ interferes with $z$, \\
  1894. Line 12: $t.2$ interferes with $t.1$, \\
  1895. Line 13: no interference. \\
  1896. Line 14: no interference.
  1897. \end{quote}
  1898. The resulting interference graph is shown in
  1899. Figure~\ref{fig:interfere}.
  1900. \begin{figure}[tbp]
  1901. \large
  1902. \[
  1903. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1904. \node (v) at (0,0) {$v$};
  1905. \node (w) at (2,0) {$w$};
  1906. \node (x) at (4,0) {$x$};
  1907. \node (t1) at (6,0) {$t.1$};
  1908. \node (y) at (2,-2) {$y$};
  1909. \node (z) at (4,-2) {$z$};
  1910. \node (t2) at (6,-2) {$t.2$};
  1911. \draw (v) to (w);
  1912. \foreach \i in {w,x,y}
  1913. {
  1914. \foreach \j in {w,x,y}
  1915. {
  1916. \draw (\i) to (\j);
  1917. }
  1918. }
  1919. \draw (z) to (w);
  1920. \draw (z) to (y);
  1921. \draw (t1) to (z);
  1922. \draw (t2) to (t1);
  1923. \end{tikzpicture}
  1924. \]
  1925. \caption{The interference graph of the example program.}
  1926. \label{fig:interfere}
  1927. \end{figure}
  1928. Our next concern is to choose a data structure for representing the
  1929. interference graph. There are many standard choices for how to
  1930. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  1931. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  1932. structure is to study the algorithm that uses the data structure,
  1933. determine what operations need to be performed, and then choose the
  1934. data structure that provide the most efficient implementations of
  1935. those operations. Often times the choice of data structure can have an
  1936. effect on the time complexity of the algorithm, as it does here. If
  1937. you skim the next section, you will see that the register allocation
  1938. algorithm needs to ask the graph for all of its vertices and, given a
  1939. vertex, it needs to known all of the adjacent vertices. Thus, the
  1940. correct choice of graph representation is that of an adjacency
  1941. list. There are helper functions in \code{utilities.rkt} for
  1942. representing graphs using the adjacency list representation:
  1943. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  1944. (Appendix~\ref{appendix:utilities}). In particular, those functions
  1945. use a hash table to map each vertex to the set of adjacent vertices,
  1946. and the sets are represented using Racket's \key{set}, which is also a
  1947. hash table.
  1948. \begin{exercise}\normalfont
  1949. Implement the compiler pass named \code{build-interference} according
  1950. to the algorithm suggested above. The output of this pass should
  1951. replace the live-after sets with the interference $\itm{graph}$ as
  1952. follows.
  1953. \begin{lstlisting}
  1954. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1955. \end{lstlisting}
  1956. \end{exercise}
  1957. \section{Graph Coloring via Sudoku}
  1958. \label{sec:graph-coloring}
  1959. We now come to the main event, mapping variables to registers (or to
  1960. stack locations in the event that we run out of registers). We need
  1961. to make sure not to map two variables to the same register if the two
  1962. variables interfere with each other. In terms of the interference
  1963. graph, this means we cannot map adjacent nodes to the same register.
  1964. If we think of registers as colors, the register allocation problem
  1965. becomes the widely-studied graph coloring
  1966. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1967. The reader may be more familiar with the graph coloring problem then he
  1968. or she realizes; the popular game of Sudoku is an instance of the
  1969. graph coloring problem. The following describes how to build a graph
  1970. out of an initial Sudoku board.
  1971. \begin{itemize}
  1972. \item There is one node in the graph for each Sudoku square.
  1973. \item There is an edge between two nodes if the corresponding squares
  1974. are in the same row, in the same column, or if the squares are in
  1975. the same $3\times 3$ region.
  1976. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1977. \item Based on the initial assignment of numbers to squares in the
  1978. Sudoku board, assign the corresponding colors to the corresponding
  1979. nodes in the graph.
  1980. \end{itemize}
  1981. If you can color the remaining nodes in the graph with the nine
  1982. colors, then you have also solved the corresponding game of Sudoku.
  1983. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  1984. the corresponding graph with colored vertices. We map the Sudoku
  1985. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  1986. sampling of the vertices (those that are colored) because showing
  1987. edges for all of the vertices would make the graph unreadable.
  1988. \begin{figure}[tbp]
  1989. \includegraphics[width=0.45\textwidth]{sudoku}
  1990. \includegraphics[width=0.5\textwidth]{sudoku-graph}
  1991. \caption{A Sudoku game board and the corresponding colored graph.}
  1992. \label{fig:sudoku-graph}
  1993. \end{figure}
  1994. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1995. come up with an algorithm for allocating registers. For example, one
  1996. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1997. that you use a process of elimination to determine what numbers no
  1998. longer make sense for a square, and write down those numbers in the
  1999. square (writing very small). For example, if the number $1$ is
  2000. assigned to a square, then by process of elimination, you can write
  2001. the pencil mark $1$ in all the squares in the same row, column, and
  2002. region. Many Sudoku computer games provide automatic support for
  2003. Pencil Marks. This heuristic also reduces the degree of branching in
  2004. the search tree.
  2005. The Pencil Marks technique corresponds to the notion of color
  2006. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2007. node, in Sudoku terms, is the set of colors that are no longer
  2008. available. In graph terminology, we have the following definition:
  2009. \begin{equation*}
  2010. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  2011. \text{ and } \mathrm{color}(v) = c \}
  2012. \end{equation*}
  2013. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  2014. Using the Pencil Marks technique leads to a simple strategy for
  2015. filling in numbers: if there is a square with only one possible number
  2016. left, then write down that number! But what if there are no squares
  2017. with only one possibility left? One brute-force approach is to just
  2018. make a guess. If that guess ultimately leads to a solution, great. If
  2019. not, backtrack to the guess and make a different guess. Of course,
  2020. backtracking can be horribly time consuming. One standard way to
  2021. reduce the amount of backtracking is to use the most-constrained-first
  2022. heuristic. That is, when making a guess, always choose a square with
  2023. the fewest possibilities left (the node with the highest saturation).
  2024. The idea is that choosing highly constrained squares earlier rather
  2025. than later is better because later there may not be any possibilities.
  2026. In some sense, register allocation is easier than Sudoku because we
  2027. can always cheat and add more numbers by mapping variables to the
  2028. stack. We say that a variable is \emph{spilled} when we decide to map
  2029. it to a stack location. We would like to minimize the time needed to
  2030. color the graph, and backtracking is expensive. Thus, it makes sense
  2031. to keep the most-constrained-first heuristic but drop the backtracking
  2032. in favor of greedy search (guess and just keep going).
  2033. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2034. greedy algorithm for register allocation based on saturation and the
  2035. most-constrained-first heuristic, which is roughly equivalent to the
  2036. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2037. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2038. as in Sudoku, the algorithm represents colors with integers, with the
  2039. first $k$ colors corresponding to the $k$ registers in a given machine
  2040. and the rest of the integers corresponding to stack locations.
  2041. \begin{figure}[btp]
  2042. \centering
  2043. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2044. Algorithm: DSATUR
  2045. Input: a graph |$G$|
  2046. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  2047. |$W \gets \mathit{vertices}(G)$|
  2048. while |$W \neq \emptyset$| do
  2049. pick a node |$u$| from |$W$| with the highest saturation,
  2050. breaking ties randomly
  2051. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  2052. |$\mathrm{color}[u] \gets c$|
  2053. |$W \gets W - \{u\}$|
  2054. \end{lstlisting}
  2055. \caption{The saturation-based greedy graph coloring algorithm.}
  2056. \label{fig:satur-algo}
  2057. \end{figure}
  2058. With this algorithm in hand, let us return to the running example and
  2059. consider how to color the interference graph in
  2060. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2061. register allocation because we use it to patch instructions, so we
  2062. remove that vertex from the graph. Initially, all of the nodes are
  2063. not yet colored and they are unsaturated, so we annotate each of them
  2064. with a dash for their color and an empty set for the saturation.
  2065. \[
  2066. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2067. \node (v) at (0,0) {$v:-,\{\}$};
  2068. \node (w) at (3,0) {$w:-,\{\}$};
  2069. \node (x) at (6,0) {$x:-,\{\}$};
  2070. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2071. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2072. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2073. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2074. \draw (v) to (w);
  2075. \foreach \i in {w,x,y}
  2076. {
  2077. \foreach \j in {w,x,y}
  2078. {
  2079. \draw (\i) to (\j);
  2080. }
  2081. }
  2082. \draw (z) to (w);
  2083. \draw (z) to (y);
  2084. \draw (t1) to (z);
  2085. \draw (t2) to (t1);
  2086. \end{tikzpicture}
  2087. \]
  2088. We select a maximally saturated node and color it $0$. In this case we
  2089. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2090. as no longer available for $w$, $x$, and $z$ because they interfere
  2091. with $y$.
  2092. \[
  2093. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2094. \node (v) at (0,0) {$v:-,\{\}$};
  2095. \node (w) at (3,0) {$w:-,\{0\}$};
  2096. \node (x) at (6,0) {$x:-,\{0\}$};
  2097. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2098. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2099. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2100. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2101. \draw (v) to (w);
  2102. \foreach \i in {w,x,y}
  2103. {
  2104. \foreach \j in {w,x,y}
  2105. {
  2106. \draw (\i) to (\j);
  2107. }
  2108. }
  2109. \draw (z) to (w);
  2110. \draw (z) to (y);
  2111. \draw (t1) to (z);
  2112. \draw (t2) to (t1);
  2113. \end{tikzpicture}
  2114. \]
  2115. Now we repeat the process, selecting another maximally saturated node.
  2116. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2117. $w$ with $1$.
  2118. \[
  2119. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2120. \node (v) at (0,0) {$v:-,\{1\}$};
  2121. \node (w) at (3,0) {$w:1,\{0\}$};
  2122. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2123. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2124. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2125. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2126. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2127. \draw (t1) to (z);
  2128. \draw (t2) to (t1);
  2129. \draw (v) to (w);
  2130. \foreach \i in {w,x,y}
  2131. {
  2132. \foreach \j in {w,x,y}
  2133. {
  2134. \draw (\i) to (\j);
  2135. }
  2136. }
  2137. \draw (z) to (w);
  2138. \draw (z) to (y);
  2139. \end{tikzpicture}
  2140. \]
  2141. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  2142. next available color which is $2$.
  2143. \[
  2144. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2145. \node (v) at (0,0) {$v:-,\{1\}$};
  2146. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2147. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2148. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2149. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2150. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2151. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2152. \draw (t1) to (z);
  2153. \draw (t2) to (t1);
  2154. \draw (v) to (w);
  2155. \foreach \i in {w,x,y}
  2156. {
  2157. \foreach \j in {w,x,y}
  2158. {
  2159. \draw (\i) to (\j);
  2160. }
  2161. }
  2162. \draw (z) to (w);
  2163. \draw (z) to (y);
  2164. \end{tikzpicture}
  2165. \]
  2166. Node $z$ is the next most highly saturated, so we color $z$ with $2$.
  2167. \[
  2168. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2169. \node (v) at (0,0) {$v:-,\{1\}$};
  2170. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2171. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2172. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2173. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2174. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2175. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2176. \draw (t1) to (z);
  2177. \draw (t2) to (t1);
  2178. \draw (v) to (w);
  2179. \foreach \i in {w,x,y}
  2180. {
  2181. \foreach \j in {w,x,y}
  2182. {
  2183. \draw (\i) to (\j);
  2184. }
  2185. }
  2186. \draw (z) to (w);
  2187. \draw (z) to (y);
  2188. \end{tikzpicture}
  2189. \]
  2190. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2191. $0$.
  2192. \[
  2193. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2194. \node (v) at (0,0) {$v:0,\{1\}$};
  2195. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2196. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2197. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2198. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2199. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2200. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2201. \draw (t1) to (z);
  2202. \draw (t2) to (t1);
  2203. \draw (v) to (w);
  2204. \foreach \i in {w,x,y}
  2205. {
  2206. \foreach \j in {w,x,y}
  2207. {
  2208. \draw (\i) to (\j);
  2209. }
  2210. }
  2211. \draw (z) to (w);
  2212. \draw (z) to (y);
  2213. \end{tikzpicture}
  2214. \]
  2215. In the last two steps of the algorithm, we color $t.1$ with $0$
  2216. then $t.2$ with $1$.
  2217. \[
  2218. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2219. \node (v) at (0,0) {$v:0,\{1\}$};
  2220. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2221. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2222. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2223. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2224. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2225. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2226. \draw (t1) to (z);
  2227. \draw (t2) to (t1);
  2228. \draw (v) to (w);
  2229. \foreach \i in {w,x,y}
  2230. {
  2231. \foreach \j in {w,x,y}
  2232. {
  2233. \draw (\i) to (\j);
  2234. }
  2235. }
  2236. \draw (z) to (w);
  2237. \draw (z) to (y);
  2238. \end{tikzpicture}
  2239. \]
  2240. With the coloring complete, we can finalize the assignment of
  2241. variables to registers and stack locations. Recall that if we have $k$
  2242. registers, we map the first $k$ colors to registers and the rest to
  2243. stack locations. Suppose for the moment that we just have one extra
  2244. register to use for register allocation, just \key{rbx}. Then the
  2245. following is the mapping of colors to registers and stack allocations.
  2246. \[
  2247. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2248. \]
  2249. Putting this mapping together with the above coloring of the variables, we
  2250. arrive at the assignment:
  2251. \begin{gather*}
  2252. \{ v \mapsto \key{\%rbx}, \,
  2253. w \mapsto \key{-8(\%rbp)}, \,
  2254. x \mapsto \key{-16(\%rbp)}, \,
  2255. y \mapsto \key{\%rbx}, \,
  2256. z\mapsto \key{-16(\%rbp)}, \\
  2257. t.1\mapsto \key{\%rbx} ,\,
  2258. t.2\mapsto \key{-8(\%rbp)} \}
  2259. \end{gather*}
  2260. Applying this assignment to our running example
  2261. (Figure~\ref{fig:reg-eg}) yields the program on the right.\\
  2262. % why frame size of 32? -JGS
  2263. \begin{minipage}{0.4\textwidth}
  2264. \begin{lstlisting}
  2265. (program (v w x y z)
  2266. (movq (int 1) (var v))
  2267. (movq (int 46) (var w))
  2268. (movq (var v) (var x))
  2269. (addq (int 7) (var x))
  2270. (movq (var x) (var y))
  2271. (addq (int 4) (var y))
  2272. (movq (var x) (var z))
  2273. (addq (var w) (var z))
  2274. (movq (var y) (var t.1))
  2275. (negq (var t.1))
  2276. (movq (var z) (var t.2))
  2277. (addq (var t.1) (var t.2))
  2278. (movq (var t.2) (reg rax)))
  2279. \end{lstlisting}
  2280. \end{minipage}
  2281. $\Rightarrow$
  2282. \begin{minipage}{0.45\textwidth}
  2283. \begin{lstlisting}
  2284. (program 16
  2285. (movq (int 1) (reg rbx))
  2286. (movq (int 46) (deref rbp -8))
  2287. (movq (reg rbx) (deref rbp -16))
  2288. (addq (int 7) (deref rbp -16))
  2289. (movq (deref rbp -16) (reg rbx))
  2290. (addq (int 4) (reg rbx))
  2291. (movq (deref rbp -16) (deref rbp -16))
  2292. (addq (deref rbp -8) (deref rbp -16))
  2293. (movq (reg rbx) (reg rbx))
  2294. (negq (reg rbx))
  2295. (movq (deref rbp -16) (deref rbp -8))
  2296. (addq (reg rbx) (deref rbp -8))
  2297. (movq (deref rbp -8) (reg rax)))
  2298. \end{lstlisting}
  2299. \end{minipage}
  2300. The resulting program is almost an x86 program. The remaining step
  2301. is to apply the patch instructions pass. In this example, the trivial
  2302. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2303. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2304. \code{rax}. The following shows the portion of the program that
  2305. changed.
  2306. \begin{lstlisting}
  2307. (addq (int 4) (reg rbx))
  2308. (movq (deref rbp -8) (reg rax)
  2309. (addq (reg rax) (deref rbp -16))
  2310. \end{lstlisting}
  2311. An overview of all of the passes involved in register allocation is
  2312. shown in Figure~\ref{fig:reg-alloc-passes}.
  2313. \begin{figure}[p]
  2314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2315. \node (R1) at (0,2) {\large $R_1$};
  2316. \node (R1-2) at (3,2) {\large $R_1$};
  2317. \node (C0-1) at (3,0) {\large $C_0$};
  2318. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2319. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2320. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2321. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2322. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2323. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2324. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2325. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2326. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2327. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2328. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2329. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2330. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2331. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2332. \end{tikzpicture}
  2333. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2334. \label{fig:reg-alloc-passes}
  2335. \end{figure}
  2336. \begin{exercise}\normalfont
  2337. Implement the pass \code{allocate-registers} and test it by creating
  2338. new example programs that exercise all of the register allocation
  2339. algorithm, such as forcing variables to be spilled to the stack.
  2340. I recommend organizing our code by creating a helper function named
  2341. \code{color-graph} that takes an interference graph and a list of all
  2342. the variables in the program. This function should return a mapping of
  2343. variables to their colors. By creating this helper function, we will
  2344. be able to reuse it in Chapter~\ref{ch:functions} when we add support
  2345. for functions. Once you have obtained the coloring from
  2346. \code{color-graph}, you can assign the variables to registers or stack
  2347. locations based on their color and then use the \code{assign-homes}
  2348. function from Section~\ref{sec:assign-s0} to replace the variables
  2349. with their assigned location.
  2350. \end{exercise}
  2351. \section{Print x86 and Conventions for Registers}
  2352. \label{sec:print-x86-reg-alloc}
  2353. Recall the the \code{print-x86} pass generates the prelude and
  2354. conclusion instructions for the \code{main} function. The prelude
  2355. saved the values in \code{rbp} and \code{rsp} and the conclusion
  2356. returned those values to \code{rbp} and \code{rsp}. The reason for
  2357. this is that there are agreed-upon conventions for how different
  2358. functions share the same fixed set of registers. There is a function
  2359. inside the operating system (OS) that calls our \code{main} function,
  2360. and that OS function uses the same registers that we use in
  2361. \code{main}. The convention for x86 is that the caller is responsible
  2362. for freeing up some registers, the \emph{caller save registers}, prior
  2363. to the function call, and the callee is responsible for saving and
  2364. restoring some other registers, the \emph{callee save registers},
  2365. before and after using them. The caller save registers are
  2366. \begin{lstlisting}
  2367. rax rdx rcx rsi rdi r8 r9 r10 r11
  2368. \end{lstlisting}
  2369. while the callee save registers are
  2370. \begin{lstlisting}
  2371. rsp rbp rbx r12 r13 r14 r15
  2372. \end{lstlisting}
  2373. Another way to think about this caller/callee convention is the
  2374. following. The caller should assume that all the caller save registers
  2375. get overwritten with arbitrary values by the callee. On the other
  2376. hand, the caller can safely assume that all the callee save registers
  2377. contain the same values after the call that they did before the call.
  2378. The callee can freely use any of the caller save registers. However,
  2379. if the callee wants to use a callee save register, the callee must
  2380. arrange to put the original value back in the register prior to
  2381. returning to the caller, which is usually accomplished by saving and
  2382. restoring the value from the stack.
  2383. The upshot of these conventions is that the \code{main} function needs
  2384. to save (in the prelude) and restore (in the conclusion) any callee
  2385. save registers that get used during register allocation. The simplest
  2386. approach is to save and restore all the callee save registers. The
  2387. more efficient approach is to keep track of which callee save
  2388. registers were used and only save and restore them. Either way, make
  2389. sure to take this use of stack space into account when you round up
  2390. the size of the frame to make sure it is a multiple of 16 bytes.
  2391. \section{Challenge: Move Biasing$^{*}$}
  2392. \label{sec:move-biasing}
  2393. This section describes an optional enhancement to register allocation
  2394. for those students who are looking for an extra challenge or who have
  2395. a deeper interest in register allocation.
  2396. We return to the running example, but we remove the supposition that
  2397. we only have one register to use. So we have the following mapping of
  2398. color numbers to registers.
  2399. \[
  2400. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2401. \]
  2402. Using the same assignment that was produced by register allocator
  2403. described in the last section, we get the following program.
  2404. \begin{minipage}{0.45\textwidth}
  2405. \begin{lstlisting}
  2406. (program (v w x y z)
  2407. (movq (int 1) (var v))
  2408. (movq (int 46) (var w))
  2409. (movq (var v) (var x))
  2410. (addq (int 7) (var x))
  2411. (movq (var x) (var y))
  2412. (addq (int 4) (var y))
  2413. (movq (var x) (var z))
  2414. (addq (var w) (var z))
  2415. (movq (var y) (var t.1))
  2416. (negq (var t.1))
  2417. (movq (var z) (var t.2))
  2418. (addq (var t.1) (var t.2))
  2419. (movq (var t.2) (reg rax)))
  2420. \end{lstlisting}
  2421. \end{minipage}
  2422. $\Rightarrow$
  2423. \begin{minipage}{0.45\textwidth}
  2424. \begin{lstlisting}
  2425. (program 0
  2426. (movq (int 1) (reg rbx))
  2427. (movq (int 46) (reg rcx))
  2428. (movq (reg rbx) (reg rdx))
  2429. (addq (int 7) (reg rdx))
  2430. (movq (reg rdx) (reg rbx))
  2431. (addq (int 4) (reg rbx))
  2432. (movq (reg rdx) (reg rdx))
  2433. (addq (reg rcx) (reg rdx))
  2434. (movq (reg rbx) (reg rbx))
  2435. (negq (reg rbx))
  2436. (movq (reg rdx) (reg rcx))
  2437. (addq (reg rbx) (reg rcx))
  2438. (movq (reg rcx) (reg rax)))
  2439. \end{lstlisting}
  2440. \end{minipage}
  2441. While this allocation is quite good, we could do better. For example,
  2442. the variables \key{v} and \key{x} ended up in different registers, but
  2443. if they had been placed in the same register, then the move from
  2444. \key{v} to \key{x} could be removed.
  2445. We say that two variables $p$ and $q$ are \emph{move related} if they
  2446. participate together in a \key{movq} instruction, that is, \key{movq
  2447. p, q} or \key{movq q, p}. When the register allocator chooses a
  2448. color for a variable, it should prefer a color that has already been
  2449. used for a move-related variable (assuming that they do not
  2450. interfere). Of course, this preference should not override the
  2451. preference for registers over stack locations, but should only be used
  2452. as a tie breaker when choosing between registers or when choosing
  2453. between stack locations.
  2454. We recommend that you represent the move relationships in a graph,
  2455. similar to how we represented interference. The following is the
  2456. \emph{move graph} for our running example.
  2457. \[
  2458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2459. \node (v) at (0,0) {$v$};
  2460. \node (w) at (3,0) {$w$};
  2461. \node (x) at (6,0) {$x$};
  2462. \node (y) at (3,-1.5) {$y$};
  2463. \node (z) at (6,-1.5) {$z$};
  2464. \node (t1) at (9,0) {$t.1$};
  2465. \node (t2) at (9,-1.5) {$t.2$};
  2466. \draw (t1) to (y);
  2467. \draw (t2) to (z);
  2468. \draw[bend left=20] (v) to (x);
  2469. \draw (x) to (y);
  2470. \draw (x) to (z);
  2471. \end{tikzpicture}
  2472. \]
  2473. Now we replay the graph coloring, pausing to see the coloring of $z$
  2474. and $v$. So we have the following coloring so far and the most
  2475. saturated vertex is $z$.
  2476. \[
  2477. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2478. \node (v) at (0,0) {$v:-,\{1\}$};
  2479. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2480. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2481. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2482. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2483. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2484. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2485. \draw (t1) to (z);
  2486. \draw (t2) to (t1);
  2487. \draw (v) to (w);
  2488. \foreach \i in {w,x,y}
  2489. {
  2490. \foreach \j in {w,x,y}
  2491. {
  2492. \draw (\i) to (\j);
  2493. }
  2494. }
  2495. \draw (z) to (w);
  2496. \draw (z) to (y);
  2497. \end{tikzpicture}
  2498. \]
  2499. Last time we chose to color $z$ with $2$, which so happens to be the
  2500. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2501. and if the program had been a little different, and say $x$ had been
  2502. already assigned to $3$, then $z$ would still get $2$ and our luck
  2503. would have run out. With move biasing, we use the fact that $z$ and
  2504. $x$ are move related to influence the choice of color for $z$, in this
  2505. case choosing $2$ because that's the color of $x$.
  2506. \[
  2507. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2508. \node (v) at (0,0) {$v:-,\{1\}$};
  2509. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2510. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2511. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2512. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2513. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2514. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2515. \draw (t1) to (z);
  2516. \draw (t2) to (t1);
  2517. \draw (v) to (w);
  2518. \foreach \i in {w,x,y}
  2519. {
  2520. \foreach \j in {w,x,y}
  2521. {
  2522. \draw (\i) to (\j);
  2523. }
  2524. }
  2525. \draw (z) to (w);
  2526. \draw (z) to (y);
  2527. \end{tikzpicture}
  2528. \]
  2529. Next we consider coloring the variable $v$, and we just need to avoid
  2530. choosing $1$ because of the interference with $w$. Last time we choose
  2531. the color $0$, simply because it was the lowest, but this time we know
  2532. that $v$ is move related to $x$, so we choose the color $2$.
  2533. \[
  2534. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2535. \node (v) at (0,0) {$v:2,\{1\}$};
  2536. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2537. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2538. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2539. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2540. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2541. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2542. \draw (t1) to (z);
  2543. \draw (t2) to (t1);
  2544. \draw (v) to (w);
  2545. \foreach \i in {w,x,y}
  2546. {
  2547. \foreach \j in {w,x,y}
  2548. {
  2549. \draw (\i) to (\j);
  2550. }
  2551. }
  2552. \draw (z) to (w);
  2553. \draw (z) to (y);
  2554. \end{tikzpicture}
  2555. \]
  2556. We apply this register assignment to the running example, on the left,
  2557. to obtain the code on right.
  2558. \begin{minipage}{0.45\textwidth}
  2559. \begin{lstlisting}
  2560. (program (v w x y z)
  2561. (movq (int 1) (var v))
  2562. (movq (int 46) (var w))
  2563. (movq (var v) (var x))
  2564. (addq (int 7) (var x))
  2565. (movq (var x) (var y))
  2566. (addq (int 4) (var y))
  2567. (movq (var x) (var z))
  2568. (addq (var w) (var z))
  2569. (movq (var y) (var t.1))
  2570. (negq (var t.1))
  2571. (movq (var z) (var t.2))
  2572. (addq (var t.1) (var t.2))
  2573. (movq (var t.2) (reg rax)))
  2574. \end{lstlisting}
  2575. \end{minipage}
  2576. $\Rightarrow$
  2577. \begin{minipage}{0.45\textwidth}
  2578. \begin{lstlisting}
  2579. (program 0
  2580. (movq (int 1) (reg rdx))
  2581. (movq (int 46) (reg rcx))
  2582. (movq (reg rdx) (reg rdx))
  2583. (addq (int 7) (reg rdx))
  2584. (movq (reg rdx) (reg rbx))
  2585. (addq (int 4) (reg rbx))
  2586. (movq (reg rdx) (reg rdx))
  2587. (addq (reg rcx) (reg rdx))
  2588. (movq (reg rbx) (reg rbx))
  2589. (negq (reg rbx))
  2590. (movq (reg rdx) (reg rcx))
  2591. (addq (reg rbx) (reg rcx))
  2592. (movq (reg rcx) (reg rax)))
  2593. \end{lstlisting}
  2594. \end{minipage}
  2595. The \code{patch-instructions} then removes the trivial moves from
  2596. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2597. \key{t.1}, to obtain the following result.
  2598. \begin{lstlisting}
  2599. (program 0
  2600. (movq (int 1) (reg rdx))
  2601. (movq (int 46) (reg rcx))
  2602. (addq (int 7) (reg rdx))
  2603. (movq (reg rdx) (reg rbx))
  2604. (addq (int 4) (reg rbx))
  2605. (addq (reg rcx) (reg rdx))
  2606. (negq (reg rbx))
  2607. (movq (reg rdx) (reg rcx))
  2608. (addq (reg rbx) (reg rcx))
  2609. (movq (reg rcx) (reg rax)))
  2610. \end{lstlisting}
  2611. \begin{exercise}\normalfont
  2612. Change your implementation of \code{allocate-registers} to take move
  2613. biasing into account. Make sure that your compiler still passes all of
  2614. the previous tests. Create two new tests that include at least one
  2615. opportunity for move biasing and visually inspect the output x86
  2616. programs to make sure that your move biasing is working properly.
  2617. \end{exercise}
  2618. \marginpar{\footnotesize To do: another neat challenge would be to do
  2619. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2620. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2621. \chapter{Booleans, Control Flow, and Type Checking}
  2622. \label{ch:bool-types}
  2623. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2624. integers. In this Chapter we add a second kind of value, the Booleans,
  2625. to create the $R_2$ language. The Boolean values \emph{true} and
  2626. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2627. Racket. We also introduce several operations that involve Booleans
  2628. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2629. \key{if} expression. With the addition of \key{if} expressions,
  2630. programs can have non-trivial control flow which has an impact on
  2631. several parts of the compiler. Also, because we now have two kinds of
  2632. values, we need to worry about programs that apply an operation to the
  2633. wrong kind of value, such as \code{(not 1)}.
  2634. There are two language design options for such situations. One option
  2635. is to signal an error and the other is to provide a wider
  2636. interpretation of the operation. The Racket language uses a mixture of
  2637. these two options, depending on the operation and the kind of
  2638. value. For example, the result of \code{(not 1)} in Racket is
  2639. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2640. the other hand, \code{(car 1)} results in a run-time error in Racket
  2641. stating that \code{car} expects a pair.
  2642. The Typed Racket language makes similar design choices as Racket,
  2643. except much of the error detection happens at compile time instead of
  2644. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2645. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2646. reports a compile-time error because the type of the argument is
  2647. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2648. For the $R_2$ language we choose to be more like Typed Racket in that
  2649. we shall perform type checking during compilation. In
  2650. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2651. is, how to compile a dynamically typed language like Racket. The
  2652. $R_2$ language is a subset of Typed Racket but by no means includes
  2653. all of Typed Racket. Furthermore, for many of the operations we shall
  2654. take a narrower interpretation than Typed Racket, for example,
  2655. rejecting \code{(not 1)}.
  2656. This chapter is organized as follows. We begin by defining the syntax
  2657. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2658. then introduce the idea of type checking and build a type checker for
  2659. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2660. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2661. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2662. how our compiler passes need to change to accommodate Booleans and
  2663. conditional control flow.
  2664. \section{The $R_2$ Language}
  2665. \label{sec:r2-lang}
  2666. The syntax of the $R_2$ language is defined in
  2667. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray) ,
  2668. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2669. \code{if} expression. Also, we expand the operators to include the
  2670. \key{and} and \key{not} on Booleans, the \key{eq?} operations for
  2671. comparing two integers or two Booleans, and the \key{<}, \key{<=},
  2672. \key{>}, and \key{>=} operations for comparing integers.
  2673. \begin{figure}[tp]
  2674. \centering
  2675. \fbox{
  2676. \begin{minipage}{0.96\textwidth}
  2677. \[
  2678. \begin{array}{lcl}
  2679. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2680. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2681. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2682. &\mid& \key{\#t} \mid \key{\#f} \mid
  2683. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2684. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2685. R_2 &::=& (\key{program} \; \Exp)
  2686. \end{array}
  2687. \]
  2688. \end{minipage}
  2689. }
  2690. \caption{The syntax of $R_2$, extending $R_1$ with Booleans and
  2691. conditionals.}
  2692. \label{fig:r2-syntax}
  2693. \end{figure}
  2694. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2695. the parts that are the same as the interpreter for $R_1$
  2696. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2697. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2698. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2699. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2700. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2701. operations \code{not} and \code{and} behave as you might expect, but
  2702. note that the \code{and} operation is short-circuiting. That is, given
  2703. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2704. evaluated if $e_1$ evaluates to \code{\#f}.
  2705. With the addition of the comparison operations, there are quite a few
  2706. primitive operations and the interpreter code for them is somewhat
  2707. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2708. parts into the \code{interp-op} function and the similar parts into
  2709. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2710. important for that match clause to come last because it matches
  2711. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2712. the \code{and} operation because of the short-circuiting behavior in
  2713. the order of evaluation of its arguments.
  2714. \begin{figure}[tbp]
  2715. \begin{lstlisting}
  2716. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2717. (define (interp-op op)
  2718. (match op
  2719. ['+ fx+]
  2720. ['- (lambda (n) (fx- 0 n))]
  2721. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2722. ['read read-fixnum]
  2723. ['eq? (lambda (v1 v2)
  2724. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2725. (and (boolean? v1) (boolean? v2))
  2726. (and (vector? v1) (vector? v2)))
  2727. (eq? v1 v2)]))]
  2728. ['< (lambda (v1 v2)
  2729. (cond [(and (fixnum? v1) (fixnum? v2))
  2730. (< v1 v2)]))]
  2731. ['<= (lambda (v1 v2)
  2732. (cond [(and (fixnum? v1) (fixnum? v2))
  2733. (<= v1 v2)]))]
  2734. ['> (lambda (v1 v2)
  2735. (cond [(and (fixnum? v1) (fixnum? v2))
  2736. (<= v1 v2)]))]
  2737. ['>= (lambda (v1 v2)
  2738. (cond [(and (fixnum? v1) (fixnum? v2))
  2739. (<= v1 v2)]))]
  2740. [else (error 'interp-op "unknown operator")]))
  2741. (define (interp-R2 env)
  2742. (lambda (e)
  2743. (define recur (interp-R2 env))
  2744. (match e
  2745. ...
  2746. [(? boolean?) e]
  2747. [`(if ,(app recur cnd) ,thn ,els)
  2748. (match cnd
  2749. [#t (recur thn)]
  2750. [#f (recur els)])]
  2751. [`(not ,(app recur v))
  2752. (match v [#t #f] [#f #t])]
  2753. [`(and ,(app recur v1) ,e2)
  2754. (match v1
  2755. [#t (match (recur e2) [#t #t] [#f #f])]
  2756. [#f #f])]
  2757. [`(,op ,(app recur args) ...)
  2758. #:when (set-member? primitives op)
  2759. (apply (interp-op op) args)]
  2760. )))
  2761. \end{lstlisting}
  2762. \caption{Interpreter for the $R_2$ language.}
  2763. \label{fig:interp-R2}
  2764. \end{figure}
  2765. \section{Type Checking $R_2$ Programs}
  2766. \label{sec:type-check-r2}
  2767. It is helpful to think about type checking into two complementary
  2768. ways. A type checker predicts the \emph{type} of value that will be
  2769. produced by each expression in the program. For $R_2$, we have just
  2770. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2771. predict that
  2772. \begin{lstlisting}
  2773. (+ 10 (- (+ 12 20)))
  2774. \end{lstlisting}
  2775. produces an \key{Integer} while
  2776. \begin{lstlisting}
  2777. (and (not #f) #t)
  2778. \end{lstlisting}
  2779. produces a \key{Boolean}.
  2780. As mentioned at the beginning of this chapter, a type checker also
  2781. rejects programs that apply operators to the wrong type of value. Our
  2782. type checker for $R_2$ will signal an error for the following
  2783. expression because, as we have seen above, the expression \code{(+ 10
  2784. ...)} has type \key{Integer}, and we require the argument of a
  2785. \code{not} to have type \key{Boolean}.
  2786. \begin{lstlisting}
  2787. (not (+ 10 (- (+ 12 20))))
  2788. \end{lstlisting}
  2789. The type checker for $R_2$ is best implemented as a structurally
  2790. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2791. many of the clauses for the \code{typecheck-R2} function. Given an
  2792. input expression \code{e}, the type checker either returns the type
  2793. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2794. the type of an integer literal is \code{Integer} and the type of a
  2795. Boolean literal is \code{Boolean}. To handle variables, the type
  2796. checker, like the interpreter, uses an association list. However, in
  2797. this case the association list maps variables to types instead of
  2798. values. Consider the clause for \key{let}. We type check the
  2799. initializing expression to obtain its type \key{T} and then associate
  2800. type \code{T} with the variable \code{x}. When the type checker
  2801. encounters the use of a variable, it can lookup its type in the
  2802. association list.
  2803. \begin{figure}[tbp]
  2804. \begin{lstlisting}
  2805. (define (typecheck-R2 env)
  2806. (lambda (e)
  2807. (define recur (typecheck-R2 env e))
  2808. (match e
  2809. [(? fixnum?) 'Integer]
  2810. [(? boolean?) 'Boolean]
  2811. [(? symbol?) (lookup e env)]
  2812. [`(let ([,x ,(app recur T)]) ,body)
  2813. (define new-env (cons (cons x T) env))
  2814. (typecheck-R2 new-env body)]
  2815. ...
  2816. [`(not ,(app (typecheck-R2 env) T))
  2817. (match T
  2818. ['Boolean 'Boolean]
  2819. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2820. ...
  2821. [`(program ,body)
  2822. (define ty ((typecheck-R2 '()) body))
  2823. `(program (type ,ty) ,body)]
  2824. )))
  2825. \end{lstlisting}
  2826. \caption{Skeleton of a type checker for the $R_2$ language.}
  2827. \label{fig:type-check-R2}
  2828. \end{figure}
  2829. To print the resulting value correctly, the overall type of the
  2830. program must be threaded through the remainder of the passes. We can
  2831. store the type within the \key{program} form as shown in Figure
  2832. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  2833. programs as follows: \\
  2834. \fbox{
  2835. \begin{minipage}{0.87\textwidth}
  2836. \[
  2837. \begin{array}{lcl}
  2838. R_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  2839. \end{array}
  2840. \]
  2841. \end{minipage}
  2842. }
  2843. \begin{exercise}\normalfont
  2844. Complete the implementation of \code{typecheck-R2} and test it on 10
  2845. new example programs in $R_2$ that you choose based on how thoroughly
  2846. they test the type checking algorithm. Half of the example programs
  2847. should have a type error, to make sure that your type checker properly
  2848. rejects them. The other half of the example programs should not have
  2849. type errors. Your testing should check that the result of the type
  2850. checker agrees with the value returned by the interpreter, that is, if
  2851. the type checker returns \key{Integer}, then the interpreter should
  2852. return an integer. Likewise, if the type checker returns
  2853. \key{Boolean}, then the interpreter should return \code{\#t} or
  2854. \code{\#f}. Note that if your type checker does not signal an error
  2855. for a program, then interpreting that program should not encounter an
  2856. error. If it does, there is something wrong with your type checker.
  2857. \end{exercise}
  2858. \section{The $C_1$ Language}
  2859. \label{sec:c1}
  2860. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2861. As with $R_1$, we shall compile to a C-like intermediate language, but
  2862. we need to grow that intermediate language to handle the new features
  2863. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2864. we add logic and comparison operators to the $\Exp$ non-terminal, the
  2865. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  2866. add an \key{if} statement. The \key{if} statement of $C_1$ includes an
  2867. \key{eq?} test, which is needed for improving code generation in
  2868. Section~\ref{sec:opt-if}. We do not include \key{and} in $C_1$
  2869. because it is not needed in the translation of the \key{and} of $R_2$.
  2870. \begin{figure}[tp]
  2871. \fbox{
  2872. \begin{minipage}{0.96\textwidth}
  2873. \[
  2874. \begin{array}{lcl}
  2875. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  2876. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2877. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  2878. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  2879. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  2880. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  2881. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  2882. \end{array}
  2883. \]
  2884. \end{minipage}
  2885. }
  2886. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  2887. \label{fig:c1-syntax}
  2888. \end{figure}
  2889. \section{Flatten Expressions}
  2890. \label{sec:flatten-r2}
  2891. We expand the \code{flatten} pass to handle the Boolean literals
  2892. \key{\#t} and \key{\#f}, the new logic and comparison operations, and
  2893. \key{if} expressions. We shall start with a simple example of
  2894. translating a \key{if} expression, shown below on the left. \\
  2895. \begin{tabular}{lll}
  2896. \begin{minipage}{0.4\textwidth}
  2897. \begin{lstlisting}
  2898. (program (if #f 0 42))
  2899. \end{lstlisting}
  2900. \end{minipage}
  2901. &
  2902. $\Rightarrow$
  2903. &
  2904. \begin{minipage}{0.4\textwidth}
  2905. \begin{lstlisting}
  2906. (program (if.1)
  2907. (if (eq? #t #f)
  2908. ((assign if.1 0))
  2909. ((assign if.1 42)))
  2910. (return if.1))
  2911. \end{lstlisting}
  2912. \end{minipage}
  2913. \end{tabular} \\
  2914. The value of the \key{if} expression is the value of the branch that
  2915. is selected. Recall that in the \code{flatten} pass we need to replace
  2916. arbitrary expressions with $\Arg$'s (variables or literals). In the
  2917. translation above, on the right, we have replaced the \key{if}
  2918. expression with a new variable \key{if.1}, inside \code{(return
  2919. if.1)}, and we have produced code that will assign the appropriate
  2920. value to \key{if.1} using an \code{if} statement prior to the
  2921. \code{return}. For $R_1$, the \code{flatten} pass returned a list of
  2922. assignment statements. Here, for $R_2$, we return a list of statements
  2923. that can include both \key{if} statements and assignment statements.
  2924. The next example is a bit more involved, showing what happens when
  2925. there are complex expressions (not variables or literals) in the
  2926. condition and branch expressions of an \key{if}, including nested
  2927. \key{if} expressions.
  2928. \begin{tabular}{lll}
  2929. \begin{minipage}{0.4\textwidth}
  2930. \begin{lstlisting}
  2931. (program
  2932. (if (eq? (read) 0)
  2933. 777
  2934. (+ 2 (if (eq? (read) 0)
  2935. 40
  2936. 444))))
  2937. \end{lstlisting}
  2938. \end{minipage}
  2939. &
  2940. $\Rightarrow$
  2941. &
  2942. \begin{minipage}{0.4\textwidth}
  2943. \begin{lstlisting}
  2944. (program (t.1 t.2 if.1 t.3 t.4
  2945. if.2 t.5)
  2946. (assign t.1 (read))
  2947. (assign t.2 (eq? t.1 0))
  2948. (if (eq? #t t.2)
  2949. ((assign if.1 777))
  2950. ((assign t.3 (read))
  2951. (assign t.4 (eq? t.3 0))
  2952. (if (eq? #t t.4)
  2953. ((assign if.2 40))
  2954. ((assign if.2 444)))
  2955. (assign t.5 (+ 2 if.2))
  2956. (assign if.1 t.5)))
  2957. (return if.1))
  2958. \end{lstlisting}
  2959. \end{minipage}
  2960. \end{tabular} \\
  2961. The \code{flatten} clauses for the Boolean literals and the operations
  2962. \key{not} and \key{eq?} are straightforward. However, the
  2963. \code{flatten} clause for \key{and} requires some care to properly
  2964. imitate the order of evaluation of the interpreter for $R_2$
  2965. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  2966. in the code you generate for \key{and}.
  2967. The \code{flatten} clause for \key{if} also requires some care because
  2968. the condition of the \key{if} can be an arbitrary expression in $R_2$,
  2969. but in $C_1$ the condition must be an equality predicate. For now we
  2970. recommend flattening the condition into an $\Arg$ and then comparing
  2971. it with \code{\#t}. We discuss a more efficient approach in
  2972. Section~\ref{sec:opt-if}.
  2973. \begin{exercise}\normalfont
  2974. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2975. Boolean literals, the new logic and comparison operations, and the
  2976. \key{if} expressions. Create 4 more test cases that expose whether
  2977. your flattening code is correct. Test your \code{flatten} pass by
  2978. running the output programs with \code{interp-C}
  2979. (Appendix~\ref{appendix:interp}).
  2980. \end{exercise}
  2981. \section{XOR, Comparisons, and Control Flow in x86}
  2982. \label{sec:x86-1}
  2983. To implement the new logical operations, the comparison operations,
  2984. and the \key{if} statement, we need to delve further into the x86
  2985. language. Figure~\ref{fig:x86-2} defines the abstract syntax for a
  2986. larger subset of x86 that includes instructions for logical
  2987. operations, comparisons, and jumps.
  2988. One small challenge is that x86 does not provide an instruction that
  2989. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  2990. However, the \code{xorq} instruction can be used to encode \code{not}.
  2991. The \key{xorq} instruction takes two arguments, performs a pairwise
  2992. exclusive-or operation on each bit of its arguments, and writes the
  2993. results into its second argument. Recall the truth table for
  2994. exclusive-or:
  2995. \begin{center}
  2996. \begin{tabular}{l|cc}
  2997. & 0 & 1 \\ \hline
  2998. 0 & 0 & 1 \\
  2999. 1 & 1 & 0
  3000. \end{tabular}
  3001. \end{center}
  3002. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3003. in row of the table for the bit $1$, the result is the opposite of the
  3004. second bit. Thus, the \code{not} operation can be implemented by
  3005. \code{xorq} with $1$ as the first argument: $0001
  3006. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3007. 0001 = 0000$.
  3008. \begin{figure}[tp]
  3009. \fbox{
  3010. \begin{minipage}{0.96\textwidth}
  3011. \[
  3012. \begin{array}{lcl}
  3013. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3014. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3015. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3016. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3017. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3018. (\key{subq} \; \Arg\; \Arg) \mid
  3019. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3020. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3021. (\key{pushq}\;\Arg) \mid
  3022. (\key{popq}\;\Arg) \mid
  3023. (\key{retq})} \\
  3024. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3025. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3026. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3027. \mid (\key{jmp} \; \itm{label})
  3028. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3029. &\mid& (\key{label} \; \itm{label}) \\
  3030. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3031. \end{array}
  3032. \]
  3033. \end{minipage}
  3034. }
  3035. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3036. \label{fig:x86-1}
  3037. \end{figure}
  3038. Next we consider the x86 instructions that are relevant for
  3039. compiling the comparison operations. The \key{cmpq} instruction
  3040. compares its two arguments to determine whether one argument is less
  3041. than, equal, or greater than the other argument. The \key{cmpq}
  3042. instruction is unusual regarding the order of its arguments and where
  3043. the result is placed. The argument order is backwards: if you want to
  3044. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3045. \key{cmpq} is placed in the special EFLAGS register. This register
  3046. cannot be accessed directly but it can be queried by a number of
  3047. instructions, including the \key{set} instruction. The \key{set}
  3048. instruction puts a \key{1} or \key{0} into its destination depending
  3049. on whether the comparison came out according to the condition code
  3050. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3051. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3052. The set instruction has an annoying quirk in that its destination
  3053. argument must be single byte register, such as \code{al}, which is
  3054. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3055. instruction can then be used to move from a single byte register to a
  3056. normal 64-bit register.
  3057. For compiling the \key{if} expression, the x86 instructions for
  3058. jumping are relevant. The \key{jmp} instruction updates the program
  3059. counter to point to the instruction after the indicated label. The
  3060. \key{jmp-if} instruction updates the program counter to point to the
  3061. instruction after the indicated label depending on whether the result
  3062. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3063. the \key{jmp-if} instruction falls through to the next
  3064. instruction. Our abstract syntax for \key{jmp-if} differs from the
  3065. concrete syntax for x86 to separate the instruction name from the
  3066. condition code. For example, \code{(jmp-if le foo)} corresponds to
  3067. \code{jle foo}.
  3068. \section{Select Instructions}
  3069. \label{sec:select-r2}
  3070. The \code{select-instructions} pass lowers from $C_1$ to another
  3071. intermediate representation suitable for conducting register
  3072. allocation, that is, a language close to x86$_1$.
  3073. We can take the usual approach of encoding Booleans as integers, with
  3074. true as 1 and false as 0.
  3075. \[
  3076. \key{\#t} \Rightarrow \key{1}
  3077. \qquad
  3078. \key{\#f} \Rightarrow \key{0}
  3079. \]
  3080. The \code{not} operation can be implemented in terms of \code{xorq}
  3081. as we discussed at the beginning of this section.
  3082. %% Can you think of a bit pattern that, when XOR'd with the bit
  3083. %% representation of 0 produces 1, and when XOR'd with the bit
  3084. %% representation of 1 produces 0?
  3085. Translating the \code{eq?} and the other comparison operations to x86
  3086. is slightly involved due to the unusual nature of the \key{cmpq}
  3087. instruction discussed above. We recommend translating an assignment
  3088. from \code{eq?} into the following sequence of three instructions. \\
  3089. \begin{tabular}{lll}
  3090. \begin{minipage}{0.4\textwidth}
  3091. \begin{lstlisting}
  3092. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3093. \end{lstlisting}
  3094. \end{minipage}
  3095. &
  3096. $\Rightarrow$
  3097. &
  3098. \begin{minipage}{0.4\textwidth}
  3099. \begin{lstlisting}
  3100. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3101. (set e (byte-reg al))
  3102. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3103. \end{lstlisting}
  3104. \end{minipage}
  3105. \end{tabular} \\
  3106. % The translation of the \code{not} operator is not quite as simple
  3107. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3108. % one. For example, the following program performs bitwise negation on
  3109. % the integer 1:
  3110. %
  3111. % \begin{tabular}{lll}
  3112. % \begin{minipage}{0.4\textwidth}
  3113. % \begin{lstlisting}
  3114. % (movq (int 1) (reg rax))
  3115. % (notq (reg rax))
  3116. % \end{lstlisting}
  3117. % \end{minipage}
  3118. % \end{tabular}
  3119. %
  3120. % After the program is run, \key{rax} does not contain 0, as you might
  3121. % hope -- it contains the binary value $111\ldots10$, which is the
  3122. % two's complement representation of $-2$. We recommend implementing boolean
  3123. % not by using \key{notq} and then masking the upper bits of the result with
  3124. % the \key{andq} instruction.
  3125. Regarding \key{if} statements, we recommend delaying when they are
  3126. lowered until the \code{patch-instructions} pass. The reason is that
  3127. for purposes of liveness analysis, \key{if} statements are easier to
  3128. deal with than jump instructions.
  3129. \begin{exercise}\normalfont
  3130. Expand your \code{select-instructions} pass to handle the new features
  3131. of the $R_2$ language. Test the pass on all the examples you have
  3132. created and make sure that you have some test programs that use the
  3133. \code{eq?} operator, creating some if necessary. Test the output of
  3134. \code{select-instructions} using the \code{interp-x86} interpreter
  3135. (Appendix~\ref{appendix:interp}).
  3136. \end{exercise}
  3137. \section{Register Allocation}
  3138. \label{sec:register-allocation-r2}
  3139. The changes required for $R_2$ affect the liveness analysis, building
  3140. the interference graph, and assigning homes, but the graph coloring
  3141. algorithm itself does not need to change.
  3142. \subsection{Liveness Analysis}
  3143. \label{sec:liveness-analysis-r2}
  3144. The addition of \key{if} statements brings up an interesting issue in
  3145. liveness analysis. Recall that liveness analysis works backwards
  3146. through the program, for each instruction it computes the variables
  3147. that are live before the instruction based on which variables are live
  3148. after the instruction. Now consider the situation for \code{(\key{if}
  3149. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know
  3150. the $L_{\mathsf{after}}$ set and we need to produce the
  3151. $L_{\mathsf{before}}$ set. We can recursively perform liveness
  3152. analysis on the $\itm{thns}$ and $\itm{elss}$ branches, using
  3153. $L_{\mathsf{after}}$ as the starting point, to obtain
  3154. $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3155. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3156. know, during compilation, which way the branch will go, so we do not
  3157. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3158. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3159. the entire \key{if} statement. The solution comes from the observation
  3160. that there is no harm in identifying more variables as live than
  3161. absolutely necessary. Thus, we can take the union of the live
  3162. variables from the two branches to be the live set for the whole
  3163. \key{if}, as shown below. Of course, we also need to include the
  3164. variables that are read in $e_1$ and $e_2$.
  3165. \[
  3166. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3167. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3168. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3169. \]
  3170. We need the live-after sets for all the instructions in both branches
  3171. of the \key{if} when we build the interference graph, so I recommend
  3172. storing that data in the \key{if} statement AST as follows:
  3173. \begin{lstlisting}
  3174. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3175. \end{lstlisting}
  3176. If you wrote helper functions for computing the variables in an
  3177. instruction's argument and for computing the variables read-from ($R$)
  3178. or written-to ($W$) by an instruction, you need to be update them to
  3179. handle the new kinds of arguments and instructions in x86$_1$.
  3180. \subsection{Build Interference}
  3181. \label{sec:build-interference-r2}
  3182. Many of the new instructions, such as the logical operations, can be
  3183. handled in the same way as the arithmetic instructions. Thus, if your
  3184. code was already quite general, it will not need to be changed to
  3185. handle the logical operations. If not, I recommend that you change
  3186. your code to be more general. The \key{movzbq} instruction should be
  3187. handled like the \key{movq} instruction. The \key{if} statement is
  3188. straightforward to handle because we stored the live-after sets for
  3189. the two branches in the AST node as described above. Here we just need
  3190. to recursively process the two branches. The output of this pass can
  3191. discard the live after sets, as they are no longer needed.
  3192. \subsection{Assign Homes}
  3193. \label{sec:assign-homes-r2}
  3194. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3195. to be updated to handle the \key{if} statement, simply by recursively
  3196. processing the child nodes. Hopefully your code already handles the
  3197. other new instructions, but if not, you can generalize your code.
  3198. \begin{exercise}\normalfont
  3199. Implement the additions to the \code{register-allocation} pass so that
  3200. it works for $R_2$ and test your compiler using your previously
  3201. created programs on the \code{interp-x86} interpreter
  3202. (Appendix~\ref{appendix:interp}).
  3203. \end{exercise}
  3204. \section{Lower Conditionals (New Pass)}
  3205. \label{sec:lower-conditionals}
  3206. In the \code{select-instructions} pass we decided to procrastinate in
  3207. the lowering of the \key{if} statement, thereby making liveness
  3208. analysis easier. Now we need to make up for that and turn the \key{if}
  3209. statement into the appropriate instruction sequence. The following
  3210. translation gives the general idea. If the condition is true, we need
  3211. to execute the $\itm{thns}$ branch and otherwise we need to execute
  3212. the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3213. jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3214. is appropriate for the comparison operator \itm{cmp}. If the
  3215. condition is false, we fall through to the $\itm{elss}$ branch. At the
  3216. end of the $\itm{elss}$ branch we need to take care to not fall
  3217. through to the $\itm{thns}$ branch. So we jump to the
  3218. $\itm{endlabel}$. All of the labels in the generated code should be
  3219. created with \code{gensym}.
  3220. \begin{tabular}{lll}
  3221. \begin{minipage}{0.4\textwidth}
  3222. \begin{lstlisting}
  3223. (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3224. \end{lstlisting}
  3225. \end{minipage}
  3226. &
  3227. $\Rightarrow$
  3228. &
  3229. \begin{minipage}{0.4\textwidth}
  3230. \begin{lstlisting}
  3231. (cmpq |$\Arg_2$| |$\Arg_1$|)
  3232. (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3233. |$\itm{elss}$|
  3234. (jmp |$\itm{endlabel}$|)
  3235. (label |$\itm{thenlabel}$|)
  3236. |$\itm{thns}$|
  3237. (label |$\itm{endlabel}$|)
  3238. \end{lstlisting}
  3239. \end{minipage}
  3240. \end{tabular}
  3241. \begin{exercise}\normalfont
  3242. Implement the \code{lower-conditionals} pass. Test your compiler using
  3243. your previously created programs on the \code{interp-x86} interpreter
  3244. (Appendix~\ref{appendix:interp}).
  3245. \end{exercise}
  3246. \section{Patch Instructions}
  3247. There are no special restrictions on the instructions \key{jmp-if},
  3248. \key{jmp}, and \key{label}, but there is an unusual restriction on
  3249. \key{cmpq}. The second argument is not allowed to be an immediate
  3250. value (such as a literal integer). If you are comparing two
  3251. immediates, you must insert another \key{movq} instruction to put the
  3252. second argument in \key{rax}.
  3253. \begin{exercise}\normalfont
  3254. Update \code{patch-instructions} to handle the new x86 instructions.
  3255. Test your compiler using your previously created programs on the
  3256. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3257. \end{exercise}
  3258. \section{An Example Translation}
  3259. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3260. $R_2$ translated to x86, showing the results of \code{flatten},
  3261. \code{select-instructions}, and the final x86 assembly.
  3262. \begin{figure}[tbp]
  3263. \begin{tabular}{lll}
  3264. \begin{minipage}{0.5\textwidth}
  3265. \begin{lstlisting}
  3266. (program
  3267. (if (eq? (read) 1) 42 0))
  3268. \end{lstlisting}
  3269. $\Downarrow$
  3270. \begin{lstlisting}
  3271. (program (t.1 t.2 if.1)
  3272. (assign t.1 (read))
  3273. (assign t.2 (eq? t.1 1))
  3274. (if (eq? #t t.2)
  3275. ((assign if.1 42))
  3276. ((assign if.1 0)))
  3277. (return if.1))
  3278. \end{lstlisting}
  3279. $\Downarrow$
  3280. \begin{lstlisting}
  3281. (program (t.1 t.2 if.1)
  3282. (callq read_int)
  3283. (movq (reg rax) (var t.1))
  3284. (cmpq (int 1) (var t.1))
  3285. (set e (byte-reg al))
  3286. (movzbq (byte-reg al) (var t.2))
  3287. (if (eq? (int 1) (var t.2))
  3288. ((movq (int 42) (var if.1)))
  3289. ((movq (int 0) (var if.1))))
  3290. (movq (var if.1) (reg rax)))
  3291. \end{lstlisting}
  3292. \end{minipage}
  3293. &
  3294. $\Rightarrow$
  3295. \begin{minipage}{0.4\textwidth}
  3296. \begin{lstlisting}
  3297. .globl _main
  3298. _main:
  3299. pushq %rbp
  3300. movq %rsp, %rbp
  3301. pushq %r15
  3302. pushq %r14
  3303. pushq %r13
  3304. pushq %r12
  3305. pushq %rbx
  3306. subq $8, %rsp
  3307. callq _read_int
  3308. movq %rax, %rcx
  3309. cmpq $1, %rcx
  3310. sete %al
  3311. movzbq %al, %rcx
  3312. cmpq $1, %rcx
  3313. je then21288
  3314. movq $0, %rbx
  3315. jmp if_end21289
  3316. then21288:
  3317. movq $42, %rbx
  3318. if_end21289:
  3319. movq %rbx, %rax
  3320. movq %rax, %rdi
  3321. callq _print_int
  3322. movq $0, %rax
  3323. addq $8, %rsp
  3324. popq %rbx
  3325. popq %r12
  3326. popq %r13
  3327. popq %r14
  3328. popq %r15
  3329. popq %rbp
  3330. retq
  3331. \end{lstlisting}
  3332. \end{minipage}
  3333. \end{tabular}
  3334. \caption{Example compilation of an \key{if} expression to x86.}
  3335. \label{fig:if-example-x86}
  3336. \end{figure}
  3337. \begin{figure}[p]
  3338. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3339. \node (R1) at (0,2) {\large $R_1$};
  3340. \node (R1-2) at (3,2) {\large $R_1$};
  3341. \node (R1-3) at (6,2) {\large $R_1$};
  3342. \node (C1-1) at (3,0) {\large $C_1$};
  3343. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3344. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3345. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3346. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3347. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3348. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3349. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3350. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R1-2);
  3351. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  3352. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize\color{red} flatten} (C1-1);
  3353. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3354. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3355. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3356. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3357. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} lower-cond.} (x86-4);
  3358. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-5);
  3359. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3360. \end{tikzpicture}
  3361. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3362. \label{fig:R2-passes}
  3363. \end{figure}
  3364. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3365. for the compilation of $R_2$.
  3366. \section{Challenge: Optimizing Conditions$^{*}$}
  3367. \label{sec:opt-if}
  3368. A close inspection of the x86 code generated in
  3369. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3370. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3371. twice using \key{cmpq} as follows.
  3372. % Wierd LaTeX bug if I remove the following. -Jeremy
  3373. % Does it have to do with page breaks?
  3374. \begin{lstlisting}
  3375. \end{lstlisting}
  3376. \begin{lstlisting}
  3377. cmpq $1, %rcx
  3378. sete %al
  3379. movzbq %al, %rcx
  3380. cmpq $1, %rcx
  3381. je then21288
  3382. \end{lstlisting}
  3383. The reason for this non-optimal code has to do with the \code{flatten}
  3384. pass earlier in this Chapter. We recommended flattening the condition
  3385. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3386. is already an \code{eq?} test, then we would like to use that
  3387. directly. In fact, for many of the expressions of Boolean type, we can
  3388. generate more optimized code. For example, if the condition is
  3389. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3390. all. If the condition is a \code{let}, we can optimize based on the
  3391. form of its body. If the condition is a \code{not}, then we can flip
  3392. the two branches.
  3393. %
  3394. \marginpar{\tiny We could do even better by converting to basic
  3395. blocks.\\ --Jeremy}
  3396. %
  3397. On the other hand, if the condition is a \code{and}
  3398. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3399. code duplication.
  3400. Figure~\ref{fig:opt-if} shows an example program and the result of
  3401. applying the above suggested optimizations.
  3402. \begin{exercise}\normalfont
  3403. Change the \code{flatten} pass to improve the code that gets
  3404. generated for \code{if} expressions. We recommend writing a helper
  3405. function that recursively traverses the condition of the \code{if}.
  3406. \end{exercise}
  3407. \begin{figure}[tbp]
  3408. \begin{tabular}{lll}
  3409. \begin{minipage}{0.5\textwidth}
  3410. \begin{lstlisting}
  3411. (program
  3412. (if (let ([x 1])
  3413. (not (eq? 2 x)))
  3414. 42
  3415. 777))
  3416. \end{lstlisting}
  3417. $\Downarrow$
  3418. \begin{lstlisting}
  3419. (program (x.1 t.1 if.1)
  3420. (assign x.1 1)
  3421. (assign t.1 (read))
  3422. (if (eq? x.1 t.1)
  3423. ((assign if.1 42))
  3424. ((assign if.1 777)))
  3425. (return if.1))
  3426. \end{lstlisting}
  3427. $\Downarrow$
  3428. \begin{lstlisting}
  3429. (program (x.1 t.1 if.1)
  3430. (movq (int 1) (var x.1))
  3431. (callq read_int)
  3432. (movq (reg rax) (var t.1))
  3433. (if (eq? (var x.1) (var t.1))
  3434. ((movq (int 42) (var if.1)))
  3435. ((movq (int 777) (var if.1))))
  3436. (movq (var if.1) (reg rax)))
  3437. \end{lstlisting}
  3438. \end{minipage}
  3439. &
  3440. $\Rightarrow$
  3441. \begin{minipage}{0.4\textwidth}
  3442. \begin{lstlisting}
  3443. .globl _main
  3444. _main:
  3445. pushq %rbp
  3446. movq %rsp, %rbp
  3447. pushq %r15
  3448. pushq %r14
  3449. pushq %r13
  3450. pushq %r12
  3451. pushq %rbx
  3452. subq $8, %rsp
  3453. movq $1, %rbx
  3454. callq _read_int
  3455. movq %rax, %rcx
  3456. cmpq %rbx, %rcx
  3457. je then21288
  3458. movq $777, %r12
  3459. jmp if_end21289
  3460. then21288:
  3461. movq $42, %r12
  3462. if_end21289:
  3463. movq %r12, %rax
  3464. movq %rax, %rdi
  3465. callq _print_int
  3466. movq $0, %rax
  3467. addq $8, %rsp
  3468. popq %rbx
  3469. popq %r12
  3470. popq %r13
  3471. popq %r14
  3472. popq %r15
  3473. popq %rbp
  3474. retq
  3475. \end{lstlisting}
  3476. \end{minipage}
  3477. \end{tabular}
  3478. \caption{Example program with optimized conditionals.}
  3479. \label{fig:opt-if}
  3480. \end{figure}
  3481. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3482. \chapter{Tuples and Garbage Collection}
  3483. \label{ch:tuples}
  3484. \marginpar{\scriptsize To do: look through Andre's code comments for extra
  3485. things to discuss in this chapter. \\ --Jeremy}
  3486. \marginpar{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3487. all the IR grammars are spelled out! \\ --Jeremy}
  3488. \marginpar{\scriptsize Introduce has-type, but after flatten, remove it,
  3489. but keep type annotations on vector creation and local variables, function
  3490. parameters, etc. \\ --Jeremy}
  3491. In this chapter we study the implementation of mutable tuples (called
  3492. ``vectors'' in Racket). This language feature is the first to use the
  3493. computer's \emph{heap} because the lifetime of a Racket tuple is
  3494. indefinite, that is, a tuple does not follow a stack (FIFO) discipline
  3495. but instead lives forever from the programmer's viewpoint. Of course,
  3496. from an implementor's viewpoint, it is important to reclaim the space
  3497. associated with tuples when they are no longer needed, which is why we
  3498. also study \emph{garbage collection} techniques in this chapter.
  3499. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3500. interpreter and type checker. The $R_3$ language extends the $R_2$
  3501. language of Chapter~\ref{ch:bool-types} with vectors and void values
  3502. (because the \code{vector-set!} operation returns a void
  3503. value). Section~\ref{sec:GC} describes a garbage collection algorithm
  3504. based on copying live objects back and forth between two halves of the
  3505. heap. The garbage collector requires coordination with the compiler so
  3506. that it can see all of the \emph{root} pointers, that is, pointers in
  3507. registers or on the procedure call stack.
  3508. Section~\ref{sec:code-generation-gc} discusses all the necessary
  3509. changes and additions to the compiler passes, including type checking,
  3510. instruction selection, register allocation, and a new compiler pass
  3511. named \code{expose-allocation}.
  3512. \section{The $R_3$ Language}
  3513. \label{sec:r3}
  3514. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3515. includes three new forms for creating a tuple, reading an element of a
  3516. tuple, and writing to an element of a tuple. The program in
  3517. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3518. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3519. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3520. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3521. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3522. $40$, to which we add the $2$, the element at index $0$ of the
  3523. 1-tuple.
  3524. \begin{figure}[tbp]
  3525. \begin{lstlisting}
  3526. (let ([t (vector 40 #t (vector 2))])
  3527. (if (vector-ref t 1)
  3528. (+ (vector-ref t 0)
  3529. (vector-ref (vector-ref t 2) 0))
  3530. 44))
  3531. \end{lstlisting}
  3532. \caption{Example program that creates tuples and reads from them.}
  3533. \label{fig:vector-eg}
  3534. \end{figure}
  3535. \begin{figure}[tbp]
  3536. \centering
  3537. \fbox{
  3538. \begin{minipage}{0.96\textwidth}
  3539. \[
  3540. \begin{array}{lcl}
  3541. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3542. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3543. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3544. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3545. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3546. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3547. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3548. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3549. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3550. (\key{vector-ref}\;\Exp\;\Int) \\
  3551. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3552. &\mid& (\key{void}) \\
  3553. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3554. \end{array}
  3555. \]
  3556. \end{minipage}
  3557. }
  3558. \caption{The syntax of $R_3$, extending $R_2$ with tuples.}
  3559. \label{fig:r3-syntax}
  3560. \end{figure}
  3561. Tuples are our first encounter with heap-allocated data, which raises
  3562. several interesting issues. First, variable binding performs a
  3563. shallow-copy when dealing with tuples, which means that different
  3564. variables can refer to the same tuple, i.e., different variables can
  3565. be \emph{aliases} for the same thing. Consider the following example
  3566. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  3567. the mutation through \code{t2} is visible when referencing the tuple
  3568. from \code{t1}, so the result of this program is \code{42}.
  3569. \begin{lstlisting}
  3570. (let ([t1 (vector 3 7)])
  3571. (let ([t2 t1])
  3572. (let ([_ (vector-set! t2 0 42)])
  3573. (vector-ref t1 0))))
  3574. \end{lstlisting}
  3575. The next issue concerns the lifetime of tuples. Of course, they are
  3576. created by the \code{vector} form, but when does their lifetime end?
  3577. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3578. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  3579. is not tied to any notion of static scoping. For example, the
  3580. following program returns \code{3} even though the variable \code{t}
  3581. goes out of scope prior to accessing the vector.
  3582. \begin{lstlisting}
  3583. (vector-ref
  3584. (let ([t (vector 3 7)])
  3585. t)
  3586. 0)
  3587. \end{lstlisting}
  3588. From the perspective of programmer-observable behavior, tuples live
  3589. forever. Of course, if they really lived forever, then many programs
  3590. would run out of memory.\footnote{The $R_3$ language does not have
  3591. looping or recursive function, so it is nigh impossible to write a
  3592. program in $R_3$ that will run out of memory. However, we add
  3593. recursive functions in the next Chapter!} A Racket implementation
  3594. must therefore perform automatic garbage collection.
  3595. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3596. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3597. checker. The additions to the interpreter are straightforward but the
  3598. updates to the type checker deserve some explanation. As we shall see
  3599. in Section~\ref{sec:GC}, we need to know which variables are pointers
  3600. into the heap, that is, which variables are vectors. Also, when
  3601. allocating a vector, we shall need to know which elements of the
  3602. vector are pointers. We can obtain this information during type
  3603. checking and flattening. The type checker in
  3604. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  3605. expression, it also wraps every sub-expression $e$ with the form
  3606. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  3607. the flatten pass (Section~\ref{sec:flatten-gc}) this type information is
  3608. propagated to all variables (including temporaries generated during
  3609. flattening).
  3610. \begin{figure}[tbp]
  3611. \begin{lstlisting}
  3612. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3613. (define (interp-op op)
  3614. (match op
  3615. ...
  3616. ['vector vector]
  3617. ['vector-ref vector-ref]
  3618. ['vector-set! vector-set!]
  3619. [else (error 'interp-op "unknown operator")]))
  3620. (define (interp-R3 env)
  3621. (lambda (e)
  3622. (match e
  3623. ...
  3624. [else (error 'interp-R3 "unrecognized expression")]
  3625. )))
  3626. \end{lstlisting}
  3627. \caption{Interpreter for the $R_3$ language.}
  3628. \label{fig:interp-R3}
  3629. \end{figure}
  3630. \begin{figure}[tbp]
  3631. \begin{lstlisting}
  3632. (define (typecheck-R3 env)
  3633. (lambda (e)
  3634. (match e
  3635. ...
  3636. ['(void) (values '(has-type (void) Void) 'Void)]
  3637. [`(vector ,(app (type-check env) e* t*) ...)
  3638. (let ([t `(Vector ,@t*)])
  3639. (values `(has-type (vector ,@e*) ,t) t))]
  3640. [`(vector-ref ,(app (type-check env) e t) ,i)
  3641. (match t
  3642. [`(Vector ,ts ...)
  3643. (unless (and (exact-nonnegative-integer? i)
  3644. (i . < . (length ts)))
  3645. (error 'type-check "invalid index ~a" i))
  3646. (let ([t (list-ref ts i)])
  3647. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3648. t))]
  3649. [else (error "expected a vector in vector-ref, not" t)])]
  3650. [`(vector-set! ,(app (type-check env) e-vec^ t-vec) ,i
  3651. ,(app (type-check env) e-arg^ t-arg))
  3652. (match t-vec
  3653. [`(Vector ,ts ...)
  3654. (unless (and (exact-nonnegative-integer? i)
  3655. (i . < . (length ts)))
  3656. (error 'type-check "invalid index ~a" i))
  3657. (unless (equal? (list-ref ts i) t-arg)
  3658. (error 'type-check "type mismatch in vector-set! ~a ~a"
  3659. (list-ref ts i) t-arg))
  3660. (values `(has-type (vector-set! ,e-vec^
  3661. (has-type ,i Integer)
  3662. ,e-arg^) Void) 'Void)]
  3663. [else (error 'type-check
  3664. "expected a vector in vector-set!, not ~a" t-vec)])]
  3665. [`(eq? ,(app (type-check env) e1 t1)
  3666. ,(app (type-check env) e2 t2))
  3667. (match* (t1 t2)
  3668. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3669. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3670. [(other wise) ((super type-check env) e)])]
  3671. )))
  3672. \end{lstlisting}
  3673. \caption{Type checker for the $R_3$ language.}
  3674. \label{fig:typecheck-R3}
  3675. \end{figure}
  3676. \section{Garbage Collection}
  3677. \label{sec:GC}
  3678. Here we study a relatively simple algorithm for garbage collection
  3679. that is the basis of state-of-the-art garbage
  3680. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3681. particular, we describe a two-space copying
  3682. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3683. perform the
  3684. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3685. coarse-grained depiction of what happens in a two-space collector,
  3686. showing two time steps, prior to garbage collection on the top and
  3687. after garbage collection on the bottom. In a two-space collector, the
  3688. heap is divided into two parts, the FromSpace and the
  3689. ToSpace. Initially, all allocations go to the FromSpace until there is
  3690. not enough room for the next allocation request. At that point, the
  3691. garbage collector goes to work to make more room.
  3692. The garbage collector must be careful not to reclaim tuples that will
  3693. be used by the program in the future. Of course, it is impossible in
  3694. general to predict what a program will do, but we can overapproximate
  3695. the will-be-used tuples by preserving all tuples that could be
  3696. accessed by \emph{any} program given the current computer state. A
  3697. program could access any tuple whose address is in a register or on
  3698. the procedure call stack. These addresses are called the \emph{root
  3699. set}. In addition, a program could access any tuple that is
  3700. transitively reachable from the root set. Thus, it is safe for the
  3701. garbage collector to reclaim the tuples that are not reachable in this
  3702. way.
  3703. %
  3704. \footnote{The sitation in Figure~\ref{fig:copying-collector}, with a
  3705. cycle, cannot be created by a well-typed program in $R_3$. However,
  3706. creating cycles will be possible once we get to $R_6$. We design
  3707. the garbage collector to deal with cycles to begin with, so we will
  3708. not need to revisit this issue.}
  3709. So the goal of the garbage collector is twofold:
  3710. \begin{enumerate}
  3711. \item preserve all tuple that are reachable from the root set via a
  3712. path of pointers, that is, the \emph{live} tuples, and
  3713. \item reclaim the memory of everything else, that is, the
  3714. \emph{garbage}.
  3715. \end{enumerate}
  3716. A copying collector accomplishes this by copying all of the live
  3717. objects into the ToSpace and then performs a slight of hand, treating
  3718. the ToSpace as the new FromSpace and the old FromSpace as the new
  3719. ToSpace. In the example of Figure~\ref{fig:copying-collector}, there
  3720. are three pointers in the root set, one in a register and two on the
  3721. stack. All of the live objects have been copied to the ToSpace (the
  3722. right-hand side of Figure~\ref{fig:copying-collector}) in a way that
  3723. preserves the pointer relationships. For example, the pointer in the
  3724. register still points to a 2-tuple whose first element is a 3-tuple
  3725. and second element is a 2-tuple. There are four tuples that are not
  3726. reachable from the root set and therefore do not get copied into the
  3727. ToSpace.
  3728. \begin{figure}[tbp]
  3729. \centering
  3730. \includegraphics[width=\textwidth]{copy-collect-1} \\[5ex]
  3731. \includegraphics[width=\textwidth]{copy-collect-2}
  3732. \caption{A copying collector in action.}
  3733. \label{fig:copying-collector}
  3734. \end{figure}
  3735. %% \marginpar{\tiny Need to add comment somewhere about the goodness
  3736. %% of copying collection, especially that it doesn't touch
  3737. %% the garbage, so its time complexity only depends on the
  3738. %% amount of live data.\\ --Jeremy}
  3739. There are many alternatives to copying collectors (and their older
  3740. siblings, the generational collectors) when its comes to garbage
  3741. collection, such as mark-and-sweep and reference counting. The
  3742. strengths of copying collectors are that allocation is fast (just a
  3743. test and pointer increment), there is no fragmentation, cyclic garbage
  3744. is collected, and the time complexity of collection only depends on
  3745. the amount of live data, and not on the amount of
  3746. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  3747. copying collectors is that they use a lot of space, though that
  3748. problem is ameliorated in generational collectors. Racket and Scheme
  3749. programs tend to allocate many small objects and generate a lot of
  3750. garbage, so copying and generational collectors are a good fit. Of
  3751. course, garbage collection is an active research topic, especially
  3752. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  3753. continuously developing new techniques and revisiting old
  3754. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  3755. \subsection{Graph Copying via Cheney's Algorithm}
  3756. \label{sec:cheney}
  3757. Let us take a closer look at how the copy works. The allocated objects
  3758. and pointers can be viewed as a graph and we need to copy the part of
  3759. the graph that is reachable from the root set. To make sure we copy
  3760. all of the reachable vertices in the graph, we need an exhaustive
  3761. graph traversal algorithm, such as depth-first search or breadth-first
  3762. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3763. take into account the possibility of cycles by marking which vertices
  3764. have already been visited, so as to ensure termination of the
  3765. algorithm. These search algorithms also use a data structure such as a
  3766. stack or queue as a to-do list to keep track of the vertices that need
  3767. to be visited. We shall use breadth-first search and a trick due to
  3768. \citet{Cheney:1970aa} for simultaneously representing the queue and
  3769. copying tuples into the ToSpace.
  3770. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3771. copy progresses. The queue is represented by a chunk of contiguous
  3772. memory at the beginning of the ToSpace, using two pointers to track
  3773. the front and the back of the queue. The algorithm starts by copying
  3774. all tuples that are immediately reachable from the root set into the
  3775. ToSpace to form the initial queue. When we copy a tuple, we mark the
  3776. old tuple to indicate that it has been visited. (We discuss the
  3777. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3778. inside the copied tuples in the queue still point back to the
  3779. FromSpace. Once the initial queue has been created, the algorithm
  3780. enters a loop in which it repeatedly processes the tuple at the front
  3781. of the queue and pops it off the queue. To process a tuple, the
  3782. algorithm copies all the tuple that are directly reachable from it to
  3783. the ToSpace, placing them at the back of the queue. The algorithm then
  3784. updates the pointers in the popped tuple so they point to the newly
  3785. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  3786. step we copy the tuple whose second element is $42$ to the back of the
  3787. queue. The other pointer goes to a tuple that has already been copied,
  3788. so we do not need to copy it again, but we do need to update the
  3789. pointer to the new location. This can be accomplished by storing a
  3790. \emph{forwarding} pointer to the new location in the old tuple, back
  3791. when we initially copied the tuple into the ToSpace. This completes
  3792. one step of the algorithm. The algorithm continues in this way until
  3793. the front of the queue is empty, that is, until the front catches up
  3794. with the back.
  3795. \begin{figure}[tbp]
  3796. \centering \includegraphics[width=0.9\textwidth]{cheney}
  3797. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  3798. \label{fig:cheney}
  3799. \end{figure}
  3800. \subsection{Data Representation}
  3801. \label{sec:data-rep-gc}
  3802. The garbage collector places some requirements on the data
  3803. representations used by our compiler. First, the garbage collector
  3804. needs to distinguish between pointers and other kinds of data. There
  3805. are several ways to accomplish this.
  3806. \begin{enumerate}
  3807. \item Attached a tag to each object that identifies what type of
  3808. object it is~\citep{McCarthy:1960dz}.
  3809. \item Store different types of objects in different
  3810. regions~\citep{Steele:1977ab}.
  3811. \item Use type information from the program to either generate
  3812. type-specific code for collecting or to generate tables that can
  3813. guide the
  3814. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3815. \end{enumerate}
  3816. Dynamically typed languages, such as Lisp, need to tag objects
  3817. anyways, so option 1 is a natural choice for those languages.
  3818. However, $R_3$ is a statically typed language, so it would be
  3819. unfortunate to require tags on every object, especially small and
  3820. pervasive objects like integers and Booleans. Option 3 is the
  3821. best-performing choice for statically typed languages, but comes with
  3822. a relatively high implementation complexity. To keep this chapter to a
  3823. 2-week time budget, we recommend a combination of options 1 and 2,
  3824. with separate strategies used for the stack and the heap.
  3825. Regarding the stack, we recommend using a separate stack for
  3826. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  3827. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  3828. local variable needs to be spilled and is of type \code{(Vector
  3829. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  3830. of the normal procedure call stack. Furthermore, we always spill
  3831. vector-typed variables if they are live during a call to the
  3832. collector, thereby ensuring that no pointers are in registers during a
  3833. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  3834. Figure~\ref{fig:copying-collector} and contrasts it with the data
  3835. layout using a root stack. The root stack contains the two pointers
  3836. from the regular stack and also the pointer in the second
  3837. register.
  3838. \begin{figure}[tbp]
  3839. \centering \includegraphics[width=0.7\textwidth]{root-stack}
  3840. \caption{Maintaining a root stack to facilitate garbage collection.}
  3841. \label{fig:shadow-stack}
  3842. \end{figure}
  3843. The problem of distinguishing between pointers and other kinds of data
  3844. also arises inside of each tuple. We solve this problem by attaching a
  3845. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  3846. in on the tags for two of the tuples in the example from
  3847. Figure~\ref{fig:copying-collector}. Part of each tag is dedicated to
  3848. specifying which elements of the tuple are pointers, the part labeled
  3849. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  3850. a pointer and a 0 bit indicates some other kind of data. The pointer
  3851. mask starts at bit location 7. We have limited tuples to a maximum
  3852. size of 50 elements, so we just need 50 bits for the pointer mask. The
  3853. tag also contains two other pieces of information. The length of the
  3854. tuple (number of elements) is stored in bits location 1 through
  3855. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  3856. to be copied to the FromSpace. If the bit has value 1, then this
  3857. tuple has not yet been copied. If the bit has value 0 then the entire
  3858. tag is in fact a forwarding pointer. (The lower 3 bits of an pointer
  3859. are always zero anyways because our tuples are 8-byte aligned.)
  3860. \begin{figure}[tbp]
  3861. \centering \includegraphics[width=0.8\textwidth]{tuple-rep}
  3862. \caption{Representation for tuples in the heap.}
  3863. \label{fig:tuple-rep}
  3864. \end{figure}
  3865. \subsection{Implementation of the Garbage Collector}
  3866. \label{sec:organize-gz}
  3867. The implementation of the garbage collector needs to do a lot of
  3868. bit-level data manipulation and we need to link it with our
  3869. compiler-generated x86 code. Thus, we recommend implementing the
  3870. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  3871. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  3872. interface to the garbage collector. The \code{initialize} function
  3873. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  3874. function is meant to be called near the beginning of \code{main},
  3875. before the rest of the program executes. The \code{initialize}
  3876. function puts the address of the beginning of the FromSpace into the
  3877. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  3878. points to the address that is 1-past the last element of the
  3879. FromSpace. (We use half-open intervals to represent chunks of
  3880. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  3881. points to the first element of the root stack.
  3882. As long as there is room left in the FromSpace, your generated code
  3883. can allocate tuples simply by moving the \code{free\_ptr} forward.
  3884. %
  3885. \marginpar{\tiny Should we dedicate a register to the free pointer? \\
  3886. --Jeremy}
  3887. %
  3888. The amount of room left in FromSpace is the difference between the
  3889. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  3890. function should be called when there is not enough room left in the
  3891. FromSpace for the next allocation. The \code{collect} function takes
  3892. a pointer to the current top of the root stack (one past the last item
  3893. that was pushed) and the number of bytes that need to be
  3894. allocated. The \code{collect} function performs the copying collection
  3895. and leaves the heap in a state such that the next allocation will
  3896. succeed.
  3897. \begin{figure}[tbp]
  3898. \begin{lstlisting}
  3899. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  3900. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  3901. int64_t* free_ptr;
  3902. int64_t* fromspace_begin;
  3903. int64_t* fromspace_end;
  3904. int64_t** rootstack_begin;
  3905. \end{lstlisting}
  3906. \caption{The compiler's interface to the garbage collector.}
  3907. \label{fig:gc-header}
  3908. \end{figure}
  3909. \begin{exercise}
  3910. In the file \code{runtime.c} you will find the implementation of
  3911. \code{initialize} and a partial implementation of \code{collect}.
  3912. The \code{collect} function calls another function, \code{cheney},
  3913. to perform the actual copy, and that function is left to the reader
  3914. to implement. The following is the prototype for \code{cheney}.
  3915. \begin{lstlisting}
  3916. static void cheney(int64_t** rootstack_ptr);
  3917. \end{lstlisting}
  3918. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  3919. rootstack (which is array of pointers). The \code{cheney} function
  3920. also communicates with \code{collect} through several global
  3921. variables, the \code{framespace\_begin} and \code{framespace\_end}
  3922. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  3923. the ToSpace:
  3924. \begin{lstlisting}
  3925. static int64_t* tospace_begin;
  3926. static int64_t* tospace_end;
  3927. \end{lstlisting}
  3928. The job of the \code{cheney} function is to copy all the live
  3929. objects (reachable from the root stack) into the ToSpace, update
  3930. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  3931. update the root stack so that it points to the objects in the
  3932. ToSpace, and finally to swap the global pointers for the FromSpace
  3933. and ToSpace.
  3934. \end{exercise}
  3935. \section{Compiler Passes}
  3936. \label{sec:code-generation-gc}
  3937. The introduction of garbage collection has a non-trivial impact on our
  3938. compiler passes. We introduce one new compiler pass called
  3939. \code{expose-allocation} and make non-trivial changes to
  3940. \code{type-check}, \code{flatten}, \code{select-instructions},
  3941. \code{allocate-registers}, and \code{print-x86}. The following
  3942. program will serve as our running example. It creates two tuples, one
  3943. nested inside the other. Both tuples have length one. The example then
  3944. accesses the element in the inner tuple tuple via two vector
  3945. references.
  3946. % tests/s2_17.rkt
  3947. \begin{lstlisting}
  3948. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  3949. \end{lstlisting}
  3950. We already discuss the changes to \code{type-check} in
  3951. Section~\ref{sec:r3}, including the addition of \code{has-type}, so we
  3952. proceed to discuss the new \code{expose-allocation} pass.
  3953. \subsection{Expose Allocation (New)}
  3954. \label{sec:expose-allocation}
  3955. The pass \code{expose-allocation} lowers the \code{vector} creation
  3956. form into a conditional call to the collector followed by the
  3957. allocation. We choose to place the \code{expose-allocation} pass
  3958. before \code{flatten} because \code{expose-allocation} introduces new
  3959. variables, which can be done locally with \code{let}, but \code{let}
  3960. is gone after \code{flatten}. In the following, we show the
  3961. transformation for the \code{vector} form into let-bindings for the
  3962. intializing expressions, by a conditional \code{collect}, an
  3963. \code{allocate}, and the initialization of the vector.
  3964. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  3965. total bytes need to be allocated for the vector, which is 8 for the
  3966. tag plus \itm{len} times 8.)
  3967. \begin{lstlisting}
  3968. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  3969. |$\Longrightarrow$|
  3970. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  3971. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  3972. (global-value fromspace_end))
  3973. (void)
  3974. (collect |\itm{bytes}|))])
  3975. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  3976. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  3977. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  3978. |$v$|) ... )))) ...)
  3979. \end{lstlisting}
  3980. (In the above, we suppressed all of the \code{has-type} forms in the
  3981. output for the sake of readability.) The ordering of the initializing
  3982. expressions ($e_0,\ldots,e_{n-1}$) prior to the \code{allocate} is
  3983. important, as those expressions may trigger garbage collection and we
  3984. do not want an allocated but uninitialized tuple to be present during
  3985. a garbage collection.
  3986. The output of \code{expose-allocation} is a language that extends
  3987. $R_3$ with the three new forms that we use above in the translation of
  3988. \code{vector}.
  3989. \[
  3990. \begin{array}{lcl}
  3991. \Exp &::=& \cdots
  3992. \mid (\key{collect} \,\itm{int})
  3993. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  3994. \mid (\key{global-value} \,\itm{name})
  3995. \end{array}
  3996. \]
  3997. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  3998. %% the beginning of the program which will instruct the garbage collector
  3999. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4000. %% two arguments of \code{initialize} specify the initial allocated space
  4001. %% for the root stack and for the heap.
  4002. %
  4003. %% The \code{expose-allocation} pass annotates all of the local variables
  4004. %% in the \code{program} form with their type.
  4005. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4006. \code{expose-allocation} pass on our running example.
  4007. \begin{figure}[tbp]
  4008. \begin{lstlisting}
  4009. (program (type Integer)
  4010. (vector-ref
  4011. (vector-ref
  4012. (let ((vecinit32990
  4013. (let ([vecinit32986 42])
  4014. (let ((collectret32988
  4015. (if (< (+ (global-value free_ptr) 16)
  4016. (global-value fromspace_end))
  4017. (void)
  4018. (collect 16))))
  4019. (let ([alloc32985
  4020. (allocate 1 (Vector Integer))])
  4021. (let ([initret32987
  4022. (vector-set! alloc32985 0 vecinit32986)])
  4023. alloc32985))))))
  4024. (let ([collectret32992
  4025. (if (< (+ (global-value free_ptr) 16)
  4026. (global-value fromspace_end))
  4027. (void)
  4028. (collect 16))])
  4029. (let ([alloc32989 (allocate 1 (Vector (Vector Integer)))])
  4030. (let ([initret32991 (vector-set! alloc32989 0 vecinit32990)])
  4031. alloc32989))))
  4032. 0)
  4033. 0))
  4034. \end{lstlisting}
  4035. \caption{Output of the \code{expose-allocation} pass, minus
  4036. all of the \code{has-type} forms.}
  4037. \label{fig:expose-alloc-output}
  4038. \end{figure}
  4039. \clearpage
  4040. \subsection{Flatten and the $C_2$ intermediate language}
  4041. \label{sec:flatten-gc}
  4042. \begin{figure}[tp]
  4043. \fbox{
  4044. \begin{minipage}{0.96\textwidth}
  4045. \[
  4046. \begin{array}{lcl}
  4047. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4048. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4049. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4050. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4051. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4052. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4053. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4054. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4055. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4056. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4057. &\mid& (\key{collect} \,\itm{int}) \\
  4058. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  4059. \end{array}
  4060. \]
  4061. \end{minipage}
  4062. }
  4063. \caption{The $C_2$ language, extending $C_1$ with support for tuples.}
  4064. \label{fig:c2-syntax}
  4065. \end{figure}
  4066. The output of \code{flatten} is a program in the intermediate language
  4067. $C_2$, whose syntax is defined in Figure~\ref{fig:c2-syntax}. The new
  4068. forms of $C_2$ include the expressions \key{allocate},
  4069. \key{vector-ref}, and \key{vector-set!}, and \key{global-value} and
  4070. the statement \code{collect}. The \code{flatten} pass can treat these
  4071. new forms much like the other forms.
  4072. Recall that the \code{flatten} function collects all of the local
  4073. variables so that it can decorate the \code{program} form with
  4074. them. Also recall that we need to know the types of all the local
  4075. variables for purposes of identifying the root set for the garbage
  4076. collector. Thus, we change \code{flatten} to collect not just the
  4077. variables, but the variables and their types in the form of an
  4078. association list. Thanks to the \code{has-type} forms, the types are
  4079. readily available. For example, consider the translation of the
  4080. \code{let} form.
  4081. \begin{lstlisting}
  4082. (let ([|$x$| (has-type |\itm{rhs}| |\itm{type}|)]) |\itm{body}|)
  4083. |$\Longrightarrow$|
  4084. (values |\itm{body'}|
  4085. (|\itm{ss_1}| (assign |$x$| |\itm{rhs'}|) |\itm{ss_2}|)
  4086. ((|$x$| . |\itm{type}|) |\itm{xt_1}| |\itm{xt_2}|))
  4087. \end{lstlisting}
  4088. where \itm{rhs'}, \itm{ss_1}, and \itm{xs_1} are the results of
  4089. recursively flattening \itm{rhs} and \itm{body'}, \itm{ss_2}, and
  4090. \itm{xs_2} are the results of recursively flattening \itm{body}. The
  4091. output on our running example is shown in Figure~\ref{fig:flatten-gc}.
  4092. \begin{figure}[tbp]
  4093. \begin{lstlisting}
  4094. '(program
  4095. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4096. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void)
  4097. (tmp94 . Integer) (tmp93 . Integer) (tmp95 . Integer)
  4098. (tmp85 Vector Integer) (tmp87 . Void) (tmp92 . Void)
  4099. (tmp00 . Void) (tmp98 . Integer) (tmp97 . Integer)
  4100. (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4101. (tmp91 . Void))
  4102. (type Integer)
  4103. (assign tmp86 42)
  4104. (assign tmp93 (global-value free_ptr))
  4105. (assign tmp94 (+ tmp93 16))
  4106. (assign tmp95 (global-value fromspace_end))
  4107. (if (< tmp94 tmp95)
  4108. ((assign tmp96 (void)))
  4109. ((collect 16) (assign tmp96 (void))))
  4110. (assign tmp88 tmp96)
  4111. (assign tmp85 (allocate 1 (Vector Integer)))
  4112. (assign tmp87 (vector-set! tmp85 0 tmp86))
  4113. (assign tmp90 tmp85)
  4114. (assign tmp97 (global-value free_ptr))
  4115. (assign tmp98 (+ tmp97 16))
  4116. (assign tmp99 (global-value fromspace_end))
  4117. (if (< tmp98 tmp99)
  4118. ((assign tmp00 (void)))
  4119. ((collect 16) (assign tmp00 (void))))
  4120. (assign tmp92 tmp00)
  4121. (assign tmp89 (allocate 1 (Vector (Vector Integer))))
  4122. (assign tmp91 (vector-set! tmp89 0 tmp90))
  4123. (assign tmp01 (vector-ref tmp89 0))
  4124. (assign tmp02 (vector-ref tmp01 0))
  4125. (return tmp02))
  4126. \end{lstlisting}
  4127. \caption{Output of \code{flatten} for the running example.}
  4128. \label{fig:flatten-gc}
  4129. \end{figure}
  4130. \clearpage
  4131. \subsection{Select Instructions}
  4132. \label{sec:select-instructions-gc}
  4133. %% void (rep as zero)
  4134. %% allocate
  4135. %% collect (callq collect)
  4136. %% vector-ref
  4137. %% vector-set!
  4138. %% global-value (postpone)
  4139. In this pass we generate x86 code for most of the new operations that
  4140. were needed to compile tuples, including \code{allocate},
  4141. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4142. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4143. The \code{vector-ref} and \code{vector-set!} forms translate into
  4144. \code{movq} instructions with the appropriate \key{deref}. (The
  4145. plus one is to get past the tag at the beginning of the tuple
  4146. representation.)
  4147. \begin{lstlisting}
  4148. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4149. |$\Longrightarrow$|
  4150. (movq |$\itm{vec}'$| (reg r11))
  4151. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4152. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4153. |$\Longrightarrow$|
  4154. (movq |$\itm{vec}'$| (reg r11))
  4155. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4156. (movq (int 0) |$\itm{lhs}$|)
  4157. \end{lstlisting}
  4158. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4159. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4160. register \code{r11} ensures that offsets are only performed with
  4161. register operands. This requires removing \code{r11} from
  4162. consideration by the register allocating.
  4163. We compile the \code{allocate} form to operations on the
  4164. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4165. is the next free address in the FromSpace, so we move it into the
  4166. \itm{lhs} and then move it forward by enough space for the tuple being
  4167. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4168. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4169. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4170. how the tag is organized. We recommend using the Racket operations
  4171. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4172. The type annoation in the \code{vector} form is used to determine the
  4173. pointer mask region of the tag.
  4174. \begin{lstlisting}
  4175. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4176. |$\Longrightarrow$|
  4177. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4178. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4179. (movq |$\itm{lhs}'$| (reg r11))
  4180. (movq (int |$\itm{tag}$|) (deref r11 0))
  4181. \end{lstlisting}
  4182. The \code{collect} form is compiled to a call to the \code{collect}
  4183. function in the runtime. The arguments to \code{collect} are the top
  4184. of the root stack and the number of bytes that need to be allocated.
  4185. We shall use a dedicated register, \code{r15}, to store the pointer to
  4186. the top of the root stack. So \code{r15} is not available for use by
  4187. the register allocator.
  4188. \begin{lstlisting}
  4189. (collect |$\itm{bytes}$|)
  4190. |$\Longrightarrow$|
  4191. (movq (reg 15) (reg rdi))
  4192. (movq |\itm{bytes}| (reg rsi))
  4193. (callq collect)
  4194. \end{lstlisting}
  4195. \begin{figure}[tp]
  4196. \fbox{
  4197. \begin{minipage}{0.96\textwidth}
  4198. \[
  4199. \begin{array}{lcl}
  4200. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4201. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4202. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4203. \mid (\key{global-value}\; \itm{name}) \\
  4204. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4205. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4206. (\key{subq} \; \Arg\; \Arg) \mid
  4207. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4208. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4209. (\key{pushq}\;\Arg) \mid
  4210. (\key{popq}\;\Arg) \mid
  4211. (\key{retq})} \\
  4212. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4213. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4214. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4215. \mid (\key{jmp} \; \itm{label})
  4216. \mid (\key{j}\itm{cc} \; \itm{label})
  4217. \mid (\key{label} \; \itm{label}) } \\
  4218. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4219. \end{array}
  4220. \]
  4221. \end{minipage}
  4222. }
  4223. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4224. \label{fig:x86-2}
  4225. \end{figure}
  4226. The syntax of the $x86_2$ language is defined in
  4227. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4228. of the form for global variables.
  4229. %
  4230. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4231. \code{select-instructions} pass on the running example.
  4232. \begin{figure}[tbp]
  4233. \centering
  4234. \begin{minipage}{0.75\textwidth}
  4235. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4236. (program
  4237. ((tmp02 . Integer) (tmp01 Vector Integer) (tmp90 Vector Integer)
  4238. (tmp86 . Integer) (tmp88 . Void) (tmp96 . Void) (tmp94 . Integer)
  4239. (tmp93 . Integer) (tmp95 . Integer) (tmp85 Vector Integer)
  4240. (tmp87 . Void) (tmp92 . Void) (tmp00 . Void) (tmp98 . Integer)
  4241. (tmp97 . Integer) (tmp99 . Integer) (tmp89 Vector (Vector Integer))
  4242. (tmp91 . Void)) (type Integer)
  4243. (movq (int 42) (var tmp86))
  4244. (movq (global-value free_ptr) (var tmp93))
  4245. (movq (var tmp93) (var tmp94))
  4246. (addq (int 16) (var tmp94))
  4247. (movq (global-value fromspace_end) (var tmp95))
  4248. (if (< (var tmp94) (var tmp95))
  4249. ((movq (int 0) (var tmp96)))
  4250. ((movq (reg r15) (reg rdi))
  4251. (movq (int 16) (reg rsi))
  4252. (callq collect)
  4253. (movq (int 0) (var tmp96))))
  4254. (movq (var tmp96) (var tmp88))
  4255. (movq (global-value free_ptr) (var tmp85))
  4256. (addq (int 16) (global-value free_ptr))
  4257. (movq (var tmp85) (reg r11))
  4258. (movq (int 3) (deref r11 0))
  4259. (movq (var tmp85) (reg r11))
  4260. (movq (var tmp86) (deref r11 8))
  4261. (movq (int 0) (var tmp87))
  4262. (movq (var tmp85) (var tmp90))
  4263. (movq (global-value free_ptr) (var tmp97))
  4264. (movq (var tmp97) (var tmp98))
  4265. (addq (int 16) (var tmp98))
  4266. (movq (global-value fromspace_end) (var tmp99))
  4267. (if (< (var tmp98) (var tmp99))
  4268. ((movq (int 0) (var tmp00)))
  4269. ((movq (reg r15) (reg rdi))
  4270. (movq (int 16) (reg rsi))
  4271. (callq collect)
  4272. (movq (int 0) (var tmp00))))
  4273. (movq (var tmp00) (var tmp92))
  4274. (movq (global-value free_ptr) (var tmp89))
  4275. (addq (int 16) (global-value free_ptr))
  4276. (movq (var tmp89) (reg r11))
  4277. (movq (int 131) (deref r11 0))
  4278. (movq (var tmp89) (reg r11))
  4279. (movq (var tmp90) (deref r11 8))
  4280. (movq (int 0) (var tmp91))
  4281. (movq (var tmp89) (reg r11))
  4282. (movq (deref r11 8) (var tmp01))
  4283. (movq (var tmp01) (reg r11))
  4284. (movq (deref r11 8) (var tmp02))
  4285. (movq (var tmp02) (reg rax)))
  4286. \end{lstlisting}
  4287. \end{minipage}
  4288. \caption{Output of the \code{select-instructions} pass.}
  4289. \label{fig:select-instr-output-gc}
  4290. \end{figure}
  4291. \clearpage
  4292. \subsection{Register Allocation}
  4293. \label{sec:reg-alloc-gc}
  4294. As discussed earlier in this chapter, the garbage collector needs to
  4295. access all the pointers in the root set, that is, all variables that
  4296. are vectors. It will be the responsibility of the register allocator
  4297. to make sure that:
  4298. \begin{enumerate}
  4299. \item the root stack is used for spilling vector-typed variables, and
  4300. \item if a vector-typed variable is live during a call to the
  4301. collector, it must be spilled to ensure it is visible to the
  4302. collector.
  4303. \end{enumerate}
  4304. The later responsibility can be handled during construction of the
  4305. inference graph, by adding interference edges between the call-live
  4306. vector-typed variables and all the callee-save registers. (They
  4307. already interfere with the caller-save registers.) The type
  4308. information for variables is in the \code{program} form, so we
  4309. recommend adding another parameter to the \code{build-interference}
  4310. function to communicate this association list.
  4311. The spilling of vector-typed variables to the root stack can be
  4312. handled after graph coloring, when choosing how to assign the colors
  4313. (integers) to registers and stack locations. The \code{program} output
  4314. of this pass changes to also record the number of spills to the root
  4315. stack.
  4316. \[
  4317. \begin{array}{lcl}
  4318. x86_2 &::= & (\key{program} \;(\itm{stackSpills} \; \itm{rootstackSpills}) \;(\key{type}\;\itm{type})\; \Instr^{+})
  4319. \end{array}
  4320. \]
  4321. % build-interference
  4322. %
  4323. % callq
  4324. % extra parameter for var->type assoc. list
  4325. % update 'program' and 'if'
  4326. % allocate-registers
  4327. % allocate spilled vectors to the rootstack
  4328. % don't change color-graph
  4329. \subsection{Print x86}
  4330. \label{sec:print-x86-gc}
  4331. \marginpar{\scriptsize We need to show the translation to x86 and what
  4332. to do about global-value. \\ --Jeremy}
  4333. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4334. \code{print-x86} pass.
  4335. \begin{figure}[htbp]
  4336. \begin{minipage}[t]{0.5\textwidth}
  4337. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4338. .globl _main
  4339. _main:
  4340. pushq %rbp
  4341. movq %rsp, %rbp
  4342. pushq %r14
  4343. pushq %r13
  4344. pushq %r12
  4345. pushq %rbx
  4346. subq $0, %rsp
  4347. movq $16384, %rdi
  4348. movq $16, %rsi
  4349. callq _initialize
  4350. movq _rootstack_begin(%rip), %r15
  4351. movq _free_ptr(%rip), %rbx
  4352. addq $16, %rbx
  4353. cmpq _fromspace_end(%rip), %rbx
  4354. setl %al
  4355. movzbq %al, %rbx
  4356. cmpq $0, %rbx
  4357. je then30964
  4358. jmp if_end30965
  4359. then30964:
  4360. movq %r15, %rdi
  4361. movq $16, %rsi
  4362. callq _collect
  4363. if_end30965:
  4364. movq _free_ptr(%rip), %rbx
  4365. addq $16, _free_ptr(%rip)
  4366. movq %rbx, %r11
  4367. movq $3, 0(%r11)
  4368. movq %rbx, %r11
  4369. movq $42, 8(%r11)
  4370. movq _free_ptr(%rip), %rcx
  4371. addq $16, %rcx
  4372. cmpq _fromspace_end(%rip), %rcx
  4373. setl %al
  4374. movzbq %al, %rcx
  4375. cmpq $0, %rcx
  4376. je then30966
  4377. jmp if_end30967
  4378. \end{lstlisting}
  4379. \end{minipage}
  4380. \begin{minipage}[t]{0.45\textwidth}
  4381. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4382. then30966:
  4383. movq %rbx, 0(%r15)
  4384. addq $8, %r15
  4385. movq %r15, %rdi
  4386. movq $16, %rsi
  4387. callq _collect
  4388. subq $8, %r15
  4389. movq 0(%r15), %rbx
  4390. if_end30967:
  4391. movq _free_ptr(%rip), %rcx
  4392. addq $16, _free_ptr(%rip)
  4393. movq %rcx, %r11
  4394. movq $131, 0(%r11)
  4395. movq %rcx, %r11
  4396. movq %rbx, 8(%r11)
  4397. movq %rcx, %r11
  4398. movq 8(%r11), %rbx
  4399. movq %rbx, %r11
  4400. movq 8(%r11), %rbx
  4401. movq %rbx, %rax
  4402. movq %rax, %rdi
  4403. callq _print_int
  4404. movq $0, %rax
  4405. addq $0, %rsp
  4406. popq %rbx
  4407. popq %r12
  4408. popq %r13
  4409. popq %r14
  4410. popq %rbp
  4411. retq
  4412. \end{lstlisting}
  4413. \end{minipage}
  4414. \caption{Output of the \code{print-x86} pass.}
  4415. \label{fig:print-x86-output-gc}
  4416. \end{figure}
  4417. \marginpar{\scriptsize Suggest an implementation strategy
  4418. in which the students first do the code gen and test that
  4419. without GC (just use a big heap), then after that is debugged,
  4420. implement the GC. \\ --Jeremy}
  4421. \begin{figure}[p]
  4422. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4423. \node (R1) at (0,2) {\large $R_1$};
  4424. \node (R1-2) at (3,2) {\large $R_1$};
  4425. \node (R1-3) at (6,2) {\large $R_1$};
  4426. \node (C1-1) at (9,0) {\large $C_1$};
  4427. \node (C1-2) at (6,0) {\large $C_1$};
  4428. \node (C1-3) at (3,0) {\large $C_1$};
  4429. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4430. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4431. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4432. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  4433. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  4434. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4435. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4436. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize typecheck} (R1-2);
  4437. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  4438. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize flatten} (C1-1);
  4439. \path[->,bend left=15] (C1-1) edge [below] node {\ttfamily\footnotesize\color{red} expose-alloc.} (C1-2);
  4440. \path[->,bend left=15] (C1-2) edge [below] node {\ttfamily\footnotesize\color{red} uncover...roots} (C1-3);
  4441. \path[->,bend right=15] (C1-3) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4442. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4443. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4444. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4445. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  4446. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  4447. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  4448. \end{tikzpicture}
  4449. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4450. \label{fig:R3-passes}
  4451. \end{figure}
  4452. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4453. for the compilation of $R_3$.
  4454. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4455. \chapter{Functions}
  4456. \label{ch:functions}
  4457. This chapter studies the compilation of functions (aka. procedures) at
  4458. the level of abstraction of the C language. This corresponds to a
  4459. subset of Typed Racket in which only top-level function definitions
  4460. are allowed. This abstraction level is an important stepping stone to
  4461. implementing lexically-scoped functions in the form of \key{lambda}
  4462. abstractions (Chapter~\ref{ch:lambdas}).
  4463. \section{The $R_4$ Language}
  4464. The syntax for function definitions and function application
  4465. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4466. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4467. function definitions. The function names from these definitions are
  4468. in-scope for the entire program, including all other function
  4469. definitions (so the ordering of function definitions does not matter).
  4470. Functions are first-class in the sense that a function pointer is data
  4471. and can be stored in memory or passed as a parameter to another
  4472. function. Thus, we introduce a function type, written
  4473. \begin{lstlisting}
  4474. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4475. \end{lstlisting}
  4476. for a function whose $n$ parameters have the types $\Type_1$ through
  4477. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4478. these functions (with respect to Racket functions) is that they are
  4479. not lexically scoped. That is, the only external entities that can be
  4480. referenced from inside a function body are other globally-defined
  4481. functions. The syntax of $R_4$ prevents functions from being nested
  4482. inside each other; they can only be defined at the top level.
  4483. \begin{figure}[tp]
  4484. \centering
  4485. \fbox{
  4486. \begin{minipage}{0.96\textwidth}
  4487. \[
  4488. \begin{array}{lcl}
  4489. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4490. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4491. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4492. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4493. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4494. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4495. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4496. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4497. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4498. (\key{vector-ref}\;\Exp\;\Int)} \\
  4499. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4500. &\mid& (\Exp \; \Exp^{*}) \\
  4501. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4502. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4503. \end{array}
  4504. \]
  4505. \end{minipage}
  4506. }
  4507. \caption{Syntax of $R_4$, extending $R_3$ with functions.}
  4508. \label{fig:r4-syntax}
  4509. \end{figure}
  4510. The program in Figure~\ref{fig:r4-function-example} is a
  4511. representative example of defining and using functions in $R_4$. We
  4512. define a function \code{map-vec} that applies some other function
  4513. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4514. vector containing the results. We also define a function \code{add1}
  4515. that does what its name suggests. The program then applies
  4516. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4517. \code{(vector 1 42)}, from which we return the \code{42}.
  4518. \begin{figure}[tbp]
  4519. \begin{lstlisting}
  4520. (program
  4521. (define (map-vec [f : (Integer -> Integer)]
  4522. [v : (Vector Integer Integer)])
  4523. : (Vector Integer Integer)
  4524. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4525. (define (add1 [x : Integer]) : Integer
  4526. (+ x 1))
  4527. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4528. )
  4529. \end{lstlisting}
  4530. \caption{Example of using functions in $R_4$.}
  4531. \label{fig:r4-function-example}
  4532. \end{figure}
  4533. The definitional interpreter for $R_4$ is in
  4534. Figure~\ref{fig:interp-R4}.
  4535. \begin{figure}[tp]
  4536. \begin{lstlisting}
  4537. (define (interp-R4 env)
  4538. (lambda (e)
  4539. (match e
  4540. ....
  4541. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4542. (cons f `(lambda ,xs ,body))]
  4543. [`(program ,ds ... ,body)
  4544. (let ([top-level (map (interp-R4 '()) ds)])
  4545. ((interp-R4 top-level) body))]
  4546. [`(,fun ,args ...)
  4547. (define arg-vals (map (interp-R4 env) args))
  4548. (define fun-val ((interp-R4 env) fun))
  4549. (match fun-val
  4550. [`(lambda (,xs ...) ,body)
  4551. (define new-env (append (map cons xs arg-vals) env))
  4552. ((interp-R4 new-env) body)]
  4553. [else (error "interp-R4, expected function, not" fun-val)]))]
  4554. [else (error 'interp-R4 "unrecognized expression")]
  4555. )))
  4556. \end{lstlisting}
  4557. \caption{Interpreter for the $R_4$ language.}
  4558. \label{fig:interp-R4}
  4559. \end{figure}
  4560. \section{Functions in x86}
  4561. \label{sec:fun-x86}
  4562. \marginpar{\tiny Make sure callee save registers are discussed
  4563. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  4564. \marginpar{\tiny Talk about the return address on the
  4565. stack and what callq and retq does.\\ --Jeremy }
  4566. The x86 architecture provides a few features to support the
  4567. implementation of functions. We have already seen that x86 provides
  4568. labels so that one can refer to the location of an instruction, as is
  4569. needed for jump instructions. Labels can also be used to mark the
  4570. beginning of the instructions for a function. Going further, we can
  4571. obtain the address of a label by using the \key{leaq} instruction and
  4572. \key{rip}-relative addressing. For example, the following puts the
  4573. address of the \code{add1} label into the \code{rbx} register.
  4574. \begin{lstlisting}
  4575. leaq add1(%rip), %rbx
  4576. \end{lstlisting}
  4577. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4578. the \code{callq} instruction for jumping to a function as specified by
  4579. a label. The use of the instruction changes slightly if the function
  4580. is specified by an address in a register, that is, an \emph{indirect
  4581. function call}. The x86 syntax is to give the register name prefixed
  4582. with an asterisk.
  4583. \begin{lstlisting}
  4584. callq *%rbx
  4585. \end{lstlisting}
  4586. The x86 architecture does not directly support passing arguments to
  4587. functions; instead we use a combination of registers and stack
  4588. locations for passing arguments, following the conventions used by
  4589. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4590. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4591. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4592. there are more than six arguments, then the rest must be placed on the
  4593. stack, which we call \emph{stack arguments}, which we discuss in later
  4594. paragraphs. The register \code{rax} is for the return value of the
  4595. function.
  4596. Recall from Section~\ref{sec:x86} that the stack is also used for
  4597. local variables and for storing the values of callee-save registers
  4598. (we shall refer to all of these collectively as ``locals''), and that
  4599. at the beginning of a function we move the stack pointer \code{rsp}
  4600. down to make room for them.
  4601. %% We recommend storing the local variables
  4602. %% first and then the callee-save registers, so that the local variables
  4603. %% can be accessed using \code{rbp} the same as before the addition of
  4604. %% functions.
  4605. To make additional room for passing arguments, we shall
  4606. move the stack pointer even further down. We count how many stack
  4607. arguments are needed for each function call that occurs inside the
  4608. body of the function and find their maximum. Adding this number to the
  4609. number of locals gives us how much the \code{rsp} should be moved at
  4610. the beginning of the function. In preparation for a function call, we
  4611. offset from \code{rsp} to set up the stack arguments. We put the first
  4612. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4613. so on.
  4614. Upon calling the function, the stack arguments are retrieved by the
  4615. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4616. is the location of the first stack argument, \code{24(\%rbp)} is the
  4617. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4618. the layout of the caller and callee frames. Notice how important it is
  4619. that we correctly compute the maximum number of arguments needed for
  4620. function calls; if that number is too small then the arguments and
  4621. local variables will smash into each other!
  4622. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4623. is responsible for following conventions regarding the use of
  4624. registers: the caller should assume that all the caller save registers
  4625. get overwritten with arbitrary values by the callee. Thus, the caller
  4626. should either 1) not put values that are live across a call in caller
  4627. save registers, or 2) save and restore values that are live across
  4628. calls. We shall recommend option 1). On the flip side, if the callee
  4629. wants to use a callee save register, the callee must arrange to put
  4630. the original value back in the register prior to returning to the
  4631. caller.
  4632. \begin{figure}[tbp]
  4633. \centering
  4634. \begin{tabular}{r|r|l|l} \hline
  4635. Caller View & Callee View & Contents & Frame \\ \hline
  4636. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4637. 0(\key{\%rbp}) & & old \key{rbp} \\
  4638. -8(\key{\%rbp}) & & local $1$ \\
  4639. \ldots & & \ldots \\
  4640. $-8k$(\key{\%rbp}) & & local $k$ \\
  4641. & & \\
  4642. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4643. & \ldots & \ldots \\
  4644. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4645. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4646. & 0(\key{\%rbp}) & old \key{rbp} \\
  4647. & -8(\key{\%rbp}) & local $1$ \\
  4648. & \ldots & \ldots \\
  4649. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4650. \end{tabular}
  4651. \caption{Memory layout of caller and callee frames.}
  4652. \label{fig:call-frames}
  4653. \end{figure}
  4654. \section{The compilation of functions}
  4655. \marginpar{\scriptsize To do: discuss the need to push and
  4656. pop call-live pointers (vectors and functions)
  4657. to the root stack \\ --Jeremy}
  4658. Now that we have a good understanding of functions as they appear in
  4659. $R_4$ and the support for functions in x86, we need to plan the
  4660. changes to our compiler, that is, do we need any new passes and/or do
  4661. we need to change any existing passes? Also, do we need to add new
  4662. kinds of AST nodes to any of the intermediate languages?
  4663. \begin{figure}[tp]
  4664. \centering
  4665. \fbox{
  4666. \begin{minipage}{0.96\textwidth}
  4667. \[
  4668. \begin{array}{lcl}
  4669. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4670. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4671. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4672. &\mid& (\key{function-ref}\, \itm{label})
  4673. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4674. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4675. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4676. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4677. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4678. (\key{vector-ref}\;\Exp\;\Int)} \\
  4679. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4680. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4681. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4682. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4683. \end{array}
  4684. \]
  4685. \end{minipage}
  4686. }
  4687. \caption{The $F_1$ language, an extension of $R_3$
  4688. (Figure~\ref{fig:r3-syntax}).}
  4689. \label{fig:f1-syntax}
  4690. \end{figure}
  4691. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4692. compilation because it conflates the use of function names and local
  4693. variables and it conflates the application of primitive operations and
  4694. the application of functions. This is a problem because we need to
  4695. compile the use of a function name differently than the use of a local
  4696. variable; we need to use \code{leaq} to move the function name to a
  4697. register. Similarly, the application of a function is going to require
  4698. a complex sequence of instructions, unlike the primitive
  4699. operations. Thus, it is a good idea to create a new pass that changes
  4700. function references from just a symbol $f$ to \code{(function-ref
  4701. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4702. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4703. $\ldots$ $e_n$)}. A good name for this pass is
  4704. \code{reveal-functions} and the output language, $F_1$, is defined in
  4705. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4706. a good idea, because it will make sure that there are no local
  4707. variables and functions that share the same name. On the other hand,
  4708. \code{reveal-functions} needs to come before the \code{flatten} pass
  4709. because \code{flatten} will help us compile \code{function-ref}.
  4710. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4711. \key{flatten}.
  4712. \begin{figure}[tp]
  4713. \fbox{
  4714. \begin{minipage}{0.96\textwidth}
  4715. \[
  4716. \begin{array}{lcl}
  4717. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4718. \mid (\key{function-ref}\,\itm{label})\\
  4719. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4720. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4721. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4722. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4723. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4724. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4725. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4726. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4727. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4728. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4729. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4730. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4731. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4732. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4733. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4734. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4735. \end{array}
  4736. \]
  4737. \end{minipage}
  4738. }
  4739. \caption{The $C_3$ language, extending $C_2$ with functions.}
  4740. \label{fig:c3-syntax}
  4741. \end{figure}
  4742. Because each \code{function-ref} needs to eventually become an
  4743. \code{leaq} instruction, it first needs to become an assignment
  4744. statement so there is a left-hand side in which to put the
  4745. result. This can be handled easily in the \code{flatten} pass by
  4746. categorizing \code{function-ref} as a complex expression. Then, in
  4747. the \code{select-instructions} pass, an assignment of
  4748. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4749. \begin{tabular}{lll}
  4750. \begin{minipage}{0.45\textwidth}
  4751. \begin{lstlisting}
  4752. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4753. \end{lstlisting}
  4754. \end{minipage}
  4755. &
  4756. $\Rightarrow$
  4757. &
  4758. \begin{minipage}{0.4\textwidth}
  4759. \begin{lstlisting}
  4760. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4761. \end{lstlisting}
  4762. \end{minipage}
  4763. \end{tabular} \\
  4764. %
  4765. The output of select instructions is a program in the x86$_3$
  4766. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4767. \begin{figure}[tp]
  4768. \fbox{
  4769. \begin{minipage}{0.96\textwidth}
  4770. \[
  4771. \begin{array}{lcl}
  4772. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4773. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4774. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4775. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4776. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4777. (\key{subq} \; \Arg\; \Arg) \mid
  4778. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4779. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4780. (\key{pushq}\;\Arg) \mid
  4781. (\key{popq}\;\Arg) \mid
  4782. (\key{retq}) } \\
  4783. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4784. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4785. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4786. \mid (\key{jmp} \; \itm{label})
  4787. \mid (\key{j}\itm{cc} \; \itm{label})
  4788. \mid (\key{label} \; \itm{label}) } \\
  4789. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4790. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4791. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4792. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4793. \end{array}
  4794. \]
  4795. \end{minipage}
  4796. }
  4797. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4798. \label{fig:x86-3}
  4799. \end{figure}
  4800. Next we consider compiling function definitions. The \code{flatten}
  4801. pass should handle function definitions a lot like a \code{program}
  4802. node; after all, the \code{program} node represents the \code{main}
  4803. function. So the \code{flatten} pass, in addition to flattening the
  4804. body of the function into a sequence of statements, should record the
  4805. local variables in the $\Var^{*}$ field as shown below.
  4806. \begin{lstlisting}
  4807. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  4808. \end{lstlisting}
  4809. In the \code{select-instructions} pass, we need to encode the
  4810. parameter passing in terms of the conventions discussed in
  4811. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  4812. list \itm{xs}, some of them may be in registers and some of them may
  4813. be on the stack. I recommend generating \code{movq} instructions to
  4814. move the parameters from their registers and stack locations into the
  4815. variables \itm{xs}, then let register allocation handle the assignment
  4816. of those variables to homes. After this pass, the \itm{xs} can be
  4817. added to the list of local variables. As mentioned in
  4818. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  4819. stack pointer to ensure we have enough space for stack arguments in
  4820. all the calls inside the body of this function. This pass is a good
  4821. place to do this and store the result in the \itm{maxStack} field of
  4822. the output \code{define} shown below.
  4823. \begin{lstlisting}
  4824. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  4825. \end{lstlisting}
  4826. Next, consider the compilation of function applications, which have
  4827. the following form at the start of \code{select-instructions}.
  4828. \begin{lstlisting}
  4829. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  4830. \end{lstlisting}
  4831. In the mirror image of handling the parameters of function
  4832. definitions, some of the arguments \itm{args} need to be moved to the
  4833. argument passing registers and the rest should be moved to the
  4834. appropriate stack locations, as discussed in
  4835. Section~\ref{sec:fun-x86}.
  4836. %% You might want to introduce a new kind of AST node for stack
  4837. %% arguments, \code{(stack-arg $i$)} where $i$ is the index of this
  4838. %% argument with respect to the other stack arguments.
  4839. As you're generating the code for parameter passing, take note of how
  4840. many stack arguments are needed for purposes of computing the
  4841. \itm{maxStack} discussed above.
  4842. Once the instructions for parameter passing have been generated, the
  4843. function call itself can be performed with an indirect function call,
  4844. for which I recommend creating the new instruction
  4845. \code{indirect-callq}. Of course, the return value from the function
  4846. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  4847. \begin{lstlisting}
  4848. (indirect-callq |\itm{fun}|)
  4849. (movq (reg rax) |\itm{lhs}|)
  4850. \end{lstlisting}
  4851. The rest of the passes need only minor modifications to handle the new
  4852. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  4853. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  4854. (written variables) for an \code{indirect-callq} instruction, I
  4855. recommend including all the caller save registers, which will have the
  4856. affect of making sure that no caller save register actually needs to be
  4857. saved. In \code{patch-instructions}, you should deal with the x86
  4858. idiosyncrasy that the destination argument of \code{leaq} must be a
  4859. register.
  4860. For the \code{print-x86} pass, I recommend the following translations:
  4861. \begin{lstlisting}
  4862. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  4863. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  4864. \end{lstlisting}
  4865. For function definitions, the \code{print-x86} pass should add the
  4866. code for saving and restoring the callee save registers, if you
  4867. haven't already done that.
  4868. \section{An Example Translation}
  4869. Figure~\ref{fig:add-fun} shows an example translation of a simple
  4870. function in $R_4$ to x86. The figure includes the results of the
  4871. \code{flatten} and \code{select-instructions} passes. Can you see any
  4872. ways to improve the translation?
  4873. \begin{figure}[tbp]
  4874. \begin{tabular}{lll}
  4875. \begin{minipage}{0.5\textwidth}
  4876. \begin{lstlisting}
  4877. (program
  4878. (define (add [x : Integer]
  4879. [y : Integer])
  4880. : Integer (+ x y))
  4881. (add 40 2))
  4882. \end{lstlisting}
  4883. $\Downarrow$
  4884. \begin{lstlisting}
  4885. (program (t.1 t.2)
  4886. (defines
  4887. (define (add.1 [x.1 : Integer]
  4888. [y.1 : Integer])
  4889. : Integer (t.3)
  4890. (assign t.3 (+ x.1 y.1))
  4891. (return t.3)))
  4892. (assign t.1 (function-ref add.1))
  4893. (assign t.2 (app t.1 40 2))
  4894. (return t.2))
  4895. \end{lstlisting}
  4896. $\Downarrow$
  4897. \begin{lstlisting}
  4898. (program ((rs.1 t.1 t.2) 0)
  4899. (type Integer)
  4900. (defines
  4901. (define (add28545) 3
  4902. ((rs.2 x.2 y.3 t.4) 0)
  4903. (movq (reg rdi) (var rs.2))
  4904. (movq (reg rsi) (var x.2))
  4905. (movq (reg rdx) (var y.3))
  4906. (movq (var x.2) (var t.4))
  4907. (addq (var y.3) (var t.4))
  4908. (movq (var t.4) (reg rax))))
  4909. (movq (int 16384) (reg rdi))
  4910. (movq (int 16) (reg rsi))
  4911. (callq initialize)
  4912. (movq (global-value rootstack_begin)
  4913. (var rs.1))
  4914. (leaq (function-ref add28545) (var t.1))
  4915. (movq (var rs.1) (reg rdi))
  4916. (movq (int 40) (reg rsi))
  4917. (movq (int 2) (reg rdx))
  4918. (indirect-callq (var t.1))
  4919. (movq (reg rax) (var t.2))
  4920. (movq (var t.2) (reg rax)))
  4921. \end{lstlisting}
  4922. \end{minipage}
  4923. &
  4924. \begin{minipage}{0.4\textwidth}
  4925. $\Downarrow$
  4926. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4927. .globl add28545
  4928. add28545:
  4929. pushq %rbp
  4930. movq %rsp, %rbp
  4931. pushq %r15
  4932. pushq %r14
  4933. pushq %r13
  4934. pushq %r12
  4935. pushq %rbx
  4936. subq $8, %rsp
  4937. movq %rdi, %rbx
  4938. movq %rsi, %rbx
  4939. movq %rdx, %rcx
  4940. addq %rcx, %rbx
  4941. movq %rbx, %rax
  4942. addq $8, %rsp
  4943. popq %rbx
  4944. popq %r12
  4945. popq %r13
  4946. popq %r14
  4947. popq %r15
  4948. popq %rbp
  4949. retq
  4950. .globl _main
  4951. _main:
  4952. pushq %rbp
  4953. movq %rsp, %rbp
  4954. pushq %r15
  4955. pushq %r14
  4956. pushq %r13
  4957. pushq %r12
  4958. pushq %rbx
  4959. subq $8, %rsp
  4960. movq $16384, %rdi
  4961. movq $16, %rsi
  4962. callq _initialize
  4963. movq _rootstack_begin(%rip), %rcx
  4964. leaq add28545(%rip), %rbx
  4965. movq %rcx, %rdi
  4966. movq $40, %rsi
  4967. movq $2, %rdx
  4968. callq *%rbx
  4969. movq %rax, %rbx
  4970. movq %rbx, %rax
  4971. movq %rax, %rdi
  4972. callq _print_int
  4973. movq $0, %rax
  4974. addq $8, %rsp
  4975. popq %rbx
  4976. popq %r12
  4977. popq %r13
  4978. popq %r14
  4979. popq %r15
  4980. popq %rbp
  4981. retq
  4982. \end{lstlisting}
  4983. \end{minipage}
  4984. \end{tabular}
  4985. \caption{Example compilation of a simple function to x86.}
  4986. \label{fig:add-fun}
  4987. \end{figure}
  4988. \begin{exercise}\normalfont
  4989. Expand your compiler to handle $R_4$ as outlined in this section.
  4990. Create 5 new programs that use functions, including examples that pass
  4991. functions and return functions from other functions, and test your
  4992. compiler on these new programs and all of your previously created test
  4993. programs.
  4994. \end{exercise}
  4995. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4996. \chapter{Lexically Scoped Functions}
  4997. \label{ch:lambdas}
  4998. This chapter studies lexically scoped functions as they appear in
  4999. functional languages such as Racket. By lexical scoping we mean that a
  5000. function's body may refer to variables whose binding site is outside
  5001. of the function, in an enclosing scope.
  5002. %
  5003. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5004. anonymous function defined using the \key{lambda} form. The body of
  5005. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5006. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5007. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5008. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5009. returned from the function \code{f}. Below the definition of \code{f},
  5010. we have two calls to \code{f} with different arguments for \code{x},
  5011. first \code{5} then \code{3}. The functions returned from \code{f} are
  5012. bound to variables \code{g} and \code{h}. Even though these two
  5013. functions were created by the same \code{lambda}, they are really
  5014. different functions because they use different values for
  5015. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5016. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5017. the result of this program is \code{42}.
  5018. \begin{figure}[btp]
  5019. \begin{lstlisting}
  5020. (define (f [x : Integer]) : (Integer -> Integer)
  5021. (let ([y 4])
  5022. (lambda: ([z : Integer]) : Integer
  5023. (+ x (+ y z)))))
  5024. (let ([g (f 5)])
  5025. (let ([h (f 3)])
  5026. (+ (g 11) (h 15))))
  5027. \end{lstlisting}
  5028. \caption{Example of a lexically scoped function.}
  5029. \label{fig:lexical-scoping}
  5030. \end{figure}
  5031. \section{The $R_5$ Language}
  5032. The syntax for this language with anonymous functions and lexical
  5033. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5034. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5035. for function application. In this chapter we shall descibe how to
  5036. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5037. into a combination of functions (as in $R_4$) and tuples (as in
  5038. $R_3$).
  5039. \begin{figure}[tp]
  5040. \centering
  5041. \fbox{
  5042. \begin{minipage}{0.96\textwidth}
  5043. \[
  5044. \begin{array}{lcl}
  5045. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5046. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5047. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5048. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5049. \mid (\key{+} \; \Exp\;\Exp)} \\
  5050. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  5051. \mid \key{\#t} \mid \key{\#f} \mid
  5052. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5053. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5054. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5055. (\key{vector-ref}\;\Exp\;\Int)} \\
  5056. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5057. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5058. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5059. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5060. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5061. \end{array}
  5062. \]
  5063. \end{minipage}
  5064. }
  5065. \caption{Syntax of $R_5$, extending $R_4$ with \key{lambda}.}
  5066. \label{fig:r5-syntax}
  5067. \end{figure}
  5068. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  5069. functions with top-level function definitions. However, our compiler
  5070. must provide special treatment to variable occurences such as \code{x}
  5071. and \code{y} in the body of the \code{lambda} of
  5072. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  5073. refer to variables defined outside the function. To identify such
  5074. variable occurences, we review the standard notion of free variable.
  5075. \begin{definition}
  5076. A variable is \emph{free with respect to an expression} $e$ if the
  5077. variable occurs inside $e$ but does not have an enclosing binding in
  5078. $e$.
  5079. \end{definition}
  5080. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5081. free with respect to the expression \code{(+ x (+ y z))}. On the
  5082. other hand, only \code{x} and \code{y} are free with respect to the
  5083. following expression becuase \code{z} is bound by the \code{lambda}.
  5084. \begin{lstlisting}
  5085. (lambda: ([z : Integer]) : Integer
  5086. (+ x (+ y z)))
  5087. \end{lstlisting}
  5088. Once we have identified the free variables of a \code{lambda}, we need
  5089. to arrange for some way to transport, at runtime, the values of those
  5090. variables from the point where the \code{lambda} was created to the
  5091. point where the \code{lambda} is applied. Referring again to
  5092. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5093. needs to be used in the application of \code{g} to \code{11}, but the
  5094. binding of \code{x} to \code{3} needs to be used in the application of
  5095. \code{h} to \code{15}. The solution is to bundle the values of the
  5096. free variables together with the function pointer for the lambda's
  5097. code into a data structure called a \emph{closure}. Fortunately, we
  5098. already have the appropriate ingredients to make closures,
  5099. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5100. gave us function pointers. The function pointer shall reside at index
  5101. $0$ and the values for free variables will fill in the rest of the
  5102. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5103. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5104. Because the two closures came from the same \key{lambda}, they share
  5105. the same code but differ in the values for free variable \code{x}.
  5106. \begin{figure}[tbp]
  5107. \centering \includegraphics[width=0.6\textwidth]{closures}
  5108. \caption{Example closure representation for the \key{lambda}'s
  5109. in Figure~\ref{fig:lexical-scoping}.}
  5110. \label{fig:closures}
  5111. \end{figure}
  5112. \section{Interpreting $R_5$}
  5113. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5114. $R_5$. There are several things to worth noting. First, and most
  5115. importantly, the match clause for \key{lambda} saves the current
  5116. environment inside the returned \key{lambda}. Then the clause for
  5117. \key{app} uses the environment from the \key{lambda}, the
  5118. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  5119. course, the \code{lam-env} environment is extending with the mapping
  5120. parameters to argument values. To enable mutual recursion and allow a
  5121. unified handling of functions created with \key{lambda} and with
  5122. \key{define}, the match clause for \key{program} includes a second
  5123. pass over the top-level functions to set their environments to be the
  5124. top-level environment.
  5125. \begin{figure}[tbp]
  5126. \begin{lstlisting}
  5127. (define (interp-R5 env)
  5128. (lambda (ast)
  5129. (match ast
  5130. ...
  5131. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5132. `(lambda ,xs ,body ,env)]
  5133. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5134. (mcons f `(lambda ,xs ,body))]
  5135. [`(program ,defs ... ,body)
  5136. (let ([top-level (map (interp-R5 '()) defs)])
  5137. (for/list ([b top-level])
  5138. (set-mcdr! b (match (mcdr b)
  5139. [`(lambda ,xs ,body)
  5140. `(lambda ,xs ,body ,top-level)])))
  5141. ((interp-R5 top-level) body))]
  5142. [`(,fun ,args ...)
  5143. (define arg-vals (map (interp-R5 env) args))
  5144. (define fun-val ((interp-R5 env) fun))
  5145. (match fun-val
  5146. [`(lambda (,xs ...) ,body ,lam-env)
  5147. (define new-env (append (map cons xs arg-vals) lam-env))
  5148. ((interp-R5 new-env) body)]
  5149. [else (error "interp-R5, expected function, not" fun-val)])]
  5150. )))
  5151. \end{lstlisting}
  5152. \caption{Interpreter for $R_5$.}
  5153. \label{fig:interp-R5}
  5154. \end{figure}
  5155. \section{Type Checking $R_5$}
  5156. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5157. \key{lambda} form. The body of the \key{lambda} is checked in an
  5158. environment that includes the current environment (because it is
  5159. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5160. require the body's type to match the declared return type.
  5161. \begin{figure}[tbp]
  5162. \begin{lstlisting}
  5163. (define (typecheck-R5 env)
  5164. (lambda (e)
  5165. (match e
  5166. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5167. (define new-env (append (map cons xs Ts) env))
  5168. (define bodyT ((typecheck-R5 new-env) body))
  5169. (cond [(equal? rT bodyT)
  5170. `(,@Ts -> ,rT)]
  5171. [else
  5172. (error "mismatch in return type" bodyT rT)])]
  5173. ...
  5174. )))
  5175. \end{lstlisting}
  5176. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5177. \label{fig:typecheck-R5}
  5178. \end{figure}
  5179. \section{Closure Conversion}
  5180. The compiling of lexically-scoped functions into C-style functions is
  5181. accomplished in the pass \code{convert-to-closures} that comes after
  5182. \code{reveal-functions} and before flatten. This pass needs to treat
  5183. regular function calls differently from applying primitive operators,
  5184. and \code{reveal-functions} differentiates those two cases for us.
  5185. As usual, we shall implement the pass as a recursive function over the
  5186. AST. All of the action is in the clauses for \key{lambda} and
  5187. \key{app} (function application). We transform a \key{lambda}
  5188. expression into an expression that creates a closure, that is, creates
  5189. a vector whose first element is a function pointer and the rest of the
  5190. elements are the free variables of the \key{lambda}. The \itm{name}
  5191. is a unique symbol generated to identify the function.
  5192. \begin{tabular}{lll}
  5193. \begin{minipage}{0.4\textwidth}
  5194. \begin{lstlisting}
  5195. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5196. \end{lstlisting}
  5197. \end{minipage}
  5198. &
  5199. $\Rightarrow$
  5200. &
  5201. \begin{minipage}{0.4\textwidth}
  5202. \begin{lstlisting}
  5203. (vector |\itm{name}| |\itm{fvs}| ...)
  5204. \end{lstlisting}
  5205. \end{minipage}
  5206. \end{tabular} \\
  5207. %
  5208. In addition to transforming each \key{lambda} into a \key{vector}, we
  5209. must create a top-level function definition for each \key{lambda}, as
  5210. shown below.
  5211. \begin{lstlisting}
  5212. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  5213. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5214. ...
  5215. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5216. |\itm{body'}|)...))
  5217. \end{lstlisting}
  5218. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  5219. the normal parameters of the \key{lambda}. The sequence of \key{let}
  5220. forms being the free variables to their values obtained from the
  5221. closure.
  5222. We transform function application into code that retreives the
  5223. function pointer from the closure and then calls the function, passing
  5224. in the closure as the first argument. We bind $e'$ to a temporary
  5225. variable to avoid code duplication.
  5226. \begin{tabular}{lll}
  5227. \begin{minipage}{0.3\textwidth}
  5228. \begin{lstlisting}
  5229. (app |$e$| |\itm{es}| ...)
  5230. \end{lstlisting}
  5231. \end{minipage}
  5232. &
  5233. $\Rightarrow$
  5234. &
  5235. \begin{minipage}{0.5\textwidth}
  5236. \begin{lstlisting}
  5237. (let ([|\itm{tmp}| |$e'$|])
  5238. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5239. \end{lstlisting}
  5240. \end{minipage}
  5241. \end{tabular} \\
  5242. There is also the question of what to do with top-level function
  5243. definitions. To maintain a uniform translation of function
  5244. application, we turn function references into closures.
  5245. \begin{tabular}{lll}
  5246. \begin{minipage}{0.3\textwidth}
  5247. \begin{lstlisting}
  5248. (function-ref |$f$|)
  5249. \end{lstlisting}
  5250. \end{minipage}
  5251. &
  5252. $\Rightarrow$
  5253. &
  5254. \begin{minipage}{0.5\textwidth}
  5255. \begin{lstlisting}
  5256. (vector (function-ref |$f$|))
  5257. \end{lstlisting}
  5258. \end{minipage}
  5259. \end{tabular} \\
  5260. %
  5261. The top-level function definitions need to be updated as well to take
  5262. an extra closure parameter.
  5263. \section{An Example Translation}
  5264. \label{sec:example-lambda}
  5265. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5266. conversion for the example program demonstrating lexical scoping that
  5267. we discussed at the beginning of this chapter.
  5268. \begin{figure}[h]
  5269. \begin{minipage}{0.8\textwidth}
  5270. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5271. (program
  5272. (define (f [x : Integer]) : (Integer -> Integer)
  5273. (let ([y 4])
  5274. (lambda: ([z : Integer]) : Integer
  5275. (+ x (+ y z)))))
  5276. (let ([g (f 5)])
  5277. (let ([h (f 3)])
  5278. (+ (g 11) (h 15)))))
  5279. \end{lstlisting}
  5280. $\Downarrow$
  5281. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5282. (program (type Integer)
  5283. (define (f (x : Integer)) : (Integer -> Integer)
  5284. (let ((y 4))
  5285. (lambda: ((z : Integer)) : Integer
  5286. (+ x (+ y z)))))
  5287. (let ((g (app (function-ref f) 5)))
  5288. (let ((h (app (function-ref f) 3)))
  5289. (+ (app g 11) (app h 15)))))
  5290. \end{lstlisting}
  5291. $\Downarrow$
  5292. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5293. (program (type Integer)
  5294. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5295. (let ((y 4))
  5296. (vector (function-ref lam.1) x y)))
  5297. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5298. (let ((x (vector-ref clos.2 1)))
  5299. (let ((y (vector-ref clos.2 2)))
  5300. (+ x (+ y z)))))
  5301. (let ((g (let ((t.1 (vector (function-ref f))))
  5302. (app (vector-ref t.1 0) t.1 5))))
  5303. (let ((h (let ((t.2 (vector (function-ref f))))
  5304. (app (vector-ref t.2 0) t.2 3))))
  5305. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5306. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5307. \end{lstlisting}
  5308. \end{minipage}
  5309. \caption{Example of closure conversion.}
  5310. \label{fig:lexical-functions-example}
  5311. \end{figure}
  5312. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5313. \chapter{Dynamic Typing}
  5314. \label{ch:type-dynamic}
  5315. In this chapter we discuss the compilation of a dynamically typed
  5316. language, named $R_7$, that is a subset of the Racket language. (In
  5317. the previous chapters we have studied subsets of the \emph{Typed}
  5318. Racket language.) In dynamically typed languages, an expression may
  5319. produce values of differing type. Consider the following example with
  5320. a conditional expression that may return a Boolean or an integer
  5321. depending on the input to the program.
  5322. \begin{lstlisting}
  5323. (not (if (eq? (read) 1) #f 0))
  5324. \end{lstlisting}
  5325. Languages that allow expressions to produce different kinds of values
  5326. are called \emph{polymorphic}, and there are many kinds of
  5327. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5328. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5329. Another characteristic of dynamically typed languages is that
  5330. primitive operations, such as \code{not}, are often defined to operate
  5331. on many different types of values. In fact, in Racket, the \code{not}
  5332. operator produces a result for any kind of value: given \code{\#f} it
  5333. returns \code{\#t} and given anything else it returns \code{\#f}.
  5334. Furthermore, even when primitive operations restrict their inputs to
  5335. values of a certain type, this restriction is enforced at runtime
  5336. instead of during compilation. For example, the following vector
  5337. reference results in a run-time contract violation.
  5338. \begin{lstlisting}
  5339. (vector-ref (vector 42) #t)
  5340. \end{lstlisting}
  5341. Let us consider how we might compile untyped Racket to x86, thinking
  5342. about the first example above. Our bit-level representation of the
  5343. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5344. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5345. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5346. \code{not}, in general, cannot be determined at compile time, but
  5347. depends on the runtime type of its input, as in the example above that
  5348. depends on the result of \code{(read)}.
  5349. The way around this problem is to include information about a value's
  5350. runtime type in the value itself, so that this information can be
  5351. inspected by operators such as \code{not}. In particular, we shall
  5352. steal the 3 right-most bits from our 64-bit values to encode the
  5353. runtime type. We shall use $001$ to identify integers, $100$ for
  5354. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  5355. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5356. define the following auxilliary function.
  5357. \begin{align*}
  5358. \itm{tagof}(\key{Integer}) &= 001 \\
  5359. \itm{tagof}(\key{Boolean}) &= 100 \\
  5360. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5361. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5362. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5363. \itm{tagof}(\key{Void}) &= 101
  5364. \end{align*}
  5365. (We shall say more about the new \key{Vectorof} type shortly.)
  5366. This stealing of 3 bits comes at some
  5367. price: our integers are reduced to ranging from $-2^{60}$ to
  5368. $2^{60}$. The stealing does not adversely affect vectors and
  5369. procedures because those values are addresses, and our addresses are
  5370. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5371. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5372. bits with the tag and we can simply zero-out the tag to recover the
  5373. original address.
  5374. In some sense, these tagged values are a new kind of value. Indeed,
  5375. we can extend our \emph{typed} language with tagged values by adding a
  5376. new type to classify them, called \key{Any}, and with operations for
  5377. creating and using tagged values, creating the $R_6$ language defined
  5378. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5379. support for polymorphism and runtime types that we need to support
  5380. dynamic typing.
  5381. We shall implement our untyped language $R_7$ by compiling it to
  5382. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5383. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5384. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5385. \label{sec:r6-lang}
  5386. \begin{figure}[tp]
  5387. \centering
  5388. \fbox{
  5389. \begin{minipage}{0.97\textwidth}
  5390. \[
  5391. \begin{array}{lcl}
  5392. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5393. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5394. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5395. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5396. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5397. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5398. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5399. \mid (\key{+} \; \Exp\;\Exp)} \\
  5400. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5401. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5402. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5403. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5404. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5405. (\key{vector-ref}\;\Exp\;\Int)} \\
  5406. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5407. &\mid& \gray{(\Exp \; \Exp^{*})
  5408. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5409. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5410. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5411. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  5412. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5413. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5414. \end{array}
  5415. \]
  5416. \end{minipage}
  5417. }
  5418. \caption{Syntax of $R_6$, extending $R_5$ with \key{Any}.}
  5419. \label{fig:r6-syntax}
  5420. \end{figure}
  5421. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5422. $(\key{inject}\; e\; T)$ form converts the value produced by
  5423. expression $e$ of type $T$ into a tagged value. The
  5424. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5425. expression $e$ into a value of type $T$ or else halts the program if
  5426. the type tag does not match $T$. Note that in both \key{inject} and
  5427. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5428. which simplifies the implementation and corresponds with what is
  5429. needed for compiling untyped Racket. The type predicates,
  5430. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5431. if the tag corresponds to the predicate, and return \key{\#t}
  5432. otherwise.
  5433. %
  5434. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5435. \begin{figure}[tbp]
  5436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5437. (define type-predicates
  5438. (set 'boolean? 'integer? 'vector? 'procedure?))
  5439. (define (typecheck-R6 env)
  5440. (lambda (e)
  5441. (define recur (typecheck-R6 env))
  5442. (match e
  5443. [`(inject ,(app recur new-e e-ty) ,ty)
  5444. (cond
  5445. [(equal? e-ty ty)
  5446. (values `(inject ,new-e ,ty) 'Any)]
  5447. [else
  5448. (error "inject expected ~a to have type ~a" e ty)])]
  5449. [`(project ,(app recur new-e e-ty) ,ty)
  5450. (cond
  5451. [(equal? e-ty 'Any)
  5452. (values `(project ,new-e ,ty) ty)]
  5453. [else
  5454. (error "project expected ~a to have type Any" e)])]
  5455. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5456. (define-values (new-e e-ty) (recur e))
  5457. (cond
  5458. [(equal? e-ty 'Any)
  5459. (values `(,pred ,new-e) 'Boolean)]
  5460. [else
  5461. (error "predicate expected arg of type Any, not" e-ty)])]
  5462. [`(vector-ref ,(app recur e t) ,i)
  5463. (match t
  5464. [`(Vector ,ts ...) ...]
  5465. [`(Vectorof ,t)
  5466. (unless (exact-nonnegative-integer? i)
  5467. (error 'type-check "invalid index ~a" i))
  5468. (values `(vector-ref ,e ,i) t)]
  5469. [else (error "expected a vector in vector-ref, not" t)])]
  5470. [`(vector-set! ,(app recur e-vec^ t-vec) ,i
  5471. ,(app recur e-arg^ t-arg))
  5472. (match t-vec
  5473. [`(Vector ,ts ...) ...]
  5474. [`(Vectorof ,t)
  5475. (unless (exact-nonnegative-integer? i)
  5476. (error 'type-check "invalid index ~a" i))
  5477. (unless (equal? t t-arg)
  5478. (error 'type-check "type mismatch in vector-set! ~a ~a"
  5479. t t-arg))
  5480. (values `(vector-set! ,e-vec^
  5481. ,i
  5482. ,e-arg^) 'Void)]
  5483. [else (error 'type-check
  5484. "expected a vector in vector-set!, not ~a"
  5485. t-vec)])]
  5486. ...
  5487. )))
  5488. \end{lstlisting}
  5489. \caption{Type checker for the $R_6$ language.}
  5490. \label{fig:typecheck-R6}
  5491. \end{figure}
  5492. % to do: add rules for vector-ref, etc. for Vectorof
  5493. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5494. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5495. for $R_6$.
  5496. \begin{figure}[tbp]
  5497. \begin{lstlisting}
  5498. (define primitives (set 'boolean? ...))
  5499. (define (interp-op op)
  5500. (match op
  5501. ['boolean? (lambda (v)
  5502. (match v
  5503. [`(tagged ,v1 Boolean) #t]
  5504. [else #f]))]
  5505. ...))
  5506. (define (interp-R6 env)
  5507. (lambda (ast)
  5508. (match ast
  5509. [`(inject ,e ,t)
  5510. `(tagged ,((interp-R6 env) e) ,t)]
  5511. [`(project ,e ,t2)
  5512. (define v ((interp-R6 env) e))
  5513. (match v
  5514. [`(tagged ,v1 ,t1)
  5515. (cond [(equal? t1 t2)
  5516. v1]
  5517. [else
  5518. (error "in project, type mismatch" t1 t2)])]
  5519. [else
  5520. (error "in project, expected tagged value" v)])]
  5521. ...)))
  5522. \end{lstlisting}
  5523. \caption{Interpreter for $R_6$.}
  5524. \label{fig:interp-R6}
  5525. \end{figure}
  5526. \section{The $R_7$ Language: Untyped Racket}
  5527. \label{sec:r7-lang}
  5528. \begin{figure}[tp]
  5529. \centering
  5530. \fbox{
  5531. \begin{minipage}{0.97\textwidth}
  5532. \[
  5533. \begin{array}{rcl}
  5534. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5535. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5536. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5537. &\mid& \key{\#t} \mid \key{\#f} \mid
  5538. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5539. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5540. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5541. (\key{vector-ref}\;\Exp\;\Exp) \\
  5542. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5543. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5544. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5545. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5546. \end{array}
  5547. \]
  5548. \end{minipage}
  5549. }
  5550. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  5551. \label{fig:r7-syntax}
  5552. \end{figure}
  5553. The syntax of $R_7$, our subset of Racket, is defined in
  5554. Figure~\ref{fig:r7-syntax}.
  5555. %
  5556. The definitional interpreter for $R_7$ is given in
  5557. Figure~\ref{fig:interp-R7}.
  5558. \begin{figure}[tbp]
  5559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5560. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  5561. (define (valid-op? op) (member op '(+ - and or not)))
  5562. (define (interp-r7 env)
  5563. (lambda (ast)
  5564. (define recur (interp-r7 env))
  5565. (match ast
  5566. [(? symbol?) (lookup ast env)]
  5567. [(? integer?) `(inject ,ast Integer)]
  5568. [#t `(inject #t Boolean)]
  5569. [#f `(inject #f Boolean)]
  5570. [`(read) `(inject ,(read-fixnum) Integer)]
  5571. [`(lambda (,xs ...) ,body)
  5572. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  5573. [`(define (,f ,xs ...) ,body)
  5574. (mcons f `(lambda ,xs ,body))]
  5575. [`(program ,ds ... ,body)
  5576. (let ([top-level (map (interp-r7 '()) ds)])
  5577. (for/list ([b top-level])
  5578. (set-mcdr! b (match (mcdr b)
  5579. [`(lambda ,xs ,body)
  5580. `(inject (lambda ,xs ,body ,top-level)
  5581. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  5582. ((interp-r7 top-level) body))]
  5583. [`(vector ,(app recur elts) ...)
  5584. (define tys (map get-tagged-type elts))
  5585. `(inject ,(apply vector elts) (Vector ,@tys))]
  5586. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  5587. (match v1
  5588. [`(inject ,vec ,ty)
  5589. (vector-set! vec n v2)
  5590. `(inject (void) Void)])]
  5591. [`(vector-ref ,(app recur v) ,n)
  5592. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  5593. [`(let ([,x ,(app recur v)]) ,body)
  5594. ((interp-r7 (cons (cons x v) env)) body)]
  5595. [`(,op ,es ...) #:when (valid-op? op)
  5596. (interp-r7-op op (map recur es))]
  5597. [`(eq? ,(app recur l) ,(app recur r))
  5598. `(inject ,(equal? l r) Boolean)]
  5599. [`(if ,(app recur q) ,t ,f)
  5600. (match q
  5601. [`(inject #f Boolean) (recur f)]
  5602. [else (recur t)])]
  5603. [`(,(app recur f-val) ,(app recur vs) ...)
  5604. (match f-val
  5605. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  5606. (define new-env (append (map cons xs vs) lam-env))
  5607. ((interp-r7 new-env) body)]
  5608. [else (error "interp-r7, expected function, not" f-val)])])))
  5609. \end{lstlisting}
  5610. \caption{Interpreter for the $R_7$ language.}
  5611. \label{fig:interp-R7}
  5612. \end{figure}
  5613. \section{Compiling $R_6$}
  5614. \label{sec:compile-r6}
  5615. Most of the compiler passes only require straightforward changes. The
  5616. interesting part is in instruction selection.
  5617. \paragraph{Inject}
  5618. We recommend compiling an \key{inject} as follows if the type is
  5619. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5620. destination to the left by the number of bits specified by the source
  5621. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5622. instruction to combine the tag and the value to form the tagged value.
  5623. \\
  5624. \begin{tabular}{lll}
  5625. \begin{minipage}{0.4\textwidth}
  5626. \begin{lstlisting}
  5627. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5628. \end{lstlisting}
  5629. \end{minipage}
  5630. &
  5631. $\Rightarrow$
  5632. &
  5633. \begin{minipage}{0.5\textwidth}
  5634. \begin{lstlisting}
  5635. (movq |$e'$| |\itm{lhs}'|)
  5636. (salq (int 2) |\itm{lhs}'|)
  5637. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5638. \end{lstlisting}
  5639. \end{minipage}
  5640. \end{tabular} \\
  5641. The instruction selection for vectors and procedures is different
  5642. because their is no need to shift them to the left. The rightmost 3
  5643. bits are already zeros as described above. So we combine the value and
  5644. the tag using
  5645. \key{orq}. \\
  5646. \begin{tabular}{lll}
  5647. \begin{minipage}{0.4\textwidth}
  5648. \begin{lstlisting}
  5649. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5650. \end{lstlisting}
  5651. \end{minipage}
  5652. &
  5653. $\Rightarrow$
  5654. &
  5655. \begin{minipage}{0.5\textwidth}
  5656. \begin{lstlisting}
  5657. (movq |$e'$| |\itm{lhs}'|)
  5658. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5659. \end{lstlisting}
  5660. \end{minipage}
  5661. \end{tabular} \\
  5662. \paragraph{Project}
  5663. The instruction selection for \key{project} is a bit more involved.
  5664. Like \key{inject}, the instructions are different depending on whether
  5665. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5666. Boolean). The following shows the instruction selection for Integer
  5667. and Boolean. We first check to see if the tag on the tagged value
  5668. matches the tag of the target type $T$. If not, we halt the program by
  5669. calling the \code{exit} function. If we have a match, we need to
  5670. produce an untagged value by shifting it to the right by 2 bits.
  5671. %
  5672. \\
  5673. \begin{tabular}{lll}
  5674. \begin{minipage}{0.4\textwidth}
  5675. \begin{lstlisting}
  5676. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5677. \end{lstlisting}
  5678. \end{minipage}
  5679. &
  5680. $\Rightarrow$
  5681. &
  5682. \begin{minipage}{0.5\textwidth}
  5683. \begin{lstlisting}
  5684. (movq |$e'$| |\itm{lhs}'|)
  5685. (andq (int 3) |\itm{lhs}'|)
  5686. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5687. ((movq |$e'$| |\itm{lhs}'|)
  5688. (sarq (int 2) |\itm{lhs}'|))
  5689. ((callq exit)))
  5690. \end{lstlisting}
  5691. \end{minipage}
  5692. \end{tabular} \\
  5693. %
  5694. The case for vectors and procedures begins in a similar way, checking
  5695. that the runtime tag matches the target type $T$ and exiting if there
  5696. is a mismatch. However, the way in which we convert the tagged value
  5697. to a value is different, as there is no need to shift. Instead we need
  5698. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5699. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5700. 1100$, and then applying \code{andq} with the tagged value get the
  5701. desired result. \\
  5702. %
  5703. \begin{tabular}{lll}
  5704. \begin{minipage}{0.4\textwidth}
  5705. \begin{lstlisting}
  5706. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5707. \end{lstlisting}
  5708. \end{minipage}
  5709. &
  5710. $\Rightarrow$
  5711. &
  5712. \begin{minipage}{0.5\textwidth}
  5713. \begin{lstlisting}
  5714. (movq |$e'$| |\itm{lhs}'|)
  5715. (andq (int 3) |\itm{lhs}'|)
  5716. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5717. ((movq (int 3) |\itm{lhs}'|)
  5718. (notq |\itm{lhs}'|)
  5719. (andq |$e'$| |\itm{lhs}'|))
  5720. ((callq exit)))
  5721. \end{lstlisting}
  5722. \end{minipage}
  5723. \end{tabular} \\
  5724. \paragraph{Type Predicates} We leave it to the reader to
  5725. devise a sequence of instructions to implement the type predicates
  5726. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5727. \section{Compiling $R_7$ to $R_6$}
  5728. \label{sec:compile-r7}
  5729. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5730. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5731. given a subexpression $e$ of $R_7$, the pass will produce an
  5732. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5733. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5734. the Boolean \code{\#t}, which must be injected to produce an
  5735. expression of type \key{Any}.
  5736. %
  5737. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5738. addition, is representative of compilation for many operations: the
  5739. arguments have type \key{Any} and must be projected to \key{Integer}
  5740. before the addition can be performed.
  5741. %
  5742. The compilation of \key{lambda} (third row of
  5743. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5744. produce type annotations, we simply use \key{Any}.
  5745. %
  5746. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5747. demonstrate how this pass has to account for some differences in
  5748. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5749. permissive than $R_6$ regarding what kind of values can be used in
  5750. various places. For example, the condition of an \key{if} does not
  5751. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5752. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5753. same type.
  5754. \begin{figure}[tbp]
  5755. \centering
  5756. \begin{tabular}{|lll|} \hline
  5757. \begin{minipage}{0.25\textwidth}
  5758. \begin{lstlisting}
  5759. #t
  5760. \end{lstlisting}
  5761. \end{minipage}
  5762. &
  5763. $\Rightarrow$
  5764. &
  5765. \begin{minipage}{0.6\textwidth}
  5766. \begin{lstlisting}
  5767. (inject #t Boolean)
  5768. \end{lstlisting}
  5769. \end{minipage}
  5770. \\[2ex]\hline
  5771. \begin{minipage}{0.25\textwidth}
  5772. \begin{lstlisting}
  5773. (+ |$e_1$| |$e_2$|)
  5774. \end{lstlisting}
  5775. \end{minipage}
  5776. &
  5777. $\Rightarrow$
  5778. &
  5779. \begin{minipage}{0.6\textwidth}
  5780. \begin{lstlisting}
  5781. (inject
  5782. (+ (project |$e'_1$| Integer)
  5783. (project |$e'_2$| Integer))
  5784. Integer)
  5785. \end{lstlisting}
  5786. \end{minipage}
  5787. \\[2ex]\hline
  5788. \begin{minipage}{0.25\textwidth}
  5789. \begin{lstlisting}
  5790. (lambda (|$x_1 \ldots$|) |$e$|)
  5791. \end{lstlisting}
  5792. \end{minipage}
  5793. &
  5794. $\Rightarrow$
  5795. &
  5796. \begin{minipage}{0.6\textwidth}
  5797. \begin{lstlisting}
  5798. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5799. (Any|$\ldots$|Any -> Any))
  5800. \end{lstlisting}
  5801. \end{minipage}
  5802. \\[2ex]\hline
  5803. \begin{minipage}{0.25\textwidth}
  5804. \begin{lstlisting}
  5805. (app |$e_0$| |$e_1 \ldots e_n$|)
  5806. \end{lstlisting}
  5807. \end{minipage}
  5808. &
  5809. $\Rightarrow$
  5810. &
  5811. \begin{minipage}{0.6\textwidth}
  5812. \begin{lstlisting}
  5813. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  5814. |$e'_1 \ldots e'_n$|)
  5815. \end{lstlisting}
  5816. \end{minipage}
  5817. \\[2ex]\hline
  5818. \begin{minipage}{0.25\textwidth}
  5819. \begin{lstlisting}
  5820. (vector-ref |$e_1$| |$e_2$|)
  5821. \end{lstlisting}
  5822. \end{minipage}
  5823. &
  5824. $\Rightarrow$
  5825. &
  5826. \begin{minipage}{0.6\textwidth}
  5827. \begin{lstlisting}
  5828. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  5829. (let ([tmp2 (project |$e'_2$| Integer)])
  5830. (vector-ref tmp1 tmp2)))
  5831. \end{lstlisting}
  5832. \end{minipage}
  5833. \\[2ex]\hline
  5834. \begin{minipage}{0.25\textwidth}
  5835. \begin{lstlisting}
  5836. (if |$e_1$| |$e_2$| |$e_3$|)
  5837. \end{lstlisting}
  5838. \end{minipage}
  5839. &
  5840. $\Rightarrow$
  5841. &
  5842. \begin{minipage}{0.6\textwidth}
  5843. \begin{lstlisting}
  5844. (if (eq? |$e'_1$| (inject #f Boolean))
  5845. |$e'_3$|
  5846. |$e'_2$|)
  5847. \end{lstlisting}
  5848. \end{minipage}
  5849. \\[2ex]\hline
  5850. \begin{minipage}{0.25\textwidth}
  5851. \begin{lstlisting}
  5852. (eq? |$e_1$| |$e_2$|)
  5853. \end{lstlisting}
  5854. \end{minipage}
  5855. &
  5856. $\Rightarrow$
  5857. &
  5858. \begin{minipage}{0.6\textwidth}
  5859. \begin{lstlisting}
  5860. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  5861. \end{lstlisting}
  5862. \end{minipage}
  5863. \\[2ex]\hline
  5864. \begin{minipage}{0.25\textwidth}
  5865. \begin{lstlisting}
  5866. (and |$e_1$| |$e_2$|)
  5867. \end{lstlisting}
  5868. \end{minipage}
  5869. &
  5870. $\Rightarrow$
  5871. &
  5872. \begin{minipage}{0.6\textwidth}
  5873. \begin{lstlisting}
  5874. (let ([tmp |$e'_1$|])
  5875. (if (eq? tmp (inject #f Boolean))
  5876. tmp
  5877. |$e'_2$|))
  5878. \end{lstlisting}
  5879. \end{minipage} \\\hline
  5880. \end{tabular} \\
  5881. \caption{Compiling $R_7$ to $R_6$.}
  5882. \label{fig:compile-r7-r6}
  5883. \end{figure}
  5884. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5885. \chapter{Gradual Typing}
  5886. \label{ch:gradual-typing}
  5887. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  5888. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5889. \chapter{Parametric Polymorphism}
  5890. \label{ch:parametric-polymorphism}
  5891. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  5892. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  5893. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5894. \chapter{High-level Optimization}
  5895. \label{ch:high-level-optimization}
  5896. This chapter will present a procedure inlining pass based on the
  5897. algorithm of \citet{Waddell:1997fk}.
  5898. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5899. \chapter{Appendix}
  5900. \section{Interpreters}
  5901. \label{appendix:interp}
  5902. We provide several interpreters in the \key{interp.rkt} file. The
  5903. \key{interp-scheme} function takes an AST in one of the Racket-like
  5904. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  5905. the program, returning the result value. The \key{interp-C} function
  5906. interprets an AST for a program in one of the C-like languages ($C_0,
  5907. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  5908. for an x86 program.
  5909. \section{Utility Functions}
  5910. \label{appendix:utilities}
  5911. The utility function described in this section can be found in the
  5912. \key{utilities.rkt} file.
  5913. The \key{read-program} function takes a file path and parses that file
  5914. (it must be a Racket program) into an abstract syntax tree (as an
  5915. S-expression) with a \key{program} AST at the top.
  5916. The \key{assert} function displays the error message \key{msg} if the
  5917. Boolean \key{bool} is false.
  5918. \begin{lstlisting}
  5919. (define (assert msg bool) ...)
  5920. \end{lstlisting}
  5921. The \key{lookup} function ...
  5922. The \key{map2} function ...
  5923. \subsection{Graphs}
  5924. \begin{itemize}
  5925. \item The \code{make-graph} function takes a list of vertices
  5926. (symbols) and returns a graph.
  5927. \item The \code{add-edge} function takes a graph and two vertices and
  5928. adds an edge to the graph that connects the two vertices. The graph
  5929. is updated in-place. There is no return value for this function.
  5930. \item The \code{adjacent} function takes a graph and a vertex and
  5931. returns the set of vertices that are adjacent to the given
  5932. vertex. The return value is a Racket \code{hash-set} so it can be
  5933. used with functions from the \code{racket/set} module.
  5934. \item The \code{vertices} function takes a graph and returns the list
  5935. of vertices in the graph.
  5936. \end{itemize}
  5937. \subsection{Testing}
  5938. The \key{interp-tests} function takes a compiler name (a string), a
  5939. description of the passes, an interpreter for the source language, a
  5940. test family name (a string), and a list of test numbers, and runs the
  5941. compiler passes and the interpreters to check whether the passes
  5942. correct. The description of the passes is a list with one entry per
  5943. pass. An entry is a list with three things: a string giving the name
  5944. of the pass, the function that implements the pass (a translator from
  5945. AST to AST), and a function that implements the interpreter (a
  5946. function from AST to result value) for the language of the output of
  5947. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  5948. good choice. The \key{interp-tests} function assumes that the
  5949. subdirectory \key{tests} has a bunch of Scheme programs whose names
  5950. all start with the family name, followed by an underscore and then the
  5951. test number, ending in \key{.scm}. Also, for each Scheme program there
  5952. is a file with the same number except that it ends with \key{.in} that
  5953. provides the input for the Scheme program.
  5954. \begin{lstlisting}
  5955. (define (interp-tests name passes test-family test-nums) ...
  5956. \end{lstlisting}
  5957. The compiler-tests function takes a compiler name (a string) a
  5958. description of the passes (see the comment for \key{interp-tests}) a
  5959. test family name (a string), and a list of test numbers (see the
  5960. comment for interp-tests), and runs the compiler to generate x86 (a
  5961. \key{.s} file) and then runs gcc to generate machine code. It runs
  5962. the machine code and checks that the output is 42.
  5963. \begin{lstlisting}
  5964. (define (compiler-tests name passes test-family test-nums) ...)
  5965. \end{lstlisting}
  5966. The compile-file function takes a description of the compiler passes
  5967. (see the comment for \key{interp-tests}) and returns a function that,
  5968. given a program file name (a string ending in \key{.scm}), applies all
  5969. of the passes and writes the output to a file whose name is the same
  5970. as the program file name but with \key{.scm} replaced with \key{.s}.
  5971. \begin{lstlisting}
  5972. (define (compile-file passes)
  5973. (lambda (prog-file-name) ...))
  5974. \end{lstlisting}
  5975. \section{x86 Instruction Set Quick-Reference}
  5976. \label{sec:x86-quick-reference}
  5977. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  5978. do. We write $A \to B$ to mean that the value of $A$ is written into
  5979. location $B$. Address offsets are given in bytes. The instruction
  5980. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  5981. registers (such as $\%rax$), or memory references (such as
  5982. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  5983. reference per instruction. Other operands must be immediates or
  5984. registers.
  5985. \begin{table}[tbp]
  5986. \centering
  5987. \begin{tabular}{l|l}
  5988. \textbf{Instruction} & \textbf{Operation} \\ \hline
  5989. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  5990. \texttt{negq} $A$ & $- A \to A$ \\
  5991. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  5992. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  5993. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  5994. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  5995. \texttt{retq} & Pops the return address and jumps to it \\
  5996. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  5997. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  5998. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  5999. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set flag \\
  6000. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag matches
  6001. the condition code, otherwise go to the next instructions.
  6002. The condition codes are \key{e} for ``equal'',
  6003. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6004. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6005. \texttt{jl} $L$ & \\
  6006. \texttt{jle} $L$ & \\
  6007. \texttt{jg} $L$ & \\
  6008. \texttt{jge} $L$ & \\
  6009. \texttt{jmp} $L$ & Jump to label $L$ \\
  6010. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6011. \texttt{movzbq} $A$, $B$ &
  6012. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6013. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6014. and the extra bytes of $B$ are set to zero.} \\
  6015. & \\
  6016. & \\
  6017. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6018. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6019. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6020. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6021. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6022. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6023. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6024. description of the condition codes. $A$ must be a single byte register
  6025. (e.g., \texttt{al} or \texttt{cl}).} \\
  6026. \texttt{setl} $A$ & \\
  6027. \texttt{setle} $A$ & \\
  6028. \texttt{setg} $A$ & \\
  6029. \texttt{setge} $A$ &
  6030. \end{tabular}
  6031. \vspace{5pt}
  6032. \caption{Quick-reference for the x86 instructions used in this book.}
  6033. \label{tab:x86-instr}
  6034. \end{table}
  6035. \bibliographystyle{plainnat}
  6036. \bibliography{all}
  6037. \end{document}
  6038. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6039. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6040. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6041. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6042. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6043. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6044. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6045. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6046. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6047. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6048. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6049. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6050. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6051. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6052. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6053. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6054. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6055. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6056. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6057. %% LocalWords: len prev rootlen heaplen setl lt