book.tex 279 KB

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