book.tex 236 KB

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