book.tex 251 KB

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