book.tex 291 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \definecolor{lightgray}{gray}{1}
  51. \newcommand{\black}[1]{{\color{black} #1}}
  52. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  53. %% For pictures
  54. \usepackage{tikz}
  55. \usetikzlibrary{arrows.meta}
  56. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  57. % Computer Modern is already the default. -Jeremy
  58. %\renewcommand{\ttdefault}{cmtt}
  59. \definecolor{comment-red}{rgb}{0.8,0,0}
  60. \if{0}
  61. % Peanut gallery comments:
  62. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  63. \newcommand{\margincomment}[1]{\marginpar{#1}}
  64. \else
  65. \newcommand{\rn}[1]{}
  66. \newcommand{\margincomment}[1]{}
  67. \fi
  68. \lstset{%
  69. language=Lisp,
  70. basicstyle=\ttfamily\small,
  71. escapechar=|,
  72. columns=flexible,
  73. moredelim=[is][\color{red}]{~}{~}
  74. }
  75. \newtheorem{theorem}{Theorem}
  76. \newtheorem{lemma}[theorem]{Lemma}
  77. \newtheorem{corollary}[theorem]{Corollary}
  78. \newtheorem{proposition}[theorem]{Proposition}
  79. \newtheorem{constraint}[theorem]{Constraint}
  80. \newtheorem{definition}[theorem]{Definition}
  81. \newtheorem{exercise}[theorem]{Exercise}
  82. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  83. % 'dedication' environment: To add a dedication paragraph at the start of book %
  84. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. \newenvironment{dedication}
  87. {
  88. \cleardoublepage
  89. \thispagestyle{empty}
  90. \vspace*{\stretch{1}}
  91. \hfill\begin{minipage}[t]{0.66\textwidth}
  92. \raggedright
  93. }
  94. {
  95. \end{minipage}
  96. \vspace*{\stretch{3}}
  97. \clearpage
  98. }
  99. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  100. % Chapter quote at the start of chapter %
  101. % Source: http://tex.stackexchange.com/a/53380 %
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. \makeatletter
  104. \renewcommand{\@chapapp}{}% Not necessary...
  105. \newenvironment{chapquote}[2][2em]
  106. {\setlength{\@tempdima}{#1}%
  107. \def\chapquote@author{#2}%
  108. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  109. \itshape}
  110. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  111. \makeatother
  112. \input{defs}
  113. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  114. \title{\Huge \textbf{Essentials of Compilation} \\
  115. \huge An Incremental Approach}
  116. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  117. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  118. Indiana University \\
  119. \\
  120. with contributions from: \\
  121. Carl Factora \\
  122. Andre Kuhlenschmidt \\
  123. Michael M. Vitousek \\
  124. Michael Vollmer \\
  125. Ryan Scott \\
  126. Cameron Swords
  127. }
  128. \begin{document}
  129. \frontmatter
  130. \maketitle
  131. \begin{dedication}
  132. This book is dedicated to the programming language wonks at Indiana
  133. University.
  134. \end{dedication}
  135. \tableofcontents
  136. \listoffigures
  137. %\listoftables
  138. \mainmatter
  139. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  140. \chapter*{Preface}
  141. The tradition of compiler writing at Indiana University goes back to
  142. research and courses about programming languages by Daniel Friedman in
  143. the 1970's and 1980's. Dan had conducted research on lazy
  144. evaluation~\citep{Friedman:1976aa} in the context of
  145. Lisp~\citep{McCarthy:1960dz} and then studied
  146. continuations~\citep{Felleisen:kx} and
  147. macros~\citep{Kohlbecker:1986dk} in the context of the
  148. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  149. of those courses, Kent Dybvig, went on to build Chez
  150. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  151. compiler for Scheme. After completing his Ph.D. at the University of
  152. North Carolina, Kent returned to teach at Indiana University.
  153. Throughout the 1990's and 2000's, Kent continued development of Chez
  154. Scheme and taught the compiler course.
  155. The compiler course evolved to incorporate novel pedagogical ideas
  156. while also including elements of effective real-world compilers. One
  157. of Dan's ideas was to split the compiler into many small ``passes'' so
  158. that the code for each pass would be easy to understood in isolation.
  159. (In contrast, most compilers of the time were organized into only a
  160. few monolithic passes for reasons of compile-time efficiency.) Kent,
  161. with later help from his students Dipanwita Sarkar and Andrew Keep,
  162. developed infrastructure to support this approach and evolved the
  163. course, first to use micro-sized passes and then into even smaller
  164. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  165. student in this compiler course in the early 2000's, as part of his
  166. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  167. the course immensely!
  168. One of Jeremy's classmates, Abdulaziz Ghuloum, observed that the
  169. front-to-back organization of the course made it difficult for
  170. students to understand the rationale for the compiler
  171. design. Abdulaziz proposed an incremental approach in which the
  172. students build the compiler in stages; they start by implementing a
  173. complete compiler for a very small subset of the input language, then
  174. in each subsequent stage they add a feature to the input language and
  175. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  176. In this way, the students see how the language features motivate
  177. aspects of the compiler design.
  178. After graduating from Indiana University in 2005, Jeremy went on to
  179. teach at the University of Colorado. He adapted the nano pass and
  180. incremental approaches to compiling a subset of the Python
  181. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  182. on the surface but there is a large overlap in the compiler techniques
  183. required for the two languages. Thus, Jeremy was able to teach much of
  184. the same content from the Indiana compiler course. He very much
  185. enjoyed teaching the course organized in this way, and even better,
  186. many of the students learned a lot and got excited about compilers.
  187. Jeremy returned to teach at Indiana University in 2013. In his
  188. absence the compiler course had switched from the front-to-back
  189. organization to a back-to-front organization. Seeing how well the
  190. incremental approach worked at Colorado, he started porting and
  191. adapting the structure of the Colorado course back into the land of
  192. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  193. the course is now about compiling a subset of Racket (and Typed
  194. Racket) to the x86 assembly language. The compiler is implemented in
  195. Racket 7.1~\citep{plt-tr}.
  196. This is the textbook for the incremental version of the compiler
  197. course at Indiana University (Spring 2016 - present) and it is the
  198. first open textbook for an Indiana compiler course. With this book we
  199. hope to make the Indiana compiler course available to people that have
  200. not had the chance to study in Bloomington in person. Many of the
  201. compiler design decisions in this book are drawn from the assignment
  202. descriptions of \cite{Dybvig:2010aa}. We have captured what we think are
  203. the most important topics from \cite{Dybvig:2010aa} but we have omitted
  204. topics that we think are less interesting conceptually and we have made
  205. simplifications to reduce complexity. In this way, this book leans
  206. more towards pedagogy than towards the absolute efficiency of the
  207. generated code. Also, the book differs in places where we saw the
  208. opportunity to make the topics more fun, such as in relating register
  209. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  210. \section*{Prerequisites}
  211. The material in this book is challenging but rewarding. It is meant to
  212. prepare students for a lifelong career in programming languages. We do
  213. not recommend this book for students who want to dabble in programming
  214. languages.
  215. The book uses the Racket language both for the implementation of the
  216. compiler and for the language that is compiled, so a student should be
  217. proficient with Racket (or Scheme) prior to reading this book. There
  218. are many other excellent resources for learning Scheme and
  219. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  220. is helpful but not necessary for the student to have prior exposure to
  221. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  222. obtain from a computer systems
  223. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  224. parts of x86-64 assembly language that are needed.
  225. %\section*{Structure of book}
  226. % You might want to add short description about each chapter in this book.
  227. %\section*{About the companion website}
  228. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  229. %\begin{itemize}
  230. % \item A link to (freely downlodable) latest version of this document.
  231. % \item Link to download LaTeX source for this document.
  232. % \item Miscellaneous material (e.g. suggested readings etc).
  233. %\end{itemize}
  234. \section*{Acknowledgments}
  235. Many people have contributed to the ideas, techniques, organization,
  236. and teaching of the materials in this book. We especially thank the
  237. following people.
  238. \begin{itemize}
  239. \item Bor-Yuh Evan Chang
  240. \item Kent Dybvig
  241. \item Daniel P. Friedman
  242. \item Ronald Garcia
  243. \item Abdulaziz Ghuloum
  244. \item Jay McCarthy
  245. \item Dipanwita Sarkar
  246. \item Andrew Keep
  247. \item Oscar Waddell
  248. \item Michael Wollowski
  249. \end{itemize}
  250. \mbox{}\\
  251. \noindent Jeremy G. Siek \\
  252. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  253. %\noindent Spring 2016
  254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  255. \chapter{Preliminaries}
  256. \label{ch:trees-recur}
  257. In this chapter, we review the basic tools that are needed for implementing a
  258. compiler. We use abstract syntax trees (ASTs), which refer to data structures in
  259. the compilers memory, rather than programs as they are stored on disk, in
  260. \emph{concrete syntax}.
  261. %
  262. ASTs can be represented in many different ways, depending on the programming
  263. language used to write the compiler.
  264. %
  265. Because this book uses Racket (\url{http://racket-lang.org}), a
  266. descendant of Lisp, we use S-expressions to represent programs
  267. (Section~\ref{sec:ast}). We use grammars to defined programming languages
  268. (Section~\ref{sec:grammar}) and pattern matching to inspect
  269. individual nodes in an AST (Section~\ref{sec:pattern-matching}). We
  270. use recursion to construct and deconstruct entire ASTs
  271. (Section~\ref{sec:recursion}). This chapter provides an brief
  272. introduction to these ideas.
  273. \section{Abstract Syntax Trees and S-expressions}
  274. \label{sec:ast}
  275. The primary data structure that is commonly used for representing
  276. programs is the \emph{abstract syntax tree} (AST). When considering
  277. some part of a program, a compiler needs to ask what kind of part it
  278. is and what sub-parts it has. For example, the program on the left,
  279. represented by an S-expression, corresponds to the AST on the right.
  280. \begin{center}
  281. \begin{minipage}{0.4\textwidth}
  282. \begin{lstlisting}
  283. (+ (read) (- 8))
  284. \end{lstlisting}
  285. \end{minipage}
  286. \begin{minipage}{0.4\textwidth}
  287. \begin{equation}
  288. \begin{tikzpicture}
  289. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  290. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  291. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  292. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  293. \draw[->] (plus) to (read);
  294. \draw[->] (plus) to (minus);
  295. \draw[->] (minus) to (8);
  296. \end{tikzpicture}
  297. \label{eq:arith-prog}
  298. \end{equation}
  299. \end{minipage}
  300. \end{center}
  301. We shall use the standard terminology for trees: each circle above is
  302. called a \emph{node}. The arrows connect a node to its \emph{children}
  303. (which are also nodes). The top-most node is the \emph{root}. Every
  304. node except for the root has a \emph{parent} (the node it is the child
  305. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  306. it is an \emph{internal} node.
  307. Recall that an \emph{symbolic expression} (S-expression) is either
  308. \begin{enumerate}
  309. \item an atom, or
  310. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  311. where $e_1$ and $e_2$ are each an S-expression.
  312. \end{enumerate}
  313. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the null
  314. value \code{'()}, etc.
  315. We can create an S-expression in Racket simply by writing a backquote
  316. (called a quasi-quote in Racket).
  317. followed by the textual representation of the S-expression.
  318. It is quite common to use S-expressions
  319. to represent a list, such as $a, b ,c$ in the following way:
  320. \begin{lstlisting}
  321. `(a . (b . (c . ())))
  322. \end{lstlisting}
  323. Each element of the list is in the first slot of a pair, and the
  324. second slot is either the rest of the list or the null value, to mark
  325. the end of the list. Such lists are so common that Racket provides
  326. special notation for them that removes the need for the periods
  327. and so many parenthesis:
  328. \begin{lstlisting}
  329. `(a b c)
  330. \end{lstlisting}
  331. For another example,
  332. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  333. by the following Racket expression:
  334. \begin{center}
  335. \texttt{`(+ (read) (- 8))}
  336. \end{center}
  337. When using S-expressions to represent ASTs, the convention is to
  338. represent each AST node as a list and to put the operation symbol at
  339. the front of the list. The rest of the list contains the children. So
  340. in the above case, the root AST node has operation \code{`+} and its
  341. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  342. diagram \eqref{eq:arith-prog}.
  343. To build larger S-expressions one often needs to splice together
  344. several smaller S-expressions. Racket provides the comma operator to
  345. splice an S-expression into a larger one. For example, instead of
  346. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  347. we could have first created an S-expression for AST
  348. \eqref{eq:arith-neg8} and then spliced that into the addition
  349. S-expression.
  350. \begin{lstlisting}
  351. (define ast1.4 `(- 8))
  352. (define ast1.1 `(+ (read) ,ast1.4))
  353. \end{lstlisting}
  354. In general, the Racket expression that follows the comma (splice)
  355. can be any expression that computes an S-expression.
  356. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  357. know that the operation associated with the root node is addition and
  358. that it has two children: \texttt{read} and a negation. The AST data
  359. structure directly supports these queries, as we shall see in
  360. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  361. in compilers. In this book, we will often write down the S-expression
  362. representation of a program even when we really have in mind the AST
  363. because the S-expression is more concise. We recommend that, in your
  364. mind, you always think of programs as abstract syntax trees.
  365. \section{Grammars}
  366. \label{sec:grammar}
  367. A programming language can be thought of as a \emph{set} of programs.
  368. The set is typically infinite (one can always create larger and larger
  369. programs), so one cannot simply describe a language by listing all of
  370. the programs in the language. Instead we write down a set of rules, a
  371. \emph{grammar}, for building programs. We shall write our rules in a
  372. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  373. As an example, we describe a small language, named $R_0$, of
  374. integers and arithmetic operations. The first rule says that any
  375. integer is an expression, $\Exp$, in the language:
  376. \begin{equation}
  377. \Exp ::= \Int \label{eq:arith-int}
  378. \end{equation}
  379. %
  380. Each rule has a left-hand-side and a right-hand-side. The way to read
  381. a rule is that if you have all the program parts on the
  382. right-hand-side, then you can create an AST node and categorize it
  383. according to the left-hand-side.
  384. %
  385. A name such as $\Exp$ that is
  386. defined by the grammar rules is a \emph{non-terminal}.
  387. %
  388. The name $\Int$ is a also a non-terminal, however,
  389. we do not define $\Int$ because the
  390. reader already knows what an integer is.
  391. %
  392. Further, we make the simplifying design decision that all of the languages in
  393. this book only handle machine-representable integers. On most modern machines
  394. this corresponds to integers represented with 64-bits, i.e., the in range
  395. $-2^{63}$ to $2^{63}-1$.
  396. %
  397. However, we restrict this range further to match the Racket \texttt{fixnum}
  398. datatype, which allows 63-bit integers on a 64-bit machine.
  399. The second grammar rule is the \texttt{read} operation that receives
  400. an input integer from the user of the program.
  401. \begin{equation}
  402. \Exp ::= (\key{read}) \label{eq:arith-read}
  403. \end{equation}
  404. The third rule says that, given an $\Exp$ node, you can build another
  405. $\Exp$ node by negating it.
  406. \begin{equation}
  407. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  408. \end{equation}
  409. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  410. and must literally appear in the program for the rule to be
  411. applicable.
  412. We can apply the rules to build ASTs in the $R_0$
  413. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  414. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  415. an $\Exp$.
  416. \begin{center}
  417. \begin{minipage}{0.25\textwidth}
  418. \begin{lstlisting}
  419. (- 8)
  420. \end{lstlisting}
  421. \end{minipage}
  422. \begin{minipage}{0.25\textwidth}
  423. \begin{equation}
  424. \begin{tikzpicture}
  425. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  426. \node[draw, circle] (8) at (0, -1.2) {$8$};
  427. \draw[->] (minus) to (8);
  428. \end{tikzpicture}
  429. \label{eq:arith-neg8}
  430. \end{equation}
  431. \end{minipage}
  432. \end{center}
  433. The following grammar rule defines addition expressions:
  434. \begin{equation}
  435. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  436. \end{equation}
  437. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  438. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  439. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  440. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  441. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  442. If you have an AST for which the above rules do not apply, then the
  443. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  444. not in $R_0$ because there are no rules for \key{+} with only one
  445. argument, nor for \key{-} with two arguments. Whenever we define a
  446. language with a grammar, we implicitly mean for the language to be the
  447. smallest set of programs that are justified by the rules. That is, the
  448. language only includes those programs that the rules allow.
  449. The last grammar rule for $R_0$ states that there is a \key{program}
  450. node to mark the top of the whole program:
  451. \[
  452. R_0 ::= (\key{program} \; \Exp)
  453. \]
  454. The \code{read-program} function provided in \code{utilities.rkt}
  455. reads programs in from a file (the sequence of characters in the
  456. concrete syntax of Racket) and parses them into the abstract syntax
  457. tree. The concrete syntax does not include a \key{program} form; that
  458. is added by the \code{read-program} function as it creates the
  459. AST. See the description of \code{read-program} in
  460. Appendix~\ref{appendix:utilities} for more details.
  461. It is common to have many rules with the same left-hand side, such as
  462. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  463. for gathering several rules, as shown in
  464. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  465. called an {\em alternative}.
  466. \begin{figure}[tp]
  467. \fbox{
  468. \begin{minipage}{0.96\textwidth}
  469. \[
  470. \begin{array}{rcl}
  471. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  472. (\key{+} \; \Exp \; \Exp) \\
  473. R_0 &::=& (\key{program} \; \Exp)
  474. \end{array}
  475. \]
  476. \end{minipage}
  477. }
  478. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  479. \label{fig:r0-syntax}
  480. \end{figure}
  481. \section{Pattern Matching}
  482. \label{sec:pattern-matching}
  483. As mentioned above, one of the operations that a compiler needs to
  484. perform on an AST is to access the children of a node. Racket
  485. provides the \texttt{match} form to access the parts of an
  486. S-expression. Consider the following example and the output on the
  487. right.
  488. \begin{center}
  489. \begin{minipage}{0.5\textwidth}
  490. \begin{lstlisting}
  491. (match ast1.1
  492. [`(,op ,child1 ,child2)
  493. (print op) (newline)
  494. (print child1) (newline)
  495. (print child2)])
  496. \end{lstlisting}
  497. \end{minipage}
  498. \vrule
  499. \begin{minipage}{0.25\textwidth}
  500. \begin{lstlisting}
  501. '+
  502. '(read)
  503. '(- 8)
  504. \end{lstlisting}
  505. \end{minipage}
  506. \end{center}
  507. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  508. parts to the three variables \texttt{op}, \texttt{child1}, and
  509. \texttt{child2}. In general, a match clause consists of a
  510. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  511. that may contain pattern-variables (each one preceded by a comma).
  512. %
  513. The pattern is not the same thing as a quasiquote expression used to
  514. \emph{construct} ASTs, however, the similarity is intentional: constructing and
  515. deconstructing ASTs uses similar syntax.
  516. %
  517. While the pattern uses a restricted syntax,
  518. the body of the match clause may contain any Racket code whatsoever.
  519. A \texttt{match} form may contain several clauses, as in the following
  520. function \texttt{leaf?} that recognizes when an $R_0$ node is
  521. a leaf. The \texttt{match} proceeds through the clauses in order,
  522. checking whether the pattern can match the input S-expression. The
  523. body of the first clause that matches is executed. The output of
  524. \texttt{leaf?} for several S-expressions is shown on the right. In the
  525. below \texttt{match}, we see another form of pattern: the \texttt{(?
  526. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  527. S-expression to see if it is a machine-representable integer.
  528. \begin{center}
  529. \begin{minipage}{0.5\textwidth}
  530. \begin{lstlisting}
  531. (define (leaf? arith)
  532. (match arith
  533. [(? fixnum?) #t]
  534. [`(read) #t]
  535. [`(- ,c1) #f]
  536. [`(+ ,c1 ,c2) #f]))
  537. (leaf? `(read))
  538. (leaf? `(- 8))
  539. (leaf? `(+ (read) (- 8)))
  540. \end{lstlisting}
  541. \end{minipage}
  542. \vrule
  543. \begin{minipage}{0.25\textwidth}
  544. \begin{lstlisting}
  545. #t
  546. #f
  547. #f
  548. \end{lstlisting}
  549. \end{minipage}
  550. \end{center}
  551. \section{Recursion}
  552. \label{sec:recursion}
  553. Programs are inherently recursive in that an $R_0$ expression ($\Exp$)
  554. is made up of smaller expressions. Thus, the natural way to process an
  555. entire program is with a recursive function. As a first example of
  556. such a function, we define \texttt{exp?} below, which takes an
  557. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  558. sexp} is an $R_0$ expression. Note that each match clause
  559. corresponds to one grammar rule the body of each clause makes a
  560. recursive call for each child node. This pattern of recursive function
  561. is so common that it has a name, \emph{structural recursion}. In
  562. general, when a recursive function is defined using a sequence of
  563. match clauses that correspond to a grammar, and each clause body makes
  564. a recursive call on each child node, then we say the function is
  565. defined by structural recursion. Below we also define a second
  566. function, named \code{R0?}, determines whether an S-expression is an
  567. $R_0$ program.
  568. %
  569. \begin{center}
  570. \begin{minipage}{0.7\textwidth}
  571. \begin{lstlisting}
  572. (define (exp? sexp)
  573. (match sexp
  574. [(? fixnum?) #t]
  575. [`(read) #t]
  576. [`(- ,e) (exp? e)]
  577. [`(+ ,e1 ,e2)
  578. (and (exp? e1) (exp? e2))]
  579. [else #f]))
  580. (define (R0? sexp)
  581. (match sexp
  582. [`(program ,e) (exp? e)]
  583. [else #f]))
  584. (R0? `(program (+ (read) (- 8))))
  585. (R0? `(program (- (read) (+ 8))))
  586. \end{lstlisting}
  587. \end{minipage}
  588. \vrule
  589. \begin{minipage}{0.25\textwidth}
  590. \begin{lstlisting}
  591. #t
  592. #f
  593. \end{lstlisting}
  594. \end{minipage}
  595. \end{center}
  596. Indeed, the structural recursion follows the grammar itself. We can
  597. generally expect to write a recursive function to handle each
  598. non-terminal in the grammar.\footnote{This principle of structuring
  599. code according to the data definition is advocated in the book
  600. \emph{How to Design Programs}
  601. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}
  602. You may be tempted to write the program with just one function, like this:
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (define (R0? sexp)
  607. (match sexp
  608. [(? fixnum?) #t]
  609. [`(read) #t]
  610. [`(- ,e) (R0? e)]
  611. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  612. [`(program ,e) (R0? e)]
  613. [else #f]))
  614. \end{lstlisting}
  615. \end{minipage}
  616. \end{center}
  617. %
  618. Sometimes such a trick will save a few lines of code, especially when it comes
  619. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  620. recommended because it can get you into trouble.
  621. %
  622. For instance, the above function is subtly wrong:
  623. \lstinline{(R0? `(program (program 3)))} will return true, when it
  624. should return false.
  625. %% NOTE FIXME - must check for consistency on this issue throughout.
  626. \section{Interpreters}
  627. \label{sec:interp-R0}
  628. The meaning, or semantics, of a program is typically defined in the
  629. specification of the language. For example, the Scheme language is
  630. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  631. defined in its reference manual~\citep{plt-tr}. In this book we use an
  632. interpreter to define the meaning of each language that we consider,
  633. following Reynolds' advice in this
  634. regard~\citep{reynolds72:_def_interp}. Here we warm up by writing an
  635. interpreter for the $R_0$ language, which serves as a second example
  636. of structural recursion. The \texttt{interp-R0} function is defined in
  637. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  638. input program \texttt{p} and then a call to the \lstinline{interp-exp}
  639. helper function, which in turn has one match clause per grammar rule
  640. for $R_0$ expressions.
  641. \begin{figure}[tbp]
  642. \begin{lstlisting}
  643. (define (interp-exp e)
  644. (match e
  645. [(? fixnum?) e]
  646. [`(read)
  647. (let ([r (read)])
  648. (cond [(fixnum? r) r]
  649. [else (error 'interp-R0 "input not an integer" r)]))]
  650. [`(- ,e1) (fx- 0 (interp-exp e1))]
  651. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  652. ))
  653. (define (interp-R0 p)
  654. (match p
  655. [`(program ,e) (interp-exp e)]))
  656. \end{lstlisting}
  657. \caption{Interpreter for the $R_0$ language.}
  658. \label{fig:interp-R0}
  659. \end{figure}
  660. Let us consider the result of interpreting a few $R_0$ programs. The
  661. following program simply adds two integers.
  662. \begin{lstlisting}
  663. (+ 10 32)
  664. \end{lstlisting}
  665. The result is \key{42}, as you might have expected. Here we have written the
  666. program in concrete syntax, whereas the parsed abstract syntax would be the
  667. slightly different: \lstinline{(program (+ 10 32))}.
  668. The next example demonstrates that expressions may be nested within
  669. each other, in this case nesting several additions and negations.
  670. \begin{lstlisting}
  671. (+ 10 (- (+ 12 20)))
  672. \end{lstlisting}
  673. What is the result of the above program?
  674. As mentioned previously, the $R0$ language does not support
  675. arbitrarily-large integers, but only $63$-bit integers, so we
  676. interpret the arithmetic operations of $R0$ using fixnum arithmetic.
  677. What happens when we run the following program?
  678. \begin{lstlisting}
  679. (define large 999999999999999999)
  680. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  681. (+ (+ ,large ,large) (+ ,large ,large)))))
  682. \end{lstlisting}
  683. It produces an error:
  684. \begin{lstlisting}
  685. fx+: result is not a fixnum
  686. \end{lstlisting}
  687. We shall use the convention that if the interpreter for a language
  688. produces an error when run on a program, then the meaning of the
  689. program is unspecified. The compiler for the language is under no
  690. obligation for such a program; it can produce an executable that does
  691. anything.
  692. \noindent
  693. Moving on, the \key{read} operation prompts the user of the program
  694. for an integer. If we interpret the AST \eqref{eq:arith-prog} and give
  695. it the input \texttt{50}
  696. \begin{lstlisting}
  697. (interp-R0 ast1.1)
  698. \end{lstlisting}
  699. we get the answer to life, the universe, and everything:
  700. \begin{lstlisting}
  701. 42
  702. \end{lstlisting}
  703. We include the \key{read} operation in $R_0$ so a clever student
  704. cannot implement a compiler for $R_0$ simply by running the
  705. interpreter at compilation time to obtain the output and then
  706. generating the trivial code to return the output. (A clever student
  707. did this in a previous version of the course.)
  708. The job of a compiler is to translate a program in one language into a
  709. program in another language so that the output program behaves the
  710. same way as the input program. This idea is depicted in the following
  711. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  712. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  713. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  714. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  715. and $P_2$ on their respective interpreters with input $i$ should yield
  716. the same output $o$.
  717. \begin{equation} \label{eq:compile-correct}
  718. \begin{tikzpicture}[baseline=(current bounding box.center)]
  719. \node (p1) at (0, 0) {$P_1$};
  720. \node (p2) at (3, 0) {$P_2$};
  721. \node (o) at (3, -2.5) {$o$};
  722. \path[->] (p1) edge [above] node {compile} (p2);
  723. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  724. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  725. \end{tikzpicture}
  726. \end{equation}
  727. In the next section we see our first example of a compiler, which is
  728. another example of structural recursion.
  729. \section{Example Compiler: a Partial Evaluator}
  730. \label{sec:partial-evaluation}
  731. In this section we consider a compiler that translates $R_0$
  732. programs into $R_0$ programs that are more efficient, that is,
  733. this compiler is an optimizer. Our optimizer will accomplish this by
  734. trying to eagerly compute the parts of the program that do not depend
  735. on any inputs. For example, given the following program
  736. \begin{lstlisting}
  737. (+ (read) (- (+ 5 3)))
  738. \end{lstlisting}
  739. our compiler will translate it into the program
  740. \begin{lstlisting}
  741. (+ (read) -8)
  742. \end{lstlisting}
  743. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  744. evaluator for the $R_0$ language. The output of the partial evaluator
  745. is an $R_0$ program, which we build up using a combination of
  746. quasiquotes and commas. (Though no quasiquote is necessary for
  747. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  748. recursion is captured in the main \texttt{pe-arith} function whereas
  749. the code for partially evaluating negation and addition is factored
  750. into two separate helper functions: \texttt{pe-neg} and
  751. \texttt{pe-add}. The input to these helper functions is the output of
  752. partially evaluating the children nodes.
  753. \begin{figure}[tbp]
  754. \begin{lstlisting}
  755. (define (pe-neg r)
  756. (cond [(fixnum? r) (fx- 0 r)]
  757. [else `(- ,r)]))
  758. (define (pe-add r1 r2)
  759. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  760. [else `(+ ,r1 ,r2)]))
  761. (define (pe-arith e)
  762. (match e
  763. [(? fixnum?) e]
  764. [`(read) `(read)]
  765. [`(- ,e1)
  766. (pe-neg (pe-arith e1))]
  767. [`(+ ,e1 ,e2)
  768. (pe-add (pe-arith e1) (pe-arith e2))]))
  769. \end{lstlisting}
  770. \caption{A partial evaluator for $R_0$ expressions.}
  771. \label{fig:pe-arith}
  772. \end{figure}
  773. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  774. idea of checking whether their arguments are integers and if they are,
  775. to go ahead and perform the arithmetic. Otherwise, we use quasiquote
  776. to create an AST node for the appropriate operation (either negation
  777. or addition) and use comma to splice in the child nodes.
  778. To gain some confidence that the partial evaluator is correct, we can
  779. test whether it produces programs that get the same result as the
  780. input program. That is, we can test whether it satisfies Diagram
  781. \eqref{eq:compile-correct}. The following code runs the partial
  782. evaluator on several examples and tests the output program. The
  783. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  784. \begin{lstlisting}
  785. (define (test-pe p)
  786. (assert "testing pe-arith"
  787. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  788. (test-pe `(+ (read) (- (+ 5 3))))
  789. (test-pe `(+ 1 (+ (read) 1)))
  790. (test-pe `(- (+ (read) (- 5))))
  791. \end{lstlisting}
  792. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  793. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  794. \begin{exercise}
  795. \normalfont % I don't like the italics for exercises. -Jeremy
  796. We challenge the reader to improve on the simple partial evaluator in
  797. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  798. \texttt{pe-add} helper functions with functions that know more about
  799. arithmetic. For example, your partial evaluator should translate
  800. \begin{lstlisting}
  801. (+ 1 (+ (read) 1))
  802. \end{lstlisting}
  803. into
  804. \begin{lstlisting}
  805. (+ 2 (read))
  806. \end{lstlisting}
  807. To accomplish this, we recommend that your partial evaluator produce
  808. output that takes the form of the $\itm{residual}$ non-terminal in the
  809. following grammar.
  810. \[
  811. \begin{array}{lcl}
  812. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  813. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  814. \end{array}
  815. \]
  816. \end{exercise}
  817. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  818. \chapter{Integers and Variables}
  819. \label{ch:int-exp}
  820. This chapter concerns the challenge of compiling a subset of Racket
  821. that includes integer arithmetic and local variable binding, which we
  822. name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. Henceforth
  823. we shall refer to x86-64 simply as x86. The chapter begins with a
  824. description of the $R_1$ language (Section~\ref{sec:s0}) followed by a
  825. description of x86 (Section~\ref{sec:x86}). The x86 assembly language
  826. is quite large, so we only discuss what is needed for compiling
  827. $R_1$. We introduce more of x86 in later chapters. Once we have
  828. introduced $R_1$ and x86, we reflect on their differences and come up
  829. with a plan to break down the translation from $R_1$ to x86 into a
  830. handful of steps (Section~\ref{sec:plan-s0-x86}). The rest of the
  831. sections in this Chapter give detailed hints regarding each step
  832. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  833. to give enough hints that the well-prepared reader can implement a
  834. compiler from $R_1$ to x86 while at the same time leaving room for
  835. some fun and creativity.
  836. \section{The $R_1$ Language}
  837. \label{sec:s0}
  838. The $R_1$ language extends the $R_0$ language
  839. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  840. the $R_1$ language is defined by the grammar in
  841. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  842. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  843. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  844. the $R_1$ language includes the \key{program} construct to mark the
  845. top of the program, which is helpful in parts of the compiler. The
  846. $\itm{info}$ field of the \key{program} construct contains an
  847. association list that is used to communicate auxiliary data from one
  848. step of the compiler to the next.
  849. The $R_1$ language is rich enough to exhibit several compilation
  850. techniques but simple enough so that the reader, together with couple
  851. friends, can implement a compiler for it in a week or two of part-time
  852. work. To give the reader a feeling for the scale of this first
  853. compiler, the instructor solution for the $R_1$ compiler is less than
  854. 500 lines of code.
  855. \begin{figure}[btp]
  856. \centering
  857. \fbox{
  858. \begin{minipage}{0.96\textwidth}
  859. \[
  860. \begin{array}{rcl}
  861. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  862. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  863. R_1 &::=& (\key{program} \;\itm{info}\; \Exp)
  864. \end{array}
  865. \]
  866. \end{minipage}
  867. }
  868. \caption{The syntax of $R_1$, a language of integers and variables.}
  869. \label{fig:r1-syntax}
  870. \end{figure}
  871. Let us dive into the description of the $R_1$ language. The \key{let}
  872. construct defines a variable for use within its body and initializes
  873. the variable with the value of an expression. So the following
  874. program initializes \code{x} to \code{32} and then evaluates the body
  875. \code{(+ 10 x)}, producing \code{42}.
  876. \begin{lstlisting}
  877. (program ()
  878. (let ([x (+ 12 20)]) (+ 10 x)))
  879. \end{lstlisting}
  880. When there are multiple \key{let}'s for the same variable, the closest
  881. enclosing \key{let} is used. That is, variable definitions overshadow
  882. prior definitions. Consider the following program with two \key{let}'s
  883. that define variables named \code{x}. Can you figure out the result?
  884. \begin{lstlisting}
  885. (program ()
  886. (let ([x 32]) (+ (let ([x 10]) x) x)))
  887. \end{lstlisting}
  888. For the purposes of showing which variable uses correspond to which
  889. definitions, the following shows the \code{x}'s annotated with subscripts
  890. to distinguish them. Double check that your answer for the above is
  891. the same as your answer for this annotated version of the program.
  892. \begin{lstlisting}
  893. (program ()
  894. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  895. \end{lstlisting}
  896. The initializing expression is always evaluated before the body of the
  897. \key{let}, so in the following, the \key{read} for \code{x} is
  898. performed before the \key{read} for \code{y}. Given the input
  899. \code{52} then \code{10}, the following produces \code{42} (and not
  900. \code{-42}).
  901. \begin{lstlisting}
  902. (program ()
  903. (let ([x (read)]) (let ([y (read)]) (+ x (- y)))))
  904. \end{lstlisting}
  905. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  906. language. It extends the interpreter for $R_0$ with two new
  907. \key{match} clauses for variables and for \key{let}. For \key{let},
  908. we will need a way to communicate the initializing value of a variable
  909. to all the uses of a variable. To accomplish this, we maintain a
  910. mapping from variables to values, which is traditionally called an
  911. \emph{environment}. For simplicity, here we use an association list to
  912. represent the environment. The \code{interp-R1} function takes the
  913. current environment, \code{env}, as an extra parameter. When the
  914. interpreter encounters a variable, it finds the corresponding value
  915. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  916. When the interpreter encounters a \key{let}, it evaluates the
  917. initializing expression, extends the environment with the result bound
  918. to the variable, then evaluates the body of the \key{let}.
  919. \begin{figure}[tbp]
  920. \begin{lstlisting}
  921. (define (interp-exp env)
  922. (lambda (e)
  923. (match e
  924. [(? fixnum?) e]
  925. [`(read)
  926. (define r (read))
  927. (cond [(fixnum? r) r]
  928. [else (error 'interp-R1 "expected an integer" r)])]
  929. [`(- ,e)
  930. (define v ((interp-exp env) e))
  931. (fx- 0 v)]
  932. [`(+ ,e1 ,e2)
  933. (define v1 ((interp-exp env) e1))
  934. (define v2 ((interp-exp env) e2))
  935. (fx+ v1 v2)]
  936. [(? symbol?) (lookup e env)]
  937. [`(let ([,x ,e]) ,body)
  938. (define new-env (cons (cons x ((interp-exp env) e)) env))
  939. ((interp-exp new-env) body)]
  940. )))
  941. (define (interp-R1 env)
  942. (lambda (p)
  943. (match p
  944. [`(program ,info ,e) ((interp-exp '()) e)])))
  945. \end{lstlisting}
  946. \caption{Interpreter for the $R_1$ language.}
  947. \label{fig:interp-R1}
  948. \end{figure}
  949. The goal for this chapter is to implement a compiler that translates
  950. any program $P_1$ in the $R_1$ language into an x86 assembly
  951. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  952. computer as the $R_1$ program running in a Racket implementation.
  953. That is, they both output the same integer $n$.
  954. \[
  955. \begin{tikzpicture}[baseline=(current bounding box.center)]
  956. \node (p1) at (0, 0) {$P_1$};
  957. \node (p2) at (4, 0) {$P_2$};
  958. \node (o) at (4, -2) {$n$};
  959. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  960. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  961. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  962. \end{tikzpicture}
  963. \]
  964. In the next section we introduce enough of the x86 assembly
  965. language to compile $R_1$.
  966. \section{The x86 Assembly Language}
  967. \label{sec:x86}
  968. An x86 program is a sequence of instructions. The program is stored in the
  969. computer's memory and the \emph{program counter} points to the address of the
  970. next instruction to be executed. For most instructions, once the instruction is
  971. executed, the program counter is incremented to point to the immediately
  972. following instruction in memory. Each instruction may refer to integer
  973. constants (called \emph{immediate values}), variables called \emph{registers},
  974. and instructions may load and store values into memory. For our purposes, we
  975. can think of the computer's memory as a mapping of 64-bit addresses to 64-bit
  976. values%
  977. \footnote{This simple story suffices for describing how sequential
  978. programs access memory but is not sufficient for multi-threaded
  979. programs. However, multi-threaded execution is beyond the scope of
  980. this book.}.
  981. %
  982. Figure~\ref{fig:x86-a} defines the syntax for the
  983. subset of the x86 assembly language needed for this chapter.
  984. %
  985. We use the AT\&T syntax expected by the GNU assembler, which comes
  986. with the \key{gcc} compiler that we use for compiling assembly code to
  987. machine code.
  988. %
  989. Also, Appendix~\ref{sec:x86-quick-reference} includes a quick-reference of all
  990. the x86 instructions used in this book and a short explanation of what they do.
  991. % to do: finish treatment of imulq
  992. % it's needed for vector's in R6/R7
  993. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  994. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  995. && \key{r8} \mid \key{r9} \mid \key{r10}
  996. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  997. \mid \key{r14} \mid \key{r15}}
  998. \begin{figure}[tp]
  999. \fbox{
  1000. \begin{minipage}{0.96\textwidth}
  1001. \[
  1002. \begin{array}{lcl}
  1003. \Reg &::=& \allregisters{} \\
  1004. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  1005. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  1006. \key{subq} \; \Arg, \Arg \mid
  1007. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  1008. && \key{callq} \; \mathit{label} \mid
  1009. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1010. \Prog &::= & \key{.globl main}\\
  1011. & & \key{main:} \; \Instr^{+}
  1012. \end{array}
  1013. \]
  1014. \end{minipage}
  1015. }
  1016. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1017. \label{fig:x86-a}
  1018. \end{figure}
  1019. An immediate value is written using the notation \key{\$}$n$ where $n$
  1020. is an integer.
  1021. %
  1022. A register is written with a \key{\%} followed by the register name,
  1023. such as \key{\%rax}.
  1024. %
  1025. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1026. which obtains the address stored in register $r$ and then
  1027. offsets the address by $n$ bytes
  1028. (8 bits). The address is then used to either load or store to memory
  1029. depending on whether it occurs as a source or destination argument of
  1030. an instruction.
  1031. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  1032. source $s$ and destination $d$, applies the arithmetic operation, then
  1033. writes the result in $d$.
  1034. %
  1035. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  1036. result in $d$.
  1037. %
  1038. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1039. specified by the label.
  1040. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1041. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1042. \key{main} procedure is externally visible, which is necessary so
  1043. that the operating system can call it. The label \key{main:}
  1044. indicates the beginning of the \key{main} procedure which is where
  1045. the operating system starts executing this program. The instruction
  1046. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1047. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1048. $10$ in \key{rax} and puts the result, $42$, back into
  1049. \key{rax}.
  1050. The last instruction, \key{retq}, finishes the \key{main} function by
  1051. returning the integer in \key{rax} to the operating system. The
  1052. operating system interprets this integer as the program's exit
  1053. code. By convention, an exit code of 0 indicates the program was
  1054. successful, and all other exit codes indicate various errors.
  1055. Nevertheless, we return the result of the program as the exit code.
  1056. %\begin{wrapfigure}{r}{2.25in}
  1057. \begin{figure}[tbp]
  1058. \begin{lstlisting}
  1059. .globl main
  1060. main:
  1061. movq $10, %rax
  1062. addq $32, %rax
  1063. retq
  1064. \end{lstlisting}
  1065. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1066. \label{fig:p0-x86}
  1067. %\end{wrapfigure}
  1068. \end{figure}
  1069. Unfortunately, x86 varies in a couple ways depending on what operating
  1070. system it is assembled in. The code examples shown here are correct on
  1071. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1072. labels like \key{main} must be prefixed with an underscore, as in
  1073. \key{\_main}.
  1074. We exhibit the use of memory for storing intermediate results in the
  1075. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1076. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1077. region of memory called the \emph{procedure call stack} (or
  1078. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1079. for each procedure call. The memory layout for an individual frame is
  1080. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1081. \emph{stack pointer} and points to the item at the top of the
  1082. stack. The stack grows downward in memory, so we increase the size of
  1083. the stack by subtracting from the stack pointer. The frame size is
  1084. required to be a multiple of 16 bytes. In the context of a procedure
  1085. call, the \emph{return address} is the next instruction on the caller
  1086. side that comes after the call instruction. During a function call,
  1087. the return address is pushed onto the stack. The register \key{rbp}
  1088. is the \emph{base pointer} which serves two purposes: 1) it saves the
  1089. location of the stack pointer for the calling procedure and 2) it is
  1090. used to access variables associated with the current procedure. The
  1091. base pointer of the calling procedure is pushed onto the stack after
  1092. the return address. We number the variables from $1$ to $n$. Variable
  1093. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1094. $-16\key{(\%rbp)}$, etc.
  1095. \begin{figure}[tbp]
  1096. \begin{lstlisting}
  1097. start:
  1098. movq $10, -8(%rbp)
  1099. negq -8(%rbp)
  1100. movq -8(%rbp), %rax
  1101. addq $52, %rax
  1102. jmp conclusion
  1103. .globl main
  1104. main:
  1105. pushq %rbp
  1106. movq %rsp, %rbp
  1107. subq $16, %rsp
  1108. jmp start
  1109. conclusion:
  1110. addq $16, %rsp
  1111. popq %rbp
  1112. retq
  1113. \end{lstlisting}
  1114. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1115. \label{fig:p1-x86}
  1116. \end{figure}
  1117. \begin{figure}[tbp]
  1118. \centering
  1119. \begin{tabular}{|r|l|} \hline
  1120. Position & Contents \\ \hline
  1121. 8(\key{\%rbp}) & return address \\
  1122. 0(\key{\%rbp}) & old \key{rbp} \\
  1123. -8(\key{\%rbp}) & variable $1$ \\
  1124. -16(\key{\%rbp}) & variable $2$ \\
  1125. \ldots & \ldots \\
  1126. 0(\key{\%rsp}) & variable $n$\\ \hline
  1127. \end{tabular}
  1128. \caption{Memory layout of a frame.}
  1129. \label{fig:frame}
  1130. \end{figure}
  1131. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1132. three instructions are the typical \emph{prelude} for a procedure.
  1133. The instruction \key{pushq \%rbp} saves the base pointer for the
  1134. procedure that called the current one onto the stack and subtracts $8$
  1135. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1136. changes the base pointer to the top of the stack. The instruction
  1137. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1138. room for storing variables. This program just needs one variable ($8$
  1139. bytes) but because the frame size is required to be a multiple of 16
  1140. bytes, it rounds to 16 bytes.
  1141. The four instructions under the label \code{start} carry out the work
  1142. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1143. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1144. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1145. \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1146. \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1147. \key{rax}, at which point \key{rax} contains $42$.
  1148. The three instructions under the label \code{conclusion} are the
  1149. typical finale of a procedure. The first two are necessary to get the
  1150. state of the machine back to where it was at the beginning of the
  1151. procedure. The \key{addq \$16, \%rsp} instruction moves the stack
  1152. pointer back to point at the old base pointer. The amount added here
  1153. needs to match the amount that was subtracted in the prelude of the
  1154. procedure. Then \key{popq \%rbp} returns the old base pointer to
  1155. \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  1156. \key{retq}, jumps back to the procedure that called this one and adds
  1157. 8 to the stack pointer, which returns the stack pointer to where it
  1158. was prior to the procedure call.
  1159. The compiler will need a convenient representation for manipulating
  1160. x86 programs, so we define an abstract syntax for x86 in
  1161. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1162. a subscript $0$ because later we introduce extended versions of this
  1163. assembly language. The main difference compared to the concrete syntax
  1164. of x86 (Figure~\ref{fig:x86-a}) is that it does nto allow labelled
  1165. instructions to appear anywhere, but instead organizes instructions
  1166. into groups called \emph{blocks} and a label is associated with every
  1167. block, which is why the \key{program} form includes an association
  1168. list mapping labels to blocks. The reason for this organization
  1169. becomes apparent in Chapter~\ref{ch:bool-types}.
  1170. \begin{figure}[tp]
  1171. \fbox{
  1172. \begin{minipage}{0.96\textwidth}
  1173. \[
  1174. \begin{array}{lcl}
  1175. \itm{register} &::=& \allregisters{} \\
  1176. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1177. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1178. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1179. (\key{subq} \; \Arg\; \Arg) \mid
  1180. (\key{movq} \; \Arg\; \Arg) \mid
  1181. (\key{retq})\\
  1182. &\mid& (\key{negq} \; \Arg) \mid
  1183. (\key{callq} \; \mathit{label}) \mid
  1184. (\key{pushq}\;\Arg) \mid
  1185. (\key{popq}\;\Arg) \\
  1186. \Block &::= & (\key{block} \;\itm{info}\; \Instr^{+}) \\
  1187. x86_0 &::= & (\key{program} \;\itm{info} \; ((\itm{label} \,\key{.}\, \Block)^{+}))
  1188. \end{array}
  1189. \]
  1190. \end{minipage}
  1191. }
  1192. \caption{Abstract syntax for $x86_0$ assembly.}
  1193. \label{fig:x86-ast-a}
  1194. \end{figure}
  1195. \section{Planning the trip to x86 via the $C_0$ language}
  1196. \label{sec:plan-s0-x86}
  1197. To compile one language to another it helps to focus on the
  1198. differences between the two languages because the compiler will need
  1199. to bridge them. What are the differences between $R_1$ and x86
  1200. assembly? Here we list some of the most important ones.
  1201. \begin{enumerate}
  1202. \item[(a)] x86 arithmetic instructions typically have two arguments
  1203. and update the second argument in place. In contrast, $R_1$
  1204. arithmetic operations take two arguments and produce a new value.
  1205. An x86 instruction may have at most one memory-accessing argument.
  1206. Furthermore, some instructions place special restrictions on their
  1207. arguments.
  1208. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1209. whereas x86 instructions restrict their arguments to be \emph{simple
  1210. expressions} like integers, registers, and memory locations. (All
  1211. the other kinds are called \emph{complex expressions}.)
  1212. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1213. sequence of instructions and jumps to labeled positions, whereas in
  1214. $R_1$ it is a left-to-right depth-first traversal of the abstract
  1215. syntax tree.
  1216. \item[(d)] An $R_1$ program can have any number of variables whereas
  1217. x86 has 16 registers and the procedure calls stack.
  1218. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1219. same name. The registers and memory locations of x86 all have unique
  1220. names or addresses.
  1221. \end{enumerate}
  1222. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1223. the problem into several steps, dealing with the above differences one
  1224. at a time. Each of these steps is called a \emph{pass} of the
  1225. compiler, because step traverses (passes over) the AST of the program.
  1226. %
  1227. We begin by giving a sketch about how we might implement each pass,
  1228. and give them names. We shall then figure out an ordering of the
  1229. passes and the input/output language for each pass. The very first
  1230. pass has $R_1$ as its input language and the last pass has x86 as its
  1231. output language. In between we can choose whichever language is most
  1232. convenient for expressing the output of each pass, whether that be
  1233. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1234. Finally, to implement the compiler, we shall write one function,
  1235. typically a structural recursive function, per pass.
  1236. \begin{description}
  1237. \item[Pass \key{select-instructions}] To handle the difference between
  1238. $R_1$ operations and x86 instructions we shall convert each $R_1$
  1239. operation to a short sequence of instructions that accomplishes the
  1240. same task.
  1241. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1242. subexpression (i.e. operator and operand, and hence \key{opera*}) is
  1243. a simple expression, we shall introduce temporary variables to hold
  1244. the results of subexpressions.
  1245. \item[Pass \key{explicate-control}] To make the execution order of the
  1246. program explicit, we shall convert from the abstract syntax tree
  1247. representation into a graph representation in which each node
  1248. contains a sequence of actions and the edges say where to go after
  1249. the sequence is complete.
  1250. \item[Pass \key{assign-homes}] To handle the difference between the
  1251. variables in $R_1$ versus the registers and stack location in x86,
  1252. we shall come up with an assignment of each variable to its
  1253. \emph{home}, that is, to a register or stack location.
  1254. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1255. by renaming every variable to a unique name, so that shadowing no
  1256. longer occurs.
  1257. \end{description}
  1258. The next question is: in what order should we apply these passes? This
  1259. question can be a challenging one to answer because it is difficult to
  1260. know ahead of time which orders will be better (easier to implement,
  1261. produce more efficient code, etc.) so often some trial-and-error is
  1262. involved. Nevertheless, we can try to plan ahead and make educated
  1263. choices regarding the orderings.
  1264. Let us consider the ordering of \key{uniquify} and
  1265. \key{remove-complex-opera*}. The assignment of subexpressions to
  1266. temporary variables involves introducing new variables and moving
  1267. subexpressions, which might change the shadowing of variables and
  1268. inadvertently change the behavior of the program. But if we apply
  1269. \key{uniquify} first, this will not be an issue. Of course, this means
  1270. that in \key{remove-complex-opera*}, we need to ensure that the
  1271. temporary variables that it creates are unique.
  1272. Next we shall consider the ordering of the \key{explicate-control}
  1273. pass and \key{select-instructions}. It is clear that
  1274. \key{explicate-control} must come first because the control-flow graph
  1275. that it generates is needed when determining where to place the x86
  1276. label and jump instructions.
  1277. %
  1278. Regarding the ordering of \key{explicate-control} with respect to
  1279. \key{uniquify}, it is important to apply \key{uniquify} first because
  1280. in \key{explicate-control} we change all the \key{let}-bound variables
  1281. to become local variables whose scope is the entire program.
  1282. %
  1283. With respect to \key{remove-complex-opera*}, it perhaps does not
  1284. matter very much, but it works well to place \key{explicate-control}
  1285. after removing complex subexpressions.
  1286. The \key{assign-homes} pass should come after
  1287. \key{remove-complex-opera*} and \key{explicate-control}. The
  1288. \key{remove-complex-opera*} pass generates temporary variables, which
  1289. also need to be assigned homes. The \key{explicate-control} pass
  1290. deletes branches that will never be executed, which can remove
  1291. variables. Thus it is good to place \key{explicate-control} prior to
  1292. \key{assign-homes} so that there are fewer variables that need to be
  1293. assigned homes. This is important because the \key{assign-homes} pass
  1294. has the highest time complexity.
  1295. Last, we need to decide on the ordering of \key{select-instructions}
  1296. and \key{assign-homes}. These two issues are intertwined, creating a
  1297. bit of a Gordian Knot. To do a good job of assigning homes, it is
  1298. helpful to have already determined which instructions will be used,
  1299. because x86 instructions have restrictions about which of their
  1300. arguments can be registers versus stack locations. For example, one
  1301. can give preferential treatment to variables that occur in
  1302. register-argument positions. On the other hand, it may turn out to be
  1303. impossible to make sure that all such variables are assigned to
  1304. registers, and then one must redo the selection of instructions. Some
  1305. compilers handle this problem by iteratively repeating these two
  1306. passes until a good solution is found. We shall use a simpler
  1307. approach in which \key{select-instructions} comes first, followed by
  1308. the \key{assign-homes}, followed by a third pass, named
  1309. \key{patch-instructions}, that uses a reserved register (\key{rax}) to
  1310. patch-up outstanding problems regarding instructions with too many
  1311. memory accesses.
  1312. \begin{figure}[tbp]
  1313. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1314. \node (R1) at (0,2) {\large $R_1$};
  1315. \node (R1-2) at (3,2) {\large $R_1$};
  1316. \node (R1-3) at (6,2) {\large $R_1$};
  1317. \node (C0-1) at (6,0) {\large $C_0$};
  1318. \node (C0-2) at (3,0) {\large $C_0$};
  1319. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1320. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1321. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1322. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1323. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1324. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1325. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  1326. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1327. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1328. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1329. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1330. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1331. \end{tikzpicture}
  1332. \caption{Overview of the passes for compiling $R_1$. }
  1333. \label{fig:R1-passes}
  1334. \end{figure}
  1335. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1336. passes in the form of a graph. Each pass is an edge and the
  1337. input/output language of each pass is a node in the graph. The output
  1338. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1339. are still in the $R_1$ language, but the output of the pass
  1340. \key{explicate-control} is in a different language that is designed to
  1341. make the order of evaluation explicit in its syntax, which we
  1342. introduce in the next section. Also, there are two passes of lesser
  1343. importance in Figure~\ref{fig:R1-passes} that we have not yet talked
  1344. about, \key{uncover-locals} and \key{print-x86}. We shall discuss them
  1345. later in this Chapter.
  1346. \subsection{The $C_0$ Intermediate Language}
  1347. It so happens that the output of \key{explicate-control} is vaguely
  1348. similar to the $C$ language~\citep{Kernighan:1988nx}, so we name it
  1349. $C_0$. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1350. %
  1351. The $C_0$ language supports the same operators as $R_1$ but the
  1352. arguments of operators are now restricted to just variables and
  1353. integers, thanks to the \key{remove-complex-opera*} pass. In the
  1354. literature this style of intermediate language is called
  1355. administrative normal form, or ANF for
  1356. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{let}
  1357. expressions, $C_0$ has assignment statements which can be executed in
  1358. sequence using the \key{seq} construct. A sequence of statements
  1359. always ends with \key{return}, a guarantee that is baked into the
  1360. grammar rules for the \itm{tail} non-terminal. The naming of this
  1361. non-terminal comes from the term \emph{tail position}, which refers to
  1362. an expression that is the last one to execute within a function. (A
  1363. expression in tail position may contain subexpressions, and those may
  1364. or may not be in tail position depending on the kind of expression.)
  1365. A $C_0$ program consists of an association list mapping labels to
  1366. tails. This is overkill for the present Chapter, as we do not yet need
  1367. to introduce \key{goto} for jumping to labels, but it saves us from
  1368. having to change the syntax of the program construct in
  1369. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1370. \key{start}, and the whole program will be it's tail.
  1371. %
  1372. The $\itm{info}$ field of the program construt, after the
  1373. \key{uncover-locals} pass, will contain a mapping from the symbol
  1374. \key{locals} to a list of variables, that is, a list of all the
  1375. variables used in the program. At the start of the program, these
  1376. variables are uninitialized (they contain garbage) and each variable
  1377. becomes initialized on its first assignment.
  1378. \begin{figure}[tbp]
  1379. \fbox{
  1380. \begin{minipage}{0.96\textwidth}
  1381. \[
  1382. \begin{array}{lcl}
  1383. \Arg &::=& \Int \mid \Var \\
  1384. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1385. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1386. \Tail &::= & \RETURN{\Exp} \mid (\key{seq}\; \Stmt\; \Tail) \\
  1387. C_0 & ::= & (\key{program}\;\itm{info}\;((\itm{label}\,\key{.}\,\Tail)^{+}))
  1388. \end{array}
  1389. \]
  1390. \end{minipage}
  1391. }
  1392. \caption{The $C_0$ intermediate language.}
  1393. \label{fig:c0-syntax}
  1394. \end{figure}
  1395. %% The \key{select-instructions} pass is optimistic in the sense that it
  1396. %% treats variables as if they were all mapped to registers. The
  1397. %% \key{select-instructions} pass generates a program that consists of
  1398. %% x86 instructions but that still uses variables, so it is an
  1399. %% intermediate language that is technically different than x86, which
  1400. %% explains the asterisks in the diagram above.
  1401. %% In this Chapter we shall take the easy road to implementing
  1402. %% \key{assign-homes} and simply map all variables to stack locations.
  1403. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1404. %% smarter approach in which we make a best-effort to map variables to
  1405. %% registers, resorting to the stack only when necessary.
  1406. %% Once variables have been assigned to their homes, we can finalize the
  1407. %% instruction selection by dealing with an idiosyncrasy of x86
  1408. %% assembly. Many x86 instructions have two arguments but only one of the
  1409. %% arguments may be a memory reference (and the stack is a part of
  1410. %% memory). Because some variables may get mapped to stack locations,
  1411. %% some of our generated instructions may violate this restriction. The
  1412. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1413. %% replacing every violating instruction with a short sequence of
  1414. %% instructions that use the \key{rax} register. Once we have implemented
  1415. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1416. %% need to patch instructions will be relatively rare.
  1417. \subsection{The dialects of x86}
  1418. The x86$^{*}_0$ language, pronounced ``pseudo-x86'', is the output of
  1419. the pass \key{select-instructions}. It extends $x86_0$ with variables
  1420. and looser rules regarding instruction arguments. The x86$^{\dagger}$
  1421. language, the output of \key{print-x86}, is the concrete syntax for
  1422. x86.
  1423. \section{Uniquify Variables}
  1424. \label{sec:uniquify-s0}
  1425. The purpose of this pass is to make sure that each \key{let} uses a
  1426. unique variable name. For example, the \code{uniquify} pass should
  1427. translate the program on the left into the program on the right. \\
  1428. \begin{tabular}{lll}
  1429. \begin{minipage}{0.4\textwidth}
  1430. \begin{lstlisting}
  1431. (program ()
  1432. (let ([x 32])
  1433. (+ (let ([x 10]) x) x)))
  1434. \end{lstlisting}
  1435. \end{minipage}
  1436. &
  1437. $\Rightarrow$
  1438. &
  1439. \begin{minipage}{0.4\textwidth}
  1440. \begin{lstlisting}
  1441. (program ()
  1442. (let ([x.1 32])
  1443. (+ (let ([x.2 10]) x.2) x.1)))
  1444. \end{lstlisting}
  1445. \end{minipage}
  1446. \end{tabular} \\
  1447. %
  1448. The following is another example translation, this time of a program
  1449. with a \key{let} nested inside the initializing expression of another
  1450. \key{let}.\\
  1451. \begin{tabular}{lll}
  1452. \begin{minipage}{0.4\textwidth}
  1453. \begin{lstlisting}
  1454. (program ()
  1455. (let ([x (let ([x 4])
  1456. (+ x 1))])
  1457. (+ x 2)))
  1458. \end{lstlisting}
  1459. \end{minipage}
  1460. &
  1461. $\Rightarrow$
  1462. &
  1463. \begin{minipage}{0.4\textwidth}
  1464. \begin{lstlisting}
  1465. (program ()
  1466. (let ([x.2 (let ([x.1 4])
  1467. (+ x.1 1))])
  1468. (+ x.2 2)))
  1469. \end{lstlisting}
  1470. \end{minipage}
  1471. \end{tabular}
  1472. We recommend implementing \code{uniquify} as a structurally recursive
  1473. function that mostly copies the input program. However, when
  1474. encountering a \key{let}, it should generate a unique name for the
  1475. variable (the Racket function \code{gensym} is handy for this) and
  1476. associate the old name with the new unique name in an association
  1477. list. The \code{uniquify} function will need to access this
  1478. association list when it gets to a variable reference, so we add
  1479. another parameter to \code{uniquify} for the association list. It is
  1480. quite common for a compiler pass to need a map to store extra
  1481. information about variables. Such maps are often called \emph{symbol
  1482. tables}.
  1483. The skeleton of the \code{uniquify} function is shown in
  1484. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1485. convenient to partially apply it to an association list and then apply
  1486. it to different expressions, as in the last clause for primitive
  1487. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1488. clause for the primitive operators, note the use of the comma-@
  1489. operator to splice a list of S-expressions into an enclosing
  1490. S-expression.
  1491. \begin{exercise}
  1492. \normalfont % I don't like the italics for exercises. -Jeremy
  1493. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1494. implement the clauses for variables and for the \key{let} construct.
  1495. \end{exercise}
  1496. \begin{figure}[tbp]
  1497. \begin{lstlisting}
  1498. (define (uniquify-exp alist)
  1499. (lambda (e)
  1500. (match e
  1501. [(? symbol?) ___]
  1502. [(? integer?) e]
  1503. [`(let ([,x ,e]) ,body) ___]
  1504. [`(,op ,es ...)
  1505. `(,op ,@(for/list ([e es]) ((uniquify-exp alist) e)))]
  1506. )))
  1507. (define (uniquify alist)
  1508. (lambda (e)
  1509. (match e
  1510. [`(program ,info ,e)
  1511. `(program ,info ,((uniquify-exp alist) e))]
  1512. )))
  1513. \end{lstlisting}
  1514. \caption{Skeleton for the \key{uniquify} pass.}
  1515. \label{fig:uniquify-s0}
  1516. \end{figure}
  1517. \begin{exercise}
  1518. \normalfont % I don't like the italics for exercises. -Jeremy
  1519. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1520. and checking whether the output programs produce the same result as
  1521. the input programs. The $R_1$ programs should be designed to test the
  1522. most interesting parts of the \key{uniquify} pass, that is, the
  1523. programs should include \key{let} constructs, variables, and variables
  1524. that overshadow each other. The five programs should be in a
  1525. subdirectory named \key{tests} and they should have the same file name
  1526. except for a different integer at the end of the name, followed by the
  1527. ending \key{.rkt}. Use the \key{interp-tests} function
  1528. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1529. your \key{uniquify} pass on the example programs.
  1530. \end{exercise}
  1531. \section{Remove Complex Operators and Operands}
  1532. \label{sec:remove-complex-opera-r1}
  1533. The \code{remove-complex-opera*} pass will transform $R_1$ programs so
  1534. that the arguments of operations are simple expressions. Put another
  1535. way, this pass removes complex subexpressions, such as the expression
  1536. \code{(- 10)} in the program below. This is accomplished by
  1537. introducing a new \key{let}-bound variable, binding the complex
  1538. subexpression to the new variable, and then using the new variable in
  1539. place of the complex expression, as shown in the output of
  1540. \code{remove-complex-opera*} on the right.\\
  1541. \begin{tabular}{lll}
  1542. \begin{minipage}{0.4\textwidth}
  1543. % s0_19.rkt
  1544. \begin{lstlisting}
  1545. (program ()
  1546. (+ 52 (- 10)))
  1547. \end{lstlisting}
  1548. \end{minipage}
  1549. &
  1550. $\Rightarrow$
  1551. &
  1552. \begin{minipage}{0.4\textwidth}
  1553. \begin{lstlisting}
  1554. (program ()
  1555. (let ([tmp.1 (- 10)])
  1556. (+ 52 tmp.1)))
  1557. \end{lstlisting}
  1558. \end{minipage}
  1559. \end{tabular}
  1560. We recommend implementing this pass with two mutually recursive
  1561. functions, \code{rco-arg} and \code{rco-exp}. The idea is to apply
  1562. \code{rco-arg} to subexpressions that need to become simple and to
  1563. apply \code{rco-exp} to subexpressions can stay complex.
  1564. Both functions take an expression in $R_1$ as input.
  1565. The \code{rco-exp} function returns an expression.
  1566. The \code{rco-arg} function returns two things:
  1567. a simple expression and association list mapping temporary variables
  1568. to complex subexpressions. You can return multiple things from a
  1569. function using Racket's \key{values} form and you can receive multiple
  1570. things from a function call using the \key{define-values} form. If you
  1571. are not familiar with these constructs, the Racket documentation will
  1572. be of help. Also, the \key{for/lists} construct is useful for
  1573. applying a function to each element of a list, in the case where the
  1574. function returns multiple values.
  1575. \begin{tabular}{lll}
  1576. \begin{minipage}{0.4\textwidth}
  1577. \begin{lstlisting}
  1578. (rco-arg `(- 10))
  1579. \end{lstlisting}
  1580. \end{minipage}
  1581. &
  1582. $\Rightarrow$
  1583. &
  1584. \begin{minipage}{0.4\textwidth}
  1585. \begin{lstlisting}
  1586. (values `tmp.1
  1587. `((tmp.1 . (- 10))))
  1588. \end{lstlisting}
  1589. \end{minipage}
  1590. \end{tabular}
  1591. Take special care of programs such as the following that
  1592. \key{let}-bind variables with integers or other variables. It should
  1593. leave them unchanged, as shown in to the program on the right \\
  1594. \begin{tabular}{lll}
  1595. \begin{minipage}{0.4\textwidth}
  1596. \begin{lstlisting}
  1597. (program ()
  1598. (let ([a 42])
  1599. (let ([b a])
  1600. b)))
  1601. \end{lstlisting}
  1602. \end{minipage}
  1603. &
  1604. $\Rightarrow$
  1605. &
  1606. \begin{minipage}{0.4\textwidth}
  1607. \begin{lstlisting}
  1608. (program ()
  1609. (let ([a 42])
  1610. (let ([b a])
  1611. b)))
  1612. \end{lstlisting}
  1613. \end{minipage}
  1614. \end{tabular} \\
  1615. and not translate them to the following, which might result from a
  1616. careless implementation of \key{rco-exp} and \key{rco-arg}.
  1617. \begin{minipage}{0.4\textwidth}
  1618. \begin{lstlisting}
  1619. (program ()
  1620. (let ([tmp.1 42])
  1621. (let ([a tmp.1])
  1622. (let ([tmp.2 a])
  1623. (let ([b tmp.2])
  1624. b)))))
  1625. \end{lstlisting}
  1626. \end{minipage}
  1627. \begin{exercise}
  1628. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1629. it on all of the example programs that you created to test the
  1630. \key{uniquify} pass and create three new example programs that are
  1631. designed to exercise all of the interesting code in the
  1632. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1633. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1634. your passes on the example programs.
  1635. \end{exercise}
  1636. \section{Explicate Control}
  1637. \label{sec:explicate-control-r1}
  1638. The \code{explicate-control} pass makes the order of execution
  1639. explicit in the syntax of the program. For $R_1$, this amounts to
  1640. flattening \key{let} constructs into a sequence of assignment
  1641. statements. For example, consider the following $R_1$ program.
  1642. % s0_11.rkt
  1643. \begin{lstlisting}
  1644. (program ()
  1645. (let ([y (let ([x 20])
  1646. (+ x (let ([x 22]) x)))])
  1647. y))
  1648. \end{lstlisting}
  1649. %
  1650. The output of \code{remove-complex-opera*} is shown below, on the
  1651. left. The right-hand-side of a \key{let} executes before its body, so
  1652. the order of evaluation for this program is to assign \code{20} to
  1653. \code{x.1}, assign \code{22} to \code{x.2}, assign \code{(+ x.1 x.2)}
  1654. to \code{y}, then return \code{y}. Indeed, the result of
  1655. \code{explicate-control} produces code in the $C_0$ language that
  1656. makes this explicit.\\
  1657. \begin{tabular}{lll}
  1658. \begin{minipage}{0.4\textwidth}
  1659. \begin{lstlisting}
  1660. (program ()
  1661. (let ([y (let ([x.1 20])
  1662. (let ([x.2 22])
  1663. (+ x.1 x.2)))])
  1664. y))
  1665. \end{lstlisting}
  1666. \end{minipage}
  1667. &
  1668. $\Rightarrow$
  1669. &
  1670. \begin{minipage}{0.4\textwidth}
  1671. \begin{lstlisting}
  1672. (program ()
  1673. ((start .
  1674. (seq (assign x.1 20)
  1675. (seq (assign x.2 22)
  1676. (seq (assign y (+ x.1 x.2))
  1677. (return y)))))))
  1678. \end{lstlisting}
  1679. \end{minipage}
  1680. \end{tabular}
  1681. We recommend implementing \code{explicate-control} using two mutually
  1682. recursive functions: \code{explicate-control-tail} and
  1683. \code{explicate-control-assign}. The \code{explicate-control-tail}
  1684. function should be applied to expressions in tail position, whereas
  1685. \code{explicate-control-assign} should be applied to expressions that
  1686. occur on the right-hand-side of a \code{let}. The function
  1687. \code{explicate-control-tail} takes an $R_1$ expression as input and
  1688. produces a $C_0$ $\Tail$ (see the grammar in
  1689. Figure~\ref{fig:c0-syntax}). The \code{explicate-control-assign}
  1690. function takes an $R_1$ expression, the variable that it is to be
  1691. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1692. assignment (e.g., the code generated for the body of the \key{let}).
  1693. \section{Uncover Locals}
  1694. \label{sec:uncover-locals-r1}
  1695. The pass \code{uncover-locals} simply collects all of the variables in
  1696. the program and places then in the $\itm{info}$ of the program
  1697. construct. Here is the output for the example program of the last
  1698. section.
  1699. \begin{minipage}{0.4\textwidth}
  1700. \begin{lstlisting}
  1701. (program ((locals . (x.1 x.2 y)))
  1702. ((start .
  1703. (seq (assign x.1 20)
  1704. (seq (assign x.2 22)
  1705. (seq (assign y (+ x.1 x.2))
  1706. (return y)))))))
  1707. \end{lstlisting}
  1708. \end{minipage}
  1709. \section{Select Instructions}
  1710. \label{sec:select-r1}
  1711. In the \code{select-instructions} pass we begin the work of
  1712. translating from $C_0$ to x86. The target language of this pass is a
  1713. pseudo-x86 language that still uses variables, so we add an AST node
  1714. of the form $\VAR{\itm{var}}$ to the x86 abstract syntax. We
  1715. recommend implementing the \code{select-instructions} in terms of
  1716. three auxilliary functions, one for each of the non-terminals of
  1717. $C_0$: $\Arg$, $\Stmt$, and $\Tail$.
  1718. The cases for $\itm{arg}$ are straightforward, simply putting
  1719. variables and integer literals into the s-expression format expected
  1720. of pseudo-x86, \code{(var $x$)} and \code{(int $n$)}, respectively.
  1721. Next we discuss some of the cases for $\itm{stmt}$, starting with
  1722. arithmetic operations. For example, in $C_0$ an addition operation can
  1723. take the form below. To translate to x86, we need to use the
  1724. \key{addq} instruction which does an in-place update. So we must first
  1725. move \code{10} to \code{x}. \\
  1726. \begin{tabular}{lll}
  1727. \begin{minipage}{0.4\textwidth}
  1728. \begin{lstlisting}
  1729. (assign x (+ 10 32))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. &
  1733. $\Rightarrow$
  1734. &
  1735. \begin{minipage}{0.4\textwidth}
  1736. \begin{lstlisting}
  1737. (movq (int 10) (var x))
  1738. (addq (int 32) (var x))
  1739. \end{lstlisting}
  1740. \end{minipage}
  1741. \end{tabular} \\
  1742. %
  1743. There are some cases that require special care to avoid generating
  1744. needlessly complicated code. If one of the arguments is the same as
  1745. the left-hand side of the assignment, then there is no need for the
  1746. extra move instruction. For example, the following assignment
  1747. statement can be translated into a single \key{addq} instruction.\\
  1748. \begin{tabular}{lll}
  1749. \begin{minipage}{0.4\textwidth}
  1750. \begin{lstlisting}
  1751. (assign x (+ 10 x))
  1752. \end{lstlisting}
  1753. \end{minipage}
  1754. &
  1755. $\Rightarrow$
  1756. &
  1757. \begin{minipage}{0.4\textwidth}
  1758. \begin{lstlisting}
  1759. (addq (int 10) (var x))
  1760. \end{lstlisting}
  1761. \end{minipage}
  1762. \end{tabular} \\
  1763. The \key{read} operation does not have a direct counterpart in x86
  1764. assembly, so we have instead implemented this functionality in the C
  1765. language, with the function \code{read\_int} in the file
  1766. \code{runtime.c}. In general, we refer to all of the functionality in
  1767. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1768. for short. When compiling your generated x86 assembly code, you
  1769. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1770. file'', using \code{gcc} option \code{-c}) and link it into the final
  1771. executable. For our purposes of code generation, all you need to do is
  1772. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1773. (for left-hand side) into a call to the \code{read\_int} function
  1774. followed by a move from \code{rax} to the left-hand side. The move
  1775. from \code{rax} is needed because the return value from
  1776. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1777. \begin{tabular}{lll}
  1778. \begin{minipage}{0.4\textwidth}
  1779. \begin{lstlisting}
  1780. (assign |$\itm{lhs}$| (read))
  1781. \end{lstlisting}
  1782. \end{minipage}
  1783. &
  1784. $\Rightarrow$
  1785. &
  1786. \begin{minipage}{0.4\textwidth}
  1787. \begin{lstlisting}
  1788. (callq read_int)
  1789. (movq (reg rax) (var |$\itm{lhs}$|))
  1790. \end{lstlisting}
  1791. \end{minipage}
  1792. \end{tabular} \\
  1793. There are two cases for the $\Tail$ non-terminal: \key{return} and
  1794. \key{seq}. Regarding \RETURN{e}, we recommend treating it as an
  1795. assignment to the \key{rax} register followed by a jump to the
  1796. conclusion of the program (so the conclusion needs to be labeled).
  1797. For $(\key{seq}\,s\,t)$, we simply process the statement $s$ and tail
  1798. $t$ recursively and append the resulting instructions.
  1799. \begin{exercise}
  1800. \normalfont
  1801. Implement the \key{select-instructions} pass and test it on all of the
  1802. example programs that you created for the previous passes and create
  1803. three new example programs that are designed to exercise all of the
  1804. interesting code in this pass. Use the \key{interp-tests} function
  1805. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1806. your passes on the example programs.
  1807. \end{exercise}
  1808. \section{Assign Homes}
  1809. \label{sec:assign-r1}
  1810. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1811. \key{assign-homes} pass places all of the variables on the stack.
  1812. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1813. which after \key{select-instructions} looks like the following.
  1814. \begin{lstlisting}
  1815. (movq (int 10) (var tmp.1))
  1816. (negq (var tmp.1))
  1817. (movq (var tmp.1) (var tmp.2))
  1818. (addq (int 52) (var tmp.2))
  1819. (movq (var tmp.2) (reg rax)))
  1820. \end{lstlisting}
  1821. The variable \code{tmp.1} is assigned to stack location
  1822. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1823. the \code{assign-homes} pass translates the above to
  1824. \begin{lstlisting}
  1825. (movq (int 10) (deref rbp -8))
  1826. (negq (deref rbp -8))
  1827. (movq (deref rbp -8) (deref rbp -16))
  1828. (addq (int 52) (deref rbp -16))
  1829. (movq (deref rbp -16) (reg rax)))
  1830. \end{lstlisting}
  1831. In the process of assigning stack locations to variables, it is
  1832. convenient to compute and store the size of the frame (in bytes) in
  1833. the $\itm{info}$ field of the \key{program} node, with the key
  1834. \code{stack-space}, which will be needed later to generate the
  1835. procedure conclusion. Some operating systems place restrictions on
  1836. the frame size. For example, Mac OS X requires the frame size to be a
  1837. multiple of 16 bytes.
  1838. \begin{exercise}
  1839. \normalfont Implement the \key{assign-homes} pass and test it on all
  1840. of the example programs that you created for the previous passes pass.
  1841. We recommend that \key{assign-homes} take an extra parameter that is a
  1842. mapping of variable names to homes (stack locations for now). Use the
  1843. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1844. \key{utilities.rkt} to test your passes on the example programs.
  1845. \end{exercise}
  1846. \section{Patch Instructions}
  1847. \label{sec:patch-s0}
  1848. The purpose of this pass is to make sure that each instruction adheres
  1849. to the restrictions regarding which arguments can be memory
  1850. references. For most instructions, the rule is that at most one
  1851. argument may be a memory reference.
  1852. Consider again the following example.
  1853. \begin{lstlisting}
  1854. (let ([a 42])
  1855. (let ([b a])
  1856. b))
  1857. \end{lstlisting}
  1858. After \key{assign-homes} pass, the above has been translated to
  1859. \begin{lstlisting}
  1860. (movq (int 42) (deref rbp -8))
  1861. (movq (deref rbp -8) (deref rbp -16))
  1862. (movq (deref rbp -16) (reg rax))
  1863. (jmp conclusion)
  1864. \end{lstlisting}
  1865. The second \key{movq} instruction is problematic because both
  1866. arguments are stack locations. We suggest fixing this problem by
  1867. moving from the source to the register \key{rax} and then from
  1868. \key{rax} to the destination, as follows.
  1869. \begin{lstlisting}
  1870. (movq (int 42) (deref rbp -8))
  1871. (movq (deref rbp -8) (reg rax))
  1872. (movq (reg rax) (deref rbp -16))
  1873. (movq (deref rbp -16) (reg rax))
  1874. \end{lstlisting}
  1875. \begin{exercise}
  1876. \normalfont
  1877. Implement the \key{patch-instructions} pass and test it on all of the
  1878. example programs that you created for the previous passes and create
  1879. three new example programs that are designed to exercise all of the
  1880. interesting code in this pass. Use the \key{interp-tests} function
  1881. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1882. your passes on the example programs.
  1883. \end{exercise}
  1884. \section{Print x86}
  1885. \label{sec:print-x86}
  1886. The last step of the compiler from $R_1$ to x86 is to convert the x86
  1887. AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1888. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1889. \key{format} and \key{string-append} functions are useful in this
  1890. regard. The main work that this step needs to perform is to create the
  1891. \key{main} function and the standard instructions for its prelude and
  1892. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1893. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1894. variables, so we suggest computing it in the \key{assign-homes} pass
  1895. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  1896. of the \key{program} node.
  1897. %% Your compiled code should print the result of the program's execution
  1898. %% by using the \code{print\_int} function provided in
  1899. %% \code{runtime.c}. If your compiler has been implemented correctly so
  1900. %% far, this final result should be stored in the \key{rax} register.
  1901. %% We'll talk more about how to perform function calls with arguments in
  1902. %% general later on, but for now, place the following after the compiled
  1903. %% code for the $R_1$ program but before the conclusion:
  1904. %% \begin{lstlisting}
  1905. %% movq %rax, %rdi
  1906. %% callq print_int
  1907. %% \end{lstlisting}
  1908. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  1909. %% stores the first argument to be passed into \key{print\_int}.
  1910. If you want your program to run on Mac OS X, your code needs to
  1911. determine whether or not it is running on a Mac, and prefix
  1912. underscores to labels like \key{main}. You can determine the platform
  1913. with the Racket call \code{(system-type 'os)}, which returns
  1914. \code{'macosx}, \code{'unix}, or \code{'windows}.
  1915. %% In addition to
  1916. %% placing underscores on \key{main}, you need to put them in front of
  1917. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1918. %% \_print\_int}).
  1919. \begin{exercise}
  1920. \normalfont Implement the \key{print-x86} pass and test it on all of
  1921. the example programs that you created for the previous passes. Use the
  1922. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1923. \key{utilities.rkt} to test your complete compiler on the example
  1924. programs.
  1925. % The following is specific to P423/P523. -Jeremy
  1926. %Mac support is optional, but your compiler has to output
  1927. %valid code for Unix machines.
  1928. \end{exercise}
  1929. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1930. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1931. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1932. \chapter{Register Allocation}
  1933. \label{ch:register-allocation-r1}
  1934. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1935. assembly by placing all variables on the stack. We can improve the
  1936. performance of the generated code considerably if we instead place as
  1937. many variables as possible into registers. The CPU can access a
  1938. register in a single cycle, whereas accessing the stack takes many
  1939. cycles to go to cache or many more to access main memory.
  1940. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1941. serves as a running example. We show the source program and also the
  1942. output of instruction selection. At that point the program is almost
  1943. x86 assembly but not quite; it still contains variables instead of
  1944. stack locations or registers.
  1945. \begin{figure}
  1946. \begin{minipage}{0.45\textwidth}
  1947. $R_1$ program:
  1948. % s0_22.rkt
  1949. \begin{lstlisting}
  1950. (program ()
  1951. (let ([v 1])
  1952. (let ([w 46])
  1953. (let ([x (+ v 7)])
  1954. (let ([y (+ 4 x)])
  1955. (let ([z (+ x w)])
  1956. (+ z (- y))))))))
  1957. \end{lstlisting}
  1958. \end{minipage}
  1959. \begin{minipage}{0.45\textwidth}
  1960. After instruction selection:
  1961. \begin{lstlisting}
  1962. (program
  1963. ((locals . (v w x y z t.1)))
  1964. ((start .
  1965. (block ()
  1966. (movq (int 1) (var v))
  1967. (movq (int 46) (var w))
  1968. (movq (var v) (var x))
  1969. (addq (int 7) (var x))
  1970. (movq (var x) (var y))
  1971. (addq (int 4) (var y))
  1972. (movq (var x) (var z))
  1973. (addq (var w) (var z))
  1974. (movq (var y) (var t.1))
  1975. (negq (var t.1))
  1976. (movq (var z) (reg rax))
  1977. (addq (var t.1) (reg rax))
  1978. (jmp conclusion)))))
  1979. \end{lstlisting}
  1980. \end{minipage}
  1981. \caption{An example program for register allocation.}
  1982. \label{fig:reg-eg}
  1983. \end{figure}
  1984. The goal of register allocation is to fit as many variables into
  1985. registers as possible. It is often the case that we have more
  1986. variables than registers, so we cannot map each variable to a
  1987. different register. Fortunately, it is common for different variables
  1988. to be needed during different periods of time, and in such cases
  1989. several variables can be mapped to the same register. Consider
  1990. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1991. variable \code{x} is moved to \code{z} it is no longer needed.
  1992. Variable \code{y}, on the other hand, is used only after this point,
  1993. so \code{x} and \code{y} could share the same register. The topic of
  1994. Section~\ref{sec:liveness-analysis-r1} is how we compute where a variable
  1995. is needed. Once we have that information, we compute which variables
  1996. are needed at the same time, i.e., which ones \emph{interfere}, and
  1997. represent this relation as graph whose vertices are variables and
  1998. edges indicate when two variables interfere with eachother
  1999. (Section~\ref{sec:build-interference}). We then model register
  2000. allocation as a graph coloring problem, which we discuss in
  2001. Section~\ref{sec:graph-coloring}.
  2002. In the event that we run out of registers despite these efforts, we
  2003. place the remaining variables on the stack, similar to what we did in
  2004. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  2005. that is assigned to a stack location, it has been \emph{spilled}. The
  2006. process of spilling variables is handled as part of the graph coloring
  2007. process described in \ref{sec:graph-coloring}.
  2008. \section{Registers and Calling Conventions}
  2009. \label{sec:calling-conventions}
  2010. As we perform register allocation, we will need to be aware of the
  2011. conventions that govern the way in which registers interact with
  2012. function calls. The convention for x86 is that the caller is
  2013. responsible for freeing up some registers, the \emph{caller-saved
  2014. registers}, prior to the function call, and the callee is
  2015. responsible for saving and restoring some other registers, the
  2016. \emph{callee-saved registers}, before and after using them. The
  2017. caller-saved registers are
  2018. \begin{lstlisting}
  2019. rax rdx rcx rsi rdi r8 r9 r10 r11
  2020. \end{lstlisting}
  2021. while the callee-saved registers are
  2022. \begin{lstlisting}
  2023. rsp rbp rbx r12 r13 r14 r15
  2024. \end{lstlisting}
  2025. Another way to think about this caller/callee convention is the
  2026. following. The caller should assume that all the caller-saved registers
  2027. get overwritten with arbitrary values by the callee. On the other
  2028. hand, the caller can safely assume that all the callee-saved registers
  2029. contain the same values after the call that they did before the call.
  2030. The callee can freely use any of the caller-saved registers. However,
  2031. if the callee wants to use a callee-saved register, the callee must
  2032. arrange to put the original value back in the register prior to
  2033. returning to the caller, which is usually accomplished by saving and
  2034. restoring the value from the stack.
  2035. \section{Liveness Analysis}
  2036. \label{sec:liveness-analysis-r1}
  2037. A variable is \emph{live} if the variable is used at some later point
  2038. in the program and there is not an intervening assignment to the
  2039. variable.
  2040. %
  2041. To understand the latter condition, consider the following code
  2042. fragment in which there are two writes to \code{b}. Are \code{a} and
  2043. \code{b} both live at the same time?
  2044. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2045. (movq (int 5) (var a))
  2046. (movq (int 30) (var b))
  2047. (movq (var a) (var c))
  2048. (movq (int 10) (var b))
  2049. (addq (var b) (var c))
  2050. \end{lstlisting}
  2051. The answer is no because the value \code{30} written to \code{b} on
  2052. line 2 is never used. The variable \code{b} is read on line 5 and
  2053. there is an intervening write to \code{b} on line 4, so the read on
  2054. line 5 receives the value written on line 4, not line 2.
  2055. The live variables can be computed by traversing the instruction
  2056. sequence back to front (i.e., backwards in execution order). Let
  2057. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2058. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2059. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2060. variables before instruction $I_k$. The live variables after an
  2061. instruction are always the same as the live variables before the next
  2062. instruction.
  2063. \begin{equation*}
  2064. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2065. \end{equation*}
  2066. To start things off, there are no live variables after the last
  2067. instruction, so
  2068. \begin{equation*}
  2069. L_{\mathsf{after}}(n) = \emptyset
  2070. \end{equation*}
  2071. We then apply the following rule repeatedly, traversing the
  2072. instruction sequence back to front.
  2073. \begin{equation*}
  2074. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2075. \end{equation*}
  2076. where $W(k)$ are the variables written to by instruction $I_k$ and
  2077. $R(k)$ are the variables read by instruction $I_k$.
  2078. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2079. for the running example, with each instruction aligned with its
  2080. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2081. \margincomment{JM: I think you should walk through the explanation of this formula,
  2082. connecting it back to the example from before. \\
  2083. JS: Agreed.}
  2084. \begin{figure}[tbp]
  2085. \hspace{20pt}
  2086. \begin{minipage}{0.45\textwidth}
  2087. \begin{lstlisting}[numbers=left]
  2088. (block ()
  2089. (movq (int 1) (var v))
  2090. (movq (int 46) (var w))
  2091. (movq (var v) (var x))
  2092. (addq (int 7) (var x))
  2093. (movq (var x) (var y))
  2094. (addq (int 4) (var y))
  2095. (movq (var x) (var z))
  2096. (addq (var w) (var z))
  2097. (movq (var y) (var t.1))
  2098. (negq (var t.1))
  2099. (movq (var z) (reg rax))
  2100. (addq (var t.1) (reg rax))
  2101. (jmp conclusion))
  2102. \end{lstlisting}
  2103. \end{minipage}
  2104. \vrule\hspace{10pt}
  2105. \begin{minipage}{0.45\textwidth}
  2106. \begin{lstlisting}
  2107. |$\{\}$|
  2108. |$\{v \}$|
  2109. |$\{v,w\}$|
  2110. |$\{w,x\}$|
  2111. |$\{w,x\}$|
  2112. |$\{w,x,y\}$|
  2113. |$\{w,x,y\}$|
  2114. |$\{w,y,z\}$|
  2115. |$\{y,z\}$|
  2116. |$\{z,t.1\}$|
  2117. |$\{z,t.1\}$|
  2118. |$\{t.1\}$|
  2119. |$\{\}$|
  2120. |$\{\}$|
  2121. \end{lstlisting}
  2122. \end{minipage}
  2123. \caption{An example block annotated with live-after sets.}
  2124. \label{fig:live-eg}
  2125. \end{figure}
  2126. \begin{exercise}\normalfont
  2127. Implement the compiler pass named \code{uncover-live} that computes
  2128. the live-after sets. We recommend storing the live-after sets (a list
  2129. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2130. construct.
  2131. %
  2132. We recommend organizing your code to use a helper function that takes
  2133. a list of instructions and an initial live-after set (typically empty)
  2134. and returns the list of live-after sets.
  2135. %
  2136. We recommend creating helper functions to 1) compute the set of
  2137. variables that appear in an argument (of an instruction), 2) compute
  2138. the variables read by an instruction which corresponds to the $R$
  2139. function discussed above, and 3) the variables written by an
  2140. instruction which corresponds to $W$.
  2141. \end{exercise}
  2142. \section{Building the Interference Graph}
  2143. \label{sec:build-interference}
  2144. Based on the liveness analysis, we know where each variable is needed.
  2145. However, during register allocation, we need to answer questions of
  2146. the specific form: are variables $u$ and $v$ live at the same time?
  2147. (And therefore cannot be assigned to the same register.) To make this
  2148. question easier to answer, we create an explicit data structure, an
  2149. \emph{interference graph}. An interference graph is an undirected
  2150. graph that has an edge between two variables if they are live at the
  2151. same time, that is, if they interfere with each other.
  2152. The most obvious way to compute the interference graph is to look at
  2153. the set of live variables between each statement in the program, and
  2154. add an edge to the graph for every pair of variables in the same set.
  2155. This approach is less than ideal for two reasons. First, it can be
  2156. rather expensive because it takes $O(n^2)$ time to look at every pair
  2157. in a set of $n$ live variables. Second, there is a special case in
  2158. which two variables that are live at the same time do not actually
  2159. interfere with each other: when they both contain the same value
  2160. because we have assigned one to the other.
  2161. A better way to compute the interference graph is to focus on the
  2162. writes. That is, for each instruction, create an edge between the
  2163. variable being written to and all the \emph{other} live variables.
  2164. (One should not create self edges.) For a \key{callq} instruction,
  2165. think of all caller-saved registers as being written to, so and edge
  2166. must be added between every live variable and every caller-saved
  2167. register. For \key{movq}, we deal with the above-mentioned special
  2168. case by not adding an edge between a live variable $v$ and destination
  2169. $d$ if $v$ matches the source of the move. So we have the following
  2170. three rules.
  2171. \begin{enumerate}
  2172. \item If instruction $I_k$ is an arithmetic instruction such as
  2173. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2174. L_{\mathsf{after}}(k)$ unless $v = d$.
  2175. \item If instruction $I_k$ is of the form (\key{callq}
  2176. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2177. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2178. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2179. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2180. d$ or $v = s$.
  2181. \end{enumerate}
  2182. \margincomment{JM: I think you could give examples of each one of these
  2183. using the example program and use those to help explain why these
  2184. rules are correct.\\
  2185. JS: Agreed.}
  2186. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2187. the following interference for the instruction at the specified line
  2188. number.
  2189. \begin{quote}
  2190. Line 2: no interference,\\
  2191. Line 3: $w$ interferes with $v$,\\
  2192. Line 4: $x$ interferes with $w$,\\
  2193. Line 5: $x$ interferes with $w$,\\
  2194. Line 6: $y$ interferes with $w$,\\
  2195. Line 7: $y$ interferes with $w$ and $x$,\\
  2196. Line 8: $z$ interferes with $w$ and $y$,\\
  2197. Line 9: $z$ interferes with $y$, \\
  2198. Line 10: $t.1$ interferes with $z$, \\
  2199. Line 11: $t.1$ interferes with $z$, \\
  2200. Line 12: no interference, \\
  2201. Line 13: no interference. \\
  2202. Line 14: no interference.
  2203. \end{quote}
  2204. The resulting interference graph is shown in
  2205. Figure~\ref{fig:interfere}.
  2206. \begin{figure}[tbp]
  2207. \large
  2208. \[
  2209. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2210. \node (v) at (0,0) {$v$};
  2211. \node (w) at (2,0) {$w$};
  2212. \node (x) at (4,0) {$x$};
  2213. \node (t1) at (6,-2) {$t.1$};
  2214. \node (y) at (2,-2) {$y$};
  2215. \node (z) at (4,-2) {$z$};
  2216. \draw (v) to (w);
  2217. \foreach \i in {w,x,y}
  2218. {
  2219. \foreach \j in {w,x,y}
  2220. {
  2221. \draw (\i) to (\j);
  2222. }
  2223. }
  2224. \draw (z) to (w);
  2225. \draw (z) to (y);
  2226. \draw (t1) to (z);
  2227. \end{tikzpicture}
  2228. \]
  2229. \caption{The interference graph of the example program.}
  2230. \label{fig:interfere}
  2231. \end{figure}
  2232. %% Our next concern is to choose a data structure for representing the
  2233. %% interference graph. There are many choices for how to represent a
  2234. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2235. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2236. %% data structure is to study the algorithm that uses the data structure,
  2237. %% determine what operations need to be performed, and then choose the
  2238. %% data structure that provide the most efficient implementations of
  2239. %% those operations. Often times the choice of data structure can have an
  2240. %% effect on the time complexity of the algorithm, as it does here. If
  2241. %% you skim the next section, you will see that the register allocation
  2242. %% algorithm needs to ask the graph for all of its vertices and, given a
  2243. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2244. %% correct choice of graph representation is that of an adjacency
  2245. %% list. There are helper functions in \code{utilities.rkt} for
  2246. %% representing graphs using the adjacency list representation:
  2247. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2248. %% (Appendix~\ref{appendix:utilities}).
  2249. %% %
  2250. %% \margincomment{\footnotesize To do: change to use the
  2251. %% Racket graph library. \\ --Jeremy}
  2252. %% %
  2253. %% In particular, those functions use a hash table to map each vertex to
  2254. %% the set of adjacent vertices, and the sets are represented using
  2255. %% Racket's \key{set}, which is also a hash table.
  2256. \begin{exercise}\normalfont
  2257. Implement the compiler pass named \code{build-interference} according
  2258. to the algorithm suggested above. We recommend using the Racket
  2259. \code{graph} package to create and inspect the interference graph.
  2260. The output graph of this pass should be stored in the $\itm{info}$
  2261. field of the program, under the key \code{conflicts}.
  2262. \end{exercise}
  2263. \section{Graph Coloring via Sudoku}
  2264. \label{sec:graph-coloring}
  2265. We now come to the main event, mapping variables to registers (or to
  2266. stack locations in the event that we run out of registers). We need
  2267. to make sure not to map two variables to the same register if the two
  2268. variables interfere with each other. In terms of the interference
  2269. graph, this means that adjacent vertices must be mapped to different
  2270. registers. If we think of registers as colors, the register
  2271. allocation problem becomes the widely-studied graph coloring
  2272. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2273. The reader may be more familiar with the graph coloring problem than he
  2274. or she realizes; the popular game of Sudoku is an instance of the
  2275. graph coloring problem. The following describes how to build a graph
  2276. out of an initial Sudoku board.
  2277. \begin{itemize}
  2278. \item There is one vertex in the graph for each Sudoku square.
  2279. \item There is an edge between two vertices if the corresponding squares
  2280. are in the same row, in the same column, or if the squares are in
  2281. the same $3\times 3$ region.
  2282. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2283. \item Based on the initial assignment of numbers to squares in the
  2284. Sudoku board, assign the corresponding colors to the corresponding
  2285. vertices in the graph.
  2286. \end{itemize}
  2287. If you can color the remaining vertices in the graph with the nine
  2288. colors, then you have also solved the corresponding game of Sudoku.
  2289. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2290. the corresponding graph with colored vertices. We map the Sudoku
  2291. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2292. sampling of the vertices (those that are colored) because showing
  2293. edges for all of the vertices would make the graph unreadable.
  2294. \begin{figure}[tbp]
  2295. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2296. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2297. \caption{A Sudoku game board and the corresponding colored graph.}
  2298. \label{fig:sudoku-graph}
  2299. \end{figure}
  2300. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2301. strategies to come up with an algorithm for allocating registers. For
  2302. example, one of the basic techniques for Sudoku is called Pencil
  2303. Marks. The idea is that you use a process of elimination to determine
  2304. what numbers no longer make sense for a square, and write down those
  2305. numbers in the square (writing very small). For example, if the number
  2306. $1$ is assigned to a square, then by process of elimination, you can
  2307. write the pencil mark $1$ in all the squares in the same row, column,
  2308. and region. Many Sudoku computer games provide automatic support for
  2309. Pencil Marks.
  2310. %
  2311. The Pencil Marks technique corresponds to the notion of color
  2312. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2313. vertex, in Sudoku terms, is the set of colors that are no longer
  2314. available. In graph terminology, we have the following definition:
  2315. \begin{equation*}
  2316. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2317. \text{ and } \mathrm{color}(v) = c \}
  2318. \end{equation*}
  2319. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2320. edge with $u$.
  2321. Using the Pencil Marks technique leads to a simple strategy for
  2322. filling in numbers: if there is a square with only one possible number
  2323. left, then write down that number! But what if there are no squares
  2324. with only one possibility left? One brute-force approach is to just
  2325. make a guess. If that guess ultimately leads to a solution, great. If
  2326. not, backtrack to the guess and make a different guess. One good
  2327. thing about Pencil Marks is that it reduces the degree of branching in
  2328. the search tree. Nevertheless, backtracking can be horribly time
  2329. consuming. One way to reduce the amount of backtracking is to use the
  2330. most-constrained-first heuristic. That is, when making a guess, always
  2331. choose a square with the fewest possibilities left (the vertex with
  2332. the highest saturation). The idea is that choosing highly constrained
  2333. squares earlier rather than later is better because later there may
  2334. not be any possibilities.
  2335. In some sense, register allocation is easier than Sudoku because we
  2336. can always cheat and add more numbers by mapping variables to the
  2337. stack. We say that a variable is \emph{spilled} when we decide to map
  2338. it to a stack location. We would like to minimize the time needed to
  2339. color the graph, and backtracking is expensive. Thus, it makes sense
  2340. to keep the most-constrained-first heuristic but drop the backtracking
  2341. in favor of greedy search (guess and just keep going).
  2342. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2343. greedy algorithm for register allocation based on saturation and the
  2344. most-constrained-first heuristic, which is roughly equivalent to the
  2345. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2346. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2347. as in Sudoku, the algorithm represents colors with integers, with the
  2348. first $k$ colors corresponding to the $k$ registers in a given machine
  2349. and the rest of the integers corresponding to stack locations.
  2350. \begin{figure}[btp]
  2351. \centering
  2352. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2353. Algorithm: DSATUR
  2354. Input: a graph |$G$|
  2355. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2356. |$W \gets \mathit{vertices}(G)$|
  2357. while |$W \neq \emptyset$| do
  2358. pick a vertex |$u$| from |$W$| with the highest saturation,
  2359. breaking ties randomly
  2360. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2361. |$\mathrm{color}[u] \gets c$|
  2362. |$W \gets W - \{u\}$|
  2363. \end{lstlisting}
  2364. \caption{The saturation-based greedy graph coloring algorithm.}
  2365. \label{fig:satur-algo}
  2366. \end{figure}
  2367. With this algorithm in hand, let us return to the running example and
  2368. consider how to color the interference graph in
  2369. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2370. register allocation because we use it to patch instructions, so we
  2371. remove that vertex from the graph. Initially, all of the vertices are
  2372. not yet colored and they are unsaturated, so we annotate each of them
  2373. with a dash for their color and an empty set for the saturation.
  2374. \[
  2375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2376. \node (v) at (0,0) {$v:-,\{\}$};
  2377. \node (w) at (3,0) {$w:-,\{\}$};
  2378. \node (x) at (6,0) {$x:-,\{\}$};
  2379. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2380. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2381. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2382. \draw (v) to (w);
  2383. \foreach \i in {w,x,y}
  2384. {
  2385. \foreach \j in {w,x,y}
  2386. {
  2387. \draw (\i) to (\j);
  2388. }
  2389. }
  2390. \draw (z) to (w);
  2391. \draw (z) to (y);
  2392. \draw (t1) to (z);
  2393. \end{tikzpicture}
  2394. \]
  2395. We select a maximally saturated vertex and color it $0$. In this case we
  2396. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2397. as no longer available for $z$ because it interferes
  2398. with $t.1$.
  2399. \[
  2400. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2401. \node (v) at (0,0) {$v:-,\{\}$};
  2402. \node (w) at (3,0) {$w:-,\{\}$};
  2403. \node (x) at (6,0) {$x:-,\{\}$};
  2404. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2405. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2406. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2407. \draw (v) to (w);
  2408. \foreach \i in {w,x,y}
  2409. {
  2410. \foreach \j in {w,x,y}
  2411. {
  2412. \draw (\i) to (\j);
  2413. }
  2414. }
  2415. \draw (z) to (w);
  2416. \draw (z) to (y);
  2417. \draw (t1) to (z);
  2418. \end{tikzpicture}
  2419. \]
  2420. Now we repeat the process, selecting another maximally saturated
  2421. vertex, which in this case is $z$. We color $z$ with $1$.
  2422. \[
  2423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2424. \node (v) at (0,0) {$v:-,\{\}$};
  2425. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2426. \node (x) at (6,0) {$x:-,\{\}$};
  2427. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2428. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2429. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2430. \draw (t1) to (z);
  2431. \draw (v) to (w);
  2432. \foreach \i in {w,x,y}
  2433. {
  2434. \foreach \j in {w,x,y}
  2435. {
  2436. \draw (\i) to (\j);
  2437. }
  2438. }
  2439. \draw (z) to (w);
  2440. \draw (z) to (y);
  2441. \end{tikzpicture}
  2442. \]
  2443. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2444. first available color, which is $0$.
  2445. \[
  2446. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2447. \node (v) at (0,0) {$v:-,\{\}$};
  2448. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2449. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2450. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2451. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2452. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2453. \draw (t1) to (z);
  2454. \draw (v) to (w);
  2455. \foreach \i in {w,x,y}
  2456. {
  2457. \foreach \j in {w,x,y}
  2458. {
  2459. \draw (\i) to (\j);
  2460. }
  2461. }
  2462. \draw (z) to (w);
  2463. \draw (z) to (y);
  2464. \end{tikzpicture}
  2465. \]
  2466. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2467. \[
  2468. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2469. \node (v) at (0,0) {$v:-,\{2\}$};
  2470. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2471. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2472. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2473. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2474. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2475. \draw (t1) to (z);
  2476. \draw (v) to (w);
  2477. \foreach \i in {w,x,y}
  2478. {
  2479. \foreach \j in {w,x,y}
  2480. {
  2481. \draw (\i) to (\j);
  2482. }
  2483. }
  2484. \draw (z) to (w);
  2485. \draw (z) to (y);
  2486. \end{tikzpicture}
  2487. \]
  2488. Now $x$ has the highest saturation, so we color it $1$.
  2489. \[
  2490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2491. \node (v) at (0,0) {$v:-,\{2\}$};
  2492. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2493. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2494. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2495. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2496. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2497. \draw (t1) to (z);
  2498. \draw (v) to (w);
  2499. \foreach \i in {w,x,y}
  2500. {
  2501. \foreach \j in {w,x,y}
  2502. {
  2503. \draw (\i) to (\j);
  2504. }
  2505. }
  2506. \draw (z) to (w);
  2507. \draw (z) to (y);
  2508. \end{tikzpicture}
  2509. \]
  2510. In the last step of the algorithm, we color $v$ with $0$.
  2511. \[
  2512. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2513. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2514. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2515. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2516. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2517. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2518. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2519. \draw (t1) to (z);
  2520. \draw (v) to (w);
  2521. \foreach \i in {w,x,y}
  2522. {
  2523. \foreach \j in {w,x,y}
  2524. {
  2525. \draw (\i) to (\j);
  2526. }
  2527. }
  2528. \draw (z) to (w);
  2529. \draw (z) to (y);
  2530. \end{tikzpicture}
  2531. \]
  2532. With the coloring complete, we can finalize the assignment of
  2533. variables to registers and stack locations. Recall that if we have $k$
  2534. registers, we map the first $k$ colors to registers and the rest to
  2535. stack locations. Suppose for the moment that we have just one
  2536. register to use for register allocation, \key{rcx}. Then the following
  2537. is the mapping of colors to registers and stack allocations.
  2538. \[
  2539. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2540. \]
  2541. Putting this mapping together with the above coloring of the variables, we
  2542. arrive at the assignment:
  2543. \begin{gather*}
  2544. \{ v \mapsto \key{\%rcx}, \,
  2545. w \mapsto \key{-16(\%rbp)}, \,
  2546. x \mapsto \key{-8(\%rbp)}, \\
  2547. y \mapsto \key{\%rcx}, \,
  2548. z\mapsto \key{-8(\%rbp)},
  2549. t.1\mapsto \key{\%rcx} \}
  2550. \end{gather*}
  2551. Applying this assignment to our running example, on the left, yields
  2552. the program on the right.\\
  2553. % why frame size of 32? -JGS
  2554. \begin{minipage}{0.4\textwidth}
  2555. \begin{lstlisting}
  2556. (block ()
  2557. (movq (int 1) (var v))
  2558. (movq (int 46) (var w))
  2559. (movq (var v) (var x))
  2560. (addq (int 7) (var x))
  2561. (movq (var x) (var y))
  2562. (addq (int 4) (var y))
  2563. (movq (var x) (var z))
  2564. (addq (var w) (var z))
  2565. (movq (var y) (var t.1))
  2566. (negq (var t.1))
  2567. (movq (var z) (reg rax))
  2568. (addq (var t.1) (reg rax))
  2569. (jmp conclusion))
  2570. \end{lstlisting}
  2571. \end{minipage}
  2572. $\Rightarrow$
  2573. \begin{minipage}{0.45\textwidth}
  2574. \begin{lstlisting}
  2575. (block ()
  2576. (movq (int 1) (reg rcx))
  2577. (movq (int 46) (deref rbp -16))
  2578. (movq (reg rcx) (deref rbp -8))
  2579. (addq (int 7) (deref rbp -8))
  2580. (movq (deref rbp -8) (reg rcx))
  2581. (addq (int 4) (reg rcx))
  2582. (movq (deref rbp -8) (deref rbp -8))
  2583. (addq (deref rbp -16) (deref rbp -8))
  2584. (movq (reg rcx) (reg rcx))
  2585. (negq (reg rcx))
  2586. (movq (deref rbp -8) (reg rax))
  2587. (addq (reg rcx) (reg rax))
  2588. (jmp conclusion))
  2589. \end{lstlisting}
  2590. \end{minipage}
  2591. The resulting program is almost an x86 program. The remaining step
  2592. is to apply the patch instructions pass. In this example, the trivial
  2593. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2594. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2595. \code{rax} as follows.
  2596. \begin{lstlisting}
  2597. (movq (deref rbp -16) (reg rax)
  2598. (addq (reg rax) (deref rbp -8))
  2599. \end{lstlisting}
  2600. An overview of all of the passes involved in register allocation is
  2601. shown in Figure~\ref{fig:reg-alloc-passes}.
  2602. \begin{figure}[tbp]
  2603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2604. \node (R1) at (0,2) {\large $R_1$};
  2605. \node (R1-2) at (3,2) {\large $R_1$};
  2606. \node (R1-3) at (6,2) {\large $R_1$};
  2607. \node (C0-1) at (6,0) {\large $C_0$};
  2608. \node (C0-2) at (3,0) {\large $C_0$};
  2609. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2610. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2611. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2612. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2613. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2614. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2615. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2616. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2617. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2618. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2619. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2620. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2621. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2622. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2623. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2624. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2625. \end{tikzpicture}
  2626. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2627. \label{fig:reg-alloc-passes}
  2628. \end{figure}
  2629. \begin{exercise}\normalfont
  2630. Implement the pass \code{allocate-registers}, which should come
  2631. after the \code{build-interference} pass. The three new passes,
  2632. \code{uncover-live}, \code{build-interference}, and
  2633. \code{allocate-registers} replace the \code{assign-homes} pass of
  2634. Section~\ref{sec:assign-r1}.
  2635. We recommend that you create a helper function named
  2636. \code{color-graph} that takes an interference graph and a list of
  2637. all the variables in the program. This function should return a
  2638. mapping of variables to their colors (represented as natural
  2639. numbers). By creating this helper function, you will be able to
  2640. reuse it in Chapter~\ref{ch:functions} when you add support for
  2641. functions.
  2642. Once you have obtained the coloring from \code{color-graph}, you can
  2643. assign the variables to registers or stack locations and then reuse
  2644. code from the \code{assign-homes} pass from
  2645. Section~\ref{sec:assign-r1} to replace the variables with their
  2646. assigned location.
  2647. Test your updated compiler by creating new example programs that
  2648. exercise all of the register allocation algorithm, such as forcing
  2649. variables to be spilled to the stack.
  2650. \end{exercise}
  2651. \section{Print x86 and Conventions for Registers}
  2652. \label{sec:print-x86-reg-alloc}
  2653. Recall the \code{print-x86} pass generates the prelude and
  2654. conclusion instructions for the \code{main} function.
  2655. %
  2656. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2657. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2658. reason for this is that our \code{main} function must adhere to the
  2659. x86 calling conventions that we described in
  2660. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2661. function needs to restore (in the conclusion) any callee-saved
  2662. registers that get used during register allocation. The simplest
  2663. approach is to save and restore all of the callee-saved registers. The
  2664. more efficient approach is to keep track of which callee-saved
  2665. registers were used and only save and restore them. Either way, make
  2666. sure to take this use of stack space into account when you are
  2667. calculating the size of the frame. Also, don't forget that the size of
  2668. the frame needs to be a multiple of 16 bytes.
  2669. \section{Challenge: Move Biasing$^{*}$}
  2670. \label{sec:move-biasing}
  2671. This section describes an optional enhancement to register allocation
  2672. for those students who are looking for an extra challenge or who have
  2673. a deeper interest in register allocation.
  2674. We return to the running example, but we remove the supposition that
  2675. we only have one register to use. So we have the following mapping of
  2676. color numbers to registers.
  2677. \[
  2678. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2679. \]
  2680. Using the same assignment that was produced by register allocator
  2681. described in the last section, we get the following program.
  2682. \begin{minipage}{0.45\textwidth}
  2683. \begin{lstlisting}
  2684. (block ()
  2685. (movq (int 1) (var v))
  2686. (movq (int 46) (var w))
  2687. (movq (var v) (var x))
  2688. (addq (int 7) (var x))
  2689. (movq (var x) (var y))
  2690. (addq (int 4) (var y))
  2691. (movq (var x) (var z))
  2692. (addq (var w) (var z))
  2693. (movq (var y) (var t.1))
  2694. (negq (var t.1))
  2695. (movq (var z) (reg rax))
  2696. (addq (var t.1) (reg rax))
  2697. (jmp conclusion))
  2698. \end{lstlisting}
  2699. \end{minipage}
  2700. $\Rightarrow$
  2701. \begin{minipage}{0.45\textwidth}
  2702. \begin{lstlisting}
  2703. (block ()
  2704. (movq (int 1) (reg rbx))
  2705. (movq (int 46) (reg rdx))
  2706. (movq (reg rbx) (reg rcx))
  2707. (addq (int 7) (reg rcx))
  2708. (movq (reg rcx) (reg rbx))
  2709. (addq (int 4) (reg rbx))
  2710. (movq (reg rcx) (reg rcx))
  2711. (addq (reg rdx) (reg rcx))
  2712. (movq (reg rbx) (reg rbx))
  2713. (negq (reg rbx))
  2714. (movq (reg rcx) (reg rax))
  2715. (addq (reg rbx) (reg rax))
  2716. (jmp conclusion))
  2717. \end{lstlisting}
  2718. \end{minipage}
  2719. While this allocation is quite good, we could do better. For example,
  2720. the variables \key{v} and \key{x} ended up in different registers, but
  2721. if they had been placed in the same register, then the move from
  2722. \key{v} to \key{x} could be removed.
  2723. We say that two variables $p$ and $q$ are \emph{move related} if they
  2724. participate together in a \key{movq} instruction, that is, \key{movq}
  2725. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2726. color for a variable, it should prefer a color that has already been
  2727. used for a move-related variable (assuming that they do not
  2728. interfere). Of course, this preference should not override the
  2729. preference for registers over stack locations, but should only be used
  2730. as a tie breaker when choosing between registers or when choosing
  2731. between stack locations.
  2732. We recommend that you represent the move relationships in a graph,
  2733. similar to how we represented interference. The following is the
  2734. \emph{move graph} for our running example.
  2735. \[
  2736. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2737. \node (v) at (0,0) {$v$};
  2738. \node (w) at (3,0) {$w$};
  2739. \node (x) at (6,0) {$x$};
  2740. \node (y) at (3,-1.5) {$y$};
  2741. \node (z) at (6,-1.5) {$z$};
  2742. \node (t1) at (9,-1.5) {$t.1$};
  2743. \draw[bend left=15] (t1) to (y);
  2744. \draw[bend left=15] (v) to (x);
  2745. \draw (x) to (y);
  2746. \draw (x) to (z);
  2747. \end{tikzpicture}
  2748. \]
  2749. Now we replay the graph coloring, pausing to see the coloring of $x$
  2750. and $v$. So we have the following coloring and the most saturated
  2751. vertex is $x$.
  2752. \[
  2753. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2754. \node (v) at (0,0) {$v:-,\{2\}$};
  2755. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2756. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2757. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2758. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2759. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2760. \draw (t1) to (z);
  2761. \draw (v) to (w);
  2762. \foreach \i in {w,x,y}
  2763. {
  2764. \foreach \j in {w,x,y}
  2765. {
  2766. \draw (\i) to (\j);
  2767. }
  2768. }
  2769. \draw (z) to (w);
  2770. \draw (z) to (y);
  2771. \end{tikzpicture}
  2772. \]
  2773. Last time we chose to color $x$ with $1$,
  2774. %
  2775. which so happens to be the color of $z$, and $x$ is move related to
  2776. $z$. This was rather lucky, and if the program had been a little
  2777. different, and say $z$ had been already assigned to $2$, then $x$
  2778. would still get $1$ and our luck would have run out. With move
  2779. biasing, we use the fact that $x$ and $z$ are move related to
  2780. influence the choice of color for $x$, in this case choosing $1$
  2781. because that's the color of $z$.
  2782. \[
  2783. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2784. \node (v) at (0,0) {$v:-,\{2\}$};
  2785. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2786. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2787. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2788. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2789. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2790. \draw (t1) to (z);
  2791. \draw (v) to (w);
  2792. \foreach \i in {w,x,y}
  2793. {
  2794. \foreach \j in {w,x,y}
  2795. {
  2796. \draw (\i) to (\j);
  2797. }
  2798. }
  2799. \draw (z) to (w);
  2800. \draw (z) to (y);
  2801. \end{tikzpicture}
  2802. \]
  2803. Next we consider coloring the variable $v$, and we just need to avoid
  2804. choosing $2$ because of the interference with $w$. Last time we choose
  2805. the color $0$, simply because it was the lowest, but this time we know
  2806. that $v$ is move related to $x$, so we choose the color $1$.
  2807. \[
  2808. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2809. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2810. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2811. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2812. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2813. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2814. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2815. \draw (t1) to (z);
  2816. \draw (v) to (w);
  2817. \foreach \i in {w,x,y}
  2818. {
  2819. \foreach \j in {w,x,y}
  2820. {
  2821. \draw (\i) to (\j);
  2822. }
  2823. }
  2824. \draw (z) to (w);
  2825. \draw (z) to (y);
  2826. \end{tikzpicture}
  2827. \]
  2828. We apply this register assignment to the running example, on the left,
  2829. to obtain the code on right.
  2830. \begin{minipage}{0.45\textwidth}
  2831. \begin{lstlisting}
  2832. (block ()
  2833. (movq (int 1) (var v))
  2834. (movq (int 46) (var w))
  2835. (movq (var v) (var x))
  2836. (addq (int 7) (var x))
  2837. (movq (var x) (var y))
  2838. (addq (int 4) (var y))
  2839. (movq (var x) (var z))
  2840. (addq (var w) (var z))
  2841. (movq (var y) (var t.1))
  2842. (negq (var t.1))
  2843. (movq (var z) (reg rax))
  2844. (addq (var t.1) (reg rax))
  2845. (jmp conclusion))
  2846. \end{lstlisting}
  2847. \end{minipage}
  2848. $\Rightarrow$
  2849. \begin{minipage}{0.45\textwidth}
  2850. \begin{lstlisting}
  2851. (block ()
  2852. (movq (int 1) (reg rcx))
  2853. (movq (int 46) (reg rbx))
  2854. (movq (reg rcx) (reg rcx))
  2855. (addq (int 7) (reg rcx))
  2856. (movq (reg rcx) (reg rdx))
  2857. (addq (int 4) (reg rdx))
  2858. (movq (reg rcx) (reg rcx))
  2859. (addq (reg rbx) (reg rcx))
  2860. (movq (reg rdx) (reg rbx))
  2861. (negq (reg rbx))
  2862. (movq (reg rcx) (reg rax))
  2863. (addq (reg rbx) (reg rax))
  2864. (jmp conclusion))
  2865. \end{lstlisting}
  2866. \end{minipage}
  2867. The \code{patch-instructions} then removes the trivial moves from
  2868. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  2869. result.
  2870. \begin{minipage}{0.45\textwidth}
  2871. \begin{lstlisting}
  2872. (block ()
  2873. (movq (int 1) (reg rcx))
  2874. (movq (int 46) (reg rbx))
  2875. (addq (int 7) (reg rcx))
  2876. (movq (reg rcx) (reg rdx))
  2877. (addq (int 4) (reg rdx))
  2878. (addq (reg rbx) (reg rcx))
  2879. (movq (reg rdx) (reg rbx))
  2880. (negq (reg rbx))
  2881. (movq (reg rcx) (reg rax))
  2882. (addq (reg rbx) (reg rax))
  2883. (jmp conclusion))
  2884. \end{lstlisting}
  2885. \end{minipage}
  2886. \begin{exercise}\normalfont
  2887. Change your implementation of \code{allocate-registers} to take move
  2888. biasing into account. Make sure that your compiler still passes all of
  2889. the previous tests. Create two new tests that include at least one
  2890. opportunity for move biasing and visually inspect the output x86
  2891. programs to make sure that your move biasing is working properly.
  2892. \end{exercise}
  2893. \margincomment{\footnotesize To do: another neat challenge would be to do
  2894. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2895. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2896. \chapter{Booleans and Control Flow}
  2897. \label{ch:bool-types}
  2898. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2899. integers. In this Chapter we add a second kind of value, the Booleans,
  2900. to create the $R_2$ language. The Boolean values \emph{true} and
  2901. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2902. Racket. We also introduce several operations that involve Booleans
  2903. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2904. \key{if} expression. With the addition of \key{if} expressions,
  2905. programs can have non-trivial control flow which has an impact on
  2906. several parts of the compiler. Also, because we now have two kinds of
  2907. values, we need to worry about programs that apply an operation to the
  2908. wrong kind of value, such as \code{(not 1)}.
  2909. There are two language design options for such situations. One option
  2910. is to signal an error and the other is to provide a wider
  2911. interpretation of the operation. The Racket language uses a mixture of
  2912. these two options, depending on the operation and the kind of
  2913. value. For example, the result of \code{(not 1)} in Racket is
  2914. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2915. the other hand, \code{(car 1)} results in a run-time error in Racket
  2916. stating that \code{car} expects a pair.
  2917. The Typed Racket language makes similar design choices as Racket,
  2918. except much of the error detection happens at compile time instead of
  2919. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2920. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2921. reports a compile-time error because Typed Racket expects the type of
  2922. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2923. For the $R_2$ language we choose to be more like Typed Racket in that
  2924. we shall perform type checking during compilation. In
  2925. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2926. is, how to compile a dynamically typed language like Racket. The
  2927. $R_2$ language is a subset of Typed Racket but by no means includes
  2928. all of Typed Racket. Furthermore, for many of the operations we shall
  2929. take a narrower interpretation than Typed Racket, for example,
  2930. rejecting \code{(not 1)}.
  2931. This chapter is organized as follows. We begin by defining the syntax
  2932. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2933. then introduce the idea of type checking and build a type checker for
  2934. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2935. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2936. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2937. how our compiler passes need to change to accommodate Booleans and
  2938. conditional control flow.
  2939. \section{The $R_2$ Language}
  2940. \label{sec:r2-lang}
  2941. The syntax of the $R_2$ language is defined in
  2942. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  2943. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2944. \code{if} expression. Also, we expand the operators to include
  2945. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  2946. operations for comparing two integers or two Booleans, and the
  2947. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  2948. integers.
  2949. \begin{figure}[tp]
  2950. \centering
  2951. \fbox{
  2952. \begin{minipage}{0.96\textwidth}
  2953. \[
  2954. \begin{array}{lcl}
  2955. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2956. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  2957. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2958. &\mid& \key{\#t} \mid \key{\#f}
  2959. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  2960. \mid (\key{not}\;\Exp) \\
  2961. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2962. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  2963. \end{array}
  2964. \]
  2965. \end{minipage}
  2966. }
  2967. \caption{The syntax of $R_2$, extending $R_1$
  2968. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  2969. \label{fig:r2-syntax}
  2970. \end{figure}
  2971. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2972. the parts that are the same as the interpreter for $R_1$
  2973. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2974. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2975. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2976. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2977. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2978. operations \code{not} and \code{and} behave as you might expect, but
  2979. note that the \code{and} operation is short-circuiting. That is, given
  2980. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2981. evaluated if $e_1$ evaluates to \code{\#f}.
  2982. With the addition of the comparison operations, there are quite a few
  2983. primitive operations and the interpreter code for them is somewhat
  2984. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2985. parts into the \code{interp-op} function and the similar parts into
  2986. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  2987. use \code{interp-op} for the \code{and} operation because of the
  2988. short-circuiting behavior in the order of evaluation of its arguments.
  2989. \begin{figure}[tbp]
  2990. \begin{lstlisting}
  2991. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2992. (define (interp-op op)
  2993. (match op
  2994. ...
  2995. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2996. ['eq? (lambda (v1 v2)
  2997. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2998. (and (boolean? v1) (boolean? v2)))
  2999. (eq? v1 v2)]))]
  3000. ['< (lambda (v1 v2)
  3001. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3002. ['<= (lambda (v1 v2)
  3003. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3004. ['> (lambda (v1 v2)
  3005. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3006. ['>= (lambda (v1 v2)
  3007. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3008. [else (error 'interp-op "unknown operator")]))
  3009. (define (interp-exp env)
  3010. (lambda (e)
  3011. (define recur (interp-exp env))
  3012. (match e
  3013. ...
  3014. [(? boolean?) e]
  3015. [`(if ,cnd ,thn ,els)
  3016. (define b (recur cnd))
  3017. (match b
  3018. [#t (recur thn)]
  3019. [#f (recur els)])]
  3020. [`(and ,e1 ,e2)
  3021. (define v1 (recur e1))
  3022. (match v1
  3023. [#t (match (recur e2) [#t #t] [#f #f])]
  3024. [#f #f])]
  3025. [`(,op ,args ...)
  3026. #:when (set-member? primitives op)
  3027. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3028. )))
  3029. (define (interp-R2 env)
  3030. (lambda (p)
  3031. (match p
  3032. [`(program ,info ,e)
  3033. ((interp-exp '()) e)])))
  3034. \end{lstlisting}
  3035. \caption{Interpreter for the $R_2$ language.}
  3036. \label{fig:interp-R2}
  3037. \end{figure}
  3038. \section{Type Checking $R_2$ Programs}
  3039. \label{sec:type-check-r2}
  3040. It is helpful to think about type checking in two complementary
  3041. ways. A type checker predicts the \emph{type} of value that will be
  3042. produced by each expression in the program. For $R_2$, we have just
  3043. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3044. predict that
  3045. \begin{lstlisting}
  3046. (+ 10 (- (+ 12 20)))
  3047. \end{lstlisting}
  3048. produces an \key{Integer} while
  3049. \begin{lstlisting}
  3050. (and (not #f) #t)
  3051. \end{lstlisting}
  3052. produces a \key{Boolean}.
  3053. As mentioned at the beginning of this chapter, a type checker also
  3054. rejects programs that apply operators to the wrong type of value. Our
  3055. type checker for $R_2$ will signal an error for the following
  3056. expression because, as we have seen above, the expression \code{(+ 10
  3057. ...)} has type \key{Integer}, and we require the argument of a
  3058. \code{not} to have type \key{Boolean}.
  3059. \begin{lstlisting}
  3060. (not (+ 10 (- (+ 12 20))))
  3061. \end{lstlisting}
  3062. The type checker for $R_2$ is best implemented as a structurally
  3063. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3064. many of the clauses for the \code{type-check-exp} function. Given an
  3065. input expression \code{e}, the type checker either returns the type
  3066. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3067. the type of an integer literal is \code{Integer} and the type of a
  3068. Boolean literal is \code{Boolean}. To handle variables, the type
  3069. checker, like the interpreter, uses an association list. However, in
  3070. this case the association list maps variables to types instead of
  3071. values. Consider the clause for \key{let}. We type check the
  3072. initializing expression to obtain its type \key{T} and then associate
  3073. type \code{T} with the variable \code{x}. When the type checker
  3074. encounters the use of a variable, it can find its type in the
  3075. association list.
  3076. \begin{figure}[tbp]
  3077. \begin{lstlisting}
  3078. (define (type-check-exp env)
  3079. (lambda (e)
  3080. (define recur (type-check-exp env))
  3081. (match e
  3082. [(? fixnum?) 'Integer]
  3083. [(? boolean?) 'Boolean]
  3084. [(? symbol? x) (dict-ref env x)]
  3085. [`(read) 'Integer]
  3086. [`(let ([,x ,e]) ,body)
  3087. (define T (recur e))
  3088. (define new-env (cons (cons x T) env))
  3089. (type-check-exp new-env body)]
  3090. ...
  3091. [`(not ,e)
  3092. (match (recur e)
  3093. ['Boolean 'Boolean]
  3094. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3095. ...
  3096. )))
  3097. (define (type-check-R2 env)
  3098. (lambda (e)
  3099. (match e
  3100. [`(program ,info ,body)
  3101. (define ty ((type-check-exp '()) body))
  3102. `(program ,info ,body)]
  3103. )))
  3104. \end{lstlisting}
  3105. \caption{Skeleton of a type checker for the $R_2$ language.}
  3106. \label{fig:type-check-R2}
  3107. \end{figure}
  3108. %% To print the resulting value correctly, the overall type of the
  3109. %% program must be threaded through the remainder of the passes. We can
  3110. %% store the type within the \key{program} form as shown in Figure
  3111. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3112. %% intermediate language produced by the type checker, which we define as
  3113. %% follows: \\[1ex]
  3114. %% \fbox{
  3115. %% \begin{minipage}{0.87\textwidth}
  3116. %% \[
  3117. %% \begin{array}{lcl}
  3118. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3119. %% \end{array}
  3120. %% \]
  3121. %% \end{minipage}
  3122. %% }
  3123. \begin{exercise}\normalfont
  3124. Complete the implementation of \code{type-check-R2} and test it on 10
  3125. new example programs in $R_2$ that you choose based on how thoroughly
  3126. they test the type checking algorithm. Half of the example programs
  3127. should have a type error, to make sure that your type checker properly
  3128. rejects them. The other half of the example programs should not have
  3129. type errors. Your testing should check that the result of the type
  3130. checker agrees with the value returned by the interpreter, that is, if
  3131. the type checker returns \key{Integer}, then the interpreter should
  3132. return an integer. Likewise, if the type checker returns
  3133. \key{Boolean}, then the interpreter should return \code{\#t} or
  3134. \code{\#f}. Note that if your type checker does not signal an error
  3135. for a program, then interpreting that program should not encounter an
  3136. error. If it does, there is something wrong with your type checker.
  3137. \end{exercise}
  3138. \section{Shrink the $R_2$ Language}
  3139. \label{sec:shrink-r2}
  3140. The $R_2$ language includes several operators that are easily
  3141. expressible in terms of other operators. For example, subtraction is
  3142. expressible in terms of addition and negation.
  3143. \[
  3144. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3145. \]
  3146. Several of the comparison operations are expressible in terms of
  3147. less-than and logical negation.
  3148. \[
  3149. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{not}\;(\key{<}\;e_2\;e_1))
  3150. \]
  3151. By performing these translations near the front-end of the compiler,
  3152. the later passes of the compiler will not need to deal with these
  3153. constructs, making those passes shorter. On the other hand, sometimes
  3154. these translations make it more difficult to generate the most
  3155. efficient code with respect to the number of instructions. However,
  3156. these differences typically do not affect the number of accesses to
  3157. memory, which is the primary factor that determines execution time on
  3158. modern computer architectures.
  3159. \begin{exercise}\normalfont
  3160. Implement the pass \code{shrink} that removes subtraction,
  3161. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3162. by translating them to other constructs in $R_2$. Create tests to
  3163. make sure that the behavior of all of these constructs stays the
  3164. same after translation.
  3165. \end{exercise}
  3166. \section{XOR, Comparisons, and Control Flow in x86}
  3167. \label{sec:x86-1}
  3168. To implement the new logical operations, the comparison operations,
  3169. and the \key{if} expression, we need to delve further into the x86
  3170. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3171. larger subset of x86 that includes instructions for logical
  3172. operations, comparisons, and jumps.
  3173. One small challenge is that x86 does not provide an instruction that
  3174. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3175. However, the \code{xorq} instruction can be used to encode \code{not}.
  3176. The \key{xorq} instruction takes two arguments, performs a pairwise
  3177. exclusive-or operation on each bit of its arguments, and writes the
  3178. results into its second argument. Recall the truth table for
  3179. exclusive-or:
  3180. \begin{center}
  3181. \begin{tabular}{l|cc}
  3182. & 0 & 1 \\ \hline
  3183. 0 & 0 & 1 \\
  3184. 1 & 1 & 0
  3185. \end{tabular}
  3186. \end{center}
  3187. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3188. in row of the table for the bit $1$, the result is the opposite of the
  3189. second bit. Thus, the \code{not} operation can be implemented by
  3190. \code{xorq} with $1$ as the first argument: $0001
  3191. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3192. 0001 = 0000$.
  3193. \begin{figure}[tp]
  3194. \fbox{
  3195. \begin{minipage}{0.96\textwidth}
  3196. \[
  3197. \begin{array}{lcl}
  3198. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3199. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3200. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3201. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3202. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3203. (\key{subq} \; \Arg\; \Arg) \mid
  3204. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3205. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3206. (\key{pushq}\;\Arg) \mid
  3207. (\key{popq}\;\Arg) \mid
  3208. (\key{retq})} \\
  3209. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3210. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3211. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3212. \mid (\key{jmp} \; \itm{label})
  3213. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3214. &\mid& (\key{label} \; \itm{label}) \\
  3215. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3216. \end{array}
  3217. \]
  3218. \end{minipage}
  3219. }
  3220. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3221. \label{fig:x86-1}
  3222. \end{figure}
  3223. Next we consider the x86 instructions that are relevant for
  3224. compiling the comparison operations. The \key{cmpq} instruction
  3225. compares its two arguments to determine whether one argument is less
  3226. than, equal, or greater than the other argument. The \key{cmpq}
  3227. instruction is unusual regarding the order of its arguments and where
  3228. the result is placed. The argument order is backwards: if you want to
  3229. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3230. \key{cmpq} is placed in the special EFLAGS register. This register
  3231. cannot be accessed directly but it can be queried by a number of
  3232. instructions, including the \key{set} instruction. The \key{set}
  3233. instruction puts a \key{1} or \key{0} into its destination depending
  3234. on whether the comparison came out according to the condition code
  3235. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3236. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3237. The set instruction has an annoying quirk in that its destination
  3238. argument must be single byte register, such as \code{al}, which is
  3239. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3240. instruction can then be used to move from a single byte register to a
  3241. normal 64-bit register.
  3242. For compiling the \key{if} expression, the x86 instructions for
  3243. jumping are relevant. The \key{jmp} instruction updates the program
  3244. counter to point to the instruction after the indicated label. The
  3245. \key{jmp-if} instruction updates the program counter to point to the
  3246. instruction after the indicated label depending on whether the result
  3247. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3248. the \key{jmp-if} instruction falls through to the next
  3249. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3250. register, it is quite common for the \key{jmp-if} to be immediately
  3251. preceeded by a \key{cmpq} instruction, to set the EFLAGS regsiter.
  3252. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3253. for x86 to separate the instruction name from the condition code. For
  3254. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3255. \section{The $C_1$ Intermediate Language}
  3256. \label{sec:c1}
  3257. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3258. language, but we need to grow that intermediate language to handle the
  3259. new features in $R_2$: Booleans and conditional expressions.
  3260. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3261. logic and comparison operators to the $\Exp$ non-terminal, the
  3262. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3263. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3264. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3265. goto's in the grammar for $\Tail$. This means that a sequence of
  3266. statements may now end with a \code{goto} or a conditional
  3267. \code{goto}, which jumps to one of two labeled pieces of code
  3268. depending on the outcome of the comparison. In
  3269. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3270. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3271. and \key{goto}'s.
  3272. \begin{figure}[tp]
  3273. \fbox{
  3274. \begin{minipage}{0.96\textwidth}
  3275. \[
  3276. \begin{array}{lcl}
  3277. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3278. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3279. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3280. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3281. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3282. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3283. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3284. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3285. \end{array}
  3286. \]
  3287. \end{minipage}
  3288. }
  3289. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3290. \label{fig:c1-syntax}
  3291. \end{figure}
  3292. \section{Explicate Control}
  3293. \label{sec:explicate-control-r2}
  3294. Recall that the purpose of \code{explicate-control} is to make the
  3295. order of evaluation explicit in the syntax of the program. With the
  3296. addition of \key{if} in $R_2$, things get more interesting.
  3297. As a motivating example, consider the following program that has an
  3298. \key{if} expression nested in the predicate of another \key{if}.
  3299. % s1_38.rkt
  3300. \begin{lstlisting}
  3301. (program ()
  3302. (if (if (eq? (read) 1)
  3303. (eq? (read) 0)
  3304. (eq? (read) 2))
  3305. (+ 10 32)
  3306. (+ 700 77)))
  3307. \end{lstlisting}
  3308. %
  3309. The naive way to compile \key{if} and \key{eq?} would be to handle
  3310. each of them in isolation, regardless of their context. Each
  3311. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3312. by a couple instructions to move the result from the EFLAGS register
  3313. into a general purpose register or stack location. Each \key{if} would
  3314. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3315. However, if we take context into account we can do better and reduce
  3316. the use of \key{cmpq} and EFLAG-accessing instructions.
  3317. One idea is to try and reorganize the code at the level of $R_2$,
  3318. pushing the outer \key{if} inside the inner one. This would yield the
  3319. following code.
  3320. \begin{lstlisting}
  3321. (if (eq? (read) 1)
  3322. (if (eq? (read) 0)
  3323. (+ 10 32)
  3324. (+ 700 77))
  3325. (if (eq? (read) 2))
  3326. (+ 10 32)
  3327. (+ 700 77))
  3328. \end{lstlisting}
  3329. Unfortunately, this approach duplicates the two branches, and a
  3330. compiler must never duplicate code!
  3331. We need a way to perform the above transformation, but without
  3332. duplicating code. The solution is straightforward if we think at the
  3333. level of x86 assembly: we can label the code for each of the branches
  3334. and insert \key{goto}'s in all the places that need to execute the
  3335. branches. Put another way, we need to move away from abstract syntax
  3336. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3337. use a standard program representation called a \emph{control flow
  3338. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3339. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3340. each edge represents a jump to another block. The \key{program}
  3341. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3342. association list mapping labels to basic blocks. Each block is
  3343. represented by the $\Tail$ non-terminal.
  3344. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3345. \code{remove-complex-opera*} pass and then the
  3346. \code{explicate-control} pass on the example program. We shall walk
  3347. through the output program and then discuss the algorithm.
  3348. %
  3349. Following the order of evaluation in the output of
  3350. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3351. comparison to \code{1} from the predicate of the inner \key{if}. In
  3352. the output of \code{explicate-control}, in the \code{start} block,
  3353. this becomes a \code{(read)} followed by a conditional goto to either
  3354. \code{block61} or \code{block62}. Each of these contains the
  3355. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3356. 1)}, respectively. Regarding \code{block61}, we start with the
  3357. \code{(read)} and comparison to \code{0} and then have a conditional
  3358. goto, either to \code{block59} or \code{block60}, which indirectly
  3359. take us to \code{block55} and \code{block56}, the two branches of the
  3360. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3361. story for \code{block62} is similar.
  3362. \begin{figure}[tbp]
  3363. \begin{tabular}{lll}
  3364. \begin{minipage}{0.4\textwidth}
  3365. \begin{lstlisting}
  3366. (program ()
  3367. (if (if (eq? (read) 1)
  3368. (eq? (read) 0)
  3369. (eq? (read) 2))
  3370. (+ 10 32)
  3371. (+ 700 77)))
  3372. \end{lstlisting}
  3373. \hspace{40pt}$\Downarrow$
  3374. \begin{lstlisting}
  3375. (program ()
  3376. (if (if (let ([tmp52 (read)])
  3377. (eq? tmp52 1))
  3378. (let ([tmp53 (read)])
  3379. (eq? tmp53 0))
  3380. (let ([tmp54 (read)])
  3381. (eq? tmp54 2)))
  3382. (+ 10 32)
  3383. (+ 700 77)))
  3384. \end{lstlisting}
  3385. \end{minipage}
  3386. &
  3387. $\Rightarrow$
  3388. &
  3389. \begin{minipage}{0.55\textwidth}
  3390. \begin{lstlisting}
  3391. (program ()
  3392. ((block62 .
  3393. (seq (assign tmp54 (read))
  3394. (if (eq? tmp54 2)
  3395. (goto block59)
  3396. (goto block60))))
  3397. (block61 .
  3398. (seq (assign tmp53 (read))
  3399. (if (eq? tmp53 0)
  3400. (goto block57)
  3401. (goto block58))))
  3402. (block60 . (goto block56))
  3403. (block59 . (goto block55))
  3404. (block58 . (goto block56))
  3405. (block57 . (goto block55))
  3406. (block56 . (return (+ 700 77)))
  3407. (block55 . (return (+ 10 32)))
  3408. (start .
  3409. (seq (assign tmp52 (read))
  3410. (if (eq? tmp52 1)
  3411. (goto block61)
  3412. (goto block62))))))
  3413. \end{lstlisting}
  3414. \end{minipage}
  3415. \end{tabular}
  3416. \caption{Example translation from $R_2$ to $C_1$
  3417. via the \code{explicate-control}.}
  3418. \label{fig:explicate-control-s1-38}
  3419. \end{figure}
  3420. The nice thing about the output of \code{explicate-control} is that
  3421. there are no unnecessary uses of \code{eq?} and every use of
  3422. \code{eq?} is part of a conditional jump. The down-side of this output
  3423. is that it includes trivial blocks, such as \code{block57} through
  3424. \code{block60}, that only jump to another block. We discuss a solution
  3425. to this problem in Section~\ref{sec:opt-jumps}.
  3426. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3427. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3428. functions, \code{explicate-control-tail} and
  3429. \code{explicate-control-assign}. The former function translated
  3430. expressions in tail position whereas the later function translated
  3431. expressions on the right-hand-side of a \key{let}. With the addition
  3432. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3433. with: the predicate position of the \key{if}. So we shall need another
  3434. function, \code{explicate-control-pred}, that takes an $R_2$
  3435. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3436. then-branch and else-branch. The output of
  3437. \code{explicate-control-pred} is a $C_1$ $\Tail$. However, these
  3438. three functions also need to contruct the control-flow graph, which we
  3439. recommend they do via updates to a global variable. Next we consider
  3440. the specific additions to the tail and assign functions, and some of
  3441. cases for the pred function.
  3442. The \code{explicate-control-tail} function needs an additional case
  3443. for \key{if}. The branches of the \key{if} inherit the current
  3444. context, so they are in tail position. Let $B_1$ be the result of
  3445. \code{explicate-control-tail} on the $\itm{thn}$ branch and $B_2$ be
  3446. the result of apply \code{explicate-control-tail} to the $\itm{else}$
  3447. branch. Then the \key{if} translates to the block $B_3$ which is the
  3448. result of applying \code{explicate-control-pred} to the predicate
  3449. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3450. \[
  3451. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3452. \]
  3453. Next we consider the case for \key{if} in the
  3454. \code{explicate-control-assign} function. So the context of the
  3455. \key{if} is an assignment to some variable $x$ and then the control
  3456. continues to some block $B_1$. The code that we generate for both the
  3457. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3458. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3459. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3460. context, so that are in assignment positions. Let $B_2$ be the result
  3461. of applying \code{explicate-control-assign} to the $\itm{thn}$ branch,
  3462. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3463. result of applying \code{explicate-control-assign} to the $\itm{else}$
  3464. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3465. \key{if} translates to the block $B_4$ which is the result of applying
  3466. \code{explicate-control-pred} to the predicate $\itm{cnd}$ and the
  3467. blocks $B_2$ and $B_3$.
  3468. \[
  3469. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3470. \]
  3471. The function \code{explicate-control-pred} will need a case for every
  3472. expression that can have type \code{Boolean}. We detail a few cases
  3473. here and leave the rest for the reader. The input to this function is
  3474. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3475. enclosing \key{if}. One of the base cases of this function is when the
  3476. expression is a less-than comparision. We translate it to a
  3477. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3478. $B_2$, so we add them to the control flow graph and obtain some labels
  3479. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3480. as follows.
  3481. \[
  3482. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3483. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3484. \]
  3485. The case for \key{if} in \code{explicate-control-pred} is particularly
  3486. illuminating, as it deals with the challenges that we discussed above
  3487. regarding the example of the nested \key{if} expressions. Again, we
  3488. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3489. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3490. and $\itm{els}$ of the current \key{if} inherit their context from the
  3491. current one, i.e., predicate context. So we apply
  3492. \code{explicate-control-pred} to $\itm{thn}$ with the two blocks
  3493. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3494. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3495. Finally, we apply \code{explicate-control-pred} to
  3496. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3497. to obtain the result $B_5$.
  3498. \[
  3499. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3500. \quad\Rightarrow\quad
  3501. B_5
  3502. \]
  3503. \begin{exercise}\normalfont
  3504. Implement the pass \code{explicate-code} by adding the cases for
  3505. \key{if} to the functions for tail and assignment contexts, and
  3506. implement the function for predicate contexts. Create test cases
  3507. that exercise all of the new cases in the code for this pass.
  3508. \end{exercise}
  3509. \section{Select Instructions}
  3510. \label{sec:select-r2}
  3511. Recall that the \code{select-instructions} pass lowers from our
  3512. $C$-like intermediate representation to the pseudo-x86 language, which
  3513. is suitable for conducting register allocation. The pass is
  3514. implemented using three auxilliary functions, one for each of the
  3515. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3516. For $\Arg$, we have new cases for the Booleans. We take the usual
  3517. approach of encoding them as integers, with true as 1 and false as 0.
  3518. \[
  3519. \key{\#t} \Rightarrow \key{1}
  3520. \qquad
  3521. \key{\#f} \Rightarrow \key{0}
  3522. \]
  3523. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3524. be implemented in terms of \code{xorq} as we discussed at the
  3525. beginning of this section. Given an assignment \code{(assign
  3526. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3527. the same as $\Arg$, then just the \code{xorq} suffices:
  3528. \[
  3529. (\key{assign}\; x\; (\key{not}\; x))
  3530. \quad\Rightarrow\quad
  3531. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3532. \]
  3533. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3534. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3535. $\Arg$. Then we have
  3536. \[
  3537. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3538. \quad\Rightarrow\quad
  3539. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3540. \]
  3541. Next consider the cases for \code{eq?} and less-than comparison.
  3542. Translating these operations to x86 is slightly involved due to the
  3543. unusual nature of the \key{cmpq} instruction discussed above. We
  3544. recommend translating an assignment from \code{eq?} into the following
  3545. sequence of three instructions. \\
  3546. \begin{tabular}{lll}
  3547. \begin{minipage}{0.4\textwidth}
  3548. \begin{lstlisting}
  3549. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3550. \end{lstlisting}
  3551. \end{minipage}
  3552. &
  3553. $\Rightarrow$
  3554. &
  3555. \begin{minipage}{0.4\textwidth}
  3556. \begin{lstlisting}
  3557. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3558. (set e (byte-reg al))
  3559. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3560. \end{lstlisting}
  3561. \end{minipage}
  3562. \end{tabular} \\
  3563. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3564. \key{goto} and conditional \key{goto}. Both are straightforward
  3565. to handle. A \key{goto} becomes a jump instruction.
  3566. \[
  3567. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3568. \]
  3569. A conditional \key{goto} becomes a compare instruction followed
  3570. by a conditional jump (for ``then'') and the fall-through is
  3571. to a regular jump (for ``else'').\\
  3572. \begin{tabular}{lll}
  3573. \begin{minipage}{0.4\textwidth}
  3574. \begin{lstlisting}
  3575. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3576. (goto |$\ell_1$|)
  3577. (goto |$\ell_2$|))
  3578. \end{lstlisting}
  3579. \end{minipage}
  3580. &
  3581. $\Rightarrow$
  3582. &
  3583. \begin{minipage}{0.4\textwidth}
  3584. \begin{lstlisting}
  3585. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3586. (jmp-if e |$\ell_1$|)
  3587. (jmp |$\ell_2$|))
  3588. \end{lstlisting}
  3589. \end{minipage}
  3590. \end{tabular} \\
  3591. \begin{exercise}\normalfont
  3592. Expand your \code{select-instructions} pass to handle the new features
  3593. of the $R_2$ language. Test the pass on all the examples you have
  3594. created and make sure that you have some test programs that use the
  3595. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3596. the output using the \code{interp-x86} interpreter
  3597. (Appendix~\ref{appendix:interp}).
  3598. \end{exercise}
  3599. \section{Register Allocation}
  3600. \label{sec:register-allocation-r2}
  3601. The changes required for $R_2$ affect the liveness analysis, building
  3602. the interference graph, and assigning homes, but the graph coloring
  3603. algorithm itself does not need to change.
  3604. \subsection{Liveness Analysis}
  3605. \label{sec:liveness-analysis-r2}
  3606. Recall that for $R_1$ we implemented liveness analysis for a single
  3607. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3608. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3609. now produces many basic blocks arranged in a control-flow graph. The
  3610. first question we need to consider is in what order should we process
  3611. the basic blocks? Recall that to perform liveness analysis, we need to
  3612. know the live-after set. If a basic block has no successor blocks,
  3613. then it has an empty live-after set and we can immediately apply
  3614. liveness analysis to it. If a basic block has some successors, then we
  3615. need to complete liveness analysis on those blocks first.
  3616. Furthermore, we know that the control flow graph does not contain any
  3617. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3618. were to add loops to the language, then the CFG could contain cycles
  3619. and we would instead need to use the classic worklist algorithm for
  3620. computing the fixed point of the liveness
  3621. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3622. need to process the basic blocks in reverse topological order. We
  3623. recommend using the \code{tsort} and \code{transpose} functions of the
  3624. Racket \code{graph} package to obtain this ordering.
  3625. The next question is how to compute the live-after set of a block
  3626. given the live-before sets of all its successor blocks. During
  3627. compilation we do not know which way the branch will go, so we do not
  3628. know which of the successor's live-before set to use. The solution
  3629. comes from the observation that there is no harm in identifying more
  3630. variables as live than absolutely necessary. Thus, we can take the
  3631. union of the live-before sets from all the successors to be the
  3632. live-after set for the block. Once we have computed the live-after
  3633. set, we can proceed to perform liveness analysis on the block just as
  3634. we did in Section~\ref{sec:liveness-analysis-r1}.
  3635. The helper functions for computing the variables in an instruction's
  3636. argument and for computing the variables read-from ($R$) or written-to
  3637. ($W$) by an instruction need to be updated to handle the new kinds of
  3638. arguments and instructions in x86$_1$.
  3639. \subsection{Build Interference}
  3640. \label{sec:build-interference-r2}
  3641. Many of the new instructions in x86$_1$ can be handled in the same way
  3642. as the instructions in x86$_0$. Thus, if your code was already quite
  3643. general, it will not need to be changed to handle the new
  3644. instructions. If not, I recommend that you change your code to be more
  3645. general. The \key{movzbq} instruction should be handled like the
  3646. \key{movq} instruction.
  3647. %% \subsection{Assign Homes}
  3648. %% \label{sec:assign-homes-r2}
  3649. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3650. %% to be updated to handle the \key{if} statement, simply by recursively
  3651. %% processing the child nodes. Hopefully your code already handles the
  3652. %% other new instructions, but if not, you can generalize your code.
  3653. \begin{exercise}\normalfont
  3654. Update the \code{register-allocation} pass so that it works for $R_2$
  3655. and test your compiler using your previously created programs on the
  3656. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3657. \end{exercise}
  3658. %% \section{Lower Conditionals (New Pass)}
  3659. %% \label{sec:lower-conditionals}
  3660. %% In the \code{select-instructions} pass we decided to procrastinate in
  3661. %% the lowering of the \key{if} statement, thereby making liveness
  3662. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3663. %% statement into the appropriate instruction sequence. The following
  3664. %% translation gives the general idea. If the condition is true, we need
  3665. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3666. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3667. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3668. %% is appropriate for the comparison operator \itm{cmp}. If the
  3669. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3670. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3671. %% through to the $\itm{thns}$ branch. So we jump to the
  3672. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3673. %% created with \code{gensym}.
  3674. %% \begin{tabular}{lll}
  3675. %% \begin{minipage}{0.4\textwidth}
  3676. %% \begin{lstlisting}
  3677. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3678. %% \end{lstlisting}
  3679. %% \end{minipage}
  3680. %% &
  3681. %% $\Rightarrow$
  3682. %% &
  3683. %% \begin{minipage}{0.4\textwidth}
  3684. %% \begin{lstlisting}
  3685. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3686. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3687. %% |$\itm{elss}$|
  3688. %% (jmp |$\itm{endlabel}$|)
  3689. %% (label |$\itm{thenlabel}$|)
  3690. %% |$\itm{thns}$|
  3691. %% (label |$\itm{endlabel}$|)
  3692. %% \end{lstlisting}
  3693. %% \end{minipage}
  3694. %% \end{tabular}
  3695. %% \begin{exercise}\normalfont
  3696. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3697. %% your previously created programs on the \code{interp-x86} interpreter
  3698. %% (Appendix~\ref{appendix:interp}).
  3699. %% \end{exercise}
  3700. \section{Patch Instructions}
  3701. The second argument of the \key{cmpq} instruction must not be an
  3702. immediate value (such as a literal integer). So if you are comparing
  3703. two immediates, we recommend inserting a \key{movq} instruction to put
  3704. the second argument in \key{rax}.
  3705. %
  3706. The second argument of the \key{movzbq} must be a register.
  3707. %
  3708. There are no special restrictions on the x86 instructions
  3709. \key{jmp-if}, \key{jmp}, and \key{label}.
  3710. \begin{exercise}\normalfont
  3711. Update \code{patch-instructions} to handle the new x86 instructions.
  3712. Test your compiler using your previously created programs on the
  3713. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3714. \end{exercise}
  3715. \section{An Example Translation}
  3716. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3717. $R_2$ translated to x86, showing the results of
  3718. \code{explicate-control}, \code{select-instructions}, and the final
  3719. x86 assembly code.
  3720. \begin{figure}[tbp]
  3721. \begin{tabular}{lll}
  3722. \begin{minipage}{0.5\textwidth}
  3723. % s1_20.rkt
  3724. \begin{lstlisting}
  3725. (program ()
  3726. (if (eq? (read) 1) 42 0))
  3727. \end{lstlisting}
  3728. $\Downarrow$
  3729. \begin{lstlisting}
  3730. (program ()
  3731. ((block32 . (return 0))
  3732. (block31 . (return 42))
  3733. (start .
  3734. (seq (assign tmp30 (read))
  3735. (if (eq? tmp30 1)
  3736. (goto block31)
  3737. (goto block32))))))
  3738. \end{lstlisting}
  3739. $\Downarrow$
  3740. \begin{lstlisting}
  3741. (program ((locals . (tmp30)))
  3742. ((block32 .
  3743. (block ()
  3744. (movq (int 0) (reg rax))
  3745. (jmp conclusion)))
  3746. (block31 .
  3747. (block ()
  3748. (movq (int 42) (reg rax))
  3749. (jmp conclusion)))
  3750. (start .
  3751. (block ()
  3752. (callq read_int)
  3753. (movq (reg rax) (var tmp30))
  3754. (cmpq (int 1) (var tmp30))
  3755. (jmp-if e block31)
  3756. (jmp block32)))))
  3757. \end{lstlisting}
  3758. \end{minipage}
  3759. &
  3760. $\Rightarrow$
  3761. \begin{minipage}{0.4\textwidth}
  3762. \begin{lstlisting}
  3763. _block31:
  3764. movq $42, %rax
  3765. jmp _conclusion
  3766. _block32:
  3767. movq $0, %rax
  3768. jmp _conclusion
  3769. _start:
  3770. callq _read_int
  3771. movq %rax, %rcx
  3772. cmpq $1, %rcx
  3773. je _block31
  3774. jmp _block32
  3775. .globl _main
  3776. _main:
  3777. pushq %rbp
  3778. movq %rsp, %rbp
  3779. pushq %r12
  3780. pushq %rbx
  3781. pushq %r13
  3782. pushq %r14
  3783. subq $0, %rsp
  3784. jmp _start
  3785. _conclusion:
  3786. addq $0, %rsp
  3787. popq %r14
  3788. popq %r13
  3789. popq %rbx
  3790. popq %r12
  3791. popq %rbp
  3792. retq
  3793. \end{lstlisting}
  3794. \end{minipage}
  3795. \end{tabular}
  3796. \caption{Example compilation of an \key{if} expression to x86.}
  3797. \label{fig:if-example-x86}
  3798. \end{figure}
  3799. \begin{figure}[p]
  3800. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3801. \node (R2) at (0,2) {\large $R_2$};
  3802. \node (R2-2) at (3,2) {\large $R_2$};
  3803. \node (R2-3) at (6,2) {\large $R_2$};
  3804. \node (R2-4) at (9,2) {\large $R_2$};
  3805. \node (R2-5) at (12,2) {\large $R_2$};
  3806. \node (C1-1) at (6,0) {\large $C_1$};
  3807. \node (C1-2) at (3,0) {\large $C_1$};
  3808. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3809. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3810. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3811. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3812. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3813. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3814. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3815. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3816. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3817. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3818. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3819. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3820. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3821. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3822. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3823. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3824. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3825. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3826. \end{tikzpicture}
  3827. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3828. \label{fig:R2-passes}
  3829. \end{figure}
  3830. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3831. compilation of $R_2$.
  3832. \section{Challenge: Optimize Jumps$^{*}$}
  3833. \label{sec:opt-jumps}
  3834. UNDER CONSTRUCTION
  3835. %% \section{Challenge: Optimizing Conditions$^{*}$}
  3836. %% \label{sec:opt-if}
  3837. %% A close inspection of the x86 code generated in
  3838. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3839. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3840. %% twice using \key{cmpq} as follows.
  3841. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  3842. %% % Does it have to do with page breaks?
  3843. %% \begin{lstlisting}
  3844. %% \end{lstlisting}
  3845. %% \begin{lstlisting}
  3846. %% cmpq $1, %rcx
  3847. %% sete %al
  3848. %% movzbq %al, %rcx
  3849. %% cmpq $1, %rcx
  3850. %% je then21288
  3851. %% \end{lstlisting}
  3852. %% The reason for this non-optimal code has to do with the \code{flatten}
  3853. %% pass earlier in this Chapter. We recommended flattening the condition
  3854. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3855. %% is already an \code{eq?} test, then we would like to use that
  3856. %% directly. In fact, for many of the expressions of Boolean type, we can
  3857. %% generate more optimized code. For example, if the condition is
  3858. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3859. %% all. If the condition is a \code{let}, we can optimize based on the
  3860. %% form of its body. If the condition is a \code{not}, then we can flip
  3861. %% the two branches.
  3862. %% %
  3863. %% \margincomment{\tiny We could do even better by converting to basic
  3864. %% blocks.\\ --Jeremy}
  3865. %% %
  3866. %% On the other hand, if the condition is a \code{and}
  3867. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3868. %% code duplication.
  3869. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  3870. %% applying the above suggested optimizations.
  3871. %% \begin{exercise}\normalfont
  3872. %% Change the \code{flatten} pass to improve the code that gets
  3873. %% generated for \code{if} expressions. We recommend writing a helper
  3874. %% function that recursively traverses the condition of the \code{if}.
  3875. %% \end{exercise}
  3876. %% \begin{figure}[tbp]
  3877. %% \begin{tabular}{lll}
  3878. %% \begin{minipage}{0.5\textwidth}
  3879. %% \begin{lstlisting}
  3880. %% (program
  3881. %% (if (let ([x 1])
  3882. %% (not (eq? x (read))))
  3883. %% 777
  3884. %% 42))
  3885. %% \end{lstlisting}
  3886. %% $\Downarrow$
  3887. %% \begin{lstlisting}
  3888. %% (program (x.1 if.2 tmp.3)
  3889. %% (type Integer)
  3890. %% (assign x.1 1)
  3891. %% (assign tmp.3 (read))
  3892. %% (if (eq? x.1 tmp.3)
  3893. %% ((assign if.2 42))
  3894. %% ((assign if.2 777)))
  3895. %% (return if.2))
  3896. %% \end{lstlisting}
  3897. %% $\Downarrow$
  3898. %% \begin{lstlisting}
  3899. %% (program (x.1 if.2 tmp.3)
  3900. %% (type Integer)
  3901. %% (movq (int 1) (var x.1))
  3902. %% (callq read_int)
  3903. %% (movq (reg rax) (var tmp.3))
  3904. %% (if (eq? (var x.1) (var tmp.3))
  3905. %% ((movq (int 42) (var if.2)))
  3906. %% ((movq (int 777) (var if.2))))
  3907. %% (movq (var if.2) (reg rax)))
  3908. %% \end{lstlisting}
  3909. %% \end{minipage}
  3910. %% &
  3911. %% $\Rightarrow$
  3912. %% \begin{minipage}{0.4\textwidth}
  3913. %% \begin{lstlisting}
  3914. %% .globl _main
  3915. %% _main:
  3916. %% pushq %rbp
  3917. %% movq %rsp, %rbp
  3918. %% pushq %r13
  3919. %% pushq %r14
  3920. %% pushq %r12
  3921. %% pushq %rbx
  3922. %% subq $0, %rsp
  3923. %% movq $1, %rbx
  3924. %% callq _read_int
  3925. %% movq %rax, %rcx
  3926. %% cmpq %rcx, %rbx
  3927. %% je then35989
  3928. %% movq $777, %rbx
  3929. %% jmp if_end35990
  3930. %% then35989:
  3931. %% movq $42, %rbx
  3932. %% if_end35990:
  3933. %% movq %rbx, %rax
  3934. %% movq %rax, %rdi
  3935. %% callq _print_int
  3936. %% movq $0, %rax
  3937. %% addq $0, %rsp
  3938. %% popq %rbx
  3939. %% popq %r12
  3940. %% popq %r14
  3941. %% popq %r13
  3942. %% popq %rbp
  3943. %% retq
  3944. %% \end{lstlisting}
  3945. %% \end{minipage}
  3946. %% \end{tabular}
  3947. %% \caption{Example program with optimized conditionals.}
  3948. %% \label{fig:opt-if}
  3949. %% \end{figure}
  3950. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3951. \chapter{Tuples and Garbage Collection}
  3952. \label{ch:tuples}
  3953. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3954. things to discuss in this chapter. \\ --Jeremy}
  3955. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3956. all the IR grammars are spelled out! \\ --Jeremy}
  3957. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3958. but keep type annotations on vector creation and local variables, function
  3959. parameters, etc. \\ --Jeremy}
  3960. \margincomment{\scriptsize Be more explicit about how to deal with
  3961. the root stack. \\ --Jeremy}
  3962. In this chapter we study the implementation of mutable tuples (called
  3963. ``vectors'' in Racket). This language feature is the first to use the
  3964. computer's \emph{heap} because the lifetime of a Racket tuple is
  3965. indefinite, that is, a tuple lives forever from the programmer's
  3966. viewpoint. Of course, from an implementor's viewpoint, it is important
  3967. to reclaim the space associated with a tuple when it is no longer
  3968. needed, which is why we also study \emph{garbage collection}
  3969. techniques in this chapter.
  3970. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3971. interpreter and type checker. The $R_3$ language extends the $R_2$
  3972. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  3973. ``void'' value. The reason for including the later is that the
  3974. \code{vector-set!} operation returns a value of type
  3975. \code{Void}\footnote{This may sound contradictory, but Racket's
  3976. \code{Void} type corresponds to what is more commonly called the
  3977. \code{Unit} type. This type is inhabited by a single value that is
  3978. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  3979. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  3980. copying live objects back and forth between two halves of the
  3981. heap. The garbage collector requires coordination with the compiler so
  3982. that it can see all of the \emph{root} pointers, that is, pointers in
  3983. registers or on the procedure call stack.
  3984. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  3985. discuss all the necessary changes and additions to the compiler
  3986. passes, including a new compiler pass named \code{expose-allocation}.
  3987. \section{The $R_3$ Language}
  3988. \label{sec:r3}
  3989. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3990. includes three new forms for creating a tuple, reading an element of a
  3991. tuple, and writing to an element of a tuple. The program in
  3992. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3993. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3994. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3995. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3996. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3997. $40$, to which we add the $2$, the element at index $0$ of the
  3998. 1-tuple.
  3999. \begin{figure}[tbp]
  4000. \begin{lstlisting}
  4001. (let ([t (vector 40 #t (vector 2))])
  4002. (if (vector-ref t 1)
  4003. (+ (vector-ref t 0)
  4004. (vector-ref (vector-ref t 2) 0))
  4005. 44))
  4006. \end{lstlisting}
  4007. \caption{Example program that creates tuples and reads from them.}
  4008. \label{fig:vector-eg}
  4009. \end{figure}
  4010. \begin{figure}[tbp]
  4011. \centering
  4012. \fbox{
  4013. \begin{minipage}{0.96\textwidth}
  4014. \[
  4015. \begin{array}{lcl}
  4016. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4017. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4018. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4019. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4020. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4021. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4022. \mid (\key{and}\;\Exp\;\Exp)
  4023. \mid (\key{or}\;\Exp\;\Exp)
  4024. \mid (\key{not}\;\Exp) } \\
  4025. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4026. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4027. &\mid& (\key{vector}\;\Exp^{+})
  4028. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4029. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4030. &\mid& (\key{void}) \\
  4031. R_3 &::=& (\key{program} \; \Exp)
  4032. \end{array}
  4033. \]
  4034. \end{minipage}
  4035. }
  4036. \caption{The syntax of $R_3$, extending $R_2$
  4037. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4038. \label{fig:r3-syntax}
  4039. \end{figure}
  4040. Tuples are our first encounter with heap-allocated data, which raises
  4041. several interesting issues. First, variable binding performs a
  4042. shallow-copy when dealing with tuples, which means that different
  4043. variables can refer to the same tuple, i.e., different variables can
  4044. be \emph{aliases} for the same thing. Consider the following example
  4045. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4046. the mutation through \code{t2} is visible when referencing the tuple
  4047. from \code{t1}, so the result of this program is \code{42}.
  4048. \begin{lstlisting}
  4049. (let ([t1 (vector 3 7)])
  4050. (let ([t2 t1])
  4051. (let ([_ (vector-set! t2 0 42)])
  4052. (vector-ref t1 0))))
  4053. \end{lstlisting}
  4054. The next issue concerns the lifetime of tuples. Of course, they are
  4055. created by the \code{vector} form, but when does their lifetime end?
  4056. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4057. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4058. is not tied to any notion of static scoping. For example, the
  4059. following program returns \code{3} even though the variable \code{t}
  4060. goes out of scope prior to accessing the vector.
  4061. \begin{lstlisting}
  4062. (vector-ref
  4063. (let ([t (vector 3 7)])
  4064. t)
  4065. 0)
  4066. \end{lstlisting}
  4067. From the perspective of programmer-observable behavior, tuples live
  4068. forever. Of course, if they really lived forever, then many programs
  4069. would run out of memory.\footnote{The $R_3$ language does not have
  4070. looping or recursive function, so it is nigh impossible to write a
  4071. program in $R_3$ that will run out of memory. However, we add
  4072. recursive functions in the next Chapter!} A Racket implementation
  4073. must therefore perform automatic garbage collection.
  4074. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4075. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  4076. checker. The additions to the interpreter are straightforward but the
  4077. updates to the type checker deserve some explanation. As we shall see
  4078. in Section~\ref{sec:GC}, we need to know which variables are pointers
  4079. into the heap, that is, which variables are vectors. Also, when
  4080. allocating a vector, we shall need to know which elements of the
  4081. vector are pointers. We can obtain this information during type
  4082. checking and when we uncover local variables. The type checker in
  4083. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4084. expression, it also wraps every sub-expression $e$ with the form
  4085. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  4086. the \code{uncover-locals} pass (Section~\ref{sec:uncover-locals-r3})
  4087. this type information is propagated to all variables (including the
  4088. temporaries generated by \code{remove-complex-opera*}).
  4089. \begin{figure}[tbp]
  4090. \begin{lstlisting}
  4091. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4092. (define (interp-op op)
  4093. (match op
  4094. ...
  4095. ['vector vector]
  4096. ['vector-ref vector-ref]
  4097. ['vector-set! vector-set!]
  4098. [else (error 'interp-op "unknown operator")]))
  4099. (define (interp-R3 env)
  4100. (lambda (e)
  4101. (match e
  4102. ...
  4103. [else (error 'interp-R3 "unrecognized expression")]
  4104. )))
  4105. \end{lstlisting}
  4106. \caption{Interpreter for the $R_3$ language.}
  4107. \label{fig:interp-R3}
  4108. \end{figure}
  4109. \begin{figure}[tbp]
  4110. \begin{lstlisting}
  4111. (define (type-check-exp env)
  4112. (lambda (e)
  4113. (define recur (type-check-exp env))
  4114. (match e
  4115. ...
  4116. ['(void) (values '(has-type (void) Void) 'Void)]
  4117. [`(vector ,es ...)
  4118. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4119. (recur e)))
  4120. (let ([t `(Vector ,@t*)])
  4121. (debug "vector/type-check-exp finished vector" t)
  4122. (values `(has-type (vector ,@e*) ,t) t))]
  4123. [`(vector-ref ,e ,i)
  4124. (define-values (e^ t) (recur e))
  4125. (match t
  4126. [`(Vector ,ts ...)
  4127. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4128. (error 'type-check-exp "invalid index ~a" i))
  4129. (let ([t (list-ref ts i)])
  4130. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4131. t))]
  4132. [else (error "expected a vector in vector-ref, not" t)])]
  4133. [`(eq? ,arg1 ,arg2)
  4134. (define-values (e1 t1) (recur arg1))
  4135. (define-values (e2 t2) (recur arg2))
  4136. (match* (t1 t2)
  4137. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4138. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4139. [(other wise) ((super type-check-exp env) e)])]
  4140. ...
  4141. )))
  4142. \end{lstlisting}
  4143. \caption{Type checker for the $R_3$ language.}
  4144. \label{fig:typecheck-R3}
  4145. \end{figure}
  4146. \section{Garbage Collection}
  4147. \label{sec:GC}
  4148. Here we study a relatively simple algorithm for garbage collection
  4149. that is the basis of state-of-the-art garbage
  4150. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4151. particular, we describe a two-space copying
  4152. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4153. perform the
  4154. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4155. coarse-grained depiction of what happens in a two-space collector,
  4156. showing two time steps, prior to garbage collection on the top and
  4157. after garbage collection on the bottom. In a two-space collector, the
  4158. heap is divided into two parts, the FromSpace and the
  4159. ToSpace. Initially, all allocations go to the FromSpace until there is
  4160. not enough room for the next allocation request. At that point, the
  4161. garbage collector goes to work to make more room.
  4162. The garbage collector must be careful not to reclaim tuples that will
  4163. be used by the program in the future. Of course, it is impossible in
  4164. general to predict what a program will do, but we can overapproximate
  4165. the will-be-used tuples by preserving all tuples that could be
  4166. accessed by \emph{any} program given the current computer state. A
  4167. program could access any tuple whose address is in a register or on
  4168. the procedure call stack. These addresses are called the \emph{root
  4169. set}. In addition, a program could access any tuple that is
  4170. transitively reachable from the root set. Thus, it is safe for the
  4171. garbage collector to reclaim the tuples that are not reachable in this
  4172. way.
  4173. So the goal of the garbage collector is twofold:
  4174. \begin{enumerate}
  4175. \item preserve all tuple that are reachable from the root set via a
  4176. path of pointers, that is, the \emph{live} tuples, and
  4177. \item reclaim the memory of everything else, that is, the
  4178. \emph{garbage}.
  4179. \end{enumerate}
  4180. A copying collector accomplishes this by copying all of the live
  4181. objects from the FromSpace into the ToSpace and then performs a slight
  4182. of hand, treating the ToSpace as the new FromSpace and the old
  4183. FromSpace as the new ToSpace. In the example of
  4184. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4185. root set, one in a register and two on the stack. All of the live
  4186. objects have been copied to the ToSpace (the right-hand side of
  4187. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4188. pointer relationships. For example, the pointer in the register still
  4189. points to a 2-tuple whose first element is a 3-tuple and second
  4190. element is a 2-tuple. There are four tuples that are not reachable
  4191. from the root set and therefore do not get copied into the ToSpace.
  4192. (The sitation in Figure~\ref{fig:copying-collector}, with a
  4193. cycle, cannot be created by a well-typed program in $R_3$. However,
  4194. creating cycles will be possible once we get to $R_6$. We design
  4195. the garbage collector to deal with cycles to begin with, so we will
  4196. not need to revisit this issue.)
  4197. \begin{figure}[tbp]
  4198. \centering
  4199. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4200. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4201. \caption{A copying collector in action.}
  4202. \label{fig:copying-collector}
  4203. \end{figure}
  4204. There are many alternatives to copying collectors (and their older
  4205. siblings, the generational collectors) when its comes to garbage
  4206. collection, such as mark-and-sweep and reference counting. The
  4207. strengths of copying collectors are that allocation is fast (just a
  4208. test and pointer increment), there is no fragmentation, cyclic garbage
  4209. is collected, and the time complexity of collection only depends on
  4210. the amount of live data, and not on the amount of
  4211. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4212. copying collectors is that they use a lot of space, though that
  4213. problem is ameliorated in generational collectors. Racket and Scheme
  4214. programs tend to allocate many small objects and generate a lot of
  4215. garbage, so copying and generational collectors are a good fit. Of
  4216. course, garbage collection is an active research topic, especially
  4217. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4218. continuously developing new techniques and revisiting old
  4219. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4220. \subsection{Graph Copying via Cheney's Algorithm}
  4221. \label{sec:cheney}
  4222. Let us take a closer look at how the copy works. The allocated objects
  4223. and pointers can be viewed as a graph and we need to copy the part of
  4224. the graph that is reachable from the root set. To make sure we copy
  4225. all of the reachable vertices in the graph, we need an exhaustive
  4226. graph traversal algorithm, such as depth-first search or breadth-first
  4227. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4228. take into account the possibility of cycles by marking which vertices
  4229. have already been visited, so as to ensure termination of the
  4230. algorithm. These search algorithms also use a data structure such as a
  4231. stack or queue as a to-do list to keep track of the vertices that need
  4232. to be visited. We shall use breadth-first search and a trick due to
  4233. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4234. copying tuples into the ToSpace.
  4235. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4236. copy progresses. The queue is represented by a chunk of contiguous
  4237. memory at the beginning of the ToSpace, using two pointers to track
  4238. the front and the back of the queue. The algorithm starts by copying
  4239. all tuples that are immediately reachable from the root set into the
  4240. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4241. old tuple to indicate that it has been visited. (We discuss the
  4242. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4243. inside the copied tuples in the queue still point back to the
  4244. FromSpace. Once the initial queue has been created, the algorithm
  4245. enters a loop in which it repeatedly processes the tuple at the front
  4246. of the queue and pops it off the queue. To process a tuple, the
  4247. algorithm copies all the tuple that are directly reachable from it to
  4248. the ToSpace, placing them at the back of the queue. The algorithm then
  4249. updates the pointers in the popped tuple so they point to the newly
  4250. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4251. step we copy the tuple whose second element is $42$ to the back of the
  4252. queue. The other pointer goes to a tuple that has already been copied,
  4253. so we do not need to copy it again, but we do need to update the
  4254. pointer to the new location. This can be accomplished by storing a
  4255. \emph{forwarding} pointer to the new location in the old tuple, back
  4256. when we initially copied the tuple into the ToSpace. This completes
  4257. one step of the algorithm. The algorithm continues in this way until
  4258. the front of the queue is empty, that is, until the front catches up
  4259. with the back.
  4260. \begin{figure}[tbp]
  4261. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4262. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4263. \label{fig:cheney}
  4264. \end{figure}
  4265. \subsection{Data Representation}
  4266. \label{sec:data-rep-gc}
  4267. The garbage collector places some requirements on the data
  4268. representations used by our compiler. First, the garbage collector
  4269. needs to distinguish between pointers and other kinds of data. There
  4270. are several ways to accomplish this.
  4271. \begin{enumerate}
  4272. \item Attached a tag to each object that identifies what type of
  4273. object it is~\citep{McCarthy:1960dz}.
  4274. \item Store different types of objects in different
  4275. regions~\citep{Steele:1977ab}.
  4276. \item Use type information from the program to either generate
  4277. type-specific code for collecting or to generate tables that can
  4278. guide the
  4279. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4280. \end{enumerate}
  4281. Dynamically typed languages, such as Lisp, need to tag objects
  4282. anyways, so option 1 is a natural choice for those languages.
  4283. However, $R_3$ is a statically typed language, so it would be
  4284. unfortunate to require tags on every object, especially small and
  4285. pervasive objects like integers and Booleans. Option 3 is the
  4286. best-performing choice for statically typed languages, but comes with
  4287. a relatively high implementation complexity. To keep this chapter to a
  4288. 2-week time budget, we recommend a combination of options 1 and 2,
  4289. with separate strategies used for the stack and the heap.
  4290. Regarding the stack, we recommend using a separate stack for
  4291. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4292. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4293. local variable needs to be spilled and is of type \code{(Vector
  4294. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4295. of the normal procedure call stack. Furthermore, we always spill
  4296. vector-typed variables if they are live during a call to the
  4297. collector, thereby ensuring that no pointers are in registers during a
  4298. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4299. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4300. layout using a root stack. The root stack contains the two pointers
  4301. from the regular stack and also the pointer in the second
  4302. register.
  4303. \begin{figure}[tbp]
  4304. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4305. \caption{Maintaining a root stack to facilitate garbage collection.}
  4306. \label{fig:shadow-stack}
  4307. \end{figure}
  4308. The problem of distinguishing between pointers and other kinds of data
  4309. also arises inside of each tuple. We solve this problem by attaching a
  4310. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4311. in on the tags for two of the tuples in the example from
  4312. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4313. in a big-endian way, from right-to-left, with bit location 0 (the
  4314. least significant bit) on the far right, which corresponds to the
  4315. directionality of the x86 shifting instructions \key{salq} (shift
  4316. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4317. specifying which elements of the tuple are pointers, the part labeled
  4318. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4319. a pointer and a 0 bit indicates some other kind of data. The pointer
  4320. mask starts at bit location 7. We have limited tuples to a maximum
  4321. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4322. tag also contains two other pieces of information. The length of the
  4323. tuple (number of elements) is stored in bits location 1 through
  4324. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4325. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4326. has not yet been copied. If the bit has value 0 then the entire tag
  4327. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4328. always zero anyways because our tuples are 8-byte aligned.)
  4329. \begin{figure}[tbp]
  4330. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4331. \caption{Representation for tuples in the heap.}
  4332. \label{fig:tuple-rep}
  4333. \end{figure}
  4334. \subsection{Implementation of the Garbage Collector}
  4335. \label{sec:organize-gz}
  4336. The implementation of the garbage collector needs to do a lot of
  4337. bit-level data manipulation and we need to link it with our
  4338. compiler-generated x86 code. Thus, we recommend implementing the
  4339. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4340. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4341. interface to the garbage collector. The \code{initialize} function
  4342. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4343. function is meant to be called near the beginning of \code{main},
  4344. before the rest of the program executes. The \code{initialize}
  4345. function puts the address of the beginning of the FromSpace into the
  4346. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4347. points to the address that is 1-past the last element of the
  4348. FromSpace. (We use half-open intervals to represent chunks of
  4349. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4350. points to the first element of the root stack.
  4351. As long as there is room left in the FromSpace, your generated code
  4352. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4353. %
  4354. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4355. --Jeremy}
  4356. %
  4357. The amount of room left in FromSpace is the difference between the
  4358. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4359. function should be called when there is not enough room left in the
  4360. FromSpace for the next allocation. The \code{collect} function takes
  4361. a pointer to the current top of the root stack (one past the last item
  4362. that was pushed) and the number of bytes that need to be
  4363. allocated. The \code{collect} function performs the copying collection
  4364. and leaves the heap in a state such that the next allocation will
  4365. succeed.
  4366. \begin{figure}[tbp]
  4367. \begin{lstlisting}
  4368. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4369. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4370. int64_t* free_ptr;
  4371. int64_t* fromspace_begin;
  4372. int64_t* fromspace_end;
  4373. int64_t** rootstack_begin;
  4374. \end{lstlisting}
  4375. \caption{The compiler's interface to the garbage collector.}
  4376. \label{fig:gc-header}
  4377. \end{figure}
  4378. \begin{exercise}
  4379. In the file \code{runtime.c} you will find the implementation of
  4380. \code{initialize} and a partial implementation of \code{collect}.
  4381. The \code{collect} function calls another function, \code{cheney},
  4382. to perform the actual copy, and that function is left to the reader
  4383. to implement. The following is the prototype for \code{cheney}.
  4384. \begin{lstlisting}
  4385. static void cheney(int64_t** rootstack_ptr);
  4386. \end{lstlisting}
  4387. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4388. rootstack (which is an array of pointers). The \code{cheney} function
  4389. also communicates with \code{collect} through the global
  4390. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4391. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4392. the ToSpace:
  4393. \begin{lstlisting}
  4394. static int64_t* tospace_begin;
  4395. static int64_t* tospace_end;
  4396. \end{lstlisting}
  4397. The job of the \code{cheney} function is to copy all the live
  4398. objects (reachable from the root stack) into the ToSpace, update
  4399. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4400. update the root stack so that it points to the objects in the
  4401. ToSpace, and finally to swap the global pointers for the FromSpace
  4402. and ToSpace.
  4403. \end{exercise}
  4404. %% \section{Compiler Passes}
  4405. %% \label{sec:code-generation-gc}
  4406. The introduction of garbage collection has a non-trivial impact on our
  4407. compiler passes. We introduce one new compiler pass called
  4408. \code{expose-allocation} and make non-trivial changes to
  4409. \code{type-check}, \code{flatten}, \code{select-instructions},
  4410. \code{allocate-registers}, and \code{print-x86}. The following
  4411. program will serve as our running example. It creates two tuples, one
  4412. nested inside the other. Both tuples have length one. The example then
  4413. accesses the element in the inner tuple tuple via two vector
  4414. references.
  4415. % tests/s2_17.rkt
  4416. \begin{lstlisting}
  4417. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4418. \end{lstlisting}
  4419. Next we proceed to discuss the new \code{expose-allocation} pass.
  4420. \section{Expose Allocation}
  4421. \label{sec:expose-allocation}
  4422. The pass \code{expose-allocation} lowers the \code{vector} creation
  4423. form into a conditional call to the collector followed by the
  4424. allocation. We choose to place the \code{expose-allocation} pass
  4425. before \code{flatten} because \code{expose-allocation} introduces new
  4426. variables, which can be done locally with \code{let}, but \code{let}
  4427. is gone after \code{flatten}. In the following, we show the
  4428. transformation for the \code{vector} form into let-bindings for the
  4429. intializing expressions, by a conditional \code{collect}, an
  4430. \code{allocate}, and the initialization of the vector.
  4431. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4432. total bytes need to be allocated for the vector, which is 8 for the
  4433. tag plus \itm{len} times 8.)
  4434. \begin{lstlisting}
  4435. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4436. |$\Longrightarrow$|
  4437. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4438. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4439. (global-value fromspace_end))
  4440. (void)
  4441. (collect |\itm{bytes}|))])
  4442. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4443. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4444. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4445. |$v$|) ... )))) ...)
  4446. \end{lstlisting}
  4447. (In the above, we suppressed all of the \code{has-type} forms in the
  4448. output for the sake of readability.) The placement of the initializing
  4449. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4450. the sequence of \code{vector-set!}'s is important, as those expressions
  4451. may trigger garbage collection and we do not want an allocated but
  4452. uninitialized tuple to be present during a garbage collection.
  4453. The output of \code{expose-allocation} is a language that extends
  4454. $R_3$ with the three new forms that we use above in the translation of
  4455. \code{vector}.
  4456. \[
  4457. \begin{array}{lcl}
  4458. \Exp &::=& \cdots
  4459. \mid (\key{collect} \,\itm{int})
  4460. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4461. \mid (\key{global-value} \,\itm{name})
  4462. \end{array}
  4463. \]
  4464. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4465. %% the beginning of the program which will instruct the garbage collector
  4466. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4467. %% two arguments of \code{initialize} specify the initial allocated space
  4468. %% for the root stack and for the heap.
  4469. %
  4470. %% The \code{expose-allocation} pass annotates all of the local variables
  4471. %% in the \code{program} form with their type.
  4472. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4473. \code{expose-allocation} pass on our running example.
  4474. \begin{figure}[tbp]
  4475. \begin{lstlisting}
  4476. (program ()
  4477. (vector-ref
  4478. (vector-ref
  4479. (let ((vecinit48
  4480. (let ((vecinit44 42))
  4481. (let ((collectret46
  4482. (if (<
  4483. (+ (global-value free_ptr) 16)
  4484. (global-value fromspace_end))
  4485. (void)
  4486. (collect 16))))
  4487. (let ((alloc43 (allocate 1 (Vector Integer))))
  4488. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4489. alloc43))))))
  4490. (let ((collectret50
  4491. (if (< (+ (global-value free_ptr) 16)
  4492. (global-value fromspace_end))
  4493. (void)
  4494. (collect 16))))
  4495. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4496. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4497. alloc47))))
  4498. 0)
  4499. 0))
  4500. \end{lstlisting}
  4501. \caption{Output of the \code{expose-allocation} pass, minus
  4502. all of the \code{has-type} forms.}
  4503. \label{fig:expose-alloc-output}
  4504. \end{figure}
  4505. %\clearpage
  4506. \section{Explicate Control and the $C_2$ language}
  4507. \label{sec:explicate-control-r3}
  4508. \begin{figure}[tp]
  4509. \fbox{
  4510. \begin{minipage}{0.96\textwidth}
  4511. \[
  4512. \begin{array}{lcl}
  4513. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4514. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4515. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4516. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4517. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4518. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4519. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4520. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4521. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4522. \mid (\key{collect} \,\itm{int}) \\
  4523. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4524. &\mid& \gray{(\key{goto}\,\itm{label})
  4525. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4526. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4527. \end{array}
  4528. \]
  4529. \end{minipage}
  4530. }
  4531. \caption{The $C_2$ language, extending $C_1$
  4532. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4533. \label{fig:c2-syntax}
  4534. \end{figure}
  4535. The output of \code{explicate-control} is a program in the
  4536. intermediate language $C_2$, whose syntax is defined in
  4537. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4538. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4539. \key{global-value} expressions and the \code{collect} statement. The
  4540. \code{explicate-control} pass can treat these new forms much like the
  4541. other forms.
  4542. \section{Uncover Locals}
  4543. \label{sec:uncover-locals-r3}
  4544. Recall that the \code{uncover-locals} function collects all of the
  4545. local variables so that it can store them in the $\itm{info}$ field of
  4546. the \code{program} form. Also recall that we need to know the types of
  4547. all the local variables for purposes of identifying the root set for
  4548. the garbage collector. Thus, we change \code{uncover-locals} to
  4549. collect not just the variables, but the variables and their types in
  4550. the form of an association list. Thanks to the \code{has-type} forms,
  4551. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4552. lists the output of the \code{uncover-locals} pass on the running
  4553. example.
  4554. \begin{figure}[tbp]
  4555. \begin{lstlisting}
  4556. (program
  4557. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4558. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4559. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4560. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4561. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4562. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4563. (collectret50 . Void))))
  4564. ((block63 . (seq (collect 16) (goto block61)))
  4565. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4566. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4567. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4568. (seq (assign vecinit48 alloc43)
  4569. (seq (assign tmp54 (global-value free_ptr))
  4570. (seq (assign tmp55 (+ tmp54 16))
  4571. (seq (assign tmp56 (global-value fromspace_end))
  4572. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4573. (block60 . (seq (collect 16) (goto block58)))
  4574. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4575. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4576. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4577. (seq (assign tmp57 (vector-ref alloc47 0))
  4578. (return (vector-ref tmp57 0))))))
  4579. (start . (seq (assign vecinit44 42)
  4580. (seq (assign tmp51 (global-value free_ptr))
  4581. (seq (assign tmp52 (+ tmp51 16))
  4582. (seq (assign tmp53 (global-value fromspace_end))
  4583. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4584. \end{lstlisting}
  4585. \caption{Output of \code{uncover-locals} for the running example.}
  4586. \label{fig:uncover-locals-r3}
  4587. \end{figure}
  4588. \clearpage
  4589. \section{Select Instructions}
  4590. \label{sec:select-instructions-gc}
  4591. %% void (rep as zero)
  4592. %% allocate
  4593. %% collect (callq collect)
  4594. %% vector-ref
  4595. %% vector-set!
  4596. %% global-value (postpone)
  4597. In this pass we generate x86 code for most of the new operations that
  4598. were needed to compile tuples, including \code{allocate},
  4599. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4600. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4601. The \code{vector-ref} and \code{vector-set!} forms translate into
  4602. \code{movq} instructions with the appropriate \key{deref}. (The
  4603. plus one is to get past the tag at the beginning of the tuple
  4604. representation.)
  4605. \begin{lstlisting}
  4606. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4607. |$\Longrightarrow$|
  4608. (movq |$\itm{vec}'$| (reg r11))
  4609. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4610. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4611. |$\Longrightarrow$|
  4612. (movq |$\itm{vec}'$| (reg r11))
  4613. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4614. (movq (int 0) |$\itm{lhs}$|)
  4615. \end{lstlisting}
  4616. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4617. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4618. register \code{r11} ensures that offsets are only performed with
  4619. register operands. This requires removing \code{r11} from
  4620. consideration by the register allocating.
  4621. We compile the \code{allocate} form to operations on the
  4622. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4623. is the next free address in the FromSpace, so we move it into the
  4624. \itm{lhs} and then move it forward by enough space for the tuple being
  4625. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4626. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4627. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4628. how the tag is organized. We recommend using the Racket operations
  4629. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4630. The type annoation in the \code{vector} form is used to determine the
  4631. pointer mask region of the tag.
  4632. \begin{lstlisting}
  4633. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4634. |$\Longrightarrow$|
  4635. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4636. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4637. (movq |$\itm{lhs}'$| (reg r11))
  4638. (movq (int |$\itm{tag}$|) (deref r11 0))
  4639. \end{lstlisting}
  4640. The \code{collect} form is compiled to a call to the \code{collect}
  4641. function in the runtime. The arguments to \code{collect} are the top
  4642. of the root stack and the number of bytes that need to be allocated.
  4643. We shall use a dedicated register, \code{r15}, to store the pointer to
  4644. the top of the root stack. So \code{r15} is not available for use by
  4645. the register allocator.
  4646. \begin{lstlisting}
  4647. (collect |$\itm{bytes}$|)
  4648. |$\Longrightarrow$|
  4649. (movq (reg r15) (reg rdi))
  4650. (movq |\itm{bytes}| (reg rsi))
  4651. (callq collect)
  4652. \end{lstlisting}
  4653. \begin{figure}[tp]
  4654. \fbox{
  4655. \begin{minipage}{0.96\textwidth}
  4656. \[
  4657. \begin{array}{lcl}
  4658. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4659. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4660. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4661. \mid (\key{global-value}\; \itm{name}) \\
  4662. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4663. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4664. (\key{subq} \; \Arg\; \Arg) \mid
  4665. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4666. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4667. (\key{pushq}\;\Arg) \mid
  4668. (\key{popq}\;\Arg) \mid
  4669. (\key{retq})} \\
  4670. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4671. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4672. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4673. \mid (\key{jmp} \; \itm{label})
  4674. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4675. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4676. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4677. \end{array}
  4678. \]
  4679. \end{minipage}
  4680. }
  4681. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4682. \label{fig:x86-2}
  4683. \end{figure}
  4684. The syntax of the $x86_2$ language is defined in
  4685. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4686. of the form for global variables.
  4687. %
  4688. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4689. \code{select-instructions} pass on the running example.
  4690. \begin{figure}[tbp]
  4691. \centering
  4692. \begin{minipage}{0.75\textwidth}
  4693. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4694. (program
  4695. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4696. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4697. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4698. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4699. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4700. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4701. ((block63 . (block ()
  4702. (movq (reg r15) (reg rdi))
  4703. (movq (int 16) (reg rsi))
  4704. (callq collect)
  4705. (jmp block61)))
  4706. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4707. (block61 . (block ()
  4708. (movq (global-value free_ptr) (var alloc43))
  4709. (addq (int 16) (global-value free_ptr))
  4710. (movq (var alloc43) (reg r11))
  4711. (movq (int 3) (deref r11 0))
  4712. (movq (var alloc43) (reg r11))
  4713. (movq (var vecinit44) (deref r11 8))
  4714. (movq (int 0) (var initret45))
  4715. (movq (var alloc43) (var vecinit48))
  4716. (movq (global-value free_ptr) (var tmp54))
  4717. (movq (var tmp54) (var tmp55))
  4718. (addq (int 16) (var tmp55))
  4719. (movq (global-value fromspace_end) (var tmp56))
  4720. (cmpq (var tmp56) (var tmp55))
  4721. (jmp-if l block59)
  4722. (jmp block60)))
  4723. (block60 . (block ()
  4724. (movq (reg r15) (reg rdi))
  4725. (movq (int 16) (reg rsi))
  4726. (callq collect)
  4727. (jmp block58))
  4728. (block59 . (block ()
  4729. (movq (int 0) (var collectret50))
  4730. (jmp block58)))
  4731. (block58 . (block ()
  4732. (movq (global-value free_ptr) (var alloc47))
  4733. (addq (int 16) (global-value free_ptr))
  4734. (movq (var alloc47) (reg r11))
  4735. (movq (int 131) (deref r11 0))
  4736. (movq (var alloc47) (reg r11))
  4737. (movq (var vecinit48) (deref r11 8))
  4738. (movq (int 0) (var initret49))
  4739. (movq (var alloc47) (reg r11))
  4740. (movq (deref r11 8) (var tmp57))
  4741. (movq (var tmp57) (reg r11))
  4742. (movq (deref r11 8) (reg rax))
  4743. (jmp conclusion)))
  4744. (start . (block ()
  4745. (movq (int 42) (var vecinit44))
  4746. (movq (global-value free_ptr) (var tmp51))
  4747. (movq (var tmp51) (var tmp52))
  4748. (addq (int 16) (var tmp52))
  4749. (movq (global-value fromspace_end) (var tmp53))
  4750. (cmpq (var tmp53) (var tmp52))
  4751. (jmp-if l block62)
  4752. (jmp block63))))))
  4753. \end{lstlisting}
  4754. \end{minipage}
  4755. \caption{Output of the \code{select-instructions} pass.}
  4756. \label{fig:select-instr-output-gc}
  4757. \end{figure}
  4758. \clearpage
  4759. \section{Register Allocation}
  4760. \label{sec:reg-alloc-gc}
  4761. As discussed earlier in this chapter, the garbage collector needs to
  4762. access all the pointers in the root set, that is, all variables that
  4763. are vectors. It will be the responsibility of the register allocator
  4764. to make sure that:
  4765. \begin{enumerate}
  4766. \item the root stack is used for spilling vector-typed variables, and
  4767. \item if a vector-typed variable is live during a call to the
  4768. collector, it must be spilled to ensure it is visible to the
  4769. collector.
  4770. \end{enumerate}
  4771. The later responsibility can be handled during construction of the
  4772. inference graph, by adding interference edges between the call-live
  4773. vector-typed variables and all the callee-saved registers. (They
  4774. already interfere with the caller-saved registers.) The type
  4775. information for variables is in the \code{program} form, so we
  4776. recommend adding another parameter to the \code{build-interference}
  4777. function to communicate this association list.
  4778. The spilling of vector-typed variables to the root stack can be
  4779. handled after graph coloring, when choosing how to assign the colors
  4780. (integers) to registers and stack locations. The \code{program} output
  4781. of this pass changes to also record the number of spills to the root
  4782. stack.
  4783. % build-interference
  4784. %
  4785. % callq
  4786. % extra parameter for var->type assoc. list
  4787. % update 'program' and 'if'
  4788. % allocate-registers
  4789. % allocate spilled vectors to the rootstack
  4790. % don't change color-graph
  4791. \section{Print x86}
  4792. \label{sec:print-x86-gc}
  4793. \margincomment{\scriptsize We need to show the translation to x86 and what
  4794. to do about global-value. \\ --Jeremy}
  4795. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4796. \code{print-x86} pass on the running example. In the prelude and
  4797. conclusion of the \code{main} function, we treat the root stack very
  4798. much like the regular stack in that we move the root stack pointer
  4799. (\code{r15}) to make room for all of the spills to the root stack,
  4800. except that the root stack grows up instead of down. For the running
  4801. example, there was just one spill so we increment \code{r15} by 8
  4802. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4803. One issue that deserves special care is that there may be a call to
  4804. \code{collect} prior to the initializing assignments for all the
  4805. variables in the root stack. We do not want the garbage collector to
  4806. accidentaly think that some uninitialized variable is a pointer that
  4807. needs to be followed. Thus, we zero-out all locations on the root
  4808. stack in the prelude of \code{main}. In
  4809. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4810. %
  4811. \lstinline{movq $0, (%r15)}
  4812. %
  4813. accomplishes this task. The garbage collector tests each root to see
  4814. if it is null prior to dereferencing it.
  4815. \begin{figure}[htbp]
  4816. \begin{minipage}[t]{0.5\textwidth}
  4817. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4818. _block58:
  4819. movq _free_ptr(%rip), %rcx
  4820. addq $16, _free_ptr(%rip)
  4821. movq %rcx, %r11
  4822. movq $131, 0(%r11)
  4823. movq %rcx, %r11
  4824. movq -8(%r15), %rax
  4825. movq %rax, 8(%r11)
  4826. movq $0, %rdx
  4827. movq %rcx, %r11
  4828. movq 8(%r11), %rcx
  4829. movq %rcx, %r11
  4830. movq 8(%r11), %rax
  4831. jmp _conclusion
  4832. _block59:
  4833. movq $0, %rcx
  4834. jmp _block58
  4835. _block62:
  4836. movq $0, %rcx
  4837. jmp _block61
  4838. _block60:
  4839. movq %r15, %rdi
  4840. movq $16, %rsi
  4841. callq _collect
  4842. jmp _block58
  4843. _block63:
  4844. movq %r15, %rdi
  4845. movq $16, %rsi
  4846. callq _collect
  4847. jmp _block61
  4848. _start:
  4849. movq $42, %rbx
  4850. movq _free_ptr(%rip), %rdx
  4851. addq $16, %rdx
  4852. movq _fromspace_end(%rip), %rcx
  4853. cmpq %rcx, %rdx
  4854. jl _block62
  4855. jmp _block63
  4856. \end{lstlisting}
  4857. \end{minipage}
  4858. \begin{minipage}[t]{0.45\textwidth}
  4859. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4860. _block61:
  4861. movq _free_ptr(%rip), %rcx
  4862. addq $16, _free_ptr(%rip)
  4863. movq %rcx, %r11
  4864. movq $3, 0(%r11)
  4865. movq %rcx, %r11
  4866. movq %rbx, 8(%r11)
  4867. movq $0, %rdx
  4868. movq %rcx, -8(%r15)
  4869. movq _free_ptr(%rip), %rcx
  4870. addq $16, %rcx
  4871. movq _fromspace_end(%rip), %rdx
  4872. cmpq %rdx, %rcx
  4873. jl _block59
  4874. jmp _block60
  4875. .globl _main
  4876. _main:
  4877. pushq %rbp
  4878. movq %rsp, %rbp
  4879. pushq %r12
  4880. pushq %rbx
  4881. pushq %r13
  4882. pushq %r14
  4883. subq $0, %rsp
  4884. movq $16384, %rdi
  4885. movq $16, %rsi
  4886. callq _initialize
  4887. movq _rootstack_begin(%rip), %r15
  4888. movq $0, (%r15)
  4889. addq $8, %r15
  4890. jmp _start
  4891. _conclusion:
  4892. subq $8, %r15
  4893. addq $0, %rsp
  4894. popq %r14
  4895. popq %r13
  4896. popq %rbx
  4897. popq %r12
  4898. popq %rbp
  4899. retq
  4900. \end{lstlisting}
  4901. \end{minipage}
  4902. \caption{Output of the \code{print-x86} pass.}
  4903. \label{fig:print-x86-output-gc}
  4904. \end{figure}
  4905. \margincomment{\scriptsize Suggest an implementation strategy
  4906. in which the students first do the code gen and test that
  4907. without GC (just use a big heap), then after that is debugged,
  4908. implement the GC. \\ --Jeremy}
  4909. \begin{figure}[p]
  4910. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4911. \node (R3) at (0,2) {\large $R_3$};
  4912. \node (R3-2) at (3,2) {\large $R_3$};
  4913. \node (R3-3) at (6,2) {\large $R_3$};
  4914. \node (R3-4) at (9,2) {\large $R_3$};
  4915. \node (R3-5) at (12,2) {\large $R_3$};
  4916. \node (C2-4) at (3,0) {\large $C_2$};
  4917. \node (C2-3) at (6,0) {\large $C_2$};
  4918. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  4919. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  4920. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  4921. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  4922. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  4923. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  4924. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4925. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4926. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  4927. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  4928. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  4929. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  4930. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4931. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4932. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4933. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4934. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4935. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  4936. \end{tikzpicture}
  4937. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4938. \label{fig:R3-passes}
  4939. \end{figure}
  4940. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4941. for the compilation of $R_3$.
  4942. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4943. \chapter{Functions}
  4944. \label{ch:functions}
  4945. This chapter studies the compilation of functions at the level of
  4946. abstraction of the C language. This corresponds to a subset of Typed
  4947. Racket in which only top-level function definitions are allowed. These
  4948. kind of functions are an important stepping stone to implementing
  4949. lexically-scoped functions in the form of \key{lambda} abstractions,
  4950. which is the topic of Chapter~\ref{ch:lambdas}.
  4951. \section{The $R_4$ Language}
  4952. The syntax for function definitions and function application is shown
  4953. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  4954. Programs in $R_4$ start with zero or more function definitions. The
  4955. function names from these definitions are in-scope for the entire
  4956. program, including all other function definitions (so the ordering of
  4957. function definitions does not matter). The syntax for function
  4958. application does not include an explicit keyword, which is error prone
  4959. when using \code{match}. To alleviate this problem, we change the
  4960. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  4961. during type checking.
  4962. Functions are first-class in the sense that a function pointer is data
  4963. and can be stored in memory or passed as a parameter to another
  4964. function. Thus, we introduce a function type, written
  4965. \begin{lstlisting}
  4966. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4967. \end{lstlisting}
  4968. for a function whose $n$ parameters have the types $\Type_1$ through
  4969. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4970. these functions (with respect to Racket functions) is that they are
  4971. not lexically scoped. That is, the only external entities that can be
  4972. referenced from inside a function body are other globally-defined
  4973. functions. The syntax of $R_4$ prevents functions from being nested
  4974. inside each other.
  4975. \begin{figure}[tp]
  4976. \centering
  4977. \fbox{
  4978. \begin{minipage}{0.96\textwidth}
  4979. \[
  4980. \begin{array}{lcl}
  4981. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4982. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4983. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4984. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  4985. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4986. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4987. \mid (\key{and}\;\Exp\;\Exp)
  4988. \mid (\key{or}\;\Exp\;\Exp)
  4989. \mid (\key{not}\;\Exp)} \\
  4990. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4991. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4992. (\key{vector-ref}\;\Exp\;\Int)} \\
  4993. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4994. &\mid& (\Exp \; \Exp^{*}) \\
  4995. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4996. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  4997. \end{array}
  4998. \]
  4999. \end{minipage}
  5000. }
  5001. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5002. with functions.}
  5003. \label{fig:r4-syntax}
  5004. \end{figure}
  5005. The program in Figure~\ref{fig:r4-function-example} is a
  5006. representative example of defining and using functions in $R_4$. We
  5007. define a function \code{map-vec} that applies some other function
  5008. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5009. vector containing the results. We also define a function \code{add1}
  5010. that does what its name suggests. The program then applies
  5011. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5012. \code{(vector 1 42)}, from which we return the \code{42}.
  5013. \begin{figure}[tbp]
  5014. \begin{lstlisting}
  5015. (program ()
  5016. (define (map-vec [f : (Integer -> Integer)]
  5017. [v : (Vector Integer Integer)])
  5018. : (Vector Integer Integer)
  5019. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5020. (define (add1 [x : Integer]) : Integer
  5021. (+ x 1))
  5022. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5023. )
  5024. \end{lstlisting}
  5025. \caption{Example of using functions in $R_4$.}
  5026. \label{fig:r4-function-example}
  5027. \end{figure}
  5028. The definitional interpreter for $R_4$ is in
  5029. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5030. responsible for setting up the mutual recursion between the top-level
  5031. function definitions. We use the classic backpatching approach that
  5032. uses mutable variables and makes two passes over the function
  5033. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5034. top-level environment using a mutable cons cell for each function
  5035. definition. Note that the \code{lambda} value for each function is
  5036. incomplete; it does not yet include the environment. Once the
  5037. top-level environment is constructed, we then iterate over it and
  5038. update the \code{lambda} value's to use the top-level environment.
  5039. \begin{figure}[tp]
  5040. \begin{lstlisting}
  5041. (define (interp-exp env)
  5042. (lambda (e)
  5043. (define recur (interp-exp env))
  5044. (match e
  5045. ...
  5046. [`(,fun ,args ...)
  5047. (define arg-vals (for/list ([e args]) (recur e)))
  5048. (define fun-val (recur fun))
  5049. (match fun-val
  5050. [`(lambda (,xs ...) ,body ,fun-env)
  5051. (define new-env (append (map cons xs arg-vals) fun-env))
  5052. ((interp-exp new-env) body)]
  5053. [else (error "interp-exp, expected function, not" fun-val)])]
  5054. [else (error 'interp-exp "unrecognized expression")]
  5055. )))
  5056. (define (interp-def d)
  5057. (match d
  5058. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5059. (mcons f `(lambda ,xs ,body ()))]
  5060. ))
  5061. (define (interp-R4 p)
  5062. (match p
  5063. [`(program ,ds ... ,body)
  5064. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5065. (for/list ([b top-level])
  5066. (set-mcdr! b (match (mcdr b)
  5067. [`(lambda ,xs ,body ())
  5068. `(lambda ,xs ,body ,top-level)])))
  5069. ((interp-exp top-level) body))]
  5070. ))
  5071. \end{lstlisting}
  5072. \caption{Interpreter for the $R_4$ language.}
  5073. \label{fig:interp-R4}
  5074. \end{figure}
  5075. \section{Functions in x86}
  5076. \label{sec:fun-x86}
  5077. \margincomment{\tiny Make sure callee-saved registers are discussed
  5078. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5079. \margincomment{\tiny Talk about the return address on the
  5080. stack and what callq and retq does.\\ --Jeremy }
  5081. The x86 architecture provides a few features to support the
  5082. implementation of functions. We have already seen that x86 provides
  5083. labels so that one can refer to the location of an instruction, as is
  5084. needed for jump instructions. Labels can also be used to mark the
  5085. beginning of the instructions for a function. Going further, we can
  5086. obtain the address of a label by using the \key{leaq} instruction and
  5087. \key{rip}-relative addressing. For example, the following puts the
  5088. address of the \code{add1} label into the \code{rbx} register.
  5089. \begin{lstlisting}
  5090. leaq add1(%rip), %rbx
  5091. \end{lstlisting}
  5092. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5093. instruction for jumping to a function whose location is given by a
  5094. label. Here we instead will be jumping to a function whose location is
  5095. given by an address, that is, we need to make an \emph{indirect
  5096. function call}. The x86 syntax is to give the register name prefixed
  5097. with an asterisk.
  5098. \begin{lstlisting}
  5099. callq *%rbx
  5100. \end{lstlisting}
  5101. \subsection{Calling Conventions}
  5102. The \code{callq} instruction provides partial support for implementing
  5103. functions, but it does not handle (1) parameter passing, (2) saving
  5104. and restoring frames on the procedure call stack, or (3) determining
  5105. how registers are shared by different functions. These issues require
  5106. coordination between the caller and the callee, which is often
  5107. assembly code written by different programmers or generated by
  5108. different compilers. As a result, people have developed
  5109. \emph{conventions} that govern how functions calls are performed.
  5110. Here we shall use the same conventions used by the \code{gcc}
  5111. compiler~\citep{Matz:2013aa}.
  5112. Regarding (1) parameter passing, the convention is to use the
  5113. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5114. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5115. than six arguments, then the convention is to use space on the frame
  5116. of the caller for the rest of the arguments. However, to ease the
  5117. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5118. we shall arrange to never have more than six arguments.
  5119. %
  5120. The register \code{rax} is for the return value of the function.
  5121. Regarding (2) frames and the procedure call stack, the convention is
  5122. that the stack grows down, with each function call using a chunk of
  5123. space called a frame. The caller sets the stack pointer, register
  5124. \code{rsp}, to the last data item in its frame. The callee must not
  5125. change anything in the caller's frame, that is, anything that is at or
  5126. above the stack pointer. The callee is free to use locations that are
  5127. below the stack pointer.
  5128. Regarding (3) the sharing of registers between different functions,
  5129. recall from Section~\ref{sec:calling-conventions} that the registers
  5130. are divided into two groups, the caller-saved registers and the
  5131. callee-saved registers. The caller should assume that all the
  5132. caller-saved registers get overwritten with arbitrary values by the
  5133. callee. Thus, the caller should either 1) not put values that are live
  5134. across a call in caller-saved registers, or 2) save and restore values
  5135. that are live across calls. We shall recommend option 1). On the flip
  5136. side, if the callee wants to use a callee-saved register, the callee
  5137. must save the contents of those registers on their stack frame and
  5138. then put them back prior to returning to the caller. The base
  5139. pointer, register \code{rbp}, is used as a point-of-reference within a
  5140. frame, so that each local variable can be accessed at a fixed offset
  5141. from the base pointer.
  5142. %
  5143. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5144. frames.
  5145. %% If we were to use stack arguments, they would be between the
  5146. %% caller locals and the callee return address.
  5147. \begin{figure}[tbp]
  5148. \centering
  5149. \begin{tabular}{r|r|l|l} \hline
  5150. Caller View & Callee View & Contents & Frame \\ \hline
  5151. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5152. 0(\key{\%rbp}) & & old \key{rbp} \\
  5153. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5154. \ldots & & \ldots \\
  5155. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5156. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5157. \ldots & & \ldots \\
  5158. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5159. %% & & \\
  5160. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5161. %% & \ldots & \ldots \\
  5162. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5163. \hline
  5164. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5165. & 0(\key{\%rbp}) & old \key{rbp} \\
  5166. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5167. & \ldots & \ldots \\
  5168. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5169. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5170. & \ldots & \ldots \\
  5171. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5172. \end{tabular}
  5173. \caption{Memory layout of caller and callee frames.}
  5174. \label{fig:call-frames}
  5175. \end{figure}
  5176. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5177. %% local variables and for storing the values of callee-saved registers
  5178. %% (we shall refer to all of these collectively as ``locals''), and that
  5179. %% at the beginning of a function we move the stack pointer \code{rsp}
  5180. %% down to make room for them.
  5181. %% We recommend storing the local variables
  5182. %% first and then the callee-saved registers, so that the local variables
  5183. %% can be accessed using \code{rbp} the same as before the addition of
  5184. %% functions.
  5185. %% To make additional room for passing arguments, we shall
  5186. %% move the stack pointer even further down. We count how many stack
  5187. %% arguments are needed for each function call that occurs inside the
  5188. %% body of the function and find their maximum. Adding this number to the
  5189. %% number of locals gives us how much the \code{rsp} should be moved at
  5190. %% the beginning of the function. In preparation for a function call, we
  5191. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5192. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5193. %% so on.
  5194. %% Upon calling the function, the stack arguments are retrieved by the
  5195. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5196. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5197. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5198. %% the layout of the caller and callee frames. Notice how important it is
  5199. %% that we correctly compute the maximum number of arguments needed for
  5200. %% function calls; if that number is too small then the arguments and
  5201. %% local variables will smash into each other!
  5202. \subsection{Efficient Tail Calls}
  5203. \label{sec:tail-call}
  5204. In general, the amount of stack space used by a program is determined
  5205. by the longest chain of nested function calls. That is, if function
  5206. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5207. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5208. $n$ can grow quite large in the case of recursive or mutually
  5209. recursive functions. However, in some cases we can arrange to use only
  5210. constant space, i.e. $O(1)$, instead of $O(n)$.
  5211. If a function call is the last action in a function body, then that
  5212. call is said to be a \emph{tail call}. In such situations, the frame
  5213. of the caller is no longer needed, so we can pop the caller's frame
  5214. before making the tail call. With this approach, a recursive function
  5215. that only makes tail calls will only use $O(1)$ stack space.
  5216. Functional languages like Racket typically rely heavily on recursive
  5217. functions, so they typically guarantee that all tail calls will be
  5218. optimized in this way.
  5219. However, some care is needed with regards to argument passing in tail
  5220. calls. As mentioned above, for arguments beyond the sixth, the
  5221. convention is to use space in the caller's frame for passing
  5222. arguments. But here we've popped the caller's frame and can no longer
  5223. use it. Another alternative is to use space in the callee's frame for
  5224. passing arguments. However, this option is also problematic because
  5225. the caller and callee's frame overlap in memory. As we begin to copy
  5226. the arguments from their sources in the caller's frame, the target
  5227. locations in the callee's frame might overlap with the sources for
  5228. later arguments! We solve this problem by not using the stack for
  5229. parameter passing but instead use the heap, as we describe in the
  5230. Section~\ref{sec:limit-functions-r4}.
  5231. As mentioned above, for a tail call we pop the caller's frame prior to
  5232. making the tail call. The instructions for popping a frame are the
  5233. instructions that we usually place in the conclusion of a
  5234. function. Thus, we also need to place such code immediately before
  5235. each tail call. These instructions include restoring the callee-saved
  5236. registers, so it is good that the argument passing registers are all
  5237. caller-saved registers.
  5238. One last note regarding which instruction to use to make the tail
  5239. call. When the callee is finished, it should not return to the current
  5240. function, but it should return to the function that called the current
  5241. one. Thus, the return address that is already on the stack is the
  5242. right one, and we should not use \key{callq} to make the tail call, as
  5243. that would unnecessarily overwrite the return address. Instead we can
  5244. simply use the \key{jmp} instruction. Like the indirect function call,
  5245. we write an indirect jump with a register prefixed with an asterisk.
  5246. We recommend using \code{rax} to hold the jump target because the
  5247. preceeding ``conclusion'' overwrites just about everything else.
  5248. \begin{lstlisting}
  5249. jmp *%rax
  5250. \end{lstlisting}
  5251. %% Now that we have a good understanding of functions as they appear in
  5252. %% $R_4$ and the support for functions in x86, we need to plan the
  5253. %% changes to our compiler, that is, do we need any new passes and/or do
  5254. %% we need to change any existing passes? Also, do we need to add new
  5255. %% kinds of AST nodes to any of the intermediate languages?
  5256. \section{Shrink $R_4$}
  5257. \label{sec:shrink-r4}
  5258. The \code{shrink} pass performs a couple minor modifications to the
  5259. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5260. field to each function definition:
  5261. \begin{lstlisting}
  5262. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5263. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5264. \end{lstlisting}
  5265. and introduces an explicit \code{main} function.\\
  5266. \begin{tabular}{lll}
  5267. \begin{minipage}{0.45\textwidth}
  5268. \begin{lstlisting}
  5269. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5270. \end{lstlisting}
  5271. \end{minipage}
  5272. &
  5273. $\Rightarrow$
  5274. &
  5275. \begin{minipage}{0.45\textwidth}
  5276. \begin{lstlisting}
  5277. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5278. \end{lstlisting}
  5279. \end{minipage}
  5280. \end{tabular} \\
  5281. where $\itm{mainDef}$ is
  5282. \begin{lstlisting}
  5283. (define (main) : Integer () |$\Exp'$|)
  5284. \end{lstlisting}
  5285. \section{Reveal Functions}
  5286. \label{sec:reveal-functions-r4}
  5287. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5288. compilation because it conflates the use of function names and local
  5289. variables. This is a problem because we need to compile the use of a
  5290. function name differently than the use of a local variable; we need to
  5291. use \code{leaq} to convert the function name (a label in x86) to an
  5292. address in a register. Thus, it is a good idea to create a new pass
  5293. that changes function references from just a symbol $f$ to
  5294. \code{(fun-ref $f$)}. A good name for this pass is
  5295. \code{reveal-functions} and the output language, $F_1$, is defined in
  5296. Figure~\ref{fig:f1-syntax}.
  5297. \begin{figure}[tp]
  5298. \centering
  5299. \fbox{
  5300. \begin{minipage}{0.96\textwidth}
  5301. \[
  5302. \begin{array}{lcl}
  5303. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5304. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5305. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5306. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5307. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5308. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5309. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5310. (\key{vector-ref}\;\Exp\;\Int)} \\
  5311. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5312. (\key{app}\; \Exp \; \Exp^{*})} \\
  5313. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5314. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5315. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5316. \end{array}
  5317. \]
  5318. \end{minipage}
  5319. }
  5320. \caption{The $F_1$ language, an extension of $R_4$
  5321. (Figure~\ref{fig:r4-syntax}).}
  5322. \label{fig:f1-syntax}
  5323. \end{figure}
  5324. %% Distinguishing between calls in tail position and non-tail position
  5325. %% requires the pass to have some notion of context. We recommend using
  5326. %% two mutually recursive functions, one for processing expressions in
  5327. %% tail position and another for the rest.
  5328. Placing this pass after \code{uniquify} is a good idea, because it
  5329. will make sure that there are no local variables and functions that
  5330. share the same name. On the other hand, \code{reveal-functions} needs
  5331. to come before the \code{explicate-control} pass because that pass
  5332. will help us compile \code{fun-ref} into assignment statements.
  5333. \section{Limit Functions}
  5334. \label{sec:limit-functions-r4}
  5335. This pass transforms functions so that they have at most six
  5336. parameters and transforms all function calls so that they pass at most
  5337. six arguments. A simple strategy for imposing an argument limit of
  5338. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5339. into a vector, making that subsequent vector the $n$th argument.
  5340. \begin{tabular}{lll}
  5341. \begin{minipage}{0.2\textwidth}
  5342. \begin{lstlisting}
  5343. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5344. \end{lstlisting}
  5345. \end{minipage}
  5346. &
  5347. $\Rightarrow$
  5348. &
  5349. \begin{minipage}{0.4\textwidth}
  5350. \begin{lstlisting}
  5351. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5352. \end{lstlisting}
  5353. \end{minipage}
  5354. \end{tabular}
  5355. In the body of the function, all occurrances of the $i$th argument in
  5356. which $i>5$ must be replaced with a \code{vector-ref}.
  5357. \section{Remove Complex Operators and Operands}
  5358. \label{sec:rco-r4}
  5359. The primary decisions to make for this pass is whether to classify
  5360. \code{fun-ref} and \code{app} as either simple or complex
  5361. expressions. Recall that a simple expression will eventually end up as
  5362. just an ``immediate'' argument of an x86 instruction. Function
  5363. application will be translated to a sequence of instructions, so
  5364. \code{app} must be classified as complex expression. Regarding
  5365. \code{fun-ref}, as discussed above, the function label needs to
  5366. be converted to an address using the \code{leaq} instruction. Thus,
  5367. even though \code{fun-ref} seems rather simple, it needs to be
  5368. classified as a complex expression so that we generate an assignment
  5369. statement with a left-hand side that can serve as the target of the
  5370. \code{leaq}.
  5371. \section{Explicate Control and the $C_3$ language}
  5372. \label{sec:explicate-control-r4}
  5373. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5374. \key{explicate-control}. The three mutually recursive functions for
  5375. this pass, for assignment, tail, and predicate contexts, must all be
  5376. updated with cases for \code{fun-ref} and \code{app}. In
  5377. assignment and predicate contexts, \code{app} becomes \code{call},
  5378. whereas in tail position \code{app} becomes \code{tailcall}. We
  5379. recommend defining a new function for processing function definitions.
  5380. This code is similar to the case for \code{program} in $R_3$. The
  5381. top-level \code{explicate-control} function that handles the
  5382. \code{program} form of $R_4$ can then apply this new function to all
  5383. the function definitions.
  5384. \begin{figure}[tp]
  5385. \fbox{
  5386. \begin{minipage}{0.96\textwidth}
  5387. \[
  5388. \begin{array}{lcl}
  5389. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5390. \\
  5391. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5392. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5393. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5394. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5395. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5396. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5397. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5398. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5399. \mid (\key{collect} \,\itm{int}) }\\
  5400. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5401. &\mid& \gray{(\key{goto}\,\itm{label})
  5402. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5403. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5404. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5405. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5406. \end{array}
  5407. \]
  5408. \end{minipage}
  5409. }
  5410. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5411. \label{fig:c3-syntax}
  5412. \end{figure}
  5413. \section{Uncover Locals}
  5414. \label{sec:uncover-locals-r4}
  5415. The function for processing $\Tail$ should be updated with a case for
  5416. \code{tailcall}. We also recommend creating a new function for
  5417. processing function definitions. Each function definition in $C_3$ has
  5418. its own set of local variables, so the code for function definitions
  5419. should be similar to the case for the \code{program} form in $C_2$.
  5420. \section{Select Instructions}
  5421. \label{sec:select-r4}
  5422. The output of select instructions is a program in the x86$_3$
  5423. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5424. \begin{figure}[tp]
  5425. \fbox{
  5426. \begin{minipage}{0.96\textwidth}
  5427. \[
  5428. \begin{array}{lcl}
  5429. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5430. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5431. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5432. \mid (\key{global-value}\; \itm{name}) } \\
  5433. &\mid& (\key{fun-ref}\; \itm{label})\\
  5434. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5435. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5436. (\key{subq} \; \Arg\; \Arg) \mid
  5437. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5438. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5439. (\key{pushq}\;\Arg) \mid
  5440. (\key{popq}\;\Arg) \mid
  5441. (\key{retq}) } \\
  5442. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5443. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5444. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5445. \mid (\key{jmp} \; \itm{label})
  5446. \mid (\key{j}\itm{cc} \; \itm{label})
  5447. \mid (\key{label} \; \itm{label}) } \\
  5448. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5449. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5450. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5451. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5452. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5453. \end{array}
  5454. \]
  5455. \end{minipage}
  5456. }
  5457. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5458. \label{fig:x86-3}
  5459. \end{figure}
  5460. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5461. as follows: \\
  5462. \begin{tabular}{lll}
  5463. \begin{minipage}{0.45\textwidth}
  5464. \begin{lstlisting}
  5465. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5466. \end{lstlisting}
  5467. \end{minipage}
  5468. &
  5469. $\Rightarrow$
  5470. &
  5471. \begin{minipage}{0.4\textwidth}
  5472. \begin{lstlisting}
  5473. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5474. \end{lstlisting}
  5475. \end{minipage}
  5476. \end{tabular} \\
  5477. Regarding function definitions, we need to remove their parameters and
  5478. instead perform parameter passing in terms of the conventions
  5479. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5480. in the argument passing registers, and inside the function we should
  5481. generate a \code{movq} instruction for each parameter, to move the
  5482. argument value from the appropriate register to a new local variable
  5483. with the same name as the old parameter.
  5484. Next, consider the compilation of function calls, which have the
  5485. following form upon input to \code{select-instructions}.
  5486. \begin{lstlisting}
  5487. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5488. \end{lstlisting}
  5489. In the mirror image of handling the parameters of function
  5490. definitions, the arguments \itm{args} need to be moved to the argument
  5491. passing registers.
  5492. %
  5493. Once the instructions for parameter passing have been generated, the
  5494. function call itself can be performed with an indirect function call,
  5495. for which I recommend creating the new instruction
  5496. \code{indirect-callq}. Of course, the return value from the function
  5497. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5498. \begin{lstlisting}
  5499. (indirect-callq |\itm{fun}|)
  5500. (movq (reg rax) |\itm{lhs}|)
  5501. \end{lstlisting}
  5502. Regarding tail calls, the parameter passing is the same as non-tail
  5503. calls: generate instructions to move the arguments into to the
  5504. argument passing registers. After that we need to pop the frame from
  5505. the procedure call stack. However, we do not yet know how big the
  5506. frame is; that gets determined during register allocation. So instead
  5507. of generating those instructions here, we invent a new instruction
  5508. that means ``pop the frame and then do an indirect jump'', which we
  5509. name \code{tail-jmp}.
  5510. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5511. using the label \code{start} for the initial block of a program, and
  5512. in Section~\ref{sec:select-r1} we recommended labelling the conclusion
  5513. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5514. can be compiled to an assignment to \code{rax} followed by a jump to
  5515. \code{conclusion}. With the addition of function definitions, we will
  5516. have a starting block and conclusion for each function, but their
  5517. labels need to be unique. We recommend prepending the function's name
  5518. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5519. labels. (Alternatively, one could \code{gensym} labels for the start
  5520. and conclusion and store them in the $\itm{info}$ field of the
  5521. function definition.)
  5522. \section{Uncover Live}
  5523. %% The rest of the passes need only minor modifications to handle the new
  5524. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5525. %% \code{leaq}.
  5526. Inside \code{uncover-live}, when computing the $W$ set (written
  5527. variables) for an \code{indirect-callq} instruction, we recommend
  5528. including all the caller-saved registers, which will have the affect
  5529. of making sure that no caller-saved register actually needs to be
  5530. saved.
  5531. \section{Build Interference Graph}
  5532. With the addition of function definitions, we compute an interference
  5533. graph for each function (not just one for the whole program).
  5534. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5535. spill vector-typed variables that are live during a call to the
  5536. \code{collect}. With the addition of functions to our language, we
  5537. need to revisit this issue. Many functions will perform allocation and
  5538. therefore have calls to the collector inside of them. Thus, we should
  5539. not only spill a vector-typed variable when it is live during a call
  5540. to \code{collect}, but we should spill the variable if it is live
  5541. during any function call. Thus, in the \code{build-interference} pass,
  5542. we recommend adding interference edges between call-live vector-typed
  5543. variables and the callee-saved registers (in addition to the usual
  5544. addition of edges between call-live variables and the caller-saved
  5545. registers).
  5546. \section{Patch Instructions}
  5547. In \code{patch-instructions}, you should deal with the x86
  5548. idiosyncrasy that the destination argument of \code{leaq} must be a
  5549. register. Additionally, you should ensure that the argument of
  5550. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5551. code generation more convenient, because we will be trampling many
  5552. registers before the tail call (as explained below).
  5553. \section{Print x86}
  5554. For the \code{print-x86} pass, we recommend the following translations:
  5555. \begin{lstlisting}
  5556. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5557. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5558. \end{lstlisting}
  5559. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5560. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5561. is what we will want to do, but before the jump we need to pop the
  5562. current frame. So we need to restore the state of the registers to the
  5563. point they were at when the current function was called. This
  5564. sequence of instructions is the same as the code for the conclusion of
  5565. a function.
  5566. Note that your \code{print-x86} pass needs to add the code for saving
  5567. and restoring callee-saved registers, if you have not already
  5568. implemented that. This is necessary when generating code for function
  5569. definitions.
  5570. \section{An Example Translation}
  5571. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5572. function in $R_4$ to x86. The figure also includes the results of the
  5573. \code{explicate-control} and \code{select-instructions} passes. We
  5574. have ommited the \code{has-type} AST nodes for readability. Can you
  5575. see any ways to improve the translation?
  5576. \begin{figure}[tbp]
  5577. \begin{tabular}{ll}
  5578. \begin{minipage}{0.45\textwidth}
  5579. % s3_2.rkt
  5580. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5581. (program
  5582. (define (add [x : Integer]
  5583. [y : Integer])
  5584. : Integer (+ x y))
  5585. (add 40 2))
  5586. \end{lstlisting}
  5587. $\Downarrow$
  5588. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5589. (program ()
  5590. (define (add86 [x87 : Integer]
  5591. [y88 : Integer]) : Integer ()
  5592. ((add86start . (return (+ x87 y88)))))
  5593. (define (main) : Integer ()
  5594. ((mainstart .
  5595. (seq (assign tmp89 (fun-ref add86))
  5596. (tailcall tmp89 40 2))))))
  5597. \end{lstlisting}
  5598. \end{minipage}
  5599. &
  5600. $\Rightarrow$
  5601. \begin{minipage}{0.5\textwidth}
  5602. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5603. (program ()
  5604. (define (add86)
  5605. ((locals (x87 . Integer) (y88 . Integer))
  5606. (num-params . 2))
  5607. ((add86start .
  5608. (block ()
  5609. (movq (reg rcx) (var x87))
  5610. (movq (reg rdx) (var y88))
  5611. (movq (var x87) (reg rax))
  5612. (addq (var y88) (reg rax))
  5613. (jmp add86conclusion)))))
  5614. (define (main)
  5615. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5616. (num-params . 0))
  5617. ((mainstart .
  5618. (block ()
  5619. (leaq (fun-ref add86) (var tmp89))
  5620. (movq (int 40) (reg rcx))
  5621. (movq (int 2) (reg rdx))
  5622. (tail-jmp (var tmp89))))))
  5623. \end{lstlisting}
  5624. $\Downarrow$
  5625. \end{minipage}
  5626. \end{tabular}
  5627. \begin{tabular}{lll}
  5628. \begin{minipage}{0.3\textwidth}
  5629. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5630. _add90start:
  5631. movq %rcx, %rsi
  5632. movq %rdx, %rcx
  5633. movq %rsi, %rax
  5634. addq %rcx, %rax
  5635. jmp _add90conclusion
  5636. .globl _add90
  5637. .align 16
  5638. _add90:
  5639. pushq %rbp
  5640. movq %rsp, %rbp
  5641. pushq %r12
  5642. pushq %rbx
  5643. pushq %r13
  5644. pushq %r14
  5645. subq $0, %rsp
  5646. jmp _add90start
  5647. _add90conclusion:
  5648. addq $0, %rsp
  5649. popq %r14
  5650. popq %r13
  5651. popq %rbx
  5652. popq %r12
  5653. subq $0, %r15
  5654. popq %rbp
  5655. retq
  5656. \end{lstlisting}
  5657. \end{minipage}
  5658. &
  5659. \begin{minipage}{0.3\textwidth}
  5660. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5661. _mainstart:
  5662. leaq _add90(%rip), %rsi
  5663. movq $40, %rcx
  5664. movq $2, %rdx
  5665. movq %rsi, %rax
  5666. addq $0, %rsp
  5667. popq %r14
  5668. popq %r13
  5669. popq %rbx
  5670. popq %r12
  5671. subq $0, %r15
  5672. popq %rbp
  5673. jmp *%rax
  5674. .globl _main
  5675. .align 16
  5676. _main:
  5677. pushq %rbp
  5678. movq %rsp, %rbp
  5679. pushq %r12
  5680. pushq %rbx
  5681. pushq %r13
  5682. pushq %r14
  5683. subq $0, %rsp
  5684. movq $16384, %rdi
  5685. movq $16, %rsi
  5686. callq _initialize
  5687. movq _rootstack_begin(%rip), %r15
  5688. jmp _mainstart
  5689. \end{lstlisting}
  5690. \end{minipage}
  5691. &
  5692. \begin{minipage}{0.3\textwidth}
  5693. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5694. _mainconclusion:
  5695. addq $0, %rsp
  5696. popq %r14
  5697. popq %r13
  5698. popq %rbx
  5699. popq %r12
  5700. subq $0, %r15
  5701. popq %rbp
  5702. retq
  5703. \end{lstlisting}
  5704. \end{minipage}
  5705. \end{tabular}
  5706. \caption{Example compilation of a simple function to x86.}
  5707. \label{fig:add-fun}
  5708. \end{figure}
  5709. \begin{exercise}\normalfont
  5710. Expand your compiler to handle $R_4$ as outlined in this section.
  5711. Create 5 new programs that use functions, including examples that pass
  5712. functions and return functions from other functions and including
  5713. recursive functions. Test your compiler on these new programs and all
  5714. of your previously created test programs.
  5715. \end{exercise}
  5716. \begin{figure}[p]
  5717. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5718. \node (R4) at (0,2) {\large $R_4$};
  5719. \node (R4-2) at (3,2) {\large $R_4$};
  5720. \node (R4-3) at (6,2) {\large $R_4$};
  5721. \node (F1-1) at (12,0) {\large $F_1$};
  5722. \node (F1-2) at (9,0) {\large $F_1$};
  5723. \node (F1-3) at (6,0) {\large $F_1$};
  5724. \node (F1-4) at (3,0) {\large $F_1$};
  5725. \node (C3-1) at (6,-2) {\large $C_3$};
  5726. \node (C3-2) at (3,-2) {\large $C_3$};
  5727. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5728. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5729. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5730. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5731. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5732. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5733. \path[->,bend left=15] (R4) edge [above] node
  5734. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5735. \path[->,bend left=15] (R4-2) edge [above] node
  5736. {\ttfamily\footnotesize uniquify} (R4-3);
  5737. \path[->,bend left=15] (R4-3) edge [right] node
  5738. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5739. \path[->,bend left=15] (F1-1) edge [below] node
  5740. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5741. \path[->,bend right=15] (F1-2) edge [above] node
  5742. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5743. \path[->,bend right=15] (F1-3) edge [above] node
  5744. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5745. \path[->,bend left=15] (F1-4) edge [right] node
  5746. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5747. \path[->,bend left=15] (C3-1) edge [below] node
  5748. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5749. \path[->,bend right=15] (C3-2) edge [left] node
  5750. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5751. \path[->,bend left=15] (x86-2) edge [left] node
  5752. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5753. \path[->,bend right=15] (x86-2-1) edge [below] node
  5754. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5755. \path[->,bend right=15] (x86-2-2) edge [left] node
  5756. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5757. \path[->,bend left=15] (x86-3) edge [above] node
  5758. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5759. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5760. \end{tikzpicture}
  5761. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5762. \label{fig:R4-passes}
  5763. \end{figure}
  5764. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5765. the compilation of $R_4$.
  5766. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5767. \chapter{Lexically Scoped Functions}
  5768. \label{ch:lambdas}
  5769. This chapter studies lexically scoped functions as they appear in
  5770. functional languages such as Racket. By lexical scoping we mean that a
  5771. function's body may refer to variables whose binding site is outside
  5772. of the function, in an enclosing scope.
  5773. %
  5774. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5775. anonymous function defined using the \key{lambda} form. The body of
  5776. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5777. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5778. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5779. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5780. returned from the function \code{f}. Below the definition of \code{f},
  5781. we have two calls to \code{f} with different arguments for \code{x},
  5782. first \code{5} then \code{3}. The functions returned from \code{f} are
  5783. bound to variables \code{g} and \code{h}. Even though these two
  5784. functions were created by the same \code{lambda}, they are really
  5785. different functions because they use different values for
  5786. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5787. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5788. the result of this program is \code{42}.
  5789. \begin{figure}[btp]
  5790. % s4_6.rkt
  5791. \begin{lstlisting}
  5792. (define (f [x : Integer]) : (Integer -> Integer)
  5793. (let ([y 4])
  5794. (lambda: ([z : Integer]) : Integer
  5795. (+ x (+ y z)))))
  5796. (let ([g (f 5)])
  5797. (let ([h (f 3)])
  5798. (+ (g 11) (h 15))))
  5799. \end{lstlisting}
  5800. \caption{Example of a lexically scoped function.}
  5801. \label{fig:lexical-scoping}
  5802. \end{figure}
  5803. \section{The $R_5$ Language}
  5804. The syntax for this language with anonymous functions and lexical
  5805. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5806. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5807. for function application. In this chapter we shall descibe how to
  5808. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5809. into a combination of functions (as in $R_4$) and tuples (as in
  5810. $R_3$).
  5811. \begin{figure}[tp]
  5812. \centering
  5813. \fbox{
  5814. \begin{minipage}{0.96\textwidth}
  5815. \[
  5816. \begin{array}{lcl}
  5817. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5818. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5819. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5820. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5821. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5822. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5823. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5824. \mid (\key{and}\;\Exp\;\Exp)
  5825. \mid (\key{or}\;\Exp\;\Exp)
  5826. \mid (\key{not}\;\Exp) } \\
  5827. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5828. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5829. (\key{vector-ref}\;\Exp\;\Int)} \\
  5830. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5831. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5832. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5833. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5834. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5835. \end{array}
  5836. \]
  5837. \end{minipage}
  5838. }
  5839. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  5840. with \key{lambda}.}
  5841. \label{fig:r5-syntax}
  5842. \end{figure}
  5843. To compile lexically-scoped functions to top-level function
  5844. definitions, the compiler will need to provide special treatment to
  5845. variable occurences such as \code{x} and \code{y} in the body of the
  5846. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  5847. of $R_4$ may not refer to variables defined outside the function. To
  5848. identify such variable occurences, we review the standard notion of
  5849. free variable.
  5850. \begin{definition}
  5851. A variable is \emph{free with respect to an expression} $e$ if the
  5852. variable occurs inside $e$ but does not have an enclosing binding in
  5853. $e$.
  5854. \end{definition}
  5855. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5856. free with respect to the expression \code{(+ x (+ y z))}. On the
  5857. other hand, only \code{x} and \code{y} are free with respect to the
  5858. following expression becuase \code{z} is bound by the \code{lambda}.
  5859. \begin{lstlisting}
  5860. (lambda: ([z : Integer]) : Integer
  5861. (+ x (+ y z)))
  5862. \end{lstlisting}
  5863. Once we have identified the free variables of a \code{lambda}, we need
  5864. to arrange for some way to transport, at runtime, the values of those
  5865. variables from the point where the \code{lambda} was created to the
  5866. point where the \code{lambda} is applied. Referring again to
  5867. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5868. needs to be used in the application of \code{g} to \code{11}, but the
  5869. binding of \code{x} to \code{3} needs to be used in the application of
  5870. \code{h} to \code{15}. An efficient solution to the problem, due to
  5871. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  5872. free variables together with the function pointer for the lambda's
  5873. code, an arrangement called a \emph{flat closure} (which we shorten to
  5874. just ``closure'') . Fortunately, we have all the ingredients to make
  5875. closures, Chapter~\ref{ch:tuples} gave us vectors and
  5876. Chapter~\ref{ch:functions} gave us function pointers. The function
  5877. pointer shall reside at index $0$ and the values for free variables
  5878. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  5879. the two closures created by the two calls to \code{f} in
  5880. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  5881. the same \key{lambda}, they share the same function pointer but differ
  5882. in the values for the free variable \code{x}.
  5883. \begin{figure}[tbp]
  5884. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5885. \caption{Example closure representation for the \key{lambda}'s
  5886. in Figure~\ref{fig:lexical-scoping}.}
  5887. \label{fig:closures}
  5888. \end{figure}
  5889. \section{Interpreting $R_5$}
  5890. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5891. $R_5$. The clause for \key{lambda} saves the current environment
  5892. inside the returned \key{lambda}. Then the clause for \key{app} uses
  5893. the environment from the \key{lambda}, the \code{lam-env}, when
  5894. interpreting the body of the \key{lambda}. The \code{lam-env}
  5895. environment is extended with the mapping of parameters to argument
  5896. values.
  5897. \begin{figure}[tbp]
  5898. \begin{lstlisting}
  5899. (define (interp-exp env)
  5900. (lambda (e)
  5901. (define recur (interp-exp env))
  5902. (match e
  5903. ...
  5904. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5905. `(lambda ,xs ,body ,env)]
  5906. [`(app ,fun ,args ...)
  5907. (define fun-val ((interp-exp env) fun))
  5908. (define arg-vals (map (interp-exp env) args))
  5909. (match fun-val
  5910. [`(lambda (,xs ...) ,body ,lam-env)
  5911. (define new-env (append (map cons xs arg-vals) lam-env))
  5912. ((interp-exp new-env) body)]
  5913. [else (error "interp-exp, expected function, not" fun-val)])]
  5914. [else (error 'interp-exp "unrecognized expression")]
  5915. )))
  5916. \end{lstlisting}
  5917. \caption{Interpreter for $R_5$.}
  5918. \label{fig:interp-R5}
  5919. \end{figure}
  5920. \section{Type Checking $R_5$}
  5921. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5922. \key{lambda} form. The body of the \key{lambda} is checked in an
  5923. environment that includes the current environment (because it is
  5924. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5925. require the body's type to match the declared return type.
  5926. \begin{figure}[tbp]
  5927. \begin{lstlisting}
  5928. (define (typecheck-R5 env)
  5929. (lambda (e)
  5930. (match e
  5931. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5932. (define new-env (append (map cons xs Ts) env))
  5933. (define bodyT ((typecheck-R5 new-env) body))
  5934. (cond [(equal? rT bodyT)
  5935. `(,@Ts -> ,rT)]
  5936. [else
  5937. (error "mismatch in return type" bodyT rT)])]
  5938. ...
  5939. )))
  5940. \end{lstlisting}
  5941. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5942. \label{fig:typecheck-R5}
  5943. \end{figure}
  5944. \section{Closure Conversion}
  5945. The compiling of lexically-scoped functions into top-level function
  5946. definitions is accomplished in the pass \code{convert-to-closures}
  5947. that comes after \code{reveal-functions} and before
  5948. \code{limit-functions}.
  5949. As usual, we shall implement the pass as a recursive function over the
  5950. AST. All of the action is in the clauses for \key{lambda} and
  5951. \key{app}. We transform a \key{lambda} expression into an expression
  5952. that creates a closure, that is, creates a vector whose first element
  5953. is a function pointer and the rest of the elements are the free
  5954. variables of the \key{lambda}. The \itm{name} is a unique symbol
  5955. generated to identify the function.
  5956. \begin{tabular}{lll}
  5957. \begin{minipage}{0.4\textwidth}
  5958. \begin{lstlisting}
  5959. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5960. \end{lstlisting}
  5961. \end{minipage}
  5962. &
  5963. $\Rightarrow$
  5964. &
  5965. \begin{minipage}{0.4\textwidth}
  5966. \begin{lstlisting}
  5967. (vector |\itm{name}| |\itm{fvs}| ...)
  5968. \end{lstlisting}
  5969. \end{minipage}
  5970. \end{tabular} \\
  5971. %
  5972. In addition to transforming each \key{lambda} into a \key{vector}, we
  5973. must create a top-level function definition for each \key{lambda}, as
  5974. shown below.\\
  5975. \begin{minipage}{0.8\textwidth}
  5976. \begin{lstlisting}
  5977. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  5978. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5979. ...
  5980. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5981. |\itm{body'}|)...))
  5982. \end{lstlisting}
  5983. \end{minipage}\\
  5984. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  5985. parameters are the normal parameters of the \key{lambda}. The types
  5986. $\itm{fvts}$ are the types of the free variables in the lambda and the
  5987. underscore is a dummy type because it is rather difficult to give a
  5988. type to the function in the closure's type, and it does not matter.
  5989. The sequence of \key{let} forms bind the free variables to their
  5990. values obtained from the closure.
  5991. We transform function application into code that retreives the
  5992. function pointer from the closure and then calls the function, passing
  5993. in the closure as the first argument. We bind $e'$ to a temporary
  5994. variable to avoid code duplication.
  5995. \begin{tabular}{lll}
  5996. \begin{minipage}{0.3\textwidth}
  5997. \begin{lstlisting}
  5998. (app |$e$| |\itm{es}| ...)
  5999. \end{lstlisting}
  6000. \end{minipage}
  6001. &
  6002. $\Rightarrow$
  6003. &
  6004. \begin{minipage}{0.5\textwidth}
  6005. \begin{lstlisting}
  6006. (let ([|\itm{tmp}| |$e'$|])
  6007. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6008. \end{lstlisting}
  6009. \end{minipage}
  6010. \end{tabular} \\
  6011. There is also the question of what to do with top-level function
  6012. definitions. To maintain a uniform translation of function
  6013. application, we turn function references into closures.
  6014. \begin{tabular}{lll}
  6015. \begin{minipage}{0.3\textwidth}
  6016. \begin{lstlisting}
  6017. (fun-ref |$f$|)
  6018. \end{lstlisting}
  6019. \end{minipage}
  6020. &
  6021. $\Rightarrow$
  6022. &
  6023. \begin{minipage}{0.5\textwidth}
  6024. \begin{lstlisting}
  6025. (vector (fun-ref |$f$|))
  6026. \end{lstlisting}
  6027. \end{minipage}
  6028. \end{tabular} \\
  6029. %
  6030. The top-level function definitions need to be updated as well to take
  6031. an extra closure parameter.
  6032. \section{An Example Translation}
  6033. \label{sec:example-lambda}
  6034. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6035. conversion for the example program demonstrating lexical scoping that
  6036. we discussed at the beginning of this chapter.
  6037. \begin{figure}[h]
  6038. \begin{minipage}{0.8\textwidth}
  6039. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6040. (program
  6041. (define (f [x : Integer]) : (Integer -> Integer)
  6042. (let ([y 4])
  6043. (lambda: ([z : Integer]) : Integer
  6044. (+ x (+ y z)))))
  6045. (let ([g (f 5)])
  6046. (let ([h (f 3)])
  6047. (+ (g 11) (h 15)))))
  6048. \end{lstlisting}
  6049. $\Downarrow$
  6050. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6051. (program (type Integer)
  6052. (define (f (x : Integer)) : (Integer -> Integer)
  6053. (let ((y 4))
  6054. (lambda: ((z : Integer)) : Integer
  6055. (+ x (+ y z)))))
  6056. (let ((g (app (fun-ref f) 5)))
  6057. (let ((h (app (fun-ref f) 3)))
  6058. (+ (app g 11) (app h 15)))))
  6059. \end{lstlisting}
  6060. $\Downarrow$
  6061. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6062. (program (type Integer)
  6063. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6064. (let ((y 4))
  6065. (vector (fun-ref lam.1) x y)))
  6066. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6067. (let ((x (vector-ref clos.2 1)))
  6068. (let ((y (vector-ref clos.2 2)))
  6069. (+ x (+ y z)))))
  6070. (let ((g (let ((t.1 (vector (fun-ref f))))
  6071. (app (vector-ref t.1 0) t.1 5))))
  6072. (let ((h (let ((t.2 (vector (fun-ref f))))
  6073. (app (vector-ref t.2 0) t.2 3))))
  6074. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6075. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6076. \end{lstlisting}
  6077. \end{minipage}
  6078. \caption{Example of closure conversion.}
  6079. \label{fig:lexical-functions-example}
  6080. \end{figure}
  6081. \begin{figure}[p]
  6082. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6083. \node (R4) at (0,2) {\large $R_4$};
  6084. \node (R4-2) at (3,2) {\large $R_4$};
  6085. \node (R4-3) at (6,2) {\large $R_4$};
  6086. \node (F1-1) at (12,0) {\large $F_1$};
  6087. \node (F1-2) at (9,0) {\large $F_1$};
  6088. \node (F1-3) at (6,0) {\large $F_1$};
  6089. \node (F1-4) at (3,0) {\large $F_1$};
  6090. \node (F1-5) at (0,0) {\large $F_1$};
  6091. \node (C3-1) at (6,-2) {\large $C_3$};
  6092. \node (C3-2) at (3,-2) {\large $C_3$};
  6093. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6094. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6095. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6096. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6097. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6098. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6099. \path[->,bend left=15] (R4) edge [above] node
  6100. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6101. \path[->,bend left=15] (R4-2) edge [above] node
  6102. {\ttfamily\footnotesize uniquify} (R4-3);
  6103. \path[->] (R4-3) edge [right] node
  6104. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6105. \path[->,bend left=15] (F1-1) edge [below] node
  6106. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6107. \path[->,bend right=15] (F1-2) edge [above] node
  6108. {\ttfamily\footnotesize limit-functions} (F1-3);
  6109. \path[->,bend right=15] (F1-3) edge [above] node
  6110. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6111. \path[->,bend right=15] (F1-4) edge [above] node
  6112. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6113. \path[->] (F1-5) edge [left] node
  6114. {\ttfamily\footnotesize explicate-control} (C3-1);
  6115. \path[->,bend left=15] (C3-1) edge [below] node
  6116. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6117. \path[->,bend right=15] (C3-2) edge [left] node
  6118. {\ttfamily\footnotesize select-instr.} (x86-2);
  6119. \path[->,bend left=15] (x86-2) edge [left] node
  6120. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6121. \path[->,bend right=15] (x86-2-1) edge [below] node
  6122. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6123. \path[->,bend right=15] (x86-2-2) edge [left] node
  6124. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6125. \path[->,bend left=15] (x86-3) edge [above] node
  6126. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6127. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6128. \end{tikzpicture}
  6129. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6130. functions.}
  6131. \label{fig:R5-passes}
  6132. \end{figure}
  6133. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6134. for the compilation of $R_5$.
  6135. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6136. \chapter{Dynamic Typing}
  6137. \label{ch:type-dynamic}
  6138. In this chapter we discuss the compilation of a dynamically typed
  6139. language, named $R_7$, that is a subset of the Racket
  6140. language. (Recall that in the previous chapters we have studied
  6141. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6142. languages, an expression may produce values of differing
  6143. type. Consider the following example with a conditional expression
  6144. that may return a Boolean or an integer depending on the input to the
  6145. program.
  6146. \begin{lstlisting}
  6147. (not (if (eq? (read) 1) #f 0))
  6148. \end{lstlisting}
  6149. Languages that allow expressions to produce different kinds of values
  6150. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6151. such as subtype polymorphism and parametric
  6152. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6153. talking about here does not have a special name, but it is the usual
  6154. kind that arrises in dynamically typed languages.
  6155. Another characteristic of dynamically typed languages is that
  6156. primitive operations, such as \code{not}, are often defined to operate
  6157. on many different types of values. In fact, in Racket, the \code{not}
  6158. operator produces a result for any kind of value: given \code{\#f} it
  6159. returns \code{\#t} and given anything else it returns \code{\#f}.
  6160. Furthermore, even when primitive operations restrict their inputs to
  6161. values of a certain type, this restriction is enforced at runtime
  6162. instead of during compilation. For example, the following vector
  6163. reference results in a run-time contract violation.
  6164. \begin{lstlisting}
  6165. (vector-ref (vector 42) #t)
  6166. \end{lstlisting}
  6167. \begin{figure}[tp]
  6168. \centering
  6169. \fbox{
  6170. \begin{minipage}{0.97\textwidth}
  6171. \[
  6172. \begin{array}{rcl}
  6173. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6174. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6175. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6176. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6177. &\mid& \key{\#t} \mid \key{\#f}
  6178. \mid (\key{and}\;\Exp\;\Exp)
  6179. \mid (\key{or}\;\Exp\;\Exp)
  6180. \mid (\key{not}\;\Exp) \\
  6181. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6182. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6183. (\key{vector-ref}\;\Exp\;\Exp) \\
  6184. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6185. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6186. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6187. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6188. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6189. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6190. \end{array}
  6191. \]
  6192. \end{minipage}
  6193. }
  6194. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6195. \label{fig:r7-syntax}
  6196. \end{figure}
  6197. The syntax of $R_7$, our subset of Racket, is defined in
  6198. Figure~\ref{fig:r7-syntax}.
  6199. %
  6200. The definitional interpreter for $R_7$ is given in
  6201. Figure~\ref{fig:interp-R7}.
  6202. \begin{figure}[tbp]
  6203. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6204. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6205. (define (valid-op? op) (member op '(+ - and or not)))
  6206. (define (interp-r7 env)
  6207. (lambda (ast)
  6208. (define recur (interp-r7 env))
  6209. (match ast
  6210. [(? symbol?) (lookup ast env)]
  6211. [(? integer?) `(inject ,ast Integer)]
  6212. [#t `(inject #t Boolean)]
  6213. [#f `(inject #f Boolean)]
  6214. [`(read) `(inject ,(read-fixnum) Integer)]
  6215. [`(lambda (,xs ...) ,body)
  6216. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6217. [`(define (,f ,xs ...) ,body)
  6218. (mcons f `(lambda ,xs ,body))]
  6219. [`(program ,ds ... ,body)
  6220. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6221. (for/list ([b top-level])
  6222. (set-mcdr! b (match (mcdr b)
  6223. [`(lambda ,xs ,body)
  6224. `(inject (lambda ,xs ,body ,top-level)
  6225. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6226. ((interp-r7 top-level) body))]
  6227. [`(vector ,(app recur elts) ...)
  6228. (define tys (map get-tagged-type elts))
  6229. `(inject ,(apply vector elts) (Vector ,@tys))]
  6230. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6231. (match v1
  6232. [`(inject ,vec ,ty)
  6233. (vector-set! vec n v2)
  6234. `(inject (void) Void)])]
  6235. [`(vector-ref ,(app recur v) ,n)
  6236. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6237. [`(let ([,x ,(app recur v)]) ,body)
  6238. ((interp-r7 (cons (cons x v) env)) body)]
  6239. [`(,op ,es ...) #:when (valid-op? op)
  6240. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6241. [`(eq? ,(app recur l) ,(app recur r))
  6242. `(inject ,(equal? l r) Boolean)]
  6243. [`(if ,(app recur q) ,t ,f)
  6244. (match q
  6245. [`(inject #f Boolean) (recur f)]
  6246. [else (recur t)])]
  6247. [`(,(app recur f-val) ,(app recur vs) ...)
  6248. (match f-val
  6249. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6250. (define new-env (append (map cons xs vs) lam-env))
  6251. ((interp-r7 new-env) body)]
  6252. [else (error "interp-r7, expected function, not" f-val)])])))
  6253. \end{lstlisting}
  6254. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6255. \label{fig:interp-R7}
  6256. \end{figure}
  6257. Let us consider how we might compile $R_7$ to x86, thinking about the
  6258. first example above. Our bit-level representation of the Boolean
  6259. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6260. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6261. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6262. general, cannot be determined at compile time, but depends on the
  6263. runtime type of its input, as in the example above that depends on the
  6264. result of \code{(read)}.
  6265. The way around this problem is to include information about a value's
  6266. runtime type in the value itself, so that this information can be
  6267. inspected by operators such as \code{not}. In particular, we shall
  6268. steal the 3 right-most bits from our 64-bit values to encode the
  6269. runtime type. We shall use $001$ to identify integers, $100$ for
  6270. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6271. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6272. define the following auxilliary function.
  6273. \begin{align*}
  6274. \itm{tagof}(\key{Integer}) &= 001 \\
  6275. \itm{tagof}(\key{Boolean}) &= 100 \\
  6276. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6277. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6278. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6279. \itm{tagof}(\key{Void}) &= 101
  6280. \end{align*}
  6281. (We shall say more about the new \key{Vectorof} type shortly.)
  6282. This stealing of 3 bits comes at some
  6283. price: our integers are reduced to ranging from $-2^{60}$ to
  6284. $2^{60}$. The stealing does not adversely affect vectors and
  6285. procedures because those values are addresses, and our addresses are
  6286. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6287. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6288. bits with the tag and we can simply zero-out the tag to recover the
  6289. original address.
  6290. In some sense, these tagged values are a new kind of value. Indeed,
  6291. we can extend our \emph{typed} language with tagged values by adding a
  6292. new type to classify them, called \key{Any}, and with operations for
  6293. creating and using tagged values, yielding the $R_6$ language that we
  6294. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6295. fundamental support for polymorphism and runtime types that we need to
  6296. support dynamic typing.
  6297. There is an interesting interaction between tagged values and garbage
  6298. collection. A variable of type \code{Any} might refer to a vector and
  6299. therefore it might be a root that needs to be inspected and copied
  6300. during garbage collection. Thus, we need to treat variables of type
  6301. \code{Any} in a similar way to variables of type \code{Vector} for
  6302. purposes of register allocation, which we discuss in
  6303. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6304. variable of type \code{Any} is spilled, it must be spilled to the root
  6305. stack. But this means that the garbage collector needs to be able to
  6306. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6307. value that points to a tuple, and (3) a tagged value that is not a
  6308. tuple. We enable this differentiation by choosing not to use the tag
  6309. $000$. Instead, that bit pattern is reserved for identifying plain old
  6310. pointers to tuples. On the other hand, if one of the first three bits
  6311. is set, then we have a tagged value, and inspecting the tag can
  6312. differentiation between vectors ($010$) and the other kinds of values.
  6313. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6314. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6315. extend our compiler to handle the new features of $R_6$
  6316. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6317. \ref{sec:register-allocation-r6}).
  6318. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6319. \label{sec:r6-lang}
  6320. \begin{figure}[tp]
  6321. \centering
  6322. \fbox{
  6323. \begin{minipage}{0.97\textwidth}
  6324. \[
  6325. \begin{array}{lcl}
  6326. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6327. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6328. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6329. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6330. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6331. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6332. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6333. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6334. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6335. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6336. \mid (\key{and}\;\Exp\;\Exp)
  6337. \mid (\key{or}\;\Exp\;\Exp)
  6338. \mid (\key{not}\;\Exp)} \\
  6339. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6340. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6341. (\key{vector-ref}\;\Exp\;\Int)} \\
  6342. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6343. &\mid& \gray{(\Exp \; \Exp^{*})
  6344. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6345. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6346. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6347. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6348. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6349. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6350. \end{array}
  6351. \]
  6352. \end{minipage}
  6353. }
  6354. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6355. with \key{Any}.}
  6356. \label{fig:r6-syntax}
  6357. \end{figure}
  6358. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6359. $(\key{inject}\; e\; T)$ form converts the value produced by
  6360. expression $e$ of type $T$ into a tagged value. The
  6361. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6362. expression $e$ into a value of type $T$ or else halts the program if
  6363. the type tag is equivalent to $T$. We treat
  6364. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6365. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6366. Note that in both \key{inject} and
  6367. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6368. which simplifies the implementation and corresponds with what is
  6369. needed for compiling untyped Racket. The type predicates,
  6370. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6371. if the tag corresponds to the predicate, and return \key{\#t}
  6372. otherwise.
  6373. %
  6374. Selections from the type checker for $R_6$ are shown in
  6375. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6376. Figure~\ref{fig:interp-R6}.
  6377. \begin{figure}[btp]
  6378. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6379. (define (flat-ty? ty) ...)
  6380. (define (typecheck-R6 env)
  6381. (lambda (e)
  6382. (define recur (typecheck-R6 env))
  6383. (match e
  6384. [`(inject ,e ,ty)
  6385. (unless (flat-ty? ty)
  6386. (error "may only inject a value of flat type, not ~a" ty))
  6387. (define-values (new-e e-ty) (recur e))
  6388. (cond
  6389. [(equal? e-ty ty)
  6390. (values `(inject ,new-e ,ty) 'Any)]
  6391. [else
  6392. (error "inject expected ~a to have type ~a" e ty)])]
  6393. [`(project ,e ,ty)
  6394. (unless (flat-ty? ty)
  6395. (error "may only project to a flat type, not ~a" ty))
  6396. (define-values (new-e e-ty) (recur e))
  6397. (cond
  6398. [(equal? e-ty 'Any)
  6399. (values `(project ,new-e ,ty) ty)]
  6400. [else
  6401. (error "project expected ~a to have type Any" e)])]
  6402. [`(vector-ref ,e ,i)
  6403. (define-values (new-e e-ty) (recur e))
  6404. (match e-ty
  6405. [`(Vector ,ts ...) ...]
  6406. [`(Vectorof ,ty)
  6407. (unless (exact-nonnegative-integer? i)
  6408. (error 'type-check "invalid index ~a" i))
  6409. (values `(vector-ref ,new-e ,i) ty)]
  6410. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6411. ...
  6412. )))
  6413. \end{lstlisting}
  6414. \caption{Type checker for parts of the $R_6$ language.}
  6415. \label{fig:typecheck-R6}
  6416. \end{figure}
  6417. % to do: add rules for vector-ref, etc. for Vectorof
  6418. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6419. \begin{figure}[btp]
  6420. \begin{lstlisting}
  6421. (define primitives (set 'boolean? ...))
  6422. (define (interp-op op)
  6423. (match op
  6424. ['boolean? (lambda (v)
  6425. (match v
  6426. [`(tagged ,v1 Boolean) #t]
  6427. [else #f]))]
  6428. ...))
  6429. ;; Equavalence of flat types
  6430. (define (tyeq? t1 t2)
  6431. (match `(,t1 ,t2)
  6432. [`((Vectorof Any) (Vector ,t2s ...))
  6433. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6434. [`((Vector ,t1s ...) (Vectorof Any))
  6435. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6436. [else (equal? t1 t2)]))
  6437. (define (interp-R6 env)
  6438. (lambda (ast)
  6439. (match ast
  6440. [`(inject ,e ,t)
  6441. `(tagged ,((interp-R6 env) e) ,t)]
  6442. [`(project ,e ,t2)
  6443. (define v ((interp-R6 env) e))
  6444. (match v
  6445. [`(tagged ,v1 ,t1)
  6446. (cond [(tyeq? t1 t2)
  6447. v1]
  6448. [else
  6449. (error "in project, type mismatch" t1 t2)])]
  6450. [else
  6451. (error "in project, expected tagged value" v)])]
  6452. ...)))
  6453. \end{lstlisting}
  6454. \caption{Interpreter for $R_6$.}
  6455. \label{fig:interp-R6}
  6456. \end{figure}
  6457. %\clearpage
  6458. \section{Shrinking $R_6$}
  6459. \label{sec:shrink-r6}
  6460. In the \code{shrink} pass we recommend compiling \code{project} into
  6461. an explicit \code{if} expression that uses three new operations:
  6462. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6463. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6464. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6465. value from a tagged value. Finally, the \code{exit} operation ends the
  6466. execution of the program by invoking the operating system's
  6467. \code{exit} function. So the translation for \code{project} is as
  6468. follows. (We have ommitted the \code{has-type} AST nodes to make this
  6469. output more readable.)
  6470. \begin{tabular}{lll}
  6471. \begin{minipage}{0.3\textwidth}
  6472. \begin{lstlisting}
  6473. (project |$e$| |$\Type$|)
  6474. \end{lstlisting}
  6475. \end{minipage}
  6476. &
  6477. $\Rightarrow$
  6478. &
  6479. \begin{minipage}{0.5\textwidth}
  6480. \begin{lstlisting}
  6481. (let ([|$\itm{tmp}$| |$e'$|])
  6482. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6483. (value-of-any |$\itm{tmp}$|)
  6484. (exit)))
  6485. \end{lstlisting}
  6486. \end{minipage}
  6487. \end{tabular} \\
  6488. Similarly, we recommend translating the type predicates
  6489. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6490. \section{Instruction Selection for $R_6$}
  6491. \label{sec:select-r6}
  6492. \paragraph{Inject}
  6493. We recommend compiling an \key{inject} as follows if the type is
  6494. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6495. destination to the left by the number of bits specified its source
  6496. argument (in this case $3$, the length of the tag) and it preserves
  6497. the sign of the integer. We use the \key{orq} instruction to combine
  6498. the tag and the value to form the tagged value. \\
  6499. \begin{tabular}{lll}
  6500. \begin{minipage}{0.4\textwidth}
  6501. \begin{lstlisting}
  6502. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6503. \end{lstlisting}
  6504. \end{minipage}
  6505. &
  6506. $\Rightarrow$
  6507. &
  6508. \begin{minipage}{0.5\textwidth}
  6509. \begin{lstlisting}
  6510. (movq |$e'$| |\itm{lhs}'|)
  6511. (salq (int 3) |\itm{lhs}'|)
  6512. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6513. \end{lstlisting}
  6514. \end{minipage}
  6515. \end{tabular} \\
  6516. The instruction selection for vectors and procedures is different
  6517. because their is no need to shift them to the left. The rightmost 3
  6518. bits are already zeros as described above. So we just combine the
  6519. value and the tag using \key{orq}. \\
  6520. \begin{tabular}{lll}
  6521. \begin{minipage}{0.4\textwidth}
  6522. \begin{lstlisting}
  6523. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6524. \end{lstlisting}
  6525. \end{minipage}
  6526. &
  6527. $\Rightarrow$
  6528. &
  6529. \begin{minipage}{0.5\textwidth}
  6530. \begin{lstlisting}
  6531. (movq |$e'$| |\itm{lhs}'|)
  6532. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6533. \end{lstlisting}
  6534. \end{minipage}
  6535. \end{tabular}
  6536. \paragraph{Tag of Any}
  6537. Recall that the \code{tag-of-any} operation extracts the type tag from
  6538. a value of type \code{Any}. The type tag is the bottom three bits, so
  6539. we obtain the tag by taking the bitwise-and of the value with $111$
  6540. ($7$ in decimal).
  6541. \begin{tabular}{lll}
  6542. \begin{minipage}{0.4\textwidth}
  6543. \begin{lstlisting}
  6544. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6545. \end{lstlisting}
  6546. \end{minipage}
  6547. &
  6548. $\Rightarrow$
  6549. &
  6550. \begin{minipage}{0.5\textwidth}
  6551. \begin{lstlisting}
  6552. (movq |$e'$| |\itm{lhs}'|)
  6553. (andq (int 7) |\itm{lhs}'|)
  6554. \end{lstlisting}
  6555. \end{minipage}
  6556. \end{tabular}
  6557. \paragraph{Value of Any}
  6558. Like \key{inject}, the instructions for \key{value-of-any} are
  6559. different depending on whether the type $T$ is a pointer (vector or
  6560. procedure) or not (Integer or Boolean). The following shows the
  6561. instruction selection for Integer and Boolean. We produce an untagged
  6562. value by shifting it to the right by 3 bits.
  6563. %
  6564. \\
  6565. \begin{tabular}{lll}
  6566. \begin{minipage}{0.4\textwidth}
  6567. \begin{lstlisting}
  6568. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6569. \end{lstlisting}
  6570. \end{minipage}
  6571. &
  6572. $\Rightarrow$
  6573. &
  6574. \begin{minipage}{0.5\textwidth}
  6575. \begin{lstlisting}
  6576. (movq |$e'$| |\itm{lhs}'|)
  6577. (sarq (int 3) |\itm{lhs}'|)
  6578. \end{lstlisting}
  6579. \end{minipage}
  6580. \end{tabular} \\
  6581. %
  6582. In the case for vectors and procedures, there is no need to
  6583. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6584. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6585. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6586. \code{movq} into the destination $\itm{lhs}$. We then generate
  6587. \code{andq} with the tagged value to get the desired result. \\
  6588. %
  6589. \begin{tabular}{lll}
  6590. \begin{minipage}{0.4\textwidth}
  6591. \begin{lstlisting}
  6592. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6593. \end{lstlisting}
  6594. \end{minipage}
  6595. &
  6596. $\Rightarrow$
  6597. &
  6598. \begin{minipage}{0.5\textwidth}
  6599. \begin{lstlisting}
  6600. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6601. (andq |$e'$| |\itm{lhs}'|)
  6602. \end{lstlisting}
  6603. \end{minipage}
  6604. \end{tabular}
  6605. %% \paragraph{Type Predicates} We leave it to the reader to
  6606. %% devise a sequence of instructions to implement the type predicates
  6607. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6608. \section{Register Allocation for $R_6$}
  6609. \label{sec:register-allocation-r6}
  6610. As mentioned above, a variable of type \code{Any} might refer to a
  6611. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6612. of type \code{Any} in the same way that it treats variables of type
  6613. \code{Vector} for purposes of garbage collection. In particular,
  6614. \begin{itemize}
  6615. \item If a variable of type \code{Any} is live during a function call,
  6616. then it must be spilled. One way to accomplish this is to augment
  6617. the pass \code{build-interference} to mark all variables that are
  6618. live after a \code{callq} as interfering with all the registers.
  6619. \item If avariable of type \code{Any} is spilled, it must be spilled
  6620. to the root stack instead of the normal procedure call stack.
  6621. \end{itemize}
  6622. \section{Compiling $R_7$ to $R_6$}
  6623. \label{sec:compile-r7}
  6624. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6625. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6626. given a subexpression $e$ of $R_7$, the pass will produce an
  6627. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6628. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6629. the Boolean \code{\#t}, which must be injected to produce an
  6630. expression of type \key{Any}.
  6631. %
  6632. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6633. addition, is representative of compilation for many operations: the
  6634. arguments have type \key{Any} and must be projected to \key{Integer}
  6635. before the addition can be performed.
  6636. The compilation of \key{lambda} (third row of
  6637. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6638. produce type annotations: we simply use \key{Any}.
  6639. %
  6640. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6641. has to account for some differences in behavior between $R_7$ and
  6642. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6643. kind of values can be used in various places. For example, the
  6644. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6645. the arguments need not be of the same type (but in that case, the
  6646. result will be \code{\#f}).
  6647. \begin{figure}[btp]
  6648. \centering
  6649. \begin{tabular}{|lll|} \hline
  6650. \begin{minipage}{0.25\textwidth}
  6651. \begin{lstlisting}
  6652. #t
  6653. \end{lstlisting}
  6654. \end{minipage}
  6655. &
  6656. $\Rightarrow$
  6657. &
  6658. \begin{minipage}{0.6\textwidth}
  6659. \begin{lstlisting}
  6660. (inject #t Boolean)
  6661. \end{lstlisting}
  6662. \end{minipage}
  6663. \\[2ex]\hline
  6664. \begin{minipage}{0.25\textwidth}
  6665. \begin{lstlisting}
  6666. (+ |$e_1$| |$e_2$|)
  6667. \end{lstlisting}
  6668. \end{minipage}
  6669. &
  6670. $\Rightarrow$
  6671. &
  6672. \begin{minipage}{0.6\textwidth}
  6673. \begin{lstlisting}
  6674. (inject
  6675. (+ (project |$e'_1$| Integer)
  6676. (project |$e'_2$| Integer))
  6677. Integer)
  6678. \end{lstlisting}
  6679. \end{minipage}
  6680. \\[2ex]\hline
  6681. \begin{minipage}{0.25\textwidth}
  6682. \begin{lstlisting}
  6683. (lambda (|$x_1 \ldots$|) |$e$|)
  6684. \end{lstlisting}
  6685. \end{minipage}
  6686. &
  6687. $\Rightarrow$
  6688. &
  6689. \begin{minipage}{0.6\textwidth}
  6690. \begin{lstlisting}
  6691. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6692. (Any|$\ldots$|Any -> Any))
  6693. \end{lstlisting}
  6694. \end{minipage}
  6695. \\[2ex]\hline
  6696. \begin{minipage}{0.25\textwidth}
  6697. \begin{lstlisting}
  6698. (app |$e_0$| |$e_1 \ldots e_n$|)
  6699. \end{lstlisting}
  6700. \end{minipage}
  6701. &
  6702. $\Rightarrow$
  6703. &
  6704. \begin{minipage}{0.6\textwidth}
  6705. \begin{lstlisting}
  6706. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6707. |$e'_1 \ldots e'_n$|)
  6708. \end{lstlisting}
  6709. \end{minipage}
  6710. \\[2ex]\hline
  6711. \begin{minipage}{0.25\textwidth}
  6712. \begin{lstlisting}
  6713. (vector-ref |$e_1$| |$e_2$|)
  6714. \end{lstlisting}
  6715. \end{minipage}
  6716. &
  6717. $\Rightarrow$
  6718. &
  6719. \begin{minipage}{0.6\textwidth}
  6720. \begin{lstlisting}
  6721. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6722. (let ([tmp2 (project |$e'_2$| Integer)])
  6723. (vector-ref tmp1 tmp2)))
  6724. \end{lstlisting}
  6725. \end{minipage}
  6726. \\[2ex]\hline
  6727. \begin{minipage}{0.25\textwidth}
  6728. \begin{lstlisting}
  6729. (if |$e_1$| |$e_2$| |$e_3$|)
  6730. \end{lstlisting}
  6731. \end{minipage}
  6732. &
  6733. $\Rightarrow$
  6734. &
  6735. \begin{minipage}{0.6\textwidth}
  6736. \begin{lstlisting}
  6737. (if (eq? |$e'_1$| (inject #f Boolean))
  6738. |$e'_3$|
  6739. |$e'_2$|)
  6740. \end{lstlisting}
  6741. \end{minipage}
  6742. \\[2ex]\hline
  6743. \begin{minipage}{0.25\textwidth}
  6744. \begin{lstlisting}
  6745. (eq? |$e_1$| |$e_2$|)
  6746. \end{lstlisting}
  6747. \end{minipage}
  6748. &
  6749. $\Rightarrow$
  6750. &
  6751. \begin{minipage}{0.6\textwidth}
  6752. \begin{lstlisting}
  6753. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6754. \end{lstlisting}
  6755. \end{minipage}
  6756. \\[2ex]\hline
  6757. \end{tabular}
  6758. \caption{Compiling $R_7$ to $R_6$.}
  6759. \label{fig:compile-r7-r6}
  6760. \end{figure}
  6761. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6762. \chapter{Gradual Typing}
  6763. \label{ch:gradual-typing}
  6764. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6765. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6766. \chapter{Parametric Polymorphism}
  6767. \label{ch:parametric-polymorphism}
  6768. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6769. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6770. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6771. \chapter{High-level Optimization}
  6772. \label{ch:high-level-optimization}
  6773. This chapter will present a procedure inlining pass based on the
  6774. algorithm of \citet{Waddell:1997fk}.
  6775. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6776. \chapter{Appendix}
  6777. \section{Interpreters}
  6778. \label{appendix:interp}
  6779. We provide several interpreters in the \key{interp.rkt} file. The
  6780. \key{interp-scheme} function takes an AST in one of the Racket-like
  6781. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6782. the program, returning the result value. The \key{interp-C} function
  6783. interprets an AST for a program in one of the C-like languages ($C_0,
  6784. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6785. for an x86 program.
  6786. \section{Utility Functions}
  6787. \label{appendix:utilities}
  6788. The utility function described in this section can be found in the
  6789. \key{utilities.rkt} file.
  6790. The \key{read-program} function takes a file path and parses that file
  6791. (it must be a Racket program) into an abstract syntax tree (as an
  6792. S-expression) with a \key{program} AST at the top.
  6793. The \key{assert} function displays the error message \key{msg} if the
  6794. Boolean \key{bool} is false.
  6795. \begin{lstlisting}
  6796. (define (assert msg bool) ...)
  6797. \end{lstlisting}
  6798. The \key{lookup} function takes a key and an association list (a list
  6799. of key-value pairs), and returns the first value that is associated
  6800. with the given key, if there is one. If not, an error is triggered.
  6801. The association list may contain both immutable pairs (built with
  6802. \key{cons}) and mutable mapirs (built with \key{mcons}).
  6803. The \key{map2} function ...
  6804. %% \subsection{Graphs}
  6805. %% \begin{itemize}
  6806. %% \item The \code{make-graph} function takes a list of vertices
  6807. %% (symbols) and returns a graph.
  6808. %% \item The \code{add-edge} function takes a graph and two vertices and
  6809. %% adds an edge to the graph that connects the two vertices. The graph
  6810. %% is updated in-place. There is no return value for this function.
  6811. %% \item The \code{adjacent} function takes a graph and a vertex and
  6812. %% returns the set of vertices that are adjacent to the given
  6813. %% vertex. The return value is a Racket \code{hash-set} so it can be
  6814. %% used with functions from the \code{racket/set} module.
  6815. %% \item The \code{vertices} function takes a graph and returns the list
  6816. %% of vertices in the graph.
  6817. %% \end{itemize}
  6818. \subsection{Testing}
  6819. The \key{interp-tests} function takes a compiler name (a string), a
  6820. description of the passes, an interpreter for the source language, a
  6821. test family name (a string), and a list of test numbers, and runs the
  6822. compiler passes and the interpreters to check whether the passes
  6823. correct. The description of the passes is a list with one entry per
  6824. pass. An entry is a list with three things: a string giving the name
  6825. of the pass, the function that implements the pass (a translator from
  6826. AST to AST), and a function that implements the interpreter (a
  6827. function from AST to result value) for the language of the output of
  6828. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6829. good choice. The \key{interp-tests} function assumes that the
  6830. subdirectory \key{tests} has a bunch of Scheme programs whose names
  6831. all start with the family name, followed by an underscore and then the
  6832. test number, ending in \key{.scm}. Also, for each Scheme program there
  6833. is a file with the same number except that it ends with \key{.in} that
  6834. provides the input for the Scheme program.
  6835. \begin{lstlisting}
  6836. (define (interp-tests name passes test-family test-nums) ...
  6837. \end{lstlisting}
  6838. The compiler-tests function takes a compiler name (a string) a
  6839. description of the passes (see the comment for \key{interp-tests}) a
  6840. test family name (a string), and a list of test numbers (see the
  6841. comment for interp-tests), and runs the compiler to generate x86 (a
  6842. \key{.s} file) and then runs gcc to generate machine code. It runs
  6843. the machine code and checks that the output is 42.
  6844. \begin{lstlisting}
  6845. (define (compiler-tests name passes test-family test-nums) ...)
  6846. \end{lstlisting}
  6847. The compile-file function takes a description of the compiler passes
  6848. (see the comment for \key{interp-tests}) and returns a function that,
  6849. given a program file name (a string ending in \key{.scm}), applies all
  6850. of the passes and writes the output to a file whose name is the same
  6851. as the program file name but with \key{.scm} replaced with \key{.s}.
  6852. \begin{lstlisting}
  6853. (define (compile-file passes)
  6854. (lambda (prog-file-name) ...))
  6855. \end{lstlisting}
  6856. \section{x86 Instruction Set Quick-Reference}
  6857. \label{sec:x86-quick-reference}
  6858. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6859. do. We write $A \to B$ to mean that the value of $A$ is written into
  6860. location $B$. Address offsets are given in bytes. The instruction
  6861. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6862. registers (such as $\%rax$), or memory references (such as
  6863. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6864. reference per instruction. Other operands must be immediates or
  6865. registers.
  6866. \begin{table}[tbp]
  6867. \centering
  6868. \begin{tabular}{l|l}
  6869. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6870. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6871. \texttt{negq} $A$ & $- A \to A$ \\
  6872. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6873. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6874. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6875. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6876. \texttt{retq} & Pops the return address and jumps to it \\
  6877. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6878. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6879. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6880. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6881. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6882. matches the condition code of the instruction, otherwise go to the
  6883. next instructions. The condition codes are \key{e} for ``equal'',
  6884. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6885. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6886. \texttt{jl} $L$ & \\
  6887. \texttt{jle} $L$ & \\
  6888. \texttt{jg} $L$ & \\
  6889. \texttt{jge} $L$ & \\
  6890. \texttt{jmp} $L$ & Jump to label $L$ \\
  6891. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6892. \texttt{movzbq} $A$, $B$ &
  6893. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6894. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6895. and the extra bytes of $B$ are set to zero.} \\
  6896. & \\
  6897. & \\
  6898. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6899. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6900. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6901. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6902. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6903. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6904. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6905. description of the condition codes. $A$ must be a single byte register
  6906. (e.g., \texttt{al} or \texttt{cl}).} \\
  6907. \texttt{setl} $A$ & \\
  6908. \texttt{setle} $A$ & \\
  6909. \texttt{setg} $A$ & \\
  6910. \texttt{setge} $A$ &
  6911. \end{tabular}
  6912. \vspace{5pt}
  6913. \caption{Quick-reference for the x86 instructions used in this book.}
  6914. \label{tab:x86-instr}
  6915. \end{table}
  6916. \bibliographystyle{plainnat}
  6917. \bibliography{all}
  6918. \end{document}
  6919. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6920. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6921. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6922. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6923. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6924. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6925. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6926. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6927. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6928. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6929. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6930. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6931. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6932. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6933. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6934. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6935. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6936. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6937. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6938. %% LocalWords: len prev rootlen heaplen setl lt