book.tex 349 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285
  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. shall 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 shall 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 shall 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. We discuss procedure calls in more detail later in this
  1232. chapter and in Chapter~\ref{ch:functions}. The
  1233. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1234. the address of the instruction after the specified label.
  1235. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1236. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1237. \key{main} procedure is externally visible, which is necessary so
  1238. that the operating system can call it. The label \key{main:}
  1239. indicates the beginning of the \key{main} procedure which is where
  1240. the operating system starts executing this program. The instruction
  1241. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1242. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1243. $10$ in \key{rax} and puts the result, $42$, back into
  1244. \key{rax}.
  1245. %
  1246. The last instruction, \key{retq}, finishes the \key{main} function by
  1247. returning the integer in \key{rax} to the operating system. The
  1248. operating system interprets this integer as the program's exit
  1249. code. By convention, an exit code of 0 indicates that a program
  1250. completed successfully, and all other exit codes indicate various
  1251. errors. Nevertheless, we return the result of the program as the exit
  1252. code.
  1253. %\begin{wrapfigure}{r}{2.25in}
  1254. \begin{figure}[tbp]
  1255. \begin{lstlisting}
  1256. .globl main
  1257. main:
  1258. movq $10, %rax
  1259. addq $32, %rax
  1260. retq
  1261. \end{lstlisting}
  1262. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1263. \label{fig:p0-x86}
  1264. %\end{wrapfigure}
  1265. \end{figure}
  1266. Unfortunately, x86 varies in a couple ways depending on what operating
  1267. system it is assembled in. The code examples shown here are correct on
  1268. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1269. labels like \key{main} must be prefixed with an underscore, as in
  1270. \key{\_main}.
  1271. We exhibit the use of memory for storing intermediate results in the
  1272. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1273. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1274. memory called the \emph{procedure call stack} (or \emph{stack} for
  1275. short). \index{stack}\index{procedure call stack} The stack consists
  1276. of a separate \emph{frame}\index{frame} for each procedure call. The
  1277. memory layout for an individual frame is shown in
  1278. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1279. \emph{stack pointer}\index{stack pointer} and points to the item at
  1280. the top of the stack. The stack grows downward in memory, so we
  1281. increase the size of the stack by subtracting from the stack pointer.
  1282. In the context of a procedure call, the \emph{return
  1283. address}\index{return address} is the next instruction after the
  1284. call instruction on the caller side. During a function call, the
  1285. return address is pushed onto the stack. The register \key{rbp} is
  1286. the \emph{base pointer}\index{base pointer} and is used to access
  1287. variables associated with the current procedure call. The base
  1288. pointer of the caller is pushed onto the stack after the return
  1289. address. We number the variables from $1$ to $n$. Variable $1$ is
  1290. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1291. $-16\key{(\%rbp)}$, etc.
  1292. \begin{figure}[tbp]
  1293. \begin{lstlisting}
  1294. start:
  1295. movq $10, -8(%rbp)
  1296. negq -8(%rbp)
  1297. movq -8(%rbp), %rax
  1298. addq $52, %rax
  1299. jmp conclusion
  1300. .globl main
  1301. main:
  1302. pushq %rbp
  1303. movq %rsp, %rbp
  1304. subq $16, %rsp
  1305. jmp start
  1306. conclusion:
  1307. addq $16, %rsp
  1308. popq %rbp
  1309. retq
  1310. \end{lstlisting}
  1311. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1312. \label{fig:p1-x86}
  1313. \end{figure}
  1314. \begin{figure}[tbp]
  1315. \centering
  1316. \begin{tabular}{|r|l|} \hline
  1317. Position & Contents \\ \hline
  1318. 8(\key{\%rbp}) & return address \\
  1319. 0(\key{\%rbp}) & old \key{rbp} \\
  1320. -8(\key{\%rbp}) & variable $1$ \\
  1321. -16(\key{\%rbp}) & variable $2$ \\
  1322. \ldots & \ldots \\
  1323. 0(\key{\%rsp}) & variable $n$\\ \hline
  1324. \end{tabular}
  1325. \caption{Memory layout of a frame.}
  1326. \label{fig:frame}
  1327. \end{figure}
  1328. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1329. control is transfered from the operating system to the \code{main}
  1330. function. The operating system issues a \code{callq main} instruction
  1331. which pushes its return address on the stack and then jumps to
  1332. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1333. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1334. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1335. alignment (because the \code{callq} pushed the return address). The
  1336. first three instructions are the typical \emph{prelude}\index{prelude}
  1337. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1338. pointer for the caller onto the stack and subtracts $8$ from the stack
  1339. pointer. At this point the stack pointer is back to being 16-byte
  1340. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1341. base pointer so that it points the location of the old base
  1342. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1343. pointer down to make enough room for storing variables. This program
  1344. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1345. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1346. we are ready to make calls to other functions. The last instruction of
  1347. the prelude is \code{jmp start}, which transfers control to the
  1348. instructions that were generated from the Racket expression \code{(+
  1349. 10 32)}.
  1350. The four instructions under the label \code{start} carry out the work
  1351. of computing \code{(+ 52 (- 10)))}. The first instruction
  1352. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1353. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1354. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1355. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1356. \code{rax}, at which point \code{rax} contains $42$.
  1357. The three instructions under the label \code{conclusion} are the
  1358. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1359. two instructions are necessary to get the state of the machine back to
  1360. where it was at the beginning of the procedure. The instruction
  1361. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1362. old base pointer. The amount added here needs to match the amount that
  1363. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1364. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1365. pointer. The last instruction, \key{retq}, jumps back to the
  1366. procedure that called this one and adds 8 to the stack pointer, which
  1367. returns the stack pointer to where it was prior to the procedure call.
  1368. The compiler needs a convenient representation for manipulating x86
  1369. programs, so we define an abstract syntax for x86 in
  1370. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1371. a subscript $0$ because later we introduce extended versions of this
  1372. assembly language. The main difference compared to the concrete syntax
  1373. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1374. labeled instructions to appear anywhere, but instead organizes
  1375. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1376. and associates a label with every block, which is why the \key{CFG} struct
  1377. (for control-flow graph) includes an alist mapping labels to
  1378. blocks. The reason for this organization becomes apparent in
  1379. Chapter~\ref{ch:bool-types} when we introduce conditional
  1380. branching. The \code{Block} structure includes an $\itm{info}$ field
  1381. that is not needed for this chapter, but will become useful in
  1382. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1383. field should just contain an empty list.
  1384. \begin{figure}[tp]
  1385. \fbox{
  1386. \begin{minipage}{0.96\textwidth}
  1387. \small
  1388. \[
  1389. \begin{array}{lcl}
  1390. \Reg &::=& \allregisters{} \\
  1391. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1392. \mid \DEREF{\Reg}{\Int} \\
  1393. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1394. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1395. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1396. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1397. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1398. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1399. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1400. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1401. \end{array}
  1402. \]
  1403. \end{minipage}
  1404. }
  1405. \caption{The abstract syntax of x86$_0$ assembly.}
  1406. \label{fig:x86-0-ast}
  1407. \end{figure}
  1408. \section{Planning the trip to x86 via the $C_0$ language}
  1409. \label{sec:plan-s0-x86}
  1410. To compile one language to another it helps to focus on the
  1411. differences between the two languages because the compiler will need
  1412. to bridge those differences. What are the differences between $R_1$
  1413. and x86 assembly? Here are some of the most important ones:
  1414. \begin{enumerate}
  1415. \item[(a)] x86 arithmetic instructions typically have two arguments
  1416. and update the second argument in place. In contrast, $R_1$
  1417. arithmetic operations take two arguments and produce a new value.
  1418. An x86 instruction may have at most one memory-accessing argument.
  1419. Furthermore, some instructions place special restrictions on their
  1420. arguments.
  1421. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1422. whereas x86 instructions restrict their arguments to be integers
  1423. constants, registers, and memory locations.
  1424. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1425. sequence of instructions and jumps to labeled positions, whereas in
  1426. $R_1$ the order of evaluation is a left-to-right depth-first
  1427. traversal of the abstract syntax tree.
  1428. \item[(d)] An $R_1$ program can have any number of variables whereas
  1429. x86 has 16 registers and the procedure calls stack.
  1430. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1431. same name. The registers and memory locations of x86 all have unique
  1432. names or addresses.
  1433. \end{enumerate}
  1434. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1435. the problem into several steps, dealing with the above differences one
  1436. at a time. Each of these steps is called a \emph{pass} of the
  1437. compiler.\index{pass}\index{compiler pass}
  1438. %
  1439. This terminology comes from each step traverses (i.e. passes over) the
  1440. AST of the program.
  1441. %
  1442. We begin by sketching how we might implement each pass, and give them
  1443. names. We then figure out an ordering of the passes and the
  1444. input/output language for each pass. The very first pass has $R_1$ as
  1445. its input language and the last pass has x86 as its output
  1446. language. In between we can choose whichever language is most
  1447. convenient for expressing the output of each pass, whether that be
  1448. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1449. Finally, to implement each pass we write one recursive function per
  1450. non-terminal in the grammar of the input language of the pass.
  1451. \index{intermediate language}
  1452. \begin{description}
  1453. \item[Pass \key{select-instructions}] To handle the difference between
  1454. $R_1$ operations and x86 instructions we convert each $R_1$
  1455. operation to a short sequence of instructions that accomplishes the
  1456. same task.
  1457. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1458. subexpression (i.e. operator and operand, and hence the name
  1459. \key{opera*}) is an \emph{atomic} expression (a variable or
  1460. integer), we introduce temporary variables to hold the results
  1461. of subexpressions.\index{atomic expression}
  1462. \item[Pass \key{explicate-control}] To make the execution order of the
  1463. program explicit, we convert from the abstract syntax tree
  1464. representation into a control-flow graph in which each node
  1465. contains a sequence of statements and the edges between nodes say
  1466. where to go at the end of the sequence.
  1467. \item[Pass \key{assign-homes}] To handle the difference between the
  1468. variables in $R_1$ versus the registers and stack locations in x86,
  1469. we map each variable to a register or stack location.
  1470. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1471. by renaming every variable to a unique name, so that shadowing no
  1472. longer occurs.
  1473. \end{description}
  1474. The next question is: in what order should we apply these passes? This
  1475. question can be challenging because it is difficult to know ahead of
  1476. time which orders will be better (easier to implement, produce more
  1477. efficient code, etc.) so oftentimes trial-and-error is
  1478. involved. Nevertheless, we can try to plan ahead and make educated
  1479. choices regarding the ordering.
  1480. Let us consider the ordering of \key{uniquify} and
  1481. \key{remove-complex-opera*}. The assignment of subexpressions to
  1482. temporary variables involves introducing new variables and moving
  1483. subexpressions, which might change the shadowing of variables and
  1484. inadvertently change the behavior of the program. But if we apply
  1485. \key{uniquify} first, this will not be an issue. Of course, this means
  1486. that in \key{remove-complex-opera*}, we need to ensure that the
  1487. temporary variables that it creates are unique.
  1488. What should be the ordering of \key{explicate-control} with respect to
  1489. \key{uniquify}? The \key{uniquify} pass should come first because
  1490. \key{explicate-control} changes all the \key{let}-bound variables to
  1491. become local variables whose scope is the entire program, which would
  1492. confuse variables with the same name.
  1493. %
  1494. Likewise, we place \key{explicate-control} after
  1495. \key{remove-complex-opera*} because \key{explicate-control} removes
  1496. the \key{let} form, but it is convenient to use \key{let} in the
  1497. output of \key{remove-complex-opera*}.
  1498. %
  1499. Regarding \key{assign-homes}, it is helpful to place
  1500. \key{explicate-control} first because \key{explicate-control} changes
  1501. \key{let}-bound variables into program-scope variables. This means
  1502. that the \key{assign-homes} pass can read off the variables from the
  1503. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1504. entire program in search of \key{let}-bound variables.
  1505. Last, we need to decide on the ordering of \key{select-instructions}
  1506. and \key{assign-homes}. These two passes are intertwined, creating a
  1507. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1508. have already determined which instructions will be used, because x86
  1509. instructions have restrictions about which of their arguments can be
  1510. registers versus stack locations. One might want to give preferential
  1511. treatment to variables that occur in register-argument positions. On
  1512. the other hand, it may turn out to be impossible to make sure that all
  1513. such variables are assigned to registers, and then one must redo the
  1514. selection of instructions. Some compilers handle this problem by
  1515. iteratively repeating these two passes until a good solution is found.
  1516. We shall use a simpler approach in which \key{select-instructions}
  1517. comes first, followed by the \key{assign-homes}, then a third
  1518. pass named \key{patch-instructions} that uses a reserved register to
  1519. patch-up outstanding problems regarding instructions with too many
  1520. memory accesses. The disadvantage of this approach is some programs
  1521. may not execute as efficiently as they would if we used the iterative
  1522. approach and used all of the registers for variables.
  1523. \begin{figure}[tbp]
  1524. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1525. \node (R1) at (0,2) {\large $R_1$};
  1526. \node (R1-2) at (3,2) {\large $R_1$};
  1527. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1528. %\node (C0-1) at (6,0) {\large $C_0$};
  1529. \node (C0-2) at (3,0) {\large $C_0$};
  1530. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1531. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1532. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1533. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1534. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1535. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1536. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1537. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1538. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1539. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1540. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1541. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1542. \end{tikzpicture}
  1543. \caption{Overview of the passes for compiling $R_1$. }
  1544. \label{fig:R1-passes}
  1545. \end{figure}
  1546. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1547. passes in the form of a graph. Each pass is an edge and the
  1548. input/output language of each pass is a node in the graph. The output
  1549. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1550. are still in the $R_1$ language, but the output of the pass
  1551. \key{explicate-control} is in a different language $C_0$ that is
  1552. designed to make the order of evaluation explicit in its syntax, which
  1553. we introduce in the next section. The \key{select-instruction} pass
  1554. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1555. \key{patch-instructions} passes input and output variants of x86
  1556. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1557. \key{print-x86}, which converts from the abstract syntax of
  1558. $\text{x86}_0$ to the concrete syntax of x86.
  1559. In the next sections we discuss the $C_0$ language and the
  1560. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1561. remainder of this chapter gives hints regarding the implementation of
  1562. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1563. \subsection{The $C_0$ Intermediate Language}
  1564. The output of \key{explicate-control} is similar to the $C$
  1565. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1566. categories for expressions and statements, so we name it $C_0$. The
  1567. concrete syntax for $C_0$ is defined in
  1568. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1569. is defined in Figure~\ref{fig:c0-syntax}.
  1570. %
  1571. The $C_0$ language supports the same operators as $R_1$ but the
  1572. arguments of operators are restricted to atomic expressions (variables
  1573. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1574. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1575. executed in sequence using the \key{Seq} form. A sequence of
  1576. statements always ends with \key{Return}, a guarantee that is baked
  1577. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1578. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1579. which refers to an expression that is the last one to execute within a
  1580. function. (A expression in tail position may contain subexpressions,
  1581. and those may or may not be in tail position depending on the kind of
  1582. expression.)
  1583. A $C_0$ program consists of a control-flow graph (represented as an
  1584. alist mapping labels to tails). This is more general than
  1585. necessary for the present chapter, as we do not yet need to introduce
  1586. \key{goto} for jumping to labels, but it saves us from having to
  1587. change the syntax of the program construct in
  1588. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1589. \key{start}, and the whole program is its tail.
  1590. %
  1591. The $\itm{info}$ field of the \key{Program} form, after the
  1592. \key{explicate-control} pass, contains a mapping from the symbol
  1593. \key{locals} to a list of variables, that is, a list of all the
  1594. variables used in the program. At the start of the program, these
  1595. variables are uninitialized; they become initialized on their first
  1596. assignment.
  1597. \begin{figure}[tbp]
  1598. \fbox{
  1599. \begin{minipage}{0.96\textwidth}
  1600. \[
  1601. \begin{array}{lcl}
  1602. \Atm &::=& \Int \mid \Var \\
  1603. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1604. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1605. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1606. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1607. \end{array}
  1608. \]
  1609. \end{minipage}
  1610. }
  1611. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1612. \label{fig:c0-concrete-syntax}
  1613. \end{figure}
  1614. \begin{figure}[tbp]
  1615. \fbox{
  1616. \begin{minipage}{0.96\textwidth}
  1617. \[
  1618. \begin{array}{lcl}
  1619. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1620. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1621. &\mid& \ADD{\Atm}{\Atm}\\
  1622. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1623. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1624. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1625. \end{array}
  1626. \]
  1627. \end{minipage}
  1628. }
  1629. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1630. \label{fig:c0-syntax}
  1631. \end{figure}
  1632. %% The \key{select-instructions} pass is optimistic in the sense that it
  1633. %% treats variables as if they were all mapped to registers. The
  1634. %% \key{select-instructions} pass generates a program that consists of
  1635. %% x86 instructions but that still uses variables, so it is an
  1636. %% intermediate language that is technically different than x86, which
  1637. %% explains the asterisks in the diagram above.
  1638. %% In this Chapter we shall take the easy road to implementing
  1639. %% \key{assign-homes} and simply map all variables to stack locations.
  1640. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1641. %% smarter approach in which we make a best-effort to map variables to
  1642. %% registers, resorting to the stack only when necessary.
  1643. %% Once variables have been assigned to their homes, we can finalize the
  1644. %% instruction selection by dealing with an idiosyncrasy of x86
  1645. %% assembly. Many x86 instructions have two arguments but only one of the
  1646. %% arguments may be a memory reference (and the stack is a part of
  1647. %% memory). Because some variables may get mapped to stack locations,
  1648. %% some of our generated instructions may violate this restriction. The
  1649. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1650. %% replacing every violating instruction with a short sequence of
  1651. %% instructions that use the \key{rax} register. Once we have implemented
  1652. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1653. %% need to patch instructions will be relatively rare.
  1654. \subsection{The dialects of x86}
  1655. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1656. the pass \key{select-instructions}. It extends x86$_0$ with an
  1657. unbounded number of program-scope variables and has looser rules
  1658. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1659. output of \key{print-x86}, is the concrete syntax for x86.
  1660. \section{Uniquify Variables}
  1661. \label{sec:uniquify-s0}
  1662. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1663. programs in which every \key{let} uses a unique variable name. For
  1664. example, the \code{uniquify} pass should translate the program on the
  1665. left into the program on the right. \\
  1666. \begin{tabular}{lll}
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. (let ([x 32])
  1670. (+ (let ([x 10]) x) x))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. &
  1674. $\Rightarrow$
  1675. &
  1676. \begin{minipage}{0.4\textwidth}
  1677. \begin{lstlisting}
  1678. (let ([x.1 32])
  1679. (+ (let ([x.2 10]) x.2) x.1))
  1680. \end{lstlisting}
  1681. \end{minipage}
  1682. \end{tabular} \\
  1683. %
  1684. The following is another example translation, this time of a program
  1685. with a \key{let} nested inside the initializing expression of another
  1686. \key{let}.\\
  1687. \begin{tabular}{lll}
  1688. \begin{minipage}{0.4\textwidth}
  1689. \begin{lstlisting}
  1690. (let ([x (let ([x 4])
  1691. (+ x 1))])
  1692. (+ x 2))
  1693. \end{lstlisting}
  1694. \end{minipage}
  1695. &
  1696. $\Rightarrow$
  1697. &
  1698. \begin{minipage}{0.4\textwidth}
  1699. \begin{lstlisting}
  1700. (let ([x.2 (let ([x.1 4])
  1701. (+ x.1 1))])
  1702. (+ x.2 2))
  1703. \end{lstlisting}
  1704. \end{minipage}
  1705. \end{tabular}
  1706. We recommend implementing \code{uniquify} by creating a function named
  1707. \code{uniquify-exp} that is structurally recursive function and mostly
  1708. just copies the input program. However, when encountering a \key{let},
  1709. it should generate a unique name for the variable (the Racket function
  1710. \code{gensym} is handy for this) and associate the old name with the
  1711. new unique name in an alist. The \code{uniquify-exp}
  1712. function will need to access this alist when it gets to a
  1713. variable reference, so we add another parameter to \code{uniquify-exp}
  1714. for the alist.
  1715. The skeleton of the \code{uniquify-exp} function is shown in
  1716. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1717. convenient to partially apply it to a symbol table and then apply it
  1718. to different expressions, as in the last clause for primitive
  1719. 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}}
  1720. form is useful for applying a function to each element of a list to produce
  1721. a new list.
  1722. \index{for/list}
  1723. \begin{exercise}
  1724. \normalfont % I don't like the italics for exercises. -Jeremy
  1725. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1726. implement the clauses for variables and for the \key{let} form.
  1727. \end{exercise}
  1728. \begin{figure}[tbp]
  1729. \begin{lstlisting}
  1730. (define (uniquify-exp symtab)
  1731. (lambda (e)
  1732. (match e
  1733. [(Var x) ___]
  1734. [(Int n) (Int n)]
  1735. [(Let x e body) ___]
  1736. [(Prim op es)
  1737. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1738. )))
  1739. (define (uniquify p)
  1740. (match p
  1741. [(Program '() e)
  1742. (Program '() ((uniquify-exp '()) e))]
  1743. )))
  1744. \end{lstlisting}
  1745. \caption{Skeleton for the \key{uniquify} pass.}
  1746. \label{fig:uniquify-s0}
  1747. \end{figure}
  1748. \begin{exercise}
  1749. \normalfont % I don't like the italics for exercises. -Jeremy
  1750. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1751. and checking whether the output programs produce the same result as
  1752. the input programs. The $R_1$ programs should be designed to test the
  1753. most interesting parts of the \key{uniquify} pass, that is, the
  1754. programs should include \key{let} forms, variables, and variables
  1755. that overshadow each other. The five programs should be in a
  1756. subdirectory named \key{tests} and they should have the same file name
  1757. except for a different integer at the end of the name, followed by the
  1758. ending \key{.rkt}. Use the \key{interp-tests} function
  1759. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1760. your \key{uniquify} pass on the example programs. See the
  1761. \key{run-tests.rkt} script in the student support code for an example
  1762. of how to use \key{interp-tests}.
  1763. \end{exercise}
  1764. \section{Remove Complex Operands}
  1765. \label{sec:remove-complex-opera-R1}
  1766. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1767. $R_1$ programs in which the arguments of operations are atomic
  1768. expressions. Put another way, this pass removes complex
  1769. operands\index{complex operand}, such as the expression \code{(- 10)}
  1770. in the program below. This is accomplished by introducing a new
  1771. \key{let}-bound variable, binding the complex operand to the new
  1772. variable, and then using the new variable in place of the complex
  1773. operand, as shown in the output of \code{remove-complex-opera*} on the
  1774. right.\\
  1775. \begin{tabular}{lll}
  1776. \begin{minipage}{0.4\textwidth}
  1777. % s0_19.rkt
  1778. \begin{lstlisting}
  1779. (+ 52 (- 10))
  1780. \end{lstlisting}
  1781. \end{minipage}
  1782. &
  1783. $\Rightarrow$
  1784. &
  1785. \begin{minipage}{0.4\textwidth}
  1786. \begin{lstlisting}
  1787. (let ([tmp.1 (- 10)])
  1788. (+ 52 tmp.1))
  1789. \end{lstlisting}
  1790. \end{minipage}
  1791. \end{tabular}
  1792. \begin{figure}[tp]
  1793. \centering
  1794. \fbox{
  1795. \begin{minipage}{0.96\textwidth}
  1796. \[
  1797. \begin{array}{rcl}
  1798. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1799. \Exp &::=& \Atm \mid \READ{} \\
  1800. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1801. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1802. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1803. \end{array}
  1804. \]
  1805. \end{minipage}
  1806. }
  1807. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1808. \label{fig:r1-anf-syntax}
  1809. \end{figure}
  1810. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1811. this pass, language $R_1^{\dagger}$. The main difference is that
  1812. operator arguments are required to be atomic expressions. In the
  1813. literature this is called \emph{administrative normal form}, or ANF
  1814. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1815. \index{administrative normal form}
  1816. \index{ANF}
  1817. We recommend implementing this pass with two mutually recursive
  1818. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1819. \code{rco-atom} to subexpressions that are required to be atomic and
  1820. to apply \code{rco-exp} to subexpressions that can be atomic or
  1821. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1822. $R_1$ expression as input. The \code{rco-exp} function returns an
  1823. expression. The \code{rco-atom} function returns two things: an
  1824. atomic expression and alist mapping temporary variables to complex
  1825. subexpressions. You can return multiple things from a function using
  1826. Racket's \key{values} form and you can receive multiple things from a
  1827. function call using the \key{define-values} form. If you are not
  1828. familiar with these features, review the Racket documentation. Also,
  1829. 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}}
  1830. form is useful for applying a function to each
  1831. element of a list, in the case where the function returns multiple
  1832. values.
  1833. \index{for/lists}
  1834. The following shows the output of \code{rco-atom} on the expression
  1835. \code{(- 10)} (using concrete syntax to be concise).
  1836. \begin{tabular}{lll}
  1837. \begin{minipage}{0.4\textwidth}
  1838. \begin{lstlisting}
  1839. (- 10)
  1840. \end{lstlisting}
  1841. \end{minipage}
  1842. &
  1843. $\Rightarrow$
  1844. &
  1845. \begin{minipage}{0.4\textwidth}
  1846. \begin{lstlisting}
  1847. tmp.1
  1848. ((tmp.1 . (- 10)))
  1849. \end{lstlisting}
  1850. \end{minipage}
  1851. \end{tabular}
  1852. Take special care of programs such as the next one that \key{let}-bind
  1853. variables with integers or other variables. You should leave them
  1854. unchanged, as shown in to the program on the right \\
  1855. \begin{tabular}{lll}
  1856. \begin{minipage}{0.4\textwidth}
  1857. % s0_20.rkt
  1858. \begin{lstlisting}
  1859. (let ([a 42])
  1860. (let ([b a])
  1861. b))
  1862. \end{lstlisting}
  1863. \end{minipage}
  1864. &
  1865. $\Rightarrow$
  1866. &
  1867. \begin{minipage}{0.4\textwidth}
  1868. \begin{lstlisting}
  1869. (let ([a 42])
  1870. (let ([b a])
  1871. b))
  1872. \end{lstlisting}
  1873. \end{minipage}
  1874. \end{tabular} \\
  1875. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1876. produce the following output.\\
  1877. \begin{minipage}{0.4\textwidth}
  1878. \begin{lstlisting}
  1879. (let ([tmp.1 42])
  1880. (let ([a tmp.1])
  1881. (let ([tmp.2 a])
  1882. (let ([b tmp.2])
  1883. b))))
  1884. \end{lstlisting}
  1885. \end{minipage}
  1886. \begin{exercise}
  1887. \normalfont Implement the \code{remove-complex-opera*} pass.
  1888. Test the new pass on all of the example programs that you created to test the
  1889. \key{uniquify} pass and create three new example programs that are
  1890. designed to exercise the interesting code in the
  1891. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1892. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1893. your passes on the example programs.
  1894. \end{exercise}
  1895. \section{Explicate Control}
  1896. \label{sec:explicate-control-r1}
  1897. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1898. programs that make the order of execution explicit in their
  1899. syntax. For now this amounts to flattening \key{let} constructs into a
  1900. sequence of assignment statements. For example, consider the following
  1901. $R_1$ program.\\
  1902. % s0_11.rkt
  1903. \begin{minipage}{0.96\textwidth}
  1904. \begin{lstlisting}
  1905. (let ([y (let ([x 20])
  1906. (+ x (let ([x 22]) x)))])
  1907. y)
  1908. \end{lstlisting}
  1909. \end{minipage}\\
  1910. %
  1911. The output of the previous pass and of \code{explicate-control} is
  1912. shown below. Recall that the right-hand-side of a \key{let} executes
  1913. before its body, so the order of evaluation for this program is to
  1914. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1915. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1916. output of \code{explicate-control} makes this ordering explicit.\\
  1917. \begin{tabular}{lll}
  1918. \begin{minipage}{0.4\textwidth}
  1919. \begin{lstlisting}
  1920. (let ([y (let ([x.1 20])
  1921. (let ([x.2 22])
  1922. (+ x.1 x.2)))])
  1923. y)
  1924. \end{lstlisting}
  1925. \end{minipage}
  1926. &
  1927. $\Rightarrow$
  1928. &
  1929. \begin{minipage}{0.4\textwidth}
  1930. \begin{lstlisting}
  1931. locals: y x.1 x.2
  1932. start:
  1933. x.1 = 20;
  1934. x.2 = 22;
  1935. y = (+ x.1 x.2);
  1936. return y;
  1937. \end{lstlisting}
  1938. \end{minipage}
  1939. \end{tabular}
  1940. We recommend implementing \code{explicate-control} using two mutually
  1941. recursive functions: \code{explicate-tail} and
  1942. \code{explicate-assign}. The first function should be applied to
  1943. expressions in tail position whereas the second should be applied to
  1944. expressions that occur on the right-hand-side of a \key{let}.
  1945. %
  1946. The \code{explicate-tail} function takes an $R_1$ expression as input
  1947. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1948. list of formerly \key{let}-bound variables.
  1949. %
  1950. The \code{explicate-assign} function takes an $R_1$ expression, the
  1951. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1952. should come after the assignment (e.g., the code generated for the
  1953. body of the \key{let}). It returns a $\Tail$ and a list of
  1954. variables. The \code{explicate-assign} function is in
  1955. accumulator-passing style in that its third parameter is some $C_0$
  1956. code which it then adds to and returns. The reader might be tempted to
  1957. instead organize \code{explicate-assign} in a more direct fashion,
  1958. without the third parameter and perhaps using \code{append} to combine
  1959. statements. We warn against that alternative because the
  1960. accumulator-passing style is key to how we generate high-quality code
  1961. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1962. The top-level \code{explicate-control} function should invoke
  1963. \code{explicate-tail} on the body of the \key{program} and then
  1964. associate the \code{locals} symbol with the resulting list of
  1965. variables in the $\itm{info}$ field, as in the above example.
  1966. \section{Select Instructions}
  1967. \label{sec:select-r1}
  1968. \index{instruction selection}
  1969. In the \code{select-instructions} pass we begin the work of
  1970. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1971. this pass is a variant of x86 that still uses variables, so we add an
  1972. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1973. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1974. \code{select-instructions} in terms of three auxiliary functions, one
  1975. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1976. The cases for $\Atm$ are straightforward, variables stay
  1977. the same and integer constants are changed to immediates:
  1978. $\INT{n}$ changes to $\IMM{n}$.
  1979. Next we consider the cases for $\Stmt$, starting with arithmetic
  1980. operations. For example, in $C_0$ an addition operation can take the
  1981. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1982. need to use the \key{addq} instruction which does an in-place
  1983. update. So we must first move \code{10} to \code{x}. \\
  1984. \begin{tabular}{lll}
  1985. \begin{minipage}{0.4\textwidth}
  1986. \begin{lstlisting}
  1987. x = (+ 10 32);
  1988. \end{lstlisting}
  1989. \end{minipage}
  1990. &
  1991. $\Rightarrow$
  1992. &
  1993. \begin{minipage}{0.4\textwidth}
  1994. \begin{lstlisting}
  1995. movq $10, x
  1996. addq $32, x
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. \end{tabular} \\
  2000. %
  2001. There are cases that require special care to avoid generating
  2002. needlessly complicated code. If one of the arguments of the addition
  2003. is the same as the left-hand side of the assignment, then there is no
  2004. need for the extra move instruction. For example, the following
  2005. assignment statement can be translated into a single \key{addq}
  2006. instruction.\\
  2007. \begin{tabular}{lll}
  2008. \begin{minipage}{0.4\textwidth}
  2009. \begin{lstlisting}
  2010. x = (+ 10 x);
  2011. \end{lstlisting}
  2012. \end{minipage}
  2013. &
  2014. $\Rightarrow$
  2015. &
  2016. \begin{minipage}{0.4\textwidth}
  2017. \begin{lstlisting}
  2018. addq $10, x
  2019. \end{lstlisting}
  2020. \end{minipage}
  2021. \end{tabular} \\
  2022. The \key{read} operation does not have a direct counterpart in x86
  2023. assembly, so we have instead implemented this functionality in the C
  2024. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2025. in the file \code{runtime.c}. In general, we refer to all of the
  2026. functionality in this file as the \emph{runtime system}\index{runtime system},
  2027. or simply the \emph{runtime} for short. When compiling your generated x86
  2028. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2029. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2030. the executable. For our purposes of code generation, all you need to
  2031. do is translate an assignment of \key{read} into some variable
  2032. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2033. function followed by a move from \code{rax} to the left-hand side.
  2034. The move from \code{rax} is needed because the return value from
  2035. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2036. \begin{tabular}{lll}
  2037. \begin{minipage}{0.3\textwidth}
  2038. \begin{lstlisting}
  2039. |$\itm{var}$| = (read);
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. &
  2043. $\Rightarrow$
  2044. &
  2045. \begin{minipage}{0.3\textwidth}
  2046. \begin{lstlisting}
  2047. callq read_int
  2048. movq %rax, |$\itm{var}$|
  2049. \end{lstlisting}
  2050. \end{minipage}
  2051. \end{tabular} \\
  2052. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2053. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2054. assignment to the \key{rax} register followed by a jump to the
  2055. conclusion of the program (so the conclusion needs to be labeled).
  2056. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2057. recursively and append the resulting instructions.
  2058. \begin{exercise}
  2059. \normalfont
  2060. Implement the \key{select-instructions} pass and test it on all of the
  2061. example programs that you created for the previous passes and create
  2062. three new example programs that are designed to exercise all of the
  2063. interesting code in this pass. Use the \key{interp-tests} function
  2064. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2065. your passes on the example programs.
  2066. \end{exercise}
  2067. \section{Assign Homes}
  2068. \label{sec:assign-r1}
  2069. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2070. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2071. Thus, the \key{assign-homes} pass is responsible for placing all of
  2072. the program variables in registers or on the stack. For runtime
  2073. efficiency, it is better to place variables in registers, but as there
  2074. are only 16 registers, some programs must necessarily resort to
  2075. placing some variables on the stack. In this chapter we focus on the
  2076. mechanics of placing variables on the stack. We study an algorithm for
  2077. placing variables in registers in
  2078. Chapter~\ref{ch:register-allocation-r1}.
  2079. Consider again the following $R_1$ program.
  2080. % s0_20.rkt
  2081. \begin{lstlisting}
  2082. (let ([a 42])
  2083. (let ([b a])
  2084. b))
  2085. \end{lstlisting}
  2086. For reference, we repeat the output of \code{select-instructions} on
  2087. the left and show the output of \code{assign-homes} on the right.
  2088. Recall that \key{explicate-control} associated the list of
  2089. variables with the \code{locals} symbol in the program's $\itm{info}$
  2090. field, so \code{assign-homes} has convenient access to the them. In
  2091. this example, we assign variable \code{a} to stack location
  2092. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2093. \begin{tabular}{l}
  2094. \begin{minipage}{0.4\textwidth}
  2095. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2096. locals: a b
  2097. start:
  2098. movq $42, a
  2099. movq a, b
  2100. movq b, %rax
  2101. jmp conclusion
  2102. \end{lstlisting}
  2103. \end{minipage}
  2104. {$\Rightarrow$}
  2105. \begin{minipage}{0.4\textwidth}
  2106. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2107. stack-space: 16
  2108. start:
  2109. movq $42, -8(%rbp)
  2110. movq -8(%rbp), -16(%rbp)
  2111. movq -16(%rbp), %rax
  2112. jmp conclusion
  2113. \end{lstlisting}
  2114. \end{minipage}
  2115. \end{tabular} \\
  2116. In the process of assigning variables to stack locations, it is
  2117. convenient to compute and store the size of the frame (in bytes) in
  2118. the $\itm{info}$ field of the \key{Program} node, with the key
  2119. \code{stack-space}, which will be needed later to generate the
  2120. procedure conclusion. The x86-64 standard requires the frame size to
  2121. be a multiple of 16 bytes.
  2122. \index{frame}
  2123. \begin{exercise}
  2124. \normalfont Implement the \key{assign-homes} pass and test it on all
  2125. of the example programs that you created for the previous passes pass.
  2126. We recommend that \key{assign-homes} take an extra parameter that is a
  2127. mapping of variable names to homes (stack locations for now). Use the
  2128. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2129. \key{utilities.rkt} to test your passes on the example programs.
  2130. \end{exercise}
  2131. \section{Patch Instructions}
  2132. \label{sec:patch-s0}
  2133. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2134. programs to $\text{x86}_0$ programs by making sure that each
  2135. instruction adheres to the restrictions of the x86 assembly language.
  2136. In particular, at most one argument of an instruction may be a memory
  2137. reference.
  2138. We return to the following running example.
  2139. % s0_20.rkt
  2140. \begin{lstlisting}
  2141. (let ([a 42])
  2142. (let ([b a])
  2143. b))
  2144. \end{lstlisting}
  2145. After the \key{assign-homes} pass, the above program has been translated to
  2146. the following. \\
  2147. \begin{minipage}{0.5\textwidth}
  2148. \begin{lstlisting}
  2149. stack-space: 16
  2150. start:
  2151. movq $42, -8(%rbp)
  2152. movq -8(%rbp), -16(%rbp)
  2153. movq -16(%rbp), %rax
  2154. jmp conclusion
  2155. \end{lstlisting}
  2156. \end{minipage}\\
  2157. The second \key{movq} instruction is problematic because both
  2158. arguments are stack locations. We suggest fixing this problem by
  2159. moving from the source location to the register \key{rax} and then
  2160. from \key{rax} to the destination location, as follows.
  2161. \begin{lstlisting}
  2162. movq -8(%rbp), %rax
  2163. movq %rax, -16(%rbp)
  2164. \end{lstlisting}
  2165. \begin{exercise}
  2166. \normalfont
  2167. Implement the \key{patch-instructions} pass and test it on all of the
  2168. example programs that you created for the previous passes and create
  2169. three new example programs that are designed to exercise all of the
  2170. interesting code in this pass. Use the \key{interp-tests} function
  2171. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2172. your passes on the example programs.
  2173. \end{exercise}
  2174. \section{Print x86}
  2175. \label{sec:print-x86}
  2176. The last step of the compiler from $R_1$ to x86 is to convert the
  2177. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2178. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2179. \key{format} and \key{string-append} functions are useful in this
  2180. regard. The main work that this step needs to perform is to create the
  2181. \key{main} function and the standard instructions for its prelude and
  2182. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2183. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2184. variables, so we suggest computing it in the \key{assign-homes} pass
  2185. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2186. of the \key{program} node.
  2187. %% Your compiled code should print the result of the program's execution
  2188. %% by using the \code{print\_int} function provided in
  2189. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2190. %% far, this final result should be stored in the \key{rax} register.
  2191. %% We'll talk more about how to perform function calls with arguments in
  2192. %% general later on, but for now, place the following after the compiled
  2193. %% code for the $R_1$ program but before the conclusion:
  2194. %% \begin{lstlisting}
  2195. %% movq %rax, %rdi
  2196. %% callq print_int
  2197. %% \end{lstlisting}
  2198. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2199. %% stores the first argument to be passed into \key{print\_int}.
  2200. If you want your program to run on Mac OS X, your code needs to
  2201. determine whether or not it is running on a Mac, and prefix
  2202. underscores to labels like \key{main}. You can determine the platform
  2203. with the Racket call \code{(system-type 'os)}, which returns
  2204. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2205. %% In addition to
  2206. %% placing underscores on \key{main}, you need to put them in front of
  2207. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2208. %% \_print\_int}).
  2209. \begin{exercise}
  2210. \normalfont Implement the \key{print-x86} pass and test it on all of
  2211. the example programs that you created for the previous passes. Use the
  2212. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2213. \key{utilities.rkt} to test your complete compiler on the example
  2214. programs. See the \key{run-tests.rkt} script in the student support
  2215. code for an example of how to use \key{compiler-tests}. Also, remember
  2216. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2217. \key{gcc}.
  2218. \end{exercise}
  2219. \section{Challenge: Partial Evaluator for $R_1$}
  2220. \label{sec:pe-R1}
  2221. \index{partial evaluation}
  2222. This section describes optional challenge exercises that involve
  2223. adapting and improving the partial evaluator for $R_0$ that was
  2224. introduced in Section~\ref{sec:partial-evaluation}.
  2225. \begin{exercise}\label{ex:pe-R1}
  2226. \normalfont
  2227. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2228. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2229. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2230. and variables to the $R_0$ language, so you will need to add cases for
  2231. them in the \code{pe-exp} function. Also, note that the \key{program}
  2232. form changes slightly to include an $\itm{info}$ field. Once
  2233. complete, add the partial evaluation pass to the front of your
  2234. compiler and make sure that your compiler still passes all of the
  2235. tests.
  2236. \end{exercise}
  2237. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2238. \begin{exercise}
  2239. \normalfont
  2240. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2241. \code{pe-add} auxiliary functions with functions that know more about
  2242. arithmetic. For example, your partial evaluator should translate
  2243. \begin{lstlisting}
  2244. (+ 1 (+ (read) 1))
  2245. \end{lstlisting}
  2246. into
  2247. \begin{lstlisting}
  2248. (+ 2 (read))
  2249. \end{lstlisting}
  2250. To accomplish this, the \code{pe-exp} function should produce output
  2251. in the form of the $\itm{residual}$ non-terminal of the following
  2252. grammar.
  2253. \[
  2254. \begin{array}{lcl}
  2255. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2256. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2257. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2258. \end{array}
  2259. \]
  2260. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2261. that their inputs are $\itm{residual}$ expressions and they should
  2262. return $\itm{residual}$ expressions. Once the improvements are
  2263. complete, make sure that your compiler still passes all of the tests.
  2264. After all, fast code is useless if it produces incorrect results!
  2265. \end{exercise}
  2266. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2267. \chapter{Register Allocation}
  2268. \label{ch:register-allocation-r1}
  2269. \index{register allocation}
  2270. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2271. make our life easier. However, we can improve the performance of the
  2272. generated code if we instead place some variables into registers. The
  2273. CPU can access a register in a single cycle, whereas accessing the
  2274. stack takes many cycles if the relevant data is in cache or many more
  2275. to access main memory if the data is not in cache.
  2276. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2277. serves as a running example. We show the source program and also the
  2278. output of instruction selection. At that point the program is almost
  2279. x86 assembly but not quite; it still contains variables instead of
  2280. stack locations or registers.
  2281. \begin{figure}
  2282. \begin{minipage}{0.45\textwidth}
  2283. Example $R_1$ program:
  2284. % s0_28.rkt
  2285. \begin{lstlisting}
  2286. (let ([v 1])
  2287. (let ([w 42])
  2288. (let ([x (+ v 7)])
  2289. (let ([y x])
  2290. (let ([z (+ x w)])
  2291. (+ z (- y)))))))
  2292. \end{lstlisting}
  2293. \end{minipage}
  2294. \begin{minipage}{0.45\textwidth}
  2295. After instruction selection:
  2296. \begin{lstlisting}
  2297. locals: (v w x y z t)
  2298. start:
  2299. movq $1, v
  2300. movq $42, w
  2301. movq v, x
  2302. addq $7, x
  2303. movq x, y
  2304. movq x, z
  2305. addq w, z
  2306. movq y, t
  2307. negq t
  2308. movq z, %rax
  2309. addq t, %rax
  2310. jmp conclusion
  2311. \end{lstlisting}
  2312. \end{minipage}
  2313. \caption{A running example program for register allocation.}
  2314. \label{fig:reg-eg}
  2315. \end{figure}
  2316. The goal of register allocation is to fit as many variables into
  2317. registers as possible. A program sometimes has more variables than
  2318. registers, so we cannot map each variable to a different
  2319. register. Fortunately, it is common for different variables to be
  2320. needed during different periods of time during program execution, and
  2321. in such cases several variables can be mapped to the same register.
  2322. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2323. After the variable \code{x} is moved to \code{z} it is no longer
  2324. needed. Variable \code{y}, on the other hand, is used only after this
  2325. point, so \code{x} and \code{y} could share the same register. The
  2326. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2327. where a variable is needed. Once we have that information, we compute
  2328. which variables are needed at the same time, i.e., which ones
  2329. \emph{interfere} with each other, and represent this relation as an
  2330. undirected graph whose vertices are variables and edges indicate when
  2331. two variables interfere (Section~\ref{sec:build-interference}). We
  2332. then model register allocation as a graph coloring problem, which we
  2333. discuss in Section~\ref{sec:graph-coloring}.
  2334. In the event that we run out of registers despite these efforts, we
  2335. place the remaining variables on the stack, similar to what we did in
  2336. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2337. for assigning a variable to a stack location. The process of spilling
  2338. variables is handled as part of the graph coloring process described
  2339. in \ref{sec:graph-coloring}.
  2340. We make the simplifying assumption that each variable is assigned to
  2341. one location (a register or stack address). A more sophisticated
  2342. approach is to assign a variable to one or more locations in different
  2343. regions of the program. For example, if a variable is used many times
  2344. in short sequence and then only used again after many other
  2345. instructions, it could be more efficient to assign the variable to a
  2346. register during the intial sequence and then move it to the stack for
  2347. the rest of its lifetime. We refer the interested reader to
  2348. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2349. about this approach.
  2350. % discuss prioritizing variables based on how much they are used.
  2351. \section{Registers and Calling Conventions}
  2352. \label{sec:calling-conventions}
  2353. \index{calling conventions}
  2354. As we perform register allocation, we need to be aware of the
  2355. conventions that govern the way in which registers interact with
  2356. function calls, such as calls to the \code{read\_int} function in our
  2357. generated code and even the call that the operating system makes to
  2358. execute our \code{main} function. The convention for x86 is that the
  2359. caller is responsible for freeing up some registers, the
  2360. \emph{caller-saved registers}, prior to the function call, and the
  2361. callee is responsible for preserving the values in some other
  2362. registers, the \emph{callee-saved registers}.
  2363. \index{caller-saved registers}
  2364. \index{callee-saved registers}
  2365. The caller-saved registers are
  2366. \begin{lstlisting}
  2367. rax rcx rdx rsi rdi r8 r9 r10 r11
  2368. \end{lstlisting}
  2369. while the callee-saved registers are
  2370. \begin{lstlisting}
  2371. rsp rbp rbx r12 r13 r14 r15
  2372. \end{lstlisting}
  2373. We can think about this caller/callee convention from two points of
  2374. view, the caller view and the callee view:
  2375. \begin{itemize}
  2376. \item The caller should assume that all the caller-saved registers get
  2377. overwritten with arbitrary values by the callee. On the other hand,
  2378. the caller can safely assume that all the callee-saved registers
  2379. contain the same values after the call that they did before the
  2380. call.
  2381. \item The callee can freely use any of the caller-saved registers.
  2382. However, if the callee wants to use a callee-saved register, the
  2383. callee must arrange to put the original value back in the register
  2384. prior to returning to the caller, which is usually accomplished by
  2385. saving the value to the stack in the prelude of the function and
  2386. restoring the value in the conclusion of the function.
  2387. \end{itemize}
  2388. The next question is how these calling conventions impact register
  2389. allocation. Consider the $R_1$ program in
  2390. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2391. example from the caller point of view and then from the callee point
  2392. of view.
  2393. The program makes two calls to the \code{read} function. Also, the
  2394. variable \code{x} is in-use during the second call to \code{read}, so
  2395. we need to make sure that the value in \code{x} does not get
  2396. accidentally wiped out by the call to \code{read}. One obvious
  2397. approach is to save all the values in caller-saved registers to the
  2398. stack prior to each function call, and restore them after each
  2399. call. That way, if the register allocator chooses to assign \code{x}
  2400. to a caller-saved register, its value will be preserved accross the
  2401. call to \code{read}. However, the disadvantage of this approach is
  2402. that saving and restoring to the stack is relatively slow. If \code{x}
  2403. is not used many times, it may be better to assign \code{x} to a stack
  2404. location in the first place. Or better yet, if we can arrange for
  2405. \code{x} to be placed in a callee-saved register, then it won't need
  2406. to be saved and restored during function calls.
  2407. The approach that we recommend for variables that are in-use during a
  2408. function call is to either assign them to callee-saved registers or to
  2409. spill them to the stack. On the other hand, for variables that are not
  2410. in-use during a function call, we try the following alternatives in
  2411. order 1) look for an available caller-saved register (to leave room
  2412. for other variables in the callee-saved register), 2) look for a
  2413. callee-saved register, and 3) spill the variable to the stack.
  2414. It is straightforward to implement this approach in a graph coloring
  2415. register allocator. First, we know which variables are in-use during
  2416. every function call because we compute that information for every
  2417. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2418. build the interference graph (Section~\ref{sec:build-interference}),
  2419. we can place an edge between each of these variables and the
  2420. caller-saved registers in the interference graph. This will prevent
  2421. the graph coloring algorithm from assigning those variables to
  2422. caller-saved registers.
  2423. Returning to the example in
  2424. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2425. generated x86 code on the right-hand side, focusing on the
  2426. \code{start} block. Notice that variable \code{x} is assigned to
  2427. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2428. place during the second call to \code{read\_int}. Next, notice that
  2429. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2430. because there are no function calls in the remainder of the block.
  2431. Next we analyze the example from the callee point of view, focusing on
  2432. the prelude and conclusion of the \code{main} function. As usual the
  2433. prelude begins with saving the \code{rbp} register to the stack and
  2434. setting the \code{rbp} to the current stack pointer. We now know why
  2435. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2436. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2437. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2438. variable (\code{x}). There are several more callee-saved register that
  2439. are not saved in the prelude because they were not assigned to
  2440. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2441. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2442. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2443. from the stack with a \code{popq} instruction.
  2444. \index{prelude}\index{conclusion}
  2445. \begin{figure}[tp]
  2446. \begin{minipage}{0.45\textwidth}
  2447. Example $R_1$ program:
  2448. %s0_14.rkt
  2449. \begin{lstlisting}
  2450. (let ([x (read)])
  2451. (let ([y (read)])
  2452. (+ (+ x y) 42)))
  2453. \end{lstlisting}
  2454. \end{minipage}
  2455. \begin{minipage}{0.45\textwidth}
  2456. Generated x86 assembly:
  2457. \begin{lstlisting}
  2458. start:
  2459. callq read_int
  2460. movq %rax, %rbx
  2461. callq read_int
  2462. movq %rax, %rcx
  2463. addq %rcx, %rbx
  2464. movq %rbx, %rax
  2465. addq $42, %rax
  2466. jmp _conclusion
  2467. .globl main
  2468. main:
  2469. pushq %rbp
  2470. movq %rsp, %rbp
  2471. pushq %rbx
  2472. subq $8, %rsp
  2473. jmp start
  2474. conclusion:
  2475. addq $8, %rsp
  2476. popq %rbx
  2477. popq %rbp
  2478. retq
  2479. \end{lstlisting}
  2480. \end{minipage}
  2481. \caption{An example with function calls.}
  2482. \label{fig:example-calling-conventions}
  2483. \end{figure}
  2484. \clearpage
  2485. \section{Liveness Analysis}
  2486. \label{sec:liveness-analysis-r1}
  2487. \index{liveness analysis}
  2488. A variable or register is \emph{live} at a program point if its
  2489. current value is used at some later point in the program. We shall
  2490. refer to variables and registers collectively as \emph{locations}.
  2491. %
  2492. Consider the following code fragment in which there are two writes to
  2493. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2494. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2495. movq $5, a
  2496. movq $30, b
  2497. movq a, c
  2498. movq $10, b
  2499. addq b, c
  2500. \end{lstlisting}
  2501. The answer is no because the integer \code{30} written to \code{b} on
  2502. line 2 is never used. The variable \code{b} is read on line 5 and
  2503. there is an intervening write to \code{b} on line 4, so the read on
  2504. line 5 receives the value written on line 4, not line 2.
  2505. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2506. \small
  2507. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2508. A \emph{set} is an unordered collection of elements without duplicates.
  2509. \index{set}
  2510. \begin{description}
  2511. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2512. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2513. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2514. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2515. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2516. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2517. \end{description}
  2518. \end{tcolorbox}
  2519. \end{wrapfigure}
  2520. The live locations can be computed by traversing the instruction
  2521. sequence back to front (i.e., backwards in execution order). Let
  2522. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2523. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2524. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2525. locations before instruction $I_k$. The live locations after an
  2526. instruction are always the same as the live locations before the next
  2527. instruction. \index{live-after} \index{live-before}
  2528. \begin{equation} \label{eq:live-after-before-next}
  2529. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2530. \end{equation}
  2531. To start things off, there are no live locations after the last
  2532. instruction\footnote{Technically, the \code{rax} register is live
  2533. but we do not use it for register allocation.}, so
  2534. \begin{equation}\label{eq:live-last-empty}
  2535. L_{\mathsf{after}}(n) = \emptyset
  2536. \end{equation}
  2537. We then apply the following rule repeatedly, traversing the
  2538. instruction sequence back to front.
  2539. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2540. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2541. \end{equation}
  2542. where $W(k)$ are the locations written to by instruction $I_k$ and
  2543. $R(k)$ are the locations read by instruction $I_k$.
  2544. Let us walk through the above example, applying these formulas
  2545. starting with the instruction on line 5. We collect the answers in the
  2546. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2547. instruction is $\emptyset$ because it is the last instruction
  2548. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2549. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2550. variables \code{b} and \code{c}
  2551. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2552. \[
  2553. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2554. \]
  2555. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2556. the live-before set from line 5 to be the live-after set for this
  2557. instruction (formula~\ref{eq:live-after-before-next}).
  2558. \[
  2559. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2560. \]
  2561. This move instruction writes to \code{b} and does not read from any
  2562. variables, so we have the following live-before set
  2563. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2564. \[
  2565. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2566. \]
  2567. The live-before for instruction \code{movq a, c}
  2568. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2569. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2570. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2571. variable that is not live and does not read from a variable.
  2572. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2573. because it writes to variable \code{a}.
  2574. \begin{center}
  2575. \begin{minipage}{0.45\textwidth}
  2576. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2577. movq $5, a
  2578. movq $30, b
  2579. movq a, c
  2580. movq $10, b
  2581. addq b, c
  2582. \end{lstlisting}
  2583. \end{minipage}
  2584. \vrule\hspace{10pt}
  2585. \begin{minipage}{0.45\textwidth}
  2586. \begin{align*}
  2587. L_{\mathsf{before}}(1)= \emptyset,
  2588. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2589. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2590. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2591. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2592. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2593. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2594. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2595. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2596. L_{\mathsf{after}}(5)= \emptyset
  2597. \end{align*}
  2598. \end{minipage}
  2599. \end{center}
  2600. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2601. the running example program, with the live-before and live-after sets
  2602. shown between each instruction to make the figure easy to read.
  2603. \begin{figure}[tp]
  2604. \hspace{20pt}
  2605. \begin{minipage}{0.45\textwidth}
  2606. \begin{lstlisting}
  2607. |$\{\}$|
  2608. movq $1, v
  2609. |$\{\ttm{v}\}$|
  2610. movq $42, w
  2611. |$\{\ttm{v},\ttm{w}\}$|
  2612. movq v, x
  2613. |$\{\ttm{w},\ttm{x}\}$|
  2614. addq $7, x
  2615. |$\{\ttm{w},\ttm{x}\}$|
  2616. movq x, y
  2617. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2618. movq x, z
  2619. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2620. addq w, z
  2621. |$\{\ttm{y},\ttm{z}\}$|
  2622. movq y, t
  2623. |$\{\ttm{t},\ttm{z}\}$|
  2624. negq t
  2625. |$\{\ttm{t},\ttm{z}\}$|
  2626. movq z, %rax
  2627. |$\{\ttm{rax},\ttm{t}\}$|
  2628. addq t, %rax
  2629. |$\{\}$|
  2630. jmp conclusion
  2631. |$\{\}$|
  2632. \end{lstlisting}
  2633. \end{minipage}
  2634. \caption{The running example annotated with live-after sets.}
  2635. \label{fig:live-eg}
  2636. \end{figure}
  2637. \begin{exercise}\normalfont
  2638. Implement the compiler pass named \code{uncover-live} that computes
  2639. the live-after sets. We recommend storing the live-after sets (a list
  2640. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2641. structure.
  2642. %
  2643. We recommend organizing your code to use a helper function that takes
  2644. a list of instructions and an initial live-after set (typically empty)
  2645. and returns the list of live-after sets.
  2646. %
  2647. We recommend creating helper functions to 1) compute the set of
  2648. locations that appear in an argument (of an instruction), 2) compute
  2649. the locations read by an instruction which corresponds to the $R$
  2650. function discussed above, and 3) the locations written by an
  2651. instruction which corresponds to $W$. The \key{callq} instruction
  2652. should include all of the caller-saved registers in its $W$ because
  2653. the calling convention says that those registers may be written to
  2654. during the function call.
  2655. \end{exercise}
  2656. \section{Building the Interference Graph}
  2657. \label{sec:build-interference}
  2658. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2659. \small
  2660. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2661. A \emph{graph} is a collection of vertices and edges where each
  2662. edge connects two vertices. A graph is \emph{directed} if each
  2663. edge points from a source to a target. Otherwise the graph is
  2664. \emph{undirected}.
  2665. \index{graph}\index{directed graph}\index{undirected graph}
  2666. \begin{description}
  2667. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2668. directed graph from a list of edges. Each edge is a list
  2669. containing the source and target vertex.
  2670. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2671. undirected graph from a list of edges. Each edge is represented by
  2672. a list containing two vertices.
  2673. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2674. inserts a vertex into the graph.
  2675. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2676. inserts an edge between the two vertices into the graph.
  2677. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2678. returns a sequence of all the neighbors of the given vertex.
  2679. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2680. returns a sequence of all the vertices in the graph.
  2681. \end{description}
  2682. \end{tcolorbox}
  2683. \end{wrapfigure}
  2684. Based on the liveness analysis, we know where each variable is needed.
  2685. However, during register allocation, we need to answer questions of
  2686. the specific form: are variables $u$ and $v$ live at the same time?
  2687. (And therefore cannot be assigned to the same register.) To make this
  2688. question easier to answer, we create an explicit data structure, an
  2689. \emph{interference graph}\index{interference graph}. An interference
  2690. graph is an undirected graph that has an edge between two variables if
  2691. they are live at the same time, that is, if they interfere with each
  2692. other.
  2693. The most obvious way to compute the interference graph is to look at
  2694. the set of live location between each statement in the program and add
  2695. an edge to the graph for every pair of variables in the same set.
  2696. This approach is less than ideal for two reasons. First, it can be
  2697. expensive because it takes $O(n^2)$ time to look at every pair in a
  2698. set of $n$ live locations. Second, there is a special case in which
  2699. two locations that are live at the same time do not actually interfere
  2700. with each other: when they both contain the same value because we have
  2701. assigned one to the other.
  2702. A better way to compute the interference graph is to focus on the
  2703. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2704. instruction to overwrite something in a live location. So for each
  2705. instruction, we create an edge between the locations being written to
  2706. and all the other live locations. (Except that one should not create
  2707. self edges.) Recall that for a \key{callq} instruction, we consider
  2708. all of the caller-saved registers as being written to, so an edge will
  2709. be added between every live variable and every caller-saved
  2710. register. For \key{movq}, we deal with the above-mentioned special
  2711. case by not adding an edge between a live variable $v$ and destination
  2712. $d$ if $v$ matches the source of the move. So we have the following
  2713. two rules.
  2714. \begin{enumerate}
  2715. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2716. $d$, then add the edge $(d,v)$ for every $v \in
  2717. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2718. \item For any other instruction $I_k$, for every $d \in W(k)$
  2719. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2720. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2721. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2722. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2723. %% \item If instruction $I_k$ is of the form \key{callq}
  2724. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2725. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2726. \end{enumerate}
  2727. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2728. the above rules to each instruction. We highlight a few of the
  2729. instructions and then refer the reader to
  2730. Figure~\ref{fig:interference-results} for all the interference
  2731. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2732. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2733. interference edges because the one live variable \code{v} is also the
  2734. destination of this instruction.
  2735. %
  2736. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2737. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2738. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2739. %
  2740. Next we skip forward to the instruction \lstinline{movq x, y}.
  2741. \begin{figure}[tbp]
  2742. \begin{quote}
  2743. \begin{tabular}{ll}
  2744. \lstinline{movq $1, v}& no interference by rule 1\\
  2745. \lstinline{movq $42, w}& $\ttm{w}$ interferes with $\ttm{v}$ by rule 1\\
  2746. \lstinline{movq v, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 1\\
  2747. \lstinline{addq $7, x}& $\ttm{x}$ interferes with $\ttm{w}$ by rule 2\\
  2748. \lstinline{movq x, y}& $\ttm{y}$ interferes with $\ttm{w}$ but not $\ttm{x}$ by rule 1\\
  2749. \lstinline{movq x, z}& $\ttm{z}$ interferes with $\ttm{w}$ and $\ttm{y}$ by rule 1\\
  2750. \lstinline{addq w, z}& $\ttm{z}$ interferes with $\ttm{y}$ by rule 2 \\
  2751. \lstinline{movq y, t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 1 \\
  2752. \lstinline{negq t}& $\ttm{t}$ interferes with $\ttm{z}$ by rule 2 \\
  2753. \lstinline{movq z, %rax} & $\ttm{rax}$ interferes with $\ttm{t}$ by rule 1 \\
  2754. \lstinline{addq t, %rax} & no interference by rule 2 \\
  2755. \lstinline{jmp conclusion}& no interference by rule 2
  2756. \end{tabular}
  2757. \end{quote}
  2758. \caption{Interference results for the running example.}
  2759. \label{fig:interference-results}
  2760. \end{figure}
  2761. The resulting interference graph is shown in
  2762. Figure~\ref{fig:interfere}.
  2763. \begin{figure}[tbp]
  2764. \large
  2765. \[
  2766. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2767. \node (rax) at (0,0) {$\ttm{rax}$};
  2768. \node (t1) at (0,2) {$\ttm{t}$};
  2769. \node (z) at (3,2) {$\ttm{z}$};
  2770. \node (x) at (6,2) {$\ttm{x}$};
  2771. \node (y) at (3,0) {$\ttm{y}$};
  2772. \node (w) at (6,0) {$\ttm{w}$};
  2773. \node (v) at (9,0) {$\ttm{v}$};
  2774. \draw (t1) to (rax);
  2775. \draw (t1) to (z);
  2776. \draw (z) to (y);
  2777. \draw (z) to (w);
  2778. \draw (x) to (w);
  2779. \draw (y) to (w);
  2780. \draw (v) to (w);
  2781. \end{tikzpicture}
  2782. \]
  2783. \caption{The interference graph of the example program.}
  2784. \label{fig:interfere}
  2785. \end{figure}
  2786. %% Our next concern is to choose a data structure for representing the
  2787. %% interference graph. There are many choices for how to represent a
  2788. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2789. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2790. %% data structure is to study the algorithm that uses the data structure,
  2791. %% determine what operations need to be performed, and then choose the
  2792. %% data structure that provide the most efficient implementations of
  2793. %% those operations. Often times the choice of data structure can have an
  2794. %% effect on the time complexity of the algorithm, as it does here. If
  2795. %% you skim the next section, you will see that the register allocation
  2796. %% algorithm needs to ask the graph for all of its vertices and, given a
  2797. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2798. %% correct choice of graph representation is that of an adjacency
  2799. %% list. There are helper functions in \code{utilities.rkt} for
  2800. %% representing graphs using the adjacency list representation:
  2801. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2802. %% (Appendix~\ref{appendix:utilities}).
  2803. %% %
  2804. %% \margincomment{\footnotesize To do: change to use the
  2805. %% Racket graph library. \\ --Jeremy}
  2806. %% %
  2807. %% In particular, those functions use a hash table to map each vertex to
  2808. %% the set of adjacent vertices, and the sets are represented using
  2809. %% Racket's \key{set}, which is also a hash table.
  2810. \begin{exercise}\normalfont
  2811. Implement the compiler pass named \code{build-interference} according
  2812. to the algorithm suggested above. We recommend using the \code{graph}
  2813. package to create and inspect the interference graph. The output
  2814. graph of this pass should be stored in the $\itm{info}$ field of the
  2815. program, under the key \code{conflicts}.
  2816. \end{exercise}
  2817. \section{Graph Coloring via Sudoku}
  2818. \label{sec:graph-coloring}
  2819. \index{graph coloring}
  2820. \index{Sudoku}
  2821. \index{color}
  2822. We come to the main event, mapping variables to registers (or to stack
  2823. locations in the event that we run out of registers). We need to make
  2824. sure that two variables do not get mapped to the same register if the
  2825. two variables interfere with each other. Thinking about the
  2826. interference graph, this means that adjacent vertices must be mapped
  2827. to different registers. If we think of registers as colors, the
  2828. register allocation problem becomes the widely-studied graph coloring
  2829. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2830. The reader may be more familiar with the graph coloring problem than he
  2831. or she realizes; the popular game of Sudoku is an instance of the
  2832. graph coloring problem. The following describes how to build a graph
  2833. out of an initial Sudoku board.
  2834. \begin{itemize}
  2835. \item There is one vertex in the graph for each Sudoku square.
  2836. \item There is an edge between two vertices if the corresponding squares
  2837. are in the same row, in the same column, or if the squares are in
  2838. the same $3\times 3$ region.
  2839. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2840. \item Based on the initial assignment of numbers to squares in the
  2841. Sudoku board, assign the corresponding colors to the corresponding
  2842. vertices in the graph.
  2843. \end{itemize}
  2844. If you can color the remaining vertices in the graph with the nine
  2845. colors, then you have also solved the corresponding game of Sudoku.
  2846. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2847. the corresponding graph with colored vertices. We map the Sudoku
  2848. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2849. sampling of the vertices (the colored ones) because showing edges for
  2850. all of the vertices would make the graph unreadable.
  2851. \begin{figure}[tbp]
  2852. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2853. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2854. \caption{A Sudoku game board and the corresponding colored graph.}
  2855. \label{fig:sudoku-graph}
  2856. \end{figure}
  2857. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2858. strategies to come up with an algorithm for allocating registers. For
  2859. example, one of the basic techniques for Sudoku is called Pencil
  2860. Marks. The idea is to use a process of elimination to determine what
  2861. numbers no longer make sense for a square and write down those
  2862. numbers in the square (writing very small). For example, if the number
  2863. $1$ is assigned to a square, then by process of elimination, you can
  2864. write the pencil mark $1$ in all the squares in the same row, column,
  2865. and region. Many Sudoku computer games provide automatic support for
  2866. Pencil Marks.
  2867. %
  2868. The Pencil Marks technique corresponds to the notion of
  2869. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2870. The saturation of a
  2871. vertex, in Sudoku terms, is the set of numbers that are no longer
  2872. available. In graph terminology, we have the following definition:
  2873. \begin{equation*}
  2874. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2875. \text{ and } \mathrm{color}(v) = c \}
  2876. \end{equation*}
  2877. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2878. edge with $u$.
  2879. Using the Pencil Marks technique leads to a simple strategy for
  2880. filling in numbers: if there is a square with only one possible number
  2881. left, then choose that number! But what if there are no squares with
  2882. only one possibility left? One brute-force approach is to try them
  2883. all: choose the first and if it ultimately leads to a solution,
  2884. great. If not, backtrack and choose the next possibility. One good
  2885. thing about Pencil Marks is that it reduces the degree of branching in
  2886. the search tree. Nevertheless, backtracking can be horribly time
  2887. consuming. One way to reduce the amount of backtracking is to use the
  2888. most-constrained-first heuristic. That is, when choosing a square,
  2889. always choose one with the fewest possibilities left (the vertex with
  2890. the highest saturation). The idea is that choosing highly constrained
  2891. squares earlier rather than later is better because later on there may
  2892. not be any possibilities left for those squares.
  2893. However, register allocation is easier than Sudoku because the
  2894. register allocator can map variables to stack locations when the
  2895. registers run out. Thus, it makes sense to drop backtracking in favor
  2896. of greedy search, that is, make the best choice at the time and keep
  2897. going. We still wish to minimize the number of colors needed, so
  2898. keeping the most-constrained-first heuristic is a good idea.
  2899. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2900. algorithm for register allocation based on saturation and the
  2901. most-constrained-first heuristic. It is roughly equivalent to the
  2902. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2903. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2904. Sudoku, the algorithm represents colors with integers. The integers
  2905. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2906. register allocation. The integers $k$ and larger correspond to stack
  2907. locations. The registers that are not used for register allocation,
  2908. such as \code{rax}, are assigned to negative integers. In particular,
  2909. we assign $-1$ to \code{rax}.
  2910. \begin{figure}[btp]
  2911. \centering
  2912. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2913. Algorithm: DSATUR
  2914. Input: a graph |$G$|
  2915. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2916. |$W \gets \mathrm{vertices}(G)$|
  2917. while |$W \neq \emptyset$| do
  2918. pick a vertex |$u$| from |$W$| with the highest saturation,
  2919. breaking ties randomly
  2920. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2921. |$\mathrm{color}[u] \gets c$|
  2922. |$W \gets W - \{u\}$|
  2923. \end{lstlisting}
  2924. \caption{The saturation-based greedy graph coloring algorithm.}
  2925. \label{fig:satur-algo}
  2926. \end{figure}
  2927. With this algorithm in hand, let us return to the running example and
  2928. consider how to color the interference graph in
  2929. Figure~\ref{fig:interfere}.
  2930. %
  2931. We color the vertices for registers with their own color. For example,
  2932. \code{rax} is assigned the color $-1$. We then update the saturation
  2933. for their neighboring vertices. In this case, the saturation for
  2934. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2935. so they annotated with a dash, and their saturation sets are empty.
  2936. \[
  2937. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2938. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2939. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2940. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2941. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2942. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2943. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2944. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2945. \draw (t1) to (rax);
  2946. \draw (t1) to (z);
  2947. \draw (z) to (y);
  2948. \draw (z) to (w);
  2949. \draw (x) to (w);
  2950. \draw (y) to (w);
  2951. \draw (v) to (w);
  2952. \end{tikzpicture}
  2953. \]
  2954. The algorithm says to select a maximally saturated vertex. So we pick
  2955. $\ttm{t}$ and color it with the first available integer, which is
  2956. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2957. because they interfere with $\ttm{t}$.
  2958. \[
  2959. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2960. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2961. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2962. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2963. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2964. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2965. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2966. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2967. \draw (t1) to (rax);
  2968. \draw (t1) to (z);
  2969. \draw (z) to (y);
  2970. \draw (z) to (w);
  2971. \draw (x) to (w);
  2972. \draw (y) to (w);
  2973. \draw (v) to (w);
  2974. \end{tikzpicture}
  2975. \]
  2976. We repeat the process, selecting another maximally saturated
  2977. vertex, which is \code{z}, and color it with the first available
  2978. number, which is $1$. We add $1$ to the saturations for the
  2979. neighboring vertices \code{t}, \code{y}, and \code{w}.
  2980. \[
  2981. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2982. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2983. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  2984. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2985. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2986. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  2987. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  2988. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2989. \draw (t1) to (rax);
  2990. \draw (t1) to (z);
  2991. \draw (z) to (y);
  2992. \draw (z) to (w);
  2993. \draw (x) to (w);
  2994. \draw (y) to (w);
  2995. \draw (v) to (w);
  2996. \end{tikzpicture}
  2997. \]
  2998. The most saturated vertices are now \code{w} and \code{y}. We color
  2999. \code{w} with the first available color, which is $0$.
  3000. \[
  3001. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3002. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3003. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3004. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3005. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3006. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3007. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3008. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3009. \draw (t1) to (rax);
  3010. \draw (t1) to (z);
  3011. \draw (z) to (y);
  3012. \draw (z) to (w);
  3013. \draw (x) to (w);
  3014. \draw (y) to (w);
  3015. \draw (v) to (w);
  3016. \end{tikzpicture}
  3017. \]
  3018. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3019. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3020. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3021. and \code{z}, whose colors are $0$ and $1$ respectively.
  3022. \[
  3023. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3024. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3025. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3026. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3027. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3028. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3029. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3030. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3031. \draw (t1) to (rax);
  3032. \draw (t1) to (z);
  3033. \draw (z) to (y);
  3034. \draw (z) to (w);
  3035. \draw (x) to (w);
  3036. \draw (y) to (w);
  3037. \draw (v) to (w);
  3038. \end{tikzpicture}
  3039. \]
  3040. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3041. \[
  3042. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3043. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3044. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3045. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3046. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3047. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3048. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3049. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3050. \draw (t1) to (rax);
  3051. \draw (t1) to (z);
  3052. \draw (z) to (y);
  3053. \draw (z) to (w);
  3054. \draw (x) to (w);
  3055. \draw (y) to (w);
  3056. \draw (v) to (w);
  3057. \end{tikzpicture}
  3058. \]
  3059. In the last step of the algorithm, we color \code{x} with $1$.
  3060. \[
  3061. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3062. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3063. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3064. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3065. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3066. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3067. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3068. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3069. \draw (t1) to (rax);
  3070. \draw (t1) to (z);
  3071. \draw (z) to (y);
  3072. \draw (z) to (w);
  3073. \draw (x) to (w);
  3074. \draw (y) to (w);
  3075. \draw (v) to (w);
  3076. \end{tikzpicture}
  3077. \]
  3078. With the coloring complete, we finalize the assignment of variables to
  3079. registers and stack locations. Recall that if we have $k$ registers to
  3080. use for allocation, we map the first $k$ colors to registers and the
  3081. rest to stack locations. Suppose for the moment that we have just one
  3082. register to use for register allocation, \key{rcx}. Then the following
  3083. is the mapping of colors to registers and stack allocations.
  3084. \[
  3085. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3086. \]
  3087. Putting this mapping together with the above coloring of the
  3088. variables, we arrive at the following assignment of variables to
  3089. registers and stack locations.
  3090. \begin{gather*}
  3091. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3092. \ttm{w} \mapsto \key{\%rcx}, \,
  3093. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3094. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3095. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3096. \ttm{t} \mapsto \key{\%rcx} \}
  3097. \end{gather*}
  3098. Applying this assignment to our running example, on the left, yields
  3099. the program on the right.
  3100. % why frame size of 32? -JGS
  3101. \begin{center}
  3102. \begin{minipage}{0.3\textwidth}
  3103. \begin{lstlisting}
  3104. movq $1, v
  3105. movq $42, w
  3106. movq v, x
  3107. addq $7, x
  3108. movq x, y
  3109. movq x, z
  3110. addq w, z
  3111. movq y, t
  3112. negq t
  3113. movq z, %rax
  3114. addq t, %rax
  3115. jmp conclusion
  3116. \end{lstlisting}
  3117. \end{minipage}
  3118. $\Rightarrow\qquad$
  3119. \begin{minipage}{0.45\textwidth}
  3120. \begin{lstlisting}
  3121. movq $1, %rcx
  3122. movq $42, %rcx
  3123. movq %rcx, -8(%rbp)
  3124. addq $7, -8(%rbp)
  3125. movq -8(%rbp), -16(%rbp)
  3126. movq -8(%rbp), -8(%rbp)
  3127. addq %rcx, -8(%rbp)
  3128. movq -16(%rbp), %rcx
  3129. negq %rcx
  3130. movq -8(%rbp), %rax
  3131. addq %rcx, %rax
  3132. jmp conclusion
  3133. \end{lstlisting}
  3134. \end{minipage}
  3135. \end{center}
  3136. The resulting program is almost an x86 program. The remaining step is
  3137. the patch instructions pass. In this example, the trivial move of
  3138. \code{-8(\%rbp)} to itself is deleted and the addition of
  3139. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3140. \code{rax} as follows.
  3141. \begin{lstlisting}
  3142. movq -8(%rbp), %rax
  3143. addq %rax, -16(%rbp)
  3144. \end{lstlisting}
  3145. An overview of all of the passes involved in register allocation is
  3146. shown in Figure~\ref{fig:reg-alloc-passes}.
  3147. \begin{figure}[tbp]
  3148. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3149. \node (R1) at (0,2) {\large $R_1$};
  3150. \node (R1-2) at (3,2) {\large $R_1$};
  3151. \node (R1-3) at (6,2) {\large $R_1$};
  3152. \node (C0-1) at (3,0) {\large $C_0$};
  3153. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3154. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3155. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3156. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3157. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3158. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3159. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3160. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3161. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3162. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3163. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3164. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3165. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3166. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3167. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3168. \end{tikzpicture}
  3169. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3170. \label{fig:reg-alloc-passes}
  3171. \end{figure}
  3172. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3173. \small
  3174. \begin{tcolorbox}[title=Priority Queue]
  3175. A \emph{priority queue} is a collection of items in which the
  3176. removal of items is governed by priority. In a ``min'' queue,
  3177. lower priority items are removed first. An implementation is in
  3178. \code{priority\_queue.rkt} of the support code. \index{priority
  3179. queue} \index{minimum priority queue}
  3180. \begin{description}
  3181. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3182. priority queue that uses the $\itm{cmp}$ predicate to determine
  3183. whether its first argument has lower or equal priority to its
  3184. second argument.
  3185. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3186. items in the queue.
  3187. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3188. the item into the queue and returns a handle for the item in the
  3189. queue.
  3190. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3191. the lowest priority.
  3192. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3193. notifices the queue the the priority has decreased for the item
  3194. associated with the given handle.
  3195. \end{description}
  3196. \end{tcolorbox}
  3197. \end{wrapfigure}
  3198. We recommend creating a helper function named \code{color-graph} that
  3199. takes an interference graph and a list of all the variables in the
  3200. program. This function should return a mapping of variables to their
  3201. colors (represented as natural numbers). By creating this helper
  3202. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3203. when you add support for functions. To prioritize the process of
  3204. highly saturated nodes inside your \code{color-graph} function, we
  3205. recommend using the priority queue data structure (see the side bar on
  3206. the right). Note that you will also need to maintain a mapping from
  3207. variables to their ``handles'' in the priority queue so that you can
  3208. notify the priority queue when their saturation changes.
  3209. Once you have obtained the coloring from \code{color-graph}, you can
  3210. assign the variables to registers or stack locations and then reuse
  3211. code from the \code{assign-homes} pass from
  3212. Section~\ref{sec:assign-r1} to replace the variables with their
  3213. assigned location.
  3214. \begin{exercise}\normalfont
  3215. Implement the compiler pass \code{allocate-registers}, which should come
  3216. after the \code{build-interference} pass. The three new passes,
  3217. \code{uncover-live}, \code{build-interference}, and
  3218. \code{allocate-registers} replace the \code{assign-homes} pass of
  3219. Section~\ref{sec:assign-r1}.
  3220. Test your updated compiler by creating new example programs that
  3221. exercise all of the register allocation algorithm, such as forcing
  3222. variables to be spilled to the stack.
  3223. \end{exercise}
  3224. \section{Print x86 and Conventions for Registers}
  3225. \label{sec:print-x86-reg-alloc}
  3226. \index{calling conventions}
  3227. \index{prelude}\index{conclusion}
  3228. Recall that the \code{print-x86} pass generates the prelude and
  3229. conclusion instructions for the \code{main} function.
  3230. %
  3231. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3232. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3233. reason for this is that our \code{main} function must adhere to the
  3234. x86 calling conventions that we described in
  3235. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3236. allocator assigned variables to other callee-saved registers
  3237. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3238. saved to the stack in the prelude and restored in the conclusion. The
  3239. simplest approach is to save and restore all of the callee-saved
  3240. registers. The more efficient approach is to keep track of which
  3241. callee-saved registers were used and only save and restore
  3242. them. Either way, make sure to take this use of stack space into
  3243. account when you are calculating the size of the frame and adjusting
  3244. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3245. frame needs to be a multiple of 16 bytes!
  3246. \section{Challenge: Move Biasing}
  3247. \label{sec:move-biasing}
  3248. \index{move biasing}
  3249. This section describes an optional enhancement to register allocation
  3250. for those students who are looking for an extra challenge or who have
  3251. a deeper interest in register allocation.
  3252. We return to the running example, but we remove the supposition that
  3253. we only have one register to use. So we have the following mapping of
  3254. color numbers to registers.
  3255. \[
  3256. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3257. \]
  3258. Using the same assignment of variables to color numbers that was
  3259. produced by the register allocator described in the last section, we
  3260. get the following program.
  3261. \begin{minipage}{0.3\textwidth}
  3262. \begin{lstlisting}
  3263. movq $1, v
  3264. movq $42, w
  3265. movq v, x
  3266. addq $7, x
  3267. movq x, y
  3268. movq x, z
  3269. addq w, z
  3270. movq y, t
  3271. negq t
  3272. movq z, %rax
  3273. addq t, %rax
  3274. jmp conclusion
  3275. \end{lstlisting}
  3276. \end{minipage}
  3277. $\Rightarrow\qquad$
  3278. \begin{minipage}{0.45\textwidth}
  3279. \begin{lstlisting}
  3280. movq $1, %rcx
  3281. movq $42, $rbx
  3282. movq %rcx, %rcx
  3283. addq $7, %rcx
  3284. movq %rcx, %rdx
  3285. movq %rcx, %rcx
  3286. addq %rbx, %rcx
  3287. movq %rdx, %rbx
  3288. negq %rbx
  3289. movq %rcx, %rax
  3290. addq %rbx, %rax
  3291. jmp conclusion
  3292. \end{lstlisting}
  3293. \end{minipage}
  3294. In the above output code there are two \key{movq} instructions that
  3295. can be removed because their source and target are the same. However,
  3296. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3297. register, we could instead remove three \key{movq} instructions. We
  3298. can accomplish this by taking into account which variables appear in
  3299. \key{movq} instructions with which other variables.
  3300. We say that two variables $p$ and $q$ are \emph{move
  3301. related}\index{move related} if they participate together in a
  3302. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3303. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3304. for a variable, it should prefer a color that has already been used
  3305. for a move-related variable (assuming that they do not interfere). Of
  3306. course, this preference should not override the preference for
  3307. registers over stack locations. This preference should be used as a
  3308. tie breaker when choosing between registers or when choosing between
  3309. stack locations.
  3310. We recommend representing the move relationships in a graph, similar
  3311. to how we represented interference. The following is the \emph{move
  3312. graph} for our running example.
  3313. \[
  3314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3315. \node (rax) at (0,0) {$\ttm{rax}$};
  3316. \node (t) at (0,2) {$\ttm{t}$};
  3317. \node (z) at (3,2) {$\ttm{z}$};
  3318. \node (x) at (6,2) {$\ttm{x}$};
  3319. \node (y) at (3,0) {$\ttm{y}$};
  3320. \node (w) at (6,0) {$\ttm{w}$};
  3321. \node (v) at (9,0) {$\ttm{v}$};
  3322. \draw (v) to (x);
  3323. \draw (x) to (y);
  3324. \draw (x) to (z);
  3325. \draw (y) to (t);
  3326. \end{tikzpicture}
  3327. \]
  3328. Now we replay the graph coloring, pausing to see the coloring of
  3329. \code{y}. Recall the following configuration. The most saturated vertices
  3330. were \code{w} and \code{y}.
  3331. \[
  3332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3333. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3334. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3335. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3336. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3337. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3338. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3339. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3340. \draw (t1) to (rax);
  3341. \draw (t1) to (z);
  3342. \draw (z) to (y);
  3343. \draw (z) to (w);
  3344. \draw (x) to (w);
  3345. \draw (y) to (w);
  3346. \draw (v) to (w);
  3347. \end{tikzpicture}
  3348. \]
  3349. %
  3350. Last time we chose to color \code{w} with $0$. But this time we see
  3351. that \code{w} is not move related to any vertex, but \code{y} is move
  3352. related to \code{t}. So we choose to color \code{y} the same color,
  3353. $0$.
  3354. \[
  3355. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3356. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3357. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3358. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3359. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3360. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3361. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3362. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3363. \draw (t1) to (rax);
  3364. \draw (t1) to (z);
  3365. \draw (z) to (y);
  3366. \draw (z) to (w);
  3367. \draw (x) to (w);
  3368. \draw (y) to (w);
  3369. \draw (v) to (w);
  3370. \end{tikzpicture}
  3371. \]
  3372. Now \code{w} is the most saturated, so we color it $2$.
  3373. \[
  3374. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3375. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3376. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3377. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3378. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3379. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3380. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3381. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3382. \draw (t1) to (rax);
  3383. \draw (t1) to (z);
  3384. \draw (z) to (y);
  3385. \draw (z) to (w);
  3386. \draw (x) to (w);
  3387. \draw (y) to (w);
  3388. \draw (v) to (w);
  3389. \end{tikzpicture}
  3390. \]
  3391. At this point, vertices \code{x} and \code{v} are most saturated, but
  3392. \code{x} is move related to \code{y} and \code{z}, so we color
  3393. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3394. \[
  3395. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3396. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3397. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3398. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3399. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3400. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3401. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3402. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3403. \draw (t1) to (rax);
  3404. \draw (t) to (z);
  3405. \draw (z) to (y);
  3406. \draw (z) to (w);
  3407. \draw (x) to (w);
  3408. \draw (y) to (w);
  3409. \draw (v) to (w);
  3410. \end{tikzpicture}
  3411. \]
  3412. So we have the following assignment of variables to registers.
  3413. \begin{gather*}
  3414. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3415. \ttm{w} \mapsto \key{\%rdx}, \,
  3416. \ttm{x} \mapsto \key{\%rbx}, \,
  3417. \ttm{y} \mapsto \key{\%rbx}, \,
  3418. \ttm{z} \mapsto \key{\%rcx}, \,
  3419. \ttm{t} \mapsto \key{\%rbx} \}
  3420. \end{gather*}
  3421. We apply this register assignment to the running example, on the left,
  3422. to obtain the code on right.
  3423. \begin{minipage}{0.3\textwidth}
  3424. \begin{lstlisting}
  3425. movq $1, v
  3426. movq $42, w
  3427. movq v, x
  3428. addq $7, x
  3429. movq x, y
  3430. movq x, z
  3431. addq w, z
  3432. movq y, t
  3433. negq t
  3434. movq z, %rax
  3435. addq t, %rax
  3436. jmp conclusion
  3437. \end{lstlisting}
  3438. \end{minipage}
  3439. $\Rightarrow\qquad$
  3440. \begin{minipage}{0.45\textwidth}
  3441. \begin{lstlisting}
  3442. movq $1, %rbx
  3443. movq $42, %rdx
  3444. movq %rbx, %rbx
  3445. addq $7, %rbx
  3446. movq %rbx, %rbx
  3447. movq %rbx, %rcx
  3448. addq %rdx, %rcx
  3449. movq %rbx, %rbx
  3450. negq %rbx
  3451. movq %rcx, %rax
  3452. addq %rbx, %rax
  3453. jmp conclusion
  3454. \end{lstlisting}
  3455. \end{minipage}
  3456. The \code{patch-instructions} then removes the three trivial moves
  3457. from \key{rbx} to \key{rbx} to obtain the following result.
  3458. \begin{minipage}{0.45\textwidth}
  3459. \begin{lstlisting}
  3460. movq $1, %rbx
  3461. movq $42, %rdx
  3462. addq $7, %rbx
  3463. movq %rbx, %rcx
  3464. addq %rdx, %rcx
  3465. negq %rbx
  3466. movq %rcx, %rax
  3467. addq %rbx, %rax
  3468. jmp conclusion
  3469. \end{lstlisting}
  3470. \end{minipage}
  3471. \begin{exercise}\normalfont
  3472. Change your implementation of \code{allocate-registers} to take move
  3473. biasing into account. Make sure that your compiler still passes all of
  3474. the previous tests. Create two new tests that include at least one
  3475. opportunity for move biasing and visually inspect the output x86
  3476. programs to make sure that your move biasing is working properly.
  3477. \end{exercise}
  3478. \margincomment{\footnotesize To do: another neat challenge would be to do
  3479. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3480. \section{Output of the Running Example}
  3481. \label{sec:reg-alloc-output}
  3482. \index{prelude}\index{conclusion}
  3483. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3484. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3485. and move biasing. To demonstrate both the use of registers and the
  3486. stack, we have limited the register allocator to use just two
  3487. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3488. \code{main} function, we push \code{rbx} onto the stack because it is
  3489. a callee-saved register and it was assigned to variable by the
  3490. register allocator. We substract \code{8} from the \code{rsp} at the
  3491. end of the prelude to reserve space for the one spilled variable.
  3492. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3493. Moving on the the \code{start} block, we see how the registers were
  3494. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3495. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3496. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3497. that the prelude saved the callee-save register \code{rbx} onto the
  3498. stack. The spilled variables must be placed lower on the stack than
  3499. the saved callee-save registers, so in this case \code{w} is placed at
  3500. \code{-16(\%rbp)}.
  3501. In the \code{conclusion}, we undo the work that was done in the
  3502. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3503. spilled variables), then we pop the old values of \code{rbx} and
  3504. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3505. return control to the operating system.
  3506. \begin{figure}[tbp]
  3507. % s0_28.rkt
  3508. % (use-minimal-set-of-registers! #t)
  3509. % and only rbx rcx
  3510. % tmp 0 rbx
  3511. % z 1 rcx
  3512. % y 0 rbx
  3513. % w 2 16(%rbp)
  3514. % v 0 rbx
  3515. % x 0 rbx
  3516. \begin{lstlisting}
  3517. start:
  3518. movq $1, %rbx
  3519. movq $42, -16(%rbp)
  3520. addq $7, %rbx
  3521. movq %rbx, %rcx
  3522. addq -16(%rbp), %rcx
  3523. negq %rbx
  3524. movq %rcx, %rax
  3525. addq %rbx, %rax
  3526. jmp conclusion
  3527. .globl main
  3528. main:
  3529. pushq %rbp
  3530. movq %rsp, %rbp
  3531. pushq %rbx
  3532. subq $8, %rsp
  3533. jmp start
  3534. conclusion:
  3535. addq $8, %rsp
  3536. popq %rbx
  3537. popq %rbp
  3538. retq
  3539. \end{lstlisting}
  3540. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3541. \label{fig:running-example-x86}
  3542. \end{figure}
  3543. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3544. \chapter{Booleans and Control Flow}
  3545. \label{ch:bool-types}
  3546. \index{Boolean}
  3547. \index{control flow}
  3548. \index{conditional expression}
  3549. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3550. integers. In this chapter we add a second kind of value, the Booleans,
  3551. to create the $R_2$ language. The Boolean values \emph{true} and
  3552. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3553. Racket. The $R_2$ language includes several operations that involve
  3554. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3555. conditional \key{if} expression. With the addition of \key{if}
  3556. expressions, programs can have non-trivial control flow which which
  3557. significantly impacts the \code{explicate-control} and the liveness
  3558. analysis for register allocation. Also, because we now have two kinds
  3559. of values, we need to handle programs that apply an operation to the
  3560. wrong kind of value, such as \code{(not 1)}.
  3561. There are two language design options for such situations. One option
  3562. is to signal an error and the other is to provide a wider
  3563. interpretation of the operation. The Racket language uses a mixture of
  3564. these two options, depending on the operation and the kind of
  3565. value. For example, the result of \code{(not 1)} in Racket is
  3566. \code{\#f} because Racket treats non-zero integers as if they were
  3567. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3568. error in Racket stating that \code{car} expects a pair.
  3569. The Typed Racket language makes similar design choices as Racket,
  3570. except much of the error detection happens at compile time instead of
  3571. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3572. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3573. reports a compile-time error because Typed Racket expects the type of
  3574. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3575. For the $R_2$ language we choose to be more like Typed Racket in that
  3576. we shall perform type checking during compilation. In
  3577. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3578. is, how to compile a dynamically typed language like Racket. The
  3579. $R_2$ language is a subset of Typed Racket but by no means includes
  3580. all of Typed Racket. For many operations we take a narrower
  3581. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3582. This chapter is organized as follows. We begin by defining the syntax
  3583. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3584. then introduce the idea of type checking and build a type checker for
  3585. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3586. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3587. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3588. how our compiler passes need to change to accommodate Booleans and
  3589. conditional control flow.
  3590. \section{The $R_2$ Language}
  3591. \label{sec:r2-lang}
  3592. The concrete syntax of the $R_2$ language is defined in
  3593. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3594. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3595. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3596. and the conditional \code{if} expression. Also, we expand the
  3597. operators to include
  3598. \begin{enumerate}
  3599. \item subtraction on integers,
  3600. \item the logical operators \key{and}, \key{or} and \key{not},
  3601. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3602. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3603. comparing integers.
  3604. \end{enumerate}
  3605. \begin{figure}[tp]
  3606. \centering
  3607. \fbox{
  3608. \begin{minipage}{0.96\textwidth}
  3609. \[
  3610. \begin{array}{lcl}
  3611. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3612. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3613. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3614. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3615. &\mid& \itm{bool}
  3616. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3617. \mid (\key{not}\;\Exp) \\
  3618. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3619. R_2 &::=& \Exp
  3620. \end{array}
  3621. \]
  3622. \end{minipage}
  3623. }
  3624. \caption{The concrete syntax of $R_2$, extending $R_1$
  3625. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3626. \label{fig:r2-concrete-syntax}
  3627. \end{figure}
  3628. \begin{figure}[tp]
  3629. \centering
  3630. \fbox{
  3631. \begin{minipage}{0.96\textwidth}
  3632. \[
  3633. \begin{array}{lcl}
  3634. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3635. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3636. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3637. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3638. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3639. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3640. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3641. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3642. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3643. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3644. \end{array}
  3645. \]
  3646. \end{minipage}
  3647. }
  3648. \caption{The abstract syntax of $R_2$.}
  3649. \label{fig:r2-syntax}
  3650. \end{figure}
  3651. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3652. the parts that are the same as the interpreter for $R_1$
  3653. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3654. evaluate to the corresponding Boolean values. The conditional
  3655. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3656. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3657. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3658. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3659. you might expect, but note that the \code{and} operation is
  3660. short-circuiting. That is, given the expression
  3661. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3662. $e_1$ evaluates to \code{\#f}.
  3663. With the addition of the comparison operations, there are quite a few
  3664. primitive operations and the interpreter code for them could become
  3665. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3666. out the different parts of the code for primitive operations into the
  3667. \code{interp-op} function and the similar parts of the code into the
  3668. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3669. do not use \code{interp-op} for the \code{and} operation because of
  3670. the short-circuiting behavior in the order of evaluation of its
  3671. arguments.
  3672. \begin{figure}[tbp]
  3673. \begin{lstlisting}
  3674. (define (interp-op op)
  3675. (match op
  3676. ...
  3677. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3678. ['eq? (lambda (v1 v2)
  3679. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3680. (and (boolean? v1) (boolean? v2)))
  3681. (eq? v1 v2)]))]
  3682. ['< (lambda (v1 v2)
  3683. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3684. ['<= (lambda (v1 v2)
  3685. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3686. ['> (lambda (v1 v2)
  3687. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3688. ['>= (lambda (v1 v2)
  3689. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3690. [else (error 'interp-op "unknown operator")]))
  3691. (define (interp-exp env)
  3692. (lambda (e)
  3693. (define recur (interp-exp env))
  3694. (match e
  3695. ...
  3696. [(Bool b) b]
  3697. [(If cnd thn els)
  3698. (define b (recur cnd))
  3699. (match b
  3700. [#t (recur thn)]
  3701. [#f (recur els)])]
  3702. [(Prim 'and (list e1 e2))
  3703. (define v1 (recur e1))
  3704. (match v1
  3705. [#t (match (recur e2) [#t #t] [#f #f])]
  3706. [#f #f])]
  3707. [(Prim op args)
  3708. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3709. )))
  3710. (define (interp-R2 p)
  3711. (match p
  3712. [(Program info e)
  3713. ((interp-exp '()) e)]
  3714. ))
  3715. \end{lstlisting}
  3716. \caption{Interpreter for the $R_2$ language.}
  3717. \label{fig:interp-R2}
  3718. \end{figure}
  3719. \section{Type Checking $R_2$ Programs}
  3720. \label{sec:type-check-r2}
  3721. \index{type checking}
  3722. \index{semantic analysis}
  3723. It is helpful to think about type checking in two complementary
  3724. ways. A type checker predicts the type of value that will be produced
  3725. by each expression in the program. For $R_2$, we have just two types,
  3726. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3727. \begin{lstlisting}
  3728. (+ 10 (- (+ 12 20)))
  3729. \end{lstlisting}
  3730. produces an \key{Integer} while
  3731. \begin{lstlisting}
  3732. (and (not #f) #t)
  3733. \end{lstlisting}
  3734. produces a \key{Boolean}.
  3735. Another way to think about type checking is that it enforces a set of
  3736. rules about which operators can be applied to which kinds of
  3737. values. For example, our type checker for $R_2$ will signal an error
  3738. for the below expression because, as we have seen above, the
  3739. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3740. checker enforces the rule that the argument of \code{not} must be a
  3741. \key{Boolean}.
  3742. \begin{lstlisting}
  3743. (not (+ 10 (- (+ 12 20))))
  3744. \end{lstlisting}
  3745. The type checker for $R_2$ is a structurally recursive function over
  3746. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3747. the \code{type-check-exp} function. Given an input expression
  3748. \code{e}, the type checker either returns a type (\key{Integer} or
  3749. \key{Boolean}) or it signals an error. The type of an integer literal
  3750. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3751. To handle variables, the type checker uses an environment that maps
  3752. variables to types. Consider the clause for \key{let}. We type check
  3753. the initializing expression to obtain its type \key{T} and then
  3754. associate type \code{T} with the variable \code{x} in the
  3755. environment. When the type checker encounters a use of variable
  3756. \code{x} in the body of the \key{let}, it can find its type in the
  3757. environment.
  3758. \begin{figure}[tbp]
  3759. \begin{lstlisting}
  3760. (define (type-check-exp env)
  3761. (lambda (e)
  3762. (match e
  3763. [(Var x) (dict-ref env x)]
  3764. [(Int n) 'Integer]
  3765. [(Bool b) 'Boolean]
  3766. [(Let x e body)
  3767. (define Te ((type-check-exp env) e))
  3768. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3769. Tb]
  3770. ...
  3771. [else
  3772. (error "type-check-exp couldn't match" e)])))
  3773. (define (type-check env)
  3774. (lambda (e)
  3775. (match e
  3776. [(Program info body)
  3777. (define Tb ((type-check-exp '()) body))
  3778. (unless (equal? Tb 'Integer)
  3779. (error "result of the program must be an integer, not " Tb))
  3780. (Program info body)]
  3781. )))
  3782. \end{lstlisting}
  3783. \caption{Skeleton of a type checker for the $R_2$ language.}
  3784. \label{fig:type-check-R2}
  3785. \end{figure}
  3786. \begin{exercise}\normalfont
  3787. Complete the implementation of \code{type-check}. Test your type
  3788. checker using \code{interp-tests} and \code{compiler-tests} by passing
  3789. the \code{type-check} function as the second argument. Create 10 new
  3790. example programs in $R_2$ that you choose based on how thoroughly they
  3791. test you type checking function. Half of the example programs should
  3792. have a type error to make sure that your type checker properly rejects
  3793. them. For those programs, to signal that a type error is expected,
  3794. create an empty file with the same base name but with file extension
  3795. \code{.tyerr}. For example, if the test \code{r2\_14.rkt} is expected
  3796. to error, then create an empty file named \code{r2\_14.tyerr}. The
  3797. other half of the example programs should not have type errors. Note
  3798. that if your type checker does not signal an error for a program, then
  3799. interpreting that program should not encounter an error. If it does,
  3800. there is something wrong with your type checker.
  3801. \end{exercise}
  3802. \section{Shrink the $R_2$ Language}
  3803. \label{sec:shrink-r2}
  3804. The $R_2$ language includes several operators that are easily
  3805. expressible in terms of other operators. For example, subtraction is
  3806. expressible in terms of addition and negation.
  3807. \[
  3808. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3809. \]
  3810. Several of the comparison operations are expressible in terms of
  3811. less-than and logical negation.
  3812. \[
  3813. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3814. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3815. \]
  3816. The \key{let} is needed in the above translation to ensure that
  3817. expression $e_1$ is evaluated before $e_2$.
  3818. By performing these translations near the front-end of the compiler,
  3819. the later passes of the compiler do not need to deal with these
  3820. constructs, making those passes shorter. On the other hand, sometimes
  3821. these translations make it more difficult to generate the most
  3822. efficient code with respect to the number of instructions. However,
  3823. these differences typically do not affect the number of accesses to
  3824. memory, which is the primary factor that determines execution time on
  3825. modern computer architectures.
  3826. \begin{exercise}\normalfont
  3827. Implement the pass \code{shrink} that removes subtraction,
  3828. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3829. by translating them to other constructs in $R_2$. Create tests to
  3830. make sure that the behavior of all of these constructs stays the
  3831. same after translation.
  3832. \end{exercise}
  3833. \section{The x86$_1$ Language}
  3834. \label{sec:x86-1}
  3835. \index{x86}
  3836. To implement the new logical operations, the comparison operations,
  3837. and the \key{if} expression, we need to delve further into the x86
  3838. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3839. the concrete and abstract syntax for a larger subset of x86 that
  3840. includes instructions for logical operations, comparisons, and
  3841. conditional jumps.
  3842. One small challenge is that x86 does not provide an instruction that
  3843. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3844. However, the \code{xorq} instruction can be used to encode \code{not}.
  3845. The \key{xorq} instruction takes two arguments, performs a pairwise
  3846. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3847. and writes the results into its second argument. Recall the truth
  3848. table for exclusive-or:
  3849. \begin{center}
  3850. \begin{tabular}{l|cc}
  3851. & 0 & 1 \\ \hline
  3852. 0 & 0 & 1 \\
  3853. 1 & 1 & 0
  3854. \end{tabular}
  3855. \end{center}
  3856. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3857. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3858. for the bit $1$, the result is the opposite of the second bit. Thus,
  3859. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3860. the first argument:
  3861. \[
  3862. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3863. \qquad\Rightarrow\qquad
  3864. \begin{array}{l}
  3865. \key{movq}~ \Arg\key{,} \Var\\
  3866. \key{xorq}~ \key{\$1,} \Var
  3867. \end{array}
  3868. \]
  3869. \begin{figure}[tp]
  3870. \fbox{
  3871. \begin{minipage}{0.96\textwidth}
  3872. \[
  3873. \begin{array}{lcl}
  3874. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3875. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3876. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3877. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3878. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3879. \key{subq} \; \Arg\key{,} \Arg \mid
  3880. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3881. && \gray{ \key{callq} \; \itm{label} \mid
  3882. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3883. && \gray{ \itm{label}\key{:}\; \Instr }
  3884. \mid \key{xorq}~\Arg\key{,}~\Arg
  3885. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3886. && \key{set}cc~\Arg
  3887. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3888. \mid \key{j}cc~\itm{label}
  3889. \\
  3890. x86_1 &::= & \gray{ \key{.globl main} }\\
  3891. & & \gray{ \key{main:} \; \Instr\ldots }
  3892. \end{array}
  3893. \]
  3894. \end{minipage}
  3895. }
  3896. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3897. \label{fig:x86-1-concrete}
  3898. \end{figure}
  3899. \begin{figure}[tp]
  3900. \fbox{
  3901. \begin{minipage}{0.96\textwidth}
  3902. \small
  3903. \[
  3904. \begin{array}{lcl}
  3905. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3906. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3907. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3908. \mid \BYTEREG{\itm{bytereg}} \\
  3909. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3910. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3911. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3912. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3913. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3914. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3915. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3916. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3917. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3918. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3919. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3920. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3921. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3922. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3923. \end{array}
  3924. \]
  3925. \end{minipage}
  3926. }
  3927. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3928. \label{fig:x86-1}
  3929. \end{figure}
  3930. Next we consider the x86 instructions that are relevant for compiling
  3931. the comparison operations. The \key{cmpq} instruction compares its two
  3932. arguments to determine whether one argument is less than, equal, or
  3933. greater than the other argument. The \key{cmpq} instruction is unusual
  3934. regarding the order of its arguments and where the result is
  3935. placed. The argument order is backwards: if you want to test whether
  3936. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3937. \key{cmpq} is placed in the special EFLAGS register. This register
  3938. cannot be accessed directly but it can be queried by a number of
  3939. instructions, including the \key{set} instruction. The \key{set}
  3940. instruction puts a \key{1} or \key{0} into its destination depending
  3941. on whether the comparison came out according to the condition code
  3942. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3943. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3944. The \key{set} instruction has an annoying quirk in that its
  3945. destination argument must be single byte register, such as \code{al}
  3946. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  3947. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  3948. then be used to move from a single byte register to a normal 64-bit
  3949. register.
  3950. The x86 instruction for conditional jump are relevant to the
  3951. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3952. updates the program counter to point to the instruction after the
  3953. indicated label depending on whether the result in the EFLAGS register
  3954. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3955. instruction falls through to the next instruction. The abstract
  3956. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3957. that it separates the instruction name from the condition code. For
  3958. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3959. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3960. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3961. instruction to set the EFLAGS register.
  3962. \section{The $C_1$ Intermediate Language}
  3963. \label{sec:c1}
  3964. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3965. we need to grow that intermediate language to handle the new features
  3966. in $R_2$: Booleans and conditional expressions.
  3967. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3968. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3969. particular, we add logical and comparison operators to the $\Exp$
  3970. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3971. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3972. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3973. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3974. sequence of statements may now end with a \code{goto} or a conditional
  3975. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3976. depending on the outcome of the comparison. In
  3977. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3978. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3979. and \key{goto}'s.
  3980. \begin{figure}[tbp]
  3981. \fbox{
  3982. \begin{minipage}{0.96\textwidth}
  3983. \small
  3984. \[
  3985. \begin{array}{lcl}
  3986. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3987. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3988. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3989. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3990. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3991. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3992. \mid \key{goto}~\itm{label}\key{;}\\
  3993. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3994. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3995. \end{array}
  3996. \]
  3997. \end{minipage}
  3998. }
  3999. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4000. \label{fig:c1-concrete-syntax}
  4001. \end{figure}
  4002. \begin{figure}[tp]
  4003. \fbox{
  4004. \begin{minipage}{0.96\textwidth}
  4005. \small
  4006. \[
  4007. \begin{array}{lcl}
  4008. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4009. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4010. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4011. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4012. &\mid& \UNIOP{\key{'not}}{\Atm}
  4013. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4014. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4015. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4016. \mid \GOTO{\itm{label}} \\
  4017. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4018. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4019. \end{array}
  4020. \]
  4021. \end{minipage}
  4022. }
  4023. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4024. (Figure~\ref{fig:c0-syntax}).}
  4025. \label{fig:c1-syntax}
  4026. \end{figure}
  4027. \clearpage
  4028. \section{Remove Complex Operands}
  4029. \label{sec:remove-complex-opera-R2}
  4030. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4031. \code{rco-atom} functions according to the definition of the output
  4032. language for this pass, $R_2^{\dagger}$, the administrative normal
  4033. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4034. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4035. three sub-expressions of an \code{If} are allowed to be complex
  4036. expressions in the output of \code{remove-complex-opera*}, but the
  4037. operands of \code{not} and the comparisons must be atoms. Regarding
  4038. the \code{If} form, it is particularly important to \textbf{not}
  4039. replace its condition with a temporary variable because that would
  4040. interfere with the generation of high-quality output in the
  4041. \code{explicate-control} pass.
  4042. \begin{figure}[tp]
  4043. \centering
  4044. \fbox{
  4045. \begin{minipage}{0.96\textwidth}
  4046. \[
  4047. \begin{array}{rcl}
  4048. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4049. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4050. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4051. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4052. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4053. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4054. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4055. \end{array}
  4056. \]
  4057. \end{minipage}
  4058. }
  4059. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4060. \label{fig:r2-anf-syntax}
  4061. \end{figure}
  4062. \section{Explicate Control}
  4063. \label{sec:explicate-control-r2}
  4064. Recall that the purpose of \code{explicate-control} is to make the
  4065. order of evaluation explicit in the syntax of the program. With the
  4066. addition of \key{if} in $R_2$ this get more interesting.
  4067. As a motivating example, consider the following program that has an
  4068. \key{if} expression nested in the predicate of another \key{if}.
  4069. % s1_41.rkt
  4070. \begin{center}
  4071. \begin{minipage}{0.96\textwidth}
  4072. \begin{lstlisting}
  4073. (let ([x (read)])
  4074. (let ([y (read)])
  4075. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4076. (+ y 2)
  4077. (+ y 10))))
  4078. \end{lstlisting}
  4079. \end{minipage}
  4080. \end{center}
  4081. %
  4082. The naive way to compile \key{if} and the comparison would be to
  4083. handle each of them in isolation, regardless of their context. Each
  4084. comparison would be translated into a \key{cmpq} instruction followed
  4085. by a couple instructions to move the result from the EFLAGS register
  4086. into a general purpose register or stack location. Each \key{if} would
  4087. be translated into the combination of a \key{cmpq} and a conditional
  4088. jump. The generated code for the inner \key{if} in the above example
  4089. would be as follows.
  4090. \begin{center}
  4091. \begin{minipage}{0.96\textwidth}
  4092. \begin{lstlisting}
  4093. ...
  4094. cmpq $1, x ;; (< x 1)
  4095. setl %al
  4096. movzbq %al, tmp
  4097. cmpq $1, tmp ;; (if (< x 1) ...)
  4098. je then_branch_1
  4099. jmp else_branch_1
  4100. ...
  4101. \end{lstlisting}
  4102. \end{minipage}
  4103. \end{center}
  4104. However, if we take context into account we can do better and reduce
  4105. the use of \key{cmpq} and EFLAG-accessing instructions.
  4106. One idea is to try and reorganize the code at the level of $R_2$,
  4107. pushing the outer \key{if} inside the inner one. This would yield the
  4108. following code.
  4109. \begin{center}
  4110. \begin{minipage}{0.96\textwidth}
  4111. \begin{lstlisting}
  4112. (let ([x (read)])
  4113. (let ([y (read)])
  4114. (if (< x 1)
  4115. (if (eq? x 0)
  4116. (+ y 2)
  4117. (+ y 10))
  4118. (if (eq? x 2)
  4119. (+ y 2)
  4120. (+ y 10)))))
  4121. \end{lstlisting}
  4122. \end{minipage}
  4123. \end{center}
  4124. Unfortunately, this approach duplicates the two branches, and a
  4125. compiler must never duplicate code!
  4126. We need a way to perform the above transformation, but without
  4127. duplicating code. The solution is straightforward if we think at the
  4128. level of x86 assembly: we can label the code for each of the branches
  4129. and insert jumps in all the places that need to execute the
  4130. branches. Put another way, we need to move away from abstract syntax
  4131. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  4132. use a standard program representation called a \emph{control flow
  4133. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4134. \index{control-flow graph}
  4135. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4136. each edge represents a jump to another block. The \key{Program}
  4137. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4138. as an alist mapping labels to basic blocks. Each basic block is
  4139. represented by the $\Tail$ non-terminal.
  4140. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4141. \code{remove-complex-opera*} pass and then the
  4142. \code{explicate-control} pass on the example program. We walk through
  4143. the output program and then discuss the algorithm.
  4144. %
  4145. Following the order of evaluation in the output of
  4146. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4147. and then the less-than-comparison to \code{1} in the predicate of the
  4148. inner \key{if}. In the output of \code{explicate-control}, in the
  4149. block labeled \code{start}, this becomes two assignment statements
  4150. followed by a conditional \key{goto} to label \code{block96} or
  4151. \code{block97}. The blocks associated with those labels contain the
  4152. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4153. respectively. Regarding the block labeled with \code{block96}, we
  4154. start with the comparison to \code{0} and then have a conditional
  4155. goto, either to label \code{block92} or label \code{block93}, which
  4156. indirectly take us to labels \code{block90} and \code{block91}, the
  4157. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4158. y 10)}. The story for the block labeled \code{block97} is similar.
  4159. \begin{figure}[tbp]
  4160. \begin{tabular}{lll}
  4161. \begin{minipage}{0.4\textwidth}
  4162. % s1_41.rkt
  4163. \begin{lstlisting}
  4164. (let ([x (read)])
  4165. (let ([y (read)])
  4166. (if (if (< x 1)
  4167. (eq? x 0)
  4168. (eq? x 2))
  4169. (+ y 2)
  4170. (+ y 10))))
  4171. \end{lstlisting}
  4172. \hspace{40pt}$\Downarrow$
  4173. \begin{lstlisting}
  4174. (let ([x (read)])
  4175. (let ([y (read)])
  4176. (if (if (< x 1)
  4177. (eq? x 0)
  4178. (eq? x 2))
  4179. (+ y 2)
  4180. (+ y 10))))
  4181. \end{lstlisting}
  4182. \end{minipage}
  4183. &
  4184. $\Rightarrow$
  4185. &
  4186. \begin{minipage}{0.55\textwidth}
  4187. \begin{lstlisting}
  4188. start:
  4189. x = (read);
  4190. y = (read);
  4191. if (< x 1)
  4192. goto block96;
  4193. else
  4194. goto block97;
  4195. block96:
  4196. if (eq? x 0)
  4197. goto block92;
  4198. else
  4199. goto block93;
  4200. block97:
  4201. if (eq? x 2)
  4202. goto block94;
  4203. else
  4204. goto block95;
  4205. block92:
  4206. goto block90;
  4207. block93:
  4208. goto block91;
  4209. block94:
  4210. goto block90;
  4211. block95:
  4212. goto block91;
  4213. block90:
  4214. return (+ y 2);
  4215. block91:
  4216. return (+ y 10);
  4217. \end{lstlisting}
  4218. \end{minipage}
  4219. \end{tabular}
  4220. \caption{Example translation from $R_2$ to $C_1$
  4221. via the \code{explicate-control}.}
  4222. \label{fig:explicate-control-s1-38}
  4223. \end{figure}
  4224. The nice thing about the output of \code{explicate-control} is that
  4225. there are no unnecessary comparisons and every comparison is part of a
  4226. conditional jump. The down-side of this output is that it includes
  4227. trivial blocks, such as the blocks labeled \code{block92} through
  4228. \code{block95}, that only jump to another block. We discuss a solution
  4229. to this problem in Section~\ref{sec:opt-jumps}.
  4230. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4231. \code{explicate-control} for $R_1$ using two mutually recursive
  4232. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4233. former function translates expressions in tail position whereas the
  4234. later function translates expressions on the right-hand-side of a
  4235. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4236. new kind of context to deal with: the predicate position of the
  4237. \key{if}. We need another function, \code{explicate-pred}, that takes
  4238. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4239. the then-branch and else-branch. The output of \code{explicate-pred}
  4240. is a block and a list of formerly \key{let}-bound variables.
  4241. Note that the three explicate functions need to construct a
  4242. control-flow graph, which we recommend they do via updates to a global
  4243. variable.
  4244. In the following paragraphs we consider the specific additions to the
  4245. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4246. of cases for the \code{explicate-pred} function.
  4247. The \code{explicate-tail} function needs an additional case for
  4248. \key{if}. The branches of the \key{if} inherit the current context, so
  4249. they are in tail position. Let $B_1$ be the result of
  4250. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4251. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4252. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4253. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4254. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4255. \key{if} as a whole translates to block $B_3$.
  4256. \[
  4257. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4258. \]
  4259. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4260. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4261. should not be confused with the labels for the blocks that appear in
  4262. the generated code. We initially construct unlabeled blocks; we only
  4263. attach labels to blocks when we add them to the control-flow graph, as
  4264. we shall see in the next case.
  4265. Next consider the case for \key{if} in the \code{explicate-assign}
  4266. function. The context of the \key{if} is an assignment to some
  4267. variable $x$ and then the control continues to some block $B_1$. The
  4268. code that we generate for both the ``then'' and ``else'' branches
  4269. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4270. add it to the control flow graph with a fresh label $\ell_1$. The
  4271. branches of the \key{if} inherit the current context, so that are in
  4272. assignment positions. Let $B_2$ be the result of applying
  4273. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4274. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4275. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4276. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4277. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4278. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4279. $B_4$.
  4280. \[
  4281. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4282. \]
  4283. The function \code{explicate-pred} will need a case for every
  4284. expression that can have type \code{Boolean}. We detail a few cases
  4285. here and leave the rest for the reader. The input to this function is
  4286. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4287. the enclosing \key{if}. Suppose the expression is the Boolean
  4288. \code{\#t}. Then we can perform a kind of partial evaluation
  4289. \index{partial evaluation} and translate it to the ``then'' branch
  4290. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4291. \[
  4292. \key{\#t} \quad\Rightarrow\quad B_1,
  4293. \qquad\qquad\qquad
  4294. \key{\#f} \quad\Rightarrow\quad B_2
  4295. \]
  4296. Next, suppose the expression is a less-than comparison. We translate
  4297. it to a conditional \code{goto}. We need labels for the two branches
  4298. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4299. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4300. less-than comparison is as follows.
  4301. \[
  4302. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4303. \begin{array}{l}
  4304. \key{if}~(\key{<}~e_1~e_2) \\
  4305. \qquad\key{goto}~\ell_1\key{;}\\
  4306. \key{else}\\
  4307. \qquad\key{goto}~\ell_2\key{;}
  4308. \end{array}
  4309. \]
  4310. The case for \key{if} in \code{explicate-pred} is particularly
  4311. illuminating as it deals with the challenges that we discussed above
  4312. regarding the example of the nested \key{if} expressions. Again, we
  4313. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4314. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4315. branches of the current \key{if} inherit their context from the
  4316. current one, that is, predicate context. So we apply
  4317. \code{explicate-pred} to the ``then'' branch with the two blocks
  4318. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4319. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4320. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4321. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4322. \[
  4323. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4324. \quad\Rightarrow\quad
  4325. B_5
  4326. \]
  4327. Finally, note that the way in which the \code{shrink} pass transforms
  4328. logical operations such as \code{and} and \code{or} can impact the
  4329. quality of code generated by \code{explicate-control}. For example,
  4330. consider the following program.
  4331. \begin{lstlisting}
  4332. (if (and (eq? (read) 0) (eq? (read) 1))
  4333. 0
  4334. 42)
  4335. \end{lstlisting}
  4336. The \code{and} operation should transform into something that the
  4337. \code{explicat-pred} function can still analyze and descend through to
  4338. reach the underlying \code{eq?} conditions. Ideally, your
  4339. \code{explicate-control} pass should generate code similar to the
  4340. following for the above program.\footnote{If the trivial blocks 17,
  4341. 18, and 20 bother you, take a look at the challenge problem in
  4342. Section~\ref{sec:opt-jumps}.}
  4343. \begin{center}
  4344. \begin{minipage}{0.45\textwidth}
  4345. \begin{lstlisting}
  4346. start:
  4347. tmp13 = (read);
  4348. if (eq? tmp13 0)
  4349. goto block19;
  4350. else
  4351. goto block20;
  4352. block19:
  4353. tmp14 = (read);
  4354. if (eq? tmp14 1)
  4355. goto block17;
  4356. else
  4357. goto block18;
  4358. \end{lstlisting}
  4359. \end{minipage}
  4360. \begin{minipage}{0.45\textwidth}
  4361. \begin{lstlisting}
  4362. block20:
  4363. goto block16;
  4364. block17:
  4365. goto block15;
  4366. block18:
  4367. goto block16;
  4368. block15:
  4369. return 0;
  4370. block16:
  4371. return 42;
  4372. \end{lstlisting}
  4373. \end{minipage}
  4374. \end{center}
  4375. \begin{exercise}\normalfont
  4376. Implement the pass \code{explicate-control} by adding the cases for
  4377. \key{if} to the functions for tail and assignment contexts, and
  4378. implement \code{explicate-pred} for predicate contexts. Create test
  4379. cases that exercise all of the new cases in the code for this pass.
  4380. \end{exercise}
  4381. \section{Select Instructions}
  4382. \label{sec:select-r2}
  4383. \index{instruction selection}
  4384. Recall that the \code{select-instructions} pass lowers from our
  4385. $C$-like intermediate representation to the pseudo-x86 language, which
  4386. is suitable for conducting register allocation. The pass is
  4387. implemented using three auxiliary functions, one for each of the
  4388. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4389. For $\Atm$, we have new cases for the Booleans. We take the usual
  4390. approach of encoding them as integers, with true as 1 and false as 0.
  4391. \[
  4392. \key{\#t} \Rightarrow \key{1}
  4393. \qquad
  4394. \key{\#f} \Rightarrow \key{0}
  4395. \]
  4396. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4397. be implemented in terms of \code{xorq} as we discussed at the
  4398. beginning of this section. Given an assignment
  4399. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4400. if the left-hand side $\itm{var}$ is
  4401. the same as $\Atm$, then just the \code{xorq} suffices.
  4402. \[
  4403. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4404. \quad\Rightarrow\quad
  4405. \key{xorq}~\key{\$}1\key{,}~\Var
  4406. \]
  4407. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4408. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4409. x86. Then we have
  4410. \[
  4411. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4412. \quad\Rightarrow\quad
  4413. \begin{array}{l}
  4414. \key{movq}~\Arg\key{,}~\Var\\
  4415. \key{xorq}~\key{\$}1\key{,}~\Var
  4416. \end{array}
  4417. \]
  4418. Next consider the cases for \code{eq?} and less-than comparison.
  4419. Translating these operations to x86 is slightly involved due to the
  4420. unusual nature of the \key{cmpq} instruction discussed above. We
  4421. recommend translating an assignment from \code{eq?} into the following
  4422. sequence of three instructions. \\
  4423. \begin{tabular}{lll}
  4424. \begin{minipage}{0.4\textwidth}
  4425. \begin{lstlisting}
  4426. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4427. \end{lstlisting}
  4428. \end{minipage}
  4429. &
  4430. $\Rightarrow$
  4431. &
  4432. \begin{minipage}{0.4\textwidth}
  4433. \begin{lstlisting}
  4434. cmpq |$\Arg_2$|, |$\Arg_1$|
  4435. sete %al
  4436. movzbq %al, |$\Var$|
  4437. \end{lstlisting}
  4438. \end{minipage}
  4439. \end{tabular} \\
  4440. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4441. and conditional \key{goto}. Both are straightforward to handle. A
  4442. \key{goto} becomes a jump instruction.
  4443. \[
  4444. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4445. \]
  4446. A conditional \key{goto} becomes a compare instruction followed
  4447. by a conditional jump (for ``then'') and the fall-through is
  4448. to a regular jump (for ``else'').\\
  4449. \begin{tabular}{lll}
  4450. \begin{minipage}{0.4\textwidth}
  4451. \begin{lstlisting}
  4452. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4453. goto |$\ell_1$|;
  4454. else
  4455. goto |$\ell_2$|;
  4456. \end{lstlisting}
  4457. \end{minipage}
  4458. &
  4459. $\Rightarrow$
  4460. &
  4461. \begin{minipage}{0.4\textwidth}
  4462. \begin{lstlisting}
  4463. cmpq |$\Arg_2$|, |$\Arg_1$|
  4464. je |$\ell_1$|
  4465. jmp |$\ell_2$|
  4466. \end{lstlisting}
  4467. \end{minipage}
  4468. \end{tabular} \\
  4469. \begin{exercise}\normalfont
  4470. Expand your \code{select-instructions} pass to handle the new features
  4471. of the $R_2$ language. Test the pass on all the examples you have
  4472. created and make sure that you have some test programs that use the
  4473. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4474. the output using the \code{interp-x86} interpreter
  4475. (Appendix~\ref{appendix:interp}).
  4476. \end{exercise}
  4477. \section{Register Allocation}
  4478. \label{sec:register-allocation-r2}
  4479. \index{register allocation}
  4480. The changes required for $R_2$ affect liveness analysis, building the
  4481. interference graph, and assigning homes, but the graph coloring
  4482. algorithm itself does not change.
  4483. \subsection{Liveness Analysis}
  4484. \label{sec:liveness-analysis-r2}
  4485. \index{liveness analysis}
  4486. Recall that for $R_1$ we implemented liveness analysis for a single
  4487. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4488. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4489. produces many basic blocks arranged in a control-flow graph. The first
  4490. question we need to consider is: what order should we process the
  4491. basic blocks? Recall that to perform liveness analysis, we need to
  4492. know the live-after set. If a basic block has no successor blocks
  4493. (i.e. no out-edges in the control flow graph), then it has an empty
  4494. live-after set and we can immediately apply liveness analysis to
  4495. it. If a basic block has some successors, then we need to complete
  4496. liveness analysis on those blocks first. Furthermore, we know that
  4497. the control flow graph does not contain any cycles because $R_2$ does
  4498. not include loops
  4499. %
  4500. \footnote{If we were to add loops to the language, then the CFG could
  4501. contain cycles and we would instead need to use the classic worklist
  4502. algorithm for computing the fixed point of the liveness
  4503. analysis~\citep{Aho:1986qf}.}.
  4504. %
  4505. Returning to the question of what order should we process the basic
  4506. blocks, the answer is reverse topological order. We recommend using
  4507. the \code{tsort} (topological sort) and \code{transpose} functions of
  4508. the Racket \code{graph} package to obtain this ordering.
  4509. \index{topological order}
  4510. \index{topological sort}
  4511. The next question is how to compute the live-after set of a block
  4512. given the live-before sets of all its successor blocks. (There can be
  4513. more than one because of conditional jumps.) During compilation we do
  4514. not know which way a conditional jump will go, so we do not know which
  4515. of the successor's live-before set to use. The solution to this
  4516. challenge is based on the observation that there is no harm to the
  4517. correctness of the compiler if we classify more variables as live than
  4518. the ones that are truly live during a particular execution of the
  4519. block. Thus, we can take the union of the live-before sets from all
  4520. the successors to be the live-after set for the block. Once we have
  4521. computed the live-after set, we can proceed to perform liveness
  4522. analysis on the block just as we did in
  4523. Section~\ref{sec:liveness-analysis-r1}.
  4524. The helper functions for computing the variables in an instruction's
  4525. argument and for computing the variables read-from ($R$) or written-to
  4526. ($W$) by an instruction need to be updated to handle the new kinds of
  4527. arguments and instructions in x86$_1$.
  4528. \subsection{Build Interference}
  4529. \label{sec:build-interference-r2}
  4530. Many of the new instructions in x86$_1$ can be handled in the same way
  4531. as the instructions in x86$_0$. Thus, if your code was already quite
  4532. general, it will not need to be changed to handle the new
  4533. instructions. If you code is not general enough, I recommend that you
  4534. change your code to be more general. For example, you can factor out
  4535. the computing of the the read and write sets for each kind of
  4536. instruction into two auxiliary functions.
  4537. Note that the \key{movzbq} instruction requires some special care,
  4538. just like the \key{movq} instruction. See rule number 3 in
  4539. Section~\ref{sec:build-interference}.
  4540. %% \subsection{Assign Homes}
  4541. %% \label{sec:assign-homes-r2}
  4542. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4543. %% to be updated to handle the \key{if} statement, simply by recursively
  4544. %% processing the child nodes. Hopefully your code already handles the
  4545. %% other new instructions, but if not, you can generalize your code.
  4546. \begin{exercise}\normalfont
  4547. Update the \code{register-allocation} pass so that it works for $R_2$
  4548. and test your compiler using your previously created programs on the
  4549. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4550. \end{exercise}
  4551. \section{Patch Instructions}
  4552. The second argument of the \key{cmpq} instruction must not be an
  4553. immediate value (such as an integer). So if you are comparing two
  4554. immediates, we recommend inserting a \key{movq} instruction to put the
  4555. second argument in \key{rax}.
  4556. %
  4557. The second argument of the \key{movzbq} must be a register.
  4558. %
  4559. There are no special restrictions on the x86 instructions \key{JmpIf}
  4560. and \key{Jmp}.
  4561. \begin{exercise}\normalfont
  4562. Update \code{patch-instructions} to handle the new x86 instructions.
  4563. Test your compiler using your previously created programs on the
  4564. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4565. \end{exercise}
  4566. \section{An Example Translation}
  4567. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4568. $R_2$ translated to x86, showing the results of
  4569. \code{explicate-control}, \code{select-instructions}, and the final
  4570. x86 assembly code.
  4571. \begin{figure}[tbp]
  4572. \begin{tabular}{lll}
  4573. \begin{minipage}{0.5\textwidth}
  4574. % s1_20.rkt
  4575. \begin{lstlisting}
  4576. (if (eq? (read) 1) 42 0)
  4577. \end{lstlisting}
  4578. $\Downarrow$
  4579. \begin{lstlisting}
  4580. start:
  4581. tmp7951 = (read);
  4582. if (eq? tmp7951 1) then
  4583. goto block7952;
  4584. else
  4585. goto block7953;
  4586. block7952:
  4587. return 42;
  4588. block7953:
  4589. return 0;
  4590. \end{lstlisting}
  4591. $\Downarrow$
  4592. \begin{lstlisting}
  4593. start:
  4594. callq read_int
  4595. movq %rax, tmp7951
  4596. cmpq $1, tmp7951
  4597. je block7952
  4598. jmp block7953
  4599. block7953:
  4600. movq $0, %rax
  4601. jmp conclusion
  4602. block7952:
  4603. movq $42, %rax
  4604. jmp conclusion
  4605. \end{lstlisting}
  4606. \end{minipage}
  4607. &
  4608. $\Rightarrow\qquad$
  4609. \begin{minipage}{0.4\textwidth}
  4610. \begin{lstlisting}
  4611. start:
  4612. callq read_int
  4613. movq %rax, %rcx
  4614. cmpq $1, %rcx
  4615. je block7952
  4616. jmp block7953
  4617. block7953:
  4618. movq $0, %rax
  4619. jmp conclusion
  4620. block7952:
  4621. movq $42, %rax
  4622. jmp conclusion
  4623. .globl main
  4624. main:
  4625. pushq %rbp
  4626. movq %rsp, %rbp
  4627. pushq %r13
  4628. pushq %r12
  4629. pushq %rbx
  4630. pushq %r14
  4631. subq $0, %rsp
  4632. jmp start
  4633. conclusion:
  4634. addq $0, %rsp
  4635. popq %r14
  4636. popq %rbx
  4637. popq %r12
  4638. popq %r13
  4639. popq %rbp
  4640. retq
  4641. \end{lstlisting}
  4642. \end{minipage}
  4643. \end{tabular}
  4644. \caption{Example compilation of an \key{if} expression to x86.}
  4645. \label{fig:if-example-x86}
  4646. \end{figure}
  4647. \begin{figure}[p]
  4648. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4649. \node (R2) at (0,2) {\large $R_2$};
  4650. \node (R2-2) at (3,2) {\large $R_2$};
  4651. \node (R2-3) at (6,2) {\large $R_2$};
  4652. \node (R2-4) at (9,2) {\large $R_2$};
  4653. \node (R2-5) at (9,0) {\large $R_2$};
  4654. \node (C1-1) at (3,-2) {\large $C_1$};
  4655. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4656. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4657. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4658. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4659. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4660. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4661. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4662. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4663. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4664. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4665. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4666. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4667. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4668. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4669. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4670. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4671. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4672. \end{tikzpicture}
  4673. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4674. \label{fig:R2-passes}
  4675. \end{figure}
  4676. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4677. compilation of $R_2$.
  4678. \section{Challenge: Optimize and Remove Jumps}
  4679. \label{sec:opt-jumps}
  4680. Recall that in the example output of \code{explicate-control} in
  4681. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4682. \code{block60} are trivial blocks, they do nothing but jump to another
  4683. block. The first goal of this challenge assignment is to remove those
  4684. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4685. \code{explicate-control} on the left and shows the result of bypassing
  4686. the trivial blocks on the right. Let us focus on \code{block61}. The
  4687. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4688. \code{block55}. The optimized code on the right of
  4689. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4690. \code{then} branch jumping directly to \code{block55}. The story is
  4691. similar for the \code{else} branch, as well as for the two branches in
  4692. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4693. have been optimized in this way, there are no longer any jumps to
  4694. blocks \code{block57} through \code{block60}, so they can be removed.
  4695. \begin{figure}[tbp]
  4696. \begin{tabular}{lll}
  4697. \begin{minipage}{0.4\textwidth}
  4698. \begin{lstlisting}
  4699. block62:
  4700. tmp54 = (read);
  4701. if (eq? tmp54 2) then
  4702. goto block59;
  4703. else
  4704. goto block60;
  4705. block61:
  4706. tmp53 = (read);
  4707. if (eq? tmp53 0) then
  4708. goto block57;
  4709. else
  4710. goto block58;
  4711. block60:
  4712. goto block56;
  4713. block59:
  4714. goto block55;
  4715. block58:
  4716. goto block56;
  4717. block57:
  4718. goto block55;
  4719. block56:
  4720. return (+ 700 77);
  4721. block55:
  4722. return (+ 10 32);
  4723. start:
  4724. tmp52 = (read);
  4725. if (eq? tmp52 1) then
  4726. goto block61;
  4727. else
  4728. goto block62;
  4729. \end{lstlisting}
  4730. \end{minipage}
  4731. &
  4732. $\Rightarrow$
  4733. &
  4734. \begin{minipage}{0.55\textwidth}
  4735. \begin{lstlisting}
  4736. block62:
  4737. tmp54 = (read);
  4738. if (eq? tmp54 2) then
  4739. goto block55;
  4740. else
  4741. goto block56;
  4742. block61:
  4743. tmp53 = (read);
  4744. if (eq? tmp53 0) then
  4745. goto block55;
  4746. else
  4747. goto block56;
  4748. block56:
  4749. return (+ 700 77);
  4750. block55:
  4751. return (+ 10 32);
  4752. start:
  4753. tmp52 = (read);
  4754. if (eq? tmp52 1) then
  4755. goto block61;
  4756. else
  4757. goto block62;
  4758. \end{lstlisting}
  4759. \end{minipage}
  4760. \end{tabular}
  4761. \caption{Optimize jumps by removing trivial blocks.}
  4762. \label{fig:optimize-jumps}
  4763. \end{figure}
  4764. The name of this pass is \code{optimize-jumps}. We recommend
  4765. implementing this pass in two phases. The first phrase builds a hash
  4766. table that maps labels to possibly improved labels. The second phase
  4767. changes the target of each \code{goto} to use the improved label. If
  4768. the label is for a trivial block, then the hash table should map the
  4769. label to the first non-trivial block that can be reached from this
  4770. label by jumping through trivial blocks. If the label is for a
  4771. non-trivial block, then the hash table should map the label to itself;
  4772. we do not want to change jumps to non-trivial blocks.
  4773. The first phase can be accomplished by constructing an empty hash
  4774. table, call it \code{short-cut}, and then iterating over the control
  4775. flow graph. Each time you encouter a block that is just a \code{goto},
  4776. then update the hash table, mapping the block's source to the target
  4777. of the \code{goto}. Also, the hash table may already have mapped some
  4778. labels to the block's source, to you must iterate through the hash
  4779. table and update all of those so that they instead map to the target
  4780. of the \code{goto}.
  4781. For the second phase, we recommend iterating through the $\Tail$ of
  4782. each block in the program, updating the target of every \code{goto}
  4783. according to the mapping in \code{short-cut}.
  4784. \begin{exercise}\normalfont
  4785. Implement the \code{optimize-jumps} pass as a transformation from
  4786. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4787. Check that \code{optimize-jumps} removes trivial blocks in a few
  4788. example programs. Then check that your compiler still passes all of
  4789. your tests.
  4790. \end{exercise}
  4791. There is another opportunity for optimizing jumps that is apparent in
  4792. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4793. end with a jump to \code{block7953} and there are no other jumps to
  4794. \code{block7953} in the rest of the program. In this situation we can
  4795. avoid the runtime overhead of this jump by merging \code{block7953}
  4796. into the preceeding block, in this case the \code{start} block.
  4797. Figure~\ref{fig:remove-jumps} shows the output of
  4798. \code{select-instructions} on the left and the result of this
  4799. optimization on the right.
  4800. \begin{figure}[tbp]
  4801. \begin{tabular}{lll}
  4802. \begin{minipage}{0.5\textwidth}
  4803. % s1_20.rkt
  4804. \begin{lstlisting}
  4805. start:
  4806. callq read_int
  4807. movq %rax, tmp7951
  4808. cmpq $1, tmp7951
  4809. je block7952
  4810. jmp block7953
  4811. block7953:
  4812. movq $0, %rax
  4813. jmp conclusion
  4814. block7952:
  4815. movq $42, %rax
  4816. jmp conclusion
  4817. \end{lstlisting}
  4818. \end{minipage}
  4819. &
  4820. $\Rightarrow\qquad$
  4821. \begin{minipage}{0.4\textwidth}
  4822. \begin{lstlisting}
  4823. start:
  4824. callq read_int
  4825. movq %rax, tmp7951
  4826. cmpq $1, tmp7951
  4827. je block7952
  4828. movq $0, %rax
  4829. jmp conclusion
  4830. block7952:
  4831. movq $42, %rax
  4832. jmp conclusion
  4833. \end{lstlisting}
  4834. \end{minipage}
  4835. \end{tabular}
  4836. \caption{Merging basic blocks by removing unnecessary jumps.}
  4837. \label{fig:remove-jumps}
  4838. \end{figure}
  4839. \begin{exercise}\normalfont
  4840. Implement a pass named \code{remove-jumps} that merges basic blocks
  4841. into their preceeding basic block, when there is only one preceeding
  4842. block. The pass should translate from psuedo $x86_1$ to pseudo
  4843. $x86_1$ and it should come immediately after
  4844. \code{select-instructions}. Check that \code{remove-jumps}
  4845. accomplishes the goal of merging basic blocks on several test
  4846. programs and check that your compiler passes all of your tests.
  4847. \end{exercise}
  4848. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4849. \chapter{Tuples and Garbage Collection}
  4850. \label{ch:tuples}
  4851. \index{tuple}
  4852. \index{vector}
  4853. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4854. add simple structures. \\ --Jeremy}
  4855. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4856. things to discuss in this chapter. \\ --Jeremy}
  4857. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4858. all the IR grammars are spelled out! \\ --Jeremy}
  4859. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4860. but keep type annotations on vector creation and local variables, function
  4861. parameters, etc. \\ --Jeremy}
  4862. \margincomment{\scriptsize Be more explicit about how to deal with
  4863. the root stack. \\ --Jeremy}
  4864. In this chapter we study the implementation of mutable tuples (called
  4865. ``vectors'' in Racket). This language feature is the first to use the
  4866. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4867. indefinite, that is, a tuple lives forever from the programmer's
  4868. viewpoint. Of course, from an implementer's viewpoint, it is important
  4869. to reclaim the space associated with a tuple when it is no longer
  4870. needed, which is why we also study \emph{garbage collection}
  4871. \emph{garbage collection}
  4872. techniques in this chapter.
  4873. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4874. interpreter and type checker. The $R_3$ language extends the $R_2$
  4875. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4876. \code{void} value. The reason for including the later is that the
  4877. \code{vector-set!} operation returns a value of type
  4878. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4879. called the \code{Unit} type in the programming languages
  4880. literature. Racket's \code{Void} type is inhabited by a single value
  4881. \code{void} which corresponds to \code{unit} or \code{()} in the
  4882. literature~\citep{Pierce:2002hj}.}.
  4883. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4884. copying live objects back and forth between two halves of the
  4885. heap. The garbage collector requires coordination with the compiler so
  4886. that it can see all of the \emph{root} pointers, that is, pointers in
  4887. registers or on the procedure call stack.
  4888. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4889. discuss all the necessary changes and additions to the compiler
  4890. passes, including a new compiler pass named \code{expose-allocation}.
  4891. \section{The $R_3$ Language}
  4892. \label{sec:r3}
  4893. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4894. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4895. $R_3$ language includes three new forms: \code{vector} for creating a
  4896. tuple, \code{vector-ref} for reading an element of a tuple, and
  4897. \code{vector-set!} for writing to an element of a tuple. The program
  4898. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4899. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4900. the 3-tuple, demonstrating that tuples are first-class values. The
  4901. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4902. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4903. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4904. 1-tuple. So the result of the program is \code{42}.
  4905. \begin{figure}[tbp]
  4906. \centering
  4907. \fbox{
  4908. \begin{minipage}{0.96\textwidth}
  4909. \[
  4910. \begin{array}{lcl}
  4911. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4912. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4913. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4914. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4915. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4916. \mid (\key{and}\;\Exp\;\Exp)
  4917. \mid (\key{or}\;\Exp\;\Exp)
  4918. \mid (\key{not}\;\Exp) } \\
  4919. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4920. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4921. &\mid& (\key{vector}\;\Exp\ldots)
  4922. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4923. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4924. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4925. R_3 &::=& \Exp
  4926. \end{array}
  4927. \]
  4928. \end{minipage}
  4929. }
  4930. \caption{The concrete syntax of $R_3$, extending $R_2$
  4931. (Figure~\ref{fig:r2-concrete-syntax}).}
  4932. \label{fig:r3-concrete-syntax}
  4933. \end{figure}
  4934. \begin{figure}[tbp]
  4935. \begin{lstlisting}
  4936. (let ([t (vector 40 #t (vector 2))])
  4937. (if (vector-ref t 1)
  4938. (+ (vector-ref t 0)
  4939. (vector-ref (vector-ref t 2) 0))
  4940. 44))
  4941. \end{lstlisting}
  4942. \caption{Example program that creates tuples and reads from them.}
  4943. \label{fig:vector-eg}
  4944. \end{figure}
  4945. \begin{figure}[tp]
  4946. \centering
  4947. \fbox{
  4948. \begin{minipage}{0.96\textwidth}
  4949. \[
  4950. \begin{array}{lcl}
  4951. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4952. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4953. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4954. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4955. &\mid& \gray{ \BOOL{\itm{bool}}
  4956. \mid \AND{\Exp}{\Exp} }\\
  4957. &\mid& \gray{ \OR{\Exp}{\Exp}
  4958. \mid \NOT{\Exp} } \\
  4959. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4960. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4961. &\mid& \VECTOR{\Exp} \\
  4962. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  4963. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp}\\
  4964. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4965. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4966. \end{array}
  4967. \]
  4968. \end{minipage}
  4969. }
  4970. \caption{The abstract syntax of $R_3$.}
  4971. \label{fig:r3-syntax}
  4972. \end{figure}
  4973. \index{allocate}
  4974. \index{heap allocate}
  4975. Tuples are our first encounter with heap-allocated data, which raises
  4976. several interesting issues. First, variable binding performs a
  4977. shallow-copy when dealing with tuples, which means that different
  4978. variables can refer to the same tuple, that is, different variables
  4979. can be \emph{aliases} for the same entity. Consider the following
  4980. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4981. Thus, the mutation through \code{t2} is visible when referencing the
  4982. tuple from \code{t1}, so the result of this program is \code{42}.
  4983. \index{alias}\index{mutation}
  4984. \begin{center}
  4985. \begin{minipage}{0.96\textwidth}
  4986. \begin{lstlisting}
  4987. (let ([t1 (vector 3 7)])
  4988. (let ([t2 t1])
  4989. (let ([_ (vector-set! t2 0 42)])
  4990. (vector-ref t1 0))))
  4991. \end{lstlisting}
  4992. \end{minipage}
  4993. \end{center}
  4994. The next issue concerns the lifetime of tuples. Of course, they are
  4995. created by the \code{vector} form, but when does their lifetime end?
  4996. Notice that $R_3$ does not include an operation for deleting
  4997. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4998. of static scoping. For example, the following program returns
  4999. \code{42} even though the variable \code{w} goes out of scope prior to
  5000. the \code{vector-ref} that reads from the vector it was bound to.
  5001. \begin{center}
  5002. \begin{minipage}{0.96\textwidth}
  5003. \begin{lstlisting}
  5004. (let ([v (vector (vector 44))])
  5005. (let ([x (let ([w (vector 42)])
  5006. (let ([_ (vector-set! v 0 w)])
  5007. 0))])
  5008. (+ x (vector-ref (vector-ref v 0) 0))))
  5009. \end{lstlisting}
  5010. \end{minipage}
  5011. \end{center}
  5012. From the perspective of programmer-observable behavior, tuples live
  5013. forever. Of course, if they really lived forever, then many programs
  5014. would run out of memory.\footnote{The $R_3$ language does not have
  5015. looping or recursive functions, so it is nigh impossible to write a
  5016. program in $R_3$ that will run out of memory. However, we add
  5017. recursive functions in the next Chapter!} A Racket implementation
  5018. must therefore perform automatic garbage collection.
  5019. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5020. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5021. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5022. operations in Racket. One subtle point is that the \code{vector-set!}
  5023. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5024. can be passed around just like other values inside an $R_3$ program
  5025. and a \code{\#<void>} value can be compared for equality with another
  5026. \code{\#<void>} value. However, there are no other operations specific
  5027. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5028. the \code{void?} predicate that returns \code{\#t} when applied to
  5029. \code{\#<void>} and \code{\#f} otherwise.
  5030. \begin{figure}[tbp]
  5031. \begin{lstlisting}
  5032. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5033. (define (interp-op op)
  5034. (match op
  5035. ...
  5036. ['vector vector]
  5037. ['vector-ref vector-ref]
  5038. ['vector-set! vector-set!]
  5039. [else (error 'interp-op "unknown operator")]))
  5040. (define (interp-exp env)
  5041. (lambda (e)
  5042. (define recur (interp-exp env))
  5043. (match e
  5044. ...
  5045. )))
  5046. (define (interp-R3 p)
  5047. (match p
  5048. [(Program '() e)
  5049. ((interp-exp '()) e)]
  5050. ))
  5051. \end{lstlisting}
  5052. \caption{Interpreter for the $R_3$ language.}
  5053. \label{fig:interp-R3}
  5054. \end{figure}
  5055. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  5056. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  5057. need to know which variables contain pointers into the heap, that is,
  5058. which variables contain vectors. Also, when allocating a vector, we
  5059. need to know which elements of the vector are pointers. We can obtain
  5060. this information during type checking. The type checker in
  5061. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  5062. expression, it also wraps every sub-expression $e$ with the form
  5063. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5064. Subsequently, in the \code{uncover-locals} pass
  5065. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5066. propagated to all variables (including the temporaries generated by
  5067. \code{remove-complex-opera*}).
  5068. To create the s-expression for the \code{Vector} type in
  5069. Figure~\ref{fig:typecheck-R3}, we use the
  5070. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5071. operator} \code{,@} to insert the list \code{t*} without its usual
  5072. start and end parentheses. \index{unquote-slicing}
  5073. \begin{figure}[tp]
  5074. \begin{lstlisting}
  5075. (define (type-check-exp env)
  5076. (lambda (e)
  5077. (define recur (type-check-exp env))
  5078. (match e
  5079. ...
  5080. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5081. [(Prim 'vector es)
  5082. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5083. (let ([t `(Vector ,@t*)])
  5084. (values (HasType (Prim 'vector e*) t) t))]
  5085. [(Prim 'vector-ref (list e (Int i)))
  5086. (define-values (e^ t) (recur e))
  5087. (match t
  5088. [`(Vector ,ts ...)
  5089. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5090. (error 'type-check-exp "invalid index ~a" i))
  5091. (let ([t (list-ref ts i)])
  5092. (values
  5093. (HasType (Prim 'vector-ref
  5094. (list e^ (HasType (Int i) 'Integer)))
  5095. t)
  5096. t))]
  5097. [else (error "expected a vector in vector-ref, not" t)])]
  5098. [(Prim 'eq? (list e1 e2))
  5099. (define-values (e1^ T1) (recur e1))
  5100. (define-values (e2^ T2) (recur e2))
  5101. (unless (equal? T1 T2)
  5102. (error "arguments of eq? must have the same type, but are not"
  5103. (list T1 T2)))
  5104. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5105. ...
  5106. )))
  5107. \end{lstlisting}
  5108. \caption{Type checker for the $R_3$ language.}
  5109. \label{fig:typecheck-R3}
  5110. \end{figure}
  5111. \section{Garbage Collection}
  5112. \label{sec:GC}
  5113. Here we study a relatively simple algorithm for garbage collection
  5114. that is the basis of state-of-the-art garbage
  5115. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5116. particular, we describe a two-space copying
  5117. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5118. perform the
  5119. copy~\citep{Cheney:1970aa}.
  5120. \index{copying collector}
  5121. \index{two-space copying collector}
  5122. Figure~\ref{fig:copying-collector} gives a
  5123. coarse-grained depiction of what happens in a two-space collector,
  5124. showing two time steps, prior to garbage collection (on the top) and
  5125. after garbage collection (on the bottom). In a two-space collector,
  5126. the heap is divided into two parts named the FromSpace and the
  5127. ToSpace. Initially, all allocations go to the FromSpace until there is
  5128. not enough room for the next allocation request. At that point, the
  5129. garbage collector goes to work to make more room.
  5130. \index{ToSpace}
  5131. \index{FromSpace}
  5132. The garbage collector must be careful not to reclaim tuples that will
  5133. be used by the program in the future. Of course, it is impossible in
  5134. general to predict what a program will do, but we can over approximate
  5135. the will-be-used tuples by preserving all tuples that could be
  5136. accessed by \emph{any} program given the current computer state. A
  5137. program could access any tuple whose address is in a register or on
  5138. the procedure call stack. These addresses are called the \emph{root
  5139. set}\index{root set}. In addition, a program could access any tuple that is
  5140. transitively reachable from the root set. Thus, it is safe for the
  5141. garbage collector to reclaim the tuples that are not reachable in this
  5142. way.
  5143. So the goal of the garbage collector is twofold:
  5144. \begin{enumerate}
  5145. \item preserve all tuple that are reachable from the root set via a
  5146. path of pointers, that is, the \emph{live} tuples, and
  5147. \item reclaim the memory of everything else, that is, the
  5148. \emph{garbage}.
  5149. \end{enumerate}
  5150. A copying collector accomplishes this by copying all of the live
  5151. objects from the FromSpace into the ToSpace and then performs a slight
  5152. of hand, treating the ToSpace as the new FromSpace and the old
  5153. FromSpace as the new ToSpace. In the example of
  5154. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5155. root set, one in a register and two on the stack. All of the live
  5156. objects have been copied to the ToSpace (the right-hand side of
  5157. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5158. pointer relationships. For example, the pointer in the register still
  5159. points to a 2-tuple whose first element is a 3-tuple and whose second
  5160. element is a 2-tuple. There are four tuples that are not reachable
  5161. from the root set and therefore do not get copied into the ToSpace.
  5162. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5163. created by a well-typed program in $R_3$ because it contains a
  5164. cycle. However, creating cycles will be possible once we get to $R_6$.
  5165. We design the garbage collector to deal with cycles to begin with so
  5166. we will not need to revisit this issue.
  5167. \begin{figure}[tbp]
  5168. \centering
  5169. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5170. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5171. \caption{A copying collector in action.}
  5172. \label{fig:copying-collector}
  5173. \end{figure}
  5174. There are many alternatives to copying collectors (and their bigger
  5175. siblings, the generational collectors) when its comes to garbage
  5176. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5177. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5178. collectors are that allocation is fast (just a comparison and pointer
  5179. increment), there is no fragmentation, cyclic garbage is collected,
  5180. and the time complexity of collection only depends on the amount of
  5181. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5182. main disadvantages of a two-space copying collector is that it uses a
  5183. lot of space and takes a long time to perform the copy, though these
  5184. problems are ameliorated in generational collectors. Racket and
  5185. Scheme programs tend to allocate many small objects and generate a lot
  5186. of garbage, so copying and generational collectors are a good fit.
  5187. Garbage collection is an active research topic, especially concurrent
  5188. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5189. developing new techniques and revisiting old
  5190. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5191. meet every year at the International Symposium on Memory Management to
  5192. present these findings.
  5193. \subsection{Graph Copying via Cheney's Algorithm}
  5194. \label{sec:cheney}
  5195. \index{Cheney's algorithm}
  5196. Let us take a closer look at the copying of the live objects. The
  5197. allocated objects and pointers can be viewed as a graph and we need to
  5198. copy the part of the graph that is reachable from the root set. To
  5199. make sure we copy all of the reachable vertices in the graph, we need
  5200. an exhaustive graph traversal algorithm, such as depth-first search or
  5201. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5202. such algorithms take into account the possibility of cycles by marking
  5203. which vertices have already been visited, so as to ensure termination
  5204. of the algorithm. These search algorithms also use a data structure
  5205. such as a stack or queue as a to-do list to keep track of the vertices
  5206. that need to be visited. We shall use breadth-first search and a trick
  5207. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5208. and copying tuples into the ToSpace.
  5209. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5210. copy progresses. The queue is represented by a chunk of contiguous
  5211. memory at the beginning of the ToSpace, using two pointers to track
  5212. the front and the back of the queue. The algorithm starts by copying
  5213. all tuples that are immediately reachable from the root set into the
  5214. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5215. old tuple to indicate that it has been visited. We discuss how this
  5216. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5217. pointers inside the copied tuples in the queue still point back to the
  5218. FromSpace. Once the initial queue has been created, the algorithm
  5219. enters a loop in which it repeatedly processes the tuple at the front
  5220. of the queue and pops it off the queue. To process a tuple, the
  5221. algorithm copies all the tuple that are directly reachable from it to
  5222. the ToSpace, placing them at the back of the queue. The algorithm then
  5223. updates the pointers in the popped tuple so they point to the newly
  5224. copied tuples.
  5225. \begin{figure}[tbp]
  5226. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5227. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5228. \label{fig:cheney}
  5229. \end{figure}
  5230. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5231. tuple whose second element is $42$ to the back of the queue. The other
  5232. pointer goes to a tuple that has already been copied, so we do not
  5233. need to copy it again, but we do need to update the pointer to the new
  5234. location. This can be accomplished by storing a \emph{forwarding
  5235. pointer} to the new location in the old tuple, back when we initially
  5236. copied the tuple into the ToSpace. This completes one step of the
  5237. algorithm. The algorithm continues in this way until the front of the
  5238. queue is empty, that is, until the front catches up with the back.
  5239. \subsection{Data Representation}
  5240. \label{sec:data-rep-gc}
  5241. The garbage collector places some requirements on the data
  5242. representations used by our compiler. First, the garbage collector
  5243. needs to distinguish between pointers and other kinds of data. There
  5244. are several ways to accomplish this.
  5245. \begin{enumerate}
  5246. \item Attached a tag to each object that identifies what type of
  5247. object it is~\citep{McCarthy:1960dz}.
  5248. \item Store different types of objects in different
  5249. regions~\citep{Steele:1977ab}.
  5250. \item Use type information from the program to either generate
  5251. type-specific code for collecting or to generate tables that can
  5252. guide the
  5253. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5254. \end{enumerate}
  5255. Dynamically typed languages, such as Lisp, need to tag objects
  5256. anyways, so option 1 is a natural choice for those languages.
  5257. However, $R_3$ is a statically typed language, so it would be
  5258. unfortunate to require tags on every object, especially small and
  5259. pervasive objects like integers and Booleans. Option 3 is the
  5260. best-performing choice for statically typed languages, but comes with
  5261. a relatively high implementation complexity. To keep this chapter
  5262. within a 2-week time budget, we recommend a combination of options 1
  5263. and 2, using separate strategies for the stack and the heap.
  5264. Regarding the stack, we recommend using a separate stack for pointers,
  5265. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5266. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5267. is, when a local variable needs to be spilled and is of type
  5268. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5269. stack instead of the normal procedure call stack. Furthermore, we
  5270. always spill vector-typed variables if they are live during a call to
  5271. the collector, thereby ensuring that no pointers are in registers
  5272. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5273. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5274. the data layout using a root stack. The root stack contains the two
  5275. pointers from the regular stack and also the pointer in the second
  5276. register.
  5277. \begin{figure}[tbp]
  5278. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5279. \caption{Maintaining a root stack to facilitate garbage collection.}
  5280. \label{fig:shadow-stack}
  5281. \end{figure}
  5282. The problem of distinguishing between pointers and other kinds of data
  5283. also arises inside of each tuple on the heap. We solve this problem by
  5284. attaching a tag, an extra 64-bits, to each
  5285. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5286. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5287. that we have drawn the bits in a big-endian way, from right-to-left,
  5288. with bit location 0 (the least significant bit) on the far right,
  5289. which corresponds to the direction of the x86 shifting instructions
  5290. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5291. is dedicated to specifying which elements of the tuple are pointers,
  5292. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5293. indicates there is a pointer and a 0 bit indicates some other kind of
  5294. data. The pointer mask starts at bit location 7. We have limited
  5295. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5296. the pointer mask. The tag also contains two other pieces of
  5297. information. The length of the tuple (number of elements) is stored in
  5298. bits location 1 through 6. Finally, the bit at location 0 indicates
  5299. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5300. value 1, then this tuple has not yet been copied. If the bit has
  5301. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5302. of a pointer are always zero anyways because our tuples are 8-byte
  5303. aligned.)
  5304. \begin{figure}[tbp]
  5305. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5306. \caption{Representation of tuples in the heap.}
  5307. \label{fig:tuple-rep}
  5308. \end{figure}
  5309. \subsection{Implementation of the Garbage Collector}
  5310. \label{sec:organize-gz}
  5311. \index{prelude}
  5312. An implementation of the copying collector is provided in the
  5313. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5314. interface to the garbage collector that is used by the compiler. The
  5315. \code{initialize} function creates the FromSpace, ToSpace, and root
  5316. stack and should be called in the prelude of the \code{main}
  5317. function. The \code{initialize} function puts the address of the
  5318. beginning of the FromSpace into the global variable
  5319. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5320. the address that is 1-past the last element of the FromSpace. (We use
  5321. half-open intervals to represent chunks of
  5322. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5323. points to the first element of the root stack.
  5324. As long as there is room left in the FromSpace, your generated code
  5325. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5326. %
  5327. The amount of room left in FromSpace is the difference between the
  5328. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5329. function should be called when there is not enough room left in the
  5330. FromSpace for the next allocation. The \code{collect} function takes
  5331. a pointer to the current top of the root stack (one past the last item
  5332. that was pushed) and the number of bytes that need to be
  5333. allocated. The \code{collect} function performs the copying collection
  5334. and leaves the heap in a state such that the next allocation will
  5335. succeed.
  5336. \begin{figure}[tbp]
  5337. \begin{lstlisting}
  5338. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5339. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5340. int64_t* free_ptr;
  5341. int64_t* fromspace_begin;
  5342. int64_t* fromspace_end;
  5343. int64_t** rootstack_begin;
  5344. \end{lstlisting}
  5345. \caption{The compiler's interface to the garbage collector.}
  5346. \label{fig:gc-header}
  5347. \end{figure}
  5348. %% \begin{exercise}
  5349. %% In the file \code{runtime.c} you will find the implementation of
  5350. %% \code{initialize} and a partial implementation of \code{collect}.
  5351. %% The \code{collect} function calls another function, \code{cheney},
  5352. %% to perform the actual copy, and that function is left to the reader
  5353. %% to implement. The following is the prototype for \code{cheney}.
  5354. %% \begin{lstlisting}
  5355. %% static void cheney(int64_t** rootstack_ptr);
  5356. %% \end{lstlisting}
  5357. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5358. %% rootstack (which is an array of pointers). The \code{cheney} function
  5359. %% also communicates with \code{collect} through the global
  5360. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5361. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5362. %% the ToSpace:
  5363. %% \begin{lstlisting}
  5364. %% static int64_t* tospace_begin;
  5365. %% static int64_t* tospace_end;
  5366. %% \end{lstlisting}
  5367. %% The job of the \code{cheney} function is to copy all the live
  5368. %% objects (reachable from the root stack) into the ToSpace, update
  5369. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5370. %% update the root stack so that it points to the objects in the
  5371. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5372. %% and ToSpace.
  5373. %% \end{exercise}
  5374. %% \section{Compiler Passes}
  5375. %% \label{sec:code-generation-gc}
  5376. The introduction of garbage collection has a non-trivial impact on our
  5377. compiler passes. We introduce two new compiler passes named
  5378. \code{expose-allocation} and \code{uncover-locals}. We make
  5379. significant changes to \code{select-instructions},
  5380. \code{build-interference}, \code{allocate-registers}, and
  5381. \code{print-x86} and make minor changes in severl more passes. The
  5382. following program will serve as our running example. It creates two
  5383. tuples, one nested inside the other. Both tuples have length one. The
  5384. program accesses the element in the inner tuple tuple via two vector
  5385. references.
  5386. % tests/s2_17.rkt
  5387. \begin{lstlisting}
  5388. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5389. \end{lstlisting}
  5390. \section{Shrink}
  5391. \label{sec:shrink-R3}
  5392. Recall that the \code{shrink} pass translates the primitives operators
  5393. into a smaller set of primitives. Because this pass comes after type
  5394. checking, but before the passes that require the type information in
  5395. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5396. to wrap \code{HasType} around each AST node that it generates.
  5397. \section{Expose Allocation}
  5398. \label{sec:expose-allocation}
  5399. The pass \code{expose-allocation} lowers the \code{vector} creation
  5400. form into a conditional call to the collector followed by the
  5401. allocation. We choose to place the \code{expose-allocation} pass
  5402. before \code{remove-complex-opera*} because the code generated by
  5403. \code{expose-allocation} contains complex operands. We also place
  5404. \code{expose-allocation} before \code{explicate-control} because
  5405. \code{expose-allocation} introduces new variables using \code{let},
  5406. but \code{let} is gone after \code{explicate-control}.
  5407. The output of \code{expose-allocation} is a language $R'_3$ that
  5408. extends $R_3$ with the three new forms that we use in the translation
  5409. of the \code{vector} form.
  5410. \[
  5411. \begin{array}{lcl}
  5412. \Exp &::=& \cdots
  5413. \mid (\key{collect} \,\itm{int})
  5414. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5415. \mid (\key{global-value} \,\itm{name})
  5416. \end{array}
  5417. \]
  5418. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5419. $n$ bytes. It will become a call to the \code{collect} function in
  5420. \code{runtime.c} in \code{select-instructions}. The
  5421. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5422. \index{allocate}
  5423. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5424. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5425. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5426. a global variable, such as \code{free\_ptr}.
  5427. In the following, we show the transformation for the \code{vector}
  5428. form into 1) a sequence of let-bindings for the initializing
  5429. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5430. \code{allocate}, and 4) the initialization of the vector. In the
  5431. following, \itm{len} refers to the length of the vector and
  5432. \itm{bytes} is how many total bytes need to be allocated for the
  5433. vector, which is 8 for the tag plus \itm{len} times 8.
  5434. \begin{lstlisting}
  5435. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5436. |$\Longrightarrow$|
  5437. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5438. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5439. (global-value fromspace_end))
  5440. (void)
  5441. (collect |\itm{bytes}|))])
  5442. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5443. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5444. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5445. |$v$|) ... )))) ...)
  5446. \end{lstlisting}
  5447. In the above, we suppressed all of the \code{has-type} forms in the
  5448. output for the sake of readability. The placement of the initializing
  5449. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5450. sequence of \code{vector-set!} is important, as those expressions may
  5451. trigger garbage collection and we cannot have an allocated but
  5452. uninitialized tuple on the heap during a collection.
  5453. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5454. \code{expose-allocation} pass on our running example.
  5455. \begin{figure}[tbp]
  5456. % tests/s2_17.rkt
  5457. \begin{lstlisting}
  5458. (vector-ref
  5459. (vector-ref
  5460. (let ([vecinit7976
  5461. (let ([vecinit7972 42])
  5462. (let ([collectret7974
  5463. (if (< (+ (global-value free_ptr) 16)
  5464. (global-value fromspace_end))
  5465. (void)
  5466. (collect 16)
  5467. )])
  5468. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5469. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5470. alloc7971)
  5471. )
  5472. )
  5473. )
  5474. ])
  5475. (let ([collectret7978
  5476. (if (< (+ (global-value free_ptr) 16)
  5477. (global-value fromspace_end))
  5478. (void)
  5479. (collect 16)
  5480. )])
  5481. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5482. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5483. alloc7975)
  5484. )
  5485. )
  5486. )
  5487. 0)
  5488. 0)
  5489. \end{lstlisting}
  5490. \caption{Output of the \code{expose-allocation} pass, minus
  5491. all of the \code{has-type} forms.}
  5492. \label{fig:expose-alloc-output}
  5493. \end{figure}
  5494. \section{Remove Complex Operands}
  5495. \label{sec:remove-complex-opera-R3}
  5496. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5497. should all be treated as complex operands. A new case for
  5498. \code{HasType} is needed and the case for \code{Prim} needs to be
  5499. handled carefully to prevent the \code{Prim} node from being separated
  5500. from its enclosing \code{HasType}.
  5501. \section{Explicate Control and the $C_2$ language}
  5502. \label{sec:explicate-control-r3}
  5503. \begin{figure}[tbp]
  5504. \fbox{
  5505. \begin{minipage}{0.96\textwidth}
  5506. \small
  5507. \[
  5508. \begin{array}{lcl}
  5509. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5510. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5511. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5512. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5513. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5514. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5515. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5516. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5517. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5518. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5519. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5520. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5521. \end{array}
  5522. \]
  5523. \end{minipage}
  5524. }
  5525. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5526. \label{fig:c2-concrete-syntax}
  5527. \end{figure}
  5528. \begin{figure}[tp]
  5529. \fbox{
  5530. \begin{minipage}{0.96\textwidth}
  5531. \small
  5532. \[
  5533. \begin{array}{lcl}
  5534. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5535. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5536. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5537. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5538. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5539. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5540. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5541. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5542. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5543. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5544. \mid (\key{Collect} \,\itm{int}) \\
  5545. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5546. \mid \GOTO{\itm{label}} } \\
  5547. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5548. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5549. \end{array}
  5550. \]
  5551. \end{minipage}
  5552. }
  5553. \caption{The abstract syntax of $C_2$, extending $C_1$
  5554. (Figure~\ref{fig:c1-syntax}).}
  5555. \label{fig:c2-syntax}
  5556. \end{figure}
  5557. The output of \code{explicate-control} is a program in the
  5558. intermediate language $C_2$, whose concrete syntax is defined in
  5559. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5560. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5561. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5562. \key{global-value} expressions and the \code{collect} statement. The
  5563. \code{explicate-control} pass can treat these new forms much like the
  5564. other forms.
  5565. \section{Uncover Locals}
  5566. \label{sec:uncover-locals-r3}
  5567. Recall that the \code{explicate-control} function collects all of the
  5568. local variables so that it can store them in the $\itm{info}$ field of
  5569. the \code{Program} structure. Also recall that we need to know the
  5570. types of all the local variables for purposes of identifying the root
  5571. set for the garbage collector. Thus, we create a pass named
  5572. \code{uncover-locals} to collect not just the variables but the
  5573. variables and their types in the form of an alist. Thanks to the
  5574. \code{HasType} nodes, the types are readily available at every
  5575. assignment to a variable. We recommend storing the resulting alist in
  5576. the $\itm{info}$ field of the program, associated with the
  5577. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5578. of the \code{uncover-locals} pass on the running example.
  5579. \begin{figure}[tbp]
  5580. % tests/s2_17.rkt
  5581. \begin{lstlisting}
  5582. locals:
  5583. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5584. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5585. collectret7974 : 'Void, initret7977 : 'Void,
  5586. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5587. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5588. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5589. vecinit7972 : 'Integer, initret7973 : 'Void,
  5590. block91:
  5591. (collect 16)
  5592. goto block89;
  5593. block90:
  5594. collectret7974 = (void);
  5595. goto block89;
  5596. block89:
  5597. alloc7971 = (allocate 1 (Vector Integer));
  5598. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5599. vecinit7976 = alloc7971;
  5600. tmp7982 = (global-value free_ptr);
  5601. tmp7983 = (+ tmp7982 16);
  5602. tmp7984 = (global-value fromspace_end);
  5603. if (< tmp7983 tmp7984) then
  5604. goto block87;
  5605. else
  5606. goto block88;
  5607. block88:
  5608. (collect 16)
  5609. goto block86;
  5610. block87:
  5611. collectret7978 = (void);
  5612. goto block86;
  5613. block86:
  5614. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5615. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5616. tmp7985 = (vector-ref alloc7975 0);
  5617. return (vector-ref tmp7985 0);
  5618. start:
  5619. vecinit7972 = 42;
  5620. tmp7979 = (global-value free_ptr);
  5621. tmp7980 = (+ tmp7979 16);
  5622. tmp7981 = (global-value fromspace_end);
  5623. if (< tmp7980 tmp7981) then
  5624. goto block90;
  5625. else
  5626. goto block91;
  5627. \end{lstlisting}
  5628. \caption{Output of \code{uncover-locals} for the running example.}
  5629. \label{fig:uncover-locals-r3}
  5630. \end{figure}
  5631. \clearpage
  5632. \section{Select Instructions and the x86$_2$ Language}
  5633. \label{sec:select-instructions-gc}
  5634. \index{instruction selection}
  5635. %% void (rep as zero)
  5636. %% allocate
  5637. %% collect (callq collect)
  5638. %% vector-ref
  5639. %% vector-set!
  5640. %% global (postpone)
  5641. In this pass we generate x86 code for most of the new operations that
  5642. were needed to compile tuples, including \code{Allocate},
  5643. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5644. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5645. the later has a different concrete syntax (see
  5646. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5647. \index{x86}
  5648. The \code{vector-ref} and \code{vector-set!} forms translate into
  5649. \code{movq} instructions. (The plus one in the offset is to get past
  5650. the tag at the beginning of the tuple representation.)
  5651. \begin{lstlisting}
  5652. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5653. |$\Longrightarrow$|
  5654. movq |$\itm{vec}'$|, %r11
  5655. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5656. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5657. |$\Longrightarrow$|
  5658. movq |$\itm{vec}'$|, %r11
  5659. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5660. movq $0, |$\itm{lhs'}$|
  5661. \end{lstlisting}
  5662. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5663. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5664. register \code{r11} ensures that offset expression
  5665. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5666. removing \code{r11} from consideration by the register allocating.
  5667. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5668. \code{rax}. Then the generated code for \code{vector-set!} would be
  5669. \begin{lstlisting}
  5670. movq |$\itm{vec}'$|, %rax
  5671. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5672. movq $0, |$\itm{lhs}'$|
  5673. \end{lstlisting}
  5674. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5675. \code{patch-instructions} would insert a move through \code{rax}
  5676. as follows.
  5677. \begin{lstlisting}
  5678. movq |$\itm{vec}'$|, %rax
  5679. movq |$\itm{arg}'$|, %rax
  5680. movq %rax, |$8(n+1)$|(%rax)
  5681. movq $0, |$\itm{lhs}'$|
  5682. \end{lstlisting}
  5683. But the above sequence of instructions does not work because we're
  5684. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5685. $\itm{arg}'$) at the same time!
  5686. We compile the \code{allocate} form to operations on the
  5687. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5688. is the next free address in the FromSpace, so we move it into the
  5689. \itm{lhs} and then move it forward by enough space for the tuple being
  5690. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5691. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5692. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5693. how the tag is organized. We recommend using the Racket operations
  5694. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5695. during compilation. The type annotation in the \code{vector} form is
  5696. used to determine the pointer mask region of the tag.
  5697. \begin{lstlisting}
  5698. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5699. |$\Longrightarrow$|
  5700. movq free_ptr(%rip), |$\itm{lhs}'$|
  5701. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5702. movq |$\itm{lhs}'$|, %r11
  5703. movq $|$\itm{tag}$|, 0(%r11)
  5704. \end{lstlisting}
  5705. The \code{collect} form is compiled to a call to the \code{collect}
  5706. function in the runtime. The arguments to \code{collect} are 1) the
  5707. top of the root stack and 2) the number of bytes that need to be
  5708. allocated. We shall use another dedicated register, \code{r15}, to
  5709. store the pointer to the top of the root stack. So \code{r15} is not
  5710. available for use by the register allocator.
  5711. \begin{lstlisting}
  5712. (collect |$\itm{bytes}$|)
  5713. |$\Longrightarrow$|
  5714. movq %r15, %rdi
  5715. movq $|\itm{bytes}|, %rsi
  5716. callq collect
  5717. \end{lstlisting}
  5718. \begin{figure}[tp]
  5719. \fbox{
  5720. \begin{minipage}{0.96\textwidth}
  5721. \[
  5722. \begin{array}{lcl}
  5723. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5724. x86_1 &::= & \gray{ \key{.globl main} }\\
  5725. & & \gray{ \key{main:} \; \Instr\ldots }
  5726. \end{array}
  5727. \]
  5728. \end{minipage}
  5729. }
  5730. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5731. \label{fig:x86-2-concrete}
  5732. \end{figure}
  5733. \begin{figure}[tp]
  5734. \fbox{
  5735. \begin{minipage}{0.96\textwidth}
  5736. \small
  5737. \[
  5738. \begin{array}{lcl}
  5739. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5740. \mid \BYTEREG{\Reg}} \\
  5741. &\mid& (\key{Global}~\Var) \\
  5742. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5743. \end{array}
  5744. \]
  5745. \end{minipage}
  5746. }
  5747. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5748. \label{fig:x86-2}
  5749. \end{figure}
  5750. The concrete and abstract syntax of the $x86_2$ language is defined in
  5751. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5752. x86$_1$ just in the addition of the form for global variables.
  5753. %
  5754. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5755. \code{select-instructions} pass on the running example.
  5756. \begin{figure}[tbp]
  5757. \centering
  5758. % tests/s2_17.rkt
  5759. \begin{minipage}[t]{0.5\textwidth}
  5760. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5761. block35:
  5762. movq free_ptr(%rip), alloc9024
  5763. addq $16, free_ptr(%rip)
  5764. movq alloc9024, %r11
  5765. movq $131, 0(%r11)
  5766. movq alloc9024, %r11
  5767. movq vecinit9025, 8(%r11)
  5768. movq $0, initret9026
  5769. movq alloc9024, %r11
  5770. movq 8(%r11), tmp9034
  5771. movq tmp9034, %r11
  5772. movq 8(%r11), %rax
  5773. jmp conclusion
  5774. block36:
  5775. movq $0, collectret9027
  5776. jmp block35
  5777. block38:
  5778. movq free_ptr(%rip), alloc9020
  5779. addq $16, free_ptr(%rip)
  5780. movq alloc9020, %r11
  5781. movq $3, 0(%r11)
  5782. movq alloc9020, %r11
  5783. movq vecinit9021, 8(%r11)
  5784. movq $0, initret9022
  5785. movq alloc9020, vecinit9025
  5786. movq free_ptr(%rip), tmp9031
  5787. movq tmp9031, tmp9032
  5788. addq $16, tmp9032
  5789. movq fromspace_end(%rip), tmp9033
  5790. cmpq tmp9033, tmp9032
  5791. jl block36
  5792. jmp block37
  5793. block37:
  5794. movq %r15, %rdi
  5795. movq $16, %rsi
  5796. callq 'collect
  5797. jmp block35
  5798. block39:
  5799. movq $0, collectret9023
  5800. jmp block38
  5801. \end{lstlisting}
  5802. \end{minipage}
  5803. \begin{minipage}[t]{0.45\textwidth}
  5804. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5805. start:
  5806. movq $42, vecinit9021
  5807. movq free_ptr(%rip), tmp9028
  5808. movq tmp9028, tmp9029
  5809. addq $16, tmp9029
  5810. movq fromspace_end(%rip), tmp9030
  5811. cmpq tmp9030, tmp9029
  5812. jl block39
  5813. jmp block40
  5814. block40:
  5815. movq %r15, %rdi
  5816. movq $16, %rsi
  5817. callq 'collect
  5818. jmp block38
  5819. \end{lstlisting}
  5820. \end{minipage}
  5821. \caption{Output of the \code{select-instructions} pass.}
  5822. \label{fig:select-instr-output-gc}
  5823. \end{figure}
  5824. \clearpage
  5825. \section{Register Allocation}
  5826. \label{sec:reg-alloc-gc}
  5827. \index{register allocation}
  5828. As discussed earlier in this chapter, the garbage collector needs to
  5829. access all the pointers in the root set, that is, all variables that
  5830. are vectors. It will be the responsibility of the register allocator
  5831. to make sure that:
  5832. \begin{enumerate}
  5833. \item the root stack is used for spilling vector-typed variables, and
  5834. \item if a vector-typed variable is live during a call to the
  5835. collector, it must be spilled to ensure it is visible to the
  5836. collector.
  5837. \end{enumerate}
  5838. The later responsibility can be handled during construction of the
  5839. inference graph, by adding interference edges between the call-live
  5840. vector-typed variables and all the callee-saved registers. (They
  5841. already interfere with the caller-saved registers.) The type
  5842. information for variables is in the \code{Program} form, so we
  5843. recommend adding another parameter to the \code{build-interference}
  5844. function to communicate this alist.
  5845. The spilling of vector-typed variables to the root stack can be
  5846. handled after graph coloring, when choosing how to assign the colors
  5847. (integers) to registers and stack locations. The \code{Program} output
  5848. of this pass changes to also record the number of spills to the root
  5849. stack.
  5850. % build-interference
  5851. %
  5852. % callq
  5853. % extra parameter for var->type assoc. list
  5854. % update 'program' and 'if'
  5855. % allocate-registers
  5856. % allocate spilled vectors to the rootstack
  5857. % don't change color-graph
  5858. \section{Print x86}
  5859. \label{sec:print-x86-gc}
  5860. \index{prelude}\index{conclusion}
  5861. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5862. \code{print-x86} pass on the running example. In the prelude and
  5863. conclusion of the \code{main} function, we treat the root stack very
  5864. much like the regular stack in that we move the root stack pointer
  5865. (\code{r15}) to make room for the spills to the root stack, except
  5866. that the root stack grows up instead of down. For the running
  5867. example, there was just one spill so we increment \code{r15} by 8
  5868. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5869. One issue that deserves special care is that there may be a call to
  5870. \code{collect} prior to the initializing assignments for all the
  5871. variables in the root stack. We do not want the garbage collector to
  5872. accidentally think that some uninitialized variable is a pointer that
  5873. needs to be followed. Thus, we zero-out all locations on the root
  5874. stack in the prelude of \code{main}. In
  5875. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5876. %
  5877. \lstinline{movq $0, (%r15)}
  5878. %
  5879. accomplishes this task. The garbage collector tests each root to see
  5880. if it is null prior to dereferencing it.
  5881. \begin{figure}[htbp]
  5882. \begin{minipage}[t]{0.5\textwidth}
  5883. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5884. block35:
  5885. movq free_ptr(%rip), %rcx
  5886. addq $16, free_ptr(%rip)
  5887. movq %rcx, %r11
  5888. movq $131, 0(%r11)
  5889. movq %rcx, %r11
  5890. movq -8(%r15), %rax
  5891. movq %rax, 8(%r11)
  5892. movq $0, %rdx
  5893. movq %rcx, %r11
  5894. movq 8(%r11), %rcx
  5895. movq %rcx, %r11
  5896. movq 8(%r11), %rax
  5897. jmp conclusion
  5898. block36:
  5899. movq $0, %rcx
  5900. jmp block35
  5901. block38:
  5902. movq free_ptr(%rip), %rcx
  5903. addq $16, free_ptr(%rip)
  5904. movq %rcx, %r11
  5905. movq $3, 0(%r11)
  5906. movq %rcx, %r11
  5907. movq %rbx, 8(%r11)
  5908. movq $0, %rdx
  5909. movq %rcx, -8(%r15)
  5910. movq free_ptr(%rip), %rcx
  5911. addq $16, %rcx
  5912. movq fromspace_end(%rip), %rdx
  5913. cmpq %rdx, %rcx
  5914. jl block36
  5915. movq %r15, %rdi
  5916. movq $16, %rsi
  5917. callq collect
  5918. jmp block35
  5919. block39:
  5920. movq $0, %rcx
  5921. jmp block38
  5922. \end{lstlisting}
  5923. \end{minipage}
  5924. \begin{minipage}[t]{0.45\textwidth}
  5925. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5926. start:
  5927. movq $42, %rbx
  5928. movq free_ptr(%rip), %rdx
  5929. addq $16, %rdx
  5930. movq fromspace_end(%rip), %rcx
  5931. cmpq %rcx, %rdx
  5932. jl block39
  5933. movq %r15, %rdi
  5934. movq $16, %rsi
  5935. callq collect
  5936. jmp block38
  5937. .globl main
  5938. main:
  5939. pushq %rbp
  5940. movq %rsp, %rbp
  5941. pushq %r13
  5942. pushq %r12
  5943. pushq %rbx
  5944. pushq %r14
  5945. subq $0, %rsp
  5946. movq $16384, %rdi
  5947. movq $16, %rsi
  5948. callq initialize
  5949. movq rootstack_begin(%rip), %r15
  5950. movq $0, (%r15)
  5951. addq $8, %r15
  5952. jmp start
  5953. conclusion:
  5954. subq $8, %r15
  5955. addq $0, %rsp
  5956. popq %r14
  5957. popq %rbx
  5958. popq %r12
  5959. popq %r13
  5960. popq %rbp
  5961. retq
  5962. \end{lstlisting}
  5963. \end{minipage}
  5964. \caption{Output of the \code{print-x86} pass.}
  5965. \label{fig:print-x86-output-gc}
  5966. \end{figure}
  5967. \begin{figure}[p]
  5968. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5969. \node (R3) at (0,2) {\large $R_3$};
  5970. \node (R3-2) at (3,2) {\large $R_3$};
  5971. \node (R3-3) at (6,2) {\large $R_3$};
  5972. \node (R3-4) at (9,2) {\large $R_3$};
  5973. \node (R3-5) at (9,0) {\large $R'_3$};
  5974. \node (R3-6) at (6,0) {\large $R'_3$};
  5975. \node (C2-4) at (3,-2) {\large $C_2$};
  5976. \node (C2-3) at (0,-2) {\large $C_2$};
  5977. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5978. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5979. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5980. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5981. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5982. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5983. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5984. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5985. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5986. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5987. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5988. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5989. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5990. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5991. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5992. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5993. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5994. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5995. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5996. \end{tikzpicture}
  5997. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5998. \label{fig:R3-passes}
  5999. \end{figure}
  6000. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6001. for the compilation of $R_3$.
  6002. \section{Challenge: Simple Structures}
  6003. \label{sec:simple-structures}
  6004. \index{struct}
  6005. \index{structure}
  6006. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6007. $R^s_3$, which extends $R^3$ with support for simple structures.
  6008. Recall that a \code{struct} in Typed Racket is a user-defined data
  6009. type that contains named fields and that is heap allocated, similar to
  6010. a vector. The following is an example of a structure definition, in
  6011. this case the definition of a \code{point} type.
  6012. \begin{lstlisting}
  6013. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6014. \end{lstlisting}
  6015. \begin{figure}[tbp]
  6016. \centering
  6017. \fbox{
  6018. \begin{minipage}{0.96\textwidth}
  6019. \[
  6020. \begin{array}{lcl}
  6021. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6022. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6023. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6024. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6025. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6026. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6027. \mid (\key{and}\;\Exp\;\Exp)
  6028. \mid (\key{or}\;\Exp\;\Exp)
  6029. \mid (\key{not}\;\Exp) } \\
  6030. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6031. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6032. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6033. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6034. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6035. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6036. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6037. R_3 &::=& \Def \ldots \; \Exp
  6038. \end{array}
  6039. \]
  6040. \end{minipage}
  6041. }
  6042. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6043. (Figure~\ref{fig:r3-concrete-syntax}).}
  6044. \label{fig:r3s-concrete-syntax}
  6045. \end{figure}
  6046. An instance of a structure is created using function call syntax, with
  6047. the name of the structure in the function position:
  6048. \begin{lstlisting}
  6049. (point 7 12)
  6050. \end{lstlisting}
  6051. Function-call syntax is also used to read the value in a field of a
  6052. structure. The function name is formed by the structure name, a dash,
  6053. and the field name. The following example uses \code{point-x} and
  6054. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6055. instances.
  6056. \begin{center}
  6057. \begin{lstlisting}
  6058. (let ([pt1 (point 7 12)])
  6059. (let ([pt2 (point 4 3)])
  6060. (+ (- (point-x pt1) (point-x pt2))
  6061. (- (point-y pt1) (point-y pt2)))))
  6062. \end{lstlisting}
  6063. \end{center}
  6064. Similarly, to write to a field of a structure, use its set function,
  6065. whose name starts with \code{set-}, followed by the structure name,
  6066. then a dash, then the field name, and conclused with an exclamation
  6067. mark. The folowing example uses \code{set-point-x!} to change the
  6068. \code{x} field from \code{7} to \code{42}.
  6069. \begin{center}
  6070. \begin{lstlisting}
  6071. (let ([pt (point 7 12)])
  6072. (let ([_ (set-point-x! pt 42)])
  6073. (point-x pt)))
  6074. \end{lstlisting}
  6075. \end{center}
  6076. \begin{exercise}\normalfont
  6077. Extend your compiler with support for simple structures, compiling
  6078. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6079. structures and test your compiler.
  6080. \end{exercise}
  6081. \section{Challenge: Generational Collection}
  6082. The copying collector described in Section~\ref{sec:GC} can incur
  6083. significant runtime overhead because the call to \code{collect} takes
  6084. time proportional to all of the live data. One way to reduce this
  6085. overhead is to reduce how much data is inspected in each call to
  6086. \code{collect}. In particular, researchers have observed that recently
  6087. allocated data is more likely to become garbage then data that has
  6088. survived one or more previous calls to \code{collect}. This insight
  6089. motivated the creation of \emph{generational garbage collectors}
  6090. \index{generational garbage collector} that
  6091. 1) segragates data according to its age into two or more generations,
  6092. 2) allocates less space for younger generations, so collecting them is
  6093. faster, and more space for the older generations, and 3) performs
  6094. collection on the younger generations more frequently then for older
  6095. generations~\citep{Wilson:1992fk}.
  6096. For this challenge assignment, the goal is to adapt the copying
  6097. collector implemented in \code{runtime.c} to use two generations, one
  6098. for young data and one for old data. Each generation consists of a
  6099. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6100. \code{collect} function to use the two generations.
  6101. \begin{enumerate}
  6102. \item Copy the young generation's FromSpace to its ToSpace then switch
  6103. the role of the ToSpace and FromSpace
  6104. \item If there is enough space for the requested number of bytes in
  6105. the young FromSpace, then return from \code{collect}.
  6106. \item If there is not enough space in the young FromSpace for the
  6107. requested bytes, then move the data from the young generation to the
  6108. old one with the following steps:
  6109. \begin{enumerate}
  6110. \item If there is enough room in the old FromSpace, copy the young
  6111. FromSpace to the old FromSpace and then return.
  6112. \item If there is not enough room in the old FromSpace, then collect
  6113. the old generation by copying the old FromSpace to the old ToSpace
  6114. and swap the roles of the old FromSpace and ToSpace.
  6115. \item If there is enough room now, copy the young FromSpace to the
  6116. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6117. and ToSpace for the old generation. Copy the young FromSpace and
  6118. the old FromSpace into the larger FromSpace for the old
  6119. generation and then return.
  6120. \end{enumerate}
  6121. \end{enumerate}
  6122. We recommend that you generalize the \code{cheney} function so that it
  6123. can be used for all the copies mentioned above: between the young
  6124. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6125. between the young FromSpace and old FromSpace. This can be
  6126. accomplished by adding parameters to \code{cheney} that replace its
  6127. use of the global variables \code{fromspace\_begin},
  6128. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6129. Note that the collection of the young generation does not traverse the
  6130. old generation. This introduces a potential problem: there may be
  6131. young data that is only reachable through pointers in the old
  6132. generation. If these pointers are not taken into account, the
  6133. collector could throw away young data that is live! One solution,
  6134. called \emph{pointer recording}, is to maintain a set of all the
  6135. pointers from the old generation into the new generation and consider
  6136. this set as part of the root set. To maintain this set, the compiler
  6137. must insert extra instructions around every \code{vector-set!}. If the
  6138. vector being modified is in the old generation, and if the value being
  6139. written is a pointer into the new generation, than that pointer must
  6140. be added to the set. Also, if the value being overwritten was a
  6141. pointer into the new generation, then that pointer should be removed
  6142. from the set.
  6143. \begin{exercise}\normalfont
  6144. Adapt the \code{collect} function in \code{runtime.c} to implement
  6145. generational garbage collection, as outlined in this section.
  6146. Update the code generation for \code{vector-set!} to implement
  6147. pointer recording. Make sure that your new compiler and runtime
  6148. passes your test suite.
  6149. \end{exercise}
  6150. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6151. \chapter{Functions}
  6152. \label{ch:functions}
  6153. \index{function}
  6154. This chapter studies the compilation of functions similar to those
  6155. found in the C language. This corresponds to a subset of Typed Racket
  6156. in which only top-level function definitions are allowed. This kind of
  6157. function is an important stepping stone to implementing
  6158. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6159. is the topic of Chapter~\ref{ch:lambdas}.
  6160. \section{The $R_4$ Language}
  6161. The concrete and abstract syntax for function definitions and function
  6162. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6163. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6164. $R_4$ begin with zero or more function definitions. The function
  6165. names from these definitions are in-scope for the entire program,
  6166. including all other function definitions (so the ordering of function
  6167. definitions does not matter). The concrete syntax for function
  6168. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6169. where the first expression must
  6170. evaluate to a function and the rest are the arguments.
  6171. The abstract syntax for function application is
  6172. $\APPLY{\Exp}{\Exp\ldots}$.
  6173. %% The syntax for function application does not include an explicit
  6174. %% keyword, which is error prone when using \code{match}. To alleviate
  6175. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6176. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6177. Functions are first-class in the sense that a function pointer
  6178. \index{function pointer} is data and can be stored in memory or passed
  6179. as a parameter to another function. Thus, we introduce a function
  6180. type, written
  6181. \begin{lstlisting}
  6182. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6183. \end{lstlisting}
  6184. for a function whose $n$ parameters have the types $\Type_1$ through
  6185. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6186. these functions (with respect to Racket functions) is that they are
  6187. not lexically scoped. That is, the only external entities that can be
  6188. referenced from inside a function body are other globally-defined
  6189. functions. The syntax of $R_4$ prevents functions from being nested
  6190. inside each other.
  6191. \begin{figure}[tp]
  6192. \centering
  6193. \fbox{
  6194. \begin{minipage}{0.96\textwidth}
  6195. \small
  6196. \[
  6197. \begin{array}{lcl}
  6198. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6199. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6200. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6201. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  6202. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6203. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6204. \mid (\key{and}\;\Exp\;\Exp)
  6205. \mid (\key{or}\;\Exp\;\Exp)
  6206. \mid (\key{not}\;\Exp)} \\
  6207. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6208. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6209. (\key{vector-ref}\;\Exp\;\Int)} \\
  6210. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6211. \mid (\key{has-type}~\Exp~\Type)} \\
  6212. &\mid& (\Exp \; \Exp \ldots) \\
  6213. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  6214. R_4 &::=& \Def \ldots \; \Exp
  6215. \end{array}
  6216. \]
  6217. \end{minipage}
  6218. }
  6219. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6220. \label{fig:r4-concrete-syntax}
  6221. \end{figure}
  6222. \begin{figure}[tp]
  6223. \centering
  6224. \fbox{
  6225. \begin{minipage}{0.96\textwidth}
  6226. \small
  6227. \[
  6228. \begin{array}{lcl}
  6229. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6230. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6231. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6232. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6233. &\mid& \gray{ \BOOL{\itm{bool}}
  6234. \mid \AND{\Exp}{\Exp} }\\
  6235. &\mid& \gray{ \OR{\Exp}{\Exp}
  6236. \mid \NOT{\Exp} } \\
  6237. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6238. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6239. &\mid& \gray{ \VECTOR{\Exp} } \\
  6240. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6241. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6242. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6243. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6244. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  6245. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  6246. \end{array}
  6247. \]
  6248. \end{minipage}
  6249. }
  6250. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6251. \label{fig:r4-syntax}
  6252. \end{figure}
  6253. The program in Figure~\ref{fig:r4-function-example} is a
  6254. representative example of defining and using functions in $R_4$. We
  6255. define a function \code{map-vec} that applies some other function
  6256. \code{f} to both elements of a vector and returns a new
  6257. vector containing the results. We also define a function \code{add1}.
  6258. The program applies
  6259. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6260. \code{(vector 1 42)}, from which we return the \code{42}.
  6261. \begin{figure}[tbp]
  6262. \begin{lstlisting}
  6263. (define (map-vec [f : (Integer -> Integer)]
  6264. [v : (Vector Integer Integer)])
  6265. : (Vector Integer Integer)
  6266. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6267. (define (add1 [x : Integer]) : Integer
  6268. (+ x 1))
  6269. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6270. \end{lstlisting}
  6271. \caption{Example of using functions in $R_4$.}
  6272. \label{fig:r4-function-example}
  6273. \end{figure}
  6274. The definitional interpreter for $R_4$ is in
  6275. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6276. responsible for setting up the mutual recursion between the top-level
  6277. function definitions. We use the classic back-patching \index{back-patching}
  6278. approach that uses mutable variables and makes two passes over the function
  6279. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6280. top-level environment using a mutable cons cell for each function
  6281. definition. Note that the \code{lambda} value for each function is
  6282. incomplete; it does not yet include the environment. Once the
  6283. top-level environment is constructed, we then iterate over it and
  6284. update the \code{lambda} values to use the top-level environment.
  6285. \begin{figure}[tp]
  6286. \begin{lstlisting}
  6287. (define (interp-exp env)
  6288. (lambda (e)
  6289. (define recur (interp-exp env))
  6290. (match e
  6291. ...
  6292. [(Apply fun args)
  6293. (define fun-val (recur fun))
  6294. (define arg-vals (for/list ([e args]) (recur e)))
  6295. (match fun-val
  6296. [`(lambda (,xs ...) ,body ,fun-env)
  6297. (define new-env (append (map cons xs arg-vals) fun-env))
  6298. ((interp-exp new-env) body)])]
  6299. ...
  6300. )))
  6301. (define (interp-def d)
  6302. (match d
  6303. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6304. (mcons f `(lambda ,xs ,body ()))]
  6305. ))
  6306. (define (interp-R4 p)
  6307. (match p
  6308. [(ProgramDefsExp info ds body)
  6309. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6310. (for/list ([b top-level])
  6311. (set-mcdr! b (match (mcdr b)
  6312. [`(lambda ,xs ,body ())
  6313. `(lambda ,xs ,body ,top-level)])))
  6314. ((interp-exp top-level) body))]
  6315. ))
  6316. \end{lstlisting}
  6317. \caption{Interpreter for the $R_4$ language.}
  6318. \label{fig:interp-R4}
  6319. \end{figure}
  6320. \margincomment{TODO: explain type checker}
  6321. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6322. \begin{figure}[tp]
  6323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6324. (define (fun-def-name d)
  6325. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6326. (define (fun-def-type d)
  6327. (match d
  6328. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6329. (define (type-check-exp env)
  6330. (lambda (e)
  6331. (match e
  6332. ...
  6333. [(Apply e es)
  6334. (define-values (e^ ty) ((type-check-exp env) e))
  6335. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6336. ((type-check-exp env) e)))
  6337. (match ty
  6338. [`(,ty^* ... -> ,rt)
  6339. (for ([arg-ty ty*] [prm-ty ty^*])
  6340. (unless (equal? arg-ty prm-ty)
  6341. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6342. (values (HasType (Apply e^ e*) rt) rt)]
  6343. [else (error "expected a function, not" ty)])])))
  6344. (define (type-check-def env)
  6345. (lambda (e)
  6346. (match e
  6347. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6348. (define new-env (append (map cons xs ps) env))
  6349. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6350. (unless (equal? ty^ rt)
  6351. (error "body type ~a not equal to return type ~a" ty^ rt))
  6352. (Def f p:t* rt info body^)])))
  6353. (define (type-check env)
  6354. (lambda (e)
  6355. (match e
  6356. [(ProgramDefsExp info ds body)
  6357. (define new-env (for/list ([d ds])
  6358. (cons (fun-def-name d) (fun-def-type d))))
  6359. (define ds^ (for/list ([d ds])
  6360. ((type-check-def new-env) d)))
  6361. (define-values (body^ ty) ((type-check-exp new-env) body))
  6362. (unless (equal? ty 'Integer)
  6363. (error "result of the program must be an integer, not " ty))
  6364. (ProgramDefsExp info ds^ body^)]
  6365. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6366. \end{lstlisting}
  6367. \caption{Type checker for the $R_4$ language.}
  6368. \label{fig:type-check-R4}
  6369. \end{figure}
  6370. \section{Functions in x86}
  6371. \label{sec:fun-x86}
  6372. \margincomment{\tiny Make sure callee-saved registers are discussed
  6373. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6374. \margincomment{\tiny Talk about the return address on the
  6375. stack and what callq and retq does.\\ --Jeremy }
  6376. The x86 architecture provides a few features to support the
  6377. implementation of functions. We have already seen that x86 provides
  6378. labels so that one can refer to the location of an instruction, as is
  6379. needed for jump instructions. Labels can also be used to mark the
  6380. beginning of the instructions for a function. Going further, we can
  6381. obtain the address of a label by using the \key{leaq} instruction and
  6382. PC-relative addressing. For example, the following puts the
  6383. address of the \code{add1} label into the \code{rbx} register.
  6384. \begin{lstlisting}
  6385. leaq add1(%rip), %rbx
  6386. \end{lstlisting}
  6387. The instruction pointer register \key{rip} (aka. the program counter
  6388. \index{program counter}) always points to the next instruction to be
  6389. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6390. linker computes the distance $d$ between the address of \code{add1}
  6391. and where the \code{rip} would be at that moment and then changes
  6392. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6393. the address of \code{add1}.
  6394. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6395. jump to a function whose location is given by a label. To support
  6396. function calls in this chapter we instead will be jumping to a
  6397. function whose location is given by an address in a register, that is,
  6398. we need to make an \emph{indirect function call}. The x86 syntax for
  6399. this is a \code{callq} instruction but with an asterisk before the
  6400. register name.\index{indirect function call}
  6401. \begin{lstlisting}
  6402. callq *%rbx
  6403. \end{lstlisting}
  6404. \subsection{Calling Conventions}
  6405. \index{calling conventions}
  6406. The \code{callq} instruction provides partial support for implementing
  6407. functions: it pushes the return address on the stack and it jumps to
  6408. the target. However, \code{callq} does not handle
  6409. \begin{enumerate}
  6410. \item parameter passing,
  6411. \item pushing frames on the procedure call stack and popping them off,
  6412. or
  6413. \item determining how registers are shared by different functions.
  6414. \end{enumerate}
  6415. These issues require coordination between the caller and the callee,
  6416. which is often assembly code written by different programmers or
  6417. generated by different compilers. As a result, people have developed
  6418. \emph{conventions} that govern how functions calls are performed.
  6419. Here we use conventions that are compatible with those of the
  6420. \code{gcc} compiler~\citep{Matz:2013aa}.
  6421. Regarding (1) parameter passing, the convention is to use the
  6422. following six registers:
  6423. \begin{lstlisting}
  6424. rdi rsi rdx rcx r8 r9
  6425. \end{lstlisting}
  6426. in that order, to pass arguments to a function. If there are more than
  6427. six arguments, then the convention is to use space on the frame of the
  6428. caller for the rest of the arguments. However, to ease the
  6429. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  6430. we arrange to never need more than six arguments.
  6431. %
  6432. The register \code{rax} is for the return value of the function.
  6433. \index{prelude}\index{conclusion}
  6434. Regarding (2) frames \index{frame} and the procedure call stack
  6435. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6436. the stack grows down, with each function call using a chunk of space
  6437. called a frame. The caller sets the stack pointer, register
  6438. \code{rsp}, to the last data item in its frame. The callee must not
  6439. change anything in the caller's frame, that is, anything that is at or
  6440. above the stack pointer. The callee is free to use locations that are
  6441. below the stack pointer.
  6442. Recall that we are storing variables of vector type on the root stack.
  6443. So the prelude needs to move the root stack pointer \code{r15} up and
  6444. the conclusion needs to move the root stack pointer back down. Also,
  6445. the prelude must initialize to \code{0} this frame's slots in the root
  6446. stack to signal to the garbage collector that those slots do not yet
  6447. contain a pointer to a vector. Otherwise the garbage collector will
  6448. interpret the garbage bits in those slots as memory addresses and try
  6449. to traverse them, causing serious mayhem!
  6450. Regarding (3) the sharing of registers between different functions,
  6451. recall from Section~\ref{sec:calling-conventions} that the registers
  6452. are divided into two groups, the caller-saved registers and the
  6453. callee-saved registers. The caller should assume that all the
  6454. caller-saved registers get overwritten with arbitrary values by the
  6455. callee. That is why we recommend in
  6456. Section~\ref{sec:calling-conventions} that variables that are live
  6457. during a function call should not be assigned to caller-saved
  6458. registers.
  6459. On the flip side, if the callee wants to use a callee-saved register,
  6460. the callee must save the contents of those registers on their stack
  6461. frame and then put them back prior to returning to the caller. That
  6462. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6463. the register allocator assigns a variable to a callee-saved register,
  6464. then the prelude of the \code{main} function must save that register
  6465. to the stack and the conclusion of \code{main} must restore it. This
  6466. recommendation now generalizes to all functions.
  6467. Also recall that the base pointer, register \code{rbp}, is used as a
  6468. point-of-reference within a frame, so that each local variable can be
  6469. accessed at a fixed offset from the base pointer
  6470. (Section~\ref{sec:x86}).
  6471. %
  6472. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6473. and callee frames.
  6474. \begin{figure}[tbp]
  6475. \centering
  6476. \begin{tabular}{r|r|l|l} \hline
  6477. Caller View & Callee View & Contents & Frame \\ \hline
  6478. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6479. 0(\key{\%rbp}) & & old \key{rbp} \\
  6480. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6481. \ldots & & \ldots \\
  6482. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6483. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6484. \ldots & & \ldots \\
  6485. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6486. %% & & \\
  6487. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6488. %% & \ldots & \ldots \\
  6489. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6490. \hline
  6491. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6492. & 0(\key{\%rbp}) & old \key{rbp} \\
  6493. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6494. & \ldots & \ldots \\
  6495. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6496. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6497. & \ldots & \ldots \\
  6498. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6499. \end{tabular}
  6500. \caption{Memory layout of caller and callee frames.}
  6501. \label{fig:call-frames}
  6502. \end{figure}
  6503. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6504. %% local variables and for storing the values of callee-saved registers
  6505. %% (we shall refer to all of these collectively as ``locals''), and that
  6506. %% at the beginning of a function we move the stack pointer \code{rsp}
  6507. %% down to make room for them.
  6508. %% We recommend storing the local variables
  6509. %% first and then the callee-saved registers, so that the local variables
  6510. %% can be accessed using \code{rbp} the same as before the addition of
  6511. %% functions.
  6512. %% To make additional room for passing arguments, we shall
  6513. %% move the stack pointer even further down. We count how many stack
  6514. %% arguments are needed for each function call that occurs inside the
  6515. %% body of the function and find their maximum. Adding this number to the
  6516. %% number of locals gives us how much the \code{rsp} should be moved at
  6517. %% the beginning of the function. In preparation for a function call, we
  6518. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6519. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6520. %% so on.
  6521. %% Upon calling the function, the stack arguments are retrieved by the
  6522. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6523. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6524. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6525. %% the layout of the caller and callee frames. Notice how important it is
  6526. %% that we correctly compute the maximum number of arguments needed for
  6527. %% function calls; if that number is too small then the arguments and
  6528. %% local variables will smash into each other!
  6529. \subsection{Efficient Tail Calls}
  6530. \label{sec:tail-call}
  6531. In general, the amount of stack space used by a program is determined
  6532. by the longest chain of nested function calls. That is, if function
  6533. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6534. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6535. $n$ can grow quite large in the case of recursive or mutually
  6536. recursive functions. However, in some cases we can arrange to use only
  6537. constant space, i.e. $O(1)$, instead of $O(n)$.
  6538. If a function call is the last action in a function body, then that
  6539. call is said to be a \emph{tail call}\index{tail call}.
  6540. For example, in the following
  6541. program, the recursive call to \code{tail-sum} is a tail call.
  6542. \begin{center}
  6543. \begin{lstlisting}
  6544. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6545. (if (eq? n 0)
  6546. r
  6547. (tail-sum (- n 1) (+ n r))))
  6548. (+ (tail-sum 5 0) 27)
  6549. \end{lstlisting}
  6550. \end{center}
  6551. At a tail call, the frame of the caller is no longer needed, so we
  6552. can pop the caller's frame before making the tail call. With this
  6553. approach, a recursive function that only makes tail calls will only
  6554. use $O(1)$ stack space. Functional languages like Racket typically
  6555. rely heavily on recursive functions, so they typically guarantee that
  6556. all tail calls will be optimized in this way.
  6557. \index{frame}
  6558. However, some care is needed with regards to argument passing in tail
  6559. calls. As mentioned above, for arguments beyond the sixth, the
  6560. convention is to use space in the caller's frame for passing
  6561. arguments. But for a tail call we pop the caller's frame and can no
  6562. longer use it. Another alternative is to use space in the callee's
  6563. frame for passing arguments. However, this option is also problematic
  6564. because the caller and callee's frame overlap in memory. As we begin
  6565. to copy the arguments from their sources in the caller's frame, the
  6566. target locations in the callee's frame might overlap with the sources
  6567. for later arguments! We solve this problem by not using the stack for
  6568. passing more than six arguments but instead using the heap, as we
  6569. describe in the Section~\ref{sec:limit-functions-r4}.
  6570. As mentioned above, for a tail call we pop the caller's frame prior to
  6571. making the tail call. The instructions for popping a frame are the
  6572. instructions that we usually place in the conclusion of a
  6573. function. Thus, we also need to place such code immediately before
  6574. each tail call. These instructions include restoring the callee-saved
  6575. registers, so it is good that the argument passing registers are all
  6576. caller-saved registers.
  6577. One last note regarding which instruction to use to make the tail
  6578. call. When the callee is finished, it should not return to the current
  6579. function, but it should return to the function that called the current
  6580. one. Thus, the return address that is already on the stack is the
  6581. right one, and we should not use \key{callq} to make the tail call, as
  6582. that would unnecessarily overwrite the return address. Instead we can
  6583. simply use the \key{jmp} instruction. Like the indirect function call,
  6584. we write an \emph{indirect jump}\index{indirect jump} with a register
  6585. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6586. jump target because the preceding conclusion overwrites just about
  6587. everything else.
  6588. \begin{lstlisting}
  6589. jmp *%rax
  6590. \end{lstlisting}
  6591. \section{Shrink $R_4$}
  6592. \label{sec:shrink-r4}
  6593. The \code{shrink} pass performs a minor modification to ease the
  6594. later passes. This pass introduces an explicit \code{main} function
  6595. and changes the top \code{ProgramDefsExp} form to
  6596. \code{ProgramDefs} as follows.
  6597. \begin{lstlisting}
  6598. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6599. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6600. \end{lstlisting}
  6601. where $\itm{mainDef}$ is
  6602. \begin{lstlisting}
  6603. (Def 'main '() 'Integer '() |$\Exp'$|)
  6604. \end{lstlisting}
  6605. \section{Reveal Functions and the $F_1$ language}
  6606. \label{sec:reveal-functions-r4}
  6607. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6608. respect: it conflates the use of function names and local
  6609. variables. This is a problem because we need to compile the use of a
  6610. function name differently than the use of a local variable; we need to
  6611. use \code{leaq} to convert the function name (a label in x86) to an
  6612. address in a register. Thus, it is a good idea to create a new pass
  6613. that changes function references from just a symbol $f$ to
  6614. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6615. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6616. \begin{figure}[tp]
  6617. \centering
  6618. \fbox{
  6619. \begin{minipage}{0.96\textwidth}
  6620. \[
  6621. \begin{array}{lcl}
  6622. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6623. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6624. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6625. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6626. &\mid& \gray{ \BOOL{\itm{bool}}
  6627. \mid \AND{\Exp}{\Exp} }\\
  6628. &\mid& \gray{ \OR{\Exp}{\Exp}
  6629. \mid \NOT{\Exp} } \\
  6630. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6631. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6632. &\mid& \gray{ \VECTOR{\Exp} } \\
  6633. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6634. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6635. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6636. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6637. &\mid& \FUNREF{\Var}\\
  6638. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6639. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6640. \end{array}
  6641. \]
  6642. \end{minipage}
  6643. }
  6644. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6645. (Figure~\ref{fig:r4-syntax}).}
  6646. \label{fig:f1-syntax}
  6647. \end{figure}
  6648. %% Distinguishing between calls in tail position and non-tail position
  6649. %% requires the pass to have some notion of context. We recommend using
  6650. %% two mutually recursive functions, one for processing expressions in
  6651. %% tail position and another for the rest.
  6652. Placing this pass after \code{uniquify} will make sure that there are
  6653. no local variables and functions that share the same name. On the
  6654. other hand, \code{reveal-functions} needs to come before the
  6655. \code{explicate-control} pass because that pass helps us compile
  6656. \code{FunRef} forms into assignment statements.
  6657. \section{Limit Functions}
  6658. \label{sec:limit-functions-r4}
  6659. Recall that we wish to limit the number of function parameters to six
  6660. so that we do not need to use the stack for argument passing, which
  6661. makes it easier to implement efficient tail calls. However, because
  6662. the input language $R_4$ supports arbitrary numbers of function
  6663. arguments, we have some work to do!
  6664. This pass transforms functions and function calls that involve more
  6665. than six arguments to pass the first five arguments as usual, but it
  6666. packs the rest of the arguments into a vector and passes it as the
  6667. sixth argument.
  6668. Each function definition with too many parameters is transformed as
  6669. follows.
  6670. \begin{lstlisting}
  6671. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6672. |$\Rightarrow$|
  6673. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6674. \end{lstlisting}
  6675. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6676. the occurences of the later parameters with vector references.
  6677. \begin{lstlisting}
  6678. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6679. \end{lstlisting}
  6680. For function calls with too many arguments, the \code{limit-functions}
  6681. pass transforms them in the following way.
  6682. \begin{tabular}{lll}
  6683. \begin{minipage}{0.2\textwidth}
  6684. \begin{lstlisting}
  6685. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6686. \end{lstlisting}
  6687. \end{minipage}
  6688. &
  6689. $\Rightarrow$
  6690. &
  6691. \begin{minipage}{0.4\textwidth}
  6692. \begin{lstlisting}
  6693. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6694. \end{lstlisting}
  6695. \end{minipage}
  6696. \end{tabular}
  6697. \section{Remove Complex Operators and Operands}
  6698. \label{sec:rco-r4}
  6699. The primary decisions to make for this pass is whether to classify
  6700. \code{FunRef} and \code{Apply} as either simple or complex
  6701. expressions. Recall that a simple expression will eventually end up as
  6702. just an ``immediate'' argument of an x86 instruction. Function
  6703. application will be translated to a sequence of instructions, so
  6704. \code{Apply} must be classified as complex expression. Regarding
  6705. \code{FunRef}, as discussed above, the function label needs to
  6706. be converted to an address using the \code{leaq} instruction. Thus,
  6707. even though \code{FunRef} seems rather simple, it needs to be
  6708. classified as a complex expression so that we generate an assignment
  6709. statement with a left-hand side that can serve as the target of the
  6710. \code{leaq}.
  6711. \section{Explicate Control and the $C_3$ language}
  6712. \label{sec:explicate-control-r4}
  6713. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6714. the concrete and abstract syntax for $C_3$, the output of
  6715. \key{explicate-control}. The three mutually recursive functions for
  6716. this pass, for assignment, tail, and predicate contexts, must all be
  6717. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6718. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6719. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6720. $C_3$. We recommend defining a new function for processing function
  6721. definitions. This code is similar to the case for \code{Program} in
  6722. $R_3$. The top-level \code{explicate-control} function that handles
  6723. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6724. to all the function definitions.
  6725. \begin{figure}[tp]
  6726. \fbox{
  6727. \begin{minipage}{0.96\textwidth}
  6728. \[
  6729. \begin{array}{lcl}
  6730. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6731. \\
  6732. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6733. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6734. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6735. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6736. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6737. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6738. &\mid& \itm{label} \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6739. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6740. \mid (\key{collect} \,\itm{int}) }\\
  6741. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6742. &\mid& \gray{(\key{goto}\,\itm{label})
  6743. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6744. &\mid& (\Arg\,\Arg\ldots) \\
  6745. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6746. C_3 & ::= & \Def\ldots
  6747. \end{array}
  6748. \]
  6749. \end{minipage}
  6750. }
  6751. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6752. \label{fig:c3-concrete-syntax}
  6753. \end{figure}
  6754. \begin{figure}[tp]
  6755. \fbox{
  6756. \begin{minipage}{0.96\textwidth}
  6757. UNDER CONSTRUCTION
  6758. \end{minipage}
  6759. }
  6760. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6761. \label{fig:c3-syntax}
  6762. \end{figure}
  6763. \section{Uncover Locals}
  6764. \label{sec:uncover-locals-r4}
  6765. The function for processing $\Tail$ should be updated with a case for
  6766. \code{TailCall}. We also recommend creating a new function for
  6767. processing function definitions. Each function definition in $C_3$ has
  6768. its own set of local variables, so the code for function definitions
  6769. should be similar to the case for the \code{Program} form in $C_2$.
  6770. \section{Select Instructions and the x86$_3$ Language}
  6771. \label{sec:select-r4}
  6772. \index{instruction selection}
  6773. The output of select instructions is a program in the x86$_3$
  6774. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6775. \index{x86}
  6776. \begin{figure}[tp]
  6777. \fbox{
  6778. \begin{minipage}{0.96\textwidth}
  6779. \[
  6780. \begin{array}{lcl}
  6781. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6782. \mid (\key{deref}\,\Reg\,\Int) } \\
  6783. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6784. \mid (\key{global}\; \itm{name}) } \\
  6785. &\mid& (\key{fun-ref}\; \itm{label})\\
  6786. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6787. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6788. (\key{subq} \; \Arg\; \Arg) \mid
  6789. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6790. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6791. (\key{pushq}\;\Arg) \mid
  6792. (\key{popq}\;\Arg) \mid
  6793. (\key{retq}) } \\
  6794. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6795. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6796. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6797. \mid (\key{jmp} \; \itm{label})
  6798. \mid (\key{j}\itm{cc} \; \itm{label})
  6799. \mid (\key{label} \; \itm{label}) } \\
  6800. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6801. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6802. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6803. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6804. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6805. \end{array}
  6806. \]
  6807. \end{minipage}
  6808. }
  6809. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6810. \label{fig:x86-3-concrete}
  6811. \end{figure}
  6812. \begin{figure}[tp]
  6813. UNDER CONSTRUCTION
  6814. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6815. \label{fig:x86-3}
  6816. \end{figure}
  6817. \margincomment{TODO: abstract syntax for $x86_3$.}
  6818. An assignment of \code{FunRef} becomes a \code{leaq} instruction
  6819. as follows: \\
  6820. \begin{tabular}{lll}
  6821. \begin{minipage}{0.35\textwidth}
  6822. \begin{lstlisting}
  6823. (Assign |$\itm{lhs}$| (FunRef |$f$|))
  6824. \end{lstlisting}
  6825. \end{minipage}
  6826. &
  6827. $\Rightarrow$
  6828. &
  6829. \begin{minipage}{0.4\textwidth}
  6830. \begin{lstlisting}
  6831. (Instr 'leaq (list (FunRef |$f$|) |$\itm{lhs}'$|))
  6832. \end{lstlisting}
  6833. \end{minipage}
  6834. \end{tabular} \\
  6835. Regarding function definitions, we need to remove the parameters and
  6836. instead perform parameter passing in terms of the conventions
  6837. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6838. in the argument passing registers. We recommend turning the parameters
  6839. into local variables and generating instructions at the beginning of
  6840. the function to move from the argument passing registers to these
  6841. local variables.
  6842. \begin{lstlisting}
  6843. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6844. |$\Rightarrow$|
  6845. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6846. \end{lstlisting}
  6847. The $G'$ control-flow graph is the same as $G$ except that the
  6848. \code{start} block is modified to add the instructions for moving from
  6849. the argument registers to the parameter variables. So the \code{start}
  6850. block of $G$ shown on the left is changed to the code on the right.
  6851. \begin{center}
  6852. \begin{minipage}{0.3\textwidth}
  6853. \begin{lstlisting}
  6854. start:
  6855. |$\itm{instr}_1$|
  6856. |$\vdots$|
  6857. |$\itm{instr}_n$|
  6858. \end{lstlisting}
  6859. \end{minipage}
  6860. $\Rightarrow$
  6861. \begin{minipage}{0.3\textwidth}
  6862. \begin{lstlisting}
  6863. start:
  6864. movq %rdi, |$x_1$|
  6865. movq %rsi, |$x_2$|
  6866. |$\vdots$|
  6867. |$\itm{instr}_1$|
  6868. |$\vdots$|
  6869. |$\itm{instr}_n$|
  6870. \end{lstlisting}
  6871. \end{minipage}
  6872. \end{center}
  6873. By changing the parameters to local variables, we are giving the
  6874. register allocator control over which registers or stack locations to
  6875. use for them. If you implemented the move-biasing challenge
  6876. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6877. assign the parameter variables to the corresponding argument register,
  6878. in which case the \code{patch-instructions} pass will remove the
  6879. \code{movq} instruction. Also, note that the register allocator will
  6880. perform liveness analysis on this sequence of move instructions and
  6881. build the interference graph. So, for example, $x_1$ will be marked as
  6882. interfering with \code{rsi} and that will prevent the assignment of
  6883. $x_1$ to \code{rsi}, which is good, because that would overwrite the
  6884. argument that needs to move into $x_2$.
  6885. Next, consider the compilation of function calls. In the mirror image
  6886. of handling the parameters of function definitions, the arguments need
  6887. to be moved to the argument passing registers. The function call
  6888. itself is performed with an indirect function call. The return value
  6889. from the function is stored in \code{rax}, so it needs to be moved
  6890. into the \itm{lhs}.
  6891. \begin{lstlisting}
  6892. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  6893. |$\Rightarrow$|
  6894. movq |$\itm{arg}_1$|, %rdi
  6895. movq |$\itm{arg}_2$|, %rsi
  6896. |$\vdots$|
  6897. callq *|\itm{fun}|
  6898. movq %rax, |\itm{lhs}|
  6899. \end{lstlisting}
  6900. Regarding tail calls, the parameter passing is the same as non-tail
  6901. calls: generate instructions to move the arguments into to the
  6902. argument passing registers. After that we need to pop the frame from
  6903. the procedure call stack. However, we do not yet know how big the
  6904. frame is; that gets determined during register allocation. So instead
  6905. of generating those instructions here, we invent a new instruction
  6906. that means ``pop the frame and then do an indirect jump'', which we
  6907. name \code{TailJmp}.
  6908. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6909. using the label \code{start} for the initial block of a program, and
  6910. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6911. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  6912. can be compiled to an assignment to \code{rax} followed by a jump to
  6913. \code{conclusion}. With the addition of function definitions, we will
  6914. have a starting block and conclusion for each function, but their
  6915. labels need to be unique. We recommend prepending the function's name
  6916. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6917. labels. (Alternatively, one could \code{gensym} labels for the start
  6918. and conclusion and store them in the $\itm{info}$ field of the
  6919. function definition.)
  6920. \section{Uncover Live}
  6921. %% The rest of the passes need only minor modifications to handle the new
  6922. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6923. %% \code{leaq}.
  6924. The \code{IndirectCallq} instruction should be treated like
  6925. \code{Callq} regarding its written locations $W$, in that they should
  6926. include all the caller-saved registers. Recall that the reason for
  6927. that is to force call-live variables to be assigned to callee-saved
  6928. registers or to be spilled to the stack.
  6929. \section{Build Interference Graph}
  6930. With the addition of function definitions, we compute an interference
  6931. graph for each function (not just one for the whole program).
  6932. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6933. spill vector-typed variables that are live during a call to the
  6934. \code{collect}. With the addition of functions to our language, we
  6935. need to revisit this issue. Many functions will perform allocation and
  6936. therefore have calls to the collector inside of them. Thus, we should
  6937. not only spill a vector-typed variable when it is live during a call
  6938. to \code{collect}, but we should spill the variable if it is live
  6939. during any function call. Thus, in the \code{build-interference} pass,
  6940. we recommend adding interference edges between call-live vector-typed
  6941. variables and the callee-saved registers (in addition to the usual
  6942. addition of edges between call-live variables and the caller-saved
  6943. registers).
  6944. \section{Patch Instructions}
  6945. In \code{patch-instructions}, you should deal with the x86
  6946. idiosyncrasy that the destination argument of \code{leaq} must be a
  6947. register. Additionally, you should ensure that the argument of
  6948. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  6949. code generation more convenient, because we will be trampling many
  6950. registers before the tail call (as explained below).
  6951. \section{Print x86}
  6952. For the \code{print-x86} pass, we recommend the following translations:
  6953. \begin{lstlisting}
  6954. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6955. (IndirectCallq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6956. \end{lstlisting}
  6957. Handling \code{TailJmp} requires a bit more care. A straightforward
  6958. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, which
  6959. is what we will want to do, but before the jump we need to pop the
  6960. current frame. So we need to restore the state of the registers to the
  6961. point they were at when the current function was called. This
  6962. sequence of instructions is the same as the code for the conclusion of
  6963. a function.
  6964. Note that your \code{print-x86} pass needs to add the code for saving
  6965. and restoring callee-saved registers, if you have not already
  6966. implemented that. This is necessary when generating code for function
  6967. definitions.
  6968. \section{An Example Translation}
  6969. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6970. function in $R_4$ to x86. The figure also includes the results of the
  6971. \code{explicate-control} and \code{select-instructions} passes. We
  6972. have omitted the \code{HasType} AST nodes for readability.
  6973. \begin{figure}[tbp]
  6974. \begin{tabular}{ll}
  6975. \begin{minipage}{0.5\textwidth}
  6976. % s3_2.rkt
  6977. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6978. (define (add [x : Integer] [y : Integer])
  6979. : Integer
  6980. (+ x y))
  6981. (add 40 2)
  6982. \end{lstlisting}
  6983. $\Downarrow$
  6984. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6985. (define (add86 [x87 : Integer]
  6986. [y88 : Integer]) : Integer
  6987. add86start:
  6988. return (+ x87 y88);
  6989. )
  6990. (define (main) : Integer ()
  6991. mainstart:
  6992. tmp89 = (fun-ref add86);
  6993. (tail-call tmp89 40 2)
  6994. )
  6995. \end{lstlisting}
  6996. \end{minipage}
  6997. &
  6998. $\Rightarrow$
  6999. \begin{minipage}{0.5\textwidth}
  7000. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7001. (define (add86) : Integer
  7002. add86start:
  7003. movq %rdi, x87
  7004. movq %rsi, y88
  7005. movq x87, %rax
  7006. addq y88, %rax
  7007. jmp add11389conclusion
  7008. )
  7009. (define (main) : Integer
  7010. mainstart:
  7011. leaq (fun-ref add86), tmp89
  7012. movq $40, %rdi
  7013. movq $2, %rsi
  7014. tail-jmp tmp89
  7015. )
  7016. \end{lstlisting}
  7017. $\Downarrow$
  7018. \end{minipage}
  7019. \end{tabular}
  7020. \begin{tabular}{ll}
  7021. \begin{minipage}{0.3\textwidth}
  7022. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7023. .globl add86
  7024. .align 16
  7025. add86:
  7026. pushq %rbp
  7027. movq %rsp, %rbp
  7028. jmp add86start
  7029. add86start:
  7030. movq %rdi, %rax
  7031. addq %rsi, %rax
  7032. jmp add86conclusion
  7033. add86conclusion:
  7034. popq %rbp
  7035. retq
  7036. \end{lstlisting}
  7037. \end{minipage}
  7038. &
  7039. \begin{minipage}{0.5\textwidth}
  7040. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7041. .globl main
  7042. .align 16
  7043. main:
  7044. pushq %rbp
  7045. movq %rsp, %rbp
  7046. movq $16384, %rdi
  7047. movq $16384, %rsi
  7048. callq initialize
  7049. movq rootstack_begin(%rip), %r15
  7050. jmp mainstart
  7051. mainstart:
  7052. leaq add86(%rip), %rcx
  7053. movq $40, %rdi
  7054. movq $2, %rsi
  7055. movq %rcx, %rax
  7056. popq %rbp
  7057. jmp *%rax
  7058. mainconclusion:
  7059. popq %rbp
  7060. retq
  7061. \end{lstlisting}
  7062. \end{minipage}
  7063. \end{tabular}
  7064. \caption{Example compilation of a simple function to x86.}
  7065. \label{fig:add-fun}
  7066. \end{figure}
  7067. \begin{exercise}\normalfont
  7068. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7069. Create 5 new programs that use functions, including examples that pass
  7070. functions and return functions from other functions and including
  7071. recursive functions. Test your compiler on these new programs and all
  7072. of your previously created test programs.
  7073. \end{exercise}
  7074. \begin{figure}[p]
  7075. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7076. \node (R4) at (0,2) {\large $R_4$};
  7077. \node (R4-2) at (3,2) {\large $R_4$};
  7078. \node (R4-3) at (6,2) {\large $R_4$};
  7079. \node (F1-1) at (12,0) {\large $F_1$};
  7080. \node (F1-2) at (9,0) {\large $F_1$};
  7081. \node (F1-3) at (6,0) {\large $F_1$};
  7082. \node (F1-4) at (3,0) {\large $F_1$};
  7083. \node (C3-1) at (6,-2) {\large $C_3$};
  7084. \node (C3-2) at (3,-2) {\large $C_3$};
  7085. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7086. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7087. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7088. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7089. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7090. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7091. \path[->,bend left=15] (R4) edge [above] node
  7092. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7093. \path[->,bend left=15] (R4-2) edge [above] node
  7094. {\ttfamily\footnotesize uniquify} (R4-3);
  7095. \path[->,bend left=15] (R4-3) edge [right] node
  7096. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7097. \path[->,bend left=15] (F1-1) edge [below] node
  7098. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7099. \path[->,bend right=15] (F1-2) edge [above] node
  7100. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7101. \path[->,bend right=15] (F1-3) edge [above] node
  7102. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7103. \path[->,bend left=15] (F1-4) edge [right] node
  7104. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7105. \path[->,bend left=15] (C3-1) edge [below] node
  7106. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7107. \path[->,bend right=15] (C3-2) edge [left] node
  7108. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7109. \path[->,bend left=15] (x86-2) edge [left] node
  7110. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7111. \path[->,bend right=15] (x86-2-1) edge [below] node
  7112. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7113. \path[->,bend right=15] (x86-2-2) edge [left] node
  7114. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7115. \path[->,bend left=15] (x86-3) edge [above] node
  7116. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7117. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7118. \end{tikzpicture}
  7119. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7120. \label{fig:R4-passes}
  7121. \end{figure}
  7122. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  7123. the compilation of $R_4$.
  7124. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7125. \chapter{Lexically Scoped Functions}
  7126. \label{ch:lambdas}
  7127. \index{lambda}
  7128. \index{lexical scoping}
  7129. This chapter studies lexically scoped functions as they appear in
  7130. functional languages such as Racket. By lexical scoping we mean that a
  7131. function's body may refer to variables whose binding site is outside
  7132. of the function, in an enclosing scope.
  7133. %
  7134. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7135. $R_5$, which extends $R_4$ with anonymous functions using the
  7136. \key{lambda} form. The body of the \key{lambda}, refers to three
  7137. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7138. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7139. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7140. parameter of function \code{f}. The \key{lambda} is returned from the
  7141. function \code{f}. The main expression of the program includes two
  7142. calls to \code{f} with different arguments for \code{x}, first
  7143. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7144. to variables \code{g} and \code{h}. Even though these two functions
  7145. were created by the same \code{lambda}, they are really different
  7146. functions because they use different values for \code{x}. Applying
  7147. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7148. \code{15} produces \code{22}. The result of this program is \code{42}.
  7149. \begin{figure}[btp]
  7150. % s4_6.rkt
  7151. \begin{lstlisting}
  7152. (define (f [x : Integer]) : (Integer -> Integer)
  7153. (let ([y 4])
  7154. (lambda: ([z : Integer]) : Integer
  7155. (+ x (+ y z)))))
  7156. (let ([g (f 5)])
  7157. (let ([h (f 3)])
  7158. (+ (g 11) (h 15))))
  7159. \end{lstlisting}
  7160. \caption{Example of a lexically scoped function.}
  7161. \label{fig:lexical-scoping}
  7162. \end{figure}
  7163. The approach that we shall take for implementing lexically scoped
  7164. functions is to compile them into top-level function definitions,
  7165. translating from $R_5$ into $R_4$. However, the compiler will need to
  7166. provide special treatment for variable occurrences such as \code{x}
  7167. and \code{y} in the body of the \code{lambda} of
  7168. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7169. refer to variables defined outside of it. To identify such variable
  7170. occurrences, we review the standard notion of free variable.
  7171. \begin{definition}
  7172. A variable is \emph{free in expression} $e$ if the variable occurs
  7173. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7174. variable}
  7175. \end{definition}
  7176. For example, in the expression \code{(+ x (+ y z))} the variables
  7177. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7178. only \code{x} and \code{y} are free in the following expression
  7179. because \code{z} is bound by the \code{lambda}.
  7180. \begin{lstlisting}
  7181. (lambda: ([z : Integer]) : Integer
  7182. (+ x (+ y z)))
  7183. \end{lstlisting}
  7184. So the free variables of a \code{lambda} are the ones that will need
  7185. special treatment. We need to arrange for some way to transport, at
  7186. runtime, the values of those variables from the point where the
  7187. \code{lambda} was created to the point where the \code{lambda} is
  7188. applied. An efficient solution to the problem, due to
  7189. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7190. free variables together with the function pointer for the lambda's
  7191. code, an arrangement called a \emph{flat closure} (which we shorten to
  7192. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7193. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7194. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7195. pointers. The function pointer shall reside at index $0$ and the
  7196. values for the free variables will fill in the rest of the vector.
  7197. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7198. how closures work. It's a three-step dance. The program first calls
  7199. function \code{f}, which creates a closure for the \code{lambda}. The
  7200. closure is a vector whose first element is a pointer to the top-level
  7201. function that we will generate for the \code{lambda}, the second
  7202. element is the value of \code{x}, which is \code{5}, and the third
  7203. element is \code{4}, the value of \code{y}. The closure does not
  7204. contain an element for \code{z} because \code{z} is not a free
  7205. variable of the \code{lambda}. Creating the closure is step 1 of the
  7206. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7207. shown in Figure~\ref{fig:closures}.
  7208. %
  7209. The second call to \code{f} creates another closure, this time with
  7210. \code{3} in the second slot (for \code{x}). This closure is also
  7211. returned from \code{f} but bound to \code{h}, which is also shown in
  7212. Figure~\ref{fig:closures}.
  7213. \begin{figure}[tbp]
  7214. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7215. \caption{Example closure representation for the \key{lambda}'s
  7216. in Figure~\ref{fig:lexical-scoping}.}
  7217. \label{fig:closures}
  7218. \end{figure}
  7219. Continuing with the example, consider the application of \code{g} to
  7220. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7221. obtain the function pointer in the first element of the closure and
  7222. call it, passing in the closure itself and then the regular arguments,
  7223. in this case \code{11}. This technique for applying a closure is step
  7224. 2 of the dance.
  7225. %
  7226. But doesn't this \code{lambda} only take 1 argument, for parameter
  7227. \code{z}? The third and final step of the dance is generating a
  7228. top-level function for a \code{lambda}. We add an additional
  7229. parameter for the closure and we insert a \code{let} at the beginning
  7230. of the function for each free variable, to bind those variables to the
  7231. appropriate elements from the closure parameter.
  7232. %
  7233. This three-step dance is known as \emph{closure conversion}. We
  7234. discuss the details of closure conversion in
  7235. Section~\ref{sec:closure-conversion} and the code generated from the
  7236. example in Section~\ref{sec:example-lambda}. But first we define the
  7237. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7238. \section{The $R_5$ Language}
  7239. \label{sec:r5}
  7240. The concrete and abstract syntax for $R_5$, a language with anonymous
  7241. functions and lexical scoping, is defined in
  7242. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7243. the \key{lambda} form to the grammar for $R_4$, which already has
  7244. syntax for function application.
  7245. \begin{figure}[tp]
  7246. \centering
  7247. \fbox{
  7248. \begin{minipage}{0.96\textwidth}
  7249. \small
  7250. \[
  7251. \begin{array}{lcl}
  7252. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7253. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7254. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7255. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7256. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7257. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  7258. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7259. \mid (\key{and}\;\Exp\;\Exp)
  7260. \mid (\key{or}\;\Exp\;\Exp)
  7261. \mid (\key{not}\;\Exp) } \\
  7262. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7263. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7264. (\key{vector-ref}\;\Exp\;\Int)} \\
  7265. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7266. \mid (\Exp \; \Exp\ldots) } \\
  7267. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  7268. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7269. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7270. \end{array}
  7271. \]
  7272. \end{minipage}
  7273. }
  7274. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7275. with \key{lambda}.}
  7276. \label{fig:r5-concrete-syntax}
  7277. \end{figure}
  7278. \begin{figure}[tp]
  7279. \centering
  7280. \fbox{
  7281. \begin{minipage}{0.96\textwidth}
  7282. \small
  7283. \[
  7284. \begin{array}{lcl}
  7285. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  7286. &\mid& \gray{ \ADD{\Exp}{\Exp}
  7287. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  7288. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7289. &\mid& \gray{ \BOOL{\itm{bool}}
  7290. \mid \AND{\Exp}{\Exp} }\\
  7291. &\mid& \gray{ \OR{\Exp}{\Exp}
  7292. \mid \NOT{\Exp} } \\
  7293. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  7294. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7295. &\mid& \gray{ \VECTOR{\Exp} } \\
  7296. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  7297. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  7298. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7299. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7300. &\mid& \LAMBDA{[\Var\code{:}\Type]\ldots}{\Type}{\Exp}\\
  7301. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7302. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp} }
  7303. \end{array}
  7304. \]
  7305. \end{minipage}
  7306. }
  7307. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7308. \label{fig:r5-syntax}
  7309. \end{figure}
  7310. \index{interpreter}
  7311. \label{sec:interp-R5}
  7312. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7313. $R_5$. The clause for \key{lambda} saves the current environment
  7314. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7315. the environment from the \key{lambda}, the \code{lam-env}, when
  7316. interpreting the body of the \key{lambda}. The \code{lam-env}
  7317. environment is extended with the mapping of parameters to argument
  7318. values.
  7319. \begin{figure}[tbp]
  7320. \begin{lstlisting}
  7321. (define (interp-exp env)
  7322. (lambda (e)
  7323. (define recur (interp-exp env))
  7324. (match e
  7325. ...
  7326. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7327. `(lambda ,xs ,body ,env)]
  7328. [(Apply fun args)
  7329. (define fun-val ((interp-exp env) fun))
  7330. (define arg-vals (map (interp-exp env) args))
  7331. (match fun-val
  7332. [`(lambda ,xs ,body ,lam-env)
  7333. (define new-env (append (map cons xs arg-vals) lam-env))
  7334. ((interp-exp new-env) body)]
  7335. [else (error "interp-exp, expected function, not" fun-val)])]
  7336. [else (error 'interp-exp "unrecognized expression")]
  7337. )))
  7338. \end{lstlisting}
  7339. \caption{Interpreter for $R_5$.}
  7340. \label{fig:interp-R5}
  7341. \end{figure}
  7342. \label{sec:type-check-r5}
  7343. \index{type checking}
  7344. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  7345. \key{lambda} form. The body of the \key{lambda} is checked in an
  7346. environment that includes the current environment (because it is
  7347. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7348. require the body's type to match the declared return type.
  7349. \begin{figure}[tbp]
  7350. \begin{lstlisting}
  7351. (define (typecheck-R5 env)
  7352. (lambda (e)
  7353. (match e
  7354. [(Lambda (and bnd `([,xs : ,Ts] ...)) rT body)
  7355. (define-values (new-body bodyT)
  7356. ((type-check-exp (append (map cons xs Ts) env)) body))
  7357. (define ty `(,@Ts -> ,rT))
  7358. (cond
  7359. [(equal? rT bodyT)
  7360. (values (HasType (Lambda bnd rT new-body) ty) ty)]
  7361. [else
  7362. (error "mismatch in return type" bodyT rT)])]
  7363. ...
  7364. )))
  7365. \end{lstlisting}
  7366. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7367. \label{fig:typecheck-R5}
  7368. \end{figure}
  7369. \section{Closure Conversion}
  7370. \label{sec:closure-conversion}
  7371. \index{closure conversion}
  7372. The compiling of lexically-scoped functions into top-level function
  7373. definitions is accomplished in the pass \code{convert-to-closures}
  7374. that comes after \code{reveal-functions} and before
  7375. \code{limit-functions}.
  7376. As usual, we shall implement the pass as a recursive function over the
  7377. AST. All of the action is in the clauses for \key{lambda} and
  7378. \key{Apply}. We transform a \key{lambda} expression into an expression
  7379. that creates a closure, that is, creates a vector whose first element
  7380. is a function pointer and the rest of the elements are the free
  7381. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7382. generated to identify the function.
  7383. \begin{tabular}{lll}
  7384. \begin{minipage}{0.4\textwidth}
  7385. \begin{lstlisting}
  7386. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7387. \end{lstlisting}
  7388. \end{minipage}
  7389. &
  7390. $\Rightarrow$
  7391. &
  7392. \begin{minipage}{0.4\textwidth}
  7393. \begin{lstlisting}
  7394. (vector |\itm{name}| |\itm{fvs}| ...)
  7395. \end{lstlisting}
  7396. \end{minipage}
  7397. \end{tabular} \\
  7398. %
  7399. In addition to transforming each \key{lambda} into a \key{vector}, we
  7400. must create a top-level function definition for each \key{lambda}, as
  7401. shown below.\\
  7402. \begin{minipage}{0.8\textwidth}
  7403. \begin{lstlisting}
  7404. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7405. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7406. ...
  7407. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7408. |\itm{body'}|)...))
  7409. \end{lstlisting}
  7410. \end{minipage}\\
  7411. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7412. parameters are the normal parameters of the \key{lambda}. The types
  7413. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7414. underscore is a dummy type because it is rather difficult to give a
  7415. type to the function in the closure's type, and it does not matter.
  7416. The sequence of \key{let} forms bind the free variables to their
  7417. values obtained from the closure.
  7418. We transform function application into code that retrieves the
  7419. function pointer from the closure and then calls the function, passing
  7420. in the closure as the first argument. We bind $e'$ to a temporary
  7421. variable to avoid code duplication.
  7422. \begin{tabular}{lll}
  7423. \begin{minipage}{0.3\textwidth}
  7424. \begin{lstlisting}
  7425. (app |$e$| |\itm{es}| ...)
  7426. \end{lstlisting}
  7427. \end{minipage}
  7428. &
  7429. $\Rightarrow$
  7430. &
  7431. \begin{minipage}{0.5\textwidth}
  7432. \begin{lstlisting}
  7433. (let ([|\itm{tmp}| |$e'$|])
  7434. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7435. \end{lstlisting}
  7436. \end{minipage}
  7437. \end{tabular} \\
  7438. There is also the question of what to do with top-level function
  7439. definitions. To maintain a uniform translation of function
  7440. application, we turn function references into closures.
  7441. \begin{tabular}{lll}
  7442. \begin{minipage}{0.3\textwidth}
  7443. \begin{lstlisting}
  7444. (fun-ref |$f$|)
  7445. \end{lstlisting}
  7446. \end{minipage}
  7447. &
  7448. $\Rightarrow$
  7449. &
  7450. \begin{minipage}{0.5\textwidth}
  7451. \begin{lstlisting}
  7452. (vector (fun-ref |$f$|))
  7453. \end{lstlisting}
  7454. \end{minipage}
  7455. \end{tabular} \\
  7456. %
  7457. The top-level function definitions need to be updated as well to take
  7458. an extra closure parameter.
  7459. \section{An Example Translation}
  7460. \label{sec:example-lambda}
  7461. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  7462. conversion for the example program demonstrating lexical scoping that
  7463. we discussed at the beginning of this chapter.
  7464. \begin{figure}[h]
  7465. \begin{minipage}{0.8\textwidth}
  7466. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7467. (program
  7468. (define (f [x : Integer]) : (Integer -> Integer)
  7469. (let ([y 4])
  7470. (lambda: ([z : Integer]) : Integer
  7471. (+ x (+ y z)))))
  7472. (let ([g (f 5)])
  7473. (let ([h (f 3)])
  7474. (+ (g 11) (h 15)))))
  7475. \end{lstlisting}
  7476. $\Downarrow$
  7477. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7478. (program (type Integer)
  7479. (define (f (x : Integer)) : (Integer -> Integer)
  7480. (let ((y 4))
  7481. (lambda: ((z : Integer)) : Integer
  7482. (+ x (+ y z)))))
  7483. (let ((g (app (fun-ref f) 5)))
  7484. (let ((h (app (fun-ref f) 3)))
  7485. (+ (app g 11) (app h 15)))))
  7486. \end{lstlisting}
  7487. $\Downarrow$
  7488. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7489. (program (type Integer)
  7490. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7491. (let ((y 4))
  7492. (vector (fun-ref lam.1) x y)))
  7493. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7494. (let ((x (vector-ref clos.2 1)))
  7495. (let ((y (vector-ref clos.2 2)))
  7496. (+ x (+ y z)))))
  7497. (let ((g (let ((t.1 (vector (fun-ref f))))
  7498. (app (vector-ref t.1 0) t.1 5))))
  7499. (let ((h (let ((t.2 (vector (fun-ref f))))
  7500. (app (vector-ref t.2 0) t.2 3))))
  7501. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7502. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7503. \end{lstlisting}
  7504. \end{minipage}
  7505. \caption{Example of closure conversion.}
  7506. \label{fig:lexical-functions-example}
  7507. \end{figure}
  7508. \begin{figure}[p]
  7509. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7510. \node (R4) at (0,2) {\large $R_4$};
  7511. \node (R4-2) at (3,2) {\large $R_4$};
  7512. \node (R4-3) at (6,2) {\large $R_4$};
  7513. \node (F1-1) at (12,0) {\large $F_1$};
  7514. \node (F1-2) at (9,0) {\large $F_1$};
  7515. \node (F1-3) at (6,0) {\large $F_1$};
  7516. \node (F1-4) at (3,0) {\large $F_1$};
  7517. \node (F1-5) at (0,0) {\large $F_1$};
  7518. \node (C3-1) at (6,-2) {\large $C_3$};
  7519. \node (C3-2) at (3,-2) {\large $C_3$};
  7520. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7521. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7522. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7523. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7524. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7525. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7526. \path[->,bend left=15] (R4) edge [above] node
  7527. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7528. \path[->,bend left=15] (R4-2) edge [above] node
  7529. {\ttfamily\footnotesize uniquify} (R4-3);
  7530. \path[->] (R4-3) edge [right] node
  7531. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7532. \path[->,bend left=15] (F1-1) edge [below] node
  7533. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7534. \path[->,bend right=15] (F1-2) edge [above] node
  7535. {\ttfamily\footnotesize limit-functions} (F1-3);
  7536. \path[->,bend right=15] (F1-3) edge [above] node
  7537. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7538. \path[->,bend right=15] (F1-4) edge [above] node
  7539. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7540. \path[->] (F1-5) edge [left] node
  7541. {\ttfamily\footnotesize explicate-control} (C3-1);
  7542. \path[->,bend left=15] (C3-1) edge [below] node
  7543. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7544. \path[->,bend right=15] (C3-2) edge [left] node
  7545. {\ttfamily\footnotesize select-instr.} (x86-2);
  7546. \path[->,bend left=15] (x86-2) edge [left] node
  7547. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7548. \path[->,bend right=15] (x86-2-1) edge [below] node
  7549. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7550. \path[->,bend right=15] (x86-2-2) edge [left] node
  7551. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7552. \path[->,bend left=15] (x86-3) edge [above] node
  7553. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7554. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7555. \end{tikzpicture}
  7556. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7557. functions.}
  7558. \label{fig:R5-passes}
  7559. \end{figure}
  7560. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7561. for the compilation of $R_5$.
  7562. \begin{exercise}\normalfont
  7563. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7564. Create 5 new programs that use \key{lambda} functions and make use of
  7565. lexical scoping. Test your compiler on these new programs and all of
  7566. your previously created test programs.
  7567. \end{exercise}
  7568. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7569. \chapter{Dynamic Typing}
  7570. \label{ch:type-dynamic}
  7571. \index{dynamic typing}
  7572. In this chapter we discuss the compilation of a dynamically typed
  7573. language, named $R_7$, that is a subset of the Racket
  7574. language. (Recall that in the previous chapters we have studied
  7575. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7576. languages, an expression may produce values of differing
  7577. type. Consider the following example with a conditional expression
  7578. that may return a Boolean or an integer depending on the input to the
  7579. program.
  7580. \begin{lstlisting}
  7581. (not (if (eq? (read) 1) #f 0))
  7582. \end{lstlisting}
  7583. Languages that allow expressions to produce different kinds of values
  7584. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7585. such as subtype polymorphism and parametric
  7586. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we are
  7587. talking about here does not have a special name, but it is the usual
  7588. kind that arises in dynamically typed languages.
  7589. Another characteristic of dynamically typed languages is that
  7590. primitive operations, such as \code{not}, are often defined to operate
  7591. on many different types of values. In fact, in Racket, the \code{not}
  7592. operator produces a result for any kind of value: given \code{\#f} it
  7593. returns \code{\#t} and given anything else it returns \code{\#f}.
  7594. Furthermore, even when primitive operations restrict their inputs to
  7595. values of a certain type, this restriction is enforced at runtime
  7596. instead of during compilation. For example, the following vector
  7597. reference results in a run-time contract violation.
  7598. \begin{lstlisting}
  7599. (vector-ref (vector 42) #t)
  7600. \end{lstlisting}
  7601. \begin{figure}[tp]
  7602. \centering
  7603. \fbox{
  7604. \begin{minipage}{0.97\textwidth}
  7605. \[
  7606. \begin{array}{rcl}
  7607. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7608. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7609. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7610. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7611. &\mid& \key{\#t} \mid \key{\#f}
  7612. \mid (\key{and}\;\Exp\;\Exp)
  7613. \mid (\key{or}\;\Exp\;\Exp)
  7614. \mid (\key{not}\;\Exp) \\
  7615. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7616. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7617. (\key{vector-ref}\;\Exp\;\Exp) \\
  7618. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7619. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7620. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7621. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7622. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7623. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7624. \end{array}
  7625. \]
  7626. \end{minipage}
  7627. }
  7628. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7629. \label{fig:r7-syntax}
  7630. \end{figure}
  7631. The syntax of $R_7$, our subset of Racket, is defined in
  7632. Figure~\ref{fig:r7-syntax}.
  7633. %
  7634. The definitional interpreter for $R_7$ is given in
  7635. Figure~\ref{fig:interp-R7}.
  7636. \begin{figure}[tbp]
  7637. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7638. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7639. (define (valid-op? op) (member op '(+ - and or not)))
  7640. (define (interp-r7 env)
  7641. (lambda (ast)
  7642. (define recur (interp-r7 env))
  7643. (match ast
  7644. [(? symbol?) (lookup ast env)]
  7645. [(? integer?) `(inject ,ast Integer)]
  7646. [#t `(inject #t Boolean)]
  7647. [#f `(inject #f Boolean)]
  7648. [`(read) `(inject ,(read-fixnum) Integer)]
  7649. [`(lambda (,xs ...) ,body)
  7650. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7651. [`(define (,f ,xs ...) ,body)
  7652. (mcons f `(lambda ,xs ,body))]
  7653. [`(program ,ds ... ,body)
  7654. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7655. (for/list ([b top-level])
  7656. (set-mcdr! b (match (mcdr b)
  7657. [`(lambda ,xs ,body)
  7658. `(inject (lambda ,xs ,body ,top-level)
  7659. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7660. ((interp-r7 top-level) body))]
  7661. [`(vector ,(app recur elts) ...)
  7662. (define tys (map get-tagged-type elts))
  7663. `(inject ,(apply vector elts) (Vector ,@tys))]
  7664. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7665. (match v1
  7666. [`(inject ,vec ,ty)
  7667. (vector-set! vec n v2)
  7668. `(inject (void) Void)])]
  7669. [`(vector-ref ,(app recur v) ,n)
  7670. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7671. [`(let ([,x ,(app recur v)]) ,body)
  7672. ((interp-r7 (cons (cons x v) env)) body)]
  7673. [`(,op ,es ...) #:when (valid-op? op)
  7674. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7675. [`(eq? ,(app recur l) ,(app recur r))
  7676. `(inject ,(equal? l r) Boolean)]
  7677. [`(if ,(app recur q) ,t ,f)
  7678. (match q
  7679. [`(inject #f Boolean) (recur f)]
  7680. [else (recur t)])]
  7681. [`(,(app recur f-val) ,(app recur vs) ...)
  7682. (match f-val
  7683. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7684. (define new-env (append (map cons xs vs) lam-env))
  7685. ((interp-r7 new-env) body)]
  7686. [else (error "interp-r7, expected function, not" f-val)])])))
  7687. \end{lstlisting}
  7688. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7689. \label{fig:interp-R7}
  7690. \end{figure}
  7691. Let us consider how we might compile $R_7$ to x86, thinking about the
  7692. first example above. Our bit-level representation of the Boolean
  7693. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7694. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7695. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7696. general, cannot be determined at compile time, but depends on the
  7697. runtime type of its input, as in the example above that depends on the
  7698. result of \code{(read)}.
  7699. The way around this problem is to include information about a value's
  7700. runtime type in the value itself, so that this information can be
  7701. inspected by operators such as \code{not}. In particular, we shall
  7702. steal the 3 right-most bits from our 64-bit values to encode the
  7703. runtime type. We shall use $001$ to identify integers, $100$ for
  7704. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7705. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7706. define the following auxiliary function.
  7707. \begin{align*}
  7708. \itm{tagof}(\key{Integer}) &= 001 \\
  7709. \itm{tagof}(\key{Boolean}) &= 100 \\
  7710. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7711. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7712. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7713. \itm{tagof}(\key{Void}) &= 101
  7714. \end{align*}
  7715. (We shall say more about the new \key{Vectorof} type shortly.)
  7716. This stealing of 3 bits comes at some
  7717. price: our integers are reduced to ranging from $-2^{60}$ to
  7718. $2^{60}$. The stealing does not adversely affect vectors and
  7719. procedures because those values are addresses, and our addresses are
  7720. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7721. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7722. bits with the tag and we can simply zero-out the tag to recover the
  7723. original address.
  7724. In some sense, these tagged values are a new kind of value. Indeed,
  7725. we can extend our \emph{typed} language with tagged values by adding a
  7726. new type to classify them, called \key{Any}, and with operations for
  7727. creating and using tagged values, yielding the $R_6$ language that we
  7728. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7729. fundamental support for polymorphism and runtime types that we need to
  7730. support dynamic typing.
  7731. There is an interesting interaction between tagged values and garbage
  7732. collection. A variable of type \code{Any} might refer to a vector and
  7733. therefore it might be a root that needs to be inspected and copied
  7734. during garbage collection. Thus, we need to treat variables of type
  7735. \code{Any} in a similar way to variables of type \code{Vector} for
  7736. purposes of register allocation, which we discuss in
  7737. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7738. variable of type \code{Any} is spilled, it must be spilled to the root
  7739. stack. But this means that the garbage collector needs to be able to
  7740. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7741. value that points to a tuple, and (3) a tagged value that is not a
  7742. tuple. We enable this differentiation by choosing not to use the tag
  7743. $000$. Instead, that bit pattern is reserved for identifying plain old
  7744. pointers to tuples. On the other hand, if one of the first three bits
  7745. is set, then we have a tagged value, and inspecting the tag can
  7746. differentiation between vectors ($010$) and the other kinds of values.
  7747. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7748. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7749. extend our compiler to handle the new features of $R_6$
  7750. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7751. \ref{sec:register-allocation-r6}).
  7752. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7753. \label{sec:r6-lang}
  7754. \begin{figure}[tp]
  7755. \centering
  7756. \fbox{
  7757. \begin{minipage}{0.97\textwidth}
  7758. \[
  7759. \begin{array}{lcl}
  7760. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7761. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7762. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7763. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7764. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7765. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7766. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7767. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7768. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7769. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7770. \mid (\key{and}\;\Exp\;\Exp)
  7771. \mid (\key{or}\;\Exp\;\Exp)
  7772. \mid (\key{not}\;\Exp)} \\
  7773. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7774. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7775. (\key{vector-ref}\;\Exp\;\Int)} \\
  7776. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7777. &\mid& \gray{(\Exp \; \Exp\ldots)
  7778. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7779. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7780. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7781. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7782. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7783. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7784. \end{array}
  7785. \]
  7786. \end{minipage}
  7787. }
  7788. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7789. with \key{Any}.}
  7790. \label{fig:r6-syntax}
  7791. \end{figure}
  7792. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7793. $(\key{inject}\; e\; T)$ form converts the value produced by
  7794. expression $e$ of type $T$ into a tagged value. The
  7795. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7796. expression $e$ into a value of type $T$ or else halts the program if
  7797. the type tag is equivalent to $T$. We treat
  7798. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7799. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7800. Note that in both \key{inject} and
  7801. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7802. which simplifies the implementation and corresponds with what is
  7803. needed for compiling untyped Racket. The type predicates,
  7804. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7805. if the tag corresponds to the predicate, and return \key{\#t}
  7806. otherwise.
  7807. %
  7808. Selections from the type checker for $R_6$ are shown in
  7809. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7810. Figure~\ref{fig:interp-R6}.
  7811. \begin{figure}[btp]
  7812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7813. (define (flat-ty? ty) ...)
  7814. (define (typecheck-R6 env)
  7815. (lambda (e)
  7816. (define recur (typecheck-R6 env))
  7817. (match e
  7818. [`(inject ,e ,ty)
  7819. (unless (flat-ty? ty)
  7820. (error "may only inject a value of flat type, not ~a" ty))
  7821. (define-values (new-e e-ty) (recur e))
  7822. (cond
  7823. [(equal? e-ty ty)
  7824. (values `(inject ,new-e ,ty) 'Any)]
  7825. [else
  7826. (error "inject expected ~a to have type ~a" e ty)])]
  7827. [`(project ,e ,ty)
  7828. (unless (flat-ty? ty)
  7829. (error "may only project to a flat type, not ~a" ty))
  7830. (define-values (new-e e-ty) (recur e))
  7831. (cond
  7832. [(equal? e-ty 'Any)
  7833. (values `(project ,new-e ,ty) ty)]
  7834. [else
  7835. (error "project expected ~a to have type Any" e)])]
  7836. [`(vector-ref ,e ,i)
  7837. (define-values (new-e e-ty) (recur e))
  7838. (match e-ty
  7839. [`(Vector ,ts ...) ...]
  7840. [`(Vectorof ,ty)
  7841. (unless (exact-nonnegative-integer? i)
  7842. (error 'type-check "invalid index ~a" i))
  7843. (values `(vector-ref ,new-e ,i) ty)]
  7844. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7845. ...
  7846. )))
  7847. \end{lstlisting}
  7848. \caption{Type checker for parts of the $R_6$ language.}
  7849. \label{fig:typecheck-R6}
  7850. \end{figure}
  7851. % to do: add rules for vector-ref, etc. for Vectorof
  7852. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7853. \begin{figure}[btp]
  7854. \begin{lstlisting}
  7855. (define primitives (set 'boolean? ...))
  7856. (define (interp-op op)
  7857. (match op
  7858. ['boolean? (lambda (v)
  7859. (match v
  7860. [`(tagged ,v1 Boolean) #t]
  7861. [else #f]))]
  7862. ...))
  7863. ;; Equivalence of flat types
  7864. (define (tyeq? t1 t2)
  7865. (match `(,t1 ,t2)
  7866. [`((Vectorof Any) (Vector ,t2s ...))
  7867. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7868. [`((Vector ,t1s ...) (Vectorof Any))
  7869. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7870. [else (equal? t1 t2)]))
  7871. (define (interp-R6 env)
  7872. (lambda (ast)
  7873. (match ast
  7874. [`(inject ,e ,t)
  7875. `(tagged ,((interp-R6 env) e) ,t)]
  7876. [`(project ,e ,t2)
  7877. (define v ((interp-R6 env) e))
  7878. (match v
  7879. [`(tagged ,v1 ,t1)
  7880. (cond [(tyeq? t1 t2)
  7881. v1]
  7882. [else
  7883. (error "in project, type mismatch" t1 t2)])]
  7884. [else
  7885. (error "in project, expected tagged value" v)])]
  7886. ...)))
  7887. \end{lstlisting}
  7888. \caption{Interpreter for $R_6$.}
  7889. \label{fig:interp-R6}
  7890. \end{figure}
  7891. %\clearpage
  7892. \section{Shrinking $R_6$}
  7893. \label{sec:shrink-r6}
  7894. In the \code{shrink} pass we recommend compiling \code{project} into
  7895. an explicit \code{if} expression that uses three new operations:
  7896. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7897. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7898. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7899. value from a tagged value. Finally, the \code{exit} operation ends the
  7900. execution of the program by invoking the operating system's
  7901. \code{exit} function. So the translation for \code{project} is as
  7902. follows. (We have omitted the \code{has-type} AST nodes to make this
  7903. output more readable.)
  7904. \begin{tabular}{lll}
  7905. \begin{minipage}{0.3\textwidth}
  7906. \begin{lstlisting}
  7907. (project |$e$| |$\Type$|)
  7908. \end{lstlisting}
  7909. \end{minipage}
  7910. &
  7911. $\Rightarrow$
  7912. &
  7913. \begin{minipage}{0.5\textwidth}
  7914. \begin{lstlisting}
  7915. (let ([|$\itm{tmp}$| |$e'$|])
  7916. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7917. (value-of-any |$\itm{tmp}$|)
  7918. (exit)))
  7919. \end{lstlisting}
  7920. \end{minipage}
  7921. \end{tabular} \\
  7922. Similarly, we recommend translating the type predicates
  7923. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7924. \section{Instruction Selection for $R_6$}
  7925. \label{sec:select-r6}
  7926. \paragraph{Inject}
  7927. We recommend compiling an \key{inject} as follows if the type is
  7928. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7929. destination to the left by the number of bits specified its source
  7930. argument (in this case $3$, the length of the tag) and it preserves
  7931. the sign of the integer. We use the \key{orq} instruction to combine
  7932. the tag and the value to form the tagged value. \\
  7933. \begin{tabular}{lll}
  7934. \begin{minipage}{0.4\textwidth}
  7935. \begin{lstlisting}
  7936. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7937. \end{lstlisting}
  7938. \end{minipage}
  7939. &
  7940. $\Rightarrow$
  7941. &
  7942. \begin{minipage}{0.5\textwidth}
  7943. \begin{lstlisting}
  7944. (movq |$e'$| |\itm{lhs}'|)
  7945. (salq (int 3) |\itm{lhs}'|)
  7946. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7947. \end{lstlisting}
  7948. \end{minipage}
  7949. \end{tabular} \\
  7950. The instruction selection for vectors and procedures is different
  7951. because their is no need to shift them to the left. The rightmost 3
  7952. bits are already zeros as described above. So we just combine the
  7953. value and the tag using \key{orq}. \\
  7954. \begin{tabular}{lll}
  7955. \begin{minipage}{0.4\textwidth}
  7956. \begin{lstlisting}
  7957. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7958. \end{lstlisting}
  7959. \end{minipage}
  7960. &
  7961. $\Rightarrow$
  7962. &
  7963. \begin{minipage}{0.5\textwidth}
  7964. \begin{lstlisting}
  7965. (movq |$e'$| |\itm{lhs}'|)
  7966. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7967. \end{lstlisting}
  7968. \end{minipage}
  7969. \end{tabular}
  7970. \paragraph{Tag of Any}
  7971. Recall that the \code{tag-of-any} operation extracts the type tag from
  7972. a value of type \code{Any}. The type tag is the bottom three bits, so
  7973. we obtain the tag by taking the bitwise-and of the value with $111$
  7974. ($7$ in decimal).
  7975. \begin{tabular}{lll}
  7976. \begin{minipage}{0.4\textwidth}
  7977. \begin{lstlisting}
  7978. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7979. \end{lstlisting}
  7980. \end{minipage}
  7981. &
  7982. $\Rightarrow$
  7983. &
  7984. \begin{minipage}{0.5\textwidth}
  7985. \begin{lstlisting}
  7986. (movq |$e'$| |\itm{lhs}'|)
  7987. (andq (int 7) |\itm{lhs}'|)
  7988. \end{lstlisting}
  7989. \end{minipage}
  7990. \end{tabular}
  7991. \paragraph{Value of Any}
  7992. Like \key{inject}, the instructions for \key{value-of-any} are
  7993. different depending on whether the type $T$ is a pointer (vector or
  7994. procedure) or not (Integer or Boolean). The following shows the
  7995. instruction selection for Integer and Boolean. We produce an untagged
  7996. value by shifting it to the right by 3 bits.
  7997. %
  7998. \\
  7999. \begin{tabular}{lll}
  8000. \begin{minipage}{0.4\textwidth}
  8001. \begin{lstlisting}
  8002. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8003. \end{lstlisting}
  8004. \end{minipage}
  8005. &
  8006. $\Rightarrow$
  8007. &
  8008. \begin{minipage}{0.5\textwidth}
  8009. \begin{lstlisting}
  8010. (movq |$e'$| |\itm{lhs}'|)
  8011. (sarq (int 3) |\itm{lhs}'|)
  8012. \end{lstlisting}
  8013. \end{minipage}
  8014. \end{tabular} \\
  8015. %
  8016. In the case for vectors and procedures, there is no need to
  8017. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8018. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8019. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8020. \code{movq} into the destination $\itm{lhs}$. We then generate
  8021. \code{andq} with the tagged value to get the desired result. \\
  8022. %
  8023. \begin{tabular}{lll}
  8024. \begin{minipage}{0.4\textwidth}
  8025. \begin{lstlisting}
  8026. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8027. \end{lstlisting}
  8028. \end{minipage}
  8029. &
  8030. $\Rightarrow$
  8031. &
  8032. \begin{minipage}{0.5\textwidth}
  8033. \begin{lstlisting}
  8034. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8035. (andq |$e'$| |\itm{lhs}'|)
  8036. \end{lstlisting}
  8037. \end{minipage}
  8038. \end{tabular}
  8039. %% \paragraph{Type Predicates} We leave it to the reader to
  8040. %% devise a sequence of instructions to implement the type predicates
  8041. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8042. \section{Register Allocation for $R_6$}
  8043. \label{sec:register-allocation-r6}
  8044. \index{register allocation}
  8045. As mentioned above, a variable of type \code{Any} might refer to a
  8046. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8047. of type \code{Any} in the same way that it treats variables of type
  8048. \code{Vector} for purposes of garbage collection. In particular,
  8049. \begin{itemize}
  8050. \item If a variable of type \code{Any} is live during a function call,
  8051. then it must be spilled. One way to accomplish this is to augment
  8052. the pass \code{build-interference} to mark all variables that are
  8053. live after a \code{callq} as interfering with all the registers.
  8054. \item If a variable of type \code{Any} is spilled, it must be spilled
  8055. to the root stack instead of the normal procedure call stack.
  8056. \end{itemize}
  8057. \begin{exercise}\normalfont
  8058. Expand your compiler to handle $R_6$ as discussed in the last few
  8059. sections. Create 5 new programs that use the \code{Any} type and the
  8060. new operations (\code{inject}, \code{project}, \code{boolean?},
  8061. etc.). Test your compiler on these new programs and all of your
  8062. previously created test programs.
  8063. \end{exercise}
  8064. \section{Compiling $R_7$ to $R_6$}
  8065. \label{sec:compile-r7}
  8066. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8067. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8068. given a subexpression $e$ of $R_7$, the pass will produce an
  8069. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8070. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8071. the Boolean \code{\#t}, which must be injected to produce an
  8072. expression of type \key{Any}.
  8073. %
  8074. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8075. addition, is representative of compilation for many operations: the
  8076. arguments have type \key{Any} and must be projected to \key{Integer}
  8077. before the addition can be performed.
  8078. The compilation of \key{lambda} (third row of
  8079. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8080. produce type annotations: we simply use \key{Any}.
  8081. %
  8082. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8083. has to account for some differences in behavior between $R_7$ and
  8084. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8085. kind of values can be used in various places. For example, the
  8086. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8087. the arguments need not be of the same type (but in that case, the
  8088. result will be \code{\#f}).
  8089. \begin{figure}[btp]
  8090. \centering
  8091. \begin{tabular}{|lll|} \hline
  8092. \begin{minipage}{0.25\textwidth}
  8093. \begin{lstlisting}
  8094. #t
  8095. \end{lstlisting}
  8096. \end{minipage}
  8097. &
  8098. $\Rightarrow$
  8099. &
  8100. \begin{minipage}{0.6\textwidth}
  8101. \begin{lstlisting}
  8102. (inject #t Boolean)
  8103. \end{lstlisting}
  8104. \end{minipage}
  8105. \\[2ex]\hline
  8106. \begin{minipage}{0.25\textwidth}
  8107. \begin{lstlisting}
  8108. (+ |$e_1$| |$e_2$|)
  8109. \end{lstlisting}
  8110. \end{minipage}
  8111. &
  8112. $\Rightarrow$
  8113. &
  8114. \begin{minipage}{0.6\textwidth}
  8115. \begin{lstlisting}
  8116. (inject
  8117. (+ (project |$e'_1$| Integer)
  8118. (project |$e'_2$| Integer))
  8119. Integer)
  8120. \end{lstlisting}
  8121. \end{minipage}
  8122. \\[2ex]\hline
  8123. \begin{minipage}{0.25\textwidth}
  8124. \begin{lstlisting}
  8125. (lambda (|$x_1 \ldots$|) |$e$|)
  8126. \end{lstlisting}
  8127. \end{minipage}
  8128. &
  8129. $\Rightarrow$
  8130. &
  8131. \begin{minipage}{0.6\textwidth}
  8132. \begin{lstlisting}
  8133. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8134. (Any|$\ldots$|Any -> Any))
  8135. \end{lstlisting}
  8136. \end{minipage}
  8137. \\[2ex]\hline
  8138. \begin{minipage}{0.25\textwidth}
  8139. \begin{lstlisting}
  8140. (app |$e_0$| |$e_1 \ldots e_n$|)
  8141. \end{lstlisting}
  8142. \end{minipage}
  8143. &
  8144. $\Rightarrow$
  8145. &
  8146. \begin{minipage}{0.6\textwidth}
  8147. \begin{lstlisting}
  8148. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8149. |$e'_1 \ldots e'_n$|)
  8150. \end{lstlisting}
  8151. \end{minipage}
  8152. \\[2ex]\hline
  8153. \begin{minipage}{0.25\textwidth}
  8154. \begin{lstlisting}
  8155. (vector-ref |$e_1$| |$e_2$|)
  8156. \end{lstlisting}
  8157. \end{minipage}
  8158. &
  8159. $\Rightarrow$
  8160. &
  8161. \begin{minipage}{0.6\textwidth}
  8162. \begin{lstlisting}
  8163. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8164. (let ([tmp2 (project |$e'_2$| Integer)])
  8165. (vector-ref tmp1 tmp2)))
  8166. \end{lstlisting}
  8167. \end{minipage}
  8168. \\[2ex]\hline
  8169. \begin{minipage}{0.25\textwidth}
  8170. \begin{lstlisting}
  8171. (if |$e_1$| |$e_2$| |$e_3$|)
  8172. \end{lstlisting}
  8173. \end{minipage}
  8174. &
  8175. $\Rightarrow$
  8176. &
  8177. \begin{minipage}{0.6\textwidth}
  8178. \begin{lstlisting}
  8179. (if (eq? |$e'_1$| (inject #f Boolean))
  8180. |$e'_3$|
  8181. |$e'_2$|)
  8182. \end{lstlisting}
  8183. \end{minipage}
  8184. \\[2ex]\hline
  8185. \begin{minipage}{0.25\textwidth}
  8186. \begin{lstlisting}
  8187. (eq? |$e_1$| |$e_2$|)
  8188. \end{lstlisting}
  8189. \end{minipage}
  8190. &
  8191. $\Rightarrow$
  8192. &
  8193. \begin{minipage}{0.6\textwidth}
  8194. \begin{lstlisting}
  8195. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8196. \end{lstlisting}
  8197. \end{minipage}
  8198. \\[2ex]\hline
  8199. \end{tabular}
  8200. \caption{Compiling $R_7$ to $R_6$.}
  8201. \label{fig:compile-r7-r6}
  8202. \end{figure}
  8203. \begin{exercise}\normalfont
  8204. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8205. Create tests for $R_7$ by adapting all of your previous test programs
  8206. by removing type annotations. Add 5 more tests programs that
  8207. specifically rely on the language being dynamically typed. That is,
  8208. they should not be legal programs in a statically typed language, but
  8209. nevertheless, they should be valid $R_7$ programs that run to
  8210. completion without error.
  8211. \end{exercise}
  8212. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8213. \chapter{Gradual Typing}
  8214. \label{ch:gradual-typing}
  8215. \index{gradual typing}
  8216. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8217. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8218. \chapter{Parametric Polymorphism}
  8219. \label{ch:parametric-polymorphism}
  8220. \index{parametric polymorphism}
  8221. \index{generics}
  8222. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8223. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8224. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8225. \chapter{High-level Optimization}
  8226. \label{ch:high-level-optimization}
  8227. This chapter will present a procedure inlining pass based on the
  8228. algorithm of \citet{Waddell:1997fk}.
  8229. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8230. \chapter{Appendix}
  8231. \section{Interpreters}
  8232. \label{appendix:interp}
  8233. \index{interpreter}
  8234. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8235. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8236. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8237. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8238. the rest of the intermediate languages, including pseudo-x86 and x86
  8239. are in the \key{interp.rkt} file.
  8240. \section{Utility Functions}
  8241. \label{appendix:utilities}
  8242. The utility functions described here are in the \key{utilities.rkt}
  8243. file.
  8244. \paragraph{\code{interp-tests}}
  8245. The \key{interp-tests} function runs the compiler passes and the
  8246. interpreters on each of the specified tests to check whether each pass
  8247. is correct. The \key{interp-tests} function has the following
  8248. parameters:
  8249. \begin{description}
  8250. \item[name (a string)] a name to identify the compiler,
  8251. \item[typechecker] a function of exactly one argument that either
  8252. raises an error using the \code{error} function when it encounters a
  8253. type error, or returns \code{\#f} when it encounters a type
  8254. error. If there is no type error, the type checker returns the
  8255. program.
  8256. \item[passes] a list with one entry per pass. An entry is a list with
  8257. three things: a string giving the name of the pass, the function
  8258. that implements the pass (a translator from AST to AST), and a
  8259. function that implements the interpreter (a function from AST to
  8260. result value) for the language of the output of the pass.
  8261. \item[source-interp] an interpreter for the source language. The
  8262. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8263. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8264. \item[tests] a list of test numbers that specifies which tests to
  8265. run. (see below)
  8266. \end{description}
  8267. %
  8268. The \key{interp-tests} function assumes that the subdirectory
  8269. \key{tests} has a collection of Racket programs whose names all start
  8270. with the family name, followed by an underscore and then the test
  8271. number, ending with the file extension \key{.rkt}. Also, for each test
  8272. program that calls \code{read} one or more times, there is a file with
  8273. the same name except that the file extension is \key{.in} that
  8274. provides the input for the Racket program. If the test program is
  8275. expected to fail type checking, then there should be an empty file of
  8276. the same name but with extension \key{.tyerr}.
  8277. \paragraph{\code{compiler-tests}}
  8278. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8279. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8280. machine code and checks that the output is $42$. The parameters to the
  8281. \code{compiler-tests} function are similar to those of the
  8282. \code{interp-tests} function, and consist of
  8283. \begin{itemize}
  8284. \item a compiler name (a string),
  8285. \item a type checker,
  8286. \item description of the passes,
  8287. \item name of a test-family, and
  8288. \item a list of test numbers.
  8289. \end{itemize}
  8290. \paragraph{\code{compile-file}}
  8291. takes a description of the compiler passes (see the comment for
  8292. \key{interp-tests}) and returns a function that, given a program file
  8293. name (a string ending in \key{.rkt}), applies all of the passes and
  8294. writes the output to a file whose name is the same as the program file
  8295. name but with \key{.rkt} replaced with \key{.s}.
  8296. \paragraph{\code{read-program}}
  8297. takes a file path and parses that file (it must be a Racket program)
  8298. into an abstract syntax tree.
  8299. \paragraph{\code{parse-program}}
  8300. takes an S-expression representation of an abstract syntax tree and converts it into
  8301. the struct-based representation.
  8302. \paragraph{\code{assert}}
  8303. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8304. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8305. \paragraph{\code{lookup}}
  8306. % remove discussion of lookup? -Jeremy
  8307. takes a key and an alist, and returns the first value that is
  8308. associated with the given key, if there is one. If not, an error is
  8309. triggered. The alist may contain both immutable pairs (built with
  8310. \key{cons}) and mutable pairs (built with \key{mcons}).
  8311. %The \key{map2} function ...
  8312. \section{x86 Instruction Set Quick-Reference}
  8313. \label{sec:x86-quick-reference}
  8314. \index{x86}
  8315. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8316. do. We write $A \to B$ to mean that the value of $A$ is written into
  8317. location $B$. Address offsets are given in bytes. The instruction
  8318. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8319. registers (such as \code{\%rax}), or memory references (such as
  8320. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8321. reference per instruction. Other operands must be immediates or
  8322. registers.
  8323. \begin{table}[tbp]
  8324. \centering
  8325. \begin{tabular}{l|l}
  8326. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8327. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8328. \texttt{negq} $A$ & $- A \to A$ \\
  8329. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8330. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8331. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8332. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8333. \texttt{retq} & Pops the return address and jumps to it \\
  8334. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8335. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8336. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8337. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8338. be an immediate) \\
  8339. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8340. matches the condition code of the instruction, otherwise go to the
  8341. next instructions. The condition codes are \key{e} for ``equal'',
  8342. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8343. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8344. \texttt{jl} $L$ & \\
  8345. \texttt{jle} $L$ & \\
  8346. \texttt{jg} $L$ & \\
  8347. \texttt{jge} $L$ & \\
  8348. \texttt{jmp} $L$ & Jump to label $L$ \\
  8349. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8350. \texttt{movzbq} $A$, $B$ &
  8351. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8352. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8353. and the extra bytes of $B$ are set to zero.} \\
  8354. & \\
  8355. & \\
  8356. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8357. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8358. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8359. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8360. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8361. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8362. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8363. description of the condition codes. $A$ must be a single byte register
  8364. (e.g., \texttt{al} or \texttt{cl}).} \\
  8365. \texttt{setl} $A$ & \\
  8366. \texttt{setle} $A$ & \\
  8367. \texttt{setg} $A$ & \\
  8368. \texttt{setge} $A$ &
  8369. \end{tabular}
  8370. \vspace{5pt}
  8371. \caption{Quick-reference for the x86 instructions used in this book.}
  8372. \label{tab:x86-instr}
  8373. \end{table}
  8374. \cleardoublepage
  8375. \addcontentsline{toc}{chapter}{Index}
  8376. \printindex
  8377. \cleardoublepage
  8378. \bibliographystyle{plainnat}
  8379. \bibliography{all}
  8380. \addcontentsline{toc}{chapter}{Bibliography}
  8381. \end{document}
  8382. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8383. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8384. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8385. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8386. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8387. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8388. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8389. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8390. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8391. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8392. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8393. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8394. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  8395. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8396. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8397. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8398. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8399. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8400. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8401. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8402. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8403. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8404. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8405. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8406. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8407. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8408. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8409. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8410. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8411. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8412. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8413. % LocalWords: struct symtab