book.tex 350 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses about programming languages by Daniel Friedman in
  151. the 1970's and 1980's. Dan conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, Kent returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Kent continued development of Chez
  162. Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Dan's ideas was to split the compiler into many small ``passes'' so
  166. that the code for each pass would be easy to understood in isolation.
  167. (In contrast, most compilers of the time were organized into only a
  168. few monolithic passes for reasons of compile-time efficiency.) Kent,
  169. with later help from his students Dipanwita Sarkar and Andrew Keep,
  170. developed infrastructure to support this approach and evolved the
  171. course, first to use micro-sized passes and then into even smaller
  172. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  173. student in this compiler course in the early 2000's, as part of his
  174. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  175. the course immensely!
  176. During that time, another student named Abdulaziz Ghuloum observed
  177. that the front-to-back organization of the course made it difficult
  178. for students to understand the rationale for the compiler
  179. design. Abdulaziz proposed an incremental approach in which the
  180. students build the compiler in stages; they start by implementing a
  181. complete compiler for a very small subset of the input language and in
  182. each subsequent stage they add a language feature and add or modify
  183. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  184. the students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, Jeremy went on to
  187. teach at the University of Colorado. He adapted the nano pass and
  188. incremental approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, Jeremy was able to teach much of
  192. the same content from the Indiana compiler course. He very much
  193. enjoyed teaching the course organized in this way, and even better,
  194. many of the students learned a lot and got excited about compilers.
  195. Jeremy returned to teach at Indiana University in 2013. In his
  196. absence the compiler course had switched from the front-to-back
  197. organization to a back-to-front organization. Seeing how well the
  198. incremental approach worked at Colorado, he started porting and
  199. adapting the structure of the Colorado course back into the land of
  200. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  201. the course is now about compiling a subset of Racket (and Typed
  202. Racket) to the x86 assembly language. The compiler is implemented in
  203. Racket 7.1~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book we
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study in Bloomington in person. Many of the
  209. compiler design decisions in this book are drawn from the assignment
  210. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  211. are the most important topics from \cite{Dybvig:2010aa} but we have
  212. omitted topics that we think are less interesting conceptually and we
  213. have made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we saw the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  226. is helpful but not necessary for the student to have prior exposure to
  227. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  228. obtain from a computer systems
  229. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %\section*{Structure of book}
  232. % You might want to add short description about each chapter in this book.
  233. %\section*{About the companion website}
  234. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  235. %\begin{itemize}
  236. % \item A link to (freely downlodable) latest version of this document.
  237. % \item Link to download LaTeX source for this document.
  238. % \item Miscellaneous material (e.g. suggested readings etc).
  239. %\end{itemize}
  240. \section*{Acknowledgments}
  241. Many people have contributed to the ideas, techniques, organization,
  242. and teaching of the materials in this book. We especially thank the
  243. following people.
  244. \begin{itemize}
  245. \item Bor-Yuh Evan Chang
  246. \item Kent Dybvig
  247. \item Daniel P. Friedman
  248. \item Ronald Garcia
  249. \item Abdulaziz Ghuloum
  250. \item Jay McCarthy
  251. \item Dipanwita Sarkar
  252. \item Andrew Keep
  253. \item Oscar Waddell
  254. \item Michael Wollowski
  255. \end{itemize}
  256. \mbox{}\\
  257. \noindent Jeremy G. Siek \\
  258. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  259. %\noindent Spring 2016
  260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  261. \chapter{Preliminaries}
  262. \label{ch:trees-recur}
  263. In this chapter we review the basic tools that are needed to implement
  264. a compiler. Programs are typically input by a programmer as text,
  265. i.e., a sequence of characters. The program-as-text representation is
  266. called \emph{concrete syntax}. We use concrete syntax to concisely
  267. write down and talk about programs. Inside the compiler, we use
  268. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  269. that efficiently supports the operations that the compiler needs to
  270. perform.
  271. \index{concrete syntax}
  272. \index{abstract syntax}
  273. \index{abstract syntax tree}
  274. \index{AST}
  275. \index{program}
  276. \index{parse}
  277. %
  278. The translation from concrete syntax to abstract syntax is a process
  279. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  280. and implementation of parsing in this book. A parser is provided in
  281. the supporting materials for translating from concrete syntax to
  282. abstract syntax for the languages used in this book.
  283. ASTs can be represented in many different ways inside the compiler,
  284. depending on the programming language used to write the compiler.
  285. %
  286. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  287. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  288. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  289. and pattern matching to inspect individual nodes in an AST
  290. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  291. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  292. chapter provides an brief introduction to these ideas.
  293. \index{struct}
  294. \section{Abstract Syntax Trees and Racket Structures}
  295. \label{sec:ast}
  296. Compilers use abstract syntax trees to represent programs because
  297. compilers often need to ask questions like: for a given part of a
  298. program, what kind of language feature is it? What are the sub-parts
  299. of this part of the program? Consider the program on the left and its
  300. AST on the right. This program is an addition and it has two
  301. sub-parts, a read operation and a negation. The negation has another
  302. sub-part, the integer constant \code{8}. By using a tree to represent
  303. the program, we can easily follow the links to go from one part of a
  304. program to its sub-parts.
  305. \begin{center}
  306. \begin{minipage}{0.4\textwidth}
  307. \begin{lstlisting}
  308. (+ (read) (- 8))
  309. \end{lstlisting}
  310. \end{minipage}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{equation}
  313. \begin{tikzpicture}
  314. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  315. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  316. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  317. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  318. \draw[->] (plus) to (read);
  319. \draw[->] (plus) to (minus);
  320. \draw[->] (minus) to (8);
  321. \end{tikzpicture}
  322. \label{eq:arith-prog}
  323. \end{equation}
  324. \end{minipage}
  325. \end{center}
  326. We use the standard terminology for trees to describe ASTs: each
  327. circle above is called a \emph{node}. The arrows connect a node to its
  328. \emph{children} (which are also nodes). The top-most node is the
  329. \emph{root}. Every node except for the root has a \emph{parent} (the
  330. node it is the child of). If a node has no children, it is a
  331. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  332. \index{node}
  333. \index{children}
  334. \index{root}
  335. \index{parent}
  336. \index{leaf}
  337. \index{internal node}
  338. %% Recall that an \emph{symbolic expression} (S-expression) is either
  339. %% \begin{enumerate}
  340. %% \item an atom, or
  341. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  342. %% where $e_1$ and $e_2$ are each an S-expression.
  343. %% \end{enumerate}
  344. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  345. %% null value \code{'()}, etc. We can create an S-expression in Racket
  346. %% simply by writing a backquote (called a quasi-quote in Racket)
  347. %% followed by the textual representation of the S-expression. It is
  348. %% quite common to use S-expressions to represent a list, such as $a, b
  349. %% ,c$ in the following way:
  350. %% \begin{lstlisting}
  351. %% `(a . (b . (c . ())))
  352. %% \end{lstlisting}
  353. %% Each element of the list is in the first slot of a pair, and the
  354. %% second slot is either the rest of the list or the null value, to mark
  355. %% the end of the list. Such lists are so common that Racket provides
  356. %% special notation for them that removes the need for the periods
  357. %% and so many parenthesis:
  358. %% \begin{lstlisting}
  359. %% `(a b c)
  360. %% \end{lstlisting}
  361. %% The following expression creates an S-expression that represents AST
  362. %% \eqref{eq:arith-prog}.
  363. %% \begin{lstlisting}
  364. %% `(+ (read) (- 8))
  365. %% \end{lstlisting}
  366. %% When using S-expressions to represent ASTs, the convention is to
  367. %% represent each AST node as a list and to put the operation symbol at
  368. %% the front of the list. The rest of the list contains the children. So
  369. %% in the above case, the root AST node has operation \code{`+} and its
  370. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  371. %% diagram \eqref{eq:arith-prog}.
  372. %% To build larger S-expressions one often needs to splice together
  373. %% several smaller S-expressions. Racket provides the comma operator to
  374. %% splice an S-expression into a larger one. For example, instead of
  375. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  376. %% we could have first created an S-expression for AST
  377. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  378. %% S-expression.
  379. %% \begin{lstlisting}
  380. %% (define ast1.4 `(- 8))
  381. %% (define ast1.1 `(+ (read) ,ast1.4))
  382. %% \end{lstlisting}
  383. %% In general, the Racket expression that follows the comma (splice)
  384. %% can be any expression that produces an S-expression.
  385. We define a Racket \code{struct} for each kind of node. For this
  386. chapter we require just two kinds of nodes: one for integer constants
  387. and one for primitive operations. The following is the \code{struct}
  388. definition for integer constants.
  389. \begin{lstlisting}
  390. (struct Int (value))
  391. \end{lstlisting}
  392. An integer node includes just one thing: the integer value.
  393. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  394. \begin{lstlisting}
  395. (define eight (Int 8))
  396. \end{lstlisting}
  397. We say that the value created by \code{(Int 8)} is an
  398. \emph{instance} of the \code{Int} structure.
  399. The following is the \code{struct} definition for primitives operations.
  400. \begin{lstlisting}
  401. (struct Prim (op arg*))
  402. \end{lstlisting}
  403. A primitive operation node includes an operator symbol \code{op}
  404. and a list of children \code{arg*}. For example, to create
  405. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  406. \begin{lstlisting}
  407. (define neg-eight (Prim '- (list eight)))
  408. \end{lstlisting}
  409. Primitive operations may have zero or more children. The \code{read}
  410. operator has zero children:
  411. \begin{lstlisting}
  412. (define rd (Prim 'read '()))
  413. \end{lstlisting}
  414. whereas the addition operator has two children:
  415. \begin{lstlisting}
  416. (define ast1.1 (Prim '+ (list rd neg-eight)))
  417. \end{lstlisting}
  418. We have made a design choice regarding the \code{Prim} structure.
  419. Instead of using one structure for many different operations
  420. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  421. structure for each operation, as follows.
  422. \begin{lstlisting}
  423. (struct Read ())
  424. (struct Add (left right))
  425. (struct Neg (value))
  426. \end{lstlisting}
  427. The reason we choose to use just one structure is that in many parts
  428. of the compiler the code for the different primitive operators is the
  429. same, so we might as well just write that code once, which is enabled
  430. by using a single structure.
  431. When compiling a program such as \eqref{eq:arith-prog}, we need to
  432. know that the operation associated with the root node is addition and
  433. we need to be able to access its two children. Racket provides pattern
  434. matching over structures to support these kinds of queries, as we
  435. see in Section~\ref{sec:pattern-matching}.
  436. In this book, we often write down the concrete syntax of a program
  437. even when we really have in mind the AST because the concrete syntax
  438. is more concise. We recommend that, in your mind, you always think of
  439. programs as abstract syntax trees.
  440. \section{Grammars}
  441. \label{sec:grammar}
  442. \index{integer}
  443. \index{literal}
  444. \index{constant}
  445. A programming language can be thought of as a \emph{set} of programs.
  446. The set is typically infinite (one can always create larger and larger
  447. programs), so one cannot simply describe a language by listing all of
  448. the programs in the language. Instead we write down a set of rules, a
  449. \emph{grammar}, for building programs. Grammars are often used to
  450. define the concrete syntax of a language, but they can also be used to
  451. describe the abstract syntax. We write our rules in a variant of
  452. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  453. \index{Backus-Naur Form}\index{BNF}
  454. As an example, we describe a small language, named $R_0$, that consists of
  455. integers and arithmetic operations.
  456. \index{grammar}
  457. The first grammar rule for the abstract syntax of $R_0$ says that an
  458. instance of the \code{Int} structure is an expression:
  459. \begin{equation}
  460. \Exp ::= \INT{\Int} \label{eq:arith-int}
  461. \end{equation}
  462. %
  463. Each rule has a left-hand-side and a right-hand-side. The way to read
  464. a rule is that if you have all the program parts on the
  465. right-hand-side, then you can create an AST node and categorize it
  466. according to the left-hand-side.
  467. %
  468. A name such as $\Exp$ that is
  469. defined by the grammar rules is a \emph{non-terminal}.
  470. \index{non-terminal}
  471. %
  472. The name $\Int$ is a also a non-terminal, but instead of defining it
  473. with a grammar rule, we define it with the following explanation. We
  474. make the simplifying design decision that all of the languages in this
  475. book only handle machine-representable integers. On most modern
  476. machines this corresponds to integers represented with 64-bits, i.e.,
  477. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  478. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  479. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  480. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  481. that the sequence of decimals represent an integer in range $-2^{62}$
  482. to $2^{62}-1$.
  483. The second grammar rule is the \texttt{read} operation that receives
  484. an input integer from the user of the program.
  485. \begin{equation}
  486. \Exp ::= \READ{} \label{eq:arith-read}
  487. \end{equation}
  488. The third rule says that, given an $\Exp$ node, you can build another
  489. $\Exp$ node by negating it.
  490. \begin{equation}
  491. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  492. \end{equation}
  493. Symbols in typewriter font such as \key{-} and \key{read} are
  494. \emph{terminal} symbols and must literally appear in the program for
  495. the rule to be applicable.
  496. \index{terminal}
  497. We can apply the rules to build ASTs in the $R_0$
  498. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  499. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  500. an $\Exp$.
  501. \begin{center}
  502. \begin{minipage}{0.4\textwidth}
  503. \begin{lstlisting}
  504. (Prim '- (list (Int 8)))
  505. \end{lstlisting}
  506. \end{minipage}
  507. \begin{minipage}{0.25\textwidth}
  508. \begin{equation}
  509. \begin{tikzpicture}
  510. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  511. \node[draw, circle] (8) at (0, -1.2) {$8$};
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-neg8}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. The next grammar rule defines addition expressions:
  519. \begin{equation}
  520. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  521. \end{equation}
  522. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  523. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  524. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  525. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  526. to show that
  527. \begin{lstlisting}
  528. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  529. \end{lstlisting}
  530. is an $\Exp$ in the $R_0$ language.
  531. If you have an AST for which the above rules do not apply, then the
  532. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  533. is not in $R_0$ because there are no rules for \code{+} with only one
  534. argument, nor for \key{-} with two arguments. Whenever we define a
  535. language with a grammar, the language only includes those programs
  536. that are justified by the rules.
  537. The last grammar rule for $R_0$ states that there is a \code{Program}
  538. node to mark the top of the whole program:
  539. \[
  540. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  541. \]
  542. The \code{Program} structure is defined as follows
  543. \begin{lstlisting}
  544. (struct Program (info body))
  545. \end{lstlisting}
  546. where \code{body} is an expression. In later chapters, the \code{info}
  547. part will be used to store auxiliary information but for now it is
  548. just the empty list.
  549. It is common to have many grammar rules with the same left-hand side
  550. but different right-hand sides, such as the rules for $\Exp$ in the
  551. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  552. combine several right-hand-sides into a single rule.
  553. We collect all of the grammar rules for the abstract syntax of $R_0$
  554. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  555. defined in Figure~\ref{fig:r0-concrete-syntax}.
  556. The \code{read-program} function provided in \code{utilities.rkt} of
  557. the support materials reads a program in from a file (the sequence of
  558. characters in the concrete syntax of Racket) and parses it into an
  559. abstract syntax tree. See the description of \code{read-program} in
  560. Appendix~\ref{appendix:utilities} for more details.
  561. \begin{figure}[tp]
  562. \fbox{
  563. \begin{minipage}{0.96\textwidth}
  564. \[
  565. \begin{array}{rcl}
  566. \begin{array}{rcl}
  567. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  568. R_0 &::=& \Exp
  569. \end{array}
  570. \end{array}
  571. \]
  572. \end{minipage}
  573. }
  574. \caption{The concrete syntax of $R_0$.}
  575. \label{fig:r0-concrete-syntax}
  576. \end{figure}
  577. \begin{figure}[tp]
  578. \fbox{
  579. \begin{minipage}{0.96\textwidth}
  580. \[
  581. \begin{array}{rcl}
  582. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  583. &\mid& \ADD{\Exp}{\Exp} \\
  584. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  585. \end{array}
  586. \]
  587. \end{minipage}
  588. }
  589. \caption{The abstract syntax of $R_0$.}
  590. \label{fig:r0-syntax}
  591. \end{figure}
  592. \section{Pattern Matching}
  593. \label{sec:pattern-matching}
  594. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  595. the parts of an AST node. Racket provides the \texttt{match} form to
  596. access the parts of a structure. Consider the following example and
  597. the output on the right. \index{match} \index{pattern matching}
  598. \begin{center}
  599. \begin{minipage}{0.5\textwidth}
  600. \begin{lstlisting}
  601. (match ast1.1
  602. [(Prim op (list child1 child2))
  603. (print op)])
  604. \end{lstlisting}
  605. \end{minipage}
  606. \vrule
  607. \begin{minipage}{0.25\textwidth}
  608. \begin{lstlisting}
  609. '+
  610. \end{lstlisting}
  611. \end{minipage}
  612. \end{center}
  613. In the above example, the \texttt{match} form takes the AST
  614. \eqref{eq:arith-prog} and binds its parts to the three pattern
  615. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  616. general, a match clause consists of a \emph{pattern} and a
  617. \emph{body}.
  618. \index{pattern}
  619. Patterns are recursively defined to be either a pattern
  620. variable, a structure name followed by a pattern for each of the
  621. structure's arguments, or an S-expression (symbols, lists, etc.).
  622. (See Chapter 12 of The Racket
  623. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  624. and Chapter 9 of The Racket
  625. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  626. for a complete description of \code{match}.)
  627. %
  628. The body of a match clause may contain arbitrary Racket code. The
  629. pattern variables can be used in the scope of the body.
  630. A \code{match} form may contain several clauses, as in the following
  631. function \code{leaf?} that recognizes when an $R_0$ node is
  632. a leaf. The \code{match} proceeds through the clauses in order,
  633. checking whether the pattern can match the input AST. The
  634. body of the first clause that matches is executed. The output of
  635. \code{leaf?} for several ASTs is shown on the right.
  636. \begin{center}
  637. \begin{minipage}{0.6\textwidth}
  638. \begin{lstlisting}
  639. (define (leaf? arith)
  640. (match arith
  641. [(Int n) #t]
  642. [(Prim 'read '()) #t]
  643. [(Prim '- (list c1)) #f]
  644. [(Prim '+ (list c1 c2)) #f]))
  645. (leaf? (Prim 'read '()))
  646. (leaf? (Prim '- (list (Int 8))))
  647. (leaf? (Int 8))
  648. \end{lstlisting}
  649. \end{minipage}
  650. \vrule
  651. \begin{minipage}{0.25\textwidth}
  652. \begin{lstlisting}
  653. #t
  654. #f
  655. #t
  656. \end{lstlisting}
  657. \end{minipage}
  658. \end{center}
  659. When writing a \code{match}, we refer to the grammar definition to
  660. identify which non-terminal we are expecting to match against, then we
  661. make sure that 1) we have one clause for each alternative of that
  662. non-terminal and 2) that the pattern in each clause corresponds to the
  663. corresponding right-hand side of a grammar rule. For the \code{match}
  664. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  665. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  666. alternatives, so the \code{match} has 4 clauses. The pattern in each
  667. clause corresponds to the right-hand side of a grammar rule. For
  668. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  669. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  670. patterns, replace non-terminals such as $\Exp$ with pattern variables
  671. of your choice (e.g. \code{c1} and \code{c2}).
  672. \section{Recursion}
  673. \label{sec:recursion}
  674. \index{recursive function}
  675. Programs are inherently recursive. For example, an $R_0$ expression is
  676. often made of smaller expressions. Thus, the natural way to process an
  677. entire program is with a recursive function. As a first example of
  678. such a recursive function, we define \texttt{exp?} below, which takes
  679. an arbitrary value and determines whether or not it is an $R_0$
  680. expression.
  681. %
  682. When a recursive function is defined using a sequence of match clauses
  683. that correspond to a grammar, and the body of each clause makes a
  684. recursive call on each child node, then we say the function is defined
  685. by \emph{structural recursion}\footnote{This principle of structuring
  686. code according to the data definition is advocated in the book
  687. \emph{How to Design Programs}
  688. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  689. define a second function, named \code{R0?}, that determines whether a
  690. value is an $R_0$ program. In general we can expect to write one
  691. recursive function to handle each non-terminal in a grammar.
  692. \index{structural recursion}
  693. %
  694. \begin{center}
  695. \begin{minipage}{0.7\textwidth}
  696. \begin{lstlisting}
  697. (define (exp? ast)
  698. (match ast
  699. [(Int n) #t]
  700. [(Prim 'read '()) #t]
  701. [(Prim '- (list e)) (exp? e)]
  702. [(Prim '+ (list e1 e2))
  703. (and (exp? e1) (exp? e2))]
  704. [else #f]))
  705. (define (R0? ast)
  706. (match ast
  707. [(Program '() e) (exp? e)]
  708. [else #f]))
  709. (R0? (Program '() ast1.1)
  710. (R0? (Program '()
  711. (Prim '- (list (Prim 'read '())
  712. (Prim '+ (list (Num 8)))))))
  713. \end{lstlisting}
  714. \end{minipage}
  715. \vrule
  716. \begin{minipage}{0.25\textwidth}
  717. \begin{lstlisting}
  718. #t
  719. #f
  720. \end{lstlisting}
  721. \end{minipage}
  722. \end{center}
  723. You may be tempted to merge the two functions into one, like this:
  724. \begin{center}
  725. \begin{minipage}{0.5\textwidth}
  726. \begin{lstlisting}
  727. (define (R0? ast)
  728. (match ast
  729. [(Int n) #t]
  730. [(Prim 'read '()) #t]
  731. [(Prim '- (list e)) (R0? e)]
  732. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  733. [(Program '() e) (R0? e)]
  734. [else #f]))
  735. \end{lstlisting}
  736. \end{minipage}
  737. \end{center}
  738. %
  739. Sometimes such a trick will save a few lines of code, especially when
  740. it comes to the \code{Program} wrapper. Yet this style is generally
  741. \emph{not} recommended because it can get you into trouble.
  742. %
  743. For example, the above function is subtly wrong:
  744. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  745. will return true, when it should return false.
  746. %% NOTE FIXME - must check for consistency on this issue throughout.
  747. \section{Interpreters}
  748. \label{sec:interp-R0}
  749. \index{interpreter}
  750. The meaning, or semantics, of a program is typically defined in the
  751. specification of the language. For example, the Scheme language is
  752. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  753. defined in its reference manual~\citep{plt-tr}. In this book we use an
  754. interpreter to define the meaning of each language that we consider,
  755. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  756. interpreter that is designated (by some people) as the definition of a
  757. language is called a \emph{definitional interpreter}.
  758. \index{definitional interpreter}
  759. We warm up by creating a definitional interpreter for the $R_0$ language, which
  760. serves as a second example of structural recursion. The
  761. \texttt{interp-R0} function is defined in
  762. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  763. input program followed by a call to the \lstinline{interp-exp} helper
  764. function, which in turn has one match clause per grammar rule for
  765. $R_0$ expressions.
  766. \begin{figure}[tp]
  767. \begin{lstlisting}
  768. (define (interp-exp e)
  769. (match e
  770. [(Int n) n]
  771. [(Prim 'read '())
  772. (define r (read))
  773. (cond [(fixnum? r) r]
  774. [else (error 'interp-R0 "expected an integer" r)])]
  775. [(Prim '- (list e))
  776. (define v (interp-exp e))
  777. (fx- 0 v)]
  778. [(Prim '+ (list e1 e2))
  779. (define v1 (interp-exp e1))
  780. (define v2 (interp-exp e2))
  781. (fx+ v1 v2)]
  782. ))
  783. (define (interp-R0 p)
  784. (match p
  785. [(Program '() e) (interp-exp e)]
  786. ))
  787. \end{lstlisting}
  788. \caption{Interpreter for the $R_0$ language.}
  789. \label{fig:interp-R0}
  790. \end{figure}
  791. Let us consider the result of interpreting a few $R_0$ programs. The
  792. following program adds two integers.
  793. \begin{lstlisting}
  794. (+ 10 32)
  795. \end{lstlisting}
  796. The result is \key{42}. We wrote the above program in concrete syntax,
  797. whereas the parsed abstract syntax is:
  798. \begin{lstlisting}
  799. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  800. \end{lstlisting}
  801. The next example demonstrates that expressions may be nested within
  802. each other, in this case nesting several additions and negations.
  803. \begin{lstlisting}
  804. (+ 10 (- (+ 12 20)))
  805. \end{lstlisting}
  806. What is the result of the above program?
  807. As mentioned previously, the $R_0$ language does not support
  808. arbitrarily-large integers, but only $63$-bit integers, so we
  809. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  810. in Racket.
  811. Suppose
  812. \[
  813. n = 999999999999999999
  814. \]
  815. which indeed fits in $63$-bits. What happens when we run the
  816. following program in our interpreter?
  817. \begin{lstlisting}
  818. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  819. \end{lstlisting}
  820. It produces an error:
  821. \begin{lstlisting}
  822. fx+: result is not a fixnum
  823. \end{lstlisting}
  824. We establish the convention that if running the definitional
  825. interpreter on a program produces an error, then the meaning of that
  826. program is \emph{unspecified}. That means a compiler for the language
  827. is under no obligations regarding that program; it may or may not
  828. produce an executable, and if it does, that executable can do
  829. anything. This convention applies to the languages defined in this
  830. book, as a way to simplify the student's task of implementing them,
  831. but this convention is not applicable to all programming languages.
  832. \index{unspecified behavior}
  833. Moving on to the last feature of the $R_0$ language, the \key{read}
  834. operation prompts the user of the program for an integer. Recall that
  835. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  836. \code{8}. So if we run
  837. \begin{lstlisting}
  838. (interp-R0 (Program '() ast1.1))
  839. \end{lstlisting}
  840. and if the input is \code{50}, then we get the answer to life, the
  841. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  842. Guide to the Galaxy} by Douglas Adams.}
  843. We include the \key{read} operation in $R_0$ so a clever student
  844. cannot implement a compiler for $R_0$ that simply runs the interpreter
  845. during compilation to obtain the output and then generates the trivial
  846. code to produce the output. (Yes, a clever student did this in the
  847. first instance of this course.)
  848. The job of a compiler is to translate a program in one language into a
  849. program in another language so that the output program behaves the
  850. same way as the input program does according to its definitional
  851. interpreter. This idea is depicted in the following diagram. Suppose
  852. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  853. interpreter for each language. Suppose that the compiler translates
  854. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  855. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  856. respective interpreters with input $i$ should yield the same output
  857. $o$.
  858. \begin{equation} \label{eq:compile-correct}
  859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  860. \node (p1) at (0, 0) {$P_1$};
  861. \node (p2) at (3, 0) {$P_2$};
  862. \node (o) at (3, -2.5) {$o$};
  863. \path[->] (p1) edge [above] node {compile} (p2);
  864. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  865. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  866. \end{tikzpicture}
  867. \end{equation}
  868. In the next section we see our first example of a compiler.
  869. \section{Example Compiler: a Partial Evaluator}
  870. \label{sec:partial-evaluation}
  871. In this section we consider a compiler that translates $R_0$ programs
  872. into $R_0$ programs that may be more efficient, that is, this compiler
  873. is an optimizer. This optimizer eagerly computes the parts of the
  874. program that do not depend on any inputs, a process known as
  875. \emph{partial evaluation}~\cite{Jones:1993uq}.
  876. \index{partial evaluation}
  877. For example, given the following program
  878. \begin{lstlisting}
  879. (+ (read) (- (+ 5 3)))
  880. \end{lstlisting}
  881. our compiler will translate it into the program
  882. \begin{lstlisting}
  883. (+ (read) -8)
  884. \end{lstlisting}
  885. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  886. evaluator for the $R_0$ language. The output of the partial evaluator
  887. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  888. recursion over $\Exp$ is captured in the \code{pe-exp} function
  889. whereas the code for partially evaluating the negation and addition
  890. operations is factored into two separate helper functions:
  891. \code{pe-neg} and \code{pe-add}. The input to these helper
  892. functions is the output of partially evaluating the children.
  893. \begin{figure}[tp]
  894. \begin{lstlisting}
  895. (define (pe-neg r)
  896. (match r
  897. [(Int n) (Int (fx- 0 n))]
  898. [else (Prim '- (list r))]))
  899. (define (pe-add r1 r2)
  900. (match* (r1 r2)
  901. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  902. [(_ _) (Prim '+ (list r1 r2))]))
  903. (define (pe-exp e)
  904. (match e
  905. [(Int n) (Int n)]
  906. [(Prim 'read '()) (Prim 'read '())]
  907. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  908. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  909. ))
  910. (define (pe-R0 p)
  911. (match p
  912. [(Program '() e) (Program '() (pe-exp e))]
  913. ))
  914. \end{lstlisting}
  915. \caption{A partial evaluator for $R_0$ expressions.}
  916. \label{fig:pe-arith}
  917. \end{figure}
  918. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  919. arguments are integers and if they are, perform the appropriate
  920. arithmetic. Otherwise, they create an AST node for the operation
  921. (either negation or addition).
  922. To gain some confidence that the partial evaluator is correct, we can
  923. test whether it produces programs that get the same result as the
  924. input programs. That is, we can test whether it satisfies Diagram
  925. \eqref{eq:compile-correct}. The following code runs the partial
  926. evaluator on several examples and tests the output program. The
  927. \texttt{parse-program} and \texttt{assert} functions are defined in
  928. Appendix~\ref{appendix:utilities}.\\
  929. \begin{minipage}{1.0\textwidth}
  930. \begin{lstlisting}
  931. (define (test-pe p)
  932. (assert "testing pe-R0"
  933. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  934. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  935. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  936. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  937. \end{lstlisting}
  938. \end{minipage}
  939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  940. \chapter{Integers and Variables}
  941. \label{ch:int-exp}
  942. This chapter is about compiling the subset of Racket that includes
  943. integer arithmetic and local variable binding, which we name $R_1$, to
  944. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  945. to x86-64 simply as x86. The chapter begins with a description of the
  946. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  947. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  948. discuss only what is needed for compiling $R_1$. We introduce more of
  949. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  950. reflect on their differences and come up with a plan to break down the
  951. translation from $R_1$ to x86 into a handful of steps
  952. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  953. chapter give detailed hints regarding each step
  954. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  955. to give enough hints that the well-prepared reader, together with a
  956. few friends, can implement a compiler from $R_1$ to x86 in a couple
  957. weeks while at the same time leaving room for some fun and creativity.
  958. To give the reader a feeling for the scale of this first compiler, the
  959. instructor solution for the $R_1$ compiler is less than 500 lines of
  960. code.
  961. \section{The $R_1$ Language}
  962. \label{sec:s0}
  963. \index{variable}
  964. The $R_1$ language extends the $R_0$ language with variable
  965. definitions. The concrete syntax of the $R_1$ language is defined by
  966. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  967. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  968. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  969. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  970. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  971. \key{Program} struct to mark the top of the program.
  972. %% The $\itm{info}$
  973. %% field of the \key{Program} structure contains an \emph{association
  974. %% list} (a list of key-value pairs) that is used to communicate
  975. %% auxiliary data from one compiler pass the next.
  976. Despite the simplicity of the $R_1$ language, it is rich enough to
  977. exhibit several compilation techniques.
  978. \begin{figure}[tp]
  979. \centering
  980. \fbox{
  981. \begin{minipage}{0.96\textwidth}
  982. \[
  983. \begin{array}{rcl}
  984. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  985. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  986. R_1 &::=& \Exp
  987. \end{array}
  988. \]
  989. \end{minipage}
  990. }
  991. \caption{The concrete syntax of $R_1$.}
  992. \label{fig:r1-concrete-syntax}
  993. \end{figure}
  994. \begin{figure}[tp]
  995. \centering
  996. \fbox{
  997. \begin{minipage}{0.96\textwidth}
  998. \[
  999. \begin{array}{rcl}
  1000. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1001. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1002. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1003. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1004. \end{array}
  1005. \]
  1006. \end{minipage}
  1007. }
  1008. \caption{The abstract syntax of $R_1$.}
  1009. \label{fig:r1-syntax}
  1010. \end{figure}
  1011. Let us dive further into the syntax and semantics of the $R_1$
  1012. language. The \key{Let} feature defines a variable for use within its
  1013. body and initializes the variable with the value of an expression.
  1014. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1015. The concrete syntax for \key{Let} is
  1016. \begin{lstlisting}
  1017. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1018. \end{lstlisting}
  1019. For example, the following program initializes \code{x} to $32$ and then
  1020. evaluates the body \code{(+ 10 x)}, producing $42$.
  1021. \begin{lstlisting}
  1022. (let ([x (+ 12 20)]) (+ 10 x))
  1023. \end{lstlisting}
  1024. When there are multiple \key{let}'s for the same variable, the closest
  1025. enclosing \key{let} is used. That is, variable definitions overshadow
  1026. prior definitions. Consider the following program with two \key{let}'s
  1027. that define variables named \code{x}. Can you figure out the result?
  1028. \begin{lstlisting}
  1029. (let ([x 32]) (+ (let ([x 10]) x) x))
  1030. \end{lstlisting}
  1031. For the purposes of depicting which variable uses correspond to which
  1032. definitions, the following shows the \code{x}'s annotated with
  1033. subscripts to distinguish them. Double check that your answer for the
  1034. above is the same as your answer for this annotated version of the
  1035. program.
  1036. \begin{lstlisting}
  1037. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1038. \end{lstlisting}
  1039. The initializing expression is always evaluated before the body of the
  1040. \key{let}, so in the following, the \key{read} for \code{x} is
  1041. performed before the \key{read} for \code{y}. Given the input
  1042. $52$ then $10$, the following produces $42$ (not $-42$).
  1043. \begin{lstlisting}
  1044. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1045. \end{lstlisting}
  1046. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1047. \small
  1048. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1049. An \emph{association list} (alist) is a list of key-value pairs.
  1050. For example, we can map people to their ages with an alist.
  1051. \index{alist}\index{association list}
  1052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1053. (define ages
  1054. '((jane . 25) (sam . 24) (kate . 45)))
  1055. \end{lstlisting}
  1056. The \emph{dictionary} interface is for mapping keys to values.
  1057. Every alist implements this interface. \index{dictionary} The package
  1058. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1059. provides many functions for working with dictionaries. Here
  1060. are a few of them:
  1061. \begin{description}
  1062. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1063. returns the value associated with the given $\itm{key}$.
  1064. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1065. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1066. but otherwise is the same as $\itm{dict}$.
  1067. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1068. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1069. of keys and values in $\itm{dict}$. For example, the following
  1070. creates a new alist in which the ages are incremented.
  1071. \end{description}
  1072. \vspace{-10pt}
  1073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1074. (for/list ([(k v) (in-dict ages)])
  1075. (cons k (add1 v)))
  1076. \end{lstlisting}
  1077. \end{tcolorbox}
  1078. \end{wrapfigure}
  1079. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1080. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1081. \key{match} clauses for variables and for \key{let}. For \key{let},
  1082. we need a way to communicate the value of a variable to all the uses
  1083. of a variable. To accomplish this, we maintain a mapping from
  1084. variables to values. Throughout the compiler we often need to map
  1085. variables to information about them. We refer to these mappings as
  1086. \emph{environments}\index{environment}
  1087. \footnote{Another common term for environment in the compiler
  1088. literature is \emph{symbol table}\index{symbol table}.}.
  1089. For simplicity, we use an
  1090. association list (alist) to represent the environment. The sidebar to
  1091. the right gives a brief introduction to alists and the
  1092. \code{racket/dict} package. The \code{interp-R1} function takes the
  1093. current environment, \code{env}, as an extra parameter. When the
  1094. interpreter encounters a variable, it finds the corresponding value
  1095. using the \code{dict-ref} function. When the interpreter encounters a
  1096. \key{Let}, it evaluates the initializing expression, extends the
  1097. environment with the result value bound to the variable, using
  1098. \code{dict-set}, then evaluates the body of the \key{Let}.
  1099. \begin{figure}[tp]
  1100. \begin{lstlisting}
  1101. (define (interp-exp env)
  1102. (lambda (e)
  1103. (match e
  1104. [(Int n) n]
  1105. [(Prim 'read '())
  1106. (define r (read))
  1107. (cond [(fixnum? r) r]
  1108. [else (error 'interp-R1 "expected an integer" r)])]
  1109. [(Prim '- (list e))
  1110. (define v ((interp-exp env) e))
  1111. (fx- 0 v)]
  1112. [(Prim '+ (list e1 e2))
  1113. (define v1 ((interp-exp env) e1))
  1114. (define v2 ((interp-exp env) e2))
  1115. (fx+ v1 v2)]
  1116. [(Var x) (dict-ref env x)]
  1117. [(Let x e body)
  1118. (define new-env (dict-set env x ((interp-exp env) e)))
  1119. ((interp-exp new-env) body)]
  1120. )))
  1121. (define (interp-R1 p)
  1122. (match p
  1123. [(Program '() e) ((interp-exp '()) e)]
  1124. ))
  1125. \end{lstlisting}
  1126. \caption{Interpreter for the $R_1$ language.}
  1127. \label{fig:interp-R1}
  1128. \end{figure}
  1129. The goal for this chapter is to implement a compiler that translates
  1130. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1131. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1132. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1133. is, they both output the same integer $n$. We depict this correctness
  1134. criteria in the following diagram.
  1135. \[
  1136. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1137. \node (p1) at (0, 0) {$P_1$};
  1138. \node (p2) at (4, 0) {$P_2$};
  1139. \node (o) at (4, -2) {$n$};
  1140. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1141. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1142. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1143. \end{tikzpicture}
  1144. \]
  1145. In the next section we introduce enough of the x86 assembly
  1146. language to compile $R_1$.
  1147. \section{The x86$_0$ Assembly Language}
  1148. \label{sec:x86}
  1149. \index{x86}
  1150. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1151. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1152. %
  1153. An x86 program begins with a \code{main} label followed by a sequence
  1154. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1155. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1156. instructions.\index{instruction}
  1157. %
  1158. An x86 program is stored in the computer's memory and the computer has
  1159. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1160. that points to the address of the next
  1161. instruction to be executed. For most instructions, once the
  1162. instruction is executed, the program counter is incremented to point
  1163. to the immediately following instruction in memory. Most x86
  1164. instructions take two operands, where each operand is either an
  1165. integer constant (called \emph{immediate value}\index{immediate value}),
  1166. a \emph{register}\index{register}, or a memory location.
  1167. A register is a special kind of variable. Each
  1168. one holds a 64-bit value; there are 16 registers in the computer and
  1169. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1170. as a mapping of 64-bit addresses to 64-bit values%
  1171. \footnote{This simple story suffices for describing how sequential
  1172. programs access memory but is not sufficient for multi-threaded
  1173. programs. However, multi-threaded execution is beyond the scope of
  1174. this book.}.
  1175. %
  1176. We use the AT\&T syntax expected by the GNU assembler, which comes
  1177. with the \key{gcc} compiler that we use for compiling assembly code to
  1178. machine code.
  1179. %
  1180. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1181. the x86 instructions used in this book.
  1182. % to do: finish treatment of imulq
  1183. % it's needed for vector's in R6/R7
  1184. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1185. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1186. && \key{r8} \mid \key{r9} \mid \key{r10}
  1187. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1188. \mid \key{r14} \mid \key{r15}}
  1189. \begin{figure}[tp]
  1190. \fbox{
  1191. \begin{minipage}{0.96\textwidth}
  1192. \[
  1193. \begin{array}{lcl}
  1194. \Reg &::=& \allregisters{} \\
  1195. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1196. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1197. \key{subq} \; \Arg\key{,} \Arg \mid
  1198. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1199. && \key{callq} \; \mathit{label} \mid
  1200. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1201. && \itm{label}\key{:}\; \Instr \\
  1202. x86_0 &::= & \key{.globl main}\\
  1203. & & \key{main:} \; \Instr\ldots
  1204. \end{array}
  1205. \]
  1206. \end{minipage}
  1207. }
  1208. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1209. \label{fig:x86-0-concrete}
  1210. \end{figure}
  1211. An immediate value is written using the notation \key{\$}$n$ where $n$
  1212. is an integer.
  1213. %
  1214. A register is written with a \key{\%} followed by the register name,
  1215. such as \key{\%rax}.
  1216. %
  1217. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1218. which obtains the address stored in register $r$ and then adds $n$
  1219. bytes to the address. The resulting address is used to either load or
  1220. store to memory depending on whether it occurs as a source or
  1221. destination argument of an instruction.
  1222. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1223. source $s$ and destination $d$, applies the arithmetic operation, then
  1224. writes the result back to the destination $d$.
  1225. %
  1226. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1227. stores the result in $d$.
  1228. %
  1229. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1230. specified by the label and $\key{retq}$ returns from a procedure to
  1231. its caller. The abstract syntax for \code{callq} includes an extra
  1232. integer field that represents the arity (number of parameters) of the
  1233. function being called.
  1234. %
  1235. We discuss procedure calls in more detail later in this
  1236. chapter and in Chapter~\ref{ch:functions}. The
  1237. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1238. the address of the instruction after the specified label.
  1239. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1240. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1241. \key{main} procedure is externally visible, which is necessary so
  1242. that the operating system can call it. The label \key{main:}
  1243. indicates the beginning of the \key{main} procedure which is where
  1244. the operating system starts executing this program. The instruction
  1245. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1246. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1247. $10$ in \key{rax} and puts the result, $42$, back into
  1248. \key{rax}.
  1249. %
  1250. The last instruction, \key{retq}, finishes the \key{main} function by
  1251. returning the integer in \key{rax} to the operating system. The
  1252. operating system interprets this integer as the program's exit
  1253. code. By convention, an exit code of 0 indicates that a program
  1254. completed successfully, and all other exit codes indicate various
  1255. errors. Nevertheless, we return the result of the program as the exit
  1256. code.
  1257. %\begin{wrapfigure}{r}{2.25in}
  1258. \begin{figure}[tbp]
  1259. \begin{lstlisting}
  1260. .globl main
  1261. main:
  1262. movq $10, %rax
  1263. addq $32, %rax
  1264. retq
  1265. \end{lstlisting}
  1266. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1267. \label{fig:p0-x86}
  1268. %\end{wrapfigure}
  1269. \end{figure}
  1270. Unfortunately, x86 varies in a couple ways depending on what operating
  1271. system it is assembled in. The code examples shown here are correct on
  1272. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1273. labels like \key{main} must be prefixed with an underscore, as in
  1274. \key{\_main}.
  1275. We exhibit the use of memory for storing intermediate results in the
  1276. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1277. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1278. memory called the \emph{procedure call stack} (or \emph{stack} for
  1279. short). \index{stack}\index{procedure call stack} The stack consists
  1280. of a separate \emph{frame}\index{frame} for each procedure call. The
  1281. memory layout for an individual frame is shown in
  1282. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1283. \emph{stack pointer}\index{stack pointer} and points to the item at
  1284. the top of the stack. The stack grows downward in memory, so we
  1285. increase the size of the stack by subtracting from the stack pointer.
  1286. In the context of a procedure call, the \emph{return
  1287. address}\index{return address} is the instruction after the call
  1288. instruction on the caller side. The function call inststruction,
  1289. \code{callq}, pushes the return address onto the stack. The register
  1290. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1291. to access variables associated with the current procedure call. The
  1292. base pointer of the caller is pushed onto the stack after the return
  1293. address. We number the variables from $1$ to $n$. Variable $1$ is
  1294. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1295. $-16\key{(\%rbp)}$, etc.
  1296. \begin{figure}[tbp]
  1297. \begin{lstlisting}
  1298. start:
  1299. movq $10, -8(%rbp)
  1300. negq -8(%rbp)
  1301. movq -8(%rbp), %rax
  1302. addq $52, %rax
  1303. jmp conclusion
  1304. .globl main
  1305. main:
  1306. pushq %rbp
  1307. movq %rsp, %rbp
  1308. subq $16, %rsp
  1309. jmp start
  1310. conclusion:
  1311. addq $16, %rsp
  1312. popq %rbp
  1313. retq
  1314. \end{lstlisting}
  1315. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1316. \label{fig:p1-x86}
  1317. \end{figure}
  1318. \begin{figure}[tbp]
  1319. \centering
  1320. \begin{tabular}{|r|l|} \hline
  1321. Position & Contents \\ \hline
  1322. 8(\key{\%rbp}) & return address \\
  1323. 0(\key{\%rbp}) & old \key{rbp} \\
  1324. -8(\key{\%rbp}) & variable $1$ \\
  1325. -16(\key{\%rbp}) & variable $2$ \\
  1326. \ldots & \ldots \\
  1327. 0(\key{\%rsp}) & variable $n$\\ \hline
  1328. \end{tabular}
  1329. \caption{Memory layout of a frame.}
  1330. \label{fig:frame}
  1331. \end{figure}
  1332. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1333. control is transfered from the operating system to the \code{main}
  1334. function. The operating system issues a \code{callq main} instruction
  1335. which pushes its return address on the stack and then jumps to
  1336. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1337. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1338. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1339. alignment (because the \code{callq} pushed the return address). The
  1340. first three instructions are the typical \emph{prelude}\index{prelude}
  1341. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1342. pointer for the caller onto the stack and subtracts $8$ from the stack
  1343. pointer. At this point the stack pointer is back to being 16-byte
  1344. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1345. base pointer so that it points the location of the old base
  1346. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1347. pointer down to make enough room for storing variables. This program
  1348. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1349. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1350. we are ready to make calls to other functions. The last instruction of
  1351. the prelude is \code{jmp start}, which transfers control to the
  1352. instructions that were generated from the Racket expression \code{(+
  1353. 10 32)}.
  1354. The four instructions under the label \code{start} carry out the work
  1355. of computing \code{(+ 52 (- 10)))}.
  1356. %
  1357. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1358. variable $1$.
  1359. %
  1360. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1361. %
  1362. The following instruction moves the $-10$ from variable $1$ into the
  1363. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1364. the value in \code{rax}, updating its contents to $42$.
  1365. The three instructions under the label \code{conclusion} are the
  1366. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1367. two instructions are necessary to get the state of the machine back to
  1368. where it was at the beginning of the procedure. The instruction
  1369. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1370. old base pointer. The amount added here needs to match the amount that
  1371. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1372. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1373. pointer. The last instruction, \key{retq}, jumps back to the
  1374. procedure that called this one and adds 8 to the stack pointer, which
  1375. returns the stack pointer to where it was prior to the procedure call.
  1376. The compiler needs a convenient representation for manipulating x86
  1377. programs, so we define an abstract syntax for x86 in
  1378. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1379. a subscript $0$ because later we introduce extended versions of this
  1380. assembly language. The main difference compared to the concrete syntax
  1381. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1382. labeled instructions to appear anywhere, but instead organizes
  1383. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1384. and associates a label with every block, which is why the \key{CFG} struct
  1385. (for control-flow graph) includes an alist mapping labels to
  1386. blocks. The reason for this organization becomes apparent in
  1387. Chapter~\ref{ch:bool-types} when we introduce conditional
  1388. branching. The \code{Block} structure includes an $\itm{info}$ field
  1389. that is not needed for this chapter, but will become useful in
  1390. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1391. field should just contain an empty list.
  1392. \begin{figure}[tp]
  1393. \fbox{
  1394. \begin{minipage}{0.96\textwidth}
  1395. \small
  1396. \[
  1397. \begin{array}{lcl}
  1398. \Reg &::=& \allregisters{} \\
  1399. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1400. \mid \DEREF{\Reg}{\Int} \\
  1401. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1402. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1403. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1404. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1405. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1406. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1407. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1408. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1409. \end{array}
  1410. \]
  1411. \end{minipage}
  1412. }
  1413. \caption{The abstract syntax of x86$_0$ assembly.}
  1414. \label{fig:x86-0-ast}
  1415. \end{figure}
  1416. \section{Planning the trip to x86 via the $C_0$ language}
  1417. \label{sec:plan-s0-x86}
  1418. To compile one language to another it helps to focus on the
  1419. differences between the two languages because the compiler will need
  1420. to bridge those differences. What are the differences between $R_1$
  1421. and x86 assembly? Here are some of the most important ones:
  1422. \begin{enumerate}
  1423. \item[(a)] x86 arithmetic instructions typically have two arguments
  1424. and update the second argument in place. In contrast, $R_1$
  1425. arithmetic operations take two arguments and produce a new value.
  1426. An x86 instruction may have at most one memory-accessing argument.
  1427. Furthermore, some instructions place special restrictions on their
  1428. arguments.
  1429. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1430. whereas x86 instructions restrict their arguments to be integers
  1431. constants, registers, and memory locations.
  1432. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1433. sequence of instructions and jumps to labeled positions, whereas in
  1434. $R_1$ the order of evaluation is a left-to-right depth-first
  1435. traversal of the abstract syntax tree.
  1436. \item[(d)] An $R_1$ program can have any number of variables whereas
  1437. x86 has 16 registers and the procedure calls stack.
  1438. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1439. same name. The registers and memory locations of x86 all have unique
  1440. names or addresses.
  1441. \end{enumerate}
  1442. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1443. the problem into several steps, dealing with the above differences one
  1444. at a time. Each of these steps is called a \emph{pass} of the
  1445. compiler.\index{pass}\index{compiler pass}
  1446. %
  1447. This terminology comes from each step traverses (i.e. passes over) the
  1448. AST of the program.
  1449. %
  1450. We begin by sketching how we might implement each pass, and give them
  1451. names. We then figure out an ordering of the passes and the
  1452. input/output language for each pass. The very first pass has $R_1$ as
  1453. its input language and the last pass has x86 as its output
  1454. language. In between we can choose whichever language is most
  1455. convenient for expressing the output of each pass, whether that be
  1456. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1457. Finally, to implement each pass we write one recursive function per
  1458. non-terminal in the grammar of the input language of the pass.
  1459. \index{intermediate language}
  1460. \begin{description}
  1461. \item[Pass \key{select-instructions}] To handle the difference between
  1462. $R_1$ operations and x86 instructions we convert each $R_1$
  1463. operation to a short sequence of instructions that accomplishes the
  1464. same task.
  1465. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1466. subexpression (i.e. operator and operand, and hence the name
  1467. \key{opera*}) is an \emph{atomic} expression (a variable or
  1468. integer), we introduce temporary variables to hold the results
  1469. of subexpressions.\index{atomic expression}
  1470. \item[Pass \key{explicate-control}] To make the execution order of the
  1471. program explicit, we convert from the abstract syntax tree
  1472. representation into a control-flow graph in which each node
  1473. contains a sequence of statements and the edges between nodes say
  1474. where to go at the end of the sequence.
  1475. \item[Pass \key{assign-homes}] To handle the difference between the
  1476. variables in $R_1$ versus the registers and stack locations in x86,
  1477. we map each variable to a register or stack location.
  1478. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1479. by renaming every variable to a unique name, so that shadowing no
  1480. longer occurs.
  1481. \end{description}
  1482. The next question is: in what order should we apply these passes? This
  1483. question can be challenging because it is difficult to know ahead of
  1484. time which orders will be better (easier to implement, produce more
  1485. efficient code, etc.) so oftentimes trial-and-error is
  1486. involved. Nevertheless, we can try to plan ahead and make educated
  1487. choices regarding the ordering.
  1488. Let us consider the ordering of \key{uniquify} and
  1489. \key{remove-complex-opera*}. The assignment of subexpressions to
  1490. temporary variables involves introducing new variables and moving
  1491. subexpressions, which might change the shadowing of variables and
  1492. inadvertently change the behavior of the program. But if we apply
  1493. \key{uniquify} first, this will not be an issue. Of course, this means
  1494. that in \key{remove-complex-opera*}, we need to ensure that the
  1495. temporary variables that it creates are unique.
  1496. What should be the ordering of \key{explicate-control} with respect to
  1497. \key{uniquify}? The \key{uniquify} pass should come first because
  1498. \key{explicate-control} changes all the \key{let}-bound variables to
  1499. become local variables whose scope is the entire program, which would
  1500. confuse variables with the same name.
  1501. %
  1502. Likewise, we place \key{explicate-control} after
  1503. \key{remove-complex-opera*} because \key{explicate-control} removes
  1504. the \key{let} form, but it is convenient to use \key{let} in the
  1505. output of \key{remove-complex-opera*}.
  1506. %
  1507. Regarding \key{assign-homes}, it is helpful to place
  1508. \key{explicate-control} first because \key{explicate-control} changes
  1509. \key{let}-bound variables into program-scope variables. This means
  1510. that the \key{assign-homes} pass can read off the variables from the
  1511. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1512. entire program in search of \key{let}-bound variables.
  1513. Last, we need to decide on the ordering of \key{select-instructions}
  1514. and \key{assign-homes}. These two passes are intertwined, creating a
  1515. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1516. have already determined which instructions will be used, because x86
  1517. instructions have restrictions about which of their arguments can be
  1518. registers versus stack locations. One might want to give preferential
  1519. treatment to variables that occur in register-argument positions. On
  1520. the other hand, it may turn out to be impossible to make sure that all
  1521. such variables are assigned to registers, and then one must redo the
  1522. selection of instructions. Some compilers handle this problem by
  1523. iteratively repeating these two passes until a good solution is found.
  1524. We use a simpler approach in which \key{select-instructions}
  1525. comes first, followed by the \key{assign-homes}, then a third
  1526. pass named \key{patch-instructions} that uses a reserved register to
  1527. patch-up outstanding problems regarding instructions with too many
  1528. memory accesses. The disadvantage of this approach is some programs
  1529. may not execute as efficiently as they would if we used the iterative
  1530. approach and used all of the registers for variables.
  1531. \begin{figure}[tbp]
  1532. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1533. \node (R1) at (0,2) {\large $R_1$};
  1534. \node (R1-2) at (3,2) {\large $R_1$};
  1535. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1536. %\node (C0-1) at (6,0) {\large $C_0$};
  1537. \node (C0-2) at (3,0) {\large $C_0$};
  1538. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1539. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1540. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1541. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1542. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1543. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1544. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1545. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1546. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1547. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1548. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1549. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1550. \end{tikzpicture}
  1551. \caption{Overview of the passes for compiling $R_1$. }
  1552. \label{fig:R1-passes}
  1553. \end{figure}
  1554. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1555. passes in the form of a graph. Each pass is an edge and the
  1556. input/output language of each pass is a node in the graph. The output
  1557. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1558. are still in the $R_1$ language, but the output of the pass
  1559. \key{explicate-control} is in a different language $C_0$ that is
  1560. designed to make the order of evaluation explicit in its syntax, which
  1561. we introduce in the next section. The \key{select-instruction} pass
  1562. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1563. \key{patch-instructions} passes input and output variants of x86
  1564. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1565. \key{print-x86}, which converts from the abstract syntax of
  1566. $\text{x86}_0$ to the concrete syntax of x86.
  1567. In the next sections we discuss the $C_0$ language and the
  1568. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1569. remainder of this chapter gives hints regarding the implementation of
  1570. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1571. \subsection{The $C_0$ Intermediate Language}
  1572. The output of \key{explicate-control} is similar to the $C$
  1573. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1574. categories for expressions and statements, so we name it $C_0$. The
  1575. concrete syntax for $C_0$ is defined in
  1576. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1577. is defined in Figure~\ref{fig:c0-syntax}.
  1578. %
  1579. The $C_0$ language supports the same operators as $R_1$ but the
  1580. arguments of operators are restricted to atomic expressions (variables
  1581. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1582. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1583. executed in sequence using the \key{Seq} form. A sequence of
  1584. statements always ends with \key{Return}, a guarantee that is baked
  1585. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1586. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1587. which refers to an expression that is the last one to execute within a
  1588. function. (An expression in tail position may contain subexpressions,
  1589. and those may or may not be in tail position depending on the kind of
  1590. expression.)
  1591. A $C_0$ program consists of a control-flow graph (represented as an
  1592. alist mapping labels to tails). This is more general than
  1593. necessary for the present chapter, as we do not yet need to introduce
  1594. \key{goto} for jumping to labels, but it saves us from having to
  1595. change the syntax of the program construct in
  1596. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1597. \key{start}, and the whole program is its tail.
  1598. %
  1599. The $\itm{info}$ field of the \key{Program} form, after the
  1600. \key{explicate-control} pass, contains a mapping from the symbol
  1601. \key{locals} to a list of variables, that is, a list of all the
  1602. variables used in the program. At the start of the program, these
  1603. variables are uninitialized; they become initialized on their first
  1604. assignment.
  1605. \begin{figure}[tbp]
  1606. \fbox{
  1607. \begin{minipage}{0.96\textwidth}
  1608. \[
  1609. \begin{array}{lcl}
  1610. \Atm &::=& \Int \mid \Var \\
  1611. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1612. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1613. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1614. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1615. \end{array}
  1616. \]
  1617. \end{minipage}
  1618. }
  1619. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1620. \label{fig:c0-concrete-syntax}
  1621. \end{figure}
  1622. \begin{figure}[tbp]
  1623. \fbox{
  1624. \begin{minipage}{0.96\textwidth}
  1625. \[
  1626. \begin{array}{lcl}
  1627. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1628. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1629. &\mid& \ADD{\Atm}{\Atm}\\
  1630. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1631. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1632. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1633. \end{array}
  1634. \]
  1635. \end{minipage}
  1636. }
  1637. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1638. \label{fig:c0-syntax}
  1639. \end{figure}
  1640. \subsection{The dialects of x86}
  1641. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1642. the pass \key{select-instructions}. It extends x86$_0$ with an
  1643. unbounded number of program-scope variables and has looser rules
  1644. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1645. output of \key{print-x86}, is the concrete syntax for x86.
  1646. \section{Uniquify Variables}
  1647. \label{sec:uniquify-s0}
  1648. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1649. programs in which every \key{let} uses a unique variable name. For
  1650. example, the \code{uniquify} pass should translate the program on the
  1651. left into the program on the right. \\
  1652. \begin{tabular}{lll}
  1653. \begin{minipage}{0.4\textwidth}
  1654. \begin{lstlisting}
  1655. (let ([x 32])
  1656. (+ (let ([x 10]) x) x))
  1657. \end{lstlisting}
  1658. \end{minipage}
  1659. &
  1660. $\Rightarrow$
  1661. &
  1662. \begin{minipage}{0.4\textwidth}
  1663. \begin{lstlisting}
  1664. (let ([x.1 32])
  1665. (+ (let ([x.2 10]) x.2) x.1))
  1666. \end{lstlisting}
  1667. \end{minipage}
  1668. \end{tabular} \\
  1669. %
  1670. The following is another example translation, this time of a program
  1671. with a \key{let} nested inside the initializing expression of another
  1672. \key{let}.\\
  1673. \begin{tabular}{lll}
  1674. \begin{minipage}{0.4\textwidth}
  1675. \begin{lstlisting}
  1676. (let ([x (let ([x 4])
  1677. (+ x 1))])
  1678. (+ x 2))
  1679. \end{lstlisting}
  1680. \end{minipage}
  1681. &
  1682. $\Rightarrow$
  1683. &
  1684. \begin{minipage}{0.4\textwidth}
  1685. \begin{lstlisting}
  1686. (let ([x.2 (let ([x.1 4])
  1687. (+ x.1 1))])
  1688. (+ x.2 2))
  1689. \end{lstlisting}
  1690. \end{minipage}
  1691. \end{tabular}
  1692. We recommend implementing \code{uniquify} by creating a function named
  1693. \code{uniquify-exp} that is structurally recursive function and mostly
  1694. just copies the input program. However, when encountering a \key{let},
  1695. it should generate a unique name for the variable (the Racket function
  1696. \code{gensym} is handy for this) and associate the old name with the
  1697. new unique name in an alist. The \code{uniquify-exp}
  1698. function will need to access this alist when it gets to a
  1699. variable reference, so we add another parameter to \code{uniquify-exp}
  1700. for the alist.
  1701. The skeleton of the \code{uniquify-exp} function is shown in
  1702. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1703. convenient to partially apply it to a symbol table and then apply it
  1704. to different expressions, as in the last clause for primitive
  1705. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1706. form is useful for applying a function to each element of a list to produce
  1707. a new list.
  1708. \index{for/list}
  1709. \begin{exercise}
  1710. \normalfont % I don't like the italics for exercises. -Jeremy
  1711. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1712. implement the clauses for variables and for the \key{let} form.
  1713. \end{exercise}
  1714. \begin{figure}[tbp]
  1715. \begin{lstlisting}
  1716. (define (uniquify-exp symtab)
  1717. (lambda (e)
  1718. (match e
  1719. [(Var x) ___]
  1720. [(Int n) (Int n)]
  1721. [(Let x e body) ___]
  1722. [(Prim op es)
  1723. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1724. )))
  1725. (define (uniquify p)
  1726. (match p
  1727. [(Program '() e)
  1728. (Program '() ((uniquify-exp '()) e))]
  1729. )))
  1730. \end{lstlisting}
  1731. \caption{Skeleton for the \key{uniquify} pass.}
  1732. \label{fig:uniquify-s0}
  1733. \end{figure}
  1734. \begin{exercise}
  1735. \normalfont % I don't like the italics for exercises. -Jeremy
  1736. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1737. and checking whether the output programs produce the same result as
  1738. the input programs. The $R_1$ programs should be designed to test the
  1739. most interesting parts of the \key{uniquify} pass, that is, the
  1740. programs should include \key{let} forms, variables, and variables
  1741. that overshadow each other. The five programs should be in a
  1742. subdirectory named \key{tests} and they should have the same file name
  1743. except for a different integer at the end of the name, followed by the
  1744. ending \key{.rkt}. Use the \key{interp-tests} function
  1745. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1746. your \key{uniquify} pass on the example programs. See the
  1747. \key{run-tests.rkt} script in the student support code for an example
  1748. of how to use \key{interp-tests}.
  1749. \end{exercise}
  1750. \section{Remove Complex Operands}
  1751. \label{sec:remove-complex-opera-R1}
  1752. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1753. $R_1$ programs in which the arguments of operations are atomic
  1754. expressions. Put another way, this pass removes complex
  1755. operands\index{complex operand}, such as the expression \code{(- 10)}
  1756. in the program below. This is accomplished by introducing a new
  1757. \key{let}-bound variable, binding the complex operand to the new
  1758. variable, and then using the new variable in place of the complex
  1759. operand, as shown in the output of \code{remove-complex-opera*} on the
  1760. right.\\
  1761. \begin{tabular}{lll}
  1762. \begin{minipage}{0.4\textwidth}
  1763. % s0_19.rkt
  1764. \begin{lstlisting}
  1765. (+ 52 (- 10))
  1766. \end{lstlisting}
  1767. \end{minipage}
  1768. &
  1769. $\Rightarrow$
  1770. &
  1771. \begin{minipage}{0.4\textwidth}
  1772. \begin{lstlisting}
  1773. (let ([tmp.1 (- 10)])
  1774. (+ 52 tmp.1))
  1775. \end{lstlisting}
  1776. \end{minipage}
  1777. \end{tabular}
  1778. \begin{figure}[tp]
  1779. \centering
  1780. \fbox{
  1781. \begin{minipage}{0.96\textwidth}
  1782. \[
  1783. \begin{array}{rcl}
  1784. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1785. \Exp &::=& \Atm \mid \READ{} \\
  1786. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1787. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1788. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1789. \end{array}
  1790. \]
  1791. \end{minipage}
  1792. }
  1793. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1794. \label{fig:r1-anf-syntax}
  1795. \end{figure}
  1796. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1797. this pass, language $R_1^{\dagger}$. The main difference is that
  1798. operator arguments are required to be atomic expressions. In the
  1799. literature, this is called \emph{administrative normal form}, or ANF
  1800. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1801. \index{administrative normal form}
  1802. \index{ANF}
  1803. We recommend implementing this pass with two mutually recursive
  1804. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1805. \code{rco-atom} to subexpressions that are required to be atomic and
  1806. to apply \code{rco-exp} to subexpressions that can be atomic or
  1807. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1808. $R_1$ expression as input. The \code{rco-exp} function returns an
  1809. expression. The \code{rco-atom} function returns two things: an
  1810. atomic expression and alist mapping temporary variables to complex
  1811. subexpressions. You can return multiple things from a function using
  1812. Racket's \key{values} form and you can receive multiple things from a
  1813. function call using the \key{define-values} form. If you are not
  1814. familiar with these features, review the Racket documentation. Also,
  1815. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1816. form is useful for applying a function to each
  1817. element of a list, in the case where the function returns multiple
  1818. values.
  1819. \index{for/lists}
  1820. The following shows the output of \code{rco-atom} on the expression
  1821. \code{(- 10)} (using concrete syntax to be concise).
  1822. \begin{tabular}{lll}
  1823. \begin{minipage}{0.4\textwidth}
  1824. \begin{lstlisting}
  1825. (- 10)
  1826. \end{lstlisting}
  1827. \end{minipage}
  1828. &
  1829. $\Rightarrow$
  1830. &
  1831. \begin{minipage}{0.4\textwidth}
  1832. \begin{lstlisting}
  1833. tmp.1
  1834. ((tmp.1 . (- 10)))
  1835. \end{lstlisting}
  1836. \end{minipage}
  1837. \end{tabular}
  1838. Take special care of programs such as the next one that \key{let}-bind
  1839. variables with integers or other variables. You should leave them
  1840. unchanged, as shown in to the program on the right \\
  1841. \begin{tabular}{lll}
  1842. \begin{minipage}{0.4\textwidth}
  1843. % s0_20.rkt
  1844. \begin{lstlisting}
  1845. (let ([a 42])
  1846. (let ([b a])
  1847. b))
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. &
  1851. $\Rightarrow$
  1852. &
  1853. \begin{minipage}{0.4\textwidth}
  1854. \begin{lstlisting}
  1855. (let ([a 42])
  1856. (let ([b a])
  1857. b))
  1858. \end{lstlisting}
  1859. \end{minipage}
  1860. \end{tabular} \\
  1861. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1862. produce the following output.\\
  1863. \begin{minipage}{0.4\textwidth}
  1864. \begin{lstlisting}
  1865. (let ([tmp.1 42])
  1866. (let ([a tmp.1])
  1867. (let ([tmp.2 a])
  1868. (let ([b tmp.2])
  1869. b))))
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \begin{exercise}
  1873. \normalfont Implement the \code{remove-complex-opera*} pass.
  1874. Test the new pass on all of the example programs that you created to test the
  1875. \key{uniquify} pass and create three new example programs that are
  1876. designed to exercise the interesting code in the
  1877. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1878. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1879. your passes on the example programs.
  1880. \end{exercise}
  1881. \section{Explicate Control}
  1882. \label{sec:explicate-control-r1}
  1883. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1884. programs that make the order of execution explicit in their
  1885. syntax. For now this amounts to flattening \key{let} constructs into a
  1886. sequence of assignment statements. For example, consider the following
  1887. $R_1$ program.\\
  1888. % s0_11.rkt
  1889. \begin{minipage}{0.96\textwidth}
  1890. \begin{lstlisting}
  1891. (let ([y (let ([x 20])
  1892. (+ x (let ([x 22]) x)))])
  1893. y)
  1894. \end{lstlisting}
  1895. \end{minipage}\\
  1896. %
  1897. The output of the previous pass and of \code{explicate-control} is
  1898. shown below. Recall that the right-hand-side of a \key{let} executes
  1899. before its body, so the order of evaluation for this program is to
  1900. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1901. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1902. output of \code{explicate-control} makes this ordering explicit.\\
  1903. \begin{tabular}{lll}
  1904. \begin{minipage}{0.4\textwidth}
  1905. \begin{lstlisting}
  1906. (let ([y (let ([x.1 20])
  1907. (let ([x.2 22])
  1908. (+ x.1 x.2)))])
  1909. y)
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. locals: y x.1 x.2
  1918. start:
  1919. x.1 = 20;
  1920. x.2 = 22;
  1921. y = (+ x.1 x.2);
  1922. return y;
  1923. \end{lstlisting}
  1924. \end{minipage}
  1925. \end{tabular}
  1926. We recommend implementing \code{explicate-control} using two mutually
  1927. recursive functions: \code{explicate-tail} and
  1928. \code{explicate-assign}. The first function should be applied to
  1929. expressions in tail position whereas the second should be applied to
  1930. expressions that occur on the right-hand-side of a \key{let}.
  1931. %
  1932. The \code{explicate-tail} function takes an $R_1$ expression as input
  1933. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1934. list of formerly \key{let}-bound variables.
  1935. %
  1936. The \code{explicate-assign} function takes an $R_1$ expression, the
  1937. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1938. should come after the assignment (e.g., the code generated for the
  1939. body of the \key{let}). It returns a $\Tail$ and a list of
  1940. variables. The \code{explicate-assign} function is in
  1941. accumulator-passing style in that its third parameter is some $C_0$
  1942. code which it then adds to and returns. The reader might be tempted to
  1943. instead organize \code{explicate-assign} in a more direct fashion,
  1944. without the third parameter and perhaps using \code{append} to combine
  1945. statements. We warn against that alternative because the
  1946. accumulator-passing style is key to how we generate high-quality code
  1947. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1948. The top-level \code{explicate-control} function should invoke
  1949. \code{explicate-tail} on the body of the \key{program} and then
  1950. associate the \code{locals} symbol with the resulting list of
  1951. variables in the $\itm{info}$ field, as in the above example.
  1952. \section{Select Instructions}
  1953. \label{sec:select-r1}
  1954. \index{instruction selection}
  1955. In the \code{select-instructions} pass we begin the work of
  1956. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1957. this pass is a variant of x86 that still uses variables, so we add an
  1958. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1959. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1960. \code{select-instructions} in terms of three auxiliary functions, one
  1961. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1962. The cases for $\Atm$ are straightforward, variables stay
  1963. the same and integer constants are changed to immediates:
  1964. $\INT{n}$ changes to $\IMM{n}$.
  1965. Next we consider the cases for $\Stmt$, starting with arithmetic
  1966. operations. For example, in $C_0$ an addition operation can take the
  1967. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1968. need to use the \key{addq} instruction which does an in-place
  1969. update. So we must first move \code{10} to \code{x}. \\
  1970. \begin{tabular}{lll}
  1971. \begin{minipage}{0.4\textwidth}
  1972. \begin{lstlisting}
  1973. x = (+ 10 32);
  1974. \end{lstlisting}
  1975. \end{minipage}
  1976. &
  1977. $\Rightarrow$
  1978. &
  1979. \begin{minipage}{0.4\textwidth}
  1980. \begin{lstlisting}
  1981. movq $10, x
  1982. addq $32, x
  1983. \end{lstlisting}
  1984. \end{minipage}
  1985. \end{tabular} \\
  1986. %
  1987. There are cases that require special care to avoid generating
  1988. needlessly complicated code. If one of the arguments of the addition
  1989. is the same as the left-hand side of the assignment, then there is no
  1990. need for the extra move instruction. For example, the following
  1991. assignment statement can be translated into a single \key{addq}
  1992. instruction.\\
  1993. \begin{tabular}{lll}
  1994. \begin{minipage}{0.4\textwidth}
  1995. \begin{lstlisting}
  1996. x = (+ 10 x);
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. &
  2000. $\Rightarrow$
  2001. &
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}
  2004. addq $10, x
  2005. \end{lstlisting}
  2006. \end{minipage}
  2007. \end{tabular} \\
  2008. The \key{read} operation does not have a direct counterpart in x86
  2009. assembly, so we have instead implemented this functionality in the C
  2010. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2011. in the file \code{runtime.c}. In general, we refer to all of the
  2012. functionality in this file as the \emph{runtime system}\index{runtime system},
  2013. or simply the \emph{runtime} for short. When compiling your generated x86
  2014. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2015. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2016. the executable. For our purposes of code generation, all you need to
  2017. do is translate an assignment of \key{read} into some variable
  2018. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2019. function followed by a move from \code{rax} to the left-hand side.
  2020. The move from \code{rax} is needed because the return value from
  2021. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2022. \begin{tabular}{lll}
  2023. \begin{minipage}{0.3\textwidth}
  2024. \begin{lstlisting}
  2025. |$\itm{var}$| = (read);
  2026. \end{lstlisting}
  2027. \end{minipage}
  2028. &
  2029. $\Rightarrow$
  2030. &
  2031. \begin{minipage}{0.3\textwidth}
  2032. \begin{lstlisting}
  2033. callq read_int
  2034. movq %rax, |$\itm{var}$|
  2035. \end{lstlisting}
  2036. \end{minipage}
  2037. \end{tabular} \\
  2038. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2039. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2040. assignment to the \key{rax} register followed by a jump to the
  2041. conclusion of the program (so the conclusion needs to be labeled).
  2042. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2043. recursively and append the resulting instructions.
  2044. \begin{exercise}
  2045. \normalfont
  2046. Implement the \key{select-instructions} pass and test it on all of the
  2047. example programs that you created for the previous passes and create
  2048. three new example programs that are designed to exercise all of the
  2049. interesting code in this pass. Use the \key{interp-tests} function
  2050. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2051. your passes on the example programs.
  2052. \end{exercise}
  2053. \section{Assign Homes}
  2054. \label{sec:assign-r1}
  2055. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2056. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2057. Thus, the \key{assign-homes} pass is responsible for placing all of
  2058. the program variables in registers or on the stack. For runtime
  2059. efficiency, it is better to place variables in registers, but as there
  2060. are only 16 registers, some programs must necessarily resort to
  2061. placing some variables on the stack. In this chapter we focus on the
  2062. mechanics of placing variables on the stack. We study an algorithm for
  2063. placing variables in registers in
  2064. Chapter~\ref{ch:register-allocation-r1}.
  2065. Consider again the following $R_1$ program.
  2066. % s0_20.rkt
  2067. \begin{lstlisting}
  2068. (let ([a 42])
  2069. (let ([b a])
  2070. b))
  2071. \end{lstlisting}
  2072. For reference, we repeat the output of \code{select-instructions} on
  2073. the left and show the output of \code{assign-homes} on the right.
  2074. Recall that \key{explicate-control} associated the list of
  2075. variables with the \code{locals} symbol in the program's $\itm{info}$
  2076. field, so \code{assign-homes} has convenient access to the them. In
  2077. this example, we assign variable \code{a} to stack location
  2078. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2079. \begin{tabular}{l}
  2080. \begin{minipage}{0.4\textwidth}
  2081. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2082. locals: a b
  2083. start:
  2084. movq $42, a
  2085. movq a, b
  2086. movq b, %rax
  2087. jmp conclusion
  2088. \end{lstlisting}
  2089. \end{minipage}
  2090. {$\Rightarrow$}
  2091. \begin{minipage}{0.4\textwidth}
  2092. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2093. stack-space: 16
  2094. start:
  2095. movq $42, -8(%rbp)
  2096. movq -8(%rbp), -16(%rbp)
  2097. movq -16(%rbp), %rax
  2098. jmp conclusion
  2099. \end{lstlisting}
  2100. \end{minipage}
  2101. \end{tabular} \\
  2102. In the process of assigning variables to stack locations, it is
  2103. convenient to compute and store the size of the frame (in bytes) in
  2104. the $\itm{info}$ field of the \key{Program} node, with the key
  2105. \code{stack-space}, which will be needed later to generate the
  2106. procedure conclusion. The x86-64 standard requires the frame size to
  2107. be a multiple of 16 bytes.
  2108. \index{frame}
  2109. \begin{exercise}
  2110. \normalfont Implement the \key{assign-homes} pass and test it on all
  2111. of the example programs that you created for the previous passes pass.
  2112. We recommend that \key{assign-homes} take an extra parameter that is a
  2113. mapping of variable names to homes (stack locations for now). Use the
  2114. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2115. \key{utilities.rkt} to test your passes on the example programs.
  2116. \end{exercise}
  2117. \section{Patch Instructions}
  2118. \label{sec:patch-s0}
  2119. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2120. programs to $\text{x86}_0$ programs by making sure that each
  2121. instruction adheres to the restrictions of the x86 assembly language.
  2122. In particular, at most one argument of an instruction may be a memory
  2123. reference.
  2124. We return to the following running example.
  2125. % s0_20.rkt
  2126. \begin{lstlisting}
  2127. (let ([a 42])
  2128. (let ([b a])
  2129. b))
  2130. \end{lstlisting}
  2131. After the \key{assign-homes} pass, the above program has been translated to
  2132. the following. \\
  2133. \begin{minipage}{0.5\textwidth}
  2134. \begin{lstlisting}
  2135. stack-space: 16
  2136. start:
  2137. movq $42, -8(%rbp)
  2138. movq -8(%rbp), -16(%rbp)
  2139. movq -16(%rbp), %rax
  2140. jmp conclusion
  2141. \end{lstlisting}
  2142. \end{minipage}\\
  2143. The second \key{movq} instruction is problematic because both
  2144. arguments are stack locations. We suggest fixing this problem by
  2145. moving from the source location to the register \key{rax} and then
  2146. from \key{rax} to the destination location, as follows.
  2147. \begin{lstlisting}
  2148. movq -8(%rbp), %rax
  2149. movq %rax, -16(%rbp)
  2150. \end{lstlisting}
  2151. \begin{exercise}
  2152. \normalfont
  2153. Implement the \key{patch-instructions} pass and test it on all of the
  2154. example programs that you created for the previous passes and create
  2155. three new example programs that are designed to exercise all of the
  2156. interesting code in this pass. Use the \key{interp-tests} function
  2157. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2158. your passes on the example programs.
  2159. \end{exercise}
  2160. \section{Print x86}
  2161. \label{sec:print-x86}
  2162. The last step of the compiler from $R_1$ to x86 is to convert the
  2163. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2164. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2165. \key{format} and \key{string-append} functions are useful in this
  2166. regard. The main work that this step needs to perform is to create the
  2167. \key{main} function and the standard instructions for its prelude and
  2168. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2169. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2170. variables, so we suggest computing it in the \key{assign-homes} pass
  2171. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2172. of the \key{program} node.
  2173. %% Your compiled code should print the result of the program's execution
  2174. %% by using the \code{print\_int} function provided in
  2175. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2176. %% far, this final result should be stored in the \key{rax} register.
  2177. %% We'll talk more about how to perform function calls with arguments in
  2178. %% general later on, but for now, place the following after the compiled
  2179. %% code for the $R_1$ program but before the conclusion:
  2180. %% \begin{lstlisting}
  2181. %% movq %rax, %rdi
  2182. %% callq print_int
  2183. %% \end{lstlisting}
  2184. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2185. %% stores the first argument to be passed into \key{print\_int}.
  2186. If you want your program to run on Mac OS X, your code needs to
  2187. determine whether or not it is running on a Mac, and prefix
  2188. underscores to labels like \key{main}. You can determine the platform
  2189. with the Racket call \code{(system-type 'os)}, which returns
  2190. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2191. %% In addition to
  2192. %% placing underscores on \key{main}, you need to put them in front of
  2193. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2194. %% \_print\_int}).
  2195. \begin{exercise}
  2196. \normalfont Implement the \key{print-x86} pass and test it on all of
  2197. the example programs that you created for the previous passes. Use the
  2198. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2199. \key{utilities.rkt} to test your complete compiler on the example
  2200. programs. See the \key{run-tests.rkt} script in the student support
  2201. code for an example of how to use \key{compiler-tests}. Also, remember
  2202. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2203. \key{gcc}.
  2204. \end{exercise}
  2205. \section{Challenge: Partial Evaluator for $R_1$}
  2206. \label{sec:pe-R1}
  2207. \index{partial evaluation}
  2208. This section describes optional challenge exercises that involve
  2209. adapting and improving the partial evaluator for $R_0$ that was
  2210. introduced in Section~\ref{sec:partial-evaluation}.
  2211. \begin{exercise}\label{ex:pe-R1}
  2212. \normalfont
  2213. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2214. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2215. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2216. and variables to the $R_0$ language, so you will need to add cases for
  2217. them in the \code{pe-exp} function. Also, note that the \key{program}
  2218. form changes slightly to include an $\itm{info}$ field. Once
  2219. complete, add the partial evaluation pass to the front of your
  2220. compiler and make sure that your compiler still passes all of the
  2221. tests.
  2222. \end{exercise}
  2223. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2224. \begin{exercise}
  2225. \normalfont
  2226. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2227. \code{pe-add} auxiliary functions with functions that know more about
  2228. arithmetic. For example, your partial evaluator should translate
  2229. \begin{lstlisting}
  2230. (+ 1 (+ (read) 1))
  2231. \end{lstlisting}
  2232. into
  2233. \begin{lstlisting}
  2234. (+ 2 (read))
  2235. \end{lstlisting}
  2236. To accomplish this, the \code{pe-exp} function should produce output
  2237. in the form of the $\itm{residual}$ non-terminal of the following
  2238. grammar.
  2239. \[
  2240. \begin{array}{lcl}
  2241. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2242. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2243. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2244. \end{array}
  2245. \]
  2246. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2247. that their inputs are $\itm{residual}$ expressions and they should
  2248. return $\itm{residual}$ expressions. Once the improvements are
  2249. complete, make sure that your compiler still passes all of the tests.
  2250. After all, fast code is useless if it produces incorrect results!
  2251. \end{exercise}
  2252. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2253. \chapter{Register Allocation}
  2254. \label{ch:register-allocation-r1}
  2255. \index{register allocation}
  2256. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2257. make our life easier. However, we can improve the performance of the
  2258. generated code if we instead place some variables into registers. The
  2259. CPU can access a register in a single cycle, whereas accessing the
  2260. stack takes many cycles if the relevant data is in cache or many more
  2261. to access main memory if the data is not in cache.
  2262. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2263. serves as a running example. We show the source program and also the
  2264. output of instruction selection. At that point the program is almost
  2265. x86 assembly but not quite; it still contains variables instead of
  2266. stack locations or registers.
  2267. \begin{figure}
  2268. \begin{minipage}{0.45\textwidth}
  2269. Example $R_1$ program:
  2270. % s0_28.rkt
  2271. \begin{lstlisting}
  2272. (let ([v 1])
  2273. (let ([w 42])
  2274. (let ([x (+ v 7)])
  2275. (let ([y x])
  2276. (let ([z (+ x w)])
  2277. (+ z (- y)))))))
  2278. \end{lstlisting}
  2279. \end{minipage}
  2280. \begin{minipage}{0.45\textwidth}
  2281. After instruction selection:
  2282. \begin{lstlisting}
  2283. locals: (v w x y z t)
  2284. start:
  2285. movq $1, v
  2286. movq $42, w
  2287. movq v, x
  2288. addq $7, x
  2289. movq x, y
  2290. movq x, z
  2291. addq w, z
  2292. movq y, t
  2293. negq t
  2294. movq z, %rax
  2295. addq t, %rax
  2296. jmp conclusion
  2297. \end{lstlisting}
  2298. \end{minipage}
  2299. \caption{A running example program for register allocation.}
  2300. \label{fig:reg-eg}
  2301. \end{figure}
  2302. The goal of register allocation is to fit as many variables into
  2303. registers as possible. A program sometimes has more variables than
  2304. registers, so we cannot map each variable to a different
  2305. register. Fortunately, it is common for different variables to be
  2306. needed during different periods of time during program execution, and
  2307. in such cases several variables can be mapped to the same register.
  2308. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2309. After the variable \code{x} is moved to \code{z} it is no longer
  2310. needed. Variable \code{y}, on the other hand, is used only after this
  2311. point, so \code{x} and \code{y} could share the same register. The
  2312. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2313. where a variable is needed. Once we have that information, we compute
  2314. which variables are needed at the same time, i.e., which ones
  2315. \emph{interfere} with each other, and represent this relation as an
  2316. undirected graph whose vertices are variables and edges indicate when
  2317. two variables interfere (Section~\ref{sec:build-interference}). We
  2318. then model register allocation as a graph coloring problem, which we
  2319. discuss in Section~\ref{sec:graph-coloring}.
  2320. In the event that we run out of registers despite these efforts, we
  2321. place the remaining variables on the stack, similar to what we did in
  2322. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2323. for assigning a variable to a stack location. The process of spilling
  2324. variables is handled as part of the graph coloring process described
  2325. in \ref{sec:graph-coloring}.
  2326. We make the simplifying assumption that each variable is assigned to
  2327. one location (a register or stack address). A more sophisticated
  2328. approach is to assign a variable to one or more locations in different
  2329. regions of the program. For example, if a variable is used many times
  2330. in short sequence and then only used again after many other
  2331. instructions, it could be more efficient to assign the variable to a
  2332. register during the intial sequence and then move it to the stack for
  2333. the rest of its lifetime. We refer the interested reader to
  2334. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2335. about this approach.
  2336. % discuss prioritizing variables based on how much they are used.
  2337. \section{Registers and Calling Conventions}
  2338. \label{sec:calling-conventions}
  2339. \index{calling conventions}
  2340. As we perform register allocation, we need to be aware of the
  2341. conventions that govern the way in which registers interact with
  2342. function calls, such as calls to the \code{read\_int} function in our
  2343. generated code and even the call that the operating system makes to
  2344. execute our \code{main} function. The convention for x86 regarding
  2345. how functions share the use of registers is that the caller is
  2346. responsible for freeing up some registers, the \emph{caller-saved
  2347. registers}, prior to the function call, and the callee is
  2348. responsible for preserving the values of some other registers, the
  2349. \emph{callee-saved registers}. \index{caller-saved registers}
  2350. \index{callee-saved registers} The caller-saved registers are
  2351. \begin{lstlisting}
  2352. rax rcx rdx rsi rdi r8 r9 r10 r11
  2353. \end{lstlisting}
  2354. while the callee-saved registers are
  2355. \begin{lstlisting}
  2356. rsp rbp rbx r12 r13 r14 r15
  2357. \end{lstlisting}
  2358. We can think about this caller/callee convention from two points of
  2359. view, the caller view and the callee view:
  2360. \begin{itemize}
  2361. \item The caller should assume that all the caller-saved registers get
  2362. overwritten with arbitrary values by the callee. On the other hand,
  2363. the caller can safely assume that all the callee-saved registers
  2364. contain the same values after the call that they did before the
  2365. call.
  2366. \item The callee can freely use any of the caller-saved registers.
  2367. However, if the callee wants to use a callee-saved register, the
  2368. callee must arrange to put the original value back in the register
  2369. prior to returning to the caller, which is usually accomplished by
  2370. saving the value to the stack in the prelude of the function and
  2371. restoring the value in the conclusion of the function.
  2372. \end{itemize}
  2373. In x86, registers are also used for passing arguments to a function
  2374. and for the return value. In particular, the first six arguments of a
  2375. function are passed in the following six registers, in the order
  2376. given.
  2377. \begin{lstlisting}
  2378. rdi rsi rdx rcx r8 r9
  2379. \end{lstlisting}
  2380. If there are more than six arguments, then the convention is to use
  2381. space on the frame of the caller for the rest of the
  2382. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2383. need more than six arguments. For now, the only function we care about
  2384. is \code{read\_int} and it takes zero argument.
  2385. %
  2386. The register \code{rax} is for the return value of a function.
  2387. The next question is how these calling conventions impact register
  2388. allocation. Consider the $R_1$ program in
  2389. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2390. example from the caller point of view and then from the callee point
  2391. of view.
  2392. The program makes two calls to the \code{read} function. Also, the
  2393. variable \code{x} is in-use during the second call to \code{read}, so
  2394. we need to make sure that the value in \code{x} does not get
  2395. accidentally wiped out by the call to \code{read}. One obvious
  2396. approach is to save all the values in caller-saved registers to the
  2397. stack prior to each function call, and restore them after each
  2398. call. That way, if the register allocator chooses to assign \code{x}
  2399. to a caller-saved register, its value will be preserved accross the
  2400. call to \code{read}. However, the disadvantage of this approach is
  2401. that saving and restoring to the stack is relatively slow. If \code{x}
  2402. is not used many times, it may be better to assign \code{x} to a stack
  2403. location in the first place. Or better yet, if we can arrange for
  2404. \code{x} to be placed in a callee-saved register, then it won't need
  2405. to be saved and restored during function calls.
  2406. The approach that we recommend for variables that are in-use during a
  2407. function call is to either assign them to callee-saved registers or to
  2408. spill them to the stack. On the other hand, for variables that are not
  2409. in-use during a function call, we try the following alternatives in
  2410. order 1) look for an available caller-saved register (to leave room
  2411. for other variables in the callee-saved register), 2) look for a
  2412. callee-saved register, and 3) spill the variable to the stack.
  2413. It is straightforward to implement this approach in a graph coloring
  2414. register allocator. First, we know which variables are in-use during
  2415. every function call because we compute that information for every
  2416. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2417. build the interference graph (Section~\ref{sec:build-interference}),
  2418. we can place an edge between each of these variables and the
  2419. caller-saved registers in the interference graph. This will prevent
  2420. the graph coloring algorithm from assigning those variables to
  2421. caller-saved registers.
  2422. Returning to the example in
  2423. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2424. generated x86 code on the right-hand side, focusing on the
  2425. \code{start} block. Notice that variable \code{x} is assigned to
  2426. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2427. place during the second call to \code{read\_int}. Next, notice that
  2428. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2429. because there are no function calls in the remainder of the block.
  2430. Next we analyze the example from the callee point of view, focusing on
  2431. the prelude and conclusion of the \code{main} function. As usual the
  2432. prelude begins with saving the \code{rbp} register to the stack and
  2433. setting the \code{rbp} to the current stack pointer. We now know why
  2434. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2435. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2436. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2437. variable (\code{x}). There are several more callee-saved register that
  2438. are not saved in the prelude because they were not assigned to
  2439. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2440. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2441. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2442. from the stack with a \code{popq} instruction.
  2443. \index{prelude}\index{conclusion}
  2444. \begin{figure}[tp]
  2445. \begin{minipage}{0.45\textwidth}
  2446. Example $R_1$ program:
  2447. %s0_14.rkt
  2448. \begin{lstlisting}
  2449. (let ([x (read)])
  2450. (let ([y (read)])
  2451. (+ (+ x y) 42)))
  2452. \end{lstlisting}
  2453. \end{minipage}
  2454. \begin{minipage}{0.45\textwidth}
  2455. Generated x86 assembly:
  2456. \begin{lstlisting}
  2457. start:
  2458. callq read_int
  2459. movq %rax, %rbx
  2460. callq read_int
  2461. movq %rax, %rcx
  2462. addq %rcx, %rbx
  2463. movq %rbx, %rax
  2464. addq $42, %rax
  2465. jmp _conclusion
  2466. .globl main
  2467. main:
  2468. pushq %rbp
  2469. movq %rsp, %rbp
  2470. pushq %rbx
  2471. subq $8, %rsp
  2472. jmp start
  2473. conclusion:
  2474. addq $8, %rsp
  2475. popq %rbx
  2476. popq %rbp
  2477. retq
  2478. \end{lstlisting}
  2479. \end{minipage}
  2480. \caption{An example with function calls.}
  2481. \label{fig:example-calling-conventions}
  2482. \end{figure}
  2483. \clearpage
  2484. \section{Liveness Analysis}
  2485. \label{sec:liveness-analysis-r1}
  2486. \index{liveness analysis}
  2487. A variable or register is \emph{live} at a program point if its
  2488. current value is used at some later point in the program. We
  2489. refer to variables and registers collectively as \emph{locations}.
  2490. %
  2491. Consider the following code fragment in which there are two writes to
  2492. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2493. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2494. movq $5, a
  2495. movq $30, b
  2496. movq a, c
  2497. movq $10, b
  2498. addq b, c
  2499. \end{lstlisting}
  2500. The answer is no because the integer \code{30} written to \code{b} on
  2501. line 2 is never used. The variable \code{b} is read on line 5 and
  2502. there is an intervening write to \code{b} on line 4, so the read on
  2503. line 5 receives the value written on line 4, not line 2.
  2504. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2505. \small
  2506. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2507. A \emph{set} is an unordered collection of elements without duplicates.
  2508. \index{set}
  2509. \begin{description}
  2510. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2511. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2512. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2513. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2514. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2515. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2516. \end{description}
  2517. \end{tcolorbox}
  2518. \end{wrapfigure}
  2519. The live locations can be computed by traversing the instruction
  2520. sequence back to front (i.e., backwards in execution order). Let
  2521. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2522. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2523. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2524. locations before instruction $I_k$. The live locations after an
  2525. instruction are always the same as the live locations before the next
  2526. instruction. \index{live-after} \index{live-before}
  2527. \begin{equation} \label{eq:live-after-before-next}
  2528. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2529. \end{equation}
  2530. To start things off, there are no live locations after the last
  2531. instruction\footnote{Technically, the \code{rax} register is live
  2532. but we do not use it for register allocation.}, so
  2533. \begin{equation}\label{eq:live-last-empty}
  2534. L_{\mathsf{after}}(n) = \emptyset
  2535. \end{equation}
  2536. We then apply the following rule repeatedly, traversing the
  2537. instruction sequence back to front.
  2538. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2539. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2540. \end{equation}
  2541. where $W(k)$ are the locations written to by instruction $I_k$ and
  2542. $R(k)$ are the locations read by instruction $I_k$.
  2543. Let us walk through the above example, applying these formulas
  2544. starting with the instruction on line 5. We collect the answers in the
  2545. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2546. instruction is $\emptyset$ because it is the last instruction
  2547. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2548. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2549. variables \code{b} and \code{c}
  2550. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2551. \[
  2552. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2553. \]
  2554. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2555. the live-before set from line 5 to be the live-after set for this
  2556. instruction (formula~\ref{eq:live-after-before-next}).
  2557. \[
  2558. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2559. \]
  2560. This move instruction writes to \code{b} and does not read from any
  2561. variables, so we have the following live-before set
  2562. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2563. \[
  2564. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2565. \]
  2566. The live-before for instruction \code{movq a, c}
  2567. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2568. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2569. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2570. variable that is not live and does not read from a variable.
  2571. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2572. because it writes to variable \code{a}.
  2573. \begin{center}
  2574. \begin{minipage}{0.45\textwidth}
  2575. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2576. movq $5, a
  2577. movq $30, b
  2578. movq a, c
  2579. movq $10, b
  2580. addq b, c
  2581. \end{lstlisting}
  2582. \end{minipage}
  2583. \vrule\hspace{10pt}
  2584. \begin{minipage}{0.45\textwidth}
  2585. \begin{align*}
  2586. L_{\mathsf{before}}(1)= \emptyset,
  2587. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2588. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2589. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2590. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2591. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2592. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2593. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2594. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2595. L_{\mathsf{after}}(5)= \emptyset
  2596. \end{align*}
  2597. \end{minipage}
  2598. \end{center}
  2599. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2600. the running example program, with the live-before and live-after sets
  2601. shown between each instruction to make the figure easy to read.
  2602. \begin{figure}[tp]
  2603. \hspace{20pt}
  2604. \begin{minipage}{0.45\textwidth}
  2605. \begin{lstlisting}
  2606. |$\{\}$|
  2607. movq $1, v
  2608. |$\{\ttm{v}\}$|
  2609. movq $42, w
  2610. |$\{\ttm{v},\ttm{w}\}$|
  2611. movq v, x
  2612. |$\{\ttm{w},\ttm{x}\}$|
  2613. addq $7, x
  2614. |$\{\ttm{w},\ttm{x}\}$|
  2615. movq x, y
  2616. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2617. movq x, z
  2618. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2619. addq w, z
  2620. |$\{\ttm{y},\ttm{z}\}$|
  2621. movq y, t
  2622. |$\{\ttm{t},\ttm{z}\}$|
  2623. negq t
  2624. |$\{\ttm{t},\ttm{z}\}$|
  2625. movq z, %rax
  2626. |$\{\ttm{rax},\ttm{t}\}$|
  2627. addq t, %rax
  2628. |$\{\}$|
  2629. jmp conclusion
  2630. |$\{\}$|
  2631. \end{lstlisting}
  2632. \end{minipage}
  2633. \caption{The running example annotated with live-after sets.}
  2634. \label{fig:live-eg}
  2635. \end{figure}
  2636. \begin{exercise}\normalfont
  2637. Implement the compiler pass named \code{uncover-live} that computes
  2638. the live-after sets. We recommend storing the live-after sets (a list
  2639. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2640. structure.
  2641. %
  2642. We recommend organizing your code to use a helper function that takes
  2643. a list of instructions and an initial live-after set (typically empty)
  2644. and returns the list of live-after sets.
  2645. %
  2646. We recommend creating helper functions to 1) compute the set of
  2647. locations that appear in an argument (of an instruction), 2) compute
  2648. the locations read by an instruction which corresponds to the $R$
  2649. function discussed above, and 3) the locations written by an
  2650. instruction which corresponds to $W$. The \code{callq} instruction
  2651. should include all of the caller-saved registers in its write-set $W$
  2652. because the calling convention says that those registers may be
  2653. written to during the function call. Likewise, the \code{callq}
  2654. instruction should include the appropriate number of argument passing
  2655. registers in its read-set $R$, depending on the arity of the function
  2656. being called. (This is why the abstract syntax for \code{callq}
  2657. includes the arity.)
  2658. \end{exercise}
  2659. \section{Building the Interference Graph}
  2660. \label{sec:build-interference}
  2661. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2662. \small
  2663. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2664. A \emph{graph} is a collection of vertices and edges where each
  2665. edge connects two vertices. A graph is \emph{directed} if each
  2666. edge points from a source to a target. Otherwise the graph is
  2667. \emph{undirected}.
  2668. \index{graph}\index{directed graph}\index{undirected graph}
  2669. \begin{description}
  2670. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2671. directed graph from a list of edges. Each edge is a list
  2672. containing the source and target vertex.
  2673. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2674. undirected graph from a list of edges. Each edge is represented by
  2675. a list containing two vertices.
  2676. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2677. inserts a vertex into the graph.
  2678. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2679. inserts an edge between the two vertices into the graph.
  2680. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2681. returns a sequence of all the neighbors of the given vertex.
  2682. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2683. returns a sequence of all the vertices in the graph.
  2684. \end{description}
  2685. \end{tcolorbox}
  2686. \end{wrapfigure}
  2687. Based on the liveness analysis, we know where each variable is needed.
  2688. However, during register allocation, we need to answer questions of
  2689. the specific form: are variables $u$ and $v$ live at the same time?
  2690. (And therefore cannot be assigned to the same register.) To make this
  2691. question easier to answer, we create an explicit data structure, an
  2692. \emph{interference graph}\index{interference graph}. An interference
  2693. graph is an undirected graph that has an edge between two variables if
  2694. they are live at the same time, that is, if they interfere with each
  2695. other.
  2696. The most obvious way to compute the interference graph is to look at
  2697. the set of live location between each statement in the program and add
  2698. an edge to the graph for every pair of variables in the same set.
  2699. This approach is less than ideal for two reasons. First, it can be
  2700. expensive because it takes $O(n^2)$ time to look at every pair in a
  2701. set of $n$ live locations. Second, there is a special case in which
  2702. two locations that are live at the same time do not actually interfere
  2703. with each other: when they both contain the same value because we have
  2704. assigned one to the other.
  2705. A better way to compute the interference graph is to focus on the
  2706. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2707. instruction to overwrite something in a live location. So for each
  2708. instruction, we create an edge between the locations being written to
  2709. and all the other live locations. (Except that one should not create
  2710. self edges.) Recall that for a \key{callq} instruction, we consider
  2711. all of the caller-saved registers as being written to, so an edge will
  2712. be added between every live variable and every caller-saved
  2713. register. For \key{movq}, we deal with the above-mentioned special
  2714. case by not adding an edge between a live variable $v$ and destination
  2715. $d$ if $v$ matches the source of the move. So we have the following
  2716. two rules.
  2717. \begin{enumerate}
  2718. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2719. $d$, then add the edge $(d,v)$ for every $v \in
  2720. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2721. \item For any other instruction $I_k$, for every $d \in W(k)$
  2722. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2723. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2724. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2725. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2726. %% \item If instruction $I_k$ is of the form \key{callq}
  2727. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2728. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2729. \end{enumerate}
  2730. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2731. the above rules to each instruction. We highlight a few of the
  2732. instructions and then refer the reader to
  2733. Figure~\ref{fig:interference-results} for all the interference
  2734. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2735. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2736. interference edges because the one live variable \code{v} is also the
  2737. destination of this instruction.
  2738. %
  2739. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2740. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2741. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2742. %
  2743. Next we skip forward to the instruction \lstinline{movq x, y}.
  2744. \begin{figure}[tbp]
  2745. \begin{quote}
  2746. \begin{tabular}{ll}
  2747. \lstinline!movq $1, v!& no interference by rule 3,\\
  2748. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2749. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2750. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2751. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2752. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2753. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2754. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2755. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2756. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2757. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2758. \lstinline!jmp conclusion!& no interference.
  2759. \end{tabular}
  2760. \end{quote}
  2761. \caption{Interference results for the running example.}
  2762. \label{fig:interference-results}
  2763. \end{figure}
  2764. The resulting interference graph is shown in
  2765. Figure~\ref{fig:interfere}.
  2766. \begin{figure}[tbp]
  2767. \large
  2768. \[
  2769. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2770. \node (rax) at (0,0) {$\ttm{rax}$};
  2771. \node (t1) at (0,2) {$\ttm{t}$};
  2772. \node (z) at (3,2) {$\ttm{z}$};
  2773. \node (x) at (6,2) {$\ttm{x}$};
  2774. \node (y) at (3,0) {$\ttm{y}$};
  2775. \node (w) at (6,0) {$\ttm{w}$};
  2776. \node (v) at (9,0) {$\ttm{v}$};
  2777. \draw (t1) to (rax);
  2778. \draw (t1) to (z);
  2779. \draw (z) to (y);
  2780. \draw (z) to (w);
  2781. \draw (x) to (w);
  2782. \draw (y) to (w);
  2783. \draw (v) to (w);
  2784. \end{tikzpicture}
  2785. \]
  2786. \caption{The interference graph of the example program.}
  2787. \label{fig:interfere}
  2788. \end{figure}
  2789. %% Our next concern is to choose a data structure for representing the
  2790. %% interference graph. There are many choices for how to represent a
  2791. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2792. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2793. %% data structure is to study the algorithm that uses the data structure,
  2794. %% determine what operations need to be performed, and then choose the
  2795. %% data structure that provide the most efficient implementations of
  2796. %% those operations. Often times the choice of data structure can have an
  2797. %% effect on the time complexity of the algorithm, as it does here. If
  2798. %% you skim the next section, you will see that the register allocation
  2799. %% algorithm needs to ask the graph for all of its vertices and, given a
  2800. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2801. %% correct choice of graph representation is that of an adjacency
  2802. %% list. There are helper functions in \code{utilities.rkt} for
  2803. %% representing graphs using the adjacency list representation:
  2804. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2805. %% (Appendix~\ref{appendix:utilities}).
  2806. %% %
  2807. %% \margincomment{\footnotesize To do: change to use the
  2808. %% Racket graph library. \\ --Jeremy}
  2809. %% %
  2810. %% In particular, those functions use a hash table to map each vertex to
  2811. %% the set of adjacent vertices, and the sets are represented using
  2812. %% Racket's \key{set}, which is also a hash table.
  2813. \begin{exercise}\normalfont
  2814. Implement the compiler pass named \code{build-interference} according
  2815. to the algorithm suggested above. We recommend using the \code{graph}
  2816. package to create and inspect the interference graph. The output
  2817. graph of this pass should be stored in the $\itm{info}$ field of the
  2818. program, under the key \code{conflicts}.
  2819. \end{exercise}
  2820. \section{Graph Coloring via Sudoku}
  2821. \label{sec:graph-coloring}
  2822. \index{graph coloring}
  2823. \index{Sudoku}
  2824. \index{color}
  2825. We come to the main event, mapping variables to registers (or to stack
  2826. locations in the event that we run out of registers). We need to make
  2827. sure that two variables do not get mapped to the same register if the
  2828. two variables interfere with each other. Thinking about the
  2829. interference graph, this means that adjacent vertices must be mapped
  2830. to different registers. If we think of registers as colors, the
  2831. register allocation problem becomes the widely-studied graph coloring
  2832. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2833. The reader may be more familiar with the graph coloring problem than he
  2834. or she realizes; the popular game of Sudoku is an instance of the
  2835. graph coloring problem. The following describes how to build a graph
  2836. out of an initial Sudoku board.
  2837. \begin{itemize}
  2838. \item There is one vertex in the graph for each Sudoku square.
  2839. \item There is an edge between two vertices if the corresponding squares
  2840. are in the same row, in the same column, or if the squares are in
  2841. the same $3\times 3$ region.
  2842. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2843. \item Based on the initial assignment of numbers to squares in the
  2844. Sudoku board, assign the corresponding colors to the corresponding
  2845. vertices in the graph.
  2846. \end{itemize}
  2847. If you can color the remaining vertices in the graph with the nine
  2848. colors, then you have also solved the corresponding game of Sudoku.
  2849. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2850. the corresponding graph with colored vertices. We map the Sudoku
  2851. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2852. sampling of the vertices (the colored ones) because showing edges for
  2853. all of the vertices would make the graph unreadable.
  2854. \begin{figure}[tbp]
  2855. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2856. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2857. \caption{A Sudoku game board and the corresponding colored graph.}
  2858. \label{fig:sudoku-graph}
  2859. \end{figure}
  2860. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2861. strategies to come up with an algorithm for allocating registers. For
  2862. example, one of the basic techniques for Sudoku is called Pencil
  2863. Marks. The idea is to use a process of elimination to determine what
  2864. numbers no longer make sense for a square and write down those
  2865. numbers in the square (writing very small). For example, if the number
  2866. $1$ is assigned to a square, then by process of elimination, you can
  2867. write the pencil mark $1$ in all the squares in the same row, column,
  2868. and region. Many Sudoku computer games provide automatic support for
  2869. Pencil Marks.
  2870. %
  2871. The Pencil Marks technique corresponds to the notion of
  2872. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2873. The saturation of a
  2874. vertex, in Sudoku terms, is the set of numbers that are no longer
  2875. available. In graph terminology, we have the following definition:
  2876. \begin{equation*}
  2877. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2878. \text{ and } \mathrm{color}(v) = c \}
  2879. \end{equation*}
  2880. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2881. edge with $u$.
  2882. Using the Pencil Marks technique leads to a simple strategy for
  2883. filling in numbers: if there is a square with only one possible number
  2884. left, then choose that number! But what if there are no squares with
  2885. only one possibility left? One brute-force approach is to try them
  2886. all: choose the first and if it ultimately leads to a solution,
  2887. great. If not, backtrack and choose the next possibility. One good
  2888. thing about Pencil Marks is that it reduces the degree of branching in
  2889. the search tree. Nevertheless, backtracking can be horribly time
  2890. consuming. One way to reduce the amount of backtracking is to use the
  2891. most-constrained-first heuristic. That is, when choosing a square,
  2892. always choose one with the fewest possibilities left (the vertex with
  2893. the highest saturation). The idea is that choosing highly constrained
  2894. squares earlier rather than later is better because later on there may
  2895. not be any possibilities left for those squares.
  2896. However, register allocation is easier than Sudoku because the
  2897. register allocator can map variables to stack locations when the
  2898. registers run out. Thus, it makes sense to drop backtracking in favor
  2899. of greedy search, that is, make the best choice at the time and keep
  2900. going. We still wish to minimize the number of colors needed, so
  2901. keeping the most-constrained-first heuristic is a good idea.
  2902. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2903. algorithm for register allocation based on saturation and the
  2904. most-constrained-first heuristic. It is roughly equivalent to the
  2905. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2906. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2907. Sudoku, the algorithm represents colors with integers. The integers
  2908. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2909. register allocation. The integers $k$ and larger correspond to stack
  2910. locations. The registers that are not used for register allocation,
  2911. such as \code{rax}, are assigned to negative integers. In particular,
  2912. we assign $-1$ to \code{rax}.
  2913. \begin{figure}[btp]
  2914. \centering
  2915. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2916. Algorithm: DSATUR
  2917. Input: a graph |$G$|
  2918. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2919. |$W \gets \mathrm{vertices}(G)$|
  2920. while |$W \neq \emptyset$| do
  2921. pick a vertex |$u$| from |$W$| with the highest saturation,
  2922. breaking ties randomly
  2923. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2924. |$\mathrm{color}[u] \gets c$|
  2925. |$W \gets W - \{u\}$|
  2926. \end{lstlisting}
  2927. \caption{The saturation-based greedy graph coloring algorithm.}
  2928. \label{fig:satur-algo}
  2929. \end{figure}
  2930. With this algorithm in hand, let us return to the running example and
  2931. consider how to color the interference graph in
  2932. Figure~\ref{fig:interfere}.
  2933. %
  2934. We color the vertices for registers with their own color. For example,
  2935. \code{rax} is assigned the color $-1$. We then update the saturation
  2936. for their neighboring vertices. In this case, the saturation for
  2937. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2938. so they annotated with a dash, and their saturation sets are empty.
  2939. \[
  2940. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2941. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2942. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2943. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2944. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2945. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2946. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2947. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2948. \draw (t1) to (rax);
  2949. \draw (t1) to (z);
  2950. \draw (z) to (y);
  2951. \draw (z) to (w);
  2952. \draw (x) to (w);
  2953. \draw (y) to (w);
  2954. \draw (v) to (w);
  2955. \end{tikzpicture}
  2956. \]
  2957. The algorithm says to select a maximally saturated vertex. So we pick
  2958. $\ttm{t}$ and color it with the first available integer, which is
  2959. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2960. because they interfere with $\ttm{t}$.
  2961. \[
  2962. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2963. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2964. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2965. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2966. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2967. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2968. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2969. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2970. \draw (t1) to (rax);
  2971. \draw (t1) to (z);
  2972. \draw (z) to (y);
  2973. \draw (z) to (w);
  2974. \draw (x) to (w);
  2975. \draw (y) to (w);
  2976. \draw (v) to (w);
  2977. \end{tikzpicture}
  2978. \]
  2979. We repeat the process, selecting another maximally saturated
  2980. vertex, which is \code{z}, and color it with the first available
  2981. number, which is $1$. We add $1$ to the saturations for the
  2982. neighboring vertices \code{t}, \code{y}, and \code{w}.
  2983. \[
  2984. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2985. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2986. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  2987. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2988. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2989. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  2990. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  2991. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2992. \draw (t1) to (rax);
  2993. \draw (t1) to (z);
  2994. \draw (z) to (y);
  2995. \draw (z) to (w);
  2996. \draw (x) to (w);
  2997. \draw (y) to (w);
  2998. \draw (v) to (w);
  2999. \end{tikzpicture}
  3000. \]
  3001. The most saturated vertices are now \code{w} and \code{y}. We color
  3002. \code{w} with the first available color, which is $0$.
  3003. \[
  3004. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3005. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3006. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3007. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3008. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3009. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3010. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3011. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3012. \draw (t1) to (rax);
  3013. \draw (t1) to (z);
  3014. \draw (z) to (y);
  3015. \draw (z) to (w);
  3016. \draw (x) to (w);
  3017. \draw (y) to (w);
  3018. \draw (v) to (w);
  3019. \end{tikzpicture}
  3020. \]
  3021. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3022. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3023. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3024. and \code{z}, whose colors are $0$ and $1$ respectively.
  3025. \[
  3026. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3027. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3028. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3029. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3030. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3031. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3032. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3033. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3034. \draw (t1) to (rax);
  3035. \draw (t1) to (z);
  3036. \draw (z) to (y);
  3037. \draw (z) to (w);
  3038. \draw (x) to (w);
  3039. \draw (y) to (w);
  3040. \draw (v) to (w);
  3041. \end{tikzpicture}
  3042. \]
  3043. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3044. \[
  3045. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3046. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3047. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3048. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3049. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3050. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3051. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3052. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3053. \draw (t1) to (rax);
  3054. \draw (t1) to (z);
  3055. \draw (z) to (y);
  3056. \draw (z) to (w);
  3057. \draw (x) to (w);
  3058. \draw (y) to (w);
  3059. \draw (v) to (w);
  3060. \end{tikzpicture}
  3061. \]
  3062. In the last step of the algorithm, we color \code{x} with $1$.
  3063. \[
  3064. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3065. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3066. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3067. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3068. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3069. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3070. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3071. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3072. \draw (t1) to (rax);
  3073. \draw (t1) to (z);
  3074. \draw (z) to (y);
  3075. \draw (z) to (w);
  3076. \draw (x) to (w);
  3077. \draw (y) to (w);
  3078. \draw (v) to (w);
  3079. \end{tikzpicture}
  3080. \]
  3081. With the coloring complete, we finalize the assignment of variables to
  3082. registers and stack locations. Recall that if we have $k$ registers to
  3083. use for allocation, we map the first $k$ colors to registers and the
  3084. rest to stack locations. Suppose for the moment that we have just one
  3085. register to use for register allocation, \key{rcx}. Then the following
  3086. is the mapping of colors to registers and stack allocations.
  3087. \[
  3088. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3089. \]
  3090. Putting this mapping together with the above coloring of the
  3091. variables, we arrive at the following assignment of variables to
  3092. registers and stack locations.
  3093. \begin{gather*}
  3094. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3095. \ttm{w} \mapsto \key{\%rcx}, \,
  3096. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3097. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3098. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3099. \ttm{t} \mapsto \key{\%rcx} \}
  3100. \end{gather*}
  3101. Applying this assignment to our running example, on the left, yields
  3102. the program on the right.
  3103. % why frame size of 32? -JGS
  3104. \begin{center}
  3105. \begin{minipage}{0.3\textwidth}
  3106. \begin{lstlisting}
  3107. movq $1, v
  3108. movq $42, w
  3109. movq v, x
  3110. addq $7, x
  3111. movq x, y
  3112. movq x, z
  3113. addq w, z
  3114. movq y, t
  3115. negq t
  3116. movq z, %rax
  3117. addq t, %rax
  3118. jmp conclusion
  3119. \end{lstlisting}
  3120. \end{minipage}
  3121. $\Rightarrow\qquad$
  3122. \begin{minipage}{0.45\textwidth}
  3123. \begin{lstlisting}
  3124. movq $1, %rcx
  3125. movq $42, %rcx
  3126. movq %rcx, -8(%rbp)
  3127. addq $7, -8(%rbp)
  3128. movq -8(%rbp), -16(%rbp)
  3129. movq -8(%rbp), -8(%rbp)
  3130. addq %rcx, -8(%rbp)
  3131. movq -16(%rbp), %rcx
  3132. negq %rcx
  3133. movq -8(%rbp), %rax
  3134. addq %rcx, %rax
  3135. jmp conclusion
  3136. \end{lstlisting}
  3137. \end{minipage}
  3138. \end{center}
  3139. The resulting program is almost an x86 program. The remaining step is
  3140. the patch instructions pass. In this example, the trivial move of
  3141. \code{-8(\%rbp)} to itself is deleted and the addition of
  3142. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3143. \code{rax} as follows.
  3144. \begin{lstlisting}
  3145. movq -8(%rbp), %rax
  3146. addq %rax, -16(%rbp)
  3147. \end{lstlisting}
  3148. An overview of all of the passes involved in register allocation is
  3149. shown in Figure~\ref{fig:reg-alloc-passes}.
  3150. \begin{figure}[tbp]
  3151. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3152. \node (R1) at (0,2) {\large $R_1$};
  3153. \node (R1-2) at (3,2) {\large $R_1$};
  3154. \node (R1-3) at (6,2) {\large $R_1$};
  3155. \node (C0-1) at (3,0) {\large $C_0$};
  3156. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3157. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3158. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3159. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3160. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3161. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3162. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3163. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3164. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3165. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3166. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3167. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3168. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3169. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3170. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3171. \end{tikzpicture}
  3172. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3173. \label{fig:reg-alloc-passes}
  3174. \end{figure}
  3175. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3176. \small
  3177. \begin{tcolorbox}[title=Priority Queue]
  3178. A \emph{priority queue} is a collection of items in which the
  3179. removal of items is governed by priority. In a ``min'' queue,
  3180. lower priority items are removed first. An implementation is in
  3181. \code{priority\_queue.rkt} of the support code. \index{priority
  3182. queue} \index{minimum priority queue}
  3183. \begin{description}
  3184. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3185. priority queue that uses the $\itm{cmp}$ predicate to determine
  3186. whether its first argument has lower or equal priority to its
  3187. second argument.
  3188. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3189. items in the queue.
  3190. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3191. the item into the queue and returns a handle for the item in the
  3192. queue.
  3193. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3194. the lowest priority.
  3195. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3196. notifices the queue the the priority has decreased for the item
  3197. associated with the given handle.
  3198. \end{description}
  3199. \end{tcolorbox}
  3200. \end{wrapfigure}
  3201. We recommend creating a helper function named \code{color-graph} that
  3202. takes an interference graph and a list of all the variables in the
  3203. program. This function should return a mapping of variables to their
  3204. colors (represented as natural numbers). By creating this helper
  3205. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3206. when you add support for functions. To prioritize the process of
  3207. highly saturated nodes inside your \code{color-graph} function, we
  3208. recommend using the priority queue data structure (see the side bar on
  3209. the right). Note that you will also need to maintain a mapping from
  3210. variables to their ``handles'' in the priority queue so that you can
  3211. notify the priority queue when their saturation changes.
  3212. Once you have obtained the coloring from \code{color-graph}, you can
  3213. assign the variables to registers or stack locations and then reuse
  3214. code from the \code{assign-homes} pass from
  3215. Section~\ref{sec:assign-r1} to replace the variables with their
  3216. assigned location.
  3217. \begin{exercise}\normalfont
  3218. Implement the compiler pass \code{allocate-registers}, which should come
  3219. after the \code{build-interference} pass. The three new passes,
  3220. \code{uncover-live}, \code{build-interference}, and
  3221. \code{allocate-registers} replace the \code{assign-homes} pass of
  3222. Section~\ref{sec:assign-r1}.
  3223. Test your updated compiler by creating new example programs that
  3224. exercise all of the register allocation algorithm, such as forcing
  3225. variables to be spilled to the stack.
  3226. \end{exercise}
  3227. \section{Print x86 and Conventions for Registers}
  3228. \label{sec:print-x86-reg-alloc}
  3229. \index{calling conventions}
  3230. \index{prelude}\index{conclusion}
  3231. Recall that the \code{print-x86} pass generates the prelude and
  3232. conclusion instructions for the \code{main} function.
  3233. %
  3234. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3235. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3236. reason for this is that our \code{main} function must adhere to the
  3237. x86 calling conventions that we described in
  3238. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3239. allocator assigned variables to other callee-saved registers
  3240. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3241. saved to the stack in the prelude and restored in the conclusion. The
  3242. simplest approach is to save and restore all of the callee-saved
  3243. registers. The more efficient approach is to keep track of which
  3244. callee-saved registers were used and only save and restore
  3245. them. Either way, make sure to take this use of stack space into
  3246. account when you are calculating the size of the frame and adjusting
  3247. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3248. frame needs to be a multiple of 16 bytes!
  3249. \section{Challenge: Move Biasing}
  3250. \label{sec:move-biasing}
  3251. \index{move biasing}
  3252. This section describes an optional enhancement to register allocation
  3253. for those students who are looking for an extra challenge or who have
  3254. a deeper interest in register allocation.
  3255. We return to the running example, but we remove the supposition that
  3256. we only have one register to use. So we have the following mapping of
  3257. color numbers to registers.
  3258. \[
  3259. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3260. \]
  3261. Using the same assignment of variables to color numbers that was
  3262. produced by the register allocator described in the last section, we
  3263. get the following program.
  3264. \begin{minipage}{0.3\textwidth}
  3265. \begin{lstlisting}
  3266. movq $1, v
  3267. movq $42, w
  3268. movq v, x
  3269. addq $7, x
  3270. movq x, y
  3271. movq x, z
  3272. addq w, z
  3273. movq y, t
  3274. negq t
  3275. movq z, %rax
  3276. addq t, %rax
  3277. jmp conclusion
  3278. \end{lstlisting}
  3279. \end{minipage}
  3280. $\Rightarrow\qquad$
  3281. \begin{minipage}{0.45\textwidth}
  3282. \begin{lstlisting}
  3283. movq $1, %rcx
  3284. movq $42, $rbx
  3285. movq %rcx, %rcx
  3286. addq $7, %rcx
  3287. movq %rcx, %rdx
  3288. movq %rcx, %rcx
  3289. addq %rbx, %rcx
  3290. movq %rdx, %rbx
  3291. negq %rbx
  3292. movq %rcx, %rax
  3293. addq %rbx, %rax
  3294. jmp conclusion
  3295. \end{lstlisting}
  3296. \end{minipage}
  3297. In the above output code there are two \key{movq} instructions that
  3298. can be removed because their source and target are the same. However,
  3299. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3300. register, we could instead remove three \key{movq} instructions. We
  3301. can accomplish this by taking into account which variables appear in
  3302. \key{movq} instructions with which other variables.
  3303. We say that two variables $p$ and $q$ are \emph{move
  3304. related}\index{move related} if they participate together in a
  3305. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3306. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3307. for a variable, it should prefer a color that has already been used
  3308. for a move-related variable (assuming that they do not interfere). Of
  3309. course, this preference should not override the preference for
  3310. registers over stack locations. This preference should be used as a
  3311. tie breaker when choosing between registers or when choosing between
  3312. stack locations.
  3313. We recommend representing the move relationships in a graph, similar
  3314. to how we represented interference. The following is the \emph{move
  3315. graph} for our running example.
  3316. \[
  3317. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3318. \node (rax) at (0,0) {$\ttm{rax}$};
  3319. \node (t) at (0,2) {$\ttm{t}$};
  3320. \node (z) at (3,2) {$\ttm{z}$};
  3321. \node (x) at (6,2) {$\ttm{x}$};
  3322. \node (y) at (3,0) {$\ttm{y}$};
  3323. \node (w) at (6,0) {$\ttm{w}$};
  3324. \node (v) at (9,0) {$\ttm{v}$};
  3325. \draw (v) to (x);
  3326. \draw (x) to (y);
  3327. \draw (x) to (z);
  3328. \draw (y) to (t);
  3329. \end{tikzpicture}
  3330. \]
  3331. Now we replay the graph coloring, pausing to see the coloring of
  3332. \code{y}. Recall the following configuration. The most saturated vertices
  3333. were \code{w} and \code{y}.
  3334. \[
  3335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3336. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3337. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3338. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3339. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3340. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3341. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3342. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3343. \draw (t1) to (rax);
  3344. \draw (t1) to (z);
  3345. \draw (z) to (y);
  3346. \draw (z) to (w);
  3347. \draw (x) to (w);
  3348. \draw (y) to (w);
  3349. \draw (v) to (w);
  3350. \end{tikzpicture}
  3351. \]
  3352. %
  3353. Last time we chose to color \code{w} with $0$. But this time we see
  3354. that \code{w} is not move related to any vertex, but \code{y} is move
  3355. related to \code{t}. So we choose to color \code{y} the same color,
  3356. $0$.
  3357. \[
  3358. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3359. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3360. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3361. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3362. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3363. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3364. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3365. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3366. \draw (t1) to (rax);
  3367. \draw (t1) to (z);
  3368. \draw (z) to (y);
  3369. \draw (z) to (w);
  3370. \draw (x) to (w);
  3371. \draw (y) to (w);
  3372. \draw (v) to (w);
  3373. \end{tikzpicture}
  3374. \]
  3375. Now \code{w} is the most saturated, so we color it $2$.
  3376. \[
  3377. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3378. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3379. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3380. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3381. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3382. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3383. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3384. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3385. \draw (t1) to (rax);
  3386. \draw (t1) to (z);
  3387. \draw (z) to (y);
  3388. \draw (z) to (w);
  3389. \draw (x) to (w);
  3390. \draw (y) to (w);
  3391. \draw (v) to (w);
  3392. \end{tikzpicture}
  3393. \]
  3394. At this point, vertices \code{x} and \code{v} are most saturated, but
  3395. \code{x} is move related to \code{y} and \code{z}, so we color
  3396. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3397. \[
  3398. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3399. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3400. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3401. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3402. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3403. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3404. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3405. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3406. \draw (t1) to (rax);
  3407. \draw (t) to (z);
  3408. \draw (z) to (y);
  3409. \draw (z) to (w);
  3410. \draw (x) to (w);
  3411. \draw (y) to (w);
  3412. \draw (v) to (w);
  3413. \end{tikzpicture}
  3414. \]
  3415. So we have the following assignment of variables to registers.
  3416. \begin{gather*}
  3417. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3418. \ttm{w} \mapsto \key{\%rdx}, \,
  3419. \ttm{x} \mapsto \key{\%rbx}, \,
  3420. \ttm{y} \mapsto \key{\%rbx}, \,
  3421. \ttm{z} \mapsto \key{\%rcx}, \,
  3422. \ttm{t} \mapsto \key{\%rbx} \}
  3423. \end{gather*}
  3424. We apply this register assignment to the running example, on the left,
  3425. to obtain the code on right.
  3426. \begin{minipage}{0.3\textwidth}
  3427. \begin{lstlisting}
  3428. movq $1, v
  3429. movq $42, w
  3430. movq v, x
  3431. addq $7, x
  3432. movq x, y
  3433. movq x, z
  3434. addq w, z
  3435. movq y, t
  3436. negq t
  3437. movq z, %rax
  3438. addq t, %rax
  3439. jmp conclusion
  3440. \end{lstlisting}
  3441. \end{minipage}
  3442. $\Rightarrow\qquad$
  3443. \begin{minipage}{0.45\textwidth}
  3444. \begin{lstlisting}
  3445. movq $1, %rbx
  3446. movq $42, %rdx
  3447. movq %rbx, %rbx
  3448. addq $7, %rbx
  3449. movq %rbx, %rbx
  3450. movq %rbx, %rcx
  3451. addq %rdx, %rcx
  3452. movq %rbx, %rbx
  3453. negq %rbx
  3454. movq %rcx, %rax
  3455. addq %rbx, %rax
  3456. jmp conclusion
  3457. \end{lstlisting}
  3458. \end{minipage}
  3459. The \code{patch-instructions} then removes the three trivial moves
  3460. from \key{rbx} to \key{rbx} to obtain the following result.
  3461. \begin{minipage}{0.45\textwidth}
  3462. \begin{lstlisting}
  3463. movq $1, %rbx
  3464. movq $42, %rdx
  3465. addq $7, %rbx
  3466. movq %rbx, %rcx
  3467. addq %rdx, %rcx
  3468. negq %rbx
  3469. movq %rcx, %rax
  3470. addq %rbx, %rax
  3471. jmp conclusion
  3472. \end{lstlisting}
  3473. \end{minipage}
  3474. \begin{exercise}\normalfont
  3475. Change your implementation of \code{allocate-registers} to take move
  3476. biasing into account. Make sure that your compiler still passes all of
  3477. the previous tests. Create two new tests that include at least one
  3478. opportunity for move biasing and visually inspect the output x86
  3479. programs to make sure that your move biasing is working properly.
  3480. \end{exercise}
  3481. \margincomment{\footnotesize To do: another neat challenge would be to do
  3482. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3483. \section{Output of the Running Example}
  3484. \label{sec:reg-alloc-output}
  3485. \index{prelude}\index{conclusion}
  3486. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3487. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3488. and move biasing. To demonstrate both the use of registers and the
  3489. stack, we have limited the register allocator to use just two
  3490. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3491. \code{main} function, we push \code{rbx} onto the stack because it is
  3492. a callee-saved register and it was assigned to variable by the
  3493. register allocator. We substract \code{8} from the \code{rsp} at the
  3494. end of the prelude to reserve space for the one spilled variable.
  3495. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3496. Moving on the the \code{start} block, we see how the registers were
  3497. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3498. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3499. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3500. that the prelude saved the callee-save register \code{rbx} onto the
  3501. stack. The spilled variables must be placed lower on the stack than
  3502. the saved callee-save registers, so in this case \code{w} is placed at
  3503. \code{-16(\%rbp)}.
  3504. In the \code{conclusion}, we undo the work that was done in the
  3505. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3506. spilled variables), then we pop the old values of \code{rbx} and
  3507. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3508. return control to the operating system.
  3509. \begin{figure}[tbp]
  3510. % s0_28.rkt
  3511. % (use-minimal-set-of-registers! #t)
  3512. % and only rbx rcx
  3513. % tmp 0 rbx
  3514. % z 1 rcx
  3515. % y 0 rbx
  3516. % w 2 16(%rbp)
  3517. % v 0 rbx
  3518. % x 0 rbx
  3519. \begin{lstlisting}
  3520. start:
  3521. movq $1, %rbx
  3522. movq $42, -16(%rbp)
  3523. addq $7, %rbx
  3524. movq %rbx, %rcx
  3525. addq -16(%rbp), %rcx
  3526. negq %rbx
  3527. movq %rcx, %rax
  3528. addq %rbx, %rax
  3529. jmp conclusion
  3530. .globl main
  3531. main:
  3532. pushq %rbp
  3533. movq %rsp, %rbp
  3534. pushq %rbx
  3535. subq $8, %rsp
  3536. jmp start
  3537. conclusion:
  3538. addq $8, %rsp
  3539. popq %rbx
  3540. popq %rbp
  3541. retq
  3542. \end{lstlisting}
  3543. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3544. \label{fig:running-example-x86}
  3545. \end{figure}
  3546. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3547. \chapter{Booleans and Control Flow}
  3548. \label{ch:bool-types}
  3549. \index{Boolean}
  3550. \index{control flow}
  3551. \index{conditional expression}
  3552. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3553. integers. In this chapter we add a second kind of value, the Booleans,
  3554. to create the $R_2$ language. The Boolean values \emph{true} and
  3555. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3556. Racket. The $R_2$ language includes several operations that involve
  3557. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3558. conditional \key{if} expression. With the addition of \key{if}
  3559. expressions, programs can have non-trivial control flow which which
  3560. significantly impacts the \code{explicate-control} and the liveness
  3561. analysis for register allocation. Also, because we now have two kinds
  3562. of values, we need to handle programs that apply an operation to the
  3563. wrong kind of value, such as \code{(not 1)}.
  3564. There are two language design options for such situations. One option
  3565. is to signal an error and the other is to provide a wider
  3566. interpretation of the operation. The Racket language uses a mixture of
  3567. these two options, depending on the operation and the kind of
  3568. value. For example, the result of \code{(not 1)} in Racket is
  3569. \code{\#f} because Racket treats non-zero integers as if they were
  3570. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3571. error in Racket stating that \code{car} expects a pair.
  3572. The Typed Racket language makes similar design choices as Racket,
  3573. except much of the error detection happens at compile time instead of
  3574. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3575. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3576. reports a compile-time error because Typed Racket expects the type of
  3577. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3578. For the $R_2$ language we choose to be more like Typed Racket in that
  3579. we perform type checking during compilation. In
  3580. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3581. is, how to compile a dynamically typed language like Racket. The
  3582. $R_2$ language is a subset of Typed Racket but by no means includes
  3583. all of Typed Racket. For many operations we take a narrower
  3584. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3585. This chapter is organized as follows. We begin by defining the syntax
  3586. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3587. then introduce the idea of type checking and build a type checker for
  3588. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3589. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3590. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3591. how our compiler passes need to change to accommodate Booleans and
  3592. conditional control flow.
  3593. \section{The $R_2$ Language}
  3594. \label{sec:r2-lang}
  3595. The concrete syntax of the $R_2$ language is defined in
  3596. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3597. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3598. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3599. and the conditional \code{if} expression. Also, we expand the
  3600. operators to include
  3601. \begin{enumerate}
  3602. \item subtraction on integers,
  3603. \item the logical operators \key{and}, \key{or} and \key{not},
  3604. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3605. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3606. comparing integers.
  3607. \end{enumerate}
  3608. \begin{figure}[tp]
  3609. \centering
  3610. \fbox{
  3611. \begin{minipage}{0.96\textwidth}
  3612. \[
  3613. \begin{array}{lcl}
  3614. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3615. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3616. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3617. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3618. &\mid& \itm{bool}
  3619. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3620. \mid (\key{not}\;\Exp) \\
  3621. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3622. R_2 &::=& \Exp
  3623. \end{array}
  3624. \]
  3625. \end{minipage}
  3626. }
  3627. \caption{The concrete syntax of $R_2$, extending $R_1$
  3628. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3629. \label{fig:r2-concrete-syntax}
  3630. \end{figure}
  3631. \begin{figure}[tp]
  3632. \centering
  3633. \fbox{
  3634. \begin{minipage}{0.96\textwidth}
  3635. \[
  3636. \begin{array}{lcl}
  3637. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3638. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3639. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3640. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3641. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3642. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3643. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3644. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3645. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3646. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3647. \end{array}
  3648. \]
  3649. \end{minipage}
  3650. }
  3651. \caption{The abstract syntax of $R_2$.}
  3652. \label{fig:r2-syntax}
  3653. \end{figure}
  3654. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3655. the parts that are the same as the interpreter for $R_1$
  3656. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3657. evaluate to the corresponding Boolean values. The conditional
  3658. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3659. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3660. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3661. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3662. you might expect, but note that the \code{and} operation is
  3663. short-circuiting. That is, given the expression
  3664. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3665. $e_1$ evaluates to \code{\#f}.
  3666. With the addition of the comparison operations, there are quite a few
  3667. primitive operations and the interpreter code for them could become
  3668. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3669. out the different parts of the code for primitive operations into the
  3670. \code{interp-op} function and the similar parts of the code into the
  3671. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3672. do not use \code{interp-op} for the \code{and} operation because of
  3673. the short-circuiting behavior in the order of evaluation of its
  3674. arguments.
  3675. \begin{figure}[tbp]
  3676. \begin{lstlisting}
  3677. (define (interp-op op)
  3678. (match op
  3679. ...
  3680. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3681. ['eq? (lambda (v1 v2)
  3682. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3683. (and (boolean? v1) (boolean? v2)))
  3684. (eq? v1 v2)]))]
  3685. ['< (lambda (v1 v2)
  3686. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3687. ['<= (lambda (v1 v2)
  3688. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3689. ['> (lambda (v1 v2)
  3690. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3691. ['>= (lambda (v1 v2)
  3692. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3693. [else (error 'interp-op "unknown operator")]))
  3694. (define (interp-exp env)
  3695. (lambda (e)
  3696. (define recur (interp-exp env))
  3697. (match e
  3698. ...
  3699. [(Bool b) b]
  3700. [(If cnd thn els)
  3701. (define b (recur cnd))
  3702. (match b
  3703. [#t (recur thn)]
  3704. [#f (recur els)])]
  3705. [(Prim 'and (list e1 e2))
  3706. (define v1 (recur e1))
  3707. (match v1
  3708. [#t (match (recur e2) [#t #t] [#f #f])]
  3709. [#f #f])]
  3710. [(Prim op args)
  3711. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3712. )))
  3713. (define (interp-R2 p)
  3714. (match p
  3715. [(Program info e)
  3716. ((interp-exp '()) e)]
  3717. ))
  3718. \end{lstlisting}
  3719. \caption{Interpreter for the $R_2$ language.}
  3720. \label{fig:interp-R2}
  3721. \end{figure}
  3722. \section{Type Checking $R_2$ Programs}
  3723. \label{sec:type-check-r2}
  3724. \index{type checking}
  3725. \index{semantic analysis}
  3726. It is helpful to think about type checking in two complementary
  3727. ways. A type checker predicts the type of value that will be produced
  3728. by each expression in the program. For $R_2$, we have just two types,
  3729. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3730. \begin{lstlisting}
  3731. (+ 10 (- (+ 12 20)))
  3732. \end{lstlisting}
  3733. produces an \key{Integer} while
  3734. \begin{lstlisting}
  3735. (and (not #f) #t)
  3736. \end{lstlisting}
  3737. produces a \key{Boolean}.
  3738. Another way to think about type checking is that it enforces a set of
  3739. rules about which operators can be applied to which kinds of
  3740. values. For example, our type checker for $R_2$ will signal an error
  3741. for the below expression because, as we have seen above, the
  3742. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3743. checker enforces the rule that the argument of \code{not} must be a
  3744. \key{Boolean}.
  3745. \begin{lstlisting}
  3746. (not (+ 10 (- (+ 12 20))))
  3747. \end{lstlisting}
  3748. The type checker for $R_2$ is a structurally recursive function over
  3749. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3750. the \code{type-check-exp} function. Given an input expression
  3751. \code{e}, the type checker either returns a type (\key{Integer} or
  3752. \key{Boolean}) or it signals an error. The type of an integer literal
  3753. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3754. To handle variables, the type checker uses an environment that maps
  3755. variables to types. Consider the clause for \key{let}. We type check
  3756. the initializing expression to obtain its type \key{T} and then
  3757. associate type \code{T} with the variable \code{x} in the
  3758. environment. When the type checker encounters a use of variable
  3759. \code{x} in the body of the \key{let}, it can find its type in the
  3760. environment.
  3761. \begin{figure}[tbp]
  3762. \begin{lstlisting}
  3763. (define (type-check-exp env)
  3764. (lambda (e)
  3765. (match e
  3766. [(Var x) (dict-ref env x)]
  3767. [(Int n) 'Integer]
  3768. [(Bool b) 'Boolean]
  3769. [(Let x e body)
  3770. (define Te ((type-check-exp env) e))
  3771. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3772. Tb]
  3773. ...
  3774. [else
  3775. (error "type-check-exp couldn't match" e)])))
  3776. (define (type-check env)
  3777. (lambda (e)
  3778. (match e
  3779. [(Program info body)
  3780. (define Tb ((type-check-exp '()) body))
  3781. (unless (equal? Tb 'Integer)
  3782. (error "result of the program must be an integer, not " Tb))
  3783. (Program info body)]
  3784. )))
  3785. \end{lstlisting}
  3786. \caption{Skeleton of a type checker for the $R_2$ language.}
  3787. \label{fig:type-check-R2}
  3788. \end{figure}
  3789. \begin{exercise}\normalfont
  3790. Complete the implementation of \code{type-check}. Test your type
  3791. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3792. the \code{type-check} function as the second argument. Create 10 new
  3793. example programs in $R_2$ that you choose based on how thoroughly they
  3794. test you type checking function. Half of the example programs should
  3795. have a type error to make sure that your type checker properly rejects
  3796. them. For those programs, to signal that a type error is expected,
  3797. create an empty file with the same base name but with file extension
  3798. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3799. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3800. other half of the example programs should not have type errors. Note
  3801. that if your type checker does not signal an error for a program, then
  3802. interpreting that program should not encounter an error. If it does,
  3803. there is something wrong with your type checker.
  3804. \end{exercise}
  3805. \section{Shrink the $R_2$ Language}
  3806. \label{sec:shrink-r2}
  3807. The $R_2$ language includes several operators that are easily
  3808. expressible in terms of other operators. For example, subtraction is
  3809. expressible in terms of addition and negation.
  3810. \[
  3811. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3812. \]
  3813. Several of the comparison operations are expressible in terms of
  3814. less-than and logical negation.
  3815. \[
  3816. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3817. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3818. \]
  3819. The \key{let} is needed in the above translation to ensure that
  3820. expression $e_1$ is evaluated before $e_2$.
  3821. By performing these translations near the front-end of the compiler,
  3822. the later passes of the compiler do not need to deal with these
  3823. constructs, making those passes shorter. On the other hand, sometimes
  3824. these translations make it more difficult to generate the most
  3825. efficient code with respect to the number of instructions. However,
  3826. these differences typically do not affect the number of accesses to
  3827. memory, which is the primary factor that determines execution time on
  3828. modern computer architectures.
  3829. \begin{exercise}\normalfont
  3830. Implement the pass \code{shrink} that removes subtraction,
  3831. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3832. by translating them to other constructs in $R_2$. Create tests to
  3833. make sure that the behavior of all of these constructs stays the
  3834. same after translation.
  3835. \end{exercise}
  3836. \section{The x86$_1$ Language}
  3837. \label{sec:x86-1}
  3838. \index{x86}
  3839. To implement the new logical operations, the comparison operations,
  3840. and the \key{if} expression, we need to delve further into the x86
  3841. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3842. the concrete and abstract syntax for a larger subset of x86 that
  3843. includes instructions for logical operations, comparisons, and
  3844. conditional jumps.
  3845. One small challenge is that x86 does not provide an instruction that
  3846. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3847. However, the \code{xorq} instruction can be used to encode \code{not}.
  3848. The \key{xorq} instruction takes two arguments, performs a pairwise
  3849. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3850. and writes the results into its second argument. Recall the truth
  3851. table for exclusive-or:
  3852. \begin{center}
  3853. \begin{tabular}{l|cc}
  3854. & 0 & 1 \\ \hline
  3855. 0 & 0 & 1 \\
  3856. 1 & 1 & 0
  3857. \end{tabular}
  3858. \end{center}
  3859. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3860. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3861. for the bit $1$, the result is the opposite of the second bit. Thus,
  3862. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3863. the first argument:
  3864. \[
  3865. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3866. \qquad\Rightarrow\qquad
  3867. \begin{array}{l}
  3868. \key{movq}~ \Arg\key{,} \Var\\
  3869. \key{xorq}~ \key{\$1,} \Var
  3870. \end{array}
  3871. \]
  3872. \begin{figure}[tp]
  3873. \fbox{
  3874. \begin{minipage}{0.96\textwidth}
  3875. \[
  3876. \begin{array}{lcl}
  3877. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3878. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3879. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3880. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3881. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3882. \key{subq} \; \Arg\key{,} \Arg \mid
  3883. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3884. && \gray{ \key{callq} \; \itm{label} \mid
  3885. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3886. && \gray{ \itm{label}\key{:}\; \Instr }
  3887. \mid \key{xorq}~\Arg\key{,}~\Arg
  3888. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3889. && \key{set}cc~\Arg
  3890. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3891. \mid \key{j}cc~\itm{label}
  3892. \\
  3893. x86_1 &::= & \gray{ \key{.globl main} }\\
  3894. & & \gray{ \key{main:} \; \Instr\ldots }
  3895. \end{array}
  3896. \]
  3897. \end{minipage}
  3898. }
  3899. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3900. \label{fig:x86-1-concrete}
  3901. \end{figure}
  3902. \begin{figure}[tp]
  3903. \fbox{
  3904. \begin{minipage}{0.96\textwidth}
  3905. \small
  3906. \[
  3907. \begin{array}{lcl}
  3908. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3909. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3910. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3911. \mid \BYTEREG{\itm{bytereg}} \\
  3912. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3913. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3914. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3915. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3916. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3917. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  3918. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3919. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3920. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3921. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3922. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3923. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3924. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3925. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3926. \end{array}
  3927. \]
  3928. \end{minipage}
  3929. }
  3930. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3931. \label{fig:x86-1}
  3932. \end{figure}
  3933. Next we consider the x86 instructions that are relevant for compiling
  3934. the comparison operations. The \key{cmpq} instruction compares its two
  3935. arguments to determine whether one argument is less than, equal, or
  3936. greater than the other argument. The \key{cmpq} instruction is unusual
  3937. regarding the order of its arguments and where the result is
  3938. placed. The argument order is backwards: if you want to test whether
  3939. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3940. \key{cmpq} is placed in the special EFLAGS register. This register
  3941. cannot be accessed directly but it can be queried by a number of
  3942. instructions, including the \key{set} instruction. The \key{set}
  3943. instruction puts a \key{1} or \key{0} into its destination depending
  3944. on whether the comparison came out according to the condition code
  3945. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3946. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3947. The \key{set} instruction has an annoying quirk in that its
  3948. destination argument must be single byte register, such as \code{al}
  3949. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3950. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3951. then be used to move from a single byte register to a normal 64-bit
  3952. register.
  3953. The x86 instruction for conditional jump are relevant to the
  3954. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3955. updates the program counter to point to the instruction after the
  3956. indicated label depending on whether the result in the EFLAGS register
  3957. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3958. instruction falls through to the next instruction. The abstract
  3959. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3960. that it separates the instruction name from the condition code. For
  3961. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3962. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3963. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3964. instruction to set the EFLAGS register.
  3965. \section{The $C_1$ Intermediate Language}
  3966. \label{sec:c1}
  3967. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3968. we need to grow that intermediate language to handle the new features
  3969. in $R_2$: Booleans and conditional expressions.
  3970. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3971. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3972. particular, we add logical and comparison operators to the $\Exp$
  3973. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3974. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3975. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3976. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3977. sequence of statements may now end with a \code{goto} or a conditional
  3978. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3979. depending on the outcome of the comparison. In
  3980. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3981. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3982. and \key{goto}'s.
  3983. \begin{figure}[tbp]
  3984. \fbox{
  3985. \begin{minipage}{0.96\textwidth}
  3986. \small
  3987. \[
  3988. \begin{array}{lcl}
  3989. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3990. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3991. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3992. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3993. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3994. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3995. \mid \key{goto}~\itm{label}\key{;}\\
  3996. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3997. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3998. \end{array}
  3999. \]
  4000. \end{minipage}
  4001. }
  4002. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4003. \label{fig:c1-concrete-syntax}
  4004. \end{figure}
  4005. \begin{figure}[tp]
  4006. \fbox{
  4007. \begin{minipage}{0.96\textwidth}
  4008. \small
  4009. \[
  4010. \begin{array}{lcl}
  4011. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4012. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4013. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4014. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4015. &\mid& \UNIOP{\key{'not}}{\Atm}
  4016. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4017. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4018. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4019. \mid \GOTO{\itm{label}} \\
  4020. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4021. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4022. \end{array}
  4023. \]
  4024. \end{minipage}
  4025. }
  4026. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4027. (Figure~\ref{fig:c0-syntax}).}
  4028. \label{fig:c1-syntax}
  4029. \end{figure}
  4030. \clearpage
  4031. \section{Remove Complex Operands}
  4032. \label{sec:remove-complex-opera-R2}
  4033. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4034. \code{rco-atom} functions according to the definition of the output
  4035. language for this pass, $R_2^{\dagger}$, the administrative normal
  4036. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4037. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4038. three sub-expressions of an \code{If} are allowed to be complex
  4039. expressions in the output of \code{remove-complex-opera*}, but the
  4040. operands of \code{not} and the comparisons must be atoms. Regarding
  4041. the \code{If} form, it is particularly important to \textbf{not}
  4042. replace its condition with a temporary variable because that would
  4043. interfere with the generation of high-quality output in the
  4044. \code{explicate-control} pass.
  4045. \begin{figure}[tp]
  4046. \centering
  4047. \fbox{
  4048. \begin{minipage}{0.96\textwidth}
  4049. \[
  4050. \begin{array}{rcl}
  4051. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4052. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4053. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4054. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4055. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4056. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4057. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4058. \end{array}
  4059. \]
  4060. \end{minipage}
  4061. }
  4062. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4063. \label{fig:r2-anf-syntax}
  4064. \end{figure}
  4065. \section{Explicate Control}
  4066. \label{sec:explicate-control-r2}
  4067. Recall that the purpose of \code{explicate-control} is to make the
  4068. order of evaluation explicit in the syntax of the program. With the
  4069. addition of \key{if} in $R_2$ this get more interesting.
  4070. As a motivating example, consider the following program that has an
  4071. \key{if} expression nested in the predicate of another \key{if}.
  4072. % s1_41.rkt
  4073. \begin{center}
  4074. \begin{minipage}{0.96\textwidth}
  4075. \begin{lstlisting}
  4076. (let ([x (read)])
  4077. (let ([y (read)])
  4078. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4079. (+ y 2)
  4080. (+ y 10))))
  4081. \end{lstlisting}
  4082. \end{minipage}
  4083. \end{center}
  4084. %
  4085. The naive way to compile \key{if} and the comparison would be to
  4086. handle each of them in isolation, regardless of their context. Each
  4087. comparison would be translated into a \key{cmpq} instruction followed
  4088. by a couple instructions to move the result from the EFLAGS register
  4089. into a general purpose register or stack location. Each \key{if} would
  4090. be translated into the combination of a \key{cmpq} and a conditional
  4091. jump. The generated code for the inner \key{if} in the above example
  4092. would be as follows.
  4093. \begin{center}
  4094. \begin{minipage}{0.96\textwidth}
  4095. \begin{lstlisting}
  4096. ...
  4097. cmpq $1, x ;; (< x 1)
  4098. setl %al
  4099. movzbq %al, tmp
  4100. cmpq $1, tmp ;; (if (< x 1) ...)
  4101. je then_branch_1
  4102. jmp else_branch_1
  4103. ...
  4104. \end{lstlisting}
  4105. \end{minipage}
  4106. \end{center}
  4107. However, if we take context into account we can do better and reduce
  4108. the use of \key{cmpq} and EFLAG-accessing instructions.
  4109. One idea is to try and reorganize the code at the level of $R_2$,
  4110. pushing the outer \key{if} inside the inner one. This would yield the
  4111. following code.
  4112. \begin{center}
  4113. \begin{minipage}{0.96\textwidth}
  4114. \begin{lstlisting}
  4115. (let ([x (read)])
  4116. (let ([y (read)])
  4117. (if (< x 1)
  4118. (if (eq? x 0)
  4119. (+ y 2)
  4120. (+ y 10))
  4121. (if (eq? x 2)
  4122. (+ y 2)
  4123. (+ y 10)))))
  4124. \end{lstlisting}
  4125. \end{minipage}
  4126. \end{center}
  4127. Unfortunately, this approach duplicates the two branches, and a
  4128. compiler must never duplicate code!
  4129. We need a way to perform the above transformation, but without
  4130. duplicating code. The solution is straightforward if we think at the
  4131. level of x86 assembly: we can label the code for each of the branches
  4132. and insert jumps in all the places that need to execute the
  4133. branches. Put another way, we need to move away from abstract syntax
  4134. \emph{trees} and instead use \emph{graphs}. In particular, we
  4135. use a standard program representation called a \emph{control flow
  4136. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4137. \index{control-flow graph}
  4138. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4139. each edge represents a jump to another block. The \key{Program}
  4140. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4141. as an alist mapping labels to basic blocks. Each basic block is
  4142. represented by the $\Tail$ non-terminal.
  4143. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4144. \code{remove-complex-opera*} pass and then the
  4145. \code{explicate-control} pass on the example program. We walk through
  4146. the output program and then discuss the algorithm.
  4147. %
  4148. Following the order of evaluation in the output of
  4149. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4150. and then the less-than-comparison to \code{1} in the predicate of the
  4151. inner \key{if}. In the output of \code{explicate-control}, in the
  4152. block labeled \code{start}, this becomes two assignment statements
  4153. followed by a conditional \key{goto} to label \code{block96} or
  4154. \code{block97}. The blocks associated with those labels contain the
  4155. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4156. respectively. Regarding the block labeled with \code{block96}, we
  4157. start with the comparison to \code{0} and then have a conditional
  4158. goto, either to label \code{block92} or label \code{block93}, which
  4159. indirectly take us to labels \code{block90} and \code{block91}, the
  4160. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4161. y 10)}. The story for the block labeled \code{block97} is similar.
  4162. \begin{figure}[tbp]
  4163. \begin{tabular}{lll}
  4164. \begin{minipage}{0.4\textwidth}
  4165. % s1_41.rkt
  4166. \begin{lstlisting}
  4167. (let ([x (read)])
  4168. (let ([y (read)])
  4169. (if (if (< x 1)
  4170. (eq? x 0)
  4171. (eq? x 2))
  4172. (+ y 2)
  4173. (+ y 10))))
  4174. \end{lstlisting}
  4175. \hspace{40pt}$\Downarrow$
  4176. \begin{lstlisting}
  4177. (let ([x (read)])
  4178. (let ([y (read)])
  4179. (if (if (< x 1)
  4180. (eq? x 0)
  4181. (eq? x 2))
  4182. (+ y 2)
  4183. (+ y 10))))
  4184. \end{lstlisting}
  4185. \end{minipage}
  4186. &
  4187. $\Rightarrow$
  4188. &
  4189. \begin{minipage}{0.55\textwidth}
  4190. \begin{lstlisting}
  4191. start:
  4192. x = (read);
  4193. y = (read);
  4194. if (< x 1)
  4195. goto block96;
  4196. else
  4197. goto block97;
  4198. block96:
  4199. if (eq? x 0)
  4200. goto block92;
  4201. else
  4202. goto block93;
  4203. block97:
  4204. if (eq? x 2)
  4205. goto block94;
  4206. else
  4207. goto block95;
  4208. block92:
  4209. goto block90;
  4210. block93:
  4211. goto block91;
  4212. block94:
  4213. goto block90;
  4214. block95:
  4215. goto block91;
  4216. block90:
  4217. return (+ y 2);
  4218. block91:
  4219. return (+ y 10);
  4220. \end{lstlisting}
  4221. \end{minipage}
  4222. \end{tabular}
  4223. \caption{Example translation from $R_2$ to $C_1$
  4224. via the \code{explicate-control}.}
  4225. \label{fig:explicate-control-s1-38}
  4226. \end{figure}
  4227. The nice thing about the output of \code{explicate-control} is that
  4228. there are no unnecessary comparisons and every comparison is part of a
  4229. conditional jump. The down-side of this output is that it includes
  4230. trivial blocks, such as the blocks labeled \code{block92} through
  4231. \code{block95}, that only jump to another block. We discuss a solution
  4232. to this problem in Section~\ref{sec:opt-jumps}.
  4233. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4234. \code{explicate-control} for $R_1$ using two mutually recursive
  4235. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4236. former function translates expressions in tail position whereas the
  4237. later function translates expressions on the right-hand-side of a
  4238. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4239. new kind of context to deal with: the predicate position of the
  4240. \key{if}. We need another function, \code{explicate-pred}, that takes
  4241. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4242. the then-branch and else-branch. The output of \code{explicate-pred}
  4243. is a block and a list of formerly \key{let}-bound variables.
  4244. Note that the three explicate functions need to construct a
  4245. control-flow graph, which we recommend they do via updates to a global
  4246. variable.
  4247. In the following paragraphs we consider the specific additions to the
  4248. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4249. of cases for the \code{explicate-pred} function.
  4250. The \code{explicate-tail} function needs an additional case for
  4251. \key{if}. The branches of the \key{if} inherit the current context, so
  4252. they are in tail position. Let $B_1$ be the result of
  4253. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4254. is a $\Tail$ AST node. Let $B_2$ be the result of applying
  4255. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4256. the $\Tail$ that results from applying \code{explicate-pred} to the
  4257. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4258. \key{if} as a whole translates to block $B_3$.
  4259. \[
  4260. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4261. \]
  4262. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4263. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4264. should not be confused with the labels for the blocks that appear in
  4265. the generated code. We initially construct unlabeled blocks; we only
  4266. attach labels to blocks when we add them to the control-flow graph, as
  4267. we see in the next case.
  4268. Next consider the case for \key{if} in the \code{explicate-assign}
  4269. function. The context of the \key{if} is an assignment to some
  4270. variable $x$ and then the control continues to some block $B_1$. The
  4271. code that we generate for both the ``then'' and ``else'' branches
  4272. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4273. add it to the control flow graph with a fresh label $\ell_1$. The
  4274. branches of the \key{if} inherit the current context, so they are in
  4275. assignment positions. Let $B_2$ be the result of applying
  4276. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4277. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4278. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4279. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4280. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4281. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4282. $B_4$.
  4283. \[
  4284. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4285. \]
  4286. The function \code{explicate-pred} will need a case for every
  4287. expression that can have type \code{Boolean}. We detail a few cases
  4288. here and leave the rest for the reader. The input to this function is
  4289. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4290. the enclosing \key{if}. Suppose the expression is the Boolean
  4291. \code{\#t}. Then we can perform a kind of partial evaluation
  4292. \index{partial evaluation} and translate it to the ``then'' branch
  4293. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4294. \[
  4295. \key{\#t} \quad\Rightarrow\quad B_1,
  4296. \qquad\qquad\qquad
  4297. \key{\#f} \quad\Rightarrow\quad B_2
  4298. \]
  4299. Next, suppose the expression is a less-than comparison. We translate
  4300. it to a conditional \code{goto}. We need labels for the two branches
  4301. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4302. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4303. less-than comparison is as follows.
  4304. \[
  4305. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4306. \begin{array}{l}
  4307. \key{if}~(\key{<}~e_1~e_2) \\
  4308. \qquad\key{goto}~\ell_1\key{;}\\
  4309. \key{else}\\
  4310. \qquad\key{goto}~\ell_2\key{;}
  4311. \end{array}
  4312. \]
  4313. The case for \key{if} in \code{explicate-pred} is particularly
  4314. illuminating as it deals with the challenges that we discussed above
  4315. regarding the example of the nested \key{if} expressions. Again, we
  4316. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4317. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4318. branches of the current \key{if} inherit their context from the
  4319. current one, that is, predicate context. So we apply
  4320. \code{explicate-pred} to the ``then'' branch with the two blocks
  4321. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4322. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4323. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4324. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4325. \[
  4326. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4327. \quad\Rightarrow\quad
  4328. B_5
  4329. \]
  4330. Finally, note that the way in which the \code{shrink} pass transforms
  4331. logical operations such as \code{and} and \code{or} can impact the
  4332. quality of code generated by \code{explicate-control}. For example,
  4333. consider the following program.
  4334. \begin{lstlisting}
  4335. (if (and (eq? (read) 0) (eq? (read) 1))
  4336. 0
  4337. 42)
  4338. \end{lstlisting}
  4339. The \code{and} operation should transform into something that the
  4340. \code{explicat-pred} function can still analyze and descend through to
  4341. reach the underlying \code{eq?} conditions. Ideally, your
  4342. \code{explicate-control} pass should generate code similar to the
  4343. following for the above program.\footnote{If the trivial blocks 17,
  4344. 18, and 20 bother you, take a look at the challenge problem in
  4345. Section~\ref{sec:opt-jumps}.}
  4346. \begin{center}
  4347. \begin{minipage}{0.45\textwidth}
  4348. \begin{lstlisting}
  4349. start:
  4350. tmp13 = (read);
  4351. if (eq? tmp13 0)
  4352. goto block19;
  4353. else
  4354. goto block20;
  4355. block19:
  4356. tmp14 = (read);
  4357. if (eq? tmp14 1)
  4358. goto block17;
  4359. else
  4360. goto block18;
  4361. \end{lstlisting}
  4362. \end{minipage}
  4363. \begin{minipage}{0.45\textwidth}
  4364. \begin{lstlisting}
  4365. block20:
  4366. goto block16;
  4367. block17:
  4368. goto block15;
  4369. block18:
  4370. goto block16;
  4371. block15:
  4372. return 0;
  4373. block16:
  4374. return 42;
  4375. \end{lstlisting}
  4376. \end{minipage}
  4377. \end{center}
  4378. \begin{exercise}\normalfont
  4379. Implement the pass \code{explicate-control} by adding the cases for
  4380. \key{if} to the functions for tail and assignment contexts, and
  4381. implement \code{explicate-pred} for predicate contexts. Create test
  4382. cases that exercise all of the new cases in the code for this pass.
  4383. \end{exercise}
  4384. \section{Select Instructions}
  4385. \label{sec:select-r2}
  4386. \index{instruction selection}
  4387. Recall that the \code{select-instructions} pass lowers from our
  4388. $C$-like intermediate representation to the pseudo-x86 language, which
  4389. is suitable for conducting register allocation. The pass is
  4390. implemented using three auxiliary functions, one for each of the
  4391. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4392. For $\Atm$, we have new cases for the Booleans. We take the usual
  4393. approach of encoding them as integers, with true as 1 and false as 0.
  4394. \[
  4395. \key{\#t} \Rightarrow \key{1}
  4396. \qquad
  4397. \key{\#f} \Rightarrow \key{0}
  4398. \]
  4399. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4400. be implemented in terms of \code{xorq} as we discussed at the
  4401. beginning of this section. Given an assignment
  4402. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4403. if the left-hand side $\itm{var}$ is
  4404. the same as $\Atm$, then just the \code{xorq} suffices.
  4405. \[
  4406. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4407. \quad\Rightarrow\quad
  4408. \key{xorq}~\key{\$}1\key{,}~\Var
  4409. \]
  4410. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4411. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4412. x86. Then we have
  4413. \[
  4414. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4415. \quad\Rightarrow\quad
  4416. \begin{array}{l}
  4417. \key{movq}~\Arg\key{,}~\Var\\
  4418. \key{xorq}~\key{\$}1\key{,}~\Var
  4419. \end{array}
  4420. \]
  4421. Next consider the cases for \code{eq?} and less-than comparison.
  4422. Translating these operations to x86 is slightly involved due to the
  4423. unusual nature of the \key{cmpq} instruction discussed above. We
  4424. recommend translating an assignment from \code{eq?} into the following
  4425. sequence of three instructions. \\
  4426. \begin{tabular}{lll}
  4427. \begin{minipage}{0.4\textwidth}
  4428. \begin{lstlisting}
  4429. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4430. \end{lstlisting}
  4431. \end{minipage}
  4432. &
  4433. $\Rightarrow$
  4434. &
  4435. \begin{minipage}{0.4\textwidth}
  4436. \begin{lstlisting}
  4437. cmpq |$\Arg_2$|, |$\Arg_1$|
  4438. sete %al
  4439. movzbq %al, |$\Var$|
  4440. \end{lstlisting}
  4441. \end{minipage}
  4442. \end{tabular} \\
  4443. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4444. and conditional \key{goto}. Both are straightforward to handle. A
  4445. \key{goto} becomes a jump instruction.
  4446. \[
  4447. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4448. \]
  4449. A conditional \key{goto} becomes a compare instruction followed
  4450. by a conditional jump (for ``then'') and the fall-through is
  4451. to a regular jump (for ``else'').\\
  4452. \begin{tabular}{lll}
  4453. \begin{minipage}{0.4\textwidth}
  4454. \begin{lstlisting}
  4455. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4456. goto |$\ell_1$|;
  4457. else
  4458. goto |$\ell_2$|;
  4459. \end{lstlisting}
  4460. \end{minipage}
  4461. &
  4462. $\Rightarrow$
  4463. &
  4464. \begin{minipage}{0.4\textwidth}
  4465. \begin{lstlisting}
  4466. cmpq |$\Arg_2$|, |$\Arg_1$|
  4467. je |$\ell_1$|
  4468. jmp |$\ell_2$|
  4469. \end{lstlisting}
  4470. \end{minipage}
  4471. \end{tabular} \\
  4472. \begin{exercise}\normalfont
  4473. Expand your \code{select-instructions} pass to handle the new features
  4474. of the $R_2$ language. Test the pass on all the examples you have
  4475. created and make sure that you have some test programs that use the
  4476. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4477. the output using the \code{interp-x86} interpreter
  4478. (Appendix~\ref{appendix:interp}).
  4479. \end{exercise}
  4480. \section{Register Allocation}
  4481. \label{sec:register-allocation-r2}
  4482. \index{register allocation}
  4483. The changes required for $R_2$ affect liveness analysis, building the
  4484. interference graph, and assigning homes, but the graph coloring
  4485. algorithm itself does not change.
  4486. \subsection{Liveness Analysis}
  4487. \label{sec:liveness-analysis-r2}
  4488. \index{liveness analysis}
  4489. Recall that for $R_1$ we implemented liveness analysis for a single
  4490. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4491. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4492. produces many basic blocks arranged in a control-flow graph. The first
  4493. question we need to consider is: what order should we process the
  4494. basic blocks? Recall that to perform liveness analysis, we need to
  4495. know the live-after set. If a basic block has no successor blocks
  4496. (i.e. no out-edges in the control flow graph), then it has an empty
  4497. live-after set and we can immediately apply liveness analysis to
  4498. it. If a basic block has some successors, then we need to complete
  4499. liveness analysis on those blocks first. Furthermore, we know that
  4500. the control flow graph does not contain any cycles because $R_2$ does
  4501. not include loops
  4502. %
  4503. \footnote{If we were to add loops to the language, then the CFG could
  4504. contain cycles and we would instead need to use the classic worklist
  4505. algorithm for computing the fixed point of the liveness
  4506. analysis~\citep{Aho:1986qf}.}.
  4507. %
  4508. Returning to the question of what order should we process the basic
  4509. blocks, the answer is reverse topological order. We recommend using
  4510. the \code{tsort} (topological sort) and \code{transpose} functions of
  4511. the Racket \code{graph} package to obtain this ordering.
  4512. \index{topological order}
  4513. \index{topological sort}
  4514. The next question is how to compute the live-after set of a block
  4515. given the live-before sets of all its successor blocks. (There can be
  4516. more than one because of conditional jumps.) During compilation we do
  4517. not know which way a conditional jump will go, so we do not know which
  4518. of the successor's live-before set to use. The solution to this
  4519. challenge is based on the observation that there is no harm to the
  4520. correctness of the compiler if we classify more variables as live than
  4521. the ones that are truly live during a particular execution of the
  4522. block. Thus, we can take the union of the live-before sets from all
  4523. the successors to be the live-after set for the block. Once we have
  4524. computed the live-after set, we can proceed to perform liveness
  4525. analysis on the block just as we did in
  4526. Section~\ref{sec:liveness-analysis-r1}.
  4527. The helper functions for computing the variables in an instruction's
  4528. argument and for computing the variables read-from ($R$) or written-to
  4529. ($W$) by an instruction need to be updated to handle the new kinds of
  4530. arguments and instructions in x86$_1$.
  4531. \subsection{Build Interference}
  4532. \label{sec:build-interference-r2}
  4533. Many of the new instructions in x86$_1$ can be handled in the same way
  4534. as the instructions in x86$_0$. Thus, if your code was already quite
  4535. general, it will not need to be changed to handle the new
  4536. instructions. If you code is not general enough, I recommend that you
  4537. change your code to be more general. For example, you can factor out
  4538. the computing of the the read and write sets for each kind of
  4539. instruction into two auxiliary functions.
  4540. Note that the \key{movzbq} instruction requires some special care,
  4541. just like the \key{movq} instruction. See rule number 3 in
  4542. Section~\ref{sec:build-interference}.
  4543. %% \subsection{Assign Homes}
  4544. %% \label{sec:assign-homes-r2}
  4545. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4546. %% to be updated to handle the \key{if} statement, simply by recursively
  4547. %% processing the child nodes. Hopefully your code already handles the
  4548. %% other new instructions, but if not, you can generalize your code.
  4549. \begin{exercise}\normalfont
  4550. Update the \code{register-allocation} pass so that it works for $R_2$
  4551. and test your compiler using your previously created programs on the
  4552. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4553. \end{exercise}
  4554. \section{Patch Instructions}
  4555. The second argument of the \key{cmpq} instruction must not be an
  4556. immediate value (such as an integer). So if you are comparing two
  4557. immediates, we recommend inserting a \key{movq} instruction to put the
  4558. second argument in \key{rax}.
  4559. %
  4560. The second argument of the \key{movzbq} must be a register.
  4561. %
  4562. There are no special restrictions on the x86 instructions \key{JmpIf}
  4563. and \key{Jmp}.
  4564. \begin{exercise}\normalfont
  4565. Update \code{patch-instructions} to handle the new x86 instructions.
  4566. Test your compiler using your previously created programs on the
  4567. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4568. \end{exercise}
  4569. \section{An Example Translation}
  4570. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4571. $R_2$ translated to x86, showing the results of
  4572. \code{explicate-control}, \code{select-instructions}, and the final
  4573. x86 assembly code.
  4574. \begin{figure}[tbp]
  4575. \begin{tabular}{lll}
  4576. \begin{minipage}{0.5\textwidth}
  4577. % s1_20.rkt
  4578. \begin{lstlisting}
  4579. (if (eq? (read) 1) 42 0)
  4580. \end{lstlisting}
  4581. $\Downarrow$
  4582. \begin{lstlisting}
  4583. start:
  4584. tmp7951 = (read);
  4585. if (eq? tmp7951 1) then
  4586. goto block7952;
  4587. else
  4588. goto block7953;
  4589. block7952:
  4590. return 42;
  4591. block7953:
  4592. return 0;
  4593. \end{lstlisting}
  4594. $\Downarrow$
  4595. \begin{lstlisting}
  4596. start:
  4597. callq read_int
  4598. movq %rax, tmp7951
  4599. cmpq $1, tmp7951
  4600. je block7952
  4601. jmp block7953
  4602. block7953:
  4603. movq $0, %rax
  4604. jmp conclusion
  4605. block7952:
  4606. movq $42, %rax
  4607. jmp conclusion
  4608. \end{lstlisting}
  4609. \end{minipage}
  4610. &
  4611. $\Rightarrow\qquad$
  4612. \begin{minipage}{0.4\textwidth}
  4613. \begin{lstlisting}
  4614. start:
  4615. callq read_int
  4616. movq %rax, %rcx
  4617. cmpq $1, %rcx
  4618. je block7952
  4619. jmp block7953
  4620. block7953:
  4621. movq $0, %rax
  4622. jmp conclusion
  4623. block7952:
  4624. movq $42, %rax
  4625. jmp conclusion
  4626. .globl main
  4627. main:
  4628. pushq %rbp
  4629. movq %rsp, %rbp
  4630. pushq %r13
  4631. pushq %r12
  4632. pushq %rbx
  4633. pushq %r14
  4634. subq $0, %rsp
  4635. jmp start
  4636. conclusion:
  4637. addq $0, %rsp
  4638. popq %r14
  4639. popq %rbx
  4640. popq %r12
  4641. popq %r13
  4642. popq %rbp
  4643. retq
  4644. \end{lstlisting}
  4645. \end{minipage}
  4646. \end{tabular}
  4647. \caption{Example compilation of an \key{if} expression to x86.}
  4648. \label{fig:if-example-x86}
  4649. \end{figure}
  4650. \begin{figure}[p]
  4651. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4652. \node (R2) at (0,2) {\large $R_2$};
  4653. \node (R2-2) at (3,2) {\large $R_2$};
  4654. \node (R2-3) at (6,2) {\large $R_2$};
  4655. \node (R2-4) at (9,2) {\large $R_2$};
  4656. \node (R2-5) at (9,0) {\large $R_2$};
  4657. \node (C1-1) at (3,-2) {\large $C_1$};
  4658. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4659. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4660. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4661. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4662. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4663. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4664. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4665. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4666. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4667. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4668. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4669. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4670. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4671. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4672. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4673. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4674. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4675. \end{tikzpicture}
  4676. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4677. \label{fig:R2-passes}
  4678. \end{figure}
  4679. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4680. compilation of $R_2$.
  4681. \section{Challenge: Optimize and Remove Jumps}
  4682. \label{sec:opt-jumps}
  4683. Recall that in the example output of \code{explicate-control} in
  4684. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4685. \code{block60} are trivial blocks, they do nothing but jump to another
  4686. block. The first goal of this challenge assignment is to remove those
  4687. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4688. \code{explicate-control} on the left and shows the result of bypassing
  4689. the trivial blocks on the right. Let us focus on \code{block61}. The
  4690. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4691. \code{block55}. The optimized code on the right of
  4692. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4693. \code{then} branch jumping directly to \code{block55}. The story is
  4694. similar for the \code{else} branch, as well as for the two branches in
  4695. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4696. have been optimized in this way, there are no longer any jumps to
  4697. blocks \code{block57} through \code{block60}, so they can be removed.
  4698. \begin{figure}[tbp]
  4699. \begin{tabular}{lll}
  4700. \begin{minipage}{0.4\textwidth}
  4701. \begin{lstlisting}
  4702. block62:
  4703. tmp54 = (read);
  4704. if (eq? tmp54 2) then
  4705. goto block59;
  4706. else
  4707. goto block60;
  4708. block61:
  4709. tmp53 = (read);
  4710. if (eq? tmp53 0) then
  4711. goto block57;
  4712. else
  4713. goto block58;
  4714. block60:
  4715. goto block56;
  4716. block59:
  4717. goto block55;
  4718. block58:
  4719. goto block56;
  4720. block57:
  4721. goto block55;
  4722. block56:
  4723. return (+ 700 77);
  4724. block55:
  4725. return (+ 10 32);
  4726. start:
  4727. tmp52 = (read);
  4728. if (eq? tmp52 1) then
  4729. goto block61;
  4730. else
  4731. goto block62;
  4732. \end{lstlisting}
  4733. \end{minipage}
  4734. &
  4735. $\Rightarrow$
  4736. &
  4737. \begin{minipage}{0.55\textwidth}
  4738. \begin{lstlisting}
  4739. block62:
  4740. tmp54 = (read);
  4741. if (eq? tmp54 2) then
  4742. goto block55;
  4743. else
  4744. goto block56;
  4745. block61:
  4746. tmp53 = (read);
  4747. if (eq? tmp53 0) then
  4748. goto block55;
  4749. else
  4750. goto block56;
  4751. block56:
  4752. return (+ 700 77);
  4753. block55:
  4754. return (+ 10 32);
  4755. start:
  4756. tmp52 = (read);
  4757. if (eq? tmp52 1) then
  4758. goto block61;
  4759. else
  4760. goto block62;
  4761. \end{lstlisting}
  4762. \end{minipage}
  4763. \end{tabular}
  4764. \caption{Optimize jumps by removing trivial blocks.}
  4765. \label{fig:optimize-jumps}
  4766. \end{figure}
  4767. The name of this pass is \code{optimize-jumps}. We recommend
  4768. implementing this pass in two phases. The first phrase builds a hash
  4769. table that maps labels to possibly improved labels. The second phase
  4770. changes the target of each \code{goto} to use the improved label. If
  4771. the label is for a trivial block, then the hash table should map the
  4772. label to the first non-trivial block that can be reached from this
  4773. label by jumping through trivial blocks. If the label is for a
  4774. non-trivial block, then the hash table should map the label to itself;
  4775. we do not want to change jumps to non-trivial blocks.
  4776. The first phase can be accomplished by constructing an empty hash
  4777. table, call it \code{short-cut}, and then iterating over the control
  4778. flow graph. Each time you encouter a block that is just a \code{goto},
  4779. then update the hash table, mapping the block's source to the target
  4780. of the \code{goto}. Also, the hash table may already have mapped some
  4781. labels to the block's source, to you must iterate through the hash
  4782. table and update all of those so that they instead map to the target
  4783. of the \code{goto}.
  4784. For the second phase, we recommend iterating through the $\Tail$ of
  4785. each block in the program, updating the target of every \code{goto}
  4786. according to the mapping in \code{short-cut}.
  4787. \begin{exercise}\normalfont
  4788. Implement the \code{optimize-jumps} pass as a transformation from
  4789. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4790. Check that \code{optimize-jumps} removes trivial blocks in a few
  4791. example programs. Then check that your compiler still passes all of
  4792. your tests.
  4793. \end{exercise}
  4794. There is another opportunity for optimizing jumps that is apparent in
  4795. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4796. end with a jump to \code{block7953} and there are no other jumps to
  4797. \code{block7953} in the rest of the program. In this situation we can
  4798. avoid the runtime overhead of this jump by merging \code{block7953}
  4799. into the preceeding block, in this case the \code{start} block.
  4800. Figure~\ref{fig:remove-jumps} shows the output of
  4801. \code{select-instructions} on the left and the result of this
  4802. optimization on the right.
  4803. \begin{figure}[tbp]
  4804. \begin{tabular}{lll}
  4805. \begin{minipage}{0.5\textwidth}
  4806. % s1_20.rkt
  4807. \begin{lstlisting}
  4808. start:
  4809. callq read_int
  4810. movq %rax, tmp7951
  4811. cmpq $1, tmp7951
  4812. je block7952
  4813. jmp block7953
  4814. block7953:
  4815. movq $0, %rax
  4816. jmp conclusion
  4817. block7952:
  4818. movq $42, %rax
  4819. jmp conclusion
  4820. \end{lstlisting}
  4821. \end{minipage}
  4822. &
  4823. $\Rightarrow\qquad$
  4824. \begin{minipage}{0.4\textwidth}
  4825. \begin{lstlisting}
  4826. start:
  4827. callq read_int
  4828. movq %rax, tmp7951
  4829. cmpq $1, tmp7951
  4830. je block7952
  4831. movq $0, %rax
  4832. jmp conclusion
  4833. block7952:
  4834. movq $42, %rax
  4835. jmp conclusion
  4836. \end{lstlisting}
  4837. \end{minipage}
  4838. \end{tabular}
  4839. \caption{Merging basic blocks by removing unnecessary jumps.}
  4840. \label{fig:remove-jumps}
  4841. \end{figure}
  4842. \begin{exercise}\normalfont
  4843. Implement a pass named \code{remove-jumps} that merges basic blocks
  4844. into their preceeding basic block, when there is only one preceeding
  4845. block. The pass should translate from psuedo $x86_1$ to pseudo
  4846. $x86_1$ and it should come immediately after
  4847. \code{select-instructions}. Check that \code{remove-jumps}
  4848. accomplishes the goal of merging basic blocks on several test
  4849. programs and check that your compiler passes all of your tests.
  4850. \end{exercise}
  4851. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4852. \chapter{Tuples and Garbage Collection}
  4853. \label{ch:tuples}
  4854. \index{tuple}
  4855. \index{vector}
  4856. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4857. add simple structures. \\ --Jeremy}
  4858. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4859. things to discuss in this chapter. \\ --Jeremy}
  4860. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4861. all the IR grammars are spelled out! \\ --Jeremy}
  4862. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4863. but keep type annotations on vector creation and local variables, function
  4864. parameters, etc. \\ --Jeremy}
  4865. \margincomment{\scriptsize Be more explicit about how to deal with
  4866. the root stack. \\ --Jeremy}
  4867. In this chapter we study the implementation of mutable tuples (called
  4868. ``vectors'' in Racket). This language feature is the first to use the
  4869. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4870. indefinite, that is, a tuple lives forever from the programmer's
  4871. viewpoint. Of course, from an implementer's viewpoint, it is important
  4872. to reclaim the space associated with a tuple when it is no longer
  4873. needed, which is why we also study \emph{garbage collection}
  4874. \emph{garbage collection}
  4875. techniques in this chapter.
  4876. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4877. interpreter and type checker. The $R_3$ language extends the $R_2$
  4878. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4879. \code{void} value. The reason for including the later is that the
  4880. \code{vector-set!} operation returns a value of type
  4881. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4882. called the \code{Unit} type in the programming languages
  4883. literature. Racket's \code{Void} type is inhabited by a single value
  4884. \code{void} which corresponds to \code{unit} or \code{()} in the
  4885. literature~\citep{Pierce:2002hj}.}.
  4886. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4887. copying live objects back and forth between two halves of the
  4888. heap. The garbage collector requires coordination with the compiler so
  4889. that it can see all of the \emph{root} pointers, that is, pointers in
  4890. registers or on the procedure call stack.
  4891. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4892. discuss all the necessary changes and additions to the compiler
  4893. passes, including a new compiler pass named \code{expose-allocation}.
  4894. \section{The $R_3$ Language}
  4895. \label{sec:r3}
  4896. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4897. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4898. $R_3$ language includes three new forms: \code{vector} for creating a
  4899. tuple, \code{vector-ref} for reading an element of a tuple, and
  4900. \code{vector-set!} for writing to an element of a tuple. The program
  4901. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4902. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4903. the 3-tuple, demonstrating that tuples are first-class values. The
  4904. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4905. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4906. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4907. 1-tuple. So the result of the program is \code{42}.
  4908. \begin{figure}[tbp]
  4909. \centering
  4910. \fbox{
  4911. \begin{minipage}{0.96\textwidth}
  4912. \[
  4913. \begin{array}{lcl}
  4914. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4915. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4916. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4917. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4918. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4919. \mid (\key{and}\;\Exp\;\Exp)
  4920. \mid (\key{or}\;\Exp\;\Exp)
  4921. \mid (\key{not}\;\Exp) } \\
  4922. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4923. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4924. &\mid& (\key{vector}\;\Exp\ldots)
  4925. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4926. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4927. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4928. R_3 &::=& \Exp
  4929. \end{array}
  4930. \]
  4931. \end{minipage}
  4932. }
  4933. \caption{The concrete syntax of $R_3$, extending $R_2$
  4934. (Figure~\ref{fig:r2-concrete-syntax}).}
  4935. \label{fig:r3-concrete-syntax}
  4936. \end{figure}
  4937. \begin{figure}[tbp]
  4938. \begin{lstlisting}
  4939. (let ([t (vector 40 #t (vector 2))])
  4940. (if (vector-ref t 1)
  4941. (+ (vector-ref t 0)
  4942. (vector-ref (vector-ref t 2) 0))
  4943. 44))
  4944. \end{lstlisting}
  4945. \caption{Example program that creates tuples and reads from them.}
  4946. \label{fig:vector-eg}
  4947. \end{figure}
  4948. \begin{figure}[tp]
  4949. \centering
  4950. \fbox{
  4951. \begin{minipage}{0.96\textwidth}
  4952. \[
  4953. \begin{array}{lcl}
  4954. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4955. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4956. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4957. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4958. &\mid& \gray{ \BOOL{\itm{bool}}
  4959. \mid \AND{\Exp}{\Exp} }\\
  4960. &\mid& \gray{ \OR{\Exp}{\Exp}
  4961. \mid \NOT{\Exp} } \\
  4962. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4963. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4964. &\mid& \VECTOR{\Exp} \\
  4965. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  4966. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp}\\
  4967. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4968. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4969. \end{array}
  4970. \]
  4971. \end{minipage}
  4972. }
  4973. \caption{The abstract syntax of $R_3$.}
  4974. \label{fig:r3-syntax}
  4975. \end{figure}
  4976. \index{allocate}
  4977. \index{heap allocate}
  4978. Tuples are our first encounter with heap-allocated data, which raises
  4979. several interesting issues. First, variable binding performs a
  4980. shallow-copy when dealing with tuples, which means that different
  4981. variables can refer to the same tuple, that is, different variables
  4982. can be \emph{aliases} for the same entity. Consider the following
  4983. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4984. Thus, the mutation through \code{t2} is visible when referencing the
  4985. tuple from \code{t1}, so the result of this program is \code{42}.
  4986. \index{alias}\index{mutation}
  4987. \begin{center}
  4988. \begin{minipage}{0.96\textwidth}
  4989. \begin{lstlisting}
  4990. (let ([t1 (vector 3 7)])
  4991. (let ([t2 t1])
  4992. (let ([_ (vector-set! t2 0 42)])
  4993. (vector-ref t1 0))))
  4994. \end{lstlisting}
  4995. \end{minipage}
  4996. \end{center}
  4997. The next issue concerns the lifetime of tuples. Of course, they are
  4998. created by the \code{vector} form, but when does their lifetime end?
  4999. Notice that $R_3$ does not include an operation for deleting
  5000. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5001. of static scoping. For example, the following program returns
  5002. \code{42} even though the variable \code{w} goes out of scope prior to
  5003. the \code{vector-ref} that reads from the vector it was bound to.
  5004. \begin{center}
  5005. \begin{minipage}{0.96\textwidth}
  5006. \begin{lstlisting}
  5007. (let ([v (vector (vector 44))])
  5008. (let ([x (let ([w (vector 42)])
  5009. (let ([_ (vector-set! v 0 w)])
  5010. 0))])
  5011. (+ x (vector-ref (vector-ref v 0) 0))))
  5012. \end{lstlisting}
  5013. \end{minipage}
  5014. \end{center}
  5015. From the perspective of programmer-observable behavior, tuples live
  5016. forever. Of course, if they really lived forever, then many programs
  5017. would run out of memory.\footnote{The $R_3$ language does not have
  5018. looping or recursive functions, so it is nigh impossible to write a
  5019. program in $R_3$ that will run out of memory. However, we add
  5020. recursive functions in the next Chapter!} A Racket implementation
  5021. must therefore perform automatic garbage collection.
  5022. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5023. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5024. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5025. operations in Racket. One subtle point is that the \code{vector-set!}
  5026. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5027. can be passed around just like other values inside an $R_3$ program
  5028. and a \code{\#<void>} value can be compared for equality with another
  5029. \code{\#<void>} value. However, there are no other operations specific
  5030. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5031. the \code{void?} predicate that returns \code{\#t} when applied to
  5032. \code{\#<void>} and \code{\#f} otherwise.
  5033. \begin{figure}[tbp]
  5034. \begin{lstlisting}
  5035. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5036. (define (interp-op op)
  5037. (match op
  5038. ...
  5039. ['vector vector]
  5040. ['vector-ref vector-ref]
  5041. ['vector-set! vector-set!]
  5042. [else (error 'interp-op "unknown operator")]))
  5043. (define (interp-exp env)
  5044. (lambda (e)
  5045. (define recur (interp-exp env))
  5046. (match e
  5047. ...
  5048. )))
  5049. (define (interp-R3 p)
  5050. (match p
  5051. [(Program '() e)
  5052. ((interp-exp '()) e)]
  5053. ))
  5054. \end{lstlisting}
  5055. \caption{Interpreter for the $R_3$ language.}
  5056. \label{fig:interp-R3}
  5057. \end{figure}
  5058. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5059. deserves some explanation. As we see in Section~\ref{sec:GC}, we
  5060. need to know which variables contain pointers into the heap, that is,
  5061. which variables contain vectors. Also, when allocating a vector, we
  5062. need to know which elements of the vector are pointers. We can obtain
  5063. this information during type checking. The type checker in
  5064. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5065. expression, it also wraps every sub-expression $e$ with the form
  5066. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5067. Subsequently, in the \code{uncover-locals} pass
  5068. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5069. propagated to all variables (including the temporaries generated by
  5070. \code{remove-complex-opera*}).
  5071. To create the s-expression for the \code{Vector} type in
  5072. Figure~\ref{fig:type-check-R3}, we use the
  5073. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5074. operator} \code{,@} to insert the list \code{t*} without its usual
  5075. start and end parentheses. \index{unquote-slicing}
  5076. \begin{figure}[tp]
  5077. \begin{lstlisting}
  5078. (define (type-check-exp env)
  5079. (lambda (e)
  5080. (define recur (type-check-exp env))
  5081. (match e
  5082. ...
  5083. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5084. [(Prim 'vector es)
  5085. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5086. (let ([t `(Vector ,@t*)])
  5087. (values (HasType (Prim 'vector e*) t) t))]
  5088. [(Prim 'vector-ref (list e (Int i)))
  5089. (define-values (e^ t) (recur e))
  5090. (match t
  5091. [`(Vector ,ts ...)
  5092. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5093. (error 'type-check-exp "invalid index ~a" i))
  5094. (let ([t (list-ref ts i)])
  5095. (values
  5096. (HasType (Prim 'vector-ref
  5097. (list e^ (HasType (Int i) 'Integer)))
  5098. t)
  5099. t))]
  5100. [else (error "expected a vector in vector-ref, not" t)])]
  5101. [(Prim 'eq? (list e1 e2))
  5102. (define-values (e1^ T1) (recur e1))
  5103. (define-values (e2^ T2) (recur e2))
  5104. (unless (equal? T1 T2)
  5105. (error "arguments of eq? must have the same type, but are not"
  5106. (list T1 T2)))
  5107. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5108. ...
  5109. )))
  5110. \end{lstlisting}
  5111. \caption{Type checker for the $R_3$ language.}
  5112. \label{fig:type-check-R3}
  5113. \end{figure}
  5114. \section{Garbage Collection}
  5115. \label{sec:GC}
  5116. Here we study a relatively simple algorithm for garbage collection
  5117. that is the basis of state-of-the-art garbage
  5118. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5119. particular, we describe a two-space copying
  5120. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5121. perform the
  5122. copy~\citep{Cheney:1970aa}.
  5123. \index{copying collector}
  5124. \index{two-space copying collector}
  5125. Figure~\ref{fig:copying-collector} gives a
  5126. coarse-grained depiction of what happens in a two-space collector,
  5127. showing two time steps, prior to garbage collection (on the top) and
  5128. after garbage collection (on the bottom). In a two-space collector,
  5129. the heap is divided into two parts named the FromSpace and the
  5130. ToSpace. Initially, all allocations go to the FromSpace until there is
  5131. not enough room for the next allocation request. At that point, the
  5132. garbage collector goes to work to make more room.
  5133. \index{ToSpace}
  5134. \index{FromSpace}
  5135. The garbage collector must be careful not to reclaim tuples that will
  5136. be used by the program in the future. Of course, it is impossible in
  5137. general to predict what a program will do, but we can over approximate
  5138. the will-be-used tuples by preserving all tuples that could be
  5139. accessed by \emph{any} program given the current computer state. A
  5140. program could access any tuple whose address is in a register or on
  5141. the procedure call stack. These addresses are called the \emph{root
  5142. set}\index{root set}. In addition, a program could access any tuple that is
  5143. transitively reachable from the root set. Thus, it is safe for the
  5144. garbage collector to reclaim the tuples that are not reachable in this
  5145. way.
  5146. So the goal of the garbage collector is twofold:
  5147. \begin{enumerate}
  5148. \item preserve all tuple that are reachable from the root set via a
  5149. path of pointers, that is, the \emph{live} tuples, and
  5150. \item reclaim the memory of everything else, that is, the
  5151. \emph{garbage}.
  5152. \end{enumerate}
  5153. A copying collector accomplishes this by copying all of the live
  5154. objects from the FromSpace into the ToSpace and then performs a slight
  5155. of hand, treating the ToSpace as the new FromSpace and the old
  5156. FromSpace as the new ToSpace. In the example of
  5157. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5158. root set, one in a register and two on the stack. All of the live
  5159. objects have been copied to the ToSpace (the right-hand side of
  5160. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5161. pointer relationships. For example, the pointer in the register still
  5162. points to a 2-tuple whose first element is a 3-tuple and whose second
  5163. element is a 2-tuple. There are four tuples that are not reachable
  5164. from the root set and therefore do not get copied into the ToSpace.
  5165. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5166. created by a well-typed program in $R_3$ because it contains a
  5167. cycle. However, creating cycles will be possible once we get to $R_6$.
  5168. We design the garbage collector to deal with cycles to begin with so
  5169. we will not need to revisit this issue.
  5170. \begin{figure}[tbp]
  5171. \centering
  5172. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5173. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5174. \caption{A copying collector in action.}
  5175. \label{fig:copying-collector}
  5176. \end{figure}
  5177. There are many alternatives to copying collectors (and their bigger
  5178. siblings, the generational collectors) when its comes to garbage
  5179. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5180. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5181. collectors are that allocation is fast (just a comparison and pointer
  5182. increment), there is no fragmentation, cyclic garbage is collected,
  5183. and the time complexity of collection only depends on the amount of
  5184. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5185. main disadvantages of a two-space copying collector is that it uses a
  5186. lot of space and takes a long time to perform the copy, though these
  5187. problems are ameliorated in generational collectors. Racket and
  5188. Scheme programs tend to allocate many small objects and generate a lot
  5189. of garbage, so copying and generational collectors are a good fit.
  5190. Garbage collection is an active research topic, especially concurrent
  5191. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5192. developing new techniques and revisiting old
  5193. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5194. meet every year at the International Symposium on Memory Management to
  5195. present these findings.
  5196. \subsection{Graph Copying via Cheney's Algorithm}
  5197. \label{sec:cheney}
  5198. \index{Cheney's algorithm}
  5199. Let us take a closer look at the copying of the live objects. The
  5200. allocated objects and pointers can be viewed as a graph and we need to
  5201. copy the part of the graph that is reachable from the root set. To
  5202. make sure we copy all of the reachable vertices in the graph, we need
  5203. an exhaustive graph traversal algorithm, such as depth-first search or
  5204. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5205. such algorithms take into account the possibility of cycles by marking
  5206. which vertices have already been visited, so as to ensure termination
  5207. of the algorithm. These search algorithms also use a data structure
  5208. such as a stack or queue as a to-do list to keep track of the vertices
  5209. that need to be visited. We use breadth-first search and a trick
  5210. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5211. and copying tuples into the ToSpace.
  5212. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5213. copy progresses. The queue is represented by a chunk of contiguous
  5214. memory at the beginning of the ToSpace, using two pointers to track
  5215. the front and the back of the queue. The algorithm starts by copying
  5216. all tuples that are immediately reachable from the root set into the
  5217. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5218. old tuple to indicate that it has been visited. We discuss how this
  5219. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5220. pointers inside the copied tuples in the queue still point back to the
  5221. FromSpace. Once the initial queue has been created, the algorithm
  5222. enters a loop in which it repeatedly processes the tuple at the front
  5223. of the queue and pops it off the queue. To process a tuple, the
  5224. algorithm copies all the tuple that are directly reachable from it to
  5225. the ToSpace, placing them at the back of the queue. The algorithm then
  5226. updates the pointers in the popped tuple so they point to the newly
  5227. copied tuples.
  5228. \begin{figure}[tbp]
  5229. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5230. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5231. \label{fig:cheney}
  5232. \end{figure}
  5233. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5234. tuple whose second element is $42$ to the back of the queue. The other
  5235. pointer goes to a tuple that has already been copied, so we do not
  5236. need to copy it again, but we do need to update the pointer to the new
  5237. location. This can be accomplished by storing a \emph{forwarding
  5238. pointer} to the new location in the old tuple, back when we initially
  5239. copied the tuple into the ToSpace. This completes one step of the
  5240. algorithm. The algorithm continues in this way until the front of the
  5241. queue is empty, that is, until the front catches up with the back.
  5242. \subsection{Data Representation}
  5243. \label{sec:data-rep-gc}
  5244. The garbage collector places some requirements on the data
  5245. representations used by our compiler. First, the garbage collector
  5246. needs to distinguish between pointers and other kinds of data. There
  5247. are several ways to accomplish this.
  5248. \begin{enumerate}
  5249. \item Attached a tag to each object that identifies what type of
  5250. object it is~\citep{McCarthy:1960dz}.
  5251. \item Store different types of objects in different
  5252. regions~\citep{Steele:1977ab}.
  5253. \item Use type information from the program to either generate
  5254. type-specific code for collecting or to generate tables that can
  5255. guide the
  5256. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5257. \end{enumerate}
  5258. Dynamically typed languages, such as Lisp, need to tag objects
  5259. anyways, so option 1 is a natural choice for those languages.
  5260. However, $R_3$ is a statically typed language, so it would be
  5261. unfortunate to require tags on every object, especially small and
  5262. pervasive objects like integers and Booleans. Option 3 is the
  5263. best-performing choice for statically typed languages, but comes with
  5264. a relatively high implementation complexity. To keep this chapter
  5265. within a 2-week time budget, we recommend a combination of options 1
  5266. and 2, using separate strategies for the stack and the heap.
  5267. Regarding the stack, we recommend using a separate stack for pointers,
  5268. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5269. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5270. is, when a local variable needs to be spilled and is of type
  5271. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5272. stack instead of the normal procedure call stack. Furthermore, we
  5273. always spill vector-typed variables if they are live during a call to
  5274. the collector, thereby ensuring that no pointers are in registers
  5275. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5276. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5277. the data layout using a root stack. The root stack contains the two
  5278. pointers from the regular stack and also the pointer in the second
  5279. register.
  5280. \begin{figure}[tbp]
  5281. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5282. \caption{Maintaining a root stack to facilitate garbage collection.}
  5283. \label{fig:shadow-stack}
  5284. \end{figure}
  5285. The problem of distinguishing between pointers and other kinds of data
  5286. also arises inside of each tuple on the heap. We solve this problem by
  5287. attaching a tag, an extra 64-bits, to each
  5288. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5289. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5290. that we have drawn the bits in a big-endian way, from right-to-left,
  5291. with bit location 0 (the least significant bit) on the far right,
  5292. which corresponds to the direction of the x86 shifting instructions
  5293. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5294. is dedicated to specifying which elements of the tuple are pointers,
  5295. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5296. indicates there is a pointer and a 0 bit indicates some other kind of
  5297. data. The pointer mask starts at bit location 7. We have limited
  5298. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5299. the pointer mask. The tag also contains two other pieces of
  5300. information. The length of the tuple (number of elements) is stored in
  5301. bits location 1 through 6. Finally, the bit at location 0 indicates
  5302. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5303. value 1, then this tuple has not yet been copied. If the bit has
  5304. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5305. of a pointer are always zero anyways because our tuples are 8-byte
  5306. aligned.)
  5307. \begin{figure}[tbp]
  5308. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5309. \caption{Representation of tuples in the heap.}
  5310. \label{fig:tuple-rep}
  5311. \end{figure}
  5312. \subsection{Implementation of the Garbage Collector}
  5313. \label{sec:organize-gz}
  5314. \index{prelude}
  5315. An implementation of the copying collector is provided in the
  5316. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5317. interface to the garbage collector that is used by the compiler. The
  5318. \code{initialize} function creates the FromSpace, ToSpace, and root
  5319. stack and should be called in the prelude of the \code{main}
  5320. function. The \code{initialize} function puts the address of the
  5321. beginning of the FromSpace into the global variable
  5322. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5323. the address that is 1-past the last element of the FromSpace. (We use
  5324. half-open intervals to represent chunks of
  5325. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5326. points to the first element of the root stack.
  5327. As long as there is room left in the FromSpace, your generated code
  5328. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5329. %
  5330. The amount of room left in FromSpace is the difference between the
  5331. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5332. function should be called when there is not enough room left in the
  5333. FromSpace for the next allocation. The \code{collect} function takes
  5334. a pointer to the current top of the root stack (one past the last item
  5335. that was pushed) and the number of bytes that need to be
  5336. allocated. The \code{collect} function performs the copying collection
  5337. and leaves the heap in a state such that the next allocation will
  5338. succeed.
  5339. \begin{figure}[tbp]
  5340. \begin{lstlisting}
  5341. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5342. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5343. int64_t* free_ptr;
  5344. int64_t* fromspace_begin;
  5345. int64_t* fromspace_end;
  5346. int64_t** rootstack_begin;
  5347. \end{lstlisting}
  5348. \caption{The compiler's interface to the garbage collector.}
  5349. \label{fig:gc-header}
  5350. \end{figure}
  5351. %% \begin{exercise}
  5352. %% In the file \code{runtime.c} you will find the implementation of
  5353. %% \code{initialize} and a partial implementation of \code{collect}.
  5354. %% The \code{collect} function calls another function, \code{cheney},
  5355. %% to perform the actual copy, and that function is left to the reader
  5356. %% to implement. The following is the prototype for \code{cheney}.
  5357. %% \begin{lstlisting}
  5358. %% static void cheney(int64_t** rootstack_ptr);
  5359. %% \end{lstlisting}
  5360. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5361. %% rootstack (which is an array of pointers). The \code{cheney} function
  5362. %% also communicates with \code{collect} through the global
  5363. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5364. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5365. %% the ToSpace:
  5366. %% \begin{lstlisting}
  5367. %% static int64_t* tospace_begin;
  5368. %% static int64_t* tospace_end;
  5369. %% \end{lstlisting}
  5370. %% The job of the \code{cheney} function is to copy all the live
  5371. %% objects (reachable from the root stack) into the ToSpace, update
  5372. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5373. %% update the root stack so that it points to the objects in the
  5374. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5375. %% and ToSpace.
  5376. %% \end{exercise}
  5377. %% \section{Compiler Passes}
  5378. %% \label{sec:code-generation-gc}
  5379. The introduction of garbage collection has a non-trivial impact on our
  5380. compiler passes. We introduce two new compiler passes named
  5381. \code{expose-allocation} and \code{uncover-locals}. We make
  5382. significant changes to \code{select-instructions},
  5383. \code{build-interference}, \code{allocate-registers}, and
  5384. \code{print-x86} and make minor changes in severl more passes. The
  5385. following program will serve as our running example. It creates two
  5386. tuples, one nested inside the other. Both tuples have length one. The
  5387. program accesses the element in the inner tuple tuple via two vector
  5388. references.
  5389. % tests/s2_17.rkt
  5390. \begin{lstlisting}
  5391. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5392. \end{lstlisting}
  5393. \section{Shrink}
  5394. \label{sec:shrink-R3}
  5395. Recall that the \code{shrink} pass translates the primitives operators
  5396. into a smaller set of primitives. Because this pass comes after type
  5397. checking, but before the passes that require the type information in
  5398. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5399. to wrap \code{HasType} around each AST node that it generates.
  5400. \section{Expose Allocation}
  5401. \label{sec:expose-allocation}
  5402. The pass \code{expose-allocation} lowers the \code{vector} creation
  5403. form into a conditional call to the collector followed by the
  5404. allocation. We choose to place the \code{expose-allocation} pass
  5405. before \code{remove-complex-opera*} because the code generated by
  5406. \code{expose-allocation} contains complex operands. We also place
  5407. \code{expose-allocation} before \code{explicate-control} because
  5408. \code{expose-allocation} introduces new variables using \code{let},
  5409. but \code{let} is gone after \code{explicate-control}.
  5410. The output of \code{expose-allocation} is a language $R'_3$ that
  5411. extends $R_3$ with the three new forms that we use in the translation
  5412. of the \code{vector} form.
  5413. \[
  5414. \begin{array}{lcl}
  5415. \Exp &::=& \cdots
  5416. \mid (\key{collect} \,\itm{int})
  5417. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5418. \mid (\key{global-value} \,\itm{name})
  5419. \end{array}
  5420. \]
  5421. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5422. $n$ bytes. It will become a call to the \code{collect} function in
  5423. \code{runtime.c} in \code{select-instructions}. The
  5424. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5425. \index{allocate}
  5426. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5427. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5428. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5429. a global variable, such as \code{free\_ptr}.
  5430. In the following, we show the transformation for the \code{vector}
  5431. form into 1) a sequence of let-bindings for the initializing
  5432. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5433. \code{allocate}, and 4) the initialization of the vector. In the
  5434. following, \itm{len} refers to the length of the vector and
  5435. \itm{bytes} is how many total bytes need to be allocated for the
  5436. vector, which is 8 for the tag plus \itm{len} times 8.
  5437. \begin{lstlisting}
  5438. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5439. |$\Longrightarrow$|
  5440. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5441. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5442. (global-value fromspace_end))
  5443. (void)
  5444. (collect |\itm{bytes}|))])
  5445. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5446. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5447. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5448. |$v$|) ... )))) ...)
  5449. \end{lstlisting}
  5450. In the above, we suppressed all of the \code{has-type} forms in the
  5451. output for the sake of readability. The placement of the initializing
  5452. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5453. sequence of \code{vector-set!} is important, as those expressions may
  5454. trigger garbage collection and we cannot have an allocated but
  5455. uninitialized tuple on the heap during a collection.
  5456. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5457. \code{expose-allocation} pass on our running example.
  5458. \begin{figure}[tbp]
  5459. % tests/s2_17.rkt
  5460. \begin{lstlisting}
  5461. (vector-ref
  5462. (vector-ref
  5463. (let ([vecinit7976
  5464. (let ([vecinit7972 42])
  5465. (let ([collectret7974
  5466. (if (< (+ (global-value free_ptr) 16)
  5467. (global-value fromspace_end))
  5468. (void)
  5469. (collect 16)
  5470. )])
  5471. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5472. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5473. alloc7971)
  5474. )
  5475. )
  5476. )
  5477. ])
  5478. (let ([collectret7978
  5479. (if (< (+ (global-value free_ptr) 16)
  5480. (global-value fromspace_end))
  5481. (void)
  5482. (collect 16)
  5483. )])
  5484. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5485. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5486. alloc7975)
  5487. )
  5488. )
  5489. )
  5490. 0)
  5491. 0)
  5492. \end{lstlisting}
  5493. \caption{Output of the \code{expose-allocation} pass, minus
  5494. all of the \code{has-type} forms.}
  5495. \label{fig:expose-alloc-output}
  5496. \end{figure}
  5497. \section{Remove Complex Operands}
  5498. \label{sec:remove-complex-opera-R3}
  5499. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5500. should all be treated as complex operands. A new case for
  5501. \code{HasType} is needed and the case for \code{Prim} needs to be
  5502. handled carefully to prevent the \code{Prim} node from being separated
  5503. from its enclosing \code{HasType}.
  5504. \section{Explicate Control and the $C_2$ language}
  5505. \label{sec:explicate-control-r3}
  5506. \begin{figure}[tbp]
  5507. \fbox{
  5508. \begin{minipage}{0.96\textwidth}
  5509. \small
  5510. \[
  5511. \begin{array}{lcl}
  5512. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5513. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5514. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5515. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5516. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5517. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5518. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5519. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5520. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5521. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5522. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5523. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5524. \end{array}
  5525. \]
  5526. \end{minipage}
  5527. }
  5528. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5529. \label{fig:c2-concrete-syntax}
  5530. \end{figure}
  5531. \begin{figure}[tp]
  5532. \fbox{
  5533. \begin{minipage}{0.96\textwidth}
  5534. \small
  5535. \[
  5536. \begin{array}{lcl}
  5537. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5538. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5539. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5540. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5541. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5542. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5543. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5544. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5545. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5546. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5547. \mid (\key{Collect} \,\itm{int}) \\
  5548. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5549. \mid \GOTO{\itm{label}} } \\
  5550. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5551. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5552. \end{array}
  5553. \]
  5554. \end{minipage}
  5555. }
  5556. \caption{The abstract syntax of $C_2$, extending $C_1$
  5557. (Figure~\ref{fig:c1-syntax}).}
  5558. \label{fig:c2-syntax}
  5559. \end{figure}
  5560. The output of \code{explicate-control} is a program in the
  5561. intermediate language $C_2$, whose concrete syntax is defined in
  5562. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5563. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5564. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5565. \key{global-value} expressions and the \code{collect} statement. The
  5566. \code{explicate-control} pass can treat these new forms much like the
  5567. other forms.
  5568. \section{Uncover Locals}
  5569. \label{sec:uncover-locals-r3}
  5570. Recall that the \code{explicate-control} function collects all of the
  5571. local variables so that it can store them in the $\itm{info}$ field of
  5572. the \code{Program} structure. Also recall that we need to know the
  5573. types of all the local variables for purposes of identifying the root
  5574. set for the garbage collector. Thus, we create a pass named
  5575. \code{uncover-locals} to collect not just the variables but the
  5576. variables and their types in the form of an alist. Thanks to the
  5577. \code{HasType} nodes, the types are readily available at every
  5578. assignment to a variable. We recommend storing the resulting alist in
  5579. the $\itm{info}$ field of the program, associated with the
  5580. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5581. of the \code{uncover-locals} pass on the running example.
  5582. \begin{figure}[tbp]
  5583. % tests/s2_17.rkt
  5584. \begin{lstlisting}
  5585. locals:
  5586. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5587. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5588. collectret7974 : 'Void, initret7977 : 'Void,
  5589. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5590. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5591. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5592. vecinit7972 : 'Integer, initret7973 : 'Void,
  5593. block91:
  5594. (collect 16)
  5595. goto block89;
  5596. block90:
  5597. collectret7974 = (void);
  5598. goto block89;
  5599. block89:
  5600. alloc7971 = (allocate 1 (Vector Integer));
  5601. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5602. vecinit7976 = alloc7971;
  5603. tmp7982 = (global-value free_ptr);
  5604. tmp7983 = (+ tmp7982 16);
  5605. tmp7984 = (global-value fromspace_end);
  5606. if (< tmp7983 tmp7984) then
  5607. goto block87;
  5608. else
  5609. goto block88;
  5610. block88:
  5611. (collect 16)
  5612. goto block86;
  5613. block87:
  5614. collectret7978 = (void);
  5615. goto block86;
  5616. block86:
  5617. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5618. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5619. tmp7985 = (vector-ref alloc7975 0);
  5620. return (vector-ref tmp7985 0);
  5621. start:
  5622. vecinit7972 = 42;
  5623. tmp7979 = (global-value free_ptr);
  5624. tmp7980 = (+ tmp7979 16);
  5625. tmp7981 = (global-value fromspace_end);
  5626. if (< tmp7980 tmp7981) then
  5627. goto block90;
  5628. else
  5629. goto block91;
  5630. \end{lstlisting}
  5631. \caption{Output of \code{uncover-locals} for the running example.}
  5632. \label{fig:uncover-locals-r3}
  5633. \end{figure}
  5634. \clearpage
  5635. \section{Select Instructions and the x86$_2$ Language}
  5636. \label{sec:select-instructions-gc}
  5637. \index{instruction selection}
  5638. %% void (rep as zero)
  5639. %% allocate
  5640. %% collect (callq collect)
  5641. %% vector-ref
  5642. %% vector-set!
  5643. %% global (postpone)
  5644. In this pass we generate x86 code for most of the new operations that
  5645. were needed to compile tuples, including \code{Allocate},
  5646. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5647. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5648. the later has a different concrete syntax (see
  5649. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5650. \index{x86}
  5651. The \code{vector-ref} and \code{vector-set!} forms translate into
  5652. \code{movq} instructions. (The plus one in the offset is to get past
  5653. the tag at the beginning of the tuple representation.)
  5654. \begin{lstlisting}
  5655. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5656. |$\Longrightarrow$|
  5657. movq |$\itm{vec}'$|, %r11
  5658. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5659. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5660. |$\Longrightarrow$|
  5661. movq |$\itm{vec}'$|, %r11
  5662. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5663. movq $0, |$\itm{lhs'}$|
  5664. \end{lstlisting}
  5665. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5666. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5667. register \code{r11} ensures that offset expression
  5668. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5669. removing \code{r11} from consideration by the register allocating.
  5670. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5671. \code{rax}. Then the generated code for \code{vector-set!} would be
  5672. \begin{lstlisting}
  5673. movq |$\itm{vec}'$|, %rax
  5674. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5675. movq $0, |$\itm{lhs}'$|
  5676. \end{lstlisting}
  5677. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5678. \code{patch-instructions} would insert a move through \code{rax}
  5679. as follows.
  5680. \begin{lstlisting}
  5681. movq |$\itm{vec}'$|, %rax
  5682. movq |$\itm{arg}'$|, %rax
  5683. movq %rax, |$8(n+1)$|(%rax)
  5684. movq $0, |$\itm{lhs}'$|
  5685. \end{lstlisting}
  5686. But the above sequence of instructions does not work because we're
  5687. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5688. $\itm{arg}'$) at the same time!
  5689. We compile the \code{allocate} form to operations on the
  5690. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5691. is the next free address in the FromSpace, so we copy it into
  5692. \code{r11} and then move it forward by enough space for the tuple
  5693. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5694. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5695. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5696. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5697. tag is organized. We recommend using the Racket operations
  5698. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5699. during compilation. The type annotation in the \code{vector} form is
  5700. used to determine the pointer mask region of the tag.
  5701. \begin{lstlisting}
  5702. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5703. |$\Longrightarrow$|
  5704. movq free_ptr(%rip), %r11
  5705. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5706. movq $|$\itm{tag}$|, 0(%r11)
  5707. movq %r11, |$\itm{lhs}'$|
  5708. \end{lstlisting}
  5709. The \code{collect} form is compiled to a call to the \code{collect}
  5710. function in the runtime. The arguments to \code{collect} are 1) the
  5711. top of the root stack and 2) the number of bytes that need to be
  5712. allocated. We use another dedicated register, \code{r15}, to
  5713. store the pointer to the top of the root stack. So \code{r15} is not
  5714. available for use by the register allocator.
  5715. \begin{lstlisting}
  5716. (collect |$\itm{bytes}$|)
  5717. |$\Longrightarrow$|
  5718. movq %r15, %rdi
  5719. movq $|\itm{bytes}|, %rsi
  5720. callq collect
  5721. \end{lstlisting}
  5722. \begin{figure}[tp]
  5723. \fbox{
  5724. \begin{minipage}{0.96\textwidth}
  5725. \[
  5726. \begin{array}{lcl}
  5727. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5728. x86_1 &::= & \gray{ \key{.globl main} }\\
  5729. & & \gray{ \key{main:} \; \Instr\ldots }
  5730. \end{array}
  5731. \]
  5732. \end{minipage}
  5733. }
  5734. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5735. \label{fig:x86-2-concrete}
  5736. \end{figure}
  5737. \begin{figure}[tp]
  5738. \fbox{
  5739. \begin{minipage}{0.96\textwidth}
  5740. \small
  5741. \[
  5742. \begin{array}{lcl}
  5743. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5744. \mid \BYTEREG{\Reg}} \\
  5745. &\mid& (\key{Global}~\Var) \\
  5746. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5747. \end{array}
  5748. \]
  5749. \end{minipage}
  5750. }
  5751. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5752. \label{fig:x86-2}
  5753. \end{figure}
  5754. The concrete and abstract syntax of the $x86_2$ language is defined in
  5755. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5756. x86$_1$ just in the addition of the form for global variables.
  5757. %
  5758. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5759. \code{select-instructions} pass on the running example.
  5760. \begin{figure}[tbp]
  5761. \centering
  5762. % tests/s2_17.rkt
  5763. \begin{minipage}[t]{0.5\textwidth}
  5764. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5765. block35:
  5766. movq free_ptr(%rip), alloc9024
  5767. addq $16, free_ptr(%rip)
  5768. movq alloc9024, %r11
  5769. movq $131, 0(%r11)
  5770. movq alloc9024, %r11
  5771. movq vecinit9025, 8(%r11)
  5772. movq $0, initret9026
  5773. movq alloc9024, %r11
  5774. movq 8(%r11), tmp9034
  5775. movq tmp9034, %r11
  5776. movq 8(%r11), %rax
  5777. jmp conclusion
  5778. block36:
  5779. movq $0, collectret9027
  5780. jmp block35
  5781. block38:
  5782. movq free_ptr(%rip), alloc9020
  5783. addq $16, free_ptr(%rip)
  5784. movq alloc9020, %r11
  5785. movq $3, 0(%r11)
  5786. movq alloc9020, %r11
  5787. movq vecinit9021, 8(%r11)
  5788. movq $0, initret9022
  5789. movq alloc9020, vecinit9025
  5790. movq free_ptr(%rip), tmp9031
  5791. movq tmp9031, tmp9032
  5792. addq $16, tmp9032
  5793. movq fromspace_end(%rip), tmp9033
  5794. cmpq tmp9033, tmp9032
  5795. jl block36
  5796. jmp block37
  5797. block37:
  5798. movq %r15, %rdi
  5799. movq $16, %rsi
  5800. callq 'collect
  5801. jmp block35
  5802. block39:
  5803. movq $0, collectret9023
  5804. jmp block38
  5805. \end{lstlisting}
  5806. \end{minipage}
  5807. \begin{minipage}[t]{0.45\textwidth}
  5808. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5809. start:
  5810. movq $42, vecinit9021
  5811. movq free_ptr(%rip), tmp9028
  5812. movq tmp9028, tmp9029
  5813. addq $16, tmp9029
  5814. movq fromspace_end(%rip), tmp9030
  5815. cmpq tmp9030, tmp9029
  5816. jl block39
  5817. jmp block40
  5818. block40:
  5819. movq %r15, %rdi
  5820. movq $16, %rsi
  5821. callq 'collect
  5822. jmp block38
  5823. \end{lstlisting}
  5824. \end{minipage}
  5825. \caption{Output of the \code{select-instructions} pass.}
  5826. \label{fig:select-instr-output-gc}
  5827. \end{figure}
  5828. \clearpage
  5829. \section{Register Allocation}
  5830. \label{sec:reg-alloc-gc}
  5831. \index{register allocation}
  5832. As discussed earlier in this chapter, the garbage collector needs to
  5833. access all the pointers in the root set, that is, all variables that
  5834. are vectors. It will be the responsibility of the register allocator
  5835. to make sure that:
  5836. \begin{enumerate}
  5837. \item the root stack is used for spilling vector-typed variables, and
  5838. \item if a vector-typed variable is live during a call to the
  5839. collector, it must be spilled to ensure it is visible to the
  5840. collector.
  5841. \end{enumerate}
  5842. The later responsibility can be handled during construction of the
  5843. interference graph, by adding interference edges between the call-live
  5844. vector-typed variables and all the callee-saved registers. (They
  5845. already interfere with the caller-saved registers.) The type
  5846. information for variables is in the \code{Program} form, so we
  5847. recommend adding another parameter to the \code{build-interference}
  5848. function to communicate this alist.
  5849. The spilling of vector-typed variables to the root stack can be
  5850. handled after graph coloring, when choosing how to assign the colors
  5851. (integers) to registers and stack locations. The \code{Program} output
  5852. of this pass changes to also record the number of spills to the root
  5853. stack.
  5854. % build-interference
  5855. %
  5856. % callq
  5857. % extra parameter for var->type assoc. list
  5858. % update 'program' and 'if'
  5859. % allocate-registers
  5860. % allocate spilled vectors to the rootstack
  5861. % don't change color-graph
  5862. \section{Print x86}
  5863. \label{sec:print-x86-gc}
  5864. \index{prelude}\index{conclusion}
  5865. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5866. \code{print-x86} pass on the running example. In the prelude and
  5867. conclusion of the \code{main} function, we treat the root stack very
  5868. much like the regular stack in that we move the root stack pointer
  5869. (\code{r15}) to make room for the spills to the root stack, except
  5870. that the root stack grows up instead of down. For the running
  5871. example, there was just one spill so we increment \code{r15} by 8
  5872. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5873. One issue that deserves special care is that there may be a call to
  5874. \code{collect} prior to the initializing assignments for all the
  5875. variables in the root stack. We do not want the garbage collector to
  5876. accidentally think that some uninitialized variable is a pointer that
  5877. needs to be followed. Thus, we zero-out all locations on the root
  5878. stack in the prelude of \code{main}. In
  5879. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5880. %
  5881. \lstinline{movq $0, (%r15)}
  5882. %
  5883. accomplishes this task. The garbage collector tests each root to see
  5884. if it is null prior to dereferencing it.
  5885. \begin{figure}[htbp]
  5886. \begin{minipage}[t]{0.5\textwidth}
  5887. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5888. block35:
  5889. movq free_ptr(%rip), %rcx
  5890. addq $16, free_ptr(%rip)
  5891. movq %rcx, %r11
  5892. movq $131, 0(%r11)
  5893. movq %rcx, %r11
  5894. movq -8(%r15), %rax
  5895. movq %rax, 8(%r11)
  5896. movq $0, %rdx
  5897. movq %rcx, %r11
  5898. movq 8(%r11), %rcx
  5899. movq %rcx, %r11
  5900. movq 8(%r11), %rax
  5901. jmp conclusion
  5902. block36:
  5903. movq $0, %rcx
  5904. jmp block35
  5905. block38:
  5906. movq free_ptr(%rip), %rcx
  5907. addq $16, free_ptr(%rip)
  5908. movq %rcx, %r11
  5909. movq $3, 0(%r11)
  5910. movq %rcx, %r11
  5911. movq %rbx, 8(%r11)
  5912. movq $0, %rdx
  5913. movq %rcx, -8(%r15)
  5914. movq free_ptr(%rip), %rcx
  5915. addq $16, %rcx
  5916. movq fromspace_end(%rip), %rdx
  5917. cmpq %rdx, %rcx
  5918. jl block36
  5919. movq %r15, %rdi
  5920. movq $16, %rsi
  5921. callq collect
  5922. jmp block35
  5923. block39:
  5924. movq $0, %rcx
  5925. jmp block38
  5926. \end{lstlisting}
  5927. \end{minipage}
  5928. \begin{minipage}[t]{0.45\textwidth}
  5929. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5930. start:
  5931. movq $42, %rbx
  5932. movq free_ptr(%rip), %rdx
  5933. addq $16, %rdx
  5934. movq fromspace_end(%rip), %rcx
  5935. cmpq %rcx, %rdx
  5936. jl block39
  5937. movq %r15, %rdi
  5938. movq $16, %rsi
  5939. callq collect
  5940. jmp block38
  5941. .globl main
  5942. main:
  5943. pushq %rbp
  5944. movq %rsp, %rbp
  5945. pushq %r13
  5946. pushq %r12
  5947. pushq %rbx
  5948. pushq %r14
  5949. subq $0, %rsp
  5950. movq $16384, %rdi
  5951. movq $16, %rsi
  5952. callq initialize
  5953. movq rootstack_begin(%rip), %r15
  5954. movq $0, (%r15)
  5955. addq $8, %r15
  5956. jmp start
  5957. conclusion:
  5958. subq $8, %r15
  5959. addq $0, %rsp
  5960. popq %r14
  5961. popq %rbx
  5962. popq %r12
  5963. popq %r13
  5964. popq %rbp
  5965. retq
  5966. \end{lstlisting}
  5967. \end{minipage}
  5968. \caption{Output of the \code{print-x86} pass.}
  5969. \label{fig:print-x86-output-gc}
  5970. \end{figure}
  5971. \begin{figure}[p]
  5972. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5973. \node (R3) at (0,2) {\large $R_3$};
  5974. \node (R3-2) at (3,2) {\large $R_3$};
  5975. \node (R3-3) at (6,2) {\large $R_3$};
  5976. \node (R3-4) at (9,2) {\large $R_3$};
  5977. \node (R3-5) at (9,0) {\large $R'_3$};
  5978. \node (R3-6) at (6,0) {\large $R'_3$};
  5979. \node (C2-4) at (3,-2) {\large $C_2$};
  5980. \node (C2-3) at (0,-2) {\large $C_2$};
  5981. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5982. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5983. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5984. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5985. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5986. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5987. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  5988. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5989. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5990. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5991. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5992. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5993. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5994. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5995. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5996. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5997. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5998. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5999. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6000. \end{tikzpicture}
  6001. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6002. \label{fig:R3-passes}
  6003. \end{figure}
  6004. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6005. for the compilation of $R_3$.
  6006. \section{Challenge: Simple Structures}
  6007. \label{sec:simple-structures}
  6008. \index{struct}
  6009. \index{structure}
  6010. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6011. $R^s_3$, which extends $R^3$ with support for simple structures.
  6012. Recall that a \code{struct} in Typed Racket is a user-defined data
  6013. type that contains named fields and that is heap allocated, similar to
  6014. a vector. The following is an example of a structure definition, in
  6015. this case the definition of a \code{point} type.
  6016. \begin{lstlisting}
  6017. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6018. \end{lstlisting}
  6019. \begin{figure}[tbp]
  6020. \centering
  6021. \fbox{
  6022. \begin{minipage}{0.96\textwidth}
  6023. \[
  6024. \begin{array}{lcl}
  6025. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6026. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6027. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6028. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6029. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6030. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6031. \mid (\key{and}\;\Exp\;\Exp)
  6032. \mid (\key{or}\;\Exp\;\Exp)
  6033. \mid (\key{not}\;\Exp) } \\
  6034. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6035. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6036. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6037. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6038. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6039. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6040. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6041. R_3 &::=& \Def \ldots \; \Exp
  6042. \end{array}
  6043. \]
  6044. \end{minipage}
  6045. }
  6046. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6047. (Figure~\ref{fig:r3-concrete-syntax}).}
  6048. \label{fig:r3s-concrete-syntax}
  6049. \end{figure}
  6050. An instance of a structure is created using function call syntax, with
  6051. the name of the structure in the function position:
  6052. \begin{lstlisting}
  6053. (point 7 12)
  6054. \end{lstlisting}
  6055. Function-call syntax is also used to read the value in a field of a
  6056. structure. The function name is formed by the structure name, a dash,
  6057. and the field name. The following example uses \code{point-x} and
  6058. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6059. instances.
  6060. \begin{center}
  6061. \begin{lstlisting}
  6062. (let ([pt1 (point 7 12)])
  6063. (let ([pt2 (point 4 3)])
  6064. (+ (- (point-x pt1) (point-x pt2))
  6065. (- (point-y pt1) (point-y pt2)))))
  6066. \end{lstlisting}
  6067. \end{center}
  6068. Similarly, to write to a field of a structure, use its set function,
  6069. whose name starts with \code{set-}, followed by the structure name,
  6070. then a dash, then the field name, and conclused with an exclamation
  6071. mark. The folowing example uses \code{set-point-x!} to change the
  6072. \code{x} field from \code{7} to \code{42}.
  6073. \begin{center}
  6074. \begin{lstlisting}
  6075. (let ([pt (point 7 12)])
  6076. (let ([_ (set-point-x! pt 42)])
  6077. (point-x pt)))
  6078. \end{lstlisting}
  6079. \end{center}
  6080. \begin{exercise}\normalfont
  6081. Extend your compiler with support for simple structures, compiling
  6082. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6083. structures and test your compiler.
  6084. \end{exercise}
  6085. \section{Challenge: Generational Collection}
  6086. The copying collector described in Section~\ref{sec:GC} can incur
  6087. significant runtime overhead because the call to \code{collect} takes
  6088. time proportional to all of the live data. One way to reduce this
  6089. overhead is to reduce how much data is inspected in each call to
  6090. \code{collect}. In particular, researchers have observed that recently
  6091. allocated data is more likely to become garbage then data that has
  6092. survived one or more previous calls to \code{collect}. This insight
  6093. motivated the creation of \emph{generational garbage collectors}
  6094. \index{generational garbage collector} that
  6095. 1) segragates data according to its age into two or more generations,
  6096. 2) allocates less space for younger generations, so collecting them is
  6097. faster, and more space for the older generations, and 3) performs
  6098. collection on the younger generations more frequently then for older
  6099. generations~\citep{Wilson:1992fk}.
  6100. For this challenge assignment, the goal is to adapt the copying
  6101. collector implemented in \code{runtime.c} to use two generations, one
  6102. for young data and one for old data. Each generation consists of a
  6103. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6104. \code{collect} function to use the two generations.
  6105. \begin{enumerate}
  6106. \item Copy the young generation's FromSpace to its ToSpace then switch
  6107. the role of the ToSpace and FromSpace
  6108. \item If there is enough space for the requested number of bytes in
  6109. the young FromSpace, then return from \code{collect}.
  6110. \item If there is not enough space in the young FromSpace for the
  6111. requested bytes, then move the data from the young generation to the
  6112. old one with the following steps:
  6113. \begin{enumerate}
  6114. \item If there is enough room in the old FromSpace, copy the young
  6115. FromSpace to the old FromSpace and then return.
  6116. \item If there is not enough room in the old FromSpace, then collect
  6117. the old generation by copying the old FromSpace to the old ToSpace
  6118. and swap the roles of the old FromSpace and ToSpace.
  6119. \item If there is enough room now, copy the young FromSpace to the
  6120. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6121. and ToSpace for the old generation. Copy the young FromSpace and
  6122. the old FromSpace into the larger FromSpace for the old
  6123. generation and then return.
  6124. \end{enumerate}
  6125. \end{enumerate}
  6126. We recommend that you generalize the \code{cheney} function so that it
  6127. can be used for all the copies mentioned above: between the young
  6128. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6129. between the young FromSpace and old FromSpace. This can be
  6130. accomplished by adding parameters to \code{cheney} that replace its
  6131. use of the global variables \code{fromspace\_begin},
  6132. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6133. Note that the collection of the young generation does not traverse the
  6134. old generation. This introduces a potential problem: there may be
  6135. young data that is only reachable through pointers in the old
  6136. generation. If these pointers are not taken into account, the
  6137. collector could throw away young data that is live! One solution,
  6138. called \emph{pointer recording}, is to maintain a set of all the
  6139. pointers from the old generation into the new generation and consider
  6140. this set as part of the root set. To maintain this set, the compiler
  6141. must insert extra instructions around every \code{vector-set!}. If the
  6142. vector being modified is in the old generation, and if the value being
  6143. written is a pointer into the new generation, than that pointer must
  6144. be added to the set. Also, if the value being overwritten was a
  6145. pointer into the new generation, then that pointer should be removed
  6146. from the set.
  6147. \begin{exercise}\normalfont
  6148. Adapt the \code{collect} function in \code{runtime.c} to implement
  6149. generational garbage collection, as outlined in this section.
  6150. Update the code generation for \code{vector-set!} to implement
  6151. pointer recording. Make sure that your new compiler and runtime
  6152. passes your test suite.
  6153. \end{exercise}
  6154. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6155. \chapter{Functions}
  6156. \label{ch:functions}
  6157. \index{function}
  6158. This chapter studies the compilation of functions similar to those
  6159. found in the C language. This corresponds to a subset of Typed Racket
  6160. in which only top-level function definitions are allowed. This kind of
  6161. function is an important stepping stone to implementing
  6162. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6163. is the topic of Chapter~\ref{ch:lambdas}.
  6164. \section{The $R_4$ Language}
  6165. The concrete and abstract syntax for function definitions and function
  6166. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6167. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6168. $R_4$ begin with zero or more function definitions. The function
  6169. names from these definitions are in-scope for the entire program,
  6170. including all other function definitions (so the ordering of function
  6171. definitions does not matter). The concrete syntax for function
  6172. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6173. where the first expression must
  6174. evaluate to a function and the rest are the arguments.
  6175. The abstract syntax for function application is
  6176. $\APPLY{\Exp}{\Exp\ldots}$.
  6177. %% The syntax for function application does not include an explicit
  6178. %% keyword, which is error prone when using \code{match}. To alleviate
  6179. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6180. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6181. Functions are first-class in the sense that a function pointer
  6182. \index{function pointer} is data and can be stored in memory or passed
  6183. as a parameter to another function. Thus, we introduce a function
  6184. type, written
  6185. \begin{lstlisting}
  6186. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6187. \end{lstlisting}
  6188. for a function whose $n$ parameters have the types $\Type_1$ through
  6189. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6190. these functions (with respect to Racket functions) is that they are
  6191. not lexically scoped. That is, the only external entities that can be
  6192. referenced from inside a function body are other globally-defined
  6193. functions. The syntax of $R_4$ prevents functions from being nested
  6194. inside each other.
  6195. \begin{figure}[tp]
  6196. \centering
  6197. \fbox{
  6198. \begin{minipage}{0.96\textwidth}
  6199. \small
  6200. \[
  6201. \begin{array}{lcl}
  6202. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6203. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6204. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6205. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6206. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6207. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6208. \mid (\key{and}\;\Exp\;\Exp)
  6209. \mid (\key{or}\;\Exp\;\Exp)
  6210. \mid (\key{not}\;\Exp)} \\
  6211. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6212. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6213. (\key{vector-ref}\;\Exp\;\Int)} \\
  6214. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6215. \mid (\key{has-type}~\Exp~\Type)} \\
  6216. &\mid& (\Exp \; \Exp \ldots) \\
  6217. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6218. R_4 &::=& \Def \ldots \; \Exp
  6219. \end{array}
  6220. \]
  6221. \end{minipage}
  6222. }
  6223. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6224. \label{fig:r4-concrete-syntax}
  6225. \end{figure}
  6226. \begin{figure}[tp]
  6227. \centering
  6228. \fbox{
  6229. \begin{minipage}{0.96\textwidth}
  6230. \small
  6231. \[
  6232. \begin{array}{lcl}
  6233. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6234. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6235. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6236. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6237. &\mid& \gray{ \BOOL{\itm{bool}}
  6238. \mid \AND{\Exp}{\Exp} }\\
  6239. &\mid& \gray{ \OR{\Exp}{\Exp}
  6240. \mid \NOT{\Exp} } \\
  6241. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6242. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6243. &\mid& \gray{ \VECTOR{\Exp} } \\
  6244. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6245. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6246. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6247. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6248. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6249. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6250. \end{array}
  6251. \]
  6252. \end{minipage}
  6253. }
  6254. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6255. \label{fig:r4-syntax}
  6256. \end{figure}
  6257. The program in Figure~\ref{fig:r4-function-example} is a
  6258. representative example of defining and using functions in $R_4$. We
  6259. define a function \code{map-vec} that applies some other function
  6260. \code{f} to both elements of a vector and returns a new
  6261. vector containing the results. We also define a function \code{add1}.
  6262. The program applies
  6263. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6264. \code{(vector 1 42)}, from which we return the \code{42}.
  6265. \begin{figure}[tbp]
  6266. \begin{lstlisting}
  6267. (define (map-vec [f : (Integer -> Integer)]
  6268. [v : (Vector Integer Integer)])
  6269. : (Vector Integer Integer)
  6270. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6271. (define (add1 [x : Integer]) : Integer
  6272. (+ x 1))
  6273. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6274. \end{lstlisting}
  6275. \caption{Example of using functions in $R_4$.}
  6276. \label{fig:r4-function-example}
  6277. \end{figure}
  6278. The definitional interpreter for $R_4$ is in
  6279. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6280. responsible for setting up the mutual recursion between the top-level
  6281. function definitions. We use the classic back-patching \index{back-patching}
  6282. approach that uses mutable variables and makes two passes over the function
  6283. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6284. top-level environment using a mutable cons cell for each function
  6285. definition. Note that the \code{lambda} value for each function is
  6286. incomplete; it does not yet include the environment. Once the
  6287. top-level environment is constructed, we then iterate over it and
  6288. update the \code{lambda} values to use the top-level environment.
  6289. \begin{figure}[tp]
  6290. \begin{lstlisting}
  6291. (define (interp-exp env)
  6292. (lambda (e)
  6293. (define recur (interp-exp env))
  6294. (match e
  6295. ...
  6296. [(Apply fun args)
  6297. (define fun-val (recur fun))
  6298. (define arg-vals (for/list ([e args]) (recur e)))
  6299. (match fun-val
  6300. [`(lambda (,xs ...) ,body ,fun-env)
  6301. (define new-env (append (map cons xs arg-vals) fun-env))
  6302. ((interp-exp new-env) body)])]
  6303. ...
  6304. )))
  6305. (define (interp-def d)
  6306. (match d
  6307. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6308. (mcons f `(lambda ,xs ,body ()))]
  6309. ))
  6310. (define (interp-R4 p)
  6311. (match p
  6312. [(ProgramDefsExp info ds body)
  6313. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6314. (for/list ([b top-level])
  6315. (set-mcdr! b (match (mcdr b)
  6316. [`(lambda ,xs ,body ())
  6317. `(lambda ,xs ,body ,top-level)])))
  6318. ((interp-exp top-level) body))]
  6319. ))
  6320. \end{lstlisting}
  6321. \caption{Interpreter for the $R_4$ language.}
  6322. \label{fig:interp-R4}
  6323. \end{figure}
  6324. \margincomment{TODO: explain type checker}
  6325. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6326. \begin{figure}[tp]
  6327. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6328. (define (fun-def-name d)
  6329. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6330. (define (fun-def-type d)
  6331. (match d
  6332. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6333. (define (type-check-exp env)
  6334. (lambda (e)
  6335. (match e
  6336. ...
  6337. [(Apply e es)
  6338. (define-values (e^ ty) ((type-check-exp env) e))
  6339. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6340. ((type-check-exp env) e)))
  6341. (match ty
  6342. [`(,ty^* ... -> ,rt)
  6343. (for ([arg-ty ty*] [prm-ty ty^*])
  6344. (unless (equal? arg-ty prm-ty)
  6345. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6346. (values (HasType (Apply e^ e*) rt) rt)]
  6347. [else (error "expected a function, not" ty)])])))
  6348. (define (type-check-def env)
  6349. (lambda (e)
  6350. (match e
  6351. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6352. (define new-env (append (map cons xs ps) env))
  6353. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6354. (unless (equal? ty^ rt)
  6355. (error "body type ~a not equal to return type ~a" ty^ rt))
  6356. (Def f p:t* rt info body^)])))
  6357. (define (type-check env)
  6358. (lambda (e)
  6359. (match e
  6360. [(ProgramDefsExp info ds body)
  6361. (define new-env (for/list ([d ds])
  6362. (cons (fun-def-name d) (fun-def-type d))))
  6363. (define ds^ (for/list ([d ds])
  6364. ((type-check-def new-env) d)))
  6365. (define-values (body^ ty) ((type-check-exp new-env) body))
  6366. (unless (equal? ty 'Integer)
  6367. (error "result of the program must be an integer, not " ty))
  6368. (ProgramDefsExp info ds^ body^)]
  6369. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6370. \end{lstlisting}
  6371. \caption{Type checker for the $R_4$ language.}
  6372. \label{fig:type-check-R4}
  6373. \end{figure}
  6374. \section{Functions in x86}
  6375. \label{sec:fun-x86}
  6376. \margincomment{\tiny Make sure callee-saved registers are discussed
  6377. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6378. \margincomment{\tiny Talk about the return address on the
  6379. stack and what callq and retq does.\\ --Jeremy }
  6380. The x86 architecture provides a few features to support the
  6381. implementation of functions. We have already seen that x86 provides
  6382. labels so that one can refer to the location of an instruction, as is
  6383. needed for jump instructions. Labels can also be used to mark the
  6384. beginning of the instructions for a function. Going further, we can
  6385. obtain the address of a label by using the \key{leaq} instruction and
  6386. PC-relative addressing. For example, the following puts the
  6387. address of the \code{add1} label into the \code{rbx} register.
  6388. \begin{lstlisting}
  6389. leaq add1(%rip), %rbx
  6390. \end{lstlisting}
  6391. The instruction pointer register \key{rip} (aka. the program counter
  6392. \index{program counter}) always points to the next instruction to be
  6393. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6394. linker computes the distance $d$ between the address of \code{add1}
  6395. and where the \code{rip} would be at that moment and then changes
  6396. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6397. the address of \code{add1}.
  6398. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6399. jump to a function whose location is given by a label. To support
  6400. function calls in this chapter we instead will be jumping to a
  6401. function whose location is given by an address in a register, that is,
  6402. we need to make an \emph{indirect function call}. The x86 syntax for
  6403. this is a \code{callq} instruction but with an asterisk before the
  6404. register name.\index{indirect function call}
  6405. \begin{lstlisting}
  6406. callq *%rbx
  6407. \end{lstlisting}
  6408. \subsection{Calling Conventions}
  6409. \index{calling conventions}
  6410. The \code{callq} instruction provides partial support for implementing
  6411. functions: it pushes the return address on the stack and it jumps to
  6412. the target. However, \code{callq} does not handle
  6413. \begin{enumerate}
  6414. \item parameter passing,
  6415. \item pushing frames on the procedure call stack and popping them off,
  6416. or
  6417. \item determining how registers are shared by different functions.
  6418. \end{enumerate}
  6419. These issues require coordination between the caller and the callee,
  6420. which is often assembly code written by different programmers or
  6421. generated by different compilers. As a result, people have developed
  6422. \emph{conventions} that govern how functions calls are performed.
  6423. Here we use conventions that are compatible with those of the
  6424. \code{gcc} compiler~\citep{Matz:2013aa}.
  6425. Regarding (1) parameter passing, recall that the following six
  6426. registers:
  6427. \begin{lstlisting}
  6428. rdi rsi rdx rcx r8 r9
  6429. \end{lstlisting}
  6430. in that order, are used to pass arguments to a function. If there are
  6431. more than six arguments, then the convention is to use space on the
  6432. frame of the caller for the rest of the arguments. However, to ease
  6433. the implementation of efficient tail calls
  6434. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6435. arguments.
  6436. %
  6437. Also recall that the register \code{rax} is for the return value of
  6438. the function.
  6439. \index{prelude}\index{conclusion}
  6440. Regarding (2) frames \index{frame} and the procedure call stack
  6441. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6442. the stack grows down, with each function call using a chunk of space
  6443. called a frame. The caller sets the stack pointer, register
  6444. \code{rsp}, to the last data item in its frame. The callee must not
  6445. change anything in the caller's frame, that is, anything that is at or
  6446. above the stack pointer. The callee is free to use locations that are
  6447. below the stack pointer.
  6448. Recall that we are storing variables of vector type on the root stack.
  6449. So the prelude needs to move the root stack pointer \code{r15} up and
  6450. the conclusion needs to move the root stack pointer back down. Also,
  6451. the prelude must initialize to \code{0} this frame's slots in the root
  6452. stack to signal to the garbage collector that those slots do not yet
  6453. contain a pointer to a vector. Otherwise the garbage collector will
  6454. interpret the garbage bits in those slots as memory addresses and try
  6455. to traverse them, causing serious mayhem!
  6456. Regarding (3) the sharing of registers between different functions,
  6457. recall from Section~\ref{sec:calling-conventions} that the registers
  6458. are divided into two groups, the caller-saved registers and the
  6459. callee-saved registers. The caller should assume that all the
  6460. caller-saved registers get overwritten with arbitrary values by the
  6461. callee. That is why we recommend in
  6462. Section~\ref{sec:calling-conventions} that variables that are live
  6463. during a function call should not be assigned to caller-saved
  6464. registers.
  6465. On the flip side, if the callee wants to use a callee-saved register,
  6466. the callee must save the contents of those registers on their stack
  6467. frame and then put them back prior to returning to the caller. That
  6468. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6469. the register allocator assigns a variable to a callee-saved register,
  6470. then the prelude of the \code{main} function must save that register
  6471. to the stack and the conclusion of \code{main} must restore it. This
  6472. recommendation now generalizes to all functions.
  6473. Also recall that the base pointer, register \code{rbp}, is used as a
  6474. point-of-reference within a frame, so that each local variable can be
  6475. accessed at a fixed offset from the base pointer
  6476. (Section~\ref{sec:x86}).
  6477. %
  6478. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6479. and callee frames.
  6480. \begin{figure}[tbp]
  6481. \centering
  6482. \begin{tabular}{r|r|l|l} \hline
  6483. Caller View & Callee View & Contents & Frame \\ \hline
  6484. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6485. 0(\key{\%rbp}) & & old \key{rbp} \\
  6486. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6487. \ldots & & \ldots \\
  6488. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6489. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6490. \ldots & & \ldots \\
  6491. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6492. %% & & \\
  6493. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6494. %% & \ldots & \ldots \\
  6495. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6496. \hline
  6497. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6498. & 0(\key{\%rbp}) & old \key{rbp} \\
  6499. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6500. & \ldots & \ldots \\
  6501. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6502. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6503. & \ldots & \ldots \\
  6504. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6505. \end{tabular}
  6506. \caption{Memory layout of caller and callee frames.}
  6507. \label{fig:call-frames}
  6508. \end{figure}
  6509. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6510. %% local variables and for storing the values of callee-saved registers
  6511. %% (we shall refer to all of these collectively as ``locals''), and that
  6512. %% at the beginning of a function we move the stack pointer \code{rsp}
  6513. %% down to make room for them.
  6514. %% We recommend storing the local variables
  6515. %% first and then the callee-saved registers, so that the local variables
  6516. %% can be accessed using \code{rbp} the same as before the addition of
  6517. %% functions.
  6518. %% To make additional room for passing arguments, we shall
  6519. %% move the stack pointer even further down. We count how many stack
  6520. %% arguments are needed for each function call that occurs inside the
  6521. %% body of the function and find their maximum. Adding this number to the
  6522. %% number of locals gives us how much the \code{rsp} should be moved at
  6523. %% the beginning of the function. In preparation for a function call, we
  6524. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6525. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6526. %% so on.
  6527. %% Upon calling the function, the stack arguments are retrieved by the
  6528. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6529. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6530. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6531. %% the layout of the caller and callee frames. Notice how important it is
  6532. %% that we correctly compute the maximum number of arguments needed for
  6533. %% function calls; if that number is too small then the arguments and
  6534. %% local variables will smash into each other!
  6535. \subsection{Efficient Tail Calls}
  6536. \label{sec:tail-call}
  6537. In general, the amount of stack space used by a program is determined
  6538. by the longest chain of nested function calls. That is, if function
  6539. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6540. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6541. $n$ can grow quite large in the case of recursive or mutually
  6542. recursive functions. However, in some cases we can arrange to use only
  6543. constant space, i.e. $O(1)$, instead of $O(n)$.
  6544. If a function call is the last action in a function body, then that
  6545. call is said to be a \emph{tail call}\index{tail call}.
  6546. For example, in the following
  6547. program, the recursive call to \code{tail-sum} is a tail call.
  6548. \begin{center}
  6549. \begin{lstlisting}
  6550. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6551. (if (eq? n 0)
  6552. r
  6553. (tail-sum (- n 1) (+ n r))))
  6554. (+ (tail-sum 5 0) 27)
  6555. \end{lstlisting}
  6556. \end{center}
  6557. At a tail call, the frame of the caller is no longer needed, so we
  6558. can pop the caller's frame before making the tail call. With this
  6559. approach, a recursive function that only makes tail calls will only
  6560. use $O(1)$ stack space. Functional languages like Racket typically
  6561. rely heavily on recursive functions, so they typically guarantee that
  6562. all tail calls will be optimized in this way.
  6563. \index{frame}
  6564. However, some care is needed with regards to argument passing in tail
  6565. calls. As mentioned above, for arguments beyond the sixth, the
  6566. convention is to use space in the caller's frame for passing
  6567. arguments. But for a tail call we pop the caller's frame and can no
  6568. longer use it. Another alternative is to use space in the callee's
  6569. frame for passing arguments. However, this option is also problematic
  6570. because the caller and callee's frame overlap in memory. As we begin
  6571. to copy the arguments from their sources in the caller's frame, the
  6572. target locations in the callee's frame might overlap with the sources
  6573. for later arguments! We solve this problem by not using the stack for
  6574. passing more than six arguments but instead using the heap, as we
  6575. describe in the Section~\ref{sec:limit-functions-r4}.
  6576. As mentioned above, for a tail call we pop the caller's frame prior to
  6577. making the tail call. The instructions for popping a frame are the
  6578. instructions that we usually place in the conclusion of a
  6579. function. Thus, we also need to place such code immediately before
  6580. each tail call. These instructions include restoring the callee-saved
  6581. registers, so it is good that the argument passing registers are all
  6582. caller-saved registers.
  6583. One last note regarding which instruction to use to make the tail
  6584. call. When the callee is finished, it should not return to the current
  6585. function, but it should return to the function that called the current
  6586. one. Thus, the return address that is already on the stack is the
  6587. right one, and we should not use \key{callq} to make the tail call, as
  6588. that would unnecessarily overwrite the return address. Instead we can
  6589. simply use the \key{jmp} instruction. Like the indirect function call,
  6590. we write an \emph{indirect jump}\index{indirect jump} with a register
  6591. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6592. jump target because the preceding conclusion overwrites just about
  6593. everything else.
  6594. \begin{lstlisting}
  6595. jmp *%rax
  6596. \end{lstlisting}
  6597. \section{Shrink $R_4$}
  6598. \label{sec:shrink-r4}
  6599. The \code{shrink} pass performs a minor modification to ease the
  6600. later passes. This pass introduces an explicit \code{main} function
  6601. and changes the top \code{ProgramDefsExp} form to
  6602. \code{ProgramDefs} as follows.
  6603. \begin{lstlisting}
  6604. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6605. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6606. \end{lstlisting}
  6607. where $\itm{mainDef}$ is
  6608. \begin{lstlisting}
  6609. (Def 'main '() 'Integer '() |$\Exp'$|)
  6610. \end{lstlisting}
  6611. \section{Reveal Functions and the $F_1$ language}
  6612. \label{sec:reveal-functions-r4}
  6613. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6614. respect: it conflates the use of function names and local
  6615. variables. This is a problem because we need to compile the use of a
  6616. function name differently than the use of a local variable; we need to
  6617. use \code{leaq} to convert the function name (a label in x86) to an
  6618. address in a register. Thus, it is a good idea to create a new pass
  6619. that changes function references from just a symbol $f$ to
  6620. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6621. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6622. \begin{figure}[tp]
  6623. \centering
  6624. \fbox{
  6625. \begin{minipage}{0.96\textwidth}
  6626. \[
  6627. \begin{array}{lcl}
  6628. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6629. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6630. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6631. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6632. &\mid& \gray{ \BOOL{\itm{bool}}
  6633. \mid \AND{\Exp}{\Exp} }\\
  6634. &\mid& \gray{ \OR{\Exp}{\Exp}
  6635. \mid \NOT{\Exp} } \\
  6636. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6637. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6638. &\mid& \gray{ \VECTOR{\Exp} } \\
  6639. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6640. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6641. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6642. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6643. &\mid& \FUNREF{\Var}\\
  6644. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6645. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6646. \end{array}
  6647. \]
  6648. \end{minipage}
  6649. }
  6650. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6651. (Figure~\ref{fig:r4-syntax}).}
  6652. \label{fig:f1-syntax}
  6653. \end{figure}
  6654. %% Distinguishing between calls in tail position and non-tail position
  6655. %% requires the pass to have some notion of context. We recommend using
  6656. %% two mutually recursive functions, one for processing expressions in
  6657. %% tail position and another for the rest.
  6658. Placing this pass after \code{uniquify} will make sure that there are
  6659. no local variables and functions that share the same name. On the
  6660. other hand, \code{reveal-functions} needs to come before the
  6661. \code{explicate-control} pass because that pass helps us compile
  6662. \code{FunRef} forms into assignment statements.
  6663. \section{Limit Functions}
  6664. \label{sec:limit-functions-r4}
  6665. Recall that we wish to limit the number of function parameters to six
  6666. so that we do not need to use the stack for argument passing, which
  6667. makes it easier to implement efficient tail calls. However, because
  6668. the input language $R_4$ supports arbitrary numbers of function
  6669. arguments, we have some work to do!
  6670. This pass transforms functions and function calls that involve more
  6671. than six arguments to pass the first five arguments as usual, but it
  6672. packs the rest of the arguments into a vector and passes it as the
  6673. sixth argument.
  6674. Each function definition with too many parameters is transformed as
  6675. follows.
  6676. \begin{lstlisting}
  6677. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6678. |$\Rightarrow$|
  6679. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6680. \end{lstlisting}
  6681. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6682. the occurences of the later parameters with vector references.
  6683. \begin{lstlisting}
  6684. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6685. \end{lstlisting}
  6686. For function calls with too many arguments, the \code{limit-functions}
  6687. pass transforms them in the following way.
  6688. \begin{tabular}{lll}
  6689. \begin{minipage}{0.2\textwidth}
  6690. \begin{lstlisting}
  6691. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6692. \end{lstlisting}
  6693. \end{minipage}
  6694. &
  6695. $\Rightarrow$
  6696. &
  6697. \begin{minipage}{0.4\textwidth}
  6698. \begin{lstlisting}
  6699. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6700. \end{lstlisting}
  6701. \end{minipage}
  6702. \end{tabular}
  6703. \section{Remove Complex Operators and Operands}
  6704. \label{sec:rco-r4}
  6705. The primary decisions to make for this pass is whether to classify
  6706. \code{FunRef} and \code{Apply} as either simple or complex
  6707. expressions. Recall that a simple expression will eventually end up as
  6708. just an ``immediate'' argument of an x86 instruction. Function
  6709. application will be translated to a sequence of instructions, so
  6710. \code{Apply} must be classified as complex expression. Regarding
  6711. \code{FunRef}, as discussed above, the function label needs to
  6712. be converted to an address using the \code{leaq} instruction. Thus,
  6713. even though \code{FunRef} seems rather simple, it needs to be
  6714. classified as a complex expression so that we generate an assignment
  6715. statement with a left-hand side that can serve as the target of the
  6716. \code{leaq}.
  6717. \section{Explicate Control and the $C_3$ language}
  6718. \label{sec:explicate-control-r4}
  6719. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6720. the concrete and abstract syntax for $C_3$, the output of
  6721. \key{explicate-control}. The three mutually recursive functions for
  6722. this pass, for assignment, tail, and predicate contexts, must all be
  6723. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6724. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6725. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6726. $C_3$. We recommend defining a new function for processing function
  6727. definitions. This code is similar to the case for \code{Program} in
  6728. $R_3$. The top-level \code{explicate-control} function that handles
  6729. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6730. to all the function definitions.
  6731. \begin{figure}[tp]
  6732. \fbox{
  6733. \begin{minipage}{0.96\textwidth}
  6734. \[
  6735. \begin{array}{lcl}
  6736. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6737. \\
  6738. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6739. \Exp &::= & \gray{ \Atm \mid (\key{read}) \mid (\key{-}\;\Atm) \mid (\key{+} \; \Atm\;\Atm)
  6740. \mid (\key{not}\;\Atm) \mid (\itm{cmp}\;\Atm\;\Atm) } \\
  6741. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6742. \mid (\key{vector-ref}\, \Atm\, \Int) } \\
  6743. &\mid& \gray{ (\key{vector-set!}\,\Atm\,\Int\,\Atm) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6744. &\mid& (\key{fun-ref}~\itm{label}) \mid (\key{call} \,\Atm\,\Atm\ldots) \\
  6745. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6746. \mid (\key{collect} \,\itm{int}) }\\
  6747. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6748. &\mid& \gray{(\key{goto}\,\itm{label})
  6749. \mid \IF{(\itm{cmp}\, \Atm\,\Atm)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6750. &\mid& (\key{tail-call}\,\Atm\,\Atm\ldots) \\
  6751. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6752. C_3 & ::= & \Def\ldots
  6753. \end{array}
  6754. \]
  6755. \end{minipage}
  6756. }
  6757. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6758. \label{fig:c3-concrete-syntax}
  6759. \end{figure}
  6760. \begin{figure}[tp]
  6761. \fbox{
  6762. \begin{minipage}{0.96\textwidth}
  6763. \small
  6764. \[
  6765. \begin{array}{lcl}
  6766. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6767. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6768. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6769. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6770. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6771. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6772. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6773. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6774. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6775. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\Atm\ldots} \\
  6776. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6777. \mid (\key{Collect} \,\itm{int}) } \\
  6778. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6779. \mid \GOTO{\itm{label}} } \\
  6780. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6781. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6782. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6783. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6784. \end{array}
  6785. \]
  6786. \end{minipage}
  6787. }
  6788. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6789. \label{fig:c3-syntax}
  6790. \end{figure}
  6791. \section{Uncover Locals}
  6792. \label{sec:uncover-locals-r4}
  6793. The function for processing $\Tail$ should be updated with a case for
  6794. \code{TailCall}. We also recommend creating a new function for
  6795. processing function definitions. Each function definition in $C_3$ has
  6796. its own set of local variables, so the code for function definitions
  6797. should be similar to the case for the \code{Program} form in $C_2$.
  6798. \section{Select Instructions and the x86$_3$ Language}
  6799. \label{sec:select-r4}
  6800. \index{instruction selection}
  6801. The output of select instructions is a program in the x86$_3$
  6802. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6803. \index{x86}
  6804. \begin{figure}[tp]
  6805. \fbox{
  6806. \begin{minipage}{0.96\textwidth}
  6807. \[
  6808. \begin{array}{lcl}
  6809. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6810. \mid (\key{deref}\,\Reg\,\Int) } \\
  6811. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6812. \mid (\key{global}\; \itm{name}) }
  6813. \mid (\key{fun-ref}\; \itm{label})\\
  6814. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6815. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6816. (\key{subq} \; \Arg\; \Arg) \mid
  6817. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6818. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6819. (\key{pushq}\;\Arg) \mid
  6820. (\key{popq}\;\Arg) \mid
  6821. (\key{retq}) } \\
  6822. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6823. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6824. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6825. \mid (\key{jmp} \; \itm{label})
  6826. \mid (\key{j}\itm{cc} \; \itm{label})
  6827. \mid (\key{label} \; \itm{label}) } \\
  6828. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6829. &\mid& (\key{leaq}\;\Arg\;\Reg)\\
  6830. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6831. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6832. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6833. \end{array}
  6834. \]
  6835. \end{minipage}
  6836. }
  6837. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6838. \label{fig:x86-3-concrete}
  6839. \end{figure}
  6840. \begin{figure}[tp]
  6841. \fbox{
  6842. \begin{minipage}{0.96\textwidth}
  6843. \small
  6844. \[
  6845. \begin{array}{lcl}
  6846. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6847. \mid \BYTEREG{\Reg} } \\
  6848. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6849. \Instr &::=& \ldots \mid \INDCALLQ{\itm{label}}{\itm{int}}
  6850. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6851. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6852. \Def &::= & \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Block)\ldots)} \\
  6853. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6854. \end{array}
  6855. \]
  6856. \end{minipage}
  6857. }
  6858. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6859. \label{fig:x86-3}
  6860. \end{figure}
  6861. An assignment of a function reference to a variable becomes a
  6862. load-effective-address instruction as follows: \\
  6863. \begin{tabular}{lcl}
  6864. \begin{minipage}{0.35\textwidth}
  6865. \begin{lstlisting}
  6866. |$\itm{lhs}$| = (fun-ref |$f$|);
  6867. \end{lstlisting}
  6868. \end{minipage}
  6869. &
  6870. $\Rightarrow$\qquad\qquad
  6871. &
  6872. \begin{minipage}{0.3\textwidth}
  6873. \begin{lstlisting}
  6874. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  6875. \end{lstlisting}
  6876. \end{minipage}
  6877. \end{tabular} \\
  6878. Regarding function definitions, we need to remove the parameters and
  6879. instead perform parameter passing using the conventions discussed in
  6880. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  6881. registers. We recommend turning the parameters into local variables
  6882. and generating instructions at the beginning of the function to move
  6883. from the argument passing registers to these local variables.
  6884. \begin{lstlisting}
  6885. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6886. |$\Rightarrow$|
  6887. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6888. \end{lstlisting}
  6889. The $G'$ control-flow graph is the same as $G$ except that the
  6890. \code{start} block is modified to add the instructions for moving from
  6891. the argument registers to the parameter variables. So the \code{start}
  6892. block of $G$ shown on the left is changed to the code on the right.
  6893. \begin{center}
  6894. \begin{minipage}{0.3\textwidth}
  6895. \begin{lstlisting}
  6896. start:
  6897. |$\itm{instr}_1$|
  6898. |$\vdots$|
  6899. |$\itm{instr}_n$|
  6900. \end{lstlisting}
  6901. \end{minipage}
  6902. $\Rightarrow$
  6903. \begin{minipage}{0.3\textwidth}
  6904. \begin{lstlisting}
  6905. start:
  6906. movq %rdi, |$x_1$|
  6907. movq %rsi, |$x_2$|
  6908. |$\vdots$|
  6909. |$\itm{instr}_1$|
  6910. |$\vdots$|
  6911. |$\itm{instr}_n$|
  6912. \end{lstlisting}
  6913. \end{minipage}
  6914. \end{center}
  6915. By changing the parameters to local variables, we are giving the
  6916. register allocator control over which registers or stack locations to
  6917. use for them. If you implemented the move-biasing challenge
  6918. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6919. assign the parameter variables to the corresponding argument register,
  6920. in which case the \code{patch-instructions} pass will remove the
  6921. \code{movq} instruction. This happens in the example translation in
  6922. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  6923. the \code{add} function.
  6924. %
  6925. Also, note that the register allocator will perform liveness analysis
  6926. on this sequence of move instructions and build the interference
  6927. graph. So, for example, $x_1$ will be marked as interfering with
  6928. \code{rsi} and that will prevent the assignment of $x_1$ to
  6929. \code{rsi}, which is good, because that would overwrite the argument
  6930. that needs to move into $x_2$.
  6931. Next, consider the compilation of function calls. In the mirror image
  6932. of handling the parameters of function definitions, the arguments need
  6933. to be moved to the argument passing registers. The function call
  6934. itself is performed with an indirect function call. The return value
  6935. from the function is stored in \code{rax}, so it needs to be moved
  6936. into the \itm{lhs}.
  6937. \begin{lstlisting}
  6938. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  6939. |$\Rightarrow$|
  6940. movq |$\itm{arg}_1$|, %rdi
  6941. movq |$\itm{arg}_2$|, %rsi
  6942. |$\vdots$|
  6943. callq *|\itm{fun}|
  6944. movq %rax, |\itm{lhs}|
  6945. \end{lstlisting}
  6946. Regarding tail calls, the parameter passing is the same as non-tail
  6947. calls: generate instructions to move the arguments into to the
  6948. argument passing registers. After that we need to pop the frame from
  6949. the procedure call stack. However, we do not yet know how big the
  6950. frame is; that gets determined during register allocation. So instead
  6951. of generating those instructions here, we invent a new instruction
  6952. that means ``pop the frame and then do an indirect jump'', which we
  6953. name \code{TailJmp}. The abstract syntax for this instruction includes
  6954. an argument that specifies where to jump and an integer that
  6955. represents the arity of the function being called.
  6956. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6957. using the label \code{start} for the initial block of a program, and
  6958. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6959. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  6960. can be compiled to an assignment to \code{rax} followed by a jump to
  6961. \code{conclusion}. With the addition of function definitions, we will
  6962. have a starting block and conclusion for each function, but their
  6963. labels need to be unique. We recommend prepending the function's name
  6964. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6965. labels. (Alternatively, one could \code{gensym} labels for the start
  6966. and conclusion and store them in the $\itm{info}$ field of the
  6967. function definition.)
  6968. \section{Uncover Live}
  6969. %% The rest of the passes need only minor modifications to handle the new
  6970. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6971. %% \code{leaq}.
  6972. The \code{IndirectCallq} instruction should be treated like
  6973. \code{Callq} regarding its written locations $W$, in that they should
  6974. include all the caller-saved registers. Recall that the reason for
  6975. that is to force call-live variables to be assigned to callee-saved
  6976. registers or to be spilled to the stack.
  6977. \section{Build Interference Graph}
  6978. With the addition of function definitions, we compute an interference
  6979. graph for each function (not just one for the whole program).
  6980. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6981. spill vector-typed variables that are live during a call to the
  6982. \code{collect}. With the addition of functions to our language, we
  6983. need to revisit this issue. Many functions perform allocation and
  6984. therefore have calls to the collector inside of them. Thus, we should
  6985. not only spill a vector-typed variable when it is live during a call
  6986. to \code{collect}, but we should spill the variable if it is live
  6987. during any function call. Thus, in the \code{build-interference} pass,
  6988. we recommend adding interference edges between call-live vector-typed
  6989. variables and the callee-saved registers (in addition to the usual
  6990. addition of edges between call-live variables and the caller-saved
  6991. registers).
  6992. \section{Patch Instructions}
  6993. In \code{patch-instructions}, you should deal with the x86
  6994. idiosyncrasy that the destination argument of \code{leaq} must be a
  6995. register. Additionally, you should ensure that the argument of
  6996. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  6997. code generation more convenient, because we trample many registers
  6998. before the tail call (as explained in the next section).
  6999. \section{Print x86}
  7000. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7001. \code{IndirectCallq} are straightforward: output their concrete
  7002. syntax.
  7003. \begin{lstlisting}
  7004. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7005. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7006. \end{lstlisting}
  7007. The \code{TailJmp} node requires a bit work. A straightforward
  7008. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7009. before the jump we need to pop the current frame. This sequence of
  7010. instructions is the same as the code for the conclusion of a function,
  7011. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7012. Note that your \code{print-x86} pass needs to add the code for saving
  7013. and restoring callee-saved registers, if you have not already
  7014. implemented that. This is necessary when generating code for function
  7015. definitions.
  7016. \begin{exercise}\normalfont
  7017. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7018. Create 5 new programs that use functions, including examples that pass
  7019. functions and return functions from other functions and including
  7020. recursive functions. Test your compiler on these new programs and all
  7021. of your previously created test programs.
  7022. \end{exercise}
  7023. \begin{figure}[tbp]
  7024. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7025. \node (R4) at (0,2) {\large $R_4$};
  7026. \node (R4-2) at (3,2) {\large $R_4$};
  7027. \node (R4-3) at (6,2) {\large $R_4$};
  7028. \node (F1-1) at (12,0) {\large $F_1$};
  7029. \node (F1-2) at (9,0) {\large $F_1$};
  7030. \node (F1-3) at (6,0) {\large $F_1$};
  7031. \node (F1-4) at (3,0) {\large $F_1$};
  7032. \node (C3-1) at (6,-2) {\large $C_3$};
  7033. \node (C3-2) at (3,-2) {\large $C_3$};
  7034. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7035. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7036. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7037. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7038. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7039. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7040. \path[->,bend left=15] (R4) edge [above] node
  7041. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7042. \path[->,bend left=15] (R4-2) edge [above] node
  7043. {\ttfamily\footnotesize uniquify} (R4-3);
  7044. \path[->,bend left=15] (R4-3) edge [right] node
  7045. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7046. \path[->,bend left=15] (F1-1) edge [below] node
  7047. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7048. \path[->,bend right=15] (F1-2) edge [above] node
  7049. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7050. \path[->,bend right=15] (F1-3) edge [above] node
  7051. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7052. \path[->,bend left=15] (F1-4) edge [right] node
  7053. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7054. \path[->,bend left=15] (C3-1) edge [below] node
  7055. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7056. \path[->,bend right=15] (C3-2) edge [left] node
  7057. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7058. \path[->,bend left=15] (x86-2) edge [left] node
  7059. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7060. \path[->,bend right=15] (x86-2-1) edge [below] node
  7061. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7062. \path[->,bend right=15] (x86-2-2) edge [left] node
  7063. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7064. \path[->,bend left=15] (x86-3) edge [above] node
  7065. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7066. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7067. \end{tikzpicture}
  7068. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7069. \label{fig:R4-passes}
  7070. \end{figure}
  7071. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7072. compiling $R_4$ to x86.
  7073. \section{An Example Translation}
  7074. \label{sec:functions-example}
  7075. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7076. function in $R_4$ to x86. The figure also includes the results of the
  7077. \code{explicate-control} and \code{select-instructions} passes.
  7078. \begin{figure}[htbp]
  7079. \begin{tabular}{ll}
  7080. \begin{minipage}{0.5\textwidth}
  7081. % s3_2.rkt
  7082. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7083. (define (add [x : Integer] [y : Integer])
  7084. : Integer
  7085. (+ x y))
  7086. (add 40 2)
  7087. \end{lstlisting}
  7088. $\Downarrow$
  7089. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7090. (define (add86 [x87 : Integer]
  7091. [y88 : Integer]) : Integer
  7092. add86start:
  7093. return (+ x87 y88);
  7094. )
  7095. (define (main) : Integer ()
  7096. mainstart:
  7097. tmp89 = (fun-ref add86);
  7098. (tail-call tmp89 40 2)
  7099. )
  7100. \end{lstlisting}
  7101. \end{minipage}
  7102. &
  7103. $\Rightarrow$
  7104. \begin{minipage}{0.5\textwidth}
  7105. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7106. (define (add86) : Integer
  7107. add86start:
  7108. movq %rdi, x87
  7109. movq %rsi, y88
  7110. movq x87, %rax
  7111. addq y88, %rax
  7112. jmp add11389conclusion
  7113. )
  7114. (define (main) : Integer
  7115. mainstart:
  7116. leaq (fun-ref add86), tmp89
  7117. movq $40, %rdi
  7118. movq $2, %rsi
  7119. tail-jmp tmp89
  7120. )
  7121. \end{lstlisting}
  7122. $\Downarrow$
  7123. \end{minipage}
  7124. \end{tabular}
  7125. \begin{tabular}{ll}
  7126. \begin{minipage}{0.3\textwidth}
  7127. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7128. .globl add86
  7129. .align 16
  7130. add86:
  7131. pushq %rbp
  7132. movq %rsp, %rbp
  7133. jmp add86start
  7134. add86start:
  7135. movq %rdi, %rax
  7136. addq %rsi, %rax
  7137. jmp add86conclusion
  7138. add86conclusion:
  7139. popq %rbp
  7140. retq
  7141. \end{lstlisting}
  7142. \end{minipage}
  7143. &
  7144. \begin{minipage}{0.5\textwidth}
  7145. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7146. .globl main
  7147. .align 16
  7148. main:
  7149. pushq %rbp
  7150. movq %rsp, %rbp
  7151. movq $16384, %rdi
  7152. movq $16384, %rsi
  7153. callq initialize
  7154. movq rootstack_begin(%rip), %r15
  7155. jmp mainstart
  7156. mainstart:
  7157. leaq add86(%rip), %rcx
  7158. movq $40, %rdi
  7159. movq $2, %rsi
  7160. movq %rcx, %rax
  7161. popq %rbp
  7162. jmp *%rax
  7163. mainconclusion:
  7164. popq %rbp
  7165. retq
  7166. \end{lstlisting}
  7167. \end{minipage}
  7168. \end{tabular}
  7169. \caption{Example compilation of a simple function to x86.}
  7170. \label{fig:add-fun}
  7171. \end{figure}
  7172. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7173. \chapter{Lexically Scoped Functions}
  7174. \label{ch:lambdas}
  7175. \index{lambda}
  7176. \index{lexical scoping}
  7177. This chapter studies lexically scoped functions as they appear in
  7178. functional languages such as Racket. By lexical scoping we mean that a
  7179. function's body may refer to variables whose binding site is outside
  7180. of the function, in an enclosing scope.
  7181. %
  7182. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7183. $R_5$, which extends $R_4$ with anonymous functions using the
  7184. \key{lambda} form. The body of the \key{lambda}, refers to three
  7185. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7186. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7187. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7188. parameter of function \code{f}. The \key{lambda} is returned from the
  7189. function \code{f}. The main expression of the program includes two
  7190. calls to \code{f} with different arguments for \code{x}, first
  7191. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7192. to variables \code{g} and \code{h}. Even though these two functions
  7193. were created by the same \code{lambda}, they are really different
  7194. functions because they use different values for \code{x}. Applying
  7195. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7196. \code{15} produces \code{22}. The result of this program is \code{42}.
  7197. \begin{figure}[btp]
  7198. % s4_6.rkt
  7199. \begin{lstlisting}
  7200. (define (f [x : Integer]) : (Integer -> Integer)
  7201. (let ([y 4])
  7202. (lambda: ([z : Integer]) : Integer
  7203. (+ x (+ y z)))))
  7204. (let ([g (f 5)])
  7205. (let ([h (f 3)])
  7206. (+ (g 11) (h 15))))
  7207. \end{lstlisting}
  7208. \caption{Example of a lexically scoped function.}
  7209. \label{fig:lexical-scoping}
  7210. \end{figure}
  7211. The approach that we take for implementing lexically scoped
  7212. functions is to compile them into top-level function definitions,
  7213. translating from $R_5$ into $R_4$. However, the compiler will need to
  7214. provide special treatment for variable occurrences such as \code{x}
  7215. and \code{y} in the body of the \code{lambda} of
  7216. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7217. refer to variables defined outside of it. To identify such variable
  7218. occurrences, we review the standard notion of free variable.
  7219. \begin{definition}
  7220. A variable is \emph{free in expression} $e$ if the variable occurs
  7221. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7222. variable}
  7223. \end{definition}
  7224. For example, in the expression \code{(+ x (+ y z))} the variables
  7225. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7226. only \code{x} and \code{y} are free in the following expression
  7227. because \code{z} is bound by the \code{lambda}.
  7228. \begin{lstlisting}
  7229. (lambda: ([z : Integer]) : Integer
  7230. (+ x (+ y z)))
  7231. \end{lstlisting}
  7232. So the free variables of a \code{lambda} are the ones that will need
  7233. special treatment. We need to arrange for some way to transport, at
  7234. runtime, the values of those variables from the point where the
  7235. \code{lambda} was created to the point where the \code{lambda} is
  7236. applied. An efficient solution to the problem, due to
  7237. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7238. free variables together with the function pointer for the lambda's
  7239. code, an arrangement called a \emph{flat closure} (which we shorten to
  7240. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7241. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7242. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7243. pointers. The function pointer resides at index $0$ and the
  7244. values for the free variables will fill in the rest of the vector.
  7245. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7246. how closures work. It's a three-step dance. The program first calls
  7247. function \code{f}, which creates a closure for the \code{lambda}. The
  7248. closure is a vector whose first element is a pointer to the top-level
  7249. function that we will generate for the \code{lambda}, the second
  7250. element is the value of \code{x}, which is \code{5}, and the third
  7251. element is \code{4}, the value of \code{y}. The closure does not
  7252. contain an element for \code{z} because \code{z} is not a free
  7253. variable of the \code{lambda}. Creating the closure is step 1 of the
  7254. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7255. shown in Figure~\ref{fig:closures}.
  7256. %
  7257. The second call to \code{f} creates another closure, this time with
  7258. \code{3} in the second slot (for \code{x}). This closure is also
  7259. returned from \code{f} but bound to \code{h}, which is also shown in
  7260. Figure~\ref{fig:closures}.
  7261. \begin{figure}[tbp]
  7262. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7263. \caption{Example closure representation for the \key{lambda}'s
  7264. in Figure~\ref{fig:lexical-scoping}.}
  7265. \label{fig:closures}
  7266. \end{figure}
  7267. Continuing with the example, consider the application of \code{g} to
  7268. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7269. obtain the function pointer in the first element of the closure and
  7270. call it, passing in the closure itself and then the regular arguments,
  7271. in this case \code{11}. This technique for applying a closure is step
  7272. 2 of the dance.
  7273. %
  7274. But doesn't this \code{lambda} only take 1 argument, for parameter
  7275. \code{z}? The third and final step of the dance is generating a
  7276. top-level function for a \code{lambda}. We add an additional
  7277. parameter for the closure and we insert a \code{let} at the beginning
  7278. of the function for each free variable, to bind those variables to the
  7279. appropriate elements from the closure parameter.
  7280. %
  7281. This three-step dance is known as \emph{closure conversion}. We
  7282. discuss the details of closure conversion in
  7283. Section~\ref{sec:closure-conversion} and the code generated from the
  7284. example in Section~\ref{sec:example-lambda}. But first we define the
  7285. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7286. \section{The $R_5$ Language}
  7287. \label{sec:r5}
  7288. The concrete and abstract syntax for $R_5$, a language with anonymous
  7289. functions and lexical scoping, is defined in
  7290. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7291. the \key{lambda} form to the grammar for $R_4$, which already has
  7292. syntax for function application.
  7293. \begin{figure}[tp]
  7294. \centering
  7295. \fbox{
  7296. \begin{minipage}{0.96\textwidth}
  7297. \small
  7298. \[
  7299. \begin{array}{lcl}
  7300. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7301. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7302. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7303. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7304. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7305. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  7306. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7307. \mid (\key{and}\;\Exp\;\Exp)
  7308. \mid (\key{or}\;\Exp\;\Exp)
  7309. \mid (\key{not}\;\Exp) } \\
  7310. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7311. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7312. (\key{vector-ref}\;\Exp\;\Int)} \\
  7313. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7314. \mid (\Exp \; \Exp\ldots) } \\
  7315. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  7316. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7317. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7318. \end{array}
  7319. \]
  7320. \end{minipage}
  7321. }
  7322. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7323. with \key{lambda}.}
  7324. \label{fig:r5-concrete-syntax}
  7325. \end{figure}
  7326. \begin{figure}[tp]
  7327. \centering
  7328. \fbox{
  7329. \begin{minipage}{0.96\textwidth}
  7330. \small
  7331. \[
  7332. \begin{array}{lcl}
  7333. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  7334. &\mid& \gray{ \ADD{\Exp}{\Exp}
  7335. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  7336. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7337. &\mid& \gray{ \BOOL{\itm{bool}}
  7338. \mid \AND{\Exp}{\Exp} }\\
  7339. &\mid& \gray{ \OR{\Exp}{\Exp}
  7340. \mid \NOT{\Exp} } \\
  7341. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  7342. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7343. &\mid& \gray{ \VECTOR{\Exp} } \\
  7344. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  7345. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  7346. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7347. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7348. &\mid& \LAMBDA{[\Var\code{:}\Type]\ldots}{\Type}{\Exp}\\
  7349. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7350. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp} }
  7351. \end{array}
  7352. \]
  7353. \end{minipage}
  7354. }
  7355. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7356. \label{fig:r5-syntax}
  7357. \end{figure}
  7358. \index{interpreter}
  7359. \label{sec:interp-R5}
  7360. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7361. $R_5$. The clause for \key{lambda} saves the current environment
  7362. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7363. the environment from the \key{lambda}, the \code{lam-env}, when
  7364. interpreting the body of the \key{lambda}. The \code{lam-env}
  7365. environment is extended with the mapping of parameters to argument
  7366. values.
  7367. \begin{figure}[tbp]
  7368. \begin{lstlisting}
  7369. (define (interp-exp env)
  7370. (lambda (e)
  7371. (define recur (interp-exp env))
  7372. (match e
  7373. ...
  7374. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7375. `(lambda ,xs ,body ,env)]
  7376. [(Apply fun args)
  7377. (define fun-val ((interp-exp env) fun))
  7378. (define arg-vals (map (interp-exp env) args))
  7379. (match fun-val
  7380. [`(lambda ,xs ,body ,lam-env)
  7381. (define new-env (append (map cons xs arg-vals) lam-env))
  7382. ((interp-exp new-env) body)]
  7383. [else (error "interp-exp, expected function, not" fun-val)])]
  7384. [else (error 'interp-exp "unrecognized expression")]
  7385. )))
  7386. \end{lstlisting}
  7387. \caption{Interpreter for $R_5$.}
  7388. \label{fig:interp-R5}
  7389. \end{figure}
  7390. \label{sec:type-check-r5}
  7391. \index{type checking}
  7392. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7393. \key{lambda} form. The body of the \key{lambda} is checked in an
  7394. environment that includes the current environment (because it is
  7395. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7396. require the body's type to match the declared return type.
  7397. \begin{figure}[tbp]
  7398. \begin{lstlisting}
  7399. (define (type-check-R5 env)
  7400. (lambda (e)
  7401. (match e
  7402. [(Lambda (and bnd `([,xs : ,Ts] ...)) rT body)
  7403. (define-values (new-body bodyT)
  7404. ((type-check-exp (append (map cons xs Ts) env)) body))
  7405. (define ty `(,@Ts -> ,rT))
  7406. (cond
  7407. [(equal? rT bodyT)
  7408. (values (HasType (Lambda bnd rT new-body) ty) ty)]
  7409. [else
  7410. (error "mismatch in return type" bodyT rT)])]
  7411. ...
  7412. )))
  7413. \end{lstlisting}
  7414. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7415. \label{fig:type-check-R5}
  7416. \end{figure}
  7417. \section{Closure Conversion}
  7418. \label{sec:closure-conversion}
  7419. \index{closure conversion}
  7420. The compiling of lexically-scoped functions into top-level function
  7421. definitions is accomplished in the pass \code{convert-to-closures}
  7422. that comes after \code{reveal-functions} and before
  7423. \code{limit-functions}.
  7424. As usual, we implement the pass as a recursive function over the
  7425. AST. All of the action is in the clauses for \key{lambda} and
  7426. \key{Apply}. We transform a \key{lambda} expression into an expression
  7427. that creates a closure, that is, creates a vector whose first element
  7428. is a function pointer and the rest of the elements are the free
  7429. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7430. generated to identify the function.
  7431. \begin{tabular}{lll}
  7432. \begin{minipage}{0.4\textwidth}
  7433. \begin{lstlisting}
  7434. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7435. \end{lstlisting}
  7436. \end{minipage}
  7437. &
  7438. $\Rightarrow$
  7439. &
  7440. \begin{minipage}{0.4\textwidth}
  7441. \begin{lstlisting}
  7442. (vector |\itm{name}| |\itm{fvs}| ...)
  7443. \end{lstlisting}
  7444. \end{minipage}
  7445. \end{tabular} \\
  7446. %
  7447. In addition to transforming each \key{lambda} into a \key{vector}, we
  7448. must create a top-level function definition for each \key{lambda}, as
  7449. shown below.\\
  7450. \begin{minipage}{0.8\textwidth}
  7451. \begin{lstlisting}
  7452. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7453. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7454. ...
  7455. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7456. |\itm{body'}|)...))
  7457. \end{lstlisting}
  7458. \end{minipage}\\
  7459. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7460. parameters are the normal parameters of the \key{lambda}. The types
  7461. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7462. underscore is a dummy type because it is rather difficult to give a
  7463. type to the function in the closure's type, and it does not matter.
  7464. The sequence of \key{let} forms bind the free variables to their
  7465. values obtained from the closure.
  7466. We transform function application into code that retrieves the
  7467. function pointer from the closure and then calls the function, passing
  7468. in the closure as the first argument. We bind $e'$ to a temporary
  7469. variable to avoid code duplication.
  7470. \begin{tabular}{lll}
  7471. \begin{minipage}{0.3\textwidth}
  7472. \begin{lstlisting}
  7473. (app |$e$| |\itm{es}| ...)
  7474. \end{lstlisting}
  7475. \end{minipage}
  7476. &
  7477. $\Rightarrow$
  7478. &
  7479. \begin{minipage}{0.5\textwidth}
  7480. \begin{lstlisting}
  7481. (let ([|\itm{tmp}| |$e'$|])
  7482. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7483. \end{lstlisting}
  7484. \end{minipage}
  7485. \end{tabular} \\
  7486. There is also the question of what to do with top-level function
  7487. definitions. To maintain a uniform translation of function
  7488. application, we turn function references into closures.
  7489. \begin{tabular}{lll}
  7490. \begin{minipage}{0.3\textwidth}
  7491. \begin{lstlisting}
  7492. (fun-ref |$f$|)
  7493. \end{lstlisting}
  7494. \end{minipage}
  7495. &
  7496. $\Rightarrow$
  7497. &
  7498. \begin{minipage}{0.5\textwidth}
  7499. \begin{lstlisting}
  7500. (vector (fun-ref |$f$|))
  7501. \end{lstlisting}
  7502. \end{minipage}
  7503. \end{tabular} \\
  7504. %
  7505. The top-level function definitions need to be updated as well to take
  7506. an extra closure parameter.
  7507. \section{An Example Translation}
  7508. \label{sec:example-lambda}
  7509. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7510. conversion for the example program demonstrating lexical scoping that
  7511. we discussed at the beginning of this chapter.
  7512. \begin{figure}[h]
  7513. \begin{minipage}{0.8\textwidth}
  7514. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7515. (program
  7516. (define (f [x : Integer]) : (Integer -> Integer)
  7517. (let ([y 4])
  7518. (lambda: ([z : Integer]) : Integer
  7519. (+ x (+ y z)))))
  7520. (let ([g (f 5)])
  7521. (let ([h (f 3)])
  7522. (+ (g 11) (h 15)))))
  7523. \end{lstlisting}
  7524. $\Downarrow$
  7525. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7526. (program (type Integer)
  7527. (define (f (x : Integer)) : (Integer -> Integer)
  7528. (let ((y 4))
  7529. (lambda: ((z : Integer)) : Integer
  7530. (+ x (+ y z)))))
  7531. (let ((g (app (fun-ref f) 5)))
  7532. (let ((h (app (fun-ref f) 3)))
  7533. (+ (app g 11) (app h 15)))))
  7534. \end{lstlisting}
  7535. $\Downarrow$
  7536. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7537. (program (type Integer)
  7538. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7539. (let ((y 4))
  7540. (vector (fun-ref lam.1) x y)))
  7541. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7542. (let ((x (vector-ref clos.2 1)))
  7543. (let ((y (vector-ref clos.2 2)))
  7544. (+ x (+ y z)))))
  7545. (let ((g (let ((t.1 (vector (fun-ref f))))
  7546. (app (vector-ref t.1 0) t.1 5))))
  7547. (let ((h (let ((t.2 (vector (fun-ref f))))
  7548. (app (vector-ref t.2 0) t.2 3))))
  7549. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7550. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7551. \end{lstlisting}
  7552. \end{minipage}
  7553. \caption{Example of closure conversion.}
  7554. \label{fig:lexical-functions-example}
  7555. \end{figure}
  7556. \begin{figure}[p]
  7557. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7558. \node (R4) at (0,2) {\large $R_4$};
  7559. \node (R4-2) at (3,2) {\large $R_4$};
  7560. \node (R4-3) at (6,2) {\large $R_4$};
  7561. \node (F1-1) at (12,0) {\large $F_1$};
  7562. \node (F1-2) at (9,0) {\large $F_1$};
  7563. \node (F1-3) at (6,0) {\large $F_1$};
  7564. \node (F1-4) at (3,0) {\large $F_1$};
  7565. \node (F1-5) at (0,0) {\large $F_1$};
  7566. \node (C3-1) at (6,-2) {\large $C_3$};
  7567. \node (C3-2) at (3,-2) {\large $C_3$};
  7568. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7569. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7570. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7571. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7572. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7573. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7574. \path[->,bend left=15] (R4) edge [above] node
  7575. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7576. \path[->,bend left=15] (R4-2) edge [above] node
  7577. {\ttfamily\footnotesize uniquify} (R4-3);
  7578. \path[->] (R4-3) edge [right] node
  7579. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7580. \path[->,bend left=15] (F1-1) edge [below] node
  7581. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7582. \path[->,bend right=15] (F1-2) edge [above] node
  7583. {\ttfamily\footnotesize limit-functions} (F1-3);
  7584. \path[->,bend right=15] (F1-3) edge [above] node
  7585. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7586. \path[->,bend right=15] (F1-4) edge [above] node
  7587. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7588. \path[->] (F1-5) edge [left] node
  7589. {\ttfamily\footnotesize explicate-control} (C3-1);
  7590. \path[->,bend left=15] (C3-1) edge [below] node
  7591. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7592. \path[->,bend right=15] (C3-2) edge [left] node
  7593. {\ttfamily\footnotesize select-instr.} (x86-2);
  7594. \path[->,bend left=15] (x86-2) edge [left] node
  7595. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7596. \path[->,bend right=15] (x86-2-1) edge [below] node
  7597. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7598. \path[->,bend right=15] (x86-2-2) edge [left] node
  7599. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7600. \path[->,bend left=15] (x86-3) edge [above] node
  7601. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7602. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7603. \end{tikzpicture}
  7604. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7605. functions.}
  7606. \label{fig:R5-passes}
  7607. \end{figure}
  7608. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7609. for the compilation of $R_5$.
  7610. \begin{exercise}\normalfont
  7611. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7612. Create 5 new programs that use \key{lambda} functions and make use of
  7613. lexical scoping. Test your compiler on these new programs and all of
  7614. your previously created test programs.
  7615. \end{exercise}
  7616. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7617. \chapter{Dynamic Typing}
  7618. \label{ch:type-dynamic}
  7619. \index{dynamic typing}
  7620. In this chapter we discuss the compilation of a dynamically typed
  7621. language, named $R_7$, that is a subset of the Racket
  7622. language. (Recall that in the previous chapters we have studied
  7623. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7624. languages, an expression may produce values of differing
  7625. type. Consider the following example with a conditional expression
  7626. that may return a Boolean or an integer depending on the input to the
  7627. program.
  7628. \begin{lstlisting}
  7629. (not (if (eq? (read) 1) #f 0))
  7630. \end{lstlisting}
  7631. Languages that allow expressions to produce different kinds of values
  7632. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7633. such as subtype polymorphism and parametric
  7634. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7635. talking about here does not have a special name, but it is the usual
  7636. kind that arises in dynamically typed languages.
  7637. Another characteristic of dynamically typed languages is that
  7638. primitive operations, such as \code{not}, are often defined to operate
  7639. on many different types of values. In fact, in Racket, the \code{not}
  7640. operator produces a result for any kind of value: given \code{\#f} it
  7641. returns \code{\#t} and given anything else it returns \code{\#f}.
  7642. Furthermore, even when primitive operations restrict their inputs to
  7643. values of a certain type, this restriction is enforced at runtime
  7644. instead of during compilation. For example, the following vector
  7645. reference results in a run-time contract violation.
  7646. \begin{lstlisting}
  7647. (vector-ref (vector 42) #t)
  7648. \end{lstlisting}
  7649. \begin{figure}[tp]
  7650. \centering
  7651. \fbox{
  7652. \begin{minipage}{0.97\textwidth}
  7653. \[
  7654. \begin{array}{rcl}
  7655. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7656. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7657. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7658. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7659. &\mid& \key{\#t} \mid \key{\#f}
  7660. \mid (\key{and}\;\Exp\;\Exp)
  7661. \mid (\key{or}\;\Exp\;\Exp)
  7662. \mid (\key{not}\;\Exp) \\
  7663. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7664. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7665. (\key{vector-ref}\;\Exp\;\Exp) \\
  7666. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7667. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7668. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7669. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7670. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7671. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7672. \end{array}
  7673. \]
  7674. \end{minipage}
  7675. }
  7676. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7677. \label{fig:r7-syntax}
  7678. \end{figure}
  7679. The syntax of $R_7$, our subset of Racket, is defined in
  7680. Figure~\ref{fig:r7-syntax}.
  7681. %
  7682. The definitional interpreter for $R_7$ is given in
  7683. Figure~\ref{fig:interp-R7}.
  7684. \begin{figure}[tbp]
  7685. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7686. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7687. (define (valid-op? op) (member op '(+ - and or not)))
  7688. (define (interp-r7 env)
  7689. (lambda (ast)
  7690. (define recur (interp-r7 env))
  7691. (match ast
  7692. [(? symbol?) (lookup ast env)]
  7693. [(? integer?) `(inject ,ast Integer)]
  7694. [#t `(inject #t Boolean)]
  7695. [#f `(inject #f Boolean)]
  7696. [`(read) `(inject ,(read-fixnum) Integer)]
  7697. [`(lambda (,xs ...) ,body)
  7698. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7699. [`(define (,f ,xs ...) ,body)
  7700. (mcons f `(lambda ,xs ,body))]
  7701. [`(program ,ds ... ,body)
  7702. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7703. (for/list ([b top-level])
  7704. (set-mcdr! b (match (mcdr b)
  7705. [`(lambda ,xs ,body)
  7706. `(inject (lambda ,xs ,body ,top-level)
  7707. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7708. ((interp-r7 top-level) body))]
  7709. [`(vector ,(app recur elts) ...)
  7710. (define tys (map get-tagged-type elts))
  7711. `(inject ,(apply vector elts) (Vector ,@tys))]
  7712. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7713. (match v1
  7714. [`(inject ,vec ,ty)
  7715. (vector-set! vec n v2)
  7716. `(inject (void) Void)])]
  7717. [`(vector-ref ,(app recur v) ,n)
  7718. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7719. [`(let ([,x ,(app recur v)]) ,body)
  7720. ((interp-r7 (cons (cons x v) env)) body)]
  7721. [`(,op ,es ...) #:when (valid-op? op)
  7722. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7723. [`(eq? ,(app recur l) ,(app recur r))
  7724. `(inject ,(equal? l r) Boolean)]
  7725. [`(if ,(app recur q) ,t ,f)
  7726. (match q
  7727. [`(inject #f Boolean) (recur f)]
  7728. [else (recur t)])]
  7729. [`(,(app recur f-val) ,(app recur vs) ...)
  7730. (match f-val
  7731. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7732. (define new-env (append (map cons xs vs) lam-env))
  7733. ((interp-r7 new-env) body)]
  7734. [else (error "interp-r7, expected function, not" f-val)])])))
  7735. \end{lstlisting}
  7736. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7737. \label{fig:interp-R7}
  7738. \end{figure}
  7739. Let us consider how we might compile $R_7$ to x86, thinking about the
  7740. first example above. Our bit-level representation of the Boolean
  7741. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7742. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7743. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7744. general, cannot be determined at compile time, but depends on the
  7745. runtime type of its input, as in the example above that depends on the
  7746. result of \code{(read)}.
  7747. The way around this problem is to include information about a value's
  7748. runtime type in the value itself, so that this information can be
  7749. inspected by operators such as \code{not}. In particular, we
  7750. steal the 3 right-most bits from our 64-bit values to encode the
  7751. runtime type. We use $001$ to identify integers, $100$ for
  7752. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7753. void value. We refer to these 3 bits as the \emph{tag} and we
  7754. define the following auxiliary function.
  7755. \begin{align*}
  7756. \itm{tagof}(\key{Integer}) &= 001 \\
  7757. \itm{tagof}(\key{Boolean}) &= 100 \\
  7758. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7759. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7760. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7761. \itm{tagof}(\key{Void}) &= 101
  7762. \end{align*}
  7763. (We say more about the new \key{Vectorof} type shortly.)
  7764. This stealing of 3 bits comes at some
  7765. price: our integers are reduced to ranging from $-2^{60}$ to
  7766. $2^{60}$. The stealing does not adversely affect vectors and
  7767. procedures because those values are addresses, and our addresses are
  7768. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7769. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7770. bits with the tag and we can simply zero-out the tag to recover the
  7771. original address.
  7772. In some sense, these tagged values are a new kind of value. Indeed,
  7773. we can extend our \emph{typed} language with tagged values by adding a
  7774. new type to classify them, called \key{Any}, and with operations for
  7775. creating and using tagged values, yielding the $R_6$ language that we
  7776. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7777. fundamental support for polymorphism and runtime types that we need to
  7778. support dynamic typing.
  7779. There is an interesting interaction between tagged values and garbage
  7780. collection. A variable of type \code{Any} might refer to a vector and
  7781. therefore it might be a root that needs to be inspected and copied
  7782. during garbage collection. Thus, we need to treat variables of type
  7783. \code{Any} in a similar way to variables of type \code{Vector} for
  7784. purposes of register allocation, which we discuss in
  7785. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7786. variable of type \code{Any} is spilled, it must be spilled to the root
  7787. stack. But this means that the garbage collector needs to be able to
  7788. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7789. value that points to a tuple, and (3) a tagged value that is not a
  7790. tuple. We enable this differentiation by choosing not to use the tag
  7791. $000$. Instead, that bit pattern is reserved for identifying plain old
  7792. pointers to tuples. On the other hand, if one of the first three bits
  7793. is set, then we have a tagged value, and inspecting the tag can
  7794. differentiation between vectors ($010$) and the other kinds of values.
  7795. We implement our untyped language $R_7$ by compiling it to $R_6$
  7796. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7797. extend our compiler to handle the new features of $R_6$
  7798. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7799. \ref{sec:register-allocation-r6}).
  7800. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7801. \label{sec:r6-lang}
  7802. \begin{figure}[tp]
  7803. \centering
  7804. \fbox{
  7805. \begin{minipage}{0.97\textwidth}
  7806. \[
  7807. \begin{array}{lcl}
  7808. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7809. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7810. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7811. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7812. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7813. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7814. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7815. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7816. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7817. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7818. \mid (\key{and}\;\Exp\;\Exp)
  7819. \mid (\key{or}\;\Exp\;\Exp)
  7820. \mid (\key{not}\;\Exp)} \\
  7821. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7822. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7823. (\key{vector-ref}\;\Exp\;\Int)} \\
  7824. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7825. &\mid& \gray{(\Exp \; \Exp\ldots)
  7826. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7827. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7828. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7829. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7830. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7831. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7832. \end{array}
  7833. \]
  7834. \end{minipage}
  7835. }
  7836. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7837. with \key{Any}.}
  7838. \label{fig:r6-syntax}
  7839. \end{figure}
  7840. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7841. $(\key{inject}\; e\; T)$ form converts the value produced by
  7842. expression $e$ of type $T$ into a tagged value. The
  7843. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7844. expression $e$ into a value of type $T$ or else halts the program if
  7845. the type tag is equivalent to $T$. We treat
  7846. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7847. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7848. Note that in both \key{inject} and
  7849. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7850. which simplifies the implementation and corresponds with what is
  7851. needed for compiling untyped Racket. The type predicates,
  7852. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7853. if the tag corresponds to the predicate, and return \key{\#f}
  7854. otherwise.
  7855. %
  7856. Selections from the type checker for $R_6$ are shown in
  7857. Figure~\ref{fig:type-check-R6} and the interpreter for $R_6$ is in
  7858. Figure~\ref{fig:interp-R6}.
  7859. \begin{figure}[btp]
  7860. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7861. (define (flat-ty? ty) ...)
  7862. (define (type-check-R6 env)
  7863. (lambda (e)
  7864. (define recur (type-check-R6 env))
  7865. (match e
  7866. [`(inject ,e ,ty)
  7867. (unless (flat-ty? ty)
  7868. (error "may only inject a value of flat type, not ~a" ty))
  7869. (define-values (new-e e-ty) (recur e))
  7870. (cond
  7871. [(equal? e-ty ty)
  7872. (values `(inject ,new-e ,ty) 'Any)]
  7873. [else
  7874. (error "inject expected ~a to have type ~a" e ty)])]
  7875. [`(project ,e ,ty)
  7876. (unless (flat-ty? ty)
  7877. (error "may only project to a flat type, not ~a" ty))
  7878. (define-values (new-e e-ty) (recur e))
  7879. (cond
  7880. [(equal? e-ty 'Any)
  7881. (values `(project ,new-e ,ty) ty)]
  7882. [else
  7883. (error "project expected ~a to have type Any" e)])]
  7884. [`(vector-ref ,e ,i)
  7885. (define-values (new-e e-ty) (recur e))
  7886. (match e-ty
  7887. [`(Vector ,ts ...) ...]
  7888. [`(Vectorof ,ty)
  7889. (unless (exact-nonnegative-integer? i)
  7890. (error 'type-check "invalid index ~a" i))
  7891. (values `(vector-ref ,new-e ,i) ty)]
  7892. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7893. ...
  7894. )))
  7895. \end{lstlisting}
  7896. \caption{Type checker for parts of the $R_6$ language.}
  7897. \label{fig:type-check-R6}
  7898. \end{figure}
  7899. % to do: add rules for vector-ref, etc. for Vectorof
  7900. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7901. \begin{figure}[btp]
  7902. \begin{lstlisting}
  7903. (define primitives (set 'boolean? ...))
  7904. (define (interp-op op)
  7905. (match op
  7906. ['boolean? (lambda (v)
  7907. (match v
  7908. [`(tagged ,v1 Boolean) #t]
  7909. [else #f]))]
  7910. ...))
  7911. ;; Equivalence of flat types
  7912. (define (tyeq? t1 t2)
  7913. (match `(,t1 ,t2)
  7914. [`((Vectorof Any) (Vector ,t2s ...))
  7915. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7916. [`((Vector ,t1s ...) (Vectorof Any))
  7917. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7918. [else (equal? t1 t2)]))
  7919. (define (interp-R6 env)
  7920. (lambda (ast)
  7921. (match ast
  7922. [`(inject ,e ,t)
  7923. `(tagged ,((interp-R6 env) e) ,t)]
  7924. [`(project ,e ,t2)
  7925. (define v ((interp-R6 env) e))
  7926. (match v
  7927. [`(tagged ,v1 ,t1)
  7928. (cond [(tyeq? t1 t2)
  7929. v1]
  7930. [else
  7931. (error "in project, type mismatch" t1 t2)])]
  7932. [else
  7933. (error "in project, expected tagged value" v)])]
  7934. ...)))
  7935. \end{lstlisting}
  7936. \caption{Interpreter for $R_6$.}
  7937. \label{fig:interp-R6}
  7938. \end{figure}
  7939. %\clearpage
  7940. \section{Shrinking $R_6$}
  7941. \label{sec:shrink-r6}
  7942. In the \code{shrink} pass we recommend compiling \code{project} into
  7943. an explicit \code{if} expression that uses three new operations:
  7944. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7945. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7946. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7947. value from a tagged value. Finally, the \code{exit} operation ends the
  7948. execution of the program by invoking the operating system's
  7949. \code{exit} function. So the translation for \code{project} is as
  7950. follows. (We have omitted the \code{has-type} AST nodes to make this
  7951. output more readable.)
  7952. \begin{tabular}{lll}
  7953. \begin{minipage}{0.3\textwidth}
  7954. \begin{lstlisting}
  7955. (project |$e$| |$\Type$|)
  7956. \end{lstlisting}
  7957. \end{minipage}
  7958. &
  7959. $\Rightarrow$
  7960. &
  7961. \begin{minipage}{0.5\textwidth}
  7962. \begin{lstlisting}
  7963. (let ([|$\itm{tmp}$| |$e'$|])
  7964. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7965. (value-of-any |$\itm{tmp}$|)
  7966. (exit)))
  7967. \end{lstlisting}
  7968. \end{minipage}
  7969. \end{tabular} \\
  7970. Similarly, we recommend translating the type predicates
  7971. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7972. \section{Instruction Selection for $R_6$}
  7973. \label{sec:select-r6}
  7974. \paragraph{Inject}
  7975. We recommend compiling an \key{inject} as follows if the type is
  7976. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7977. destination to the left by the number of bits specified its source
  7978. argument (in this case $3$, the length of the tag) and it preserves
  7979. the sign of the integer. We use the \key{orq} instruction to combine
  7980. the tag and the value to form the tagged value. \\
  7981. \begin{tabular}{lll}
  7982. \begin{minipage}{0.4\textwidth}
  7983. \begin{lstlisting}
  7984. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7985. \end{lstlisting}
  7986. \end{minipage}
  7987. &
  7988. $\Rightarrow$
  7989. &
  7990. \begin{minipage}{0.5\textwidth}
  7991. \begin{lstlisting}
  7992. (movq |$e'$| |\itm{lhs}'|)
  7993. (salq (int 3) |\itm{lhs}'|)
  7994. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7995. \end{lstlisting}
  7996. \end{minipage}
  7997. \end{tabular} \\
  7998. The instruction selection for vectors and procedures is different
  7999. because their is no need to shift them to the left. The rightmost 3
  8000. bits are already zeros as described above. So we just combine the
  8001. value and the tag using \key{orq}. \\
  8002. \begin{tabular}{lll}
  8003. \begin{minipage}{0.4\textwidth}
  8004. \begin{lstlisting}
  8005. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8006. \end{lstlisting}
  8007. \end{minipage}
  8008. &
  8009. $\Rightarrow$
  8010. &
  8011. \begin{minipage}{0.5\textwidth}
  8012. \begin{lstlisting}
  8013. (movq |$e'$| |\itm{lhs}'|)
  8014. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8015. \end{lstlisting}
  8016. \end{minipage}
  8017. \end{tabular}
  8018. \paragraph{Tag of Any}
  8019. Recall that the \code{tag-of-any} operation extracts the type tag from
  8020. a value of type \code{Any}. The type tag is the bottom three bits, so
  8021. we obtain the tag by taking the bitwise-and of the value with $111$
  8022. ($7$ in decimal).
  8023. \begin{tabular}{lll}
  8024. \begin{minipage}{0.4\textwidth}
  8025. \begin{lstlisting}
  8026. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8027. \end{lstlisting}
  8028. \end{minipage}
  8029. &
  8030. $\Rightarrow$
  8031. &
  8032. \begin{minipage}{0.5\textwidth}
  8033. \begin{lstlisting}
  8034. (movq |$e'$| |\itm{lhs}'|)
  8035. (andq (int 7) |\itm{lhs}'|)
  8036. \end{lstlisting}
  8037. \end{minipage}
  8038. \end{tabular}
  8039. \paragraph{Value of Any}
  8040. Like \key{inject}, the instructions for \key{value-of-any} are
  8041. different depending on whether the type $T$ is a pointer (vector or
  8042. procedure) or not (Integer or Boolean). The following shows the
  8043. instruction selection for Integer and Boolean. We produce an untagged
  8044. value by shifting it to the right by 3 bits.
  8045. %
  8046. \\
  8047. \begin{tabular}{lll}
  8048. \begin{minipage}{0.4\textwidth}
  8049. \begin{lstlisting}
  8050. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8051. \end{lstlisting}
  8052. \end{minipage}
  8053. &
  8054. $\Rightarrow$
  8055. &
  8056. \begin{minipage}{0.5\textwidth}
  8057. \begin{lstlisting}
  8058. (movq |$e'$| |\itm{lhs}'|)
  8059. (sarq (int 3) |\itm{lhs}'|)
  8060. \end{lstlisting}
  8061. \end{minipage}
  8062. \end{tabular} \\
  8063. %
  8064. In the case for vectors and procedures, there is no need to
  8065. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8066. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8067. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8068. \code{movq} into the destination $\itm{lhs}$. We then generate
  8069. \code{andq} with the tagged value to get the desired result. \\
  8070. %
  8071. \begin{tabular}{lll}
  8072. \begin{minipage}{0.4\textwidth}
  8073. \begin{lstlisting}
  8074. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8075. \end{lstlisting}
  8076. \end{minipage}
  8077. &
  8078. $\Rightarrow$
  8079. &
  8080. \begin{minipage}{0.5\textwidth}
  8081. \begin{lstlisting}
  8082. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8083. (andq |$e'$| |\itm{lhs}'|)
  8084. \end{lstlisting}
  8085. \end{minipage}
  8086. \end{tabular}
  8087. %% \paragraph{Type Predicates} We leave it to the reader to
  8088. %% devise a sequence of instructions to implement the type predicates
  8089. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8090. \section{Register Allocation for $R_6$}
  8091. \label{sec:register-allocation-r6}
  8092. \index{register allocation}
  8093. As mentioned above, a variable of type \code{Any} might refer to a
  8094. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8095. of type \code{Any} in the same way that it treats variables of type
  8096. \code{Vector} for purposes of garbage collection. In particular,
  8097. \begin{itemize}
  8098. \item If a variable of type \code{Any} is live during a function call,
  8099. then it must be spilled. One way to accomplish this is to augment
  8100. the pass \code{build-interference} to mark all variables that are
  8101. live after a \code{callq} as interfering with all the registers.
  8102. \item If a variable of type \code{Any} is spilled, it must be spilled
  8103. to the root stack instead of the normal procedure call stack.
  8104. \end{itemize}
  8105. \begin{exercise}\normalfont
  8106. Expand your compiler to handle $R_6$ as discussed in the last few
  8107. sections. Create 5 new programs that use the \code{Any} type and the
  8108. new operations (\code{inject}, \code{project}, \code{boolean?},
  8109. etc.). Test your compiler on these new programs and all of your
  8110. previously created test programs.
  8111. \end{exercise}
  8112. \section{Compiling $R_7$ to $R_6$}
  8113. \label{sec:compile-r7}
  8114. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8115. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8116. given a subexpression $e$ of $R_7$, the pass will produce an
  8117. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8118. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8119. the Boolean \code{\#t}, which must be injected to produce an
  8120. expression of type \key{Any}.
  8121. %
  8122. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8123. addition, is representative of compilation for many operations: the
  8124. arguments have type \key{Any} and must be projected to \key{Integer}
  8125. before the addition can be performed.
  8126. The compilation of \key{lambda} (third row of
  8127. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8128. produce type annotations: we simply use \key{Any}.
  8129. %
  8130. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8131. has to account for some differences in behavior between $R_7$ and
  8132. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8133. kind of values can be used in various places. For example, the
  8134. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8135. the arguments need not be of the same type (but in that case, the
  8136. result will be \code{\#f}).
  8137. \begin{figure}[btp]
  8138. \centering
  8139. \begin{tabular}{|lll|} \hline
  8140. \begin{minipage}{0.25\textwidth}
  8141. \begin{lstlisting}
  8142. #t
  8143. \end{lstlisting}
  8144. \end{minipage}
  8145. &
  8146. $\Rightarrow$
  8147. &
  8148. \begin{minipage}{0.6\textwidth}
  8149. \begin{lstlisting}
  8150. (inject #t Boolean)
  8151. \end{lstlisting}
  8152. \end{minipage}
  8153. \\[2ex]\hline
  8154. \begin{minipage}{0.25\textwidth}
  8155. \begin{lstlisting}
  8156. (+ |$e_1$| |$e_2$|)
  8157. \end{lstlisting}
  8158. \end{minipage}
  8159. &
  8160. $\Rightarrow$
  8161. &
  8162. \begin{minipage}{0.6\textwidth}
  8163. \begin{lstlisting}
  8164. (inject
  8165. (+ (project |$e'_1$| Integer)
  8166. (project |$e'_2$| Integer))
  8167. Integer)
  8168. \end{lstlisting}
  8169. \end{minipage}
  8170. \\[2ex]\hline
  8171. \begin{minipage}{0.25\textwidth}
  8172. \begin{lstlisting}
  8173. (lambda (|$x_1 \ldots$|) |$e$|)
  8174. \end{lstlisting}
  8175. \end{minipage}
  8176. &
  8177. $\Rightarrow$
  8178. &
  8179. \begin{minipage}{0.6\textwidth}
  8180. \begin{lstlisting}
  8181. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8182. (Any|$\ldots$|Any -> Any))
  8183. \end{lstlisting}
  8184. \end{minipage}
  8185. \\[2ex]\hline
  8186. \begin{minipage}{0.25\textwidth}
  8187. \begin{lstlisting}
  8188. (app |$e_0$| |$e_1 \ldots e_n$|)
  8189. \end{lstlisting}
  8190. \end{minipage}
  8191. &
  8192. $\Rightarrow$
  8193. &
  8194. \begin{minipage}{0.6\textwidth}
  8195. \begin{lstlisting}
  8196. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8197. |$e'_1 \ldots e'_n$|)
  8198. \end{lstlisting}
  8199. \end{minipage}
  8200. \\[2ex]\hline
  8201. \begin{minipage}{0.25\textwidth}
  8202. \begin{lstlisting}
  8203. (vector-ref |$e_1$| |$e_2$|)
  8204. \end{lstlisting}
  8205. \end{minipage}
  8206. &
  8207. $\Rightarrow$
  8208. &
  8209. \begin{minipage}{0.6\textwidth}
  8210. \begin{lstlisting}
  8211. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8212. (let ([tmp2 (project |$e'_2$| Integer)])
  8213. (vector-ref tmp1 tmp2)))
  8214. \end{lstlisting}
  8215. \end{minipage}
  8216. \\[2ex]\hline
  8217. \begin{minipage}{0.25\textwidth}
  8218. \begin{lstlisting}
  8219. (if |$e_1$| |$e_2$| |$e_3$|)
  8220. \end{lstlisting}
  8221. \end{minipage}
  8222. &
  8223. $\Rightarrow$
  8224. &
  8225. \begin{minipage}{0.6\textwidth}
  8226. \begin{lstlisting}
  8227. (if (eq? |$e'_1$| (inject #f Boolean))
  8228. |$e'_3$|
  8229. |$e'_2$|)
  8230. \end{lstlisting}
  8231. \end{minipage}
  8232. \\[2ex]\hline
  8233. \begin{minipage}{0.25\textwidth}
  8234. \begin{lstlisting}
  8235. (eq? |$e_1$| |$e_2$|)
  8236. \end{lstlisting}
  8237. \end{minipage}
  8238. &
  8239. $\Rightarrow$
  8240. &
  8241. \begin{minipage}{0.6\textwidth}
  8242. \begin{lstlisting}
  8243. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8244. \end{lstlisting}
  8245. \end{minipage}
  8246. \\[2ex]\hline
  8247. \end{tabular}
  8248. \caption{Compiling $R_7$ to $R_6$.}
  8249. \label{fig:compile-r7-r6}
  8250. \end{figure}
  8251. \begin{exercise}\normalfont
  8252. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8253. Create tests for $R_7$ by adapting all of your previous test programs
  8254. by removing type annotations. Add 5 more tests programs that
  8255. specifically rely on the language being dynamically typed. That is,
  8256. they should not be legal programs in a statically typed language, but
  8257. nevertheless, they should be valid $R_7$ programs that run to
  8258. completion without error.
  8259. \end{exercise}
  8260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8261. \chapter{Gradual Typing}
  8262. \label{ch:gradual-typing}
  8263. \index{gradual typing}
  8264. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8266. \chapter{Parametric Polymorphism}
  8267. \label{ch:parametric-polymorphism}
  8268. \index{parametric polymorphism}
  8269. \index{generics}
  8270. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8271. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8272. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8273. \chapter{High-level Optimization}
  8274. \label{ch:high-level-optimization}
  8275. This chapter will present a procedure inlining pass based on the
  8276. algorithm of \citet{Waddell:1997fk}.
  8277. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8278. \chapter{Appendix}
  8279. \section{Interpreters}
  8280. \label{appendix:interp}
  8281. \index{interpreter}
  8282. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8283. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8284. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8285. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8286. the rest of the intermediate languages, including pseudo-x86 and x86
  8287. are in the \key{interp.rkt} file.
  8288. \section{Utility Functions}
  8289. \label{appendix:utilities}
  8290. The utility functions described here are in the \key{utilities.rkt}
  8291. file.
  8292. \paragraph{\code{interp-tests}}
  8293. The \key{interp-tests} function runs the compiler passes and the
  8294. interpreters on each of the specified tests to check whether each pass
  8295. is correct. The \key{interp-tests} function has the following
  8296. parameters:
  8297. \begin{description}
  8298. \item[name (a string)] a name to identify the compiler,
  8299. \item[typechecker] a function of exactly one argument that either
  8300. raises an error using the \code{error} function when it encounters a
  8301. type error, or returns \code{\#f} when it encounters a type
  8302. error. If there is no type error, the type checker returns the
  8303. program.
  8304. \item[passes] a list with one entry per pass. An entry is a list with
  8305. three things: a string giving the name of the pass, the function
  8306. that implements the pass (a translator from AST to AST), and a
  8307. function that implements the interpreter (a function from AST to
  8308. result value) for the language of the output of the pass.
  8309. \item[source-interp] an interpreter for the source language. The
  8310. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8311. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8312. \item[tests] a list of test numbers that specifies which tests to
  8313. run. (see below)
  8314. \end{description}
  8315. %
  8316. The \key{interp-tests} function assumes that the subdirectory
  8317. \key{tests} has a collection of Racket programs whose names all start
  8318. with the family name, followed by an underscore and then the test
  8319. number, ending with the file extension \key{.rkt}. Also, for each test
  8320. program that calls \code{read} one or more times, there is a file with
  8321. the same name except that the file extension is \key{.in} that
  8322. provides the input for the Racket program. If the test program is
  8323. expected to fail type checking, then there should be an empty file of
  8324. the same name but with extension \key{.tyerr}.
  8325. \paragraph{\code{compiler-tests}}
  8326. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8327. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8328. machine code and checks that the output is $42$. The parameters to the
  8329. \code{compiler-tests} function are similar to those of the
  8330. \code{interp-tests} function, and consist of
  8331. \begin{itemize}
  8332. \item a compiler name (a string),
  8333. \item a type checker,
  8334. \item description of the passes,
  8335. \item name of a test-family, and
  8336. \item a list of test numbers.
  8337. \end{itemize}
  8338. \paragraph{\code{compile-file}}
  8339. takes a description of the compiler passes (see the comment for
  8340. \key{interp-tests}) and returns a function that, given a program file
  8341. name (a string ending in \key{.rkt}), applies all of the passes and
  8342. writes the output to a file whose name is the same as the program file
  8343. name but with \key{.rkt} replaced with \key{.s}.
  8344. \paragraph{\code{read-program}}
  8345. takes a file path and parses that file (it must be a Racket program)
  8346. into an abstract syntax tree.
  8347. \paragraph{\code{parse-program}}
  8348. takes an S-expression representation of an abstract syntax tree and converts it into
  8349. the struct-based representation.
  8350. \paragraph{\code{assert}}
  8351. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8352. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8353. \paragraph{\code{lookup}}
  8354. % remove discussion of lookup? -Jeremy
  8355. takes a key and an alist, and returns the first value that is
  8356. associated with the given key, if there is one. If not, an error is
  8357. triggered. The alist may contain both immutable pairs (built with
  8358. \key{cons}) and mutable pairs (built with \key{mcons}).
  8359. %The \key{map2} function ...
  8360. \section{x86 Instruction Set Quick-Reference}
  8361. \label{sec:x86-quick-reference}
  8362. \index{x86}
  8363. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8364. do. We write $A \to B$ to mean that the value of $A$ is written into
  8365. location $B$. Address offsets are given in bytes. The instruction
  8366. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8367. registers (such as \code{\%rax}), or memory references (such as
  8368. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8369. reference per instruction. Other operands must be immediates or
  8370. registers.
  8371. \begin{table}[tbp]
  8372. \centering
  8373. \begin{tabular}{l|l}
  8374. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8375. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8376. \texttt{negq} $A$ & $- A \to A$ \\
  8377. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8378. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8379. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8380. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8381. \texttt{retq} & Pops the return address and jumps to it \\
  8382. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8383. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8384. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8385. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8386. be an immediate) \\
  8387. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8388. matches the condition code of the instruction, otherwise go to the
  8389. next instructions. The condition codes are \key{e} for ``equal'',
  8390. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8391. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8392. \texttt{jl} $L$ & \\
  8393. \texttt{jle} $L$ & \\
  8394. \texttt{jg} $L$ & \\
  8395. \texttt{jge} $L$ & \\
  8396. \texttt{jmp} $L$ & Jump to label $L$ \\
  8397. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8398. \texttt{movzbq} $A$, $B$ &
  8399. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8400. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8401. and the extra bytes of $B$ are set to zero.} \\
  8402. & \\
  8403. & \\
  8404. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8405. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8406. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8407. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8408. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8409. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8410. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8411. description of the condition codes. $A$ must be a single byte register
  8412. (e.g., \texttt{al} or \texttt{cl}).} \\
  8413. \texttt{setl} $A$ & \\
  8414. \texttt{setle} $A$ & \\
  8415. \texttt{setg} $A$ & \\
  8416. \texttt{setge} $A$ &
  8417. \end{tabular}
  8418. \vspace{5pt}
  8419. \caption{Quick-reference for the x86 instructions used in this book.}
  8420. \label{tab:x86-instr}
  8421. \end{table}
  8422. \cleardoublepage
  8423. \addcontentsline{toc}{chapter}{Index}
  8424. \printindex
  8425. \cleardoublepage
  8426. \bibliographystyle{plainnat}
  8427. \bibliography{all}
  8428. \addcontentsline{toc}{chapter}{Bibliography}
  8429. \end{document}
  8430. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8431. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8432. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8433. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8434. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8435. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8436. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8437. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8438. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8439. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8440. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8441. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8442. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  8443. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8444. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8445. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8446. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8447. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8448. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8449. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8450. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8451. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8452. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8453. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8454. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8455. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8456. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8457. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8458. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8459. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8460. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8461. % LocalWords: struct symtab