book.tex 329 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751
  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. \definecolor{lightgray}{gray}{1}
  53. \newcommand{\black}[1]{{\color{black} #1}}
  54. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  55. \newcommand{\gray}[1]{{\color{gray} #1}}
  56. %% For pictures
  57. \usepackage{tikz}
  58. \usetikzlibrary{arrows.meta}
  59. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  60. % Computer Modern is already the default. -Jeremy
  61. %\renewcommand{\ttdefault}{cmtt}
  62. \definecolor{comment-red}{rgb}{0.8,0,0}
  63. \if{0}
  64. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  65. \newcommand{\margincomment}[1]{\marginpar{#1}}
  66. \else
  67. \newcommand{\rn}[1]{}
  68. \newcommand{\margincomment}[1]{}
  69. \fi
  70. \lstset{%
  71. language=Lisp,
  72. basicstyle=\ttfamily\small,
  73. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  74. deletekeywords={read},
  75. escapechar=|,
  76. columns=flexible,
  77. moredelim=[is][\color{red}]{~}{~}
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge An Incremental Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses about programming languages by Daniel Friedman in
  148. the 1970's and 1980's. Dan conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, Kent returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Kent continued development of Chez
  159. Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Dan's ideas was to split the compiler into many small ``passes'' so
  163. that the code for each pass would be easy to understood in isolation.
  164. (In contrast, most compilers of the time were organized into only a
  165. few monolithic passes for reasons of compile-time efficiency.) Kent,
  166. with later help from his students Dipanwita Sarkar and Andrew Keep,
  167. developed infrastructure to support this approach and evolved the
  168. course, first to use micro-sized passes and then into even smaller
  169. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  170. student in this compiler course in the early 2000's, as part of his
  171. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  172. the course immensely!
  173. During that time, another student named Abdulaziz Ghuloum observed
  174. that the front-to-back organization of the course made it difficult
  175. for students to understand the rationale for the compiler
  176. design. Abdulaziz proposed an incremental approach in which the
  177. students build the compiler in stages; they start by implementing a
  178. complete compiler for a very small subset of the input language and in
  179. each subsequent stage they add a language feature and add or modify
  180. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  181. the students see how the language features motivate aspects of the
  182. compiler design.
  183. After graduating from Indiana University in 2005, Jeremy went on to
  184. teach at the University of Colorado. He adapted the nano pass and
  185. incremental approaches to compiling a subset of the Python
  186. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  187. on the surface but there is a large overlap in the compiler techniques
  188. required for the two languages. Thus, Jeremy was able to teach much of
  189. the same content from the Indiana compiler course. He very much
  190. enjoyed teaching the course organized in this way, and even better,
  191. many of the students learned a lot and got excited about compilers.
  192. Jeremy returned to teach at Indiana University in 2013. In his
  193. absence the compiler course had switched from the front-to-back
  194. organization to a back-to-front organization. Seeing how well the
  195. incremental approach worked at Colorado, he started porting and
  196. adapting the structure of the Colorado course back into the land of
  197. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  198. the course is now about compiling a subset of Racket (and Typed
  199. Racket) to the x86 assembly language. The compiler is implemented in
  200. Racket 7.1~\citep{plt-tr}.
  201. This is the textbook for the incremental version of the compiler
  202. course at Indiana University (Spring 2016 - present) and it is the
  203. first open textbook for an Indiana compiler course. With this book we
  204. hope to make the Indiana compiler course available to people that have
  205. not had the chance to study in Bloomington in person. Many of the
  206. compiler design decisions in this book are drawn from the assignment
  207. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  208. are the most important topics from \cite{Dybvig:2010aa} but we have
  209. omitted topics that we think are less interesting conceptually and we
  210. have made simplifications to reduce complexity. In this way, this
  211. book leans more towards pedagogy than towards the efficiency of the
  212. generated code. Also, the book differs in places where we saw the
  213. opportunity to make the topics more fun, such as in relating register
  214. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  215. \section*{Prerequisites}
  216. The material in this book is challenging but rewarding. It is meant to
  217. prepare students for a lifelong career in programming languages.
  218. The book uses the Racket language both for the implementation of the
  219. compiler and for the language that is compiled, so a student should be
  220. proficient with Racket (or Scheme) prior to reading this book. There
  221. are many excellent resources for learning Scheme and
  222. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  223. is helpful but not necessary for the student to have prior exposure to
  224. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  225. obtain from a computer systems
  226. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  227. parts of x86-64 assembly language that are needed.
  228. %\section*{Structure of book}
  229. % You might want to add short description about each chapter in this book.
  230. %\section*{About the companion website}
  231. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  232. %\begin{itemize}
  233. % \item A link to (freely downlodable) latest version of this document.
  234. % \item Link to download LaTeX source for this document.
  235. % \item Miscellaneous material (e.g. suggested readings etc).
  236. %\end{itemize}
  237. \section*{Acknowledgments}
  238. Many people have contributed to the ideas, techniques, organization,
  239. and teaching of the materials in this book. We especially thank the
  240. following people.
  241. \begin{itemize}
  242. \item Bor-Yuh Evan Chang
  243. \item Kent Dybvig
  244. \item Daniel P. Friedman
  245. \item Ronald Garcia
  246. \item Abdulaziz Ghuloum
  247. \item Jay McCarthy
  248. \item Dipanwita Sarkar
  249. \item Andrew Keep
  250. \item Oscar Waddell
  251. \item Michael Wollowski
  252. \end{itemize}
  253. \mbox{}\\
  254. \noindent Jeremy G. Siek \\
  255. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  256. %\noindent Spring 2016
  257. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  258. \chapter{Preliminaries}
  259. \label{ch:trees-recur}
  260. In this chapter we review the basic tools that are needed to implement
  261. a compiler. Programs are typically input by a programmer as text,
  262. i.e., a sequence of characters. The program-as-text representation is
  263. called \emph{concrete syntax}. We use concrete syntax to concisely
  264. write down and talk about programs. Inside the compiler, we use
  265. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  266. that efficiently supports the operations that the compiler needs to
  267. perform.
  268. %
  269. The translation from concrete syntax to abstract syntax is a process
  270. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  271. and implementation of parsing in this book. A parser is provided in
  272. the supporting materials for translating from concrete syntax to
  273. abstract syntax for the languages used in this book.
  274. ASTs can be represented in many different ways inside the compiler,
  275. depending on the programming language used to write the compiler.
  276. %
  277. We use Racket's \code{struct} feature to represent ASTs
  278. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  279. of programming languages (Section~\ref{sec:grammar}) and pattern
  280. matching to inspect individual nodes in an AST
  281. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  282. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  283. chapter provides an brief introduction to these ideas.
  284. \section{Abstract Syntax Trees and Racket Structures}
  285. \label{sec:ast}
  286. Compilers use abstract syntax trees to represent programs because
  287. compilers often need to ask questions like: for a given part of a
  288. program, what kind of language feature is it? What are the sub-parts
  289. of this part of the program? Consider the program on the left and its
  290. AST on the right. This program is an addition and it has two
  291. sub-parts, a read operation and a negation. The negation has another
  292. sub-part, the integer constant \code{8}. By using a tree to represent
  293. the program, we can easily follow the links to go from one part of a
  294. program to its sub-parts.
  295. \begin{center}
  296. \begin{minipage}{0.4\textwidth}
  297. \begin{lstlisting}
  298. (+ (read) (- 8))
  299. \end{lstlisting}
  300. \end{minipage}
  301. \begin{minipage}{0.4\textwidth}
  302. \begin{equation}
  303. \begin{tikzpicture}
  304. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  305. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  306. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  307. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  308. \draw[->] (plus) to (read);
  309. \draw[->] (plus) to (minus);
  310. \draw[->] (minus) to (8);
  311. \end{tikzpicture}
  312. \label{eq:arith-prog}
  313. \end{equation}
  314. \end{minipage}
  315. \end{center}
  316. We use the standard terminology for trees to describe ASTs: each
  317. circle above is called a \emph{node}. The arrows connect a node to its
  318. \emph{children} (which are also nodes). The top-most node is the
  319. \emph{root}. Every node except for the root has a \emph{parent} (the
  320. node it is the child of). If a node has no children, it is a
  321. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  322. %% Recall that an \emph{symbolic expression} (S-expression) is either
  323. %% \begin{enumerate}
  324. %% \item an atom, or
  325. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  326. %% where $e_1$ and $e_2$ are each an S-expression.
  327. %% \end{enumerate}
  328. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  329. %% null value \code{'()}, etc. We can create an S-expression in Racket
  330. %% simply by writing a backquote (called a quasi-quote in Racket)
  331. %% followed by the textual representation of the S-expression. It is
  332. %% quite common to use S-expressions to represent a list, such as $a, b
  333. %% ,c$ in the following way:
  334. %% \begin{lstlisting}
  335. %% `(a . (b . (c . ())))
  336. %% \end{lstlisting}
  337. %% Each element of the list is in the first slot of a pair, and the
  338. %% second slot is either the rest of the list or the null value, to mark
  339. %% the end of the list. Such lists are so common that Racket provides
  340. %% special notation for them that removes the need for the periods
  341. %% and so many parenthesis:
  342. %% \begin{lstlisting}
  343. %% `(a b c)
  344. %% \end{lstlisting}
  345. %% The following expression creates an S-expression that represents AST
  346. %% \eqref{eq:arith-prog}.
  347. %% \begin{lstlisting}
  348. %% `(+ (read) (- 8))
  349. %% \end{lstlisting}
  350. %% When using S-expressions to represent ASTs, the convention is to
  351. %% represent each AST node as a list and to put the operation symbol at
  352. %% the front of the list. The rest of the list contains the children. So
  353. %% in the above case, the root AST node has operation \code{`+} and its
  354. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  355. %% diagram \eqref{eq:arith-prog}.
  356. %% To build larger S-expressions one often needs to splice together
  357. %% several smaller S-expressions. Racket provides the comma operator to
  358. %% splice an S-expression into a larger one. For example, instead of
  359. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  360. %% we could have first created an S-expression for AST
  361. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  362. %% S-expression.
  363. %% \begin{lstlisting}
  364. %% (define ast1.4 `(- 8))
  365. %% (define ast1.1 `(+ (read) ,ast1.4))
  366. %% \end{lstlisting}
  367. %% In general, the Racket expression that follows the comma (splice)
  368. %% can be any expression that produces an S-expression.
  369. We define a Racket \code{struct} for each kind of node. For this
  370. chapter we require just two kinds of nodes: one for integer constants
  371. and one for primitive operations. The following is the \code{struct}
  372. definition for integer constants.
  373. \begin{lstlisting}
  374. (struct Int (value))
  375. \end{lstlisting}
  376. An integer node includes just one thing: the integer value.
  377. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  378. \begin{lstlisting}
  379. (define eight (Int 8))
  380. \end{lstlisting}
  381. We say that the value created by \code{(Int 8)} is an
  382. \emph{instance} of the \code{Int} structure.
  383. The following is the \code{struct} definition for primitives operations.
  384. \begin{lstlisting}
  385. (struct Prim (op arg*))
  386. \end{lstlisting}
  387. A primitive operation node includes an operator symbol \code{op}
  388. and a list of children \code{arg*}. For example, to create
  389. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  390. \begin{lstlisting}
  391. (define neg-eight (Prim '- (list eight)))
  392. \end{lstlisting}
  393. Primitive operations may have zero or more children. The \code{read}
  394. operator has zero children:
  395. \begin{lstlisting}
  396. (define rd (Prim 'read '()))
  397. \end{lstlisting}
  398. whereas the addition operator has two children:
  399. \begin{lstlisting}
  400. (define ast1.1 (Prim '+ (list rd neg-eight)))
  401. \end{lstlisting}
  402. We have made a design choice regarding the \code{Prim} structure.
  403. Instead of using one structure for many different operations
  404. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  405. structure for each operation, as follows.
  406. \begin{lstlisting}
  407. (struct Read ())
  408. (struct Add (left right))
  409. (struct Neg (value))
  410. \end{lstlisting}
  411. The reason we choose to use just one structure is that in many parts
  412. of the compiler the code for the different primitive operators is the
  413. same, so we might as well just write that code once, which is enabled
  414. by using a single structure.
  415. When compiling a program such as \eqref{eq:arith-prog}, we need to
  416. know that the operation associated with the root node is addition and
  417. we need to be able to access its two children. Racket provides pattern
  418. matching over structures to support these kinds of queries, as we
  419. shall see in Section~\ref{sec:pattern-matching}.
  420. In this book, we often write down the concrete syntax of a program
  421. even when we really have in mind the AST because the concrete syntax
  422. is more concise. We recommend that, in your mind, you always think of
  423. programs as abstract syntax trees.
  424. \section{Grammars}
  425. \label{sec:grammar}
  426. A programming language can be thought of as a \emph{set} of programs.
  427. The set is typically infinite (one can always create larger and larger
  428. programs), so one cannot simply describe a language by listing all of
  429. the programs in the language. Instead we write down a set of rules, a
  430. \emph{grammar}, for building programs. Grammars are often used to
  431. define the concrete syntax of a language, but they can also be used to
  432. describe the abstract syntax. We shall write our rules in a variant of
  433. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  434. example, we describe a small language, named $R_0$, that consists of
  435. integers and arithmetic operations.
  436. The first grammar rule for the abstract syntax of $R_0$ says that an
  437. instance of the \code{Int} structure is an expression:
  438. \begin{equation}
  439. \Exp ::= \INT{\Int} \label{eq:arith-int}
  440. \end{equation}
  441. %
  442. Each rule has a left-hand-side and a right-hand-side. The way to read
  443. a rule is that if you have all the program parts on the
  444. right-hand-side, then you can create an AST node and categorize it
  445. according to the left-hand-side.
  446. %
  447. A name such as $\Exp$ that is
  448. defined by the grammar rules is a \emph{non-terminal}.
  449. %
  450. The name $\Int$ is a also a non-terminal, but instead of defining it
  451. with a grammar rule, we define it with the following explanation. We
  452. make the simplifying design decision that all of the languages in this
  453. book only handle machine-representable integers. On most modern
  454. machines this corresponds to integers represented with 64-bits, i.e.,
  455. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  456. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  457. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  458. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  459. that the sequence of decimals represent an integer in range $-2^{62}$
  460. to $2^{62}-1$.
  461. The second grammar rule is the \texttt{read} operation that receives
  462. an input integer from the user of the program.
  463. \begin{equation}
  464. \Exp ::= \READ{} \label{eq:arith-read}
  465. \end{equation}
  466. The third rule says that, given an $\Exp$ node, you can build another
  467. $\Exp$ node by negating it.
  468. \begin{equation}
  469. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  470. \end{equation}
  471. Symbols in typewriter font such as \key{-} and \key{read} are
  472. \emph{terminal} symbols and must literally appear in the program for
  473. the rule to be applicable.
  474. We can apply the rules to build ASTs in the $R_0$
  475. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  476. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  477. an $\Exp$.
  478. \begin{center}
  479. \begin{minipage}{0.4\textwidth}
  480. \begin{lstlisting}
  481. (Prim '- (list (Int 8)))
  482. \end{lstlisting}
  483. \end{minipage}
  484. \begin{minipage}{0.25\textwidth}
  485. \begin{equation}
  486. \begin{tikzpicture}
  487. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  488. \node[draw, circle] (8) at (0, -1.2) {$8$};
  489. \draw[->] (minus) to (8);
  490. \end{tikzpicture}
  491. \label{eq:arith-neg8}
  492. \end{equation}
  493. \end{minipage}
  494. \end{center}
  495. The next grammar rule defines addition expressions:
  496. \begin{equation}
  497. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  498. \end{equation}
  499. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  500. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  501. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  502. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  503. to show that
  504. \begin{lstlisting}
  505. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  506. \end{lstlisting}
  507. is an $\Exp$ in the $R_0$ language.
  508. If you have an AST for which the above rules do not apply, then the
  509. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  510. is not in $R_0$ because there are no rules for \code{+} with only one
  511. argument, nor for \key{-} with two arguments. Whenever we define a
  512. language with a grammar, the language only includes those programs
  513. that are justified by the rules.
  514. The last grammar rule for $R_0$ states that there is a \code{Program}
  515. node to mark the top of the whole program:
  516. \[
  517. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  518. \]
  519. The \code{Program} structure is defined as follows
  520. \begin{lstlisting}
  521. (struct Program (info body))
  522. \end{lstlisting}
  523. where \code{body} is an expression. In later chapters, the \code{info}
  524. part will be used to store auxiliary information but for now it is
  525. just the empty list.
  526. It is common to have many grammar rules with the same left-hand side
  527. but different right-hand sides, such as the rules for $\Exp$ in the
  528. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  529. combine several right-hand-sides into a single rule.
  530. We collect all of the grammar rules for the abstract syntax of $R_0$
  531. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  532. defined in Figure~\ref{fig:r0-concrete-syntax}.
  533. The \code{read-program} function provided in \code{utilities.rkt} of
  534. the support materials reads a program in from a file (the sequence of
  535. characters in the concrete syntax of Racket) and parses it into an
  536. abstract syntax tree. See the description of \code{read-program} in
  537. Appendix~\ref{appendix:utilities} for more details.
  538. \begin{figure}[tp]
  539. \fbox{
  540. \begin{minipage}{0.96\textwidth}
  541. \[
  542. \begin{array}{rcl}
  543. \begin{array}{rcl}
  544. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  545. R_0 &::=& \Exp
  546. \end{array}
  547. \end{array}
  548. \]
  549. \end{minipage}
  550. }
  551. \caption{The concrete syntax of $R_0$.}
  552. \label{fig:r0-concrete-syntax}
  553. \end{figure}
  554. \begin{figure}[tp]
  555. \fbox{
  556. \begin{minipage}{0.96\textwidth}
  557. \[
  558. \begin{array}{rcl}
  559. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  560. &\mid& \ADD{\Exp}{\Exp} \\
  561. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  562. \end{array}
  563. \]
  564. \end{minipage}
  565. }
  566. \caption{The abstract syntax of $R_0$.}
  567. \label{fig:r0-syntax}
  568. \end{figure}
  569. \section{Pattern Matching}
  570. \label{sec:pattern-matching}
  571. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  572. the parts of an AST node. Racket provides the \texttt{match} form to
  573. access the parts of a structure. Consider the following example and
  574. the output on the right.
  575. \begin{center}
  576. \begin{minipage}{0.5\textwidth}
  577. \begin{lstlisting}
  578. (match ast1.1
  579. [(Prim op (list child1 child2))
  580. (print op)])
  581. \end{lstlisting}
  582. \end{minipage}
  583. \vrule
  584. \begin{minipage}{0.25\textwidth}
  585. \begin{lstlisting}
  586. '+
  587. \end{lstlisting}
  588. \end{minipage}
  589. \end{center}
  590. In the above example, the \texttt{match} form takes the AST
  591. \eqref{eq:arith-prog} and binds its parts to the three pattern
  592. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  593. general, a match clause consists of a \emph{pattern} and a
  594. \emph{body}. Patterns are recursively defined to be either a pattern
  595. variable, a structure name followed by a pattern for each of the
  596. structure's arguments, or an S-expression (symbols, lists, etc.).
  597. (See Chapter 12 of The Racket
  598. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  599. and Chapter 9 of The Racket
  600. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  601. for a complete description of \code{match}.)
  602. %
  603. The body of a match clause may contain arbitrary Racket code. The
  604. pattern variables can be used in the scope of the body.
  605. A \code{match} form may contain several clauses, as in the following
  606. function \code{leaf?} that recognizes when an $R_0$ node is
  607. a leaf. The \code{match} proceeds through the clauses in order,
  608. checking whether the pattern can match the input AST. The
  609. body of the first clause that matches is executed. The output of
  610. \code{leaf?} for several ASTs is shown on the right.
  611. \begin{center}
  612. \begin{minipage}{0.6\textwidth}
  613. \begin{lstlisting}
  614. (define (leaf? arith)
  615. (match arith
  616. [(Int n) #t]
  617. [(Prim 'read '()) #t]
  618. [(Prim '- (list c1)) #f]
  619. [(Prim '+ (list c1 c2)) #f]))
  620. (leaf? (Prim 'read '()))
  621. (leaf? (Prim '- (list (Int 8))))
  622. (leaf? (Int 8))
  623. \end{lstlisting}
  624. \end{minipage}
  625. \vrule
  626. \begin{minipage}{0.25\textwidth}
  627. \begin{lstlisting}
  628. #t
  629. #f
  630. #t
  631. \end{lstlisting}
  632. \end{minipage}
  633. \end{center}
  634. When writing a \code{match}, we refer to the grammar definition to
  635. identify which non-terminal we are expecting to match against, then we
  636. make sure that 1) we have one clause for each alternative of that
  637. non-terminal and 2) that the pattern in each clause corresponds to the
  638. corresponding right-hand side of a grammar rule. For the \code{match}
  639. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  640. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  641. alternatives, so the \code{match} has 4 clauses. The pattern in each
  642. clause corresponds to the right-hand side of a grammar rule. For
  643. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  644. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  645. patterns, replace non-terminals such as $\Exp$ with pattern variables
  646. of your choice (e.g. \code{c1} and \code{c2}).
  647. \section{Recursion}
  648. \label{sec:recursion}
  649. Programs are inherently recursive. For example, an $R_0$ expression is
  650. often made of smaller expressions. Thus, the natural way to process an
  651. entire program is with a recursive function. As a first example of
  652. such a recursive function, we define \texttt{exp?} below, which takes
  653. an arbitrary value and determines whether or not it is an $R_0$
  654. expression.
  655. %
  656. When a recursive function is defined using a sequence of match clauses
  657. that correspond to a grammar, and the body of each clause makes a
  658. recursive call on each child node, then we say the function is defined
  659. by \emph{structural recursion}\footnote{This principle of structuring
  660. code according to the data definition is advocated in the book
  661. \emph{How to Design Programs}
  662. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  663. define a second function, named \code{R0?}, that determines whether a
  664. value is an $R_0$ program. In general we can expect to write one
  665. recursive function to handle each non-terminal in a grammar.
  666. %
  667. \begin{center}
  668. \begin{minipage}{0.7\textwidth}
  669. \begin{lstlisting}
  670. (define (exp? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (exp? e)]
  675. [(Prim '+ (list e1 e2))
  676. (and (exp? e1) (exp? e2))]
  677. [else #f]))
  678. (define (R0? ast)
  679. (match ast
  680. [(Program '() e) (exp? e)]
  681. [else #f]))
  682. (R0? (Program '() ast1.1)
  683. (R0? (Program '()
  684. (Prim '- (list (Prim 'read '())
  685. (Prim '+ (list (Num 8)))))))
  686. \end{lstlisting}
  687. \end{minipage}
  688. \vrule
  689. \begin{minipage}{0.25\textwidth}
  690. \begin{lstlisting}
  691. #t
  692. #f
  693. \end{lstlisting}
  694. \end{minipage}
  695. \end{center}
  696. You may be tempted to merge the two functions into one, like this:
  697. \begin{center}
  698. \begin{minipage}{0.5\textwidth}
  699. \begin{lstlisting}
  700. (define (R0? ast)
  701. (match ast
  702. [(Int n) #t]
  703. [(Prim 'read '()) #t]
  704. [(Prim '- (list e)) (R0? e)]
  705. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  706. [(Program '() e) (R0? e)]
  707. [else #f]))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \end{center}
  711. %
  712. Sometimes such a trick will save a few lines of code, especially when
  713. it comes to the \code{Program} wrapper. Yet this style is generally
  714. \emph{not} recommended because it can get you into trouble.
  715. %
  716. For example, the above function is subtly wrong:
  717. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  718. will return true, when it should return false.
  719. %% NOTE FIXME - must check for consistency on this issue throughout.
  720. \section{Interpreters}
  721. \label{sec:interp-R0}
  722. The meaning, or semantics, of a program is typically defined in the
  723. specification of the language. For example, the Scheme language is
  724. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  725. defined in its reference manual~\citep{plt-tr}. In this book we use an
  726. interpreter to define the meaning of each language that we consider,
  727. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  728. interpreter that is designated (by some people) as the definition of a
  729. language is called a \emph{definitional interpreter}. We warm up by
  730. creating a definitional interpreter for the $R_0$ language, which
  731. serves as a second example of structural recursion. The
  732. \texttt{interp-R0} function is defined in
  733. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  734. input program followed by a call to the \lstinline{interp-exp} helper
  735. function, which in turn has one match clause per grammar rule for
  736. $R_0$ expressions.
  737. \begin{figure}[tp]
  738. \begin{lstlisting}
  739. (define (interp-exp e)
  740. (match e
  741. [(Int n) n]
  742. [(Prim 'read '())
  743. (define r (read))
  744. (cond [(fixnum? r) r]
  745. [else (error 'interp-R0 "expected an integer" r)])]
  746. [(Prim '- (list e))
  747. (define v (interp-exp e))
  748. (fx- 0 v)]
  749. [(Prim '+ (list e1 e2))
  750. (define v1 (interp-exp e1))
  751. (define v2 (interp-exp e2))
  752. (fx+ v1 v2)]
  753. ))
  754. (define (interp-R0 p)
  755. (match p
  756. [(Program '() e) (interp-exp e)]
  757. ))
  758. \end{lstlisting}
  759. \caption{Interpreter for the $R_0$ language.}
  760. \label{fig:interp-R0}
  761. \end{figure}
  762. Let us consider the result of interpreting a few $R_0$ programs. The
  763. following program adds two integers.
  764. \begin{lstlisting}
  765. (+ 10 32)
  766. \end{lstlisting}
  767. The result is \key{42}. We wrote the above program in concrete syntax,
  768. whereas the parsed abstract syntax is:
  769. \begin{lstlisting}
  770. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  771. \end{lstlisting}
  772. The next example demonstrates that expressions may be nested within
  773. each other, in this case nesting several additions and negations.
  774. \begin{lstlisting}
  775. (+ 10 (- (+ 12 20)))
  776. \end{lstlisting}
  777. What is the result of the above program?
  778. As mentioned previously, the $R_0$ language does not support
  779. arbitrarily-large integers, but only $63$-bit integers, so we
  780. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  781. in Racket.
  782. Suppose
  783. \[
  784. n = 999999999999999999
  785. \]
  786. which indeed fits in $63$-bits. What happens when we run the
  787. following program in our interpreter?
  788. \begin{lstlisting}
  789. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  790. \end{lstlisting}
  791. It produces an error:
  792. \begin{lstlisting}
  793. fx+: result is not a fixnum
  794. \end{lstlisting}
  795. We establish the convention that if running the definitional
  796. interpreter on a program produces an error, then the meaning of that
  797. program is \emph{unspecified}. That means a compiler for the language
  798. is under no obligations regarding that program; it may or may not
  799. produce an executable, and if it does, that executable can do
  800. anything. This convention applies to the languages defined in this
  801. book, as a way to simplify the student's task of implementing them,
  802. but this convention is not applicable to all programming languages.
  803. Moving on to the last feature of the $R_0$ language, the \key{read}
  804. operation prompts the user of the program for an integer. Recall that
  805. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  806. \code{8}. So if we run
  807. \begin{lstlisting}
  808. (interp-R0 (Program '() ast1.1))
  809. \end{lstlisting}
  810. and if the input is \code{50}, then we get the answer to life, the
  811. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  812. Guide to the Galaxy} by Douglas Adams.}
  813. We include the \key{read} operation in $R_0$ so a clever student
  814. cannot implement a compiler for $R_0$ that simply runs the interpreter
  815. during compilation to obtain the output and then generates the trivial
  816. code to produce the output. (Yes, a clever student did this in the
  817. first instance of this course.)
  818. The job of a compiler is to translate a program in one language into a
  819. program in another language so that the output program behaves the
  820. same way as the input program does according to its definitional
  821. interpreter. This idea is depicted in the following diagram. Suppose
  822. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  823. interpreter for each language. Suppose that the compiler translates
  824. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  825. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  826. respective interpreters with input $i$ should yield the same output
  827. $o$.
  828. \begin{equation} \label{eq:compile-correct}
  829. \begin{tikzpicture}[baseline=(current bounding box.center)]
  830. \node (p1) at (0, 0) {$P_1$};
  831. \node (p2) at (3, 0) {$P_2$};
  832. \node (o) at (3, -2.5) {$o$};
  833. \path[->] (p1) edge [above] node {compile} (p2);
  834. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  835. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  836. \end{tikzpicture}
  837. \end{equation}
  838. In the next section we see our first example of a compiler.
  839. \section{Example Compiler: a Partial Evaluator}
  840. \label{sec:partial-evaluation}
  841. In this section we consider a compiler that translates $R_0$ programs
  842. into $R_0$ programs that may be more efficient, that is, this compiler
  843. is an optimizer. This optimizer eagerly computes the parts of the
  844. program that do not depend on any inputs, a process known as
  845. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  846. following program
  847. \begin{lstlisting}
  848. (+ (read) (- (+ 5 3)))
  849. \end{lstlisting}
  850. our compiler will translate it into the program
  851. \begin{lstlisting}
  852. (+ (read) -8)
  853. \end{lstlisting}
  854. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  855. evaluator for the $R_0$ language. The output of the partial evaluator
  856. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  857. recursion over $\Exp$ is captured in the \code{pe-exp} function
  858. whereas the code for partially evaluating the negation and addition
  859. operations is factored into two separate helper functions:
  860. \code{pe-neg} and \code{pe-add}. The input to these helper
  861. functions is the output of partially evaluating the children.
  862. \begin{figure}[tp]
  863. \begin{lstlisting}
  864. (define (pe-neg r)
  865. (match r
  866. [(Int n) (Int (fx- 0 n))]
  867. [else (Prim '- (list r))]))
  868. (define (pe-add r1 r2)
  869. (match* (r1 r2)
  870. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  871. [(_ _) (Prim '+ (list r1 r2))]))
  872. (define (pe-exp e)
  873. (match e
  874. [(Int n) (Int n)]
  875. [(Prim 'read '()) (Prim 'read '())]
  876. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  877. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  878. ))
  879. (define (pe-R0 p)
  880. (match p
  881. [(Program '() e) (Program '() (pe-exp e))]
  882. ))
  883. \end{lstlisting}
  884. \caption{A partial evaluator for $R_0$ expressions.}
  885. \label{fig:pe-arith}
  886. \end{figure}
  887. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  888. arguments are integers and if they are, perform the appropriate
  889. arithmetic. Otherwise, they create an AST node for the operation
  890. (either negation or addition).
  891. To gain some confidence that the partial evaluator is correct, we can
  892. test whether it produces programs that get the same result as the
  893. input programs. That is, we can test whether it satisfies Diagram
  894. \eqref{eq:compile-correct}. The following code runs the partial
  895. evaluator on several examples and tests the output program. The
  896. \texttt{parse-program} and \texttt{assert} functions are defined in
  897. Appendix~\ref{appendix:utilities}.\\
  898. \begin{minipage}{1.0\textwidth}
  899. \begin{lstlisting}
  900. (define (test-pe p)
  901. (assert "testing pe-R0"
  902. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  903. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  904. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  905. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  906. \end{lstlisting}
  907. \end{minipage}
  908. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  909. \chapter{Integers and Variables}
  910. \label{ch:int-exp}
  911. This chapter is about compiling the subset of Racket that includes
  912. integer arithmetic and local variable binding, which we name $R_1$, to
  913. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  914. to x86-64 simply as x86. The chapter begins with a description of the
  915. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  916. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  917. discuss only what is needed for compiling $R_1$. We introduce more of
  918. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  919. reflect on their differences and come up with a plan to break down the
  920. translation from $R_1$ to x86 into a handful of steps
  921. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  922. chapter give detailed hints regarding each step
  923. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  924. to give enough hints that the well-prepared reader, together with a
  925. few friends, can implement a compiler from $R_1$ to x86 in a couple
  926. weeks while at the same time leaving room for some fun and creativity.
  927. To give the reader a feeling for the scale of this first compiler, the
  928. instructor solution for the $R_1$ compiler is less than 500 lines of
  929. code.
  930. \section{The $R_1$ Language}
  931. \label{sec:s0}
  932. The $R_1$ language extends the $R_0$ language with variable
  933. definitions. The concrete syntax of the $R_1$ language is defined by
  934. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  935. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  936. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  937. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  938. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  939. \key{Program} struct to mark the top of the program.
  940. %% The $\itm{info}$
  941. %% field of the \key{Program} structure contains an \emph{association
  942. %% list} (a list of key-value pairs) that is used to communicate
  943. %% auxiliary data from one compiler pass the next.
  944. Despite the simplicity of the $R_1$ language, it is rich enough to
  945. exhibit several compilation techniques.
  946. \begin{figure}[tp]
  947. \centering
  948. \fbox{
  949. \begin{minipage}{0.96\textwidth}
  950. \[
  951. \begin{array}{rcl}
  952. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  953. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  954. R_1 &::=& \Exp
  955. \end{array}
  956. \]
  957. \end{minipage}
  958. }
  959. \caption{The concrete syntax of $R_1$.}
  960. \label{fig:r1-concrete-syntax}
  961. \end{figure}
  962. \begin{figure}[tp]
  963. \centering
  964. \fbox{
  965. \begin{minipage}{0.96\textwidth}
  966. \[
  967. \begin{array}{rcl}
  968. \Exp &::=& \INT{\Int} \mid \READ{} \\
  969. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  970. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  971. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  972. \end{array}
  973. \]
  974. \end{minipage}
  975. }
  976. \caption{The abstract syntax of $R_1$.}
  977. \label{fig:r1-syntax}
  978. \end{figure}
  979. Let us dive further into the syntax and semantics of the $R_1$
  980. language. The \key{Let} feature defines a variable for use within its
  981. body and initializes the variable with the value of an expression.
  982. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  983. The concrete syntax for \key{Let} is
  984. \begin{lstlisting}
  985. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  986. \end{lstlisting}
  987. For example, the following program initializes \code{x} to $32$ and then
  988. evaluates the body \code{(+ 10 x)}, producing $42$.
  989. \begin{lstlisting}
  990. (let ([x (+ 12 20)]) (+ 10 x))
  991. \end{lstlisting}
  992. When there are multiple \key{let}'s for the same variable, the closest
  993. enclosing \key{let} is used. That is, variable definitions overshadow
  994. prior definitions. Consider the following program with two \key{let}'s
  995. that define variables named \code{x}. Can you figure out the result?
  996. \begin{lstlisting}
  997. (let ([x 32]) (+ (let ([x 10]) x) x))
  998. \end{lstlisting}
  999. For the purposes of depicting which variable uses correspond to which
  1000. definitions, the following shows the \code{x}'s annotated with
  1001. subscripts to distinguish them. Double check that your answer for the
  1002. above is the same as your answer for this annotated version of the
  1003. program.
  1004. \begin{lstlisting}
  1005. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1006. \end{lstlisting}
  1007. The initializing expression is always evaluated before the body of the
  1008. \key{let}, so in the following, the \key{read} for \code{x} is
  1009. performed before the \key{read} for \code{y}. Given the input
  1010. $52$ then $10$, the following produces $42$ (not $-42$).
  1011. \begin{lstlisting}
  1012. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1013. \end{lstlisting}
  1014. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1015. \small
  1016. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1017. An \emph{association list} (alist) is a list of key-value pairs.
  1018. For example, we can map people to their ages with an alist.
  1019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1020. (define ages
  1021. '((jane . 25) (sam . 24) (kate . 45)))
  1022. \end{lstlisting}
  1023. The \emph{dictionary} interface is for mapping keys to values.
  1024. Every alist implements this interface. The package
  1025. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1026. provides many functions for working with dictionaries. Here
  1027. are a few of them:
  1028. \begin{description}
  1029. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1030. returns the value associated with the given $\itm{key}$.
  1031. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1032. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1033. but otherwise is the same as $\itm{dict}$.
  1034. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1035. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1036. of keys and values in $\itm{dict}$. For example, the following
  1037. creates a new alist in which the ages are incremented.
  1038. \end{description}
  1039. \vspace{-10pt}
  1040. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1041. (for/list ([(k v) (in-dict ages)])
  1042. (cons k (add1 v)))
  1043. \end{lstlisting}
  1044. \end{tcolorbox}
  1045. \end{wrapfigure}
  1046. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1047. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1048. \key{match} clauses for variables and for \key{let}. For \key{let},
  1049. we need a way to communicate the value of a variable to all the uses
  1050. of a variable. To accomplish this, we maintain a mapping from
  1051. variables to values. Throughout the compiler we often need to map
  1052. variables to information about them. We refer to these mappings as
  1053. \emph{environments}
  1054. \footnote{Another common term for environment in the compiler
  1055. literature is \emph{symbol table}.}. For simplicity, we use an
  1056. association list (alist) to represent the environment. The sidebar to
  1057. the right gives a brief introduction to alists and the
  1058. \code{racket/dict} package. The \code{interp-R1} function takes the
  1059. current environment, \code{env}, as an extra parameter. When the
  1060. interpreter encounters a variable, it finds the corresponding value
  1061. using the \code{dict-ref} function. When the interpreter encounters a
  1062. \key{Let}, it evaluates the initializing expression, extends the
  1063. environment with the result value bound to the variable, using
  1064. \code{dict-set}, then evaluates the body of the \key{Let}.
  1065. \begin{figure}[tp]
  1066. \begin{lstlisting}
  1067. (define (interp-exp env)
  1068. (lambda (e)
  1069. (match e
  1070. [(Int n) n]
  1071. [(Prim 'read '())
  1072. (define r (read))
  1073. (cond [(fixnum? r) r]
  1074. [else (error 'interp-R1 "expected an integer" r)])]
  1075. [(Prim '- (list e))
  1076. (define v ((interp-exp env) e))
  1077. (fx- 0 v)]
  1078. [(Prim '+ (list e1 e2))
  1079. (define v1 ((interp-exp env) e1))
  1080. (define v2 ((interp-exp env) e2))
  1081. (fx+ v1 v2)]
  1082. [(Var x) (dict-ref env x)]
  1083. [(Let x e body)
  1084. (define new-env (dict-set env x ((interp-exp env) e)))
  1085. ((interp-exp new-env) body)]
  1086. )))
  1087. (define (interp-R1 p)
  1088. (match p
  1089. [(Program '() e) ((interp-exp '()) e)]
  1090. ))
  1091. \end{lstlisting}
  1092. \caption{Interpreter for the $R_1$ language.}
  1093. \label{fig:interp-R1}
  1094. \end{figure}
  1095. The goal for this chapter is to implement a compiler that translates
  1096. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1097. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1098. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1099. is, they both output the same integer $n$. We depict this correctness
  1100. criteria in the following diagram.
  1101. \[
  1102. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1103. \node (p1) at (0, 0) {$P_1$};
  1104. \node (p2) at (4, 0) {$P_2$};
  1105. \node (o) at (4, -2) {$n$};
  1106. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1107. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1108. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1109. \end{tikzpicture}
  1110. \]
  1111. In the next section we introduce enough of the x86 assembly
  1112. language to compile $R_1$.
  1113. \section{The x86$_0$ Assembly Language}
  1114. \label{sec:x86}
  1115. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1116. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1117. %
  1118. An x86 program begins with a \code{main} label followed by a sequence
  1119. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1120. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1121. instructions.
  1122. %
  1123. An x86 program is stored in the computer's memory and the computer has
  1124. a \emph{program counter} that points to the address of the next
  1125. instruction to be executed. For most instructions, once the
  1126. instruction is executed, the program counter is incremented to point
  1127. to the immediately following instruction in memory. Most x86
  1128. instructions take two operands, where each operand is either an
  1129. integer constant (called \emph{immediate value}), a \emph{register},
  1130. or a memory location. A register is a special kind of variable. Each
  1131. one holds a 64-bit value; there are 16 registers in the computer and
  1132. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1133. as a mapping of 64-bit addresses to 64-bit values%
  1134. \footnote{This simple story suffices for describing how sequential
  1135. programs access memory but is not sufficient for multi-threaded
  1136. programs. However, multi-threaded execution is beyond the scope of
  1137. this book.}.
  1138. %
  1139. We use the AT\&T syntax expected by the GNU assembler, which comes
  1140. with the \key{gcc} compiler that we use for compiling assembly code to
  1141. machine code.
  1142. %
  1143. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1144. the x86 instructions used in this book.
  1145. % to do: finish treatment of imulq
  1146. % it's needed for vector's in R6/R7
  1147. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1148. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1149. && \key{r8} \mid \key{r9} \mid \key{r10}
  1150. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1151. \mid \key{r14} \mid \key{r15}}
  1152. \begin{figure}[tp]
  1153. \fbox{
  1154. \begin{minipage}{0.96\textwidth}
  1155. \[
  1156. \begin{array}{lcl}
  1157. \Reg &::=& \allregisters{} \\
  1158. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1159. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1160. \key{subq} \; \Arg\key{,} \Arg \mid
  1161. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1162. && \key{callq} \; \mathit{label} \mid
  1163. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1164. && \itm{label}\key{:}\; \Instr \\
  1165. x86_0 &::= & \key{.globl main}\\
  1166. & & \key{main:} \; \Instr\ldots
  1167. \end{array}
  1168. \]
  1169. \end{minipage}
  1170. }
  1171. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1172. \label{fig:x86-0-concrete}
  1173. \end{figure}
  1174. An immediate value is written using the notation \key{\$}$n$ where $n$
  1175. is an integer.
  1176. %
  1177. A register is written with a \key{\%} followed by the register name,
  1178. such as \key{\%rax}.
  1179. %
  1180. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1181. which obtains the address stored in register $r$ and then adds $n$
  1182. bytes to the address. The resulting address is used to either load or
  1183. store to memory depending on whether it occurs as a source or
  1184. destination argument of an instruction.
  1185. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1186. source $s$ and destination $d$, applies the arithmetic operation, then
  1187. writes the result back to the destination $d$.
  1188. %
  1189. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1190. stores the result in $d$.
  1191. %
  1192. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1193. specified by the label and $\key{retq}$ returns from a procedure to
  1194. its caller. We discuss procedure calls in more detail later in this
  1195. chapter and in Chapter~\ref{ch:functions}. The
  1196. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1197. the address of the instruction after the specified label.
  1198. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1199. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1200. \key{main} procedure is externally visible, which is necessary so
  1201. that the operating system can call it. The label \key{main:}
  1202. indicates the beginning of the \key{main} procedure which is where
  1203. the operating system starts executing this program. The instruction
  1204. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1205. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1206. $10$ in \key{rax} and puts the result, $42$, back into
  1207. \key{rax}.
  1208. %
  1209. The last instruction, \key{retq}, finishes the \key{main} function by
  1210. returning the integer in \key{rax} to the operating system. The
  1211. operating system interprets this integer as the program's exit
  1212. code. By convention, an exit code of 0 indicates that a program
  1213. completed successfully, and all other exit codes indicate various
  1214. errors. Nevertheless, we return the result of the program as the exit
  1215. code.
  1216. %\begin{wrapfigure}{r}{2.25in}
  1217. \begin{figure}[tbp]
  1218. \begin{lstlisting}
  1219. .globl main
  1220. main:
  1221. movq $10, %rax
  1222. addq $32, %rax
  1223. retq
  1224. \end{lstlisting}
  1225. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1226. \label{fig:p0-x86}
  1227. %\end{wrapfigure}
  1228. \end{figure}
  1229. Unfortunately, x86 varies in a couple ways depending on what operating
  1230. system it is assembled in. The code examples shown here are correct on
  1231. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1232. labels like \key{main} must be prefixed with an underscore, as in
  1233. \key{\_main}.
  1234. We exhibit the use of memory for storing intermediate results in the
  1235. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1236. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1237. memory called the \emph{procedure call stack} (or \emph{stack} for
  1238. short). The stack consists of a separate \emph{frame} for each
  1239. procedure call. The memory layout for an individual frame is shown in
  1240. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1241. \emph{stack pointer} and points to the item at the top of the
  1242. stack. The stack grows downward in memory, so we increase the size of
  1243. the stack by subtracting from the stack pointer. In the context of a
  1244. procedure call, the \emph{return address} is the next instruction
  1245. after the call instruction on the caller side. During a function call,
  1246. the return address is pushed onto the stack. The register \key{rbp}
  1247. is the \emph{base pointer} and is used to access variables associated
  1248. with the current procedure call. The base pointer of the caller is
  1249. pushed onto the stack after the return address. We number the
  1250. variables from $1$ to $n$. Variable $1$ is stored at address
  1251. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1252. \begin{figure}[tbp]
  1253. \begin{lstlisting}
  1254. start:
  1255. movq $10, -8(%rbp)
  1256. negq -8(%rbp)
  1257. movq -8(%rbp), %rax
  1258. addq $52, %rax
  1259. jmp conclusion
  1260. .globl main
  1261. main:
  1262. pushq %rbp
  1263. movq %rsp, %rbp
  1264. subq $16, %rsp
  1265. jmp start
  1266. conclusion:
  1267. addq $16, %rsp
  1268. popq %rbp
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p1-x86}
  1273. \end{figure}
  1274. \begin{figure}[tbp]
  1275. \centering
  1276. \begin{tabular}{|r|l|} \hline
  1277. Position & Contents \\ \hline
  1278. 8(\key{\%rbp}) & return address \\
  1279. 0(\key{\%rbp}) & old \key{rbp} \\
  1280. -8(\key{\%rbp}) & variable $1$ \\
  1281. -16(\key{\%rbp}) & variable $2$ \\
  1282. \ldots & \ldots \\
  1283. 0(\key{\%rsp}) & variable $n$\\ \hline
  1284. \end{tabular}
  1285. \caption{Memory layout of a frame.}
  1286. \label{fig:frame}
  1287. \end{figure}
  1288. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1289. control is transfered from the operating system to the \code{main}
  1290. function. The operating system issues a \code{callq main} instruction
  1291. which pushes its return address on the stack and then jumps to
  1292. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1293. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1294. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1295. alignment (because the \code{callq} pushed the return address). The
  1296. first three instructions are the typical \emph{prelude} for a
  1297. procedure. The instruction \code{pushq \%rbp} saves the base pointer
  1298. for the caller onto the stack and subtracts $8$ from the stack
  1299. pointer. At this point the stack pointer is back to being 16-byte
  1300. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1301. base pointer so that it points the location of the old base
  1302. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1303. pointer down to make enough room for storing variables. This program
  1304. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1305. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1306. we are ready to make calls to other functions. The last instruction of
  1307. the prelude is \code{jmp start}, which transfers control to the
  1308. instructions that were generated from the Racket expression \code{(+
  1309. 10 32)}.
  1310. The four instructions under the label \code{start} carry out the work
  1311. of computing \code{(+ 52 (- 10)))}. The first instruction
  1312. \code{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1313. instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1314. instruction \code{movq \$52, \%rax} places $52$ in the register \code{rax} and
  1315. finally \code{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1316. \code{rax}, at which point \code{rax} contains $42$.
  1317. The three instructions under the label \code{conclusion} are the
  1318. typical \emph{conclusion} of a procedure. The first two instructions
  1319. are necessary to get the state of the machine back to where it was at
  1320. the beginning of the procedure. The instruction \key{addq \$16,
  1321. \%rsp} moves the stack pointer back to point at the old base
  1322. pointer. The amount added here needs to match the amount that was
  1323. subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1324. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1325. pointer. The last instruction, \key{retq}, jumps back to the
  1326. procedure that called this one and adds 8 to the stack pointer, which
  1327. returns the stack pointer to where it was prior to the procedure call.
  1328. The compiler needs a convenient representation for manipulating x86
  1329. programs, so we define an abstract syntax for x86 in
  1330. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1331. a subscript $0$ because later we introduce extended versions of this
  1332. assembly language. The main difference compared to the concrete syntax
  1333. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1334. instructions to appear anywhere, but instead organizes instructions
  1335. into groups called \emph{blocks} and associates a label with every
  1336. block, which is why the \key{CFG} struct (for control-flow graph)
  1337. includes an alist mapping labels to blocks. The reason for this
  1338. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1339. introduce conditional branching. The \code{Block} structure includes
  1340. an $\itm{info}$ field that is not needed for this chapter, but will
  1341. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1342. the $\itm{info}$ field should just contain an empty list.
  1343. \begin{figure}[tp]
  1344. \fbox{
  1345. \begin{minipage}{0.96\textwidth}
  1346. \small
  1347. \[
  1348. \begin{array}{lcl}
  1349. \Reg &::=& \allregisters{} \\
  1350. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1351. \mid \DEREF{\Reg}{\Int} \\
  1352. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1353. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1354. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1355. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1356. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1357. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1358. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1359. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1360. \end{array}
  1361. \]
  1362. \end{minipage}
  1363. }
  1364. \caption{The abstract syntax of x86$_0$ assembly.}
  1365. \label{fig:x86-0-ast}
  1366. \end{figure}
  1367. \section{Planning the trip to x86 via the $C_0$ language}
  1368. \label{sec:plan-s0-x86}
  1369. To compile one language to another it helps to focus on the
  1370. differences between the two languages because the compiler will need
  1371. to bridge those differences. What are the differences between $R_1$
  1372. and x86 assembly? Here are some of the most important ones:
  1373. \begin{enumerate}
  1374. \item[(a)] x86 arithmetic instructions typically have two arguments
  1375. and update the second argument in place. In contrast, $R_1$
  1376. arithmetic operations take two arguments and produce a new value.
  1377. An x86 instruction may have at most one memory-accessing argument.
  1378. Furthermore, some instructions place special restrictions on their
  1379. arguments.
  1380. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1381. whereas x86 instructions restrict their arguments to be integers
  1382. constants, registers, and memory locations.
  1383. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1384. sequence of instructions and jumps to labeled positions, whereas in
  1385. $R_1$ the order of evaluation is a left-to-right depth-first
  1386. traversal of the abstract syntax tree.
  1387. \item[(d)] An $R_1$ program can have any number of variables whereas
  1388. x86 has 16 registers and the procedure calls stack.
  1389. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1390. same name. The registers and memory locations of x86 all have unique
  1391. names or addresses.
  1392. \end{enumerate}
  1393. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1394. the problem into several steps, dealing with the above differences one
  1395. at a time. Each of these steps is called a \emph{pass} of the
  1396. compiler.
  1397. %
  1398. This terminology comes from each step traverses (i.e. passes over) the
  1399. AST of the program.
  1400. %
  1401. We begin by sketching how we might implement each pass, and give them
  1402. names. We then figure out an ordering of the passes and the
  1403. input/output language for each pass. The very first pass has $R_1$ as
  1404. its input language and the last pass has x86 as its output
  1405. language. In between we can choose whichever language is most
  1406. convenient for expressing the output of each pass, whether that be
  1407. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1408. Finally, to implement each pass we write one recursive function per
  1409. non-terminal in the grammar of the input language of the pass.
  1410. \begin{description}
  1411. \item[Pass \key{select-instructions}] To handle the difference between
  1412. $R_1$ operations and x86 instructions we convert each $R_1$
  1413. operation to a short sequence of instructions that accomplishes the
  1414. same task.
  1415. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1416. subexpression (i.e. operator and operand, and hence the name
  1417. \key{opera*}) is an \emph{atomic} expression (a variable or
  1418. integer), we introduce temporary variables to hold the results
  1419. of subexpressions.
  1420. \item[Pass \key{explicate-control}] To make the execution order of the
  1421. program explicit, we convert from the abstract syntax tree
  1422. representation into a \emph{control-flow graph} in which each node
  1423. contains a sequence of statements and the edges between nodes say
  1424. where to go at the end of the sequence.
  1425. \item[Pass \key{assign-homes}] To handle the difference between the
  1426. variables in $R_1$ versus the registers and stack locations in x86,
  1427. we map each variable to a register or stack location.
  1428. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1429. by renaming every variable to a unique name, so that shadowing no
  1430. longer occurs.
  1431. \end{description}
  1432. The next question is: in what order should we apply these passes? This
  1433. question can be challenging because it is difficult to know ahead of
  1434. time which orders will be better (easier to implement, produce more
  1435. efficient code, etc.) so oftentimes trial-and-error is
  1436. involved. Nevertheless, we can try to plan ahead and make educated
  1437. choices regarding the ordering.
  1438. Let us consider the ordering of \key{uniquify} and
  1439. \key{remove-complex-opera*}. The assignment of subexpressions to
  1440. temporary variables involves introducing new variables and moving
  1441. subexpressions, which might change the shadowing of variables and
  1442. inadvertently change the behavior of the program. But if we apply
  1443. \key{uniquify} first, this will not be an issue. Of course, this means
  1444. that in \key{remove-complex-opera*}, we need to ensure that the
  1445. temporary variables that it creates are unique.
  1446. What should be the ordering of \key{explicate-control} with respect to
  1447. \key{uniquify}? The \key{uniquify} pass should come first because
  1448. \key{explicate-control} changes all the \key{let}-bound variables to
  1449. become local variables whose scope is the entire program, which would
  1450. confuse variables with the same name.
  1451. %
  1452. Likewise, we place \key{explicate-control} after
  1453. \key{remove-complex-opera*} because \key{explicate-control} removes
  1454. the \key{let} form, but it is convenient to use \key{let} in the
  1455. output of \key{remove-complex-opera*}.
  1456. %
  1457. Regarding \key{assign-homes}, it is helpful to place
  1458. \key{explicate-control} first because \key{explicate-control} changes
  1459. \key{let}-bound variables into program-scope variables. This means
  1460. that the \key{assign-homes} pass can read off the variables from the
  1461. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1462. entire program in search of \key{let}-bound variables.
  1463. Last, we need to decide on the ordering of \key{select-instructions}
  1464. and \key{assign-homes}. These two passes are intertwined, creating a
  1465. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1466. have already determined which instructions will be used, because x86
  1467. instructions have restrictions about which of their arguments can be
  1468. registers versus stack locations. One might want to give preferential
  1469. treatment to variables that occur in register-argument positions. On
  1470. the other hand, it may turn out to be impossible to make sure that all
  1471. such variables are assigned to registers, and then one must redo the
  1472. selection of instructions. Some compilers handle this problem by
  1473. iteratively repeating these two passes until a good solution is found.
  1474. We shall use a simpler approach in which \key{select-instructions}
  1475. comes first, followed by the \key{assign-homes}, then a third
  1476. pass named \key{patch-instructions} that uses a reserved register to
  1477. patch-up outstanding problems regarding instructions with too many
  1478. memory accesses. The disadvantage of this approach is some programs
  1479. may not execute as efficiently as they would if we used the iterative
  1480. approach and used all of the registers for variables.
  1481. \begin{figure}[tbp]
  1482. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1483. \node (R1) at (0,2) {\large $R_1$};
  1484. \node (R1-2) at (3,2) {\large $R_1$};
  1485. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1486. %\node (C0-1) at (6,0) {\large $C_0$};
  1487. \node (C0-2) at (3,0) {\large $C_0$};
  1488. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1489. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1490. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1491. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1492. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1493. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1494. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1495. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1496. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1497. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1498. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1499. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1500. \end{tikzpicture}
  1501. \caption{Overview of the passes for compiling $R_1$. }
  1502. \label{fig:R1-passes}
  1503. \end{figure}
  1504. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1505. passes in the form of a graph. Each pass is an edge and the
  1506. input/output language of each pass is a node in the graph. The output
  1507. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1508. are still in the $R_1$ language, but the output of the pass
  1509. \key{explicate-control} is in a different language $C_0$ that is
  1510. designed to make the order of evaluation explicit in its syntax, which
  1511. we introduce in the next section. The \key{select-instruction} pass
  1512. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1513. \key{patch-instructions} passes input and output variants of x86
  1514. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1515. \key{print-x86}, which converts from the abstract syntax of
  1516. $\text{x86}_0$ to the concrete syntax of x86.
  1517. In the next sections we discuss the $C_0$ language and the
  1518. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1519. remainder of this chapter gives hints regarding the implementation of
  1520. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1521. \subsection{The $C_0$ Intermediate Language}
  1522. The output of \key{explicate-control} is similar to the $C$
  1523. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1524. categories for expressions and statements, so we name it $C_0$. The
  1525. concrete syntax for $C_0$ is defined in
  1526. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1527. is defined in Figure~\ref{fig:c0-syntax}.
  1528. %
  1529. The $C_0$ language supports the same operators as $R_1$ but the
  1530. arguments of operators are restricted to atomic expressions (variables
  1531. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1532. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1533. executed in sequence using the \key{Seq} form. A sequence of
  1534. statements always ends with \key{Return}, a guarantee that is baked
  1535. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1536. this non-terminal comes from the term \emph{tail position}, which
  1537. refers to an expression that is the last one to execute within a
  1538. function. (A expression in tail position may contain subexpressions,
  1539. and those may or may not be in tail position depending on the kind of
  1540. expression.)
  1541. A $C_0$ program consists of a control-flow graph (represented as an
  1542. alist mapping labels to tails). This is more general than
  1543. necessary for the present chapter, as we do not yet need to introduce
  1544. \key{goto} for jumping to labels, but it saves us from having to
  1545. change the syntax of the program construct in
  1546. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1547. \key{start}, and the whole program is its tail.
  1548. %
  1549. The $\itm{info}$ field of the \key{Program} form, after the
  1550. \key{explicate-control} pass, contains a mapping from the symbol
  1551. \key{locals} to a list of variables, that is, a list of all the
  1552. variables used in the program. At the start of the program, these
  1553. variables are uninitialized; they become initialized on their first
  1554. assignment.
  1555. \begin{figure}[tbp]
  1556. \fbox{
  1557. \begin{minipage}{0.96\textwidth}
  1558. \[
  1559. \begin{array}{lcl}
  1560. \Atm &::=& \Int \mid \Var \\
  1561. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1562. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1563. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1564. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1565. \end{array}
  1566. \]
  1567. \end{minipage}
  1568. }
  1569. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1570. \label{fig:c0-concrete-syntax}
  1571. \end{figure}
  1572. \begin{figure}[tbp]
  1573. \fbox{
  1574. \begin{minipage}{0.96\textwidth}
  1575. \[
  1576. \begin{array}{lcl}
  1577. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1578. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1579. &\mid& \ADD{\Atm}{\Atm}\\
  1580. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1581. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1582. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1583. \end{array}
  1584. \]
  1585. \end{minipage}
  1586. }
  1587. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1588. \label{fig:c0-syntax}
  1589. \end{figure}
  1590. %% The \key{select-instructions} pass is optimistic in the sense that it
  1591. %% treats variables as if they were all mapped to registers. The
  1592. %% \key{select-instructions} pass generates a program that consists of
  1593. %% x86 instructions but that still uses variables, so it is an
  1594. %% intermediate language that is technically different than x86, which
  1595. %% explains the asterisks in the diagram above.
  1596. %% In this Chapter we shall take the easy road to implementing
  1597. %% \key{assign-homes} and simply map all variables to stack locations.
  1598. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1599. %% smarter approach in which we make a best-effort to map variables to
  1600. %% registers, resorting to the stack only when necessary.
  1601. %% Once variables have been assigned to their homes, we can finalize the
  1602. %% instruction selection by dealing with an idiosyncrasy of x86
  1603. %% assembly. Many x86 instructions have two arguments but only one of the
  1604. %% arguments may be a memory reference (and the stack is a part of
  1605. %% memory). Because some variables may get mapped to stack locations,
  1606. %% some of our generated instructions may violate this restriction. The
  1607. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1608. %% replacing every violating instruction with a short sequence of
  1609. %% instructions that use the \key{rax} register. Once we have implemented
  1610. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1611. %% need to patch instructions will be relatively rare.
  1612. \subsection{The dialects of x86}
  1613. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1614. the pass \key{select-instructions}. It extends x86$_0$ with an
  1615. unbounded number of program-scope variables and has looser rules
  1616. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1617. output of \key{print-x86}, is the concrete syntax for x86.
  1618. \section{Uniquify Variables}
  1619. \label{sec:uniquify-s0}
  1620. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1621. programs in which every \key{let} uses a unique variable name. For
  1622. example, the \code{uniquify} pass should translate the program on the
  1623. left into the program on the right. \\
  1624. \begin{tabular}{lll}
  1625. \begin{minipage}{0.4\textwidth}
  1626. \begin{lstlisting}
  1627. (let ([x 32])
  1628. (+ (let ([x 10]) x) x))
  1629. \end{lstlisting}
  1630. \end{minipage}
  1631. &
  1632. $\Rightarrow$
  1633. &
  1634. \begin{minipage}{0.4\textwidth}
  1635. \begin{lstlisting}
  1636. (let ([x.1 32])
  1637. (+ (let ([x.2 10]) x.2) x.1))
  1638. \end{lstlisting}
  1639. \end{minipage}
  1640. \end{tabular} \\
  1641. %
  1642. The following is another example translation, this time of a program
  1643. with a \key{let} nested inside the initializing expression of another
  1644. \key{let}.\\
  1645. \begin{tabular}{lll}
  1646. \begin{minipage}{0.4\textwidth}
  1647. \begin{lstlisting}
  1648. (let ([x (let ([x 4])
  1649. (+ x 1))])
  1650. (+ x 2))
  1651. \end{lstlisting}
  1652. \end{minipage}
  1653. &
  1654. $\Rightarrow$
  1655. &
  1656. \begin{minipage}{0.4\textwidth}
  1657. \begin{lstlisting}
  1658. (let ([x.2 (let ([x.1 4])
  1659. (+ x.1 1))])
  1660. (+ x.2 2))
  1661. \end{lstlisting}
  1662. \end{minipage}
  1663. \end{tabular}
  1664. We recommend implementing \code{uniquify} by creating a function named
  1665. \code{uniquify-exp} that is structurally recursive function and mostly
  1666. just copies the input program. However, when encountering a \key{let},
  1667. it should generate a unique name for the variable (the Racket function
  1668. \code{gensym} is handy for this) and associate the old name with the
  1669. new unique name in an alist. The \code{uniquify-exp}
  1670. function will need to access this alist when it gets to a
  1671. variable reference, so we add another parameter to \code{uniquify-exp}
  1672. for the alist.
  1673. The skeleton of the \code{uniquify-exp} function is shown in
  1674. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1675. convenient to partially apply it to a symbol table and then apply it
  1676. to different expressions, as in the last clause for primitive
  1677. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1678. is useful for applying a function to each element of a list to produce
  1679. a new list.
  1680. \begin{exercise}
  1681. \normalfont % I don't like the italics for exercises. -Jeremy
  1682. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1683. implement the clauses for variables and for the \key{let} form.
  1684. \end{exercise}
  1685. \begin{figure}[tbp]
  1686. \begin{lstlisting}
  1687. (define (uniquify-exp symtab)
  1688. (lambda (e)
  1689. (match e
  1690. [(Var x) ___]
  1691. [(Int n) (Int n)]
  1692. [(Let x e body) ___]
  1693. [(Prim op es)
  1694. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1695. )))
  1696. (define (uniquify p)
  1697. (match p
  1698. [(Program '() e)
  1699. (Program '() ((uniquify-exp '()) e))]
  1700. )))
  1701. \end{lstlisting}
  1702. \caption{Skeleton for the \key{uniquify} pass.}
  1703. \label{fig:uniquify-s0}
  1704. \end{figure}
  1705. \begin{exercise}
  1706. \normalfont % I don't like the italics for exercises. -Jeremy
  1707. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1708. and checking whether the output programs produce the same result as
  1709. the input programs. The $R_1$ programs should be designed to test the
  1710. most interesting parts of the \key{uniquify} pass, that is, the
  1711. programs should include \key{let} forms, variables, and variables
  1712. that overshadow each other. The five programs should be in a
  1713. subdirectory named \key{tests} and they should have the same file name
  1714. except for a different integer at the end of the name, followed by the
  1715. ending \key{.rkt}. Use the \key{interp-tests} function
  1716. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1717. your \key{uniquify} pass on the example programs. See the
  1718. \key{run-tests.rkt} script in the student support code for an example
  1719. of how to use \key{interp-tests}.
  1720. \end{exercise}
  1721. \section{Remove Complex Operands}
  1722. \label{sec:remove-complex-opera-R1}
  1723. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1724. $R_1$ programs in which the arguments of operations are atomic
  1725. expressions. Put another way, this pass removes complex operands,
  1726. such as the expression \code{(- 10)} in the program below. This is
  1727. accomplished by introducing a new \key{let}-bound variable, binding
  1728. the complex operand to the new variable, and then using the new
  1729. variable in place of the complex operand, as shown in the output of
  1730. \code{remove-complex-opera*} on the right.\\
  1731. \begin{tabular}{lll}
  1732. \begin{minipage}{0.4\textwidth}
  1733. % s0_19.rkt
  1734. \begin{lstlisting}
  1735. (+ 52 (- 10))
  1736. \end{lstlisting}
  1737. \end{minipage}
  1738. &
  1739. $\Rightarrow$
  1740. &
  1741. \begin{minipage}{0.4\textwidth}
  1742. \begin{lstlisting}
  1743. (let ([tmp.1 (- 10)])
  1744. (+ 52 tmp.1))
  1745. \end{lstlisting}
  1746. \end{minipage}
  1747. \end{tabular}
  1748. \begin{figure}[tp]
  1749. \centering
  1750. \fbox{
  1751. \begin{minipage}{0.96\textwidth}
  1752. \[
  1753. \begin{array}{rcl}
  1754. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1755. \Exp &::=& \Atm \mid \READ{} \\
  1756. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1757. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1758. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1759. \end{array}
  1760. \]
  1761. \end{minipage}
  1762. }
  1763. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1764. \label{fig:r1-anf-syntax}
  1765. \end{figure}
  1766. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1767. this pass, language $R_1^{\dagger}$. The main difference is that
  1768. operator arguments are required to be atomic expressions. In the
  1769. literature this is called \emph{administrative normal form}, or ANF
  1770. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1771. We recommend implementing this pass with two mutually recursive
  1772. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1773. \code{rco-atom} to subexpressions that are required to be atomic and
  1774. to apply \code{rco-exp} to subexpressions that can be atomic or
  1775. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1776. $R_1$ expression as input. The \code{rco-exp} function returns an
  1777. expression. The \code{rco-atom} function returns two things: an
  1778. atomic expression and alist mapping temporary variables to complex
  1779. subexpressions. You can return multiple things from a function using
  1780. Racket's \key{values} form and you can receive multiple things from a
  1781. function call using the \key{define-values} form. If you are not
  1782. familiar with these features, review the Racket documentation. Also,
  1783. the \key{for/lists} form is useful for applying a function to each
  1784. element of a list, in the case where the function returns multiple
  1785. values.
  1786. The following shows the output of \code{rco-atom} on the expression
  1787. \code{(- 10)} (using concrete syntax to be concise).
  1788. \begin{tabular}{lll}
  1789. \begin{minipage}{0.4\textwidth}
  1790. \begin{lstlisting}
  1791. (- 10)
  1792. \end{lstlisting}
  1793. \end{minipage}
  1794. &
  1795. $\Rightarrow$
  1796. &
  1797. \begin{minipage}{0.4\textwidth}
  1798. \begin{lstlisting}
  1799. tmp.1
  1800. ((tmp.1 . (- 10)))
  1801. \end{lstlisting}
  1802. \end{minipage}
  1803. \end{tabular}
  1804. Take special care of programs such as the next one that \key{let}-bind
  1805. variables with integers or other variables. You should leave them
  1806. unchanged, as shown in to the program on the right \\
  1807. \begin{tabular}{lll}
  1808. \begin{minipage}{0.4\textwidth}
  1809. % s0_20.rkt
  1810. \begin{lstlisting}
  1811. (let ([a 42])
  1812. (let ([b a])
  1813. b))
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. &
  1817. $\Rightarrow$
  1818. &
  1819. \begin{minipage}{0.4\textwidth}
  1820. \begin{lstlisting}
  1821. (let ([a 42])
  1822. (let ([b a])
  1823. b))
  1824. \end{lstlisting}
  1825. \end{minipage}
  1826. \end{tabular} \\
  1827. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1828. produce the following output.\\
  1829. \begin{minipage}{0.4\textwidth}
  1830. \begin{lstlisting}
  1831. (let ([tmp.1 42])
  1832. (let ([a tmp.1])
  1833. (let ([tmp.2 a])
  1834. (let ([b tmp.2])
  1835. b))))
  1836. \end{lstlisting}
  1837. \end{minipage}
  1838. \begin{exercise}
  1839. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1840. it on all of the example programs that you created to test the
  1841. \key{uniquify} pass and create three new example programs that are
  1842. designed to exercise the interesting code in the
  1843. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1844. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1845. your passes on the example programs.
  1846. \end{exercise}
  1847. \section{Explicate Control}
  1848. \label{sec:explicate-control-r1}
  1849. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1850. programs that make the order of execution explicit in their
  1851. syntax. For now this amounts to flattening \key{let} constructs into a
  1852. sequence of assignment statements. For example, consider the following
  1853. $R_1$ program.\\
  1854. % s0_11.rkt
  1855. \begin{minipage}{0.96\textwidth}
  1856. \begin{lstlisting}
  1857. (let ([y (let ([x 20])
  1858. (+ x (let ([x 22]) x)))])
  1859. y)
  1860. \end{lstlisting}
  1861. \end{minipage}\\
  1862. %
  1863. The output of the previous pass and of \code{explicate-control} is
  1864. shown below. Recall that the right-hand-side of a \key{let} executes
  1865. before its body, so the order of evaluation for this program is to
  1866. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1867. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1868. output of \code{explicate-control} makes this ordering explicit.\\
  1869. \begin{tabular}{lll}
  1870. \begin{minipage}{0.4\textwidth}
  1871. \begin{lstlisting}
  1872. (let ([y (let ([x.1 20])
  1873. (let ([x.2 22])
  1874. (+ x.1 x.2)))])
  1875. y)
  1876. \end{lstlisting}
  1877. \end{minipage}
  1878. &
  1879. $\Rightarrow$
  1880. &
  1881. \begin{minipage}{0.4\textwidth}
  1882. \begin{lstlisting}
  1883. locals: y x.1 x.2
  1884. start:
  1885. x.1 = 20;
  1886. x.2 = 22;
  1887. y = (+ x.1 x.2);
  1888. return y;
  1889. \end{lstlisting}
  1890. \end{minipage}
  1891. \end{tabular}
  1892. We recommend implementing \code{explicate-control} using two mutually
  1893. recursive functions: \code{explicate-tail} and
  1894. \code{explicate-assign}. The first function should be applied to
  1895. expressions in tail position whereas the second should be applied to
  1896. expressions that occur on the right-hand-side of a \key{let}. The
  1897. \code{explicate-tail} function takes an $R_1$ expression as input and
  1898. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1899. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1900. function takes an $R_1$ expression, the variable that it is to be
  1901. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1902. assignment (e.g., the code generated for the body of the \key{let}).
  1903. It returns a $\Tail$ and a list of variables. The top-level
  1904. \code{explicate-control} function should invoke \code{explicate-tail}
  1905. on the body of the \key{program} and then associate the \code{locals}
  1906. symbol with the resulting list of variables in the $\itm{info}$ field,
  1907. as in the above example.
  1908. \section{Select Instructions}
  1909. \label{sec:select-r1}
  1910. In the \code{select-instructions} pass we begin the work of
  1911. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1912. this pass is a variant of x86 that still uses variables, so we add an
  1913. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1914. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1915. \code{select-instructions} in terms of three auxiliary functions, one
  1916. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1917. The cases for $\Atm$ are straightforward, variables stay
  1918. the same and integer constants are changed to immediates:
  1919. $\INT{n}$ changes to $\IMM{n}$.
  1920. Next we consider the cases for $\Stmt$, starting with arithmetic
  1921. operations. For example, in $C_0$ an addition operation can take the
  1922. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1923. need to use the \key{addq} instruction which does an in-place
  1924. update. So we must first move \code{10} to \code{x}. \\
  1925. \begin{tabular}{lll}
  1926. \begin{minipage}{0.4\textwidth}
  1927. \begin{lstlisting}
  1928. x = (+ 10 32);
  1929. \end{lstlisting}
  1930. \end{minipage}
  1931. &
  1932. $\Rightarrow$
  1933. &
  1934. \begin{minipage}{0.4\textwidth}
  1935. \begin{lstlisting}
  1936. movq $10, x
  1937. addq $32, x
  1938. \end{lstlisting}
  1939. \end{minipage}
  1940. \end{tabular} \\
  1941. %
  1942. There are cases that require special care to avoid generating
  1943. needlessly complicated code. If one of the arguments of the addition
  1944. is the same as the left-hand side of the assignment, then there is no
  1945. need for the extra move instruction. For example, the following
  1946. assignment statement can be translated into a single \key{addq}
  1947. instruction.\\
  1948. \begin{tabular}{lll}
  1949. \begin{minipage}{0.4\textwidth}
  1950. \begin{lstlisting}
  1951. x = (+ 10 x);
  1952. \end{lstlisting}
  1953. \end{minipage}
  1954. &
  1955. $\Rightarrow$
  1956. &
  1957. \begin{minipage}{0.4\textwidth}
  1958. \begin{lstlisting}
  1959. addq $10, x
  1960. \end{lstlisting}
  1961. \end{minipage}
  1962. \end{tabular} \\
  1963. The \key{read} operation does not have a direct counterpart in x86
  1964. assembly, so we have instead implemented this functionality in the C
  1965. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  1966. in the file \code{runtime.c}. In general, we refer to all of the
  1967. functionality in this file as the \emph{runtime system}, or simply the
  1968. \emph{runtime} for short. When compiling your generated x86 assembly
  1969. code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  1970. ``object file'', using \code{gcc} option \code{-c}) and link it into
  1971. the executable. For our purposes of code generation, all you need to
  1972. do is translate an assignment of \key{read} into some variable
  1973. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  1974. function followed by a move from \code{rax} to the left-hand side.
  1975. The move from \code{rax} is needed because the return value from
  1976. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1977. \begin{tabular}{lll}
  1978. \begin{minipage}{0.3\textwidth}
  1979. \begin{lstlisting}
  1980. |$\itm{var}$| = (read);
  1981. \end{lstlisting}
  1982. \end{minipage}
  1983. &
  1984. $\Rightarrow$
  1985. &
  1986. \begin{minipage}{0.3\textwidth}
  1987. \begin{lstlisting}
  1988. callq read_int
  1989. movq %rax, |$\itm{var}$|
  1990. \end{lstlisting}
  1991. \end{minipage}
  1992. \end{tabular} \\
  1993. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1994. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1995. assignment to the \key{rax} register followed by a jump to the
  1996. conclusion of the program (so the conclusion needs to be labeled).
  1997. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1998. recursively and append the resulting instructions.
  1999. \begin{exercise}
  2000. \normalfont
  2001. Implement the \key{select-instructions} pass and test it on all of the
  2002. example programs that you created for the previous passes and create
  2003. three new example programs that are designed to exercise all of the
  2004. interesting code in this pass. Use the \key{interp-tests} function
  2005. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2006. your passes on the example programs.
  2007. \end{exercise}
  2008. \section{Assign Homes}
  2009. \label{sec:assign-r1}
  2010. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2011. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2012. Thus, the \key{assign-homes} pass is responsible for placing all of
  2013. the program variables in registers or on the stack. For runtime
  2014. efficiency, it is better to place variables in registers, but as there
  2015. are only 16 registers, some programs must necessarily resort to
  2016. placing some variables on the stack. In this chapter we focus on the
  2017. mechanics of placing variables on the stack. We study an algorithm for
  2018. placing variables in registers in
  2019. Chapter~\ref{ch:register-allocation-r1}.
  2020. Consider again the following $R_1$ program.
  2021. % s0_20.rkt
  2022. \begin{lstlisting}
  2023. (let ([a 42])
  2024. (let ([b a])
  2025. b))
  2026. \end{lstlisting}
  2027. For reference, we repeat the output of \code{select-instructions} on
  2028. the left and show the output of \code{assign-homes} on the right.
  2029. Recall that \key{explicate-control} associated the list of
  2030. variables with the \code{locals} symbol in the program's $\itm{info}$
  2031. field, so \code{assign-homes} has convenient access to the them. In
  2032. this example, we assign variable \code{a} to stack location
  2033. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2034. \begin{tabular}{l}
  2035. \begin{minipage}{0.4\textwidth}
  2036. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2037. locals: a b
  2038. start:
  2039. movq $42, a
  2040. movq a, b
  2041. movq b, %rax
  2042. jmp conclusion
  2043. \end{lstlisting}
  2044. \end{minipage}
  2045. {$\Rightarrow$}
  2046. \begin{minipage}{0.4\textwidth}
  2047. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2048. stack-space: 16
  2049. start:
  2050. movq $42, -8(%rbp)
  2051. movq -8(%rbp), -16(%rbp)
  2052. movq -16(%rbp), %rax
  2053. jmp conclusion
  2054. \end{lstlisting}
  2055. \end{minipage}
  2056. \end{tabular} \\
  2057. In the process of assigning variables to stack locations, it is
  2058. convenient to compute and store the size of the frame (in bytes) in
  2059. the $\itm{info}$ field of the \key{Program} node, with the key
  2060. \code{stack-space}, which will be needed later to generate the
  2061. procedure conclusion. Some operating systems place restrictions on
  2062. the frame size. For example, Mac OS X requires the frame size to be a
  2063. multiple of 16 bytes.
  2064. \begin{exercise}
  2065. \normalfont Implement the \key{assign-homes} pass and test it on all
  2066. of the example programs that you created for the previous passes pass.
  2067. We recommend that \key{assign-homes} take an extra parameter that is a
  2068. mapping of variable names to homes (stack locations for now). Use the
  2069. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2070. \key{utilities.rkt} to test your passes on the example programs.
  2071. \end{exercise}
  2072. \section{Patch Instructions}
  2073. \label{sec:patch-s0}
  2074. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2075. programs to $\text{x86}_0$ programs by making sure that each
  2076. instruction adheres to the restrictions of the x86 assembly language.
  2077. In particular, at most one argument of an instruction may be a memory
  2078. reference.
  2079. We return to the following running example.
  2080. % s0_20.rkt
  2081. \begin{lstlisting}
  2082. (let ([a 42])
  2083. (let ([b a])
  2084. b))
  2085. \end{lstlisting}
  2086. After the \key{assign-homes} pass, the above program has been translated to
  2087. the following. \\
  2088. \begin{minipage}{0.5\textwidth}
  2089. \begin{lstlisting}
  2090. stack-space: 16
  2091. start:
  2092. movq $42, -8(%rbp)
  2093. movq -8(%rbp), -16(%rbp)
  2094. movq -16(%rbp), %rax
  2095. jmp conclusion
  2096. \end{lstlisting}
  2097. \end{minipage}\\
  2098. The second \key{movq} instruction is problematic because both
  2099. arguments are stack locations. We suggest fixing this problem by
  2100. moving from the source location to the register \key{rax} and then
  2101. from \key{rax} to the destination location, as follows.
  2102. \begin{lstlisting}
  2103. movq -8(%rbp), %rax
  2104. movq %rax, -16(%rbp)
  2105. \end{lstlisting}
  2106. \begin{exercise}
  2107. \normalfont
  2108. Implement the \key{patch-instructions} pass and test it on all of the
  2109. example programs that you created for the previous passes and create
  2110. three new example programs that are designed to exercise all of the
  2111. interesting code in this pass. Use the \key{interp-tests} function
  2112. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2113. your passes on the example programs.
  2114. \end{exercise}
  2115. \section{Print x86}
  2116. \label{sec:print-x86}
  2117. The last step of the compiler from $R_1$ to x86 is to convert the
  2118. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2119. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2120. \key{format} and \key{string-append} functions are useful in this
  2121. regard. The main work that this step needs to perform is to create the
  2122. \key{main} function and the standard instructions for its prelude and
  2123. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2124. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2125. variables, so we suggest computing it in the \key{assign-homes} pass
  2126. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2127. of the \key{program} node.
  2128. %% Your compiled code should print the result of the program's execution
  2129. %% by using the \code{print\_int} function provided in
  2130. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2131. %% far, this final result should be stored in the \key{rax} register.
  2132. %% We'll talk more about how to perform function calls with arguments in
  2133. %% general later on, but for now, place the following after the compiled
  2134. %% code for the $R_1$ program but before the conclusion:
  2135. %% \begin{lstlisting}
  2136. %% movq %rax, %rdi
  2137. %% callq print_int
  2138. %% \end{lstlisting}
  2139. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2140. %% stores the first argument to be passed into \key{print\_int}.
  2141. If you want your program to run on Mac OS X, your code needs to
  2142. determine whether or not it is running on a Mac, and prefix
  2143. underscores to labels like \key{main}. You can determine the platform
  2144. with the Racket call \code{(system-type 'os)}, which returns
  2145. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2146. %% In addition to
  2147. %% placing underscores on \key{main}, you need to put them in front of
  2148. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2149. %% \_print\_int}).
  2150. \begin{exercise}
  2151. \normalfont Implement the \key{print-x86} pass and test it on all of
  2152. the example programs that you created for the previous passes. Use the
  2153. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2154. \key{utilities.rkt} to test your complete compiler on the example
  2155. programs. See the \key{run-tests.rkt} script in the student support
  2156. code for an example of how to use \key{compiler-tests}. Also, remember
  2157. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2158. \key{gcc}.
  2159. \end{exercise}
  2160. \section{Challenge: Partial Evaluator for $R_1$}
  2161. \label{sec:pe-R1}
  2162. This section describes optional challenge exercises that involve
  2163. adapting and improving the partial evaluator for $R_0$ that was
  2164. introduced in Section~\ref{sec:partial-evaluation}.
  2165. \begin{exercise}\label{ex:pe-R1}
  2166. \normalfont
  2167. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2168. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2169. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2170. and variables to the $R_0$ language, so you will need to add cases for
  2171. them in the \code{pe-exp} function. Also, note that the \key{program}
  2172. form changes slightly to include an $\itm{info}$ field. Once
  2173. complete, add the partial evaluation pass to the front of your
  2174. compiler and make sure that your compiler still passes all of the
  2175. tests.
  2176. \end{exercise}
  2177. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2178. \begin{exercise}
  2179. \normalfont
  2180. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2181. \code{pe-add} auxiliary functions with functions that know more about
  2182. arithmetic. For example, your partial evaluator should translate
  2183. \begin{lstlisting}
  2184. (+ 1 (+ (read) 1))
  2185. \end{lstlisting}
  2186. into
  2187. \begin{lstlisting}
  2188. (+ 2 (read))
  2189. \end{lstlisting}
  2190. To accomplish this, the \code{pe-exp} function should produce output
  2191. in the form of the $\itm{residual}$ non-terminal of the following
  2192. grammar.
  2193. \[
  2194. \begin{array}{lcl}
  2195. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2196. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2197. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2198. \end{array}
  2199. \]
  2200. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2201. that their inputs are $\itm{residual}$ expressions and they should
  2202. return $\itm{residual}$ expressions. Once the improvements are
  2203. complete, make sure that your compiler still passes all of the tests.
  2204. After all, fast code is useless if it produces incorrect results!
  2205. \end{exercise}
  2206. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2207. \chapter{Register Allocation}
  2208. \label{ch:register-allocation-r1}
  2209. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2210. make our life easier. However, we can improve the performance of the
  2211. generated code if we instead place some variables into registers. The
  2212. CPU can access a register in a single cycle, whereas accessing the
  2213. stack takes many cycles if the relevant data is in cache or many more
  2214. to access main memory if the data is not in cache.
  2215. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2216. serves as a running example. We show the source program and also the
  2217. output of instruction selection. At that point the program is almost
  2218. x86 assembly but not quite; it still contains variables instead of
  2219. stack locations or registers.
  2220. \begin{figure}
  2221. \begin{minipage}{0.45\textwidth}
  2222. Example $R_1$ program:
  2223. % s0_28.rkt
  2224. \begin{lstlisting}
  2225. (let ([v 1])
  2226. (let ([w 42])
  2227. (let ([x (+ v 7)])
  2228. (let ([y x])
  2229. (let ([z (+ x w)])
  2230. (+ z (- y)))))))
  2231. \end{lstlisting}
  2232. \end{minipage}
  2233. \begin{minipage}{0.45\textwidth}
  2234. After instruction selection:
  2235. \begin{lstlisting}
  2236. locals: (v w x y z t)
  2237. start:
  2238. movq $1, v
  2239. movq $42, w
  2240. movq v, x
  2241. addq $7, x
  2242. movq x, y
  2243. movq x, z
  2244. addq w, z
  2245. movq y, t
  2246. negq t
  2247. movq z, %rax
  2248. addq t, %rax
  2249. jmp conclusion
  2250. \end{lstlisting}
  2251. \end{minipage}
  2252. \caption{An example program for register allocation.}
  2253. \label{fig:reg-eg}
  2254. \end{figure}
  2255. The goal of register allocation is to fit as many variables into
  2256. registers as possible. A program sometimes has more variables than
  2257. registers, so we cannot map each variable to a different
  2258. register. Fortunately, it is common for different variables to be
  2259. needed during different periods of time during program execution, and
  2260. in such cases several variables can be mapped to the same register.
  2261. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2262. After the variable \code{x} is moved to \code{z} it is no longer
  2263. needed. Variable \code{y}, on the other hand, is used only after this
  2264. point, so \code{x} and \code{y} could share the same register. The
  2265. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2266. where a variable is needed. Once we have that information, we compute
  2267. which variables are needed at the same time, i.e., which ones
  2268. \emph{interfere} with each other, and represent this relation as an
  2269. undirected graph whose vertices are variables and edges indicate when
  2270. two variables interfere (Section~\ref{sec:build-interference}). We
  2271. then model register allocation as a graph coloring problem, which we
  2272. discuss in Section~\ref{sec:graph-coloring}.
  2273. In the event that we run out of registers despite these efforts, we
  2274. place the remaining variables on the stack, similar to what we did in
  2275. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2276. for assigning a variable to a stack location. The process of spilling
  2277. variables is handled as part of the graph coloring process described
  2278. in \ref{sec:graph-coloring}.
  2279. We make the simplifying assumption that each variable is assigned to
  2280. one location (a register or stack address). A more sophisticated
  2281. approach is to assign a variable to one or more locations in different
  2282. regions of the program. For example, if a variable is used many times
  2283. in short sequence and then only used again after many other
  2284. instructions, it could be more efficient to assign the variable to a
  2285. register during the intial sequence and then move it to the stack for
  2286. the rest of its lifetime. We refer the interested reader to
  2287. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2288. about this approach.
  2289. % discuss prioritizing variables based on how much they are used.
  2290. \section{Registers and Calling Conventions}
  2291. \label{sec:calling-conventions}
  2292. As we perform register allocation, we need to be aware of the
  2293. conventions that govern the way in which registers interact with
  2294. function calls, such as calls to the \code{read\_int} function in our
  2295. generated code and even the call that the operating system makes to
  2296. execute our \code{main} function. The convention for x86 is that the
  2297. caller is responsible for freeing up some registers, the
  2298. \emph{caller-saved registers}, prior to the function call, and the
  2299. callee is responsible for preserving the values in some other
  2300. registers, the \emph{callee-saved registers}. The caller-saved
  2301. registers are
  2302. \begin{lstlisting}
  2303. rax rcx rdx rsi rdi r8 r9 r10 r11
  2304. \end{lstlisting}
  2305. while the callee-saved registers are
  2306. \begin{lstlisting}
  2307. rsp rbp rbx r12 r13 r14 r15
  2308. \end{lstlisting}
  2309. We can think about this caller/callee convention from two points of
  2310. view, the caller view and the callee view:
  2311. \begin{itemize}
  2312. \item The caller should assume that all the caller-saved registers get
  2313. overwritten with arbitrary values by the callee. On the other hand,
  2314. the caller can safely assume that all the callee-saved registers
  2315. contain the same values after the call that they did before the
  2316. call.
  2317. \item The callee can freely use any of the caller-saved registers.
  2318. However, if the callee wants to use a callee-saved register, the
  2319. callee must arrange to put the original value back in the register
  2320. prior to returning to the caller, which is usually accomplished by
  2321. saving the value to the stack in the prelude of the function and
  2322. restoring the value in the conclusion of the function.
  2323. \end{itemize}
  2324. The next question is how these calling conventions impact register
  2325. allocation. Consider the $R_1$ program in
  2326. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2327. example from the caller point of view and then from the callee point
  2328. of view.
  2329. The program makes two calls to the \code{read} function. Also, the
  2330. variable \code{x} is in-use during the second call to \code{read}, so
  2331. we need to make sure that the value in \code{x} does not get
  2332. accidentally wiped out by the call to \code{read}. One obvious
  2333. approach is to save all the values in caller-saved registers to the
  2334. stack prior to each function call, and restore them after each
  2335. call. That way, if the register allocator chooses to assign \code{x}
  2336. to a caller-saved register, its value will be preserved accross the
  2337. call to \code{read}. However, the disadvantage of this approach is
  2338. that saving and restoring to the stack is relatively slow. If \code{x}
  2339. is not used many times, it may be better to assign \code{x} to a stack
  2340. location in the first place. Or better yet, if we can arrange for
  2341. \code{x} to be placed in a callee-saved register, then it won't need
  2342. to be saved and restored during function calls.
  2343. The approach that we recommend is to treat variables differently
  2344. depending on whether they are in-use during a function call. If a
  2345. variable is in-use during a function call, then we never assign it to
  2346. a caller-saved register: we either assign it to a callee-saved
  2347. register or we spill it to the stack. If a variable is not in-use
  2348. during any function call, then we try the following alternatives in
  2349. order 1) look for an available caller-saved register (to leave room
  2350. for other variables in the callee-saved register), 2) look for a
  2351. callee-saved register, and 3) spill the variable to the stack.
  2352. It is straightforward to implement this approach in a graph coloring
  2353. register allocator. First, we know which variables are in-use during
  2354. every function call because we compute that information for every
  2355. instruciton (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2356. build the interference graph (Section~\ref{sec:build-interference}),
  2357. we can place an edge between each of these variables and the
  2358. caller-saved registers in the interference graph. This will prevent
  2359. the graph coloring algorithm from assigning those variables to
  2360. caller-saved registers.
  2361. Returning to the example in
  2362. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2363. generated x86 code on the right-hand side, focusing on the
  2364. \code{start} block. Notice that variable \code{x} is assigned to
  2365. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2366. place during the second call to \code{read\_int}. Next, notice that
  2367. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2368. because there are no function calls in the remainder of the block.
  2369. Next we analyze the example from the callee point of view, focusing on
  2370. the prelude and conclusion of the \code{main} function. As usual the
  2371. prelude begins with saving the \code{rbp} register to the stack and
  2372. setting the \code{rbp} to the current stack pointer. We now know why
  2373. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2374. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2375. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2376. variable (\code{x}). There are several more callee-saved register that
  2377. are not saved in the prelude because they were not assigned to
  2378. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2379. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2380. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2381. from the stack with a \code{popq} instruction.
  2382. \begin{figure}[tp]
  2383. \begin{minipage}{0.45\textwidth}
  2384. Example $R_1$ program:
  2385. %s0_14.rkt
  2386. \begin{lstlisting}
  2387. (let ([x (read)])
  2388. (let ([y (read)])
  2389. (+ (+ x y) 42)))
  2390. \end{lstlisting}
  2391. \end{minipage}
  2392. \begin{minipage}{0.45\textwidth}
  2393. Generated x86 assembly:
  2394. \begin{lstlisting}
  2395. start:
  2396. callq read_int
  2397. movq %rax, %rbx
  2398. callq read_int
  2399. movq %rax, %rcx
  2400. addq %rcx, %rbx
  2401. movq %rbx, %rax
  2402. addq $42, %rax
  2403. jmp _conclusion
  2404. .globl main
  2405. main:
  2406. pushq %rbp
  2407. movq %rsp, %rbp
  2408. pushq %rbx
  2409. subq $8, %rsp
  2410. jmp start
  2411. conclusion:
  2412. addq $8, %rsp
  2413. popq %rbx
  2414. popq %rbp
  2415. retq
  2416. \end{lstlisting}
  2417. \end{minipage}
  2418. \caption{An example with function calls.}
  2419. \label{fig:example-calling-conventions}
  2420. \end{figure}
  2421. \section{Liveness Analysis}
  2422. \label{sec:liveness-analysis-r1}
  2423. A variable is \emph{live} if the variable is used at some later point
  2424. in the program and there is not an intervening assignment to the
  2425. variable.
  2426. %
  2427. To understand the latter condition, consider the following code
  2428. fragment in which there are two writes to \code{b}. Are \code{a} and
  2429. \code{b} both live at the same time?
  2430. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2431. movq $5, a
  2432. movq $30, b
  2433. movq a, c
  2434. movq $10, b
  2435. addq b, c
  2436. \end{lstlisting}
  2437. The answer is no because the integer \code{30} written to \code{b} on
  2438. line 2 is never used. The variable \code{b} is read on line 5 and
  2439. there is an intervening write to \code{b} on line 4, so the read on
  2440. line 5 receives the value written on line 4, not line 2.
  2441. The live variables can be computed by traversing the instruction
  2442. sequence back to front (i.e., backwards in execution order). Let
  2443. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2444. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2445. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2446. variables before instruction $I_k$. The live variables after an
  2447. instruction are always the same as the live variables before the next
  2448. instruction.
  2449. \begin{equation} \label{eq:live-after-before-next}
  2450. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2451. \end{equation}
  2452. To start things off, there are no live variables after the last
  2453. instruction, so
  2454. \begin{equation}\label{eq:live-last-empty}
  2455. L_{\mathsf{after}}(n) = \emptyset
  2456. \end{equation}
  2457. We then apply the following rule repeatedly, traversing the
  2458. instruction sequence back to front.
  2459. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2460. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2461. \end{equation}
  2462. where $W(k)$ are the variables written to by instruction $I_k$ and
  2463. $R(k)$ are the variables read by instruction $I_k$.
  2464. Let us walk through the above example, applying these formulas
  2465. starting with the instruction on line 5. We collect the answers in the
  2466. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2467. instruction is $\emptyset$ because it is the last instruction
  2468. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2469. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2470. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2471. is
  2472. \[
  2473. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2474. \]
  2475. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2476. the live-before set from line 5 to be the live-after set for this
  2477. instruction (formula~\ref{eq:live-after-before-next}).
  2478. \[
  2479. L_{\mathsf{after}}(4) = \{ b, c \}
  2480. \]
  2481. This move instruction writes to $b$ and does not read from any
  2482. variables, so we have the following live-before set
  2483. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2484. \[
  2485. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2486. \]
  2487. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2488. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2489. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2490. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2491. variable that is not live and does not read from a variable.
  2492. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2493. because it writes to variable $a$.
  2494. \begin{center}
  2495. \begin{minipage}{0.45\textwidth}
  2496. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2497. movq $5, a
  2498. movq $30, b
  2499. movq a, c
  2500. movq $10, b
  2501. addq b, c
  2502. \end{lstlisting}
  2503. \end{minipage}
  2504. \vrule\hspace{10pt}
  2505. \begin{minipage}{0.45\textwidth}
  2506. \begin{align*}
  2507. L_{\mathsf{before}}(1)= \emptyset,
  2508. L_{\mathsf{after}}(1)= \{a\}\\
  2509. L_{\mathsf{before}}(2)= \{a\},
  2510. L_{\mathsf{after}}(2)= \{a\}\\
  2511. L_{\mathsf{before}}(3)= \{a\},
  2512. L_{\mathsf{after}}(2)= \{c\}\\
  2513. L_{\mathsf{before}}(4)= \{c\},
  2514. L_{\mathsf{after}}(4)= \{b,c\}\\
  2515. L_{\mathsf{before}}(5)= \{b,c\},
  2516. L_{\mathsf{after}}(5)= \emptyset
  2517. \end{align*}
  2518. \end{minipage}
  2519. \end{center}
  2520. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2521. for the running example program, with the live-before and live-after
  2522. sets shown between each instruction to make the figure easy to read.
  2523. \begin{figure}[tp]
  2524. \hspace{20pt}
  2525. \begin{minipage}{0.45\textwidth}
  2526. \begin{lstlisting}
  2527. |$\{\}$|
  2528. movq $1, v
  2529. |$\{v\}$|
  2530. movq $42, w
  2531. |$\{v,w\}$|
  2532. movq v, x
  2533. |$\{w,x\}$|
  2534. addq $7, x
  2535. |$\{w,x\}$|
  2536. movq x, y
  2537. |$\{w,x,y\}$|
  2538. movq x, z
  2539. |$\{w,y,z\}$|
  2540. addq w, z
  2541. |$\{y,z\}$|
  2542. movq y, t
  2543. |$\{t,z\}$|
  2544. negq t
  2545. |$\{t,z\}$|
  2546. movq z, %rax
  2547. |$\{t\}$|
  2548. addq t, %rax
  2549. |$\{\}$|
  2550. jmp conclusion
  2551. |$\{\}$|
  2552. \end{lstlisting}
  2553. \end{minipage}
  2554. \caption{The running example annotated with live-after sets.}
  2555. \label{fig:live-eg}
  2556. \end{figure}
  2557. \begin{exercise}\normalfont
  2558. Implement the compiler pass named \code{uncover-live} that computes
  2559. the live-after sets. We recommend storing the live-after sets (a list
  2560. of a set of variables) in the $\itm{info}$ field of the \key{Block}
  2561. structure. We recommend using the
  2562. \href{https://docs.racket-lang.org/reference/sets.html}{\code{racket/set}}
  2563. package for representing sets of variables.
  2564. %
  2565. We recommend organizing your code to use a helper function that takes
  2566. a list of instructions and an initial live-after set (typically empty)
  2567. and returns the list of live-after sets.
  2568. %
  2569. We recommend creating helper functions to 1) compute the set of
  2570. variables that appear in an argument (of an instruction), 2) compute
  2571. the variables read by an instruction which corresponds to the $R$
  2572. function discussed above, and 3) the variables written by an
  2573. instruction which corresponds to $W$.
  2574. \end{exercise}
  2575. \section{Building the Interference Graph}
  2576. \label{sec:build-interference}
  2577. Based on the liveness analysis, we know where each variable is needed.
  2578. However, during register allocation, we need to answer questions of
  2579. the specific form: are variables $u$ and $v$ live at the same time?
  2580. (And therefore cannot be assigned to the same register.) To make this
  2581. question easier to answer, we create an explicit data structure, an
  2582. \emph{interference graph}. An interference graph is an undirected
  2583. graph that has an edge between two variables if they are live at the
  2584. same time, that is, if they interfere with each other.
  2585. The most obvious way to compute the interference graph is to look at
  2586. the set of live variables between each statement in the program and
  2587. add an edge to the graph for every pair of variables in the same set.
  2588. This approach is less than ideal for two reasons. First, it can be
  2589. expensive because it takes $O(n^2)$ time to look at every pair in a
  2590. set of $n$ live variables. Second, there is a special case in which
  2591. two variables that are live at the same time do not actually interfere
  2592. with each other: when they both contain the same value because we have
  2593. assigned one to the other.
  2594. A better way to compute the interference graph is to focus on the
  2595. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2596. instruction to overwrite something in a live variable. So for each
  2597. instruction, we create an edge between the variable being written to
  2598. and all the \emph{other} live variables. (One should not create self
  2599. edges.) For a \key{callq} instruction, think of all caller-saved
  2600. registers as being written to, so an edge must be added between every
  2601. live variable and every caller-saved register. For \key{movq}, we deal
  2602. with the above-mentioned special case by not adding an edge between a
  2603. live variable $v$ and destination $d$ if $v$ matches the source of the
  2604. move. So we have the following three rules.
  2605. \begin{enumerate}
  2606. \item If instruction $I_k$ is an arithmetic instruction such as
  2607. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2608. L_{\mathsf{after}}(k)$ unless $v = d$.
  2609. \item If instruction $I_k$ is of the form \key{callq}
  2610. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2611. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2612. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2613. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2614. d$ or $v = s$.
  2615. \end{enumerate}
  2616. Working from the top to bottom of Figure~\ref{fig:live-eg}, apply the
  2617. above rules to each instruction. We highlight a few of the
  2618. instructions and then refer the reader to
  2619. Figure~\ref{fig:interference-results} all the interference results.
  2620. The first instruction is \lstinline{movq $1, v}, so rule 3 applies,
  2621. and the live-after set is $\{v\}$. We do not add any interference
  2622. edges because the one live variable $v$ is also the destination of
  2623. this instruction.
  2624. %
  2625. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2626. again, and the live-after set is $\{v,w\}$. So the target $w$ of
  2627. \key{movq} interferes with $v$.
  2628. %
  2629. Next we skip forward to the instruction \lstinline{movq x, y}.
  2630. \begin{figure}[tbp]
  2631. \begin{quote}
  2632. \begin{tabular}{ll}
  2633. \lstinline{movq $1, v}& no interference by rule 3,\\
  2634. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2635. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2636. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2637. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2638. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2639. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2640. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2641. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2642. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2643. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2644. \lstinline{jmp conclusion}& no interference.
  2645. \end{tabular}
  2646. \end{quote}
  2647. \caption{Interference results for the running example.}
  2648. \label{fig:interference-results}
  2649. \end{figure}
  2650. The resulting interference graph is shown in
  2651. Figure~\ref{fig:interfere}.
  2652. \begin{figure}[tbp]
  2653. \large
  2654. \[
  2655. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2656. \node (t1) at (0,2) {$t$};
  2657. \node (z) at (3,2) {$z$};
  2658. \node (x) at (6,2) {$x$};
  2659. \node (y) at (3,0) {$y$};
  2660. \node (w) at (6,0) {$w$};
  2661. \node (v) at (9,0) {$v$};
  2662. \draw (t1) to (z);
  2663. \draw (z) to (y);
  2664. \draw (z) to (w);
  2665. \draw (x) to (w);
  2666. \draw (y) to (w);
  2667. \draw (v) to (w);
  2668. \end{tikzpicture}
  2669. \]
  2670. \caption{The interference graph of the example program.}
  2671. \label{fig:interfere}
  2672. \end{figure}
  2673. %% Our next concern is to choose a data structure for representing the
  2674. %% interference graph. There are many choices for how to represent a
  2675. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2676. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2677. %% data structure is to study the algorithm that uses the data structure,
  2678. %% determine what operations need to be performed, and then choose the
  2679. %% data structure that provide the most efficient implementations of
  2680. %% those operations. Often times the choice of data structure can have an
  2681. %% effect on the time complexity of the algorithm, as it does here. If
  2682. %% you skim the next section, you will see that the register allocation
  2683. %% algorithm needs to ask the graph for all of its vertices and, given a
  2684. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2685. %% correct choice of graph representation is that of an adjacency
  2686. %% list. There are helper functions in \code{utilities.rkt} for
  2687. %% representing graphs using the adjacency list representation:
  2688. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2689. %% (Appendix~\ref{appendix:utilities}).
  2690. %% %
  2691. %% \margincomment{\footnotesize To do: change to use the
  2692. %% Racket graph library. \\ --Jeremy}
  2693. %% %
  2694. %% In particular, those functions use a hash table to map each vertex to
  2695. %% the set of adjacent vertices, and the sets are represented using
  2696. %% Racket's \key{set}, which is also a hash table.
  2697. \begin{exercise}\normalfont
  2698. Implement the compiler pass named \code{build-interference} according
  2699. to the algorithm suggested above. We recommend using the Racket
  2700. \code{graph} package to create and inspect the interference graph.
  2701. The output graph of this pass should be stored in the $\itm{info}$
  2702. field of the program, under the key \code{conflicts}.
  2703. \end{exercise}
  2704. \section{Graph Coloring via Sudoku}
  2705. \label{sec:graph-coloring}
  2706. We come to the main event, mapping variables to registers (or to stack
  2707. locations in the event that we run out of registers). We need to make
  2708. sure that two variables do not get mapped to the same register if the
  2709. two variables interfere with each other. Thinking about the
  2710. interference graph, this means that adjacent vertices must be mapped
  2711. to different registers. If we think of registers as colors, the
  2712. register allocation problem becomes the widely-studied graph coloring
  2713. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2714. The reader may be more familiar with the graph coloring problem than he
  2715. or she realizes; the popular game of Sudoku is an instance of the
  2716. graph coloring problem. The following describes how to build a graph
  2717. out of an initial Sudoku board.
  2718. \begin{itemize}
  2719. \item There is one vertex in the graph for each Sudoku square.
  2720. \item There is an edge between two vertices if the corresponding squares
  2721. are in the same row, in the same column, or if the squares are in
  2722. the same $3\times 3$ region.
  2723. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2724. \item Based on the initial assignment of numbers to squares in the
  2725. Sudoku board, assign the corresponding colors to the corresponding
  2726. vertices in the graph.
  2727. \end{itemize}
  2728. If you can color the remaining vertices in the graph with the nine
  2729. colors, then you have also solved the corresponding game of Sudoku.
  2730. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2731. the corresponding graph with colored vertices. We map the Sudoku
  2732. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2733. sampling of the vertices (the colored ones) because showing edges for
  2734. all of the vertices would make the graph unreadable.
  2735. \begin{figure}[tbp]
  2736. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2737. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2738. \caption{A Sudoku game board and the corresponding colored graph.}
  2739. \label{fig:sudoku-graph}
  2740. \end{figure}
  2741. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2742. strategies to come up with an algorithm for allocating registers. For
  2743. example, one of the basic techniques for Sudoku is called Pencil
  2744. Marks. The idea is to use a process of elimination to determine what
  2745. numbers no longer make sense for a square and write down those
  2746. numbers in the square (writing very small). For example, if the number
  2747. $1$ is assigned to a square, then by process of elimination, you can
  2748. write the pencil mark $1$ in all the squares in the same row, column,
  2749. and region. Many Sudoku computer games provide automatic support for
  2750. Pencil Marks.
  2751. %
  2752. The Pencil Marks technique corresponds to the notion of
  2753. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2754. vertex, in Sudoku terms, is the set of numbers that are no longer
  2755. available. In graph terminology, we have the following definition:
  2756. \begin{equation*}
  2757. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2758. \text{ and } \mathrm{color}(v) = c \}
  2759. \end{equation*}
  2760. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2761. edge with $u$.
  2762. Using the Pencil Marks technique leads to a simple strategy for
  2763. filling in numbers: if there is a square with only one possible number
  2764. left, then choose that number! But what if there are no squares with
  2765. only one possibility left? One brute-force approach is to try them
  2766. all: choose the first and if it ultimately leads to a solution,
  2767. great. If not, backtrack and choose the next possibility. One good
  2768. thing about Pencil Marks is that it reduces the degree of branching in
  2769. the search tree. Nevertheless, backtracking can be horribly time
  2770. consuming. One way to reduce the amount of backtracking is to use the
  2771. most-constrained-first heuristic. That is, when choosing a square,
  2772. always choose one with the fewest possibilities left (the vertex with
  2773. the highest saturation). The idea is that choosing highly constrained
  2774. squares earlier rather than later is better because later on there may
  2775. not be any possibilities left for those squares.
  2776. However, register allocation is easier than Sudoku because the
  2777. register allocator can map variables to stack locations when the
  2778. registers run out. Thus, it makes sense to drop backtracking in favor
  2779. of greedy search, that is, make the best choice at the time and keep
  2780. going. We still wish to minimize the number of colors needed, so
  2781. keeping the most-constrained-first heuristic is a good idea.
  2782. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2783. algorithm for register allocation based on saturation and the
  2784. most-constrained-first heuristic. It is roughly equivalent to the
  2785. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2786. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2787. Sudoku, the algorithm represents colors with integers. The first $k$
  2788. colors corresponding to the $k$ registers in a given machine and the
  2789. rest of the integers corresponding to stack locations.
  2790. \begin{figure}[btp]
  2791. \centering
  2792. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2793. Algorithm: DSATUR
  2794. Input: a graph |$G$|
  2795. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2796. |$W \gets \mathit{vertices}(G)$|
  2797. while |$W \neq \emptyset$| do
  2798. pick a vertex |$u$| from |$W$| with the highest saturation,
  2799. breaking ties randomly
  2800. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2801. |$\mathrm{color}[u] \gets c$|
  2802. |$W \gets W - \{u\}$|
  2803. \end{lstlisting}
  2804. \caption{The saturation-based greedy graph coloring algorithm.}
  2805. \label{fig:satur-algo}
  2806. \end{figure}
  2807. With this algorithm in hand, let us return to the running example and
  2808. consider how to color the interference graph in
  2809. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2810. colored and they are unsaturated, so we annotate each of them with a
  2811. dash for their color and an empty set for the saturation.
  2812. \[
  2813. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2814. \node (t1) at (0,2) {$t:-,\{\}$};
  2815. \node (z) at (3,2) {$z:-,\{\}$};
  2816. \node (x) at (6,2) {$x:-,\{\}$};
  2817. \node (y) at (3,0) {$y:-,\{\}$};
  2818. \node (w) at (6,0) {$w:-,\{\}$};
  2819. \node (v) at (9,0) {$v:-,\{\}$};
  2820. \draw (t1) to (z);
  2821. \draw (z) to (y);
  2822. \draw (z) to (w);
  2823. \draw (x) to (w);
  2824. \draw (y) to (w);
  2825. \draw (v) to (w);
  2826. \end{tikzpicture}
  2827. \]
  2828. The algorithm says to select a maximally saturated vertex and color it
  2829. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2830. $t$. We then mark color $0$ as no longer available for $z$ because
  2831. it interferes with $t$.
  2832. \[
  2833. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2834. \node (t1) at (0,2) {$t:0,\{\}$};
  2835. \node (z) at (3,2) {$z:-,\{0\}$};
  2836. \node (x) at (6,2) {$x:-,\{\}$};
  2837. \node (y) at (3,0) {$y:-,\{\}$};
  2838. \node (w) at (6,0) {$w:-,\{\}$};
  2839. \node (v) at (9,0) {$v:-,\{\}$};
  2840. \draw (t1) to (z);
  2841. \draw (z) to (y);
  2842. \draw (z) to (w);
  2843. \draw (x) to (w);
  2844. \draw (y) to (w);
  2845. \draw (v) to (w);
  2846. \end{tikzpicture}
  2847. \]
  2848. Next we repeat the process, selecting another maximally saturated
  2849. vertex, which is $z$, and color it with the first available number,
  2850. which is $1$.
  2851. \[
  2852. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2853. \node (t1) at (0,2) {$t:0,\{1\}$};
  2854. \node (z) at (3,2) {$z:1,\{0\}$};
  2855. \node (x) at (6,2) {$x:-,\{\}$};
  2856. \node (y) at (3,0) {$y:-,\{1\}$};
  2857. \node (w) at (6,0) {$w:-,\{1\}$};
  2858. \node (v) at (9,0) {$v:-,\{\}$};
  2859. \draw (t1) to (z);
  2860. \draw (z) to (y);
  2861. \draw (z) to (w);
  2862. \draw (x) to (w);
  2863. \draw (y) to (w);
  2864. \draw (v) to (w);
  2865. \end{tikzpicture}
  2866. \]
  2867. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2868. first available color, which is $0$.
  2869. \[
  2870. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2871. \node (t1) at (0,2) {$t:0,\{1\}$};
  2872. \node (z) at (3,2) {$z:1,\{0\}$};
  2873. \node (x) at (6,2) {$x:-,\{0\}$};
  2874. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2875. \node (w) at (6,0) {$w:0,\{1\}$};
  2876. \node (v) at (9,0) {$v:-,\{0\}$};
  2877. \draw (t1) to (z);
  2878. \draw (z) to (y);
  2879. \draw (z) to (w);
  2880. \draw (x) to (w);
  2881. \draw (y) to (w);
  2882. \draw (v) to (w);
  2883. \end{tikzpicture}
  2884. \]
  2885. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2886. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2887. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2888. are $0$ and $1$ respectively.
  2889. \[
  2890. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2891. \node (t1) at (0,2) {$t:0,\{1\}$};
  2892. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2893. \node (x) at (6,2) {$x:-,\{0\}$};
  2894. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2895. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2896. \node (v) at (9,0) {$v:-,\{0\}$};
  2897. \draw (t1) to (z);
  2898. \draw (z) to (y);
  2899. \draw (z) to (w);
  2900. \draw (x) to (w);
  2901. \draw (y) to (w);
  2902. \draw (v) to (w);
  2903. \end{tikzpicture}
  2904. \]
  2905. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  2906. \[
  2907. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2908. \node (t1) at (0,2) {$t:0,\{1\}$};
  2909. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2910. \node (x) at (6,2) {$x:-,\{0\}$};
  2911. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2912. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2913. \node (v) at (9,0) {$v:1,\{0\}$};
  2914. \draw (t1) to (z);
  2915. \draw (z) to (y);
  2916. \draw (z) to (w);
  2917. \draw (x) to (w);
  2918. \draw (y) to (w);
  2919. \draw (v) to (w);
  2920. \end{tikzpicture}
  2921. \]
  2922. In the last step of the algorithm, we color $x$ with $1$.
  2923. \[
  2924. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2925. \node (t1) at (0,2) {$t:0,\{1,\}$};
  2926. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2927. \node (x) at (6,2) {$x:1,\{0\}$};
  2928. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2929. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2930. \node (v) at (9,0) {$v:1,\{0\}$};
  2931. \draw (t1) to (z);
  2932. \draw (z) to (y);
  2933. \draw (z) to (w);
  2934. \draw (x) to (w);
  2935. \draw (y) to (w);
  2936. \draw (v) to (w);
  2937. \end{tikzpicture}
  2938. \]
  2939. With the coloring complete, we finalize the assignment of variables to
  2940. registers and stack locations. Recall that if we have $k$ registers,
  2941. we map the first $k$ colors to registers and the rest to stack
  2942. locations. Suppose for the moment that we have just one register to
  2943. use for register allocation, \key{rcx}. Then the following is the
  2944. mapping of colors to registers and stack allocations.
  2945. \[
  2946. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2947. \]
  2948. Putting this mapping together with the above coloring of the
  2949. variables, we arrive at the following assignment of variables to
  2950. registers and stack locations.
  2951. \begin{gather*}
  2952. \{ v \mapsto \key{\%rcx}, \,
  2953. w \mapsto \key{\%rcx}, \,
  2954. x \mapsto \key{-8(\%rbp)}, \\
  2955. y \mapsto \key{-16(\%rbp)}, \,
  2956. z\mapsto \key{-8(\%rbp)},
  2957. t\mapsto \key{\%rcx} \}
  2958. \end{gather*}
  2959. Applying this assignment to our running example, on the left, yields
  2960. the program on the right.
  2961. % why frame size of 32? -JGS
  2962. \begin{center}
  2963. \begin{minipage}{0.3\textwidth}
  2964. \begin{lstlisting}
  2965. movq $1, v
  2966. movq $42, w
  2967. movq v, x
  2968. addq $7, x
  2969. movq x, y
  2970. movq x, z
  2971. addq w, z
  2972. movq y, t
  2973. negq t
  2974. movq z, %rax
  2975. addq t, %rax
  2976. jmp conclusion
  2977. \end{lstlisting}
  2978. \end{minipage}
  2979. $\Rightarrow\qquad$
  2980. \begin{minipage}{0.45\textwidth}
  2981. \begin{lstlisting}
  2982. movq $1, %rcx
  2983. movq $42, %rcx
  2984. movq %rcx, -8(%rbp)
  2985. addq $7, -8(%rbp)
  2986. movq -8(%rbp), -16(%rbp)
  2987. movq -8(%rbp), -8(%rbp)
  2988. addq %rcx, -8(%rbp)
  2989. movq -16(%rbp), %rcx
  2990. negq %rcx
  2991. movq -8(%rbp), %rax
  2992. addq %rcx, %rax
  2993. jmp conclusion
  2994. \end{lstlisting}
  2995. \end{minipage}
  2996. \end{center}
  2997. The resulting program is almost an x86 program. The remaining step is
  2998. the patch instructions pass. In this example, the trivial move of
  2999. \code{-8(\%rbp)} to itself is deleted and the addition of
  3000. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3001. \code{rax} as follows.
  3002. \begin{lstlisting}
  3003. movq -8(%rbp), %rax
  3004. addq %rax, -16(%rbp)
  3005. \end{lstlisting}
  3006. An overview of all of the passes involved in register allocation is
  3007. shown in Figure~\ref{fig:reg-alloc-passes}.
  3008. \begin{figure}[tbp]
  3009. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3010. \node (R1) at (0,2) {\large $R_1$};
  3011. \node (R1-2) at (3,2) {\large $R_1$};
  3012. \node (R1-3) at (6,2) {\large $R_1$};
  3013. \node (C0-1) at (3,0) {\large $C_0$};
  3014. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3015. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3016. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3017. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3018. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3019. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3020. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3021. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3022. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3023. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3024. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3025. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3026. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3027. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3028. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3029. \end{tikzpicture}
  3030. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3031. \label{fig:reg-alloc-passes}
  3032. \end{figure}
  3033. \begin{exercise}\normalfont
  3034. Implement the pass \code{allocate-registers}, which should come
  3035. after the \code{build-interference} pass. The three new passes,
  3036. \code{uncover-live}, \code{build-interference}, and
  3037. \code{allocate-registers} replace the \code{assign-homes} pass of
  3038. Section~\ref{sec:assign-r1}.
  3039. We recommend that you create a helper function named
  3040. \code{color-graph} that takes an interference graph and a list of
  3041. all the variables in the program. This function should return a
  3042. mapping of variables to their colors (represented as natural
  3043. numbers). By creating this helper function, you will be able to
  3044. reuse it in Chapter~\ref{ch:functions} when you add support for
  3045. functions. The support code includes an implementation of the
  3046. priority queue data structure in the file
  3047. \code{priority\_queue.rkt}, which might come in handy for
  3048. prioritizing highly saturated nodes inside your \code{color-graph}
  3049. function.
  3050. Once you have obtained the coloring from \code{color-graph}, you can
  3051. assign the variables to registers or stack locations and then reuse
  3052. code from the \code{assign-homes} pass from
  3053. Section~\ref{sec:assign-r1} to replace the variables with their
  3054. assigned location.
  3055. Test your updated compiler by creating new example programs that
  3056. exercise all of the register allocation algorithm, such as forcing
  3057. variables to be spilled to the stack.
  3058. \end{exercise}
  3059. \section{Print x86 and Conventions for Registers}
  3060. \label{sec:print-x86-reg-alloc}
  3061. Recall that the \code{print-x86} pass generates the prelude and
  3062. conclusion instructions for the \code{main} function.
  3063. %
  3064. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3065. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3066. reason for this is that our \code{main} function must adhere to the
  3067. x86 calling conventions that we described in
  3068. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3069. allocator assigned variables to other callee-saved registers
  3070. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3071. saved to the stack in the prelude and restored in the conclusion. The
  3072. simplest approach is to save and restore all of the callee-saved
  3073. registers. The more efficient approach is to keep track of which
  3074. callee-saved registers were used and only save and restore
  3075. them. Either way, make sure to take this use of stack space into
  3076. account when you are calculating the size of the frame and adjusting
  3077. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3078. frame needs to be a multiple of 16 bytes!
  3079. \section{Challenge: Move Biasing}
  3080. \label{sec:move-biasing}
  3081. This section describes an optional enhancement to register allocation
  3082. for those students who are looking for an extra challenge or who have
  3083. a deeper interest in register allocation.
  3084. We return to the running example, but we remove the supposition that
  3085. we only have one register to use. So we have the following mapping of
  3086. color numbers to registers.
  3087. \[
  3088. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3089. \]
  3090. Using the same assignment of variables to color numbers that was
  3091. produced by the register allocator described in the last section, we
  3092. get the following program.
  3093. \begin{minipage}{0.3\textwidth}
  3094. \begin{lstlisting}
  3095. movq $1, v
  3096. movq $42, w
  3097. movq v, x
  3098. addq $7, x
  3099. movq x, y
  3100. movq x, z
  3101. addq w, z
  3102. movq y, t
  3103. negq t
  3104. movq z, %rax
  3105. addq t, %rax
  3106. jmp conclusion
  3107. \end{lstlisting}
  3108. \end{minipage}
  3109. $\Rightarrow\qquad$
  3110. \begin{minipage}{0.45\textwidth}
  3111. \begin{lstlisting}
  3112. movq $1, %rcx
  3113. movq $42, $rbx
  3114. movq %rcx, %rcx
  3115. addq $7, %rcx
  3116. movq %rcx, %rdx
  3117. movq %rcx, %rcx
  3118. addq %rbx, %rcx
  3119. movq %rdx, %rbx
  3120. negq %rbx
  3121. movq %rcx, %rax
  3122. addq %rbx, %rax
  3123. jmp conclusion
  3124. \end{lstlisting}
  3125. \end{minipage}
  3126. In the above output code there are two \key{movq} instructions that
  3127. can be removed because their source and target are the same. However,
  3128. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3129. register, we could instead remove three \key{movq} instructions. We
  3130. can accomplish this by taking into account which variables appear in
  3131. \key{movq} instructions with which other variables.
  3132. We say that two variables $p$ and $q$ are \emph{move related} if they
  3133. participate together in a \key{movq} instruction, that is, \key{movq}
  3134. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  3135. allocator chooses a color for a variable, it should prefer a color
  3136. that has already been used for a move-related variable (assuming that
  3137. they do not interfere). Of course, this preference should not override
  3138. the preference for registers over stack locations. This preference
  3139. should be used as a tie breaker when choosing between registers or
  3140. when choosing between stack locations.
  3141. We recommend representing the move relationships in a graph, similar
  3142. to how we represented interference. The following is the \emph{move
  3143. graph} for our running example.
  3144. \[
  3145. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3146. \node (t) at (0,2) {$t$};
  3147. \node (z) at (3,2) {$z$};
  3148. \node (x) at (6,2) {$x$};
  3149. \node (y) at (3,0) {$y$};
  3150. \node (w) at (6,0) {$w$};
  3151. \node (v) at (9,0) {$v$};
  3152. \draw (v) to (x);
  3153. \draw (x) to (y);
  3154. \draw (x) to (z);
  3155. \draw (y) to (t);
  3156. \end{tikzpicture}
  3157. \]
  3158. Now we replay the graph coloring, pausing to see the coloring of
  3159. $y$. Recall the following configuration. The most saturated vertices
  3160. were $w$ and $y$.
  3161. \[
  3162. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3163. \node (t1) at (0,2) {$t:0,\{1\}$};
  3164. \node (z) at (3,2) {$z:1,\{0\}$};
  3165. \node (x) at (6,2) {$x:-,\{\}$};
  3166. \node (y) at (3,0) {$y:-,\{1\}$};
  3167. \node (w) at (6,0) {$w:-,\{1\}$};
  3168. \node (v) at (9,0) {$v:-,\{\}$};
  3169. \draw (t1) to (z);
  3170. \draw (z) to (y);
  3171. \draw (z) to (w);
  3172. \draw (x) to (w);
  3173. \draw (y) to (w);
  3174. \draw (v) to (w);
  3175. \end{tikzpicture}
  3176. \]
  3177. %
  3178. Last time we chose to color $w$ with $0$. But this time we note that
  3179. $w$ is not move related to any vertex, and $y$ is move related to $t$.
  3180. So we choose to color $y$ the same color, $0$.
  3181. \[
  3182. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3183. \node (t1) at (0,2) {$t:0,\{1\}$};
  3184. \node (z) at (3,2) {$z:1,\{0\}$};
  3185. \node (x) at (6,2) {$x:-,\{\}$};
  3186. \node (y) at (3,0) {$y:0,\{1\}$};
  3187. \node (w) at (6,0) {$w:-,\{0,1\}$};
  3188. \node (v) at (9,0) {$v:-,\{\}$};
  3189. \draw (t1) to (z);
  3190. \draw (z) to (y);
  3191. \draw (z) to (w);
  3192. \draw (x) to (w);
  3193. \draw (y) to (w);
  3194. \draw (v) to (w);
  3195. \end{tikzpicture}
  3196. \]
  3197. Now $w$ is the most saturated, so we color it $2$.
  3198. \[
  3199. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3200. \node (t1) at (0,2) {$t:0,\{1\}$};
  3201. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3202. \node (x) at (6,2) {$x:-,\{2\}$};
  3203. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3204. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3205. \node (v) at (9,0) {$v:-,\{2\}$};
  3206. \draw (t1) to (z);
  3207. \draw (z) to (y);
  3208. \draw (z) to (w);
  3209. \draw (x) to (w);
  3210. \draw (y) to (w);
  3211. \draw (v) to (w);
  3212. \end{tikzpicture}
  3213. \]
  3214. At this point, vertices $x$ and $v$ are most saturated,
  3215. but $x$ is move related to $y$ and $z$, so we color $x$ to $0$
  3216. to match $y$. Finally, we color $v$ to $0$.
  3217. \[
  3218. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3219. \node (t) at (0,2) {$t:0,\{1\}$};
  3220. \node (z) at (3,2) {$z:1,\{0,2\}$};
  3221. \node (x) at (6,2) {$x:0,\{2\}$};
  3222. \node (y) at (3,0) {$y:0,\{1,2\}$};
  3223. \node (w) at (6,0) {$w:2,\{0,1\}$};
  3224. \node (v) at (9,0) {$v:0,\{2\}$};
  3225. \draw (t) to (z);
  3226. \draw (z) to (y);
  3227. \draw (z) to (w);
  3228. \draw (x) to (w);
  3229. \draw (y) to (w);
  3230. \draw (v) to (w);
  3231. \end{tikzpicture}
  3232. \]
  3233. So we have the following assignment of variables to registers.
  3234. \begin{gather*}
  3235. \{ v \mapsto \key{\%rbx}, \,
  3236. w \mapsto \key{\%rdx}, \,
  3237. x \mapsto \key{\%rbx}, \\
  3238. y \mapsto \key{\%rbx}, \,
  3239. z\mapsto \key{\%rcx},
  3240. t\mapsto \key{\%rbx} \}
  3241. \end{gather*}
  3242. We apply this register assignment to the running example, on the left,
  3243. to obtain the code on right.
  3244. \begin{minipage}{0.3\textwidth}
  3245. \begin{lstlisting}
  3246. movq $1, v
  3247. movq $42, w
  3248. movq v, x
  3249. addq $7, x
  3250. movq x, y
  3251. movq x, z
  3252. addq w, z
  3253. movq y, t
  3254. negq t
  3255. movq z, %rax
  3256. addq t, %rax
  3257. jmp conclusion
  3258. \end{lstlisting}
  3259. \end{minipage}
  3260. $\Rightarrow\qquad$
  3261. \begin{minipage}{0.45\textwidth}
  3262. \begin{lstlisting}
  3263. movq $1, %rbx
  3264. movq $42, %rdx
  3265. movq %rbx, %rbx
  3266. addq $7, %rbx
  3267. movq %rbx, %rbx
  3268. movq %rbx, %rcx
  3269. addq %rdx, %rcx
  3270. movq %rbx, %rbx
  3271. negq %rbx
  3272. movq %rcx, %rax
  3273. addq %rbx, %rax
  3274. jmp conclusion
  3275. \end{lstlisting}
  3276. \end{minipage}
  3277. The \code{patch-instructions} then removes the three trivial moves
  3278. from \key{rbx} to \key{rbx} to obtain the following result.
  3279. \begin{minipage}{0.45\textwidth}
  3280. \begin{lstlisting}
  3281. movq $1, %rbx
  3282. movq $42, %rdx
  3283. addq $7, %rbx
  3284. movq %rbx, %rcx
  3285. addq %rdx, %rcx
  3286. negq %rbx
  3287. movq %rcx, %rax
  3288. addq %rbx, %rax
  3289. jmp conclusion
  3290. \end{lstlisting}
  3291. \end{minipage}
  3292. \begin{exercise}\normalfont
  3293. Change your implementation of \code{allocate-registers} to take move
  3294. biasing into account. Make sure that your compiler still passes all of
  3295. the previous tests. Create two new tests that include at least one
  3296. opportunity for move biasing and visually inspect the output x86
  3297. programs to make sure that your move biasing is working properly.
  3298. \end{exercise}
  3299. \margincomment{\footnotesize To do: another neat challenge would be to do
  3300. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3301. \section{Output of the Running Example}
  3302. \label{sec:reg-alloc-output}
  3303. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3304. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3305. and move biasing. To demonstrate both the use of registers and the
  3306. stack, we have limited the register allocator to use just two
  3307. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3308. \code{main} function, we push \code{rbx} onto the stack because it is
  3309. a callee-saved register and it was assigned to variable by the
  3310. register allocator. We substract \code{8} from the \code{rsp} at the
  3311. end of the prelude to reserve space for the one spilled variable.
  3312. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3313. Moving on the the \code{start} block, we see how the registers were
  3314. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3315. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3316. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3317. that the prelude saved the callee-save register \code{rbx} onto the
  3318. stack. The spilled variables must be placed lower on the stack than
  3319. the saved callee-save registers, so in this case \code{w} is placed at
  3320. \code{-16(\%rbp)}.
  3321. In the \code{conclusion}, we undo the work that was done in the
  3322. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3323. spilled variables), then we pop the old values of \code{rbx} and
  3324. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3325. return control to the operating system.
  3326. \begin{figure}[tbp]
  3327. % s0_28.rkt
  3328. % (use-minimal-set-of-registers! #t)
  3329. % and only rbx rcx
  3330. % tmp 0 rbx
  3331. % z 1 rcx
  3332. % y 0 rbx
  3333. % w 2 16(%rbp)
  3334. % v 0 rbx
  3335. % x 0 rbx
  3336. \begin{lstlisting}
  3337. start:
  3338. movq $1, %rbx
  3339. movq $42, -16(%rbp)
  3340. addq $7, %rbx
  3341. movq %rbx, %rcx
  3342. addq -16(%rbp), %rcx
  3343. negq %rbx
  3344. movq %rcx, %rax
  3345. addq %rbx, %rax
  3346. jmp conclusion
  3347. .globl main
  3348. main:
  3349. pushq %rbp
  3350. movq %rsp, %rbp
  3351. pushq %rbx
  3352. subq $8, %rsp
  3353. jmp start
  3354. conclusion:
  3355. addq $8, %rsp
  3356. popq %rbx
  3357. popq %rbp
  3358. retq
  3359. \end{lstlisting}
  3360. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3361. \label{fig:running-example-x86}
  3362. \end{figure}
  3363. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3364. \chapter{Booleans and Control Flow}
  3365. \label{ch:bool-types}
  3366. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3367. integers. In this chapter we add a second kind of value, the Booleans,
  3368. to create the $R_2$ language. The Boolean values \emph{true} and
  3369. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3370. Racket. The $R_2$ language includes several operations that involve
  3371. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3372. conditional \key{if} expression. With the addition of \key{if}
  3373. expressions, programs can have non-trivial control flow which which
  3374. significantly impacts the \code{explicate-control} and the liveness
  3375. analysis for register allocation. Also, because we now have two kinds
  3376. of values, we need to handle programs that apply an operation to the
  3377. wrong kind of value, such as \code{(not 1)}.
  3378. There are two language design options for such situations. One option
  3379. is to signal an error and the other is to provide a wider
  3380. interpretation of the operation. The Racket language uses a mixture of
  3381. these two options, depending on the operation and the kind of
  3382. value. For example, the result of \code{(not 1)} in Racket is
  3383. \code{\#f} because Racket treats non-zero integers as if they were
  3384. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3385. error in Racket stating that \code{car} expects a pair.
  3386. The Typed Racket language makes similar design choices as Racket,
  3387. except much of the error detection happens at compile time instead of
  3388. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3389. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3390. reports a compile-time error because Typed Racket expects the type of
  3391. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3392. For the $R_2$ language we choose to be more like Typed Racket in that
  3393. we shall perform type checking during compilation. In
  3394. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3395. is, how to compile a dynamically typed language like Racket. The
  3396. $R_2$ language is a subset of Typed Racket but by no means includes
  3397. all of Typed Racket. For many operations we take a narrower
  3398. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3399. This chapter is organized as follows. We begin by defining the syntax
  3400. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3401. then introduce the idea of type checking and build a type checker for
  3402. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3403. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3404. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3405. how our compiler passes need to change to accommodate Booleans and
  3406. conditional control flow.
  3407. \section{The $R_2$ Language}
  3408. \label{sec:r2-lang}
  3409. The concrete syntax of the $R_2$ language is defined in
  3410. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3411. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3412. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3413. and the conditional \code{if} expression. Also, we expand the
  3414. operators to include
  3415. \begin{enumerate}
  3416. \item subtraction on integers,
  3417. \item the logical operators \key{and}, \key{or} and \key{not},
  3418. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3419. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3420. comparing integers.
  3421. \end{enumerate}
  3422. \begin{figure}[tp]
  3423. \centering
  3424. \fbox{
  3425. \begin{minipage}{0.96\textwidth}
  3426. \[
  3427. \begin{array}{lcl}
  3428. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3429. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3430. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3431. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3432. &\mid& \itm{bool}
  3433. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3434. \mid (\key{not}\;\Exp) \\
  3435. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3436. R_2 &::=& \Exp
  3437. \end{array}
  3438. \]
  3439. \end{minipage}
  3440. }
  3441. \caption{The concrete syntax of $R_2$, extending $R_1$
  3442. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3443. \label{fig:r2-concrete-syntax}
  3444. \end{figure}
  3445. \begin{figure}[tp]
  3446. \centering
  3447. \fbox{
  3448. \begin{minipage}{0.96\textwidth}
  3449. \[
  3450. \begin{array}{lcl}
  3451. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3452. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3453. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3454. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3455. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3456. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3457. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3458. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3459. &\mid& \BINOP{\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3460. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3461. \end{array}
  3462. \]
  3463. \end{minipage}
  3464. }
  3465. \caption{The abstract syntax of $R_2$.}
  3466. \label{fig:r2-syntax}
  3467. \end{figure}
  3468. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3469. the parts that are the same as the interpreter for $R_1$
  3470. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3471. evaluate to the corresponding Boolean values. The conditional
  3472. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3473. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3474. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3475. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3476. you might expect, but note that the \code{and} operation is
  3477. short-circuiting. That is, given the expression
  3478. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3479. $e_1$ evaluates to \code{\#f}.
  3480. With the addition of the comparison operations, there are quite a few
  3481. primitive operations and the interpreter code for them could become
  3482. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3483. out the different parts of the code for primitive operations into the
  3484. \code{interp-op} function and the similar parts of the code into the
  3485. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3486. do not use \code{interp-op} for the \code{and} operation because of
  3487. the short-circuiting behavior in the order of evaluation of its
  3488. arguments.
  3489. \begin{figure}[tbp]
  3490. \begin{lstlisting}
  3491. (define (interp-op op)
  3492. (match op
  3493. ...
  3494. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3495. ['eq? (lambda (v1 v2)
  3496. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3497. (and (boolean? v1) (boolean? v2)))
  3498. (eq? v1 v2)]))]
  3499. ['< (lambda (v1 v2)
  3500. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3501. ['<= (lambda (v1 v2)
  3502. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3503. ['> (lambda (v1 v2)
  3504. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3505. ['>= (lambda (v1 v2)
  3506. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3507. [else (error 'interp-op "unknown operator")]))
  3508. (define (interp-exp env)
  3509. (lambda (e)
  3510. (define recur (interp-exp env))
  3511. (match e
  3512. ...
  3513. [(Bool b) b]
  3514. [(If cnd thn els)
  3515. (define b (recur cnd))
  3516. (match b
  3517. [#t (recur thn)]
  3518. [#f (recur els)])]
  3519. [(Prim 'and (list e1 e2))
  3520. (define v1 (recur e1))
  3521. (match v1
  3522. [#t (match (recur e2) [#t #t] [#f #f])]
  3523. [#f #f])]
  3524. [(Prim op args)
  3525. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3526. )))
  3527. (define (interp-R2 p)
  3528. (match p
  3529. [(Program info e)
  3530. ((interp-exp '()) e)]
  3531. ))
  3532. \end{lstlisting}
  3533. \caption{Interpreter for the $R_2$ language.}
  3534. \label{fig:interp-R2}
  3535. \end{figure}
  3536. \section{Type Checking $R_2$ Programs}
  3537. \label{sec:type-check-r2}
  3538. It is helpful to think about type checking in two complementary
  3539. ways. A type checker predicts the type of value that will be produced
  3540. by each expression in the program. For $R_2$, we have just two types,
  3541. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3542. \begin{lstlisting}
  3543. (+ 10 (- (+ 12 20)))
  3544. \end{lstlisting}
  3545. produces an \key{Integer} while
  3546. \begin{lstlisting}
  3547. (and (not #f) #t)
  3548. \end{lstlisting}
  3549. produces a \key{Boolean}.
  3550. Another way to think about type checking is that it enforces a set of
  3551. rules about which operators can be applied to which kinds of
  3552. values. For example, our type checker for $R_2$ will signal an error
  3553. for the below expression because, as we have seen above, the
  3554. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3555. checker enforces the rule that the argument of \code{not} must be a
  3556. \key{Boolean}.
  3557. \begin{lstlisting}
  3558. (not (+ 10 (- (+ 12 20))))
  3559. \end{lstlisting}
  3560. The type checker for $R_2$ is a structurally recursive function over
  3561. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3562. the \code{type-check-exp} function. Given an input expression
  3563. \code{e}, the type checker either returns a type (\key{Integer} or
  3564. \key{Boolean}) or it signals an error. The type of an integer literal
  3565. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3566. To handle variables, the type checker uses an environment that maps
  3567. variables to types. Consider the clause for \key{let}. We type check
  3568. the initializing expression to obtain its type \key{T} and then
  3569. associate type \code{T} with the variable \code{x} in the
  3570. environment. When the type checker encounters a use of variable
  3571. \code{x} in the body of the \key{let}, it can find its type in the
  3572. environment.
  3573. \begin{figure}[tbp]
  3574. \begin{lstlisting}
  3575. (define (type-check-exp env)
  3576. (lambda (e)
  3577. (match e
  3578. [(Var x) (dict-ref env x)]
  3579. [(Int n) 'Integer]
  3580. [(Bool b) 'Boolean]
  3581. [(Let x e body)
  3582. (define Te ((type-check-exp env) e))
  3583. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3584. Tb]
  3585. ...
  3586. [else
  3587. (error "type-check-exp couldn't match" e)])))
  3588. (define (type-check env)
  3589. (lambda (e)
  3590. (match e
  3591. [(Program info body)
  3592. (define Tb ((type-check-exp '()) body))
  3593. (unless (equal? Tb 'Integer)
  3594. (error "result of the program must be an integer, not " Tb))
  3595. (Program info body)]
  3596. )))
  3597. \end{lstlisting}
  3598. \caption{Skeleton of a type checker for the $R_2$ language.}
  3599. \label{fig:type-check-R2}
  3600. \end{figure}
  3601. \begin{exercise}\normalfont
  3602. Complete the implementation of \code{type-check-R2} and test it on 10
  3603. new example programs in $R_2$ that you choose based on how thoroughly
  3604. they test the type checking function. Half of the example programs
  3605. should have a type error to make sure that your type checker properly
  3606. rejects them. The other half of the example programs should not have
  3607. type errors. Your testing should check that the result of the type
  3608. checker agrees with the value returned by the interpreter, that is, if
  3609. the type checker returns \key{Integer}, then the interpreter should
  3610. return an integer. Likewise, if the type checker returns
  3611. \key{Boolean}, then the interpreter should return \code{\#t} or
  3612. \code{\#f}. Note that if your type checker does not signal an error
  3613. for a program, then interpreting that program should not encounter an
  3614. error. If it does, there is something wrong with your type checker.
  3615. \end{exercise}
  3616. \section{Shrink the $R_2$ Language}
  3617. \label{sec:shrink-r2}
  3618. The $R_2$ language includes several operators that are easily
  3619. expressible in terms of other operators. For example, subtraction is
  3620. expressible in terms of addition and negation.
  3621. \[
  3622. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3623. \]
  3624. Several of the comparison operations are expressible in terms of
  3625. less-than and logical negation.
  3626. \[
  3627. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3628. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3629. \]
  3630. The \key{let} is needed in the above translation to ensure that
  3631. expression $e_1$ is evaluated before $e_2$.
  3632. By performing these translations near the front-end of the compiler,
  3633. the later passes of the compiler do not need to deal with these
  3634. constructs, making those passes shorter. On the other hand, sometimes
  3635. these translations make it more difficult to generate the most
  3636. efficient code with respect to the number of instructions. However,
  3637. these differences typically do not affect the number of accesses to
  3638. memory, which is the primary factor that determines execution time on
  3639. modern computer architectures.
  3640. \begin{exercise}\normalfont
  3641. Implement the pass \code{shrink} that removes subtraction,
  3642. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3643. by translating them to other constructs in $R_2$. Create tests to
  3644. make sure that the behavior of all of these constructs stays the
  3645. same after translation.
  3646. \end{exercise}
  3647. \section{The x86$_1$ Language}
  3648. \label{sec:x86-1}
  3649. To implement the new logical operations, the comparison operations,
  3650. and the \key{if} expression, we need to delve further into the x86
  3651. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3652. the concrete and abstract syntax for a larger subset of x86 that
  3653. includes instructions for logical operations, comparisons, and
  3654. conditional jumps.
  3655. One small challenge is that x86 does not provide an instruction that
  3656. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3657. However, the \code{xorq} instruction can be used to encode \code{not}.
  3658. The \key{xorq} instruction takes two arguments, performs a pairwise
  3659. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3660. and writes the results into its second argument. Recall the truth
  3661. table for exclusive-or:
  3662. \begin{center}
  3663. \begin{tabular}{l|cc}
  3664. & 0 & 1 \\ \hline
  3665. 0 & 0 & 1 \\
  3666. 1 & 1 & 0
  3667. \end{tabular}
  3668. \end{center}
  3669. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3670. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3671. for the bit $1$, the result is the opposite of the second bit. Thus,
  3672. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3673. the first argument:
  3674. \[
  3675. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3676. \qquad\Rightarrow\qquad
  3677. \begin{array}{l}
  3678. \key{movq}~ \Arg\key{,} \Var\\
  3679. \key{xorq}~ \key{\$1,} \Var
  3680. \end{array}
  3681. \]
  3682. \begin{figure}[tp]
  3683. \fbox{
  3684. \begin{minipage}{0.96\textwidth}
  3685. \[
  3686. \begin{array}{lcl}
  3687. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3688. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3689. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3690. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3691. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3692. \key{subq} \; \Arg\key{,} \Arg \mid
  3693. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3694. && \gray{ \key{callq} \; \itm{label} \mid
  3695. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3696. && \gray{ \itm{label}\key{:}\; \Instr }
  3697. \mid \key{xorq}~\Arg\key{,}~\Arg
  3698. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3699. && \key{set}cc~\Arg
  3700. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3701. \mid \key{j}cc~\itm{label}
  3702. \\
  3703. x86_1 &::= & \gray{ \key{.globl main} }\\
  3704. & & \gray{ \key{main:} \; \Instr\ldots }
  3705. \end{array}
  3706. \]
  3707. \end{minipage}
  3708. }
  3709. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3710. \label{fig:x86-1-concrete}
  3711. \end{figure}
  3712. \begin{figure}[tp]
  3713. \fbox{
  3714. \begin{minipage}{0.96\textwidth}
  3715. \small
  3716. \[
  3717. \begin{array}{lcl}
  3718. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3719. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3720. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3721. \mid \BYTEREG{\itm{bytereg}} \\
  3722. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3723. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3724. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3725. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3726. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3727. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3728. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3729. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3730. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3731. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3732. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3733. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3734. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3735. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3736. \end{array}
  3737. \]
  3738. \end{minipage}
  3739. }
  3740. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3741. \label{fig:x86-1}
  3742. \end{figure}
  3743. Next we consider the x86 instructions that are relevant for compiling
  3744. the comparison operations. The \key{cmpq} instruction compares its two
  3745. arguments to determine whether one argument is less than, equal, or
  3746. greater than the other argument. The \key{cmpq} instruction is unusual
  3747. regarding the order of its arguments and where the result is
  3748. placed. The argument order is backwards: if you want to test whether
  3749. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3750. \key{cmpq} is placed in the special EFLAGS register. This register
  3751. cannot be accessed directly but it can be queried by a number of
  3752. instructions, including the \key{set} instruction. The \key{set}
  3753. instruction puts a \key{1} or \key{0} into its destination depending
  3754. on whether the comparison came out according to the condition code
  3755. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3756. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3757. The \key{set} instruction has an annoying quirk in that its
  3758. destination argument must be single byte register, such as \code{al},
  3759. which is part of the \code{rax} register. Thankfully, the
  3760. \key{movzbq} instruction can then be used to move from a single byte
  3761. register to a normal 64-bit register.
  3762. The x86 instruction for conditional jump are relevant to the
  3763. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3764. updates the program counter to point to the instruction after the
  3765. indicated label depending on whether the result in the EFLAGS register
  3766. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3767. instruction falls through to the next instruction. The abstract
  3768. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3769. that it separates the instruction name from the condition code. For
  3770. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3771. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3772. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3773. instruction to set the EFLAGS register.
  3774. \section{The $C_1$ Intermediate Language}
  3775. \label{sec:c1}
  3776. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3777. we need to grow that intermediate language to handle the new features
  3778. in $R_2$: Booleans and conditional expressions.
  3779. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3780. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3781. particular, we add logical and comparison operators to the $\Exp$
  3782. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3783. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3784. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3785. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3786. sequence of statements may now end with a \code{goto} or a conditional
  3787. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3788. depending on the outcome of the comparison. In
  3789. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3790. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3791. and \key{goto}'s.
  3792. \begin{figure}[tbp]
  3793. \fbox{
  3794. \begin{minipage}{0.96\textwidth}
  3795. \small
  3796. \[
  3797. \begin{array}{lcl}
  3798. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3799. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3800. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3801. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3802. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3803. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3804. \mid \key{goto}~\itm{label}\key{;}\\
  3805. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3806. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  3807. \end{array}
  3808. \]
  3809. \end{minipage}
  3810. }
  3811. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3812. \label{fig:c1-concrete-syntax}
  3813. \end{figure}
  3814. \begin{figure}[tp]
  3815. \fbox{
  3816. \begin{minipage}{0.96\textwidth}
  3817. \small
  3818. \[
  3819. \begin{array}{lcl}
  3820. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3821. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3822. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3823. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3824. &\mid& \UNIOP{\key{'not}}{\Atm}
  3825. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3826. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3827. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3828. \mid \GOTO{\itm{label}} \\
  3829. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3830. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  3831. \end{array}
  3832. \]
  3833. \end{minipage}
  3834. }
  3835. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  3836. (Figure~\ref{fig:c0-syntax}).}
  3837. \label{fig:c1-syntax}
  3838. \end{figure}
  3839. \section{Explicate Control}
  3840. \label{sec:explicate-control-r2}
  3841. Recall that the purpose of \code{explicate-control} is to make the
  3842. order of evaluation explicit in the syntax of the program. With the
  3843. addition of \key{if} in $R_2$ this get more interesting.
  3844. As a motivating example, consider the following program that has an
  3845. \key{if} expression nested in the predicate of another \key{if}.
  3846. % s1_41.rkt
  3847. \begin{center}
  3848. \begin{minipage}{0.96\textwidth}
  3849. \begin{lstlisting}
  3850. (let ([x (read)])
  3851. (let ([y (read)])
  3852. (if (if (< x 1) (eq? x 0) (eq? x 2))
  3853. (+ y 2)
  3854. (+ y 10))))
  3855. \end{lstlisting}
  3856. \end{minipage}
  3857. \end{center}
  3858. %
  3859. The naive way to compile \key{if} and the comparison would be to
  3860. handle each of them in isolation, regardless of their context. Each
  3861. comparison would be translated into a \key{cmpq} instruction followed
  3862. by a couple instructions to move the result from the EFLAGS register
  3863. into a general purpose register or stack location. Each \key{if} would
  3864. be translated into the combination of a \key{cmpq} and a conditional
  3865. jump. The generated code for the inner \key{if} in the above example
  3866. would be as follows.
  3867. \begin{center}
  3868. \begin{minipage}{0.96\textwidth}
  3869. \begin{lstlisting}
  3870. ...
  3871. cmpq $1, x ;; (< x 1)
  3872. setl %al
  3873. movzbq %al, tmp
  3874. cmpq $1, tmp ;; (if (< x 1) ...)
  3875. je then_branch_1
  3876. jmp else_branch_1
  3877. ...
  3878. \end{lstlisting}
  3879. \end{minipage}
  3880. \end{center}
  3881. However, if we take context into account we can do better and reduce
  3882. the use of \key{cmpq} and EFLAG-accessing instructions.
  3883. One idea is to try and reorganize the code at the level of $R_2$,
  3884. pushing the outer \key{if} inside the inner one. This would yield the
  3885. following code.
  3886. \begin{center}
  3887. \begin{minipage}{0.96\textwidth}
  3888. \begin{lstlisting}
  3889. (let ([x (read)])
  3890. (let ([y (read)])
  3891. (if (< x 1)
  3892. (if (eq? x 0)
  3893. (+ y 2)
  3894. (+ y 10))
  3895. (if (eq? x 2)
  3896. (+ y 2)
  3897. (+ y 10)))))
  3898. \end{lstlisting}
  3899. \end{minipage}
  3900. \end{center}
  3901. Unfortunately, this approach duplicates the two branches, and a
  3902. compiler must never duplicate code!
  3903. We need a way to perform the above transformation, but without
  3904. duplicating code. The solution is straightforward if we think at the
  3905. level of x86 assembly: we can label the code for each of the branches
  3906. and insert jumps in all the places that need to execute the
  3907. branches. Put another way, we need to move away from abstract syntax
  3908. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3909. use a standard program representation called a \emph{control flow
  3910. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3911. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3912. each edge represents a jump to another block. The \key{Program}
  3913. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3914. as an alist mapping labels to basic blocks. Each basic block is
  3915. represented by the $\Tail$ non-terminal.
  3916. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3917. \code{remove-complex-opera*} pass and then the
  3918. \code{explicate-control} pass on the example program. We walk through
  3919. the output program and then discuss the algorithm.
  3920. %
  3921. Following the order of evaluation in the output of
  3922. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  3923. and then the less-than-comparison to \code{1} in the predicate of the
  3924. inner \key{if}. In the output of \code{explicate-control}, in the
  3925. block labeled \code{start}, this becomes two assignment statements
  3926. followed by a conditional \key{goto} to label \code{block96} or
  3927. \code{block97}. The blocks associated with those labels contain the
  3928. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  3929. respectively. Regarding the block labeled with \code{block96}, we
  3930. start with the comparison to \code{0} and then have a conditional
  3931. goto, either to label \code{block92} or label \code{block93}, which
  3932. indirectly take us to labels \code{block90} and \code{block91}, the
  3933. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  3934. y 10)}. The story for the block labeled \code{block97} is similar.
  3935. \begin{figure}[tbp]
  3936. \begin{tabular}{lll}
  3937. \begin{minipage}{0.4\textwidth}
  3938. % s1_41.rkt
  3939. \begin{lstlisting}
  3940. (let ([x (read)])
  3941. (let ([y (read)])
  3942. (if (if (< x 1)
  3943. (eq? x 0)
  3944. (eq? x 2))
  3945. (+ y 2)
  3946. (+ y 10))))
  3947. \end{lstlisting}
  3948. \hspace{40pt}$\Downarrow$
  3949. \begin{lstlisting}
  3950. (let ([x (read)])
  3951. (let ([y (read)])
  3952. (if (if (< x 1)
  3953. (eq? x 0)
  3954. (eq? x 2))
  3955. (+ y 2)
  3956. (+ y 10))))
  3957. \end{lstlisting}
  3958. \end{minipage}
  3959. &
  3960. $\Rightarrow$
  3961. &
  3962. \begin{minipage}{0.55\textwidth}
  3963. \begin{lstlisting}
  3964. start:
  3965. x = (read);
  3966. y = (read);
  3967. if (< x 1)
  3968. goto block96;
  3969. else
  3970. goto block97;
  3971. block96:
  3972. if (eq? x 0)
  3973. goto block92;
  3974. else
  3975. goto block93;
  3976. block97:
  3977. if (eq? x 2)
  3978. goto block94;
  3979. else
  3980. goto block95;
  3981. block92:
  3982. goto block90;
  3983. block93:
  3984. goto block91;
  3985. block94:
  3986. goto block90;
  3987. block95:
  3988. goto block91;
  3989. block90:
  3990. return (+ y 2);
  3991. block91:
  3992. return (+ y 10);
  3993. \end{lstlisting}
  3994. \end{minipage}
  3995. \end{tabular}
  3996. \caption{Example translation from $R_2$ to $C_1$
  3997. via the \code{explicate-control}.}
  3998. \label{fig:explicate-control-s1-38}
  3999. \end{figure}
  4000. The nice thing about the output of \code{explicate-control} is that
  4001. there are no unnecessary comparisons and every comparison is part of a
  4002. conditional jump. The down-side of this output is that it includes
  4003. trivial blocks, such as the blocks labeled \code{block92} through
  4004. \code{block95}, that only jump to another block. We discuss a solution
  4005. to this problem in Section~\ref{sec:opt-jumps}.
  4006. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4007. \code{explicate-control} for $R_1$ using two mutually recursive
  4008. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4009. former function translates expressions in tail position whereas the
  4010. later function translates expressions on the right-hand-side of a
  4011. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4012. new kind of context to deal with: the predicate position of the
  4013. \key{if}. We need another function, \code{explicate-pred}, that takes
  4014. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4015. the then-branch and else-branch. The output of \code{explicate-pred}
  4016. is a block and a list of formerly \key{let}-bound variables.
  4017. Note that the three explicate functions need to construct a
  4018. control-flow graph, which we recommend they do via updates to a global
  4019. variable.
  4020. In the following paragraphs we consider the specific additions to the
  4021. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4022. of cases for the \code{explicate-pred} function.
  4023. The \code{explicate-tail} function needs an additional case for
  4024. \key{if}. The branches of the \key{if} inherit the current context, so
  4025. they are in tail position. Let $B_1$ be the result of
  4026. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4027. is a $\Tail$ AST node. Let $B_2$ be the result of apply
  4028. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4029. the $\Tail$ that results fromapplying \code{explicate-pred} to the
  4030. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4031. \key{if} as a whole translates to block $B_3$.
  4032. \[
  4033. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4034. \]
  4035. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4036. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4037. should not be confused with the labels for the blocks that appear in
  4038. the generated code. We initially construct unlabeled blocks; we only
  4039. attach labels to blocks when we add them to the control-flow graph, as
  4040. we shall see in the next case.
  4041. Next consider the case for \key{if} in the \code{explicate-assign}
  4042. function. The context of the \key{if} is an assignment to some
  4043. variable $x$ and then the control continues to some block $B_1$. The
  4044. code that we generate for both the ``then'' and ``else'' branches
  4045. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4046. add it to the control flow graph with a fresh label $\ell_1$. The
  4047. branches of the \key{if} inherit the current context, so that are in
  4048. assignment positions. Let $B_2$ be the result of applying
  4049. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4050. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4051. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4052. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4053. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4054. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4055. $B_4$.
  4056. \[
  4057. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4058. \]
  4059. The function \code{explicate-pred} will need a case for every
  4060. expression that can have type \code{Boolean}. We detail a few cases
  4061. here and leave the rest for the reader. The input to this function is
  4062. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4063. the enclosing \key{if}. Suppose the expression is the Boolean
  4064. \code{\#t}. Then we can perform a kind of partial evaluation and
  4065. translate it to the ``then'' branch $B_1$. Likewise, we translate
  4066. \code{\#f} to the ``else`` branch $B_2$.
  4067. \[
  4068. \key{\#t} \quad\Rightarrow\quad B_1,
  4069. \qquad\qquad\qquad
  4070. \key{\#f} \quad\Rightarrow\quad B_2
  4071. \]
  4072. Next, suppose the expression is a less-than comparison. We translate
  4073. it to a conditional \code{goto}. We need labels for the two branches
  4074. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4075. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4076. less-than comparison is as follows.
  4077. \[
  4078. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4079. \begin{array}{l}
  4080. \key{if}~(\key{<}~e_1~e_2) \\
  4081. \qquad\key{goto}~\ell_1\key{;}\\
  4082. \key{else}\\
  4083. \qquad\key{goto}~\ell_2\key{;}
  4084. \end{array}
  4085. \]
  4086. The case for \key{if} in \code{explicate-pred} is particularly
  4087. illuminating as it deals with the challenges that we discussed above
  4088. regarding the example of the nested \key{if} expressions. Again, we
  4089. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4090. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4091. branches of the current \key{if} inherit their context from the
  4092. current one, that is, predicate context. So we apply
  4093. \code{explicate-pred} to the ``then'' branch with the two blocks
  4094. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4095. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4096. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4097. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4098. \[
  4099. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4100. \quad\Rightarrow\quad
  4101. B_5
  4102. \]
  4103. \begin{exercise}\normalfont
  4104. Implement the pass \code{explicate-control} by adding the cases for
  4105. \key{if} to the functions for tail and assignment contexts, and
  4106. implement \code{explicate-pred} for predicate contexts. Create test
  4107. cases that exercise all of the new cases in the code for this pass.
  4108. \end{exercise}
  4109. \section{Select Instructions}
  4110. \label{sec:select-r2}
  4111. Recall that the \code{select-instructions} pass lowers from our
  4112. $C$-like intermediate representation to the pseudo-x86 language, which
  4113. is suitable for conducting register allocation. The pass is
  4114. implemented using three auxiliary functions, one for each of the
  4115. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4116. For $\Atm$, we have new cases for the Booleans. We take the usual
  4117. approach of encoding them as integers, with true as 1 and false as 0.
  4118. \[
  4119. \key{\#t} \Rightarrow \key{1}
  4120. \qquad
  4121. \key{\#f} \Rightarrow \key{0}
  4122. \]
  4123. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4124. be implemented in terms of \code{xorq} as we discussed at the
  4125. beginning of this section. Given an assignment
  4126. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4127. if the left-hand side $\itm{var}$ is
  4128. the same as $\Atm$, then just the \code{xorq} suffices.
  4129. \[
  4130. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4131. \quad\Rightarrow\quad
  4132. \key{xorq}~\key{\$}1\key{,}~\Var
  4133. \]
  4134. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4135. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4136. x86. Then we have
  4137. \[
  4138. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4139. \quad\Rightarrow\quad
  4140. \begin{array}{l}
  4141. \key{movq}~\Arg\key{,}~\Var\\
  4142. \key{xorq}~\key{\$}1\key{,}~\Var
  4143. \end{array}
  4144. \]
  4145. Next consider the cases for \code{eq?} and less-than comparison.
  4146. Translating these operations to x86 is slightly involved due to the
  4147. unusual nature of the \key{cmpq} instruction discussed above. We
  4148. recommend translating an assignment from \code{eq?} into the following
  4149. sequence of three instructions. \\
  4150. \begin{tabular}{lll}
  4151. \begin{minipage}{0.4\textwidth}
  4152. \begin{lstlisting}
  4153. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4154. \end{lstlisting}
  4155. \end{minipage}
  4156. &
  4157. $\Rightarrow$
  4158. &
  4159. \begin{minipage}{0.4\textwidth}
  4160. \begin{lstlisting}
  4161. cmpq |$\Arg_2$|, |$\Arg_1$|
  4162. sete %al
  4163. movzbq %al, |$\Var$|
  4164. \end{lstlisting}
  4165. \end{minipage}
  4166. \end{tabular} \\
  4167. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4168. and conditional \key{goto}. Both are straightforward to handle. A
  4169. \key{goto} becomes a jump instruction.
  4170. \[
  4171. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4172. \]
  4173. A conditional \key{goto} becomes a compare instruction followed
  4174. by a conditional jump (for ``then'') and the fall-through is
  4175. to a regular jump (for ``else'').\\
  4176. \begin{tabular}{lll}
  4177. \begin{minipage}{0.4\textwidth}
  4178. \begin{lstlisting}
  4179. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4180. goto |$\ell_1$|;
  4181. else
  4182. goto |$\ell_2$|;
  4183. \end{lstlisting}
  4184. \end{minipage}
  4185. &
  4186. $\Rightarrow$
  4187. &
  4188. \begin{minipage}{0.4\textwidth}
  4189. \begin{lstlisting}
  4190. cmpq |$\Arg_2$|, |$\Arg_1$|
  4191. je |$\ell_1$|
  4192. jmp |$\ell_2$|
  4193. \end{lstlisting}
  4194. \end{minipage}
  4195. \end{tabular} \\
  4196. \begin{exercise}\normalfont
  4197. Expand your \code{select-instructions} pass to handle the new features
  4198. of the $R_2$ language. Test the pass on all the examples you have
  4199. created and make sure that you have some test programs that use the
  4200. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4201. the output using the \code{interp-x86} interpreter
  4202. (Appendix~\ref{appendix:interp}).
  4203. \end{exercise}
  4204. \section{Register Allocation}
  4205. \label{sec:register-allocation-r2}
  4206. The changes required for $R_2$ affect liveness analysis, building the
  4207. interference graph, and assigning homes, but the graph coloring
  4208. algorithm itself does not change.
  4209. \subsection{Liveness Analysis}
  4210. \label{sec:liveness-analysis-r2}
  4211. Recall that for $R_1$ we implemented liveness analysis for a single
  4212. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4213. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4214. produces many basic blocks arranged in a control-flow graph. The first
  4215. question we need to consider is: what order should we process the
  4216. basic blocks? Recall that to perform liveness analysis, we need to
  4217. know the live-after set. If a basic block has no successor blocks
  4218. (i.e. no out-edges in the control flow graph), then it has an empty
  4219. live-after set and we can immediately apply liveness analysis to
  4220. it. If a basic block has some successors, then we need to complete
  4221. liveness analysis on those blocks first. Furthermore, we know that
  4222. the control flow graph does not contain any cycles because $R_2$ does
  4223. not include loops
  4224. %
  4225. \footnote{If we were to add loops to the language, then the CFG could
  4226. contain cycles and we would instead need to use the classic worklist
  4227. algorithm for computing the fixed point of the liveness
  4228. analysis~\citep{Aho:1986qf}.}.
  4229. %
  4230. Returning to the question of what order should we process the basic
  4231. blocks, the answer is reverse topological order. We recommend using
  4232. the \code{tsort} (topological sort) and \code{transpose} functions of
  4233. the Racket \code{graph} package to obtain this ordering.
  4234. The next question is how to compute the live-after set of a block
  4235. given the live-before sets of all its successor blocks. (There can be
  4236. more than one because of conditional jumps.) During compilation we do
  4237. not know which way a conditional jump will go, so we do not know which
  4238. of the successor's live-before set to use. The solution to this
  4239. challenge is based on the observation that there is no harm to the
  4240. correctness of the compiler if we classify more variables as live than
  4241. the ones that are truly live during a particular execution of the
  4242. block. Thus, we can take the union of the live-before sets from all
  4243. the successors to be the live-after set for the block. Once we have
  4244. computed the live-after set, we can proceed to perform liveness
  4245. analysis on the block just as we did in
  4246. Section~\ref{sec:liveness-analysis-r1}.
  4247. The helper functions for computing the variables in an instruction's
  4248. argument and for computing the variables read-from ($R$) or written-to
  4249. ($W$) by an instruction need to be updated to handle the new kinds of
  4250. arguments and instructions in x86$_1$.
  4251. \subsection{Build Interference}
  4252. \label{sec:build-interference-r2}
  4253. Many of the new instructions in x86$_1$ can be handled in the same way
  4254. as the instructions in x86$_0$. Thus, if your code was already quite
  4255. general, it will not need to be changed to handle the new
  4256. instructions. If you code is not general enough, I recommend that you
  4257. change your code to be more general. For example, you can factor out
  4258. the computing of the the read and write sets for each kind of
  4259. instruction into two auxiliary functions.
  4260. Note that the \key{movzbq} instruction requires some special care,
  4261. just like the \key{movq} instruction. See rule number 3 in
  4262. Section~\ref{sec:build-interference}.
  4263. %% \subsection{Assign Homes}
  4264. %% \label{sec:assign-homes-r2}
  4265. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4266. %% to be updated to handle the \key{if} statement, simply by recursively
  4267. %% processing the child nodes. Hopefully your code already handles the
  4268. %% other new instructions, but if not, you can generalize your code.
  4269. \begin{exercise}\normalfont
  4270. Update the \code{register-allocation} pass so that it works for $R_2$
  4271. and test your compiler using your previously created programs on the
  4272. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4273. \end{exercise}
  4274. \section{Patch Instructions}
  4275. The second argument of the \key{cmpq} instruction must not be an
  4276. immediate value (such as an integer). So if you are comparing two
  4277. immediates, we recommend inserting a \key{movq} instruction to put the
  4278. second argument in \key{rax}.
  4279. %
  4280. The second argument of the \key{movzbq} must be a register.
  4281. %
  4282. There are no special restrictions on the x86 instructions \key{JmpIf}
  4283. and \key{Jmp}.
  4284. \begin{exercise}\normalfont
  4285. Update \code{patch-instructions} to handle the new x86 instructions.
  4286. Test your compiler using your previously created programs on the
  4287. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4288. \end{exercise}
  4289. \section{An Example Translation}
  4290. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4291. $R_2$ translated to x86, showing the results of
  4292. \code{explicate-control}, \code{select-instructions}, and the final
  4293. x86 assembly code.
  4294. \begin{figure}[tbp]
  4295. \begin{tabular}{lll}
  4296. \begin{minipage}{0.5\textwidth}
  4297. % s1_20.rkt
  4298. \begin{lstlisting}
  4299. (if (eq? (read) 1) 42 0)
  4300. \end{lstlisting}
  4301. $\Downarrow$
  4302. \begin{lstlisting}
  4303. start:
  4304. tmp7951 = (read);
  4305. if (eq? tmp7951 1) then
  4306. goto block7952;
  4307. else
  4308. goto block7953;
  4309. block7952:
  4310. return 42;
  4311. block7953:
  4312. return 0;
  4313. \end{lstlisting}
  4314. $\Downarrow$
  4315. \begin{lstlisting}
  4316. start:
  4317. callq read_int
  4318. movq %rax, tmp7951
  4319. cmpq $1, tmp7951
  4320. je block7952
  4321. jmp block7953
  4322. block7953:
  4323. movq $0, %rax
  4324. jmp conclusion
  4325. block7952:
  4326. movq $42, %rax
  4327. jmp conclusion
  4328. \end{lstlisting}
  4329. \end{minipage}
  4330. &
  4331. $\Rightarrow\qquad$
  4332. \begin{minipage}{0.4\textwidth}
  4333. \begin{lstlisting}
  4334. start:
  4335. callq read_int
  4336. movq %rax, %rcx
  4337. cmpq $1, %rcx
  4338. je block7952
  4339. jmp block7953
  4340. block7953:
  4341. movq $0, %rax
  4342. jmp conclusion
  4343. block7952:
  4344. movq $42, %rax
  4345. jmp conclusion
  4346. .globl main
  4347. main:
  4348. pushq %rbp
  4349. movq %rsp, %rbp
  4350. pushq %r13
  4351. pushq %r12
  4352. pushq %rbx
  4353. pushq %r14
  4354. subq $0, %rsp
  4355. jmp start
  4356. conclusion:
  4357. addq $0, %rsp
  4358. popq %r14
  4359. popq %rbx
  4360. popq %r12
  4361. popq %r13
  4362. popq %rbp
  4363. retq
  4364. \end{lstlisting}
  4365. \end{minipage}
  4366. \end{tabular}
  4367. \caption{Example compilation of an \key{if} expression to x86.}
  4368. \label{fig:if-example-x86}
  4369. \end{figure}
  4370. \begin{figure}[p]
  4371. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4372. \node (R2) at (0,2) {\large $R_2$};
  4373. \node (R2-2) at (3,2) {\large $R_2$};
  4374. \node (R2-3) at (6,2) {\large $R_2$};
  4375. \node (R2-4) at (9,2) {\large $R_2$};
  4376. \node (R2-5) at (9,0) {\large $R_2$};
  4377. \node (C1-1) at (3,-2) {\large $C_1$};
  4378. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4379. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4380. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4381. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4382. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4383. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4384. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4385. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4386. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4387. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4388. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4389. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4390. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4391. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4392. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4393. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4394. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4395. \end{tikzpicture}
  4396. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4397. \label{fig:R2-passes}
  4398. \end{figure}
  4399. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4400. compilation of $R_2$.
  4401. \section{Challenge: Optimize and Remove Jumps}
  4402. \label{sec:opt-jumps}
  4403. Recall that in the example output of \code{explicate-control} in
  4404. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4405. \code{block60} are trivial blocks, they do nothing but jump to another
  4406. block. The first goal of this challenge assignment is to remove those
  4407. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4408. \code{explicate-control} on the left and shows the result of bypassing
  4409. the trivial blocks on the right. Let us focus on \code{block61}. The
  4410. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4411. \code{block55}. The optimized code on the right of
  4412. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4413. \code{then} branch jumping directly to \code{block55}. The story is
  4414. similar for the \code{else} branch, as well as for the two branches in
  4415. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4416. have been optimized in this way, there are no longer any jumps to
  4417. blocks \code{block57} through \code{block60}, so they can be removed.
  4418. \begin{figure}[tbp]
  4419. \begin{tabular}{lll}
  4420. \begin{minipage}{0.4\textwidth}
  4421. \begin{lstlisting}
  4422. block62:
  4423. tmp54 = (read);
  4424. if (eq? tmp54 2) then
  4425. goto block59;
  4426. else
  4427. goto block60;
  4428. block61:
  4429. tmp53 = (read);
  4430. if (eq? tmp53 0) then
  4431. goto block57;
  4432. else
  4433. goto block58;
  4434. block60:
  4435. goto block56;
  4436. block59:
  4437. goto block55;
  4438. block58:
  4439. goto block56;
  4440. block57:
  4441. goto block55;
  4442. block56:
  4443. return (+ 700 77);
  4444. block55:
  4445. return (+ 10 32);
  4446. start:
  4447. tmp52 = (read);
  4448. if (eq? tmp52 1) then
  4449. goto block61;
  4450. else
  4451. goto block62;
  4452. \end{lstlisting}
  4453. \end{minipage}
  4454. &
  4455. $\Rightarrow$
  4456. &
  4457. \begin{minipage}{0.55\textwidth}
  4458. \begin{lstlisting}
  4459. block62:
  4460. tmp54 = (read);
  4461. if (eq? tmp54 2) then
  4462. goto block55;
  4463. else
  4464. goto block56;
  4465. block61:
  4466. tmp53 = (read);
  4467. if (eq? tmp53 0) then
  4468. goto block55;
  4469. else
  4470. goto block56;
  4471. block56:
  4472. return (+ 700 77);
  4473. block55:
  4474. return (+ 10 32);
  4475. start:
  4476. tmp52 = (read);
  4477. if (eq? tmp52 1) then
  4478. goto block61;
  4479. else
  4480. goto block62;
  4481. \end{lstlisting}
  4482. \end{minipage}
  4483. \end{tabular}
  4484. \caption{Optimize jumps by removing trivial blocks.}
  4485. \label{fig:optimize-jumps}
  4486. \end{figure}
  4487. The name of this pass is \code{optimize-jumps}. We recommend
  4488. implementing this pass in two phases. The first phrase builds a hash
  4489. table that maps labels to possibly improved labels. The second phase
  4490. changes the target of each \code{goto} to use the improved label. If
  4491. the label is for a trivial block, then the hash table should map the
  4492. label to the first non-trivial block that can be reached from this
  4493. label by jumping through trivial blocks. If the label is for a
  4494. non-trivial block, then the hash table should map the label to itself;
  4495. we do not want to change jumps to non-trivial blocks.
  4496. The first phase can be accomplished by constructing an empty hash
  4497. table, call it \code{short-cut}, and then iterating over the control
  4498. flow graph. Each time you encouter a block that is just a \code{goto},
  4499. then update the hash table, mapping the block's source to the target
  4500. of the \code{goto}. Also, the hash table may already have mapped some
  4501. labels to the block's source, to you must iterate through the hash
  4502. table and update all of those so that they instead map to the target
  4503. of the \code{goto}.
  4504. For the second phase, we recommend iterating through the $\Tail$ of
  4505. each block in the program, updating the target of every \code{goto}
  4506. according to the mapping in \code{short-cut}.
  4507. \begin{exercise}\normalfont
  4508. Implement the \code{optimize-jumps} pass as a transformation from
  4509. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4510. Check that \code{optimize-jumps} removes trivial blocks in a few
  4511. example programs. Then check that your compiler still passes all of
  4512. your tests.
  4513. \end{exercise}
  4514. There is another opportunity for optimizing jumps that is apparent in
  4515. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4516. end with a jump to \code{block7953} and there are no other jumps to
  4517. \code{block7953} in the rest of the program. In this situation we can
  4518. avoid the runtime overhead of this jump by merging \code{block7953}
  4519. into the preceeding block, in this case the \code{start} block.
  4520. Figure~\ref{fig:remove-jumps} shows the output of
  4521. \code{select-instructions} on the left and the result of this
  4522. optimization on the right.
  4523. \begin{figure}[tbp]
  4524. \begin{tabular}{lll}
  4525. \begin{minipage}{0.5\textwidth}
  4526. % s1_20.rkt
  4527. \begin{lstlisting}
  4528. start:
  4529. callq read_int
  4530. movq %rax, tmp7951
  4531. cmpq $1, tmp7951
  4532. je block7952
  4533. jmp block7953
  4534. block7953:
  4535. movq $0, %rax
  4536. jmp conclusion
  4537. block7952:
  4538. movq $42, %rax
  4539. jmp conclusion
  4540. \end{lstlisting}
  4541. \end{minipage}
  4542. &
  4543. $\Rightarrow\qquad$
  4544. \begin{minipage}{0.4\textwidth}
  4545. \begin{lstlisting}
  4546. start:
  4547. callq read_int
  4548. movq %rax, tmp7951
  4549. cmpq $1, tmp7951
  4550. je block7952
  4551. movq $0, %rax
  4552. jmp conclusion
  4553. block7952:
  4554. movq $42, %rax
  4555. jmp conclusion
  4556. \end{lstlisting}
  4557. \end{minipage}
  4558. \end{tabular}
  4559. \caption{Merging basic blocks by removing unnecessary jumps.}
  4560. \label{fig:remove-jumps}
  4561. \end{figure}
  4562. \begin{exercise}\normalfont
  4563. Implement a pass named \code{remove-jumps} that merges basic blocks
  4564. into their preceeding basic block, when there is only one preceeding
  4565. block. The pass should translate from psuedo $x86_1$ to pseudo
  4566. $x86_1$ and it should come immediately after
  4567. \code{select-instructions}. Check that \code{remove-jumps}
  4568. accomplishes the goal of merging basic blocks on several test
  4569. programs and check that your compiler passes all of your tests.
  4570. \end{exercise}
  4571. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4572. \chapter{Tuples and Garbage Collection}
  4573. \label{ch:tuples}
  4574. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4575. add simple structures. \\ --Jeremy}
  4576. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4577. things to discuss in this chapter. \\ --Jeremy}
  4578. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4579. all the IR grammars are spelled out! \\ --Jeremy}
  4580. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4581. but keep type annotations on vector creation and local variables, function
  4582. parameters, etc. \\ --Jeremy}
  4583. \margincomment{\scriptsize Be more explicit about how to deal with
  4584. the root stack. \\ --Jeremy}
  4585. In this chapter we study the implementation of mutable tuples (called
  4586. ``vectors'' in Racket). This language feature is the first to use the
  4587. computer's \emph{heap} because the lifetime of a Racket tuple is
  4588. indefinite, that is, a tuple lives forever from the programmer's
  4589. viewpoint. Of course, from an implementer's viewpoint, it is important
  4590. to reclaim the space associated with a tuple when it is no longer
  4591. needed, which is why we also study \emph{garbage collection}
  4592. techniques in this chapter.
  4593. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4594. interpreter and type checker. The $R_3$ language extends the $R_2$
  4595. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4596. \code{void} value. The reason for including the later is that the
  4597. \code{vector-set!} operation returns a value of type
  4598. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4599. called the \code{Unit} type in the programming languages
  4600. literature. Racket's \code{Void} type is inhabited by a single value
  4601. \code{void} which corresponds to \code{unit} or \code{()} in the
  4602. literature~\citep{Pierce:2002hj}.}.
  4603. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4604. copying live objects back and forth between two halves of the
  4605. heap. The garbage collector requires coordination with the compiler so
  4606. that it can see all of the \emph{root} pointers, that is, pointers in
  4607. registers or on the procedure call stack.
  4608. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4609. discuss all the necessary changes and additions to the compiler
  4610. passes, including a new compiler pass named \code{expose-allocation}.
  4611. \section{The $R_3$ Language}
  4612. \label{sec:r3}
  4613. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4614. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4615. $R_3$ language includes three new forms: \code{vector} for creating a
  4616. tuple, \code{vector-ref} for reading an element of a tuple, and
  4617. \code{vector-set!} for writing to an element of a tuple. The program
  4618. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4619. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4620. the 3-tuple, demonstrating that tuples are first-class values. The
  4621. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4622. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4623. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4624. 1-tuple. So the result of the program is \code{42}.
  4625. \begin{figure}[tbp]
  4626. \centering
  4627. \fbox{
  4628. \begin{minipage}{0.96\textwidth}
  4629. \[
  4630. \begin{array}{lcl}
  4631. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4632. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4633. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4634. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4635. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4636. \mid (\key{and}\;\Exp\;\Exp)
  4637. \mid (\key{or}\;\Exp\;\Exp)
  4638. \mid (\key{not}\;\Exp) } \\
  4639. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4640. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4641. &\mid& (\key{vector}\;\Exp\ldots)
  4642. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4643. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4644. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4645. R_3 &::=& \Exp
  4646. \end{array}
  4647. \]
  4648. \end{minipage}
  4649. }
  4650. \caption{The concrete syntax of $R_3$, extending $R_2$
  4651. (Figure~\ref{fig:r2-concrete-syntax}).}
  4652. \label{fig:r3-concrete-syntax}
  4653. \end{figure}
  4654. \begin{figure}[tbp]
  4655. \begin{lstlisting}
  4656. (let ([t (vector 40 #t (vector 2))])
  4657. (if (vector-ref t 1)
  4658. (+ (vector-ref t 0)
  4659. (vector-ref (vector-ref t 2) 0))
  4660. 44))
  4661. \end{lstlisting}
  4662. \caption{Example program that creates tuples and reads from them.}
  4663. \label{fig:vector-eg}
  4664. \end{figure}
  4665. \begin{figure}[tp]
  4666. \centering
  4667. \fbox{
  4668. \begin{minipage}{0.96\textwidth}
  4669. \[
  4670. \begin{array}{lcl}
  4671. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4672. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4673. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4674. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4675. &\mid& \gray{ \BOOL{\itm{bool}}
  4676. \mid \AND{\Exp}{\Exp} }\\
  4677. &\mid& \gray{ \OR{\Exp}{\Exp}
  4678. \mid \NOT{\Exp} } \\
  4679. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  4680. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4681. &\mid& \VECTOR{\Exp} \\
  4682. &\mid& \VECREF{\Exp}{\Int}\\
  4683. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4684. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  4685. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4686. \end{array}
  4687. \]
  4688. \end{minipage}
  4689. }
  4690. \caption{The abstract syntax of $R_3$.}
  4691. \label{fig:r3-syntax}
  4692. \end{figure}
  4693. Tuples are our first encounter with heap-allocated data, which raises
  4694. several interesting issues. First, variable binding performs a
  4695. shallow-copy when dealing with tuples, which means that different
  4696. variables can refer to the same tuple, that is, different variables
  4697. can be \emph{aliases} for the same entity. Consider the following
  4698. example in which both \code{t1} and \code{t2} refer to the same tuple.
  4699. Thus, the mutation through \code{t2} is visible when referencing the
  4700. tuple from \code{t1}, so the result of this program is \code{42}.
  4701. \begin{center}
  4702. \begin{minipage}{0.96\textwidth}
  4703. \begin{lstlisting}
  4704. (let ([t1 (vector 3 7)])
  4705. (let ([t2 t1])
  4706. (let ([_ (vector-set! t2 0 42)])
  4707. (vector-ref t1 0))))
  4708. \end{lstlisting}
  4709. \end{minipage}
  4710. \end{center}
  4711. The next issue concerns the lifetime of tuples. Of course, they are
  4712. created by the \code{vector} form, but when does their lifetime end?
  4713. Notice that $R_3$ does not include an operation for deleting
  4714. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  4715. of static scoping. For example, the following program returns
  4716. \code{42} even though the variable \code{w} goes out of scope prior to
  4717. the \code{vector-ref} that reads from the vector it was bound to.
  4718. \begin{center}
  4719. \begin{minipage}{0.96\textwidth}
  4720. \begin{lstlisting}
  4721. (let ([v (vector (vector 44))])
  4722. (let ([x (let ([w (vector 42)])
  4723. (let ([_ (vector-set! v 0 w)])
  4724. 0))])
  4725. (+ x (vector-ref (vector-ref v 0) 0))))
  4726. \end{lstlisting}
  4727. \end{minipage}
  4728. \end{center}
  4729. From the perspective of programmer-observable behavior, tuples live
  4730. forever. Of course, if they really lived forever, then many programs
  4731. would run out of memory.\footnote{The $R_3$ language does not have
  4732. looping or recursive functions, so it is nigh impossible to write a
  4733. program in $R_3$ that will run out of memory. However, we add
  4734. recursive functions in the next Chapter!} A Racket implementation
  4735. must therefore perform automatic garbage collection.
  4736. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4737. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4738. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4739. operations in Racket. One subtle point is that the \code{vector-set!}
  4740. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4741. can be passed around just like other values inside an $R_3$ program
  4742. and a \code{\#<void>} value can be compared for equality with another
  4743. \code{\#<void>} value. However, there are no other operations specific
  4744. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  4745. the \code{void?} predicate that returns \code{\#t} when applied to
  4746. \code{\#<void>} and \code{\#f} otherwise.
  4747. \begin{figure}[tbp]
  4748. \begin{lstlisting}
  4749. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4750. (define (interp-op op)
  4751. (match op
  4752. ...
  4753. ['vector vector]
  4754. ['vector-ref vector-ref]
  4755. ['vector-set! vector-set!]
  4756. [else (error 'interp-op "unknown operator")]))
  4757. (define (interp-exp env)
  4758. (lambda (e)
  4759. (define recur (interp-exp env))
  4760. (match e
  4761. ...
  4762. )))
  4763. (define (interp-R3 p)
  4764. (match p
  4765. [(Program '() e)
  4766. ((interp-exp '()) e)]
  4767. ))
  4768. \end{lstlisting}
  4769. \caption{Interpreter for the $R_3$ language.}
  4770. \label{fig:interp-R3}
  4771. \end{figure}
  4772. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4773. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4774. need to know which variables contain pointers into the heap, that is,
  4775. which variables contain vectors. Also, when allocating a vector, we
  4776. need to know which elements of the vector are pointers. We can obtain
  4777. this information during type checking. The type checker in
  4778. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4779. expression, it also wraps every sub-expression $e$ with the form
  4780. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4781. Subsequently, in the \code{uncover-locals} pass
  4782. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4783. propagated to all variables (including the temporaries generated by
  4784. \code{remove-complex-opera*}).
  4785. \begin{figure}[hb]
  4786. \begin{lstlisting}
  4787. (define (type-check-exp env)
  4788. (lambda (e)
  4789. (define recur (type-check-exp env))
  4790. (match e
  4791. ...
  4792. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4793. [(Prim 'vector es)
  4794. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  4795. (let ([t `(Vector ,@t*)])
  4796. (values (HasType (Prim 'vector e*) t) t))]
  4797. [(Prim 'vector-ref (list e (Int i)))
  4798. (define-values (e^ t) (recur e))
  4799. (match t
  4800. [`(Vector ,ts ...)
  4801. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4802. (error 'type-check-exp "invalid index ~a" i))
  4803. (let ([t (list-ref ts i)])
  4804. (values
  4805. (HasType (Prim 'vector-ref
  4806. (list e^ (HasType (Int i) 'Integer)))
  4807. t)
  4808. t))]
  4809. [else (error "expected a vector in vector-ref, not" t)])]
  4810. [(Prim 'eq? (list e1 e2))
  4811. (define-values (e1^ T1) (recur e1))
  4812. (define-values (e2^ T2) (recur e2))
  4813. (unless (equal? T1 T2)
  4814. (error "arguments of eq? must have the same type, but are not"
  4815. (list T1 T2)))
  4816. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4817. ...
  4818. )))
  4819. \end{lstlisting}
  4820. \caption{Type checker for the $R_3$ language.}
  4821. \label{fig:typecheck-R3}
  4822. \end{figure}
  4823. \section{Garbage Collection}
  4824. \label{sec:GC}
  4825. Here we study a relatively simple algorithm for garbage collection
  4826. that is the basis of state-of-the-art garbage
  4827. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4828. particular, we describe a two-space copying
  4829. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4830. perform the
  4831. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4832. coarse-grained depiction of what happens in a two-space collector,
  4833. showing two time steps, prior to garbage collection (on the top) and
  4834. after garbage collection (on the bottom). In a two-space collector,
  4835. the heap is divided into two parts named the FromSpace and the
  4836. ToSpace. Initially, all allocations go to the FromSpace until there is
  4837. not enough room for the next allocation request. At that point, the
  4838. garbage collector goes to work to make more room.
  4839. The garbage collector must be careful not to reclaim tuples that will
  4840. be used by the program in the future. Of course, it is impossible in
  4841. general to predict what a program will do, but we can over approximate
  4842. the will-be-used tuples by preserving all tuples that could be
  4843. accessed by \emph{any} program given the current computer state. A
  4844. program could access any tuple whose address is in a register or on
  4845. the procedure call stack. These addresses are called the \emph{root
  4846. set}. In addition, a program could access any tuple that is
  4847. transitively reachable from the root set. Thus, it is safe for the
  4848. garbage collector to reclaim the tuples that are not reachable in this
  4849. way.
  4850. So the goal of the garbage collector is twofold:
  4851. \begin{enumerate}
  4852. \item preserve all tuple that are reachable from the root set via a
  4853. path of pointers, that is, the \emph{live} tuples, and
  4854. \item reclaim the memory of everything else, that is, the
  4855. \emph{garbage}.
  4856. \end{enumerate}
  4857. A copying collector accomplishes this by copying all of the live
  4858. objects from the FromSpace into the ToSpace and then performs a slight
  4859. of hand, treating the ToSpace as the new FromSpace and the old
  4860. FromSpace as the new ToSpace. In the example of
  4861. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4862. root set, one in a register and two on the stack. All of the live
  4863. objects have been copied to the ToSpace (the right-hand side of
  4864. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4865. pointer relationships. For example, the pointer in the register still
  4866. points to a 2-tuple whose first element is a 3-tuple and whose second
  4867. element is a 2-tuple. There are four tuples that are not reachable
  4868. from the root set and therefore do not get copied into the ToSpace.
  4869. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  4870. created by a well-typed program in $R_3$ because it contains a
  4871. cycle. However, creating cycles will be possible once we get to $R_6$.
  4872. We design the garbage collector to deal with cycles to begin with so
  4873. we will not need to revisit this issue.
  4874. \begin{figure}[tbp]
  4875. \centering
  4876. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4877. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4878. \caption{A copying collector in action.}
  4879. \label{fig:copying-collector}
  4880. \end{figure}
  4881. There are many alternatives to copying collectors (and their bigger
  4882. siblings, the generational collectors) when its comes to garbage
  4883. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  4884. reference counting~\citep{Collins:1960aa}. The strengths of copying
  4885. collectors are that allocation is fast (just a comparison and pointer
  4886. increment), there is no fragmentation, cyclic garbage is collected,
  4887. and the time complexity of collection only depends on the amount of
  4888. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  4889. main disadvantages of a two-space copying collector is that it uses a
  4890. lot of space and takes a long time to perform the copy, though these
  4891. problems are ameliorated in generational collectors. Racket and
  4892. Scheme programs tend to allocate many small objects and generate a lot
  4893. of garbage, so copying and generational collectors are a good fit.
  4894. Garbage collection is an active research topic, especially concurrent
  4895. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  4896. developing new techniques and revisiting old
  4897. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  4898. meet every year at the International Symposium on Memory Management to
  4899. present these findings.
  4900. \subsection{Graph Copying via Cheney's Algorithm}
  4901. \label{sec:cheney}
  4902. Let us take a closer look at the copying of the live objects. The
  4903. allocated objects and pointers can be viewed as a graph and we need to
  4904. copy the part of the graph that is reachable from the root set. To
  4905. make sure we copy all of the reachable vertices in the graph, we need
  4906. an exhaustive graph traversal algorithm, such as depth-first search or
  4907. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  4908. such algorithms take into account the possibility of cycles by marking
  4909. which vertices have already been visited, so as to ensure termination
  4910. of the algorithm. These search algorithms also use a data structure
  4911. such as a stack or queue as a to-do list to keep track of the vertices
  4912. that need to be visited. We shall use breadth-first search and a trick
  4913. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  4914. and copying tuples into the ToSpace.
  4915. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4916. copy progresses. The queue is represented by a chunk of contiguous
  4917. memory at the beginning of the ToSpace, using two pointers to track
  4918. the front and the back of the queue. The algorithm starts by copying
  4919. all tuples that are immediately reachable from the root set into the
  4920. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4921. old tuple to indicate that it has been visited. We discuss how this
  4922. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  4923. pointers inside the copied tuples in the queue still point back to the
  4924. FromSpace. Once the initial queue has been created, the algorithm
  4925. enters a loop in which it repeatedly processes the tuple at the front
  4926. of the queue and pops it off the queue. To process a tuple, the
  4927. algorithm copies all the tuple that are directly reachable from it to
  4928. the ToSpace, placing them at the back of the queue. The algorithm then
  4929. updates the pointers in the popped tuple so they point to the newly
  4930. copied tuples.
  4931. \begin{figure}[tbp]
  4932. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4933. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4934. \label{fig:cheney}
  4935. \end{figure}
  4936. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  4937. tuple whose second element is $42$ to the back of the queue. The other
  4938. pointer goes to a tuple that has already been copied, so we do not
  4939. need to copy it again, but we do need to update the pointer to the new
  4940. location. This can be accomplished by storing a \emph{forwarding}
  4941. pointer to the new location in the old tuple, back when we initially
  4942. copied the tuple into the ToSpace. This completes one step of the
  4943. algorithm. The algorithm continues in this way until the front of the
  4944. queue is empty, that is, until the front catches up with the back.
  4945. \subsection{Data Representation}
  4946. \label{sec:data-rep-gc}
  4947. The garbage collector places some requirements on the data
  4948. representations used by our compiler. First, the garbage collector
  4949. needs to distinguish between pointers and other kinds of data. There
  4950. are several ways to accomplish this.
  4951. \begin{enumerate}
  4952. \item Attached a tag to each object that identifies what type of
  4953. object it is~\citep{McCarthy:1960dz}.
  4954. \item Store different types of objects in different
  4955. regions~\citep{Steele:1977ab}.
  4956. \item Use type information from the program to either generate
  4957. type-specific code for collecting or to generate tables that can
  4958. guide the
  4959. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4960. \end{enumerate}
  4961. Dynamically typed languages, such as Lisp, need to tag objects
  4962. anyways, so option 1 is a natural choice for those languages.
  4963. However, $R_3$ is a statically typed language, so it would be
  4964. unfortunate to require tags on every object, especially small and
  4965. pervasive objects like integers and Booleans. Option 3 is the
  4966. best-performing choice for statically typed languages, but comes with
  4967. a relatively high implementation complexity. To keep this chapter
  4968. within a 2-week time budget, we recommend a combination of options 1
  4969. and 2, using separate strategies for the stack and the heap.
  4970. Regarding the stack, we recommend using a separate stack for pointers,
  4971. which we call a \emph{root stack} (a.k.a. ``shadow
  4972. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  4973. is, when a local variable needs to be spilled and is of type
  4974. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  4975. stack instead of the normal procedure call stack. Furthermore, we
  4976. always spill vector-typed variables if they are live during a call to
  4977. the collector, thereby ensuring that no pointers are in registers
  4978. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  4979. example from Figure~\ref{fig:copying-collector} and contrasts it with
  4980. the data layout using a root stack. The root stack contains the two
  4981. pointers from the regular stack and also the pointer in the second
  4982. register.
  4983. \begin{figure}[tbp]
  4984. \centering \includegraphics[width=0.65\textwidth]{figs/root-stack}
  4985. \caption{Maintaining a root stack to facilitate garbage collection.}
  4986. \label{fig:shadow-stack}
  4987. \end{figure}
  4988. The problem of distinguishing between pointers and other kinds of data
  4989. also arises inside of each tuple on the heap. We solve this problem by
  4990. attaching a tag, an extra 64-bits, to each
  4991. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  4992. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  4993. that we have drawn the bits in a big-endian way, from right-to-left,
  4994. with bit location 0 (the least significant bit) on the far right,
  4995. which corresponds to the direction of the x86 shifting instructions
  4996. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  4997. is dedicated to specifying which elements of the tuple are pointers,
  4998. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  4999. indicates there is a pointer and a 0 bit indicates some other kind of
  5000. data. The pointer mask starts at bit location 7. We have limited
  5001. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5002. the pointer mask. The tag also contains two other pieces of
  5003. information. The length of the tuple (number of elements) is stored in
  5004. bits location 1 through 6. Finally, the bit at location 0 indicates
  5005. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5006. value 1, then this tuple has not yet been copied. If the bit has
  5007. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5008. of a pointer are always zero anyways because our tuples are 8-byte
  5009. aligned.)
  5010. \begin{figure}[tbp]
  5011. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5012. \caption{Representation of tuples in the heap.}
  5013. \label{fig:tuple-rep}
  5014. \end{figure}
  5015. \subsection{Implementation of the Garbage Collector}
  5016. \label{sec:organize-gz}
  5017. An implementation of the copying collector is provided in the
  5018. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5019. interface to the garbage collector that is used by the compiler. The
  5020. \code{initialize} function creates the FromSpace, ToSpace, and root
  5021. stack and should be called in the prelude of the \code{main}
  5022. function. The \code{initialize} function puts the address of the
  5023. beginning of the FromSpace into the global variable
  5024. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5025. the address that is 1-past the last element of the FromSpace. (We use
  5026. half-open intervals to represent chunks of
  5027. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5028. points to the first element of the root stack.
  5029. As long as there is room left in the FromSpace, your generated code
  5030. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5031. %
  5032. The amount of room left in FromSpace is the difference between the
  5033. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5034. function should be called when there is not enough room left in the
  5035. FromSpace for the next allocation. The \code{collect} function takes
  5036. a pointer to the current top of the root stack (one past the last item
  5037. that was pushed) and the number of bytes that need to be
  5038. allocated. The \code{collect} function performs the copying collection
  5039. and leaves the heap in a state such that the next allocation will
  5040. succeed.
  5041. \begin{figure}[tbp]
  5042. \begin{lstlisting}
  5043. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5044. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5045. int64_t* free_ptr;
  5046. int64_t* fromspace_begin;
  5047. int64_t* fromspace_end;
  5048. int64_t** rootstack_begin;
  5049. \end{lstlisting}
  5050. \caption{The compiler's interface to the garbage collector.}
  5051. \label{fig:gc-header}
  5052. \end{figure}
  5053. %% \begin{exercise}
  5054. %% In the file \code{runtime.c} you will find the implementation of
  5055. %% \code{initialize} and a partial implementation of \code{collect}.
  5056. %% The \code{collect} function calls another function, \code{cheney},
  5057. %% to perform the actual copy, and that function is left to the reader
  5058. %% to implement. The following is the prototype for \code{cheney}.
  5059. %% \begin{lstlisting}
  5060. %% static void cheney(int64_t** rootstack_ptr);
  5061. %% \end{lstlisting}
  5062. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5063. %% rootstack (which is an array of pointers). The \code{cheney} function
  5064. %% also communicates with \code{collect} through the global
  5065. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5066. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5067. %% the ToSpace:
  5068. %% \begin{lstlisting}
  5069. %% static int64_t* tospace_begin;
  5070. %% static int64_t* tospace_end;
  5071. %% \end{lstlisting}
  5072. %% The job of the \code{cheney} function is to copy all the live
  5073. %% objects (reachable from the root stack) into the ToSpace, update
  5074. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5075. %% update the root stack so that it points to the objects in the
  5076. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5077. %% and ToSpace.
  5078. %% \end{exercise}
  5079. %% \section{Compiler Passes}
  5080. %% \label{sec:code-generation-gc}
  5081. The introduction of garbage collection has a non-trivial impact on our
  5082. compiler passes. We introduce two new compiler passes named
  5083. \code{expose-allocation} and \code{uncover-locals}. We make
  5084. significant changes to \code{select-instructions},
  5085. \code{build-interference}, \code{allocate-registers}, and
  5086. \code{print-x86} and make minor changes in severl more passes. The
  5087. following program will serve as our running example. It creates two
  5088. tuples, one nested inside the other. Both tuples have length one. The
  5089. program accesses the element in the inner tuple tuple via two vector
  5090. references.
  5091. % tests/s2_17.rkt
  5092. \begin{lstlisting}
  5093. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  5094. \end{lstlisting}
  5095. \section{Shrink}
  5096. \label{sec:shrink-R3}
  5097. Recall that the \code{shrink} pass translates the primitives operators
  5098. into a smaller set of primitives. Because this pass comes after type
  5099. checking, but before the passes that require the type information in
  5100. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5101. to wrap \code{HasType} around each AST node that it generates.
  5102. \section{Expose Allocation}
  5103. \label{sec:expose-allocation}
  5104. The pass \code{expose-allocation} lowers the \code{vector} creation
  5105. form into a conditional call to the collector followed by the
  5106. allocation. We choose to place the \code{expose-allocation} pass
  5107. before \code{remove-complex-opera*} because the code generated by
  5108. \code{expose-allocation} contains complex operands. We also place
  5109. \code{expose-allocation} before \code{explicate-control} because
  5110. \code{expose-allocation} introduces new variables using \code{let},
  5111. but \code{let} is gone after \code{explicate-control}.
  5112. The output of \code{expose-allocation} is a language $R'_3$ that
  5113. extends $R_3$ with the three new forms that we use in the translation
  5114. of the \code{vector} form.
  5115. \[
  5116. \begin{array}{lcl}
  5117. \Exp &::=& \cdots
  5118. \mid (\key{collect} \,\itm{int})
  5119. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5120. \mid (\key{global-value} \,\itm{name})
  5121. \end{array}
  5122. \]
  5123. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5124. $n$ bytes. It will become a call to the \code{collect} function in
  5125. \code{runtime.c} in \code{select-instructions}. The
  5126. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements. The
  5127. $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5128. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5129. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5130. a global variable, such as \code{free\_ptr}.
  5131. In the following, we show the transformation for the \code{vector}
  5132. form into 1) a sequence of let-bindings for the initializing
  5133. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5134. \code{allocate}, and 4) the initialization of the vector. In the
  5135. following, \itm{len} refers to the length of the vector and
  5136. \itm{bytes} is how many total bytes need to be allocated for the
  5137. vector, which is 8 for the tag plus \itm{len} times 8.
  5138. \begin{lstlisting}
  5139. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5140. |$\Longrightarrow$|
  5141. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5142. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5143. (global-value fromspace_end))
  5144. (void)
  5145. (collect |\itm{bytes}|))])
  5146. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5147. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5148. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5149. |$v$|) ... )))) ...)
  5150. \end{lstlisting}
  5151. In the above, we suppressed all of the \code{has-type} forms in the
  5152. output for the sake of readability. The placement of the initializing
  5153. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5154. sequence of \code{vector-set!} is important, as those expressions may
  5155. trigger garbage collection and we cannot have an allocated but
  5156. uninitialized tuple on the heap during a collection.
  5157. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5158. \code{expose-allocation} pass on our running example.
  5159. \begin{figure}[tbp]
  5160. % tests/s2_17.rkt
  5161. \begin{lstlisting}
  5162. (vector-ref
  5163. (vector-ref
  5164. (let ([vecinit7976
  5165. (let ([vecinit7972 42])
  5166. (let ([collectret7974
  5167. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5168. (void)
  5169. (collect 16)
  5170. )])
  5171. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5172. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5173. alloc7971)
  5174. )
  5175. )
  5176. )
  5177. ])
  5178. (let ([collectret7978
  5179. (if (< (+ (global-value free_ptr) 16) (global-value fromspace_end))
  5180. (void)
  5181. (collect 16)
  5182. )])
  5183. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5184. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5185. alloc7975)
  5186. )
  5187. )
  5188. )
  5189. 0)
  5190. 0)
  5191. \end{lstlisting}
  5192. \caption{Output of the \code{expose-allocation} pass, minus
  5193. all of the \code{has-type} forms.}
  5194. \label{fig:expose-alloc-output}
  5195. \end{figure}
  5196. \section{Remove Complex Operands}
  5197. \label{sec:remove-complex-opera-R2}
  5198. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5199. should all be treated as complex operands. A new case for
  5200. \code{HasType} is needed and the case for \code{Prim} needs to be
  5201. handled carefully to prevent the \code{Prim} node from being separated
  5202. from its enclosing \code{HasType}.
  5203. \section{Explicate Control and the $C_2$ language}
  5204. \label{sec:explicate-control-r3}
  5205. \begin{figure}[tbp]
  5206. \fbox{
  5207. \begin{minipage}{0.96\textwidth}
  5208. \small
  5209. \[
  5210. \begin{array}{lcl}
  5211. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5212. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5213. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5214. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5215. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5216. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5217. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5218. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5219. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5220. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5221. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5222. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5223. \end{array}
  5224. \]
  5225. \end{minipage}
  5226. }
  5227. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5228. \label{fig:c2-concrete-syntax}
  5229. \end{figure}
  5230. \begin{figure}[tp]
  5231. \fbox{
  5232. \begin{minipage}{0.96\textwidth}
  5233. \small
  5234. \[
  5235. \begin{array}{lcl}
  5236. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5237. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5238. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5239. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5240. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5241. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5242. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  5243. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  5244. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5245. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5246. \mid (\key{Collect} \,\itm{int}) \\
  5247. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5248. \mid \GOTO{\itm{label}} } \\
  5249. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5250. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5251. \end{array}
  5252. \]
  5253. \end{minipage}
  5254. }
  5255. \caption{The abstract syntax of $C_2$, an extention of $C_1$
  5256. (Figure~\ref{fig:c1-syntax}).}
  5257. \label{fig:c2-syntax}
  5258. \end{figure}
  5259. The output of \code{explicate-control} is a program in the
  5260. intermediate language $C_2$, whose concrete syntax is defined in
  5261. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5262. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5263. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5264. \key{global-value} expressions and the \code{collect} statement. The
  5265. \code{explicate-control} pass can treat these new forms much like the
  5266. other forms.
  5267. \section{Uncover Locals}
  5268. \label{sec:uncover-locals-r3}
  5269. Recall that the \code{explicate-control} function collects all of the
  5270. local variables so that it can store them in the $\itm{info}$ field of
  5271. the \code{Program} structure. Also recall that we need to know the
  5272. types of all the local variables for purposes of identifying the root
  5273. set for the garbage collector. Thus, we create a pass named
  5274. \code{uncover-locals} to collect not just the variables but the
  5275. variables and their types in the form of an alist. Thanks to the
  5276. \code{HasType} nodes, the types are readily available at every
  5277. assignment to a variable. We recommend storing the resulting alist in
  5278. the $\itm{info}$ field of the program, associated with the
  5279. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5280. of the \code{uncover-locals} pass on the running example.
  5281. \begin{figure}[tbp]
  5282. % tests/s2_17.rkt
  5283. \begin{lstlisting}
  5284. locals:
  5285. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5286. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5287. collectret7974 : 'Void, initret7977 : 'Void,
  5288. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5289. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5290. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5291. vecinit7972 : 'Integer, initret7973 : 'Void,
  5292. block91:
  5293. (collect 16)
  5294. goto block89;
  5295. block90:
  5296. collectret7974 = (void);
  5297. goto block89;
  5298. block89:
  5299. alloc7971 = (allocate 1 (Vector Integer));
  5300. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5301. vecinit7976 = alloc7971;
  5302. tmp7982 = (global-value free_ptr);
  5303. tmp7983 = (+ tmp7982 16);
  5304. tmp7984 = (global-value fromspace_end);
  5305. if (< tmp7983 tmp7984) then
  5306. goto block87;
  5307. else
  5308. goto block88;
  5309. block88:
  5310. (collect 16)
  5311. goto block86;
  5312. block87:
  5313. collectret7978 = (void);
  5314. goto block86;
  5315. block86:
  5316. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5317. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5318. tmp7985 = (vector-ref alloc7975 0);
  5319. return (vector-ref tmp7985 0);
  5320. start:
  5321. vecinit7972 = 42;
  5322. tmp7979 = (global-value free_ptr);
  5323. tmp7980 = (+ tmp7979 16);
  5324. tmp7981 = (global-value fromspace_end);
  5325. if (< tmp7980 tmp7981) then
  5326. goto block90;
  5327. else
  5328. goto block91;
  5329. \end{lstlisting}
  5330. \caption{Output of \code{uncover-locals} for the running example.}
  5331. \label{fig:uncover-locals-r3}
  5332. \end{figure}
  5333. \clearpage
  5334. \section{Select Instructions and the x86$_2$ Language}
  5335. \label{sec:select-instructions-gc}
  5336. %% void (rep as zero)
  5337. %% allocate
  5338. %% collect (callq collect)
  5339. %% vector-ref
  5340. %% vector-set!
  5341. %% global (postpone)
  5342. In this pass we generate x86 code for most of the new operations that
  5343. were needed to compile tuples, including \code{Allocate},
  5344. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5345. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5346. the later has a different concrete syntax (see
  5347. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5348. The \code{vector-ref} and \code{vector-set!} forms translate into
  5349. \code{movq} instructions. (The plus one in the offset is to get past
  5350. the tag at the beginning of the tuple representation.)
  5351. \begin{lstlisting}
  5352. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5353. |$\Longrightarrow$|
  5354. movq |$\itm{vec}'$|, %r11
  5355. movq |$-8(n+1)$|(%r11), |$\itm{lhs}$|
  5356. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5357. |$\Longrightarrow$|
  5358. movq |$\itm{vec}'$|, %r11
  5359. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5360. movq $0, |$\itm{lhs}$|
  5361. \end{lstlisting}
  5362. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by translating
  5363. $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5364. register \code{r11} ensures that offset expression
  5365. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5366. removing \code{r11} from consideration by the register allocating.
  5367. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5368. \code{rax}. Then the generated code for \code{vector-set!} would be
  5369. \begin{lstlisting}
  5370. movq |$\itm{vec}'$|, %rax
  5371. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5372. movq $0, |$\itm{lhs}$|
  5373. \end{lstlisting}
  5374. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5375. \code{patch-instructions} would insert a move through \code{rax}
  5376. as follows.
  5377. \begin{lstlisting}
  5378. movq |$\itm{vec}'$|, %rax
  5379. movq |$\itm{arg}'$|, %rax
  5380. movq %rax, |$8(n+1)$|(%rax)
  5381. movq $0, |$\itm{lhs}$|
  5382. \end{lstlisting}
  5383. But the above sequence of instructions does not work because we're
  5384. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5385. $\itm{arg}'$) at the same time!
  5386. We compile the \code{allocate} form to operations on the
  5387. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5388. is the next free address in the FromSpace, so we move it into the
  5389. \itm{lhs} and then move it forward by enough space for the tuple being
  5390. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5391. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5392. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5393. how the tag is organized. We recommend using the Racket operations
  5394. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5395. during compilation. The type annotation in the \code{vector} form is
  5396. used to determine the pointer mask region of the tag.
  5397. \begin{lstlisting}
  5398. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5399. |$\Longrightarrow$|
  5400. movq free_ptr(%rip), |$\itm{lhs}'$|
  5401. addq $|$8(\itm{len}+1)$|, free_ptr(%rip)
  5402. movq |$\itm{lhs}'$|, %r11
  5403. movq $|$\itm{tag}$|, 0(%r11)
  5404. \end{lstlisting}
  5405. The \code{collect} form is compiled to a call to the \code{collect}
  5406. function in the runtime. The arguments to \code{collect} are 1) the
  5407. top of the root stack and 2) the number of bytes that need to be
  5408. allocated. We shall use another dedicated register, \code{r15}, to
  5409. store the pointer to the top of the root stack. So \code{r15} is not
  5410. available for use by the register allocator.
  5411. \begin{lstlisting}
  5412. (collect |$\itm{bytes}$|)
  5413. |$\Longrightarrow$|
  5414. movq %r15, %rdi
  5415. movq $|\itm{bytes}|, %rsi
  5416. callq collect
  5417. \end{lstlisting}
  5418. \begin{figure}[tp]
  5419. \fbox{
  5420. \begin{minipage}{0.96\textwidth}
  5421. \[
  5422. \begin{array}{lcl}
  5423. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5424. x86_1 &::= & \gray{ \key{.globl main} }\\
  5425. & & \gray{ \key{main:} \; \Instr\ldots }
  5426. \end{array}
  5427. \]
  5428. \end{minipage}
  5429. }
  5430. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5431. \label{fig:x86-2-concrete}
  5432. \end{figure}
  5433. \begin{figure}[tp]
  5434. \fbox{
  5435. \begin{minipage}{0.96\textwidth}
  5436. \small
  5437. \[
  5438. \begin{array}{lcl}
  5439. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5440. \mid \BYTEREG{\Reg}} \\
  5441. &\mid& (\key{Global}~\Var) \\
  5442. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5443. \end{array}
  5444. \]
  5445. \end{minipage}
  5446. }
  5447. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5448. \label{fig:x86-2}
  5449. \end{figure}
  5450. The concrete and abstract syntax of the $x86_2$ language is defined in
  5451. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5452. x86$_1$ just in the addition of the form for global variables.
  5453. %
  5454. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5455. \code{select-instructions} pass on the running example.
  5456. \begin{figure}[tbp]
  5457. \centering
  5458. % tests/s2_17.rkt
  5459. \begin{minipage}[t]{0.5\textwidth}
  5460. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5461. block35:
  5462. movq free_ptr(%rip), alloc9024
  5463. addq $16, free_ptr(%rip)
  5464. movq alloc9024, %r11
  5465. movq $131, 0(%r11)
  5466. movq alloc9024, %r11
  5467. movq vecinit9025, 8(%r11)
  5468. movq $0, initret9026
  5469. movq alloc9024, %r11
  5470. movq 8(%r11), tmp9034
  5471. movq tmp9034, %r11
  5472. movq 8(%r11), %rax
  5473. jmp conclusion
  5474. block36:
  5475. movq $0, collectret9027
  5476. jmp block35
  5477. block38:
  5478. movq free_ptr(%rip), alloc9020
  5479. addq $16, free_ptr(%rip)
  5480. movq alloc9020, %r11
  5481. movq $3, 0(%r11)
  5482. movq alloc9020, %r11
  5483. movq vecinit9021, 8(%r11)
  5484. movq $0, initret9022
  5485. movq alloc9020, vecinit9025
  5486. movq free_ptr(%rip), tmp9031
  5487. movq tmp9031, tmp9032
  5488. addq $16, tmp9032
  5489. movq fromspace_end(%rip), tmp9033
  5490. cmpq tmp9033, tmp9032
  5491. jl block36
  5492. jmp block37
  5493. block37:
  5494. movq %r15, %rdi
  5495. movq $16, %rsi
  5496. callq 'collect
  5497. jmp block35
  5498. block39:
  5499. movq $0, collectret9023
  5500. jmp block38
  5501. \end{lstlisting}
  5502. \end{minipage}
  5503. \begin{minipage}[t]{0.45\textwidth}
  5504. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5505. start:
  5506. movq $42, vecinit9021
  5507. movq free_ptr(%rip), tmp9028
  5508. movq tmp9028, tmp9029
  5509. addq $16, tmp9029
  5510. movq fromspace_end(%rip), tmp9030
  5511. cmpq tmp9030, tmp9029
  5512. jl block39
  5513. jmp block40
  5514. block40:
  5515. movq %r15, %rdi
  5516. movq $16, %rsi
  5517. callq 'collect
  5518. jmp block38
  5519. \end{lstlisting}
  5520. \end{minipage}
  5521. \caption{Output of the \code{select-instructions} pass.}
  5522. \label{fig:select-instr-output-gc}
  5523. \end{figure}
  5524. \clearpage
  5525. \section{Register Allocation}
  5526. \label{sec:reg-alloc-gc}
  5527. As discussed earlier in this chapter, the garbage collector needs to
  5528. access all the pointers in the root set, that is, all variables that
  5529. are vectors. It will be the responsibility of the register allocator
  5530. to make sure that:
  5531. \begin{enumerate}
  5532. \item the root stack is used for spilling vector-typed variables, and
  5533. \item if a vector-typed variable is live during a call to the
  5534. collector, it must be spilled to ensure it is visible to the
  5535. collector.
  5536. \end{enumerate}
  5537. The later responsibility can be handled during construction of the
  5538. inference graph, by adding interference edges between the call-live
  5539. vector-typed variables and all the callee-saved registers. (They
  5540. already interfere with the caller-saved registers.) The type
  5541. information for variables is in the \code{program} form, so we
  5542. recommend adding another parameter to the \code{build-interference}
  5543. function to communicate this alist.
  5544. The spilling of vector-typed variables to the root stack can be
  5545. handled after graph coloring, when choosing how to assign the colors
  5546. (integers) to registers and stack locations. The \code{program} output
  5547. of this pass changes to also record the number of spills to the root
  5548. stack.
  5549. % build-interference
  5550. %
  5551. % callq
  5552. % extra parameter for var->type assoc. list
  5553. % update 'program' and 'if'
  5554. % allocate-registers
  5555. % allocate spilled vectors to the rootstack
  5556. % don't change color-graph
  5557. \section{Print x86}
  5558. \label{sec:print-x86-gc}
  5559. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5560. \code{print-x86} pass on the running example. In the prelude and
  5561. conclusion of the \code{main} function, we treat the root stack very
  5562. much like the regular stack in that we move the root stack pointer
  5563. (\code{r15}) to make room for the spills to the root stack, except
  5564. that the root stack grows up instead of down. For the running
  5565. example, there was just one spill so we increment \code{r15} by 8
  5566. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5567. One issue that deserves special care is that there may be a call to
  5568. \code{collect} prior to the initializing assignments for all the
  5569. variables in the root stack. We do not want the garbage collector to
  5570. accidentally think that some uninitialized variable is a pointer that
  5571. needs to be followed. Thus, we zero-out all locations on the root
  5572. stack in the prelude of \code{main}. In
  5573. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5574. %
  5575. \lstinline{movq $0, (%r15)}
  5576. %
  5577. accomplishes this task. The garbage collector tests each root to see
  5578. if it is null prior to dereferencing it.
  5579. \begin{figure}[htbp]
  5580. \begin{minipage}[t]{0.5\textwidth}
  5581. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5582. block35:
  5583. movq free_ptr(%rip), %rcx
  5584. addq $16, free_ptr(%rip)
  5585. movq %rcx, %r11
  5586. movq $131, 0(%r11)
  5587. movq %rcx, %r11
  5588. movq -8(%r15), %rax
  5589. movq %rax, 8(%r11)
  5590. movq $0, %rdx
  5591. movq %rcx, %r11
  5592. movq 8(%r11), %rcx
  5593. movq %rcx, %r11
  5594. movq 8(%r11), %rax
  5595. jmp conclusion
  5596. block36:
  5597. movq $0, %rcx
  5598. jmp block35
  5599. block38:
  5600. movq free_ptr(%rip), %rcx
  5601. addq $16, free_ptr(%rip)
  5602. movq %rcx, %r11
  5603. movq $3, 0(%r11)
  5604. movq %rcx, %r11
  5605. movq %rbx, 8(%r11)
  5606. movq $0, %rdx
  5607. movq %rcx, -8(%r15)
  5608. movq free_ptr(%rip), %rcx
  5609. addq $16, %rcx
  5610. movq fromspace_end(%rip), %rdx
  5611. cmpq %rdx, %rcx
  5612. jl block36
  5613. movq %r15, %rdi
  5614. movq $16, %rsi
  5615. callq collect
  5616. jmp block35
  5617. block39:
  5618. movq $0, %rcx
  5619. jmp block38
  5620. \end{lstlisting}
  5621. \end{minipage}
  5622. \begin{minipage}[t]{0.45\textwidth}
  5623. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5624. start:
  5625. movq $42, %rbx
  5626. movq free_ptr(%rip), %rdx
  5627. addq $16, %rdx
  5628. movq fromspace_end(%rip), %rcx
  5629. cmpq %rcx, %rdx
  5630. jl block39
  5631. movq %r15, %rdi
  5632. movq $16, %rsi
  5633. callq collect
  5634. jmp block38
  5635. .globl main
  5636. main:
  5637. pushq %rbp
  5638. movq %rsp, %rbp
  5639. pushq %r13
  5640. pushq %r12
  5641. pushq %rbx
  5642. pushq %r14
  5643. subq $0, %rsp
  5644. movq $16384, %rdi
  5645. movq $16, %rsi
  5646. callq initialize
  5647. movq rootstack_begin(%rip), %r15
  5648. movq $0, (%r15)
  5649. addq $8, %r15
  5650. jmp start
  5651. conclusion:
  5652. subq $8, %r15
  5653. addq $0, %rsp
  5654. popq %r14
  5655. popq %rbx
  5656. popq %r12
  5657. popq %r13
  5658. popq %rbp
  5659. retq
  5660. \end{lstlisting}
  5661. \end{minipage}
  5662. \caption{Output of the \code{print-x86} pass.}
  5663. \label{fig:print-x86-output-gc}
  5664. \end{figure}
  5665. \margincomment{\scriptsize Suggest an implementation strategy
  5666. in which the students first do the code gen and test that
  5667. without GC (just use a big heap), then after that is debugged,
  5668. implement the GC. \\ --Jeremy}
  5669. \begin{figure}[p]
  5670. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5671. \node (R3) at (0,2) {\large $R_3$};
  5672. \node (R3-2) at (3,2) {\large $R_3$};
  5673. \node (R3-3) at (6,2) {\large $R_3$};
  5674. \node (R3-4) at (9,2) {\large $R_3$};
  5675. \node (R3-5) at (9,0) {\large $R'_3$};
  5676. \node (R3-6) at (6,0) {\large $R'_3$};
  5677. \node (C2-4) at (3,-2) {\large $C_2$};
  5678. \node (C2-3) at (0,-2) {\large $C_2$};
  5679. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  5680. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  5681. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  5682. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  5683. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  5684. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  5685. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5686. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  5687. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  5688. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  5689. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  5690. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5691. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5692. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5693. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5694. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  5695. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  5696. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5697. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5698. \end{tikzpicture}
  5699. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5700. \label{fig:R3-passes}
  5701. \end{figure}
  5702. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5703. for the compilation of $R_3$.
  5704. \section{Challenge: Simple Structures}
  5705. \label{sec:simple-structures}
  5706. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  5707. $R^s_3$, which extends $R^3$ with support for simple structures.
  5708. Recall that a \code{struct} in Typed Racket is a user-defined data
  5709. type that contains named fields and that is heap allocated, similar to
  5710. a vector. The following is an example of a structure definition, in
  5711. this case the definition of a \code{point} type.
  5712. \begin{lstlisting}
  5713. (struct point ([x : Integer] [y : Integer]) #:mutable)
  5714. \end{lstlisting}
  5715. \begin{figure}[tbp]
  5716. \centering
  5717. \fbox{
  5718. \begin{minipage}{0.96\textwidth}
  5719. \[
  5720. \begin{array}{lcl}
  5721. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5722. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void}\\
  5723. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5724. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  5725. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  5726. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5727. \mid (\key{and}\;\Exp\;\Exp)
  5728. \mid (\key{or}\;\Exp\;\Exp)
  5729. \mid (\key{not}\;\Exp) } \\
  5730. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5731. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  5732. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  5733. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  5734. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  5735. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  5736. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  5737. R_3 &::=& \Def \ldots \; \Exp
  5738. \end{array}
  5739. \]
  5740. \end{minipage}
  5741. }
  5742. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  5743. (Figure~\ref{fig:r3-concrete-syntax}).}
  5744. \label{fig:r3s-concrete-syntax}
  5745. \end{figure}
  5746. An instance of a structure is created using function call syntax, with
  5747. the name of the structure in the function position:
  5748. \begin{lstlisting}
  5749. (point 7 12)
  5750. \end{lstlisting}
  5751. Function-call syntax is also used to read the value in a field of a
  5752. structure. The function name is formed by the structure name, a dash,
  5753. and the field name. The following example uses \code{point-x} and
  5754. \code{point-y} to access the \code{x} and \code{y} fields of two point
  5755. instances.
  5756. \begin{center}
  5757. \begin{lstlisting}
  5758. (let ([pt1 (point 7 12)])
  5759. (let ([pt2 (point 4 3)])
  5760. (+ (- (point-x pt1) (point-x pt2))
  5761. (- (point-y pt1) (point-y pt2)))))
  5762. \end{lstlisting}
  5763. \end{center}
  5764. Similarly, to write to a field of a structure, use its set function,
  5765. whose name starts with \code{set-}, followed by the structure name,
  5766. then a dash, then the field name, and conclused with an exclamation
  5767. mark. The folowing example uses \code{set-point-x!} to change the
  5768. \code{x} field from \code{7} to \code{42}.
  5769. \begin{center}
  5770. \begin{lstlisting}
  5771. (let ([pt (point 7 12)])
  5772. (let ([_ (set-point-x! pt 42)])
  5773. (point-x pt)))
  5774. \end{lstlisting}
  5775. \end{center}
  5776. \begin{exercise}\normalfont
  5777. Extend your compiler with support for simple structures, compiling
  5778. $R^s_3$ to x86 assembly code. Create five new test cases that use
  5779. structures and test your compiler.
  5780. \end{exercise}
  5781. \section{Challenge: Generational Collection}
  5782. The copying collector described in Section~\ref{sec:GC} can incur
  5783. significant runtime overhead because the call to \code{collect} takes
  5784. time proportional to all of the live data. One way to reduce this
  5785. overhead is to reduce how much data is inspected in each call to
  5786. \code{collect}. In particular, researchers have observed that recently
  5787. allocated data is more likely to become garbage then data that has
  5788. survived one or more previous calls to \code{collect}. This insight
  5789. motivated the creation of \emph{generational garbage collectors} that
  5790. 1) segragates data according to its age into two or more generations,
  5791. 2) allocates less space for younger generations, so collecting them is
  5792. faster, and more space for the older generations, and 3) performs
  5793. collection on the younger generations more frequently then for older
  5794. generations~\citep{Wilson:1992fk}.
  5795. For this challenge assignment, the goal is to adapt the copying
  5796. collector implemented in \code{runtime.c} to use two generations, one
  5797. for young data and one for old data. Each generation consists of a
  5798. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  5799. \code{collect} function to use the two generations.
  5800. \begin{enumerate}
  5801. \item Copy the young generation's FromSpace to its ToSpace then switch
  5802. the role of the ToSpace and FromSpace
  5803. \item If there is enough space for the requested number of bytes in
  5804. the young FromSpace, then return from \code{collect}.
  5805. \item If there is not enough space in the young FromSpace for the
  5806. requested bytes, then move the data from the young generation to the
  5807. old one with the following steps:
  5808. \begin{enumerate}
  5809. \item If there is enough room in the old FromSpace, copy the young
  5810. FromSpace to the old FromSpace and then return.
  5811. \item If there is not enough room in the old FromSpace, then collect
  5812. the old generation by copying the old FromSpace to the old ToSpace
  5813. and swap the roles of the old FromSpace and ToSpace.
  5814. \item If there is enough room now, copy the young FromSpace to the
  5815. old FromSpace and return. Otherwise, allocate a larger FromSpace
  5816. and ToSpace for the old generation. Copy the young FromSpace and
  5817. the old FromSpace into the larger FromSpace for the old
  5818. generation and then return.
  5819. \end{enumerate}
  5820. \end{enumerate}
  5821. We recommend that you generalize the \code{cheney} function so that it
  5822. can be used for all the copies mentioned above: between the young
  5823. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  5824. between the young FromSpace and old FromSpace. This can be
  5825. accomplished by adding parameters to \code{cheney} that replace its
  5826. use of the global variables \code{fromspace\_begin},
  5827. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  5828. Note that the collection of the young generation does not traverse the
  5829. old generation. This introduces a potential problem: there may be
  5830. young data that is only reachable through pointers in the old
  5831. generation. If these pointers are not taken into account, the
  5832. collector could throw away young data that is live! One solution,
  5833. called \emph{pointer recording}, is to maintain a set of all the
  5834. pointers from the old generation into the new generation and consider
  5835. this set as part of the root set. To maintain this set, the compiler
  5836. must insert extra instructions around every \code{vector-set!}. If the
  5837. vector being modified is in the old generation, and if the value being
  5838. written is a pointer into the new generation, than that pointer must
  5839. be added to the set. Also, if the value being overwritten was a
  5840. pointer into the new generation, then that pointer should be removed
  5841. from the set.
  5842. \begin{exercise}\normalfont
  5843. Adapt the \code{collect} function in \code{runtime.c} to implement
  5844. generational garbage collection, as outlined in this section.
  5845. Update the code generation for \code{vector-set!} to implement
  5846. pointer recording. Make sure that your new compiler and runtime
  5847. passes your test suite.
  5848. \end{exercise}
  5849. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5850. \chapter{Functions}
  5851. \label{ch:functions}
  5852. This chapter studies the compilation of functions similar to those
  5853. found in the C language. This corresponds to a subset of Typed Racket
  5854. in which only top-level function definitions are allowed. This kind of
  5855. function is an important stepping stone to implementing
  5856. lexically-scoped functions, that is, \key{lambda} abstractions, which
  5857. is the topic of Chapter~\ref{ch:lambdas}.
  5858. \section{The $R_4$ Language}
  5859. The concrete and abstract syntax for function definitions and function
  5860. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  5861. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  5862. $R_4$ begin with zero or more function definitions. The function
  5863. names from these definitions are in-scope for the entire program,
  5864. including all other function definitions (so the ordering of function
  5865. definitions does not matter). The concrete syntax for function
  5866. application is $(\Exp \; \Exp \ldots)$ where the first expression must
  5867. evaluate to a function and the rest are the arguments.
  5868. The abstract syntax for function application is
  5869. $\APPLY{\Exp}{\Exp\ldots}$.
  5870. %% The syntax for function application does not include an explicit
  5871. %% keyword, which is error prone when using \code{match}. To alleviate
  5872. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  5873. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  5874. Functions are first-class in the sense that a function pointer is data
  5875. and can be stored in memory or passed as a parameter to another
  5876. function. Thus, we introduce a function type, written
  5877. \begin{lstlisting}
  5878. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5879. \end{lstlisting}
  5880. for a function whose $n$ parameters have the types $\Type_1$ through
  5881. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5882. these functions (with respect to Racket functions) is that they are
  5883. not lexically scoped. That is, the only external entities that can be
  5884. referenced from inside a function body are other globally-defined
  5885. functions. The syntax of $R_4$ prevents functions from being nested
  5886. inside each other.
  5887. \begin{figure}[tp]
  5888. \centering
  5889. \fbox{
  5890. \begin{minipage}{0.96\textwidth}
  5891. \small
  5892. \[
  5893. \begin{array}{lcl}
  5894. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5895. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  5896. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5897. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5898. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5899. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5900. \mid (\key{and}\;\Exp\;\Exp)
  5901. \mid (\key{or}\;\Exp\;\Exp)
  5902. \mid (\key{not}\;\Exp)} \\
  5903. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5904. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  5905. (\key{vector-ref}\;\Exp\;\Int)} \\
  5906. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  5907. \mid (\key{has-type}~\Exp~\Type)} \\
  5908. &\mid& (\Exp \; \Exp \ldots) \\
  5909. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp) \\
  5910. R_4 &::=& \Def \ldots \; \Exp
  5911. \end{array}
  5912. \]
  5913. \end{minipage}
  5914. }
  5915. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  5916. \label{fig:r4-concrete-syntax}
  5917. \end{figure}
  5918. \begin{figure}[tp]
  5919. \centering
  5920. \fbox{
  5921. \begin{minipage}{0.96\textwidth}
  5922. \small
  5923. \[
  5924. \begin{array}{lcl}
  5925. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  5926. &\mid& \gray{ \ADD{\Exp}{\Exp}
  5927. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  5928. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5929. &\mid& \gray{ \BOOL{\itm{bool}}
  5930. \mid \AND{\Exp}{\Exp} }\\
  5931. &\mid& \gray{ \OR{\Exp}{\Exp}
  5932. \mid \NOT{\Exp} } \\
  5933. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  5934. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5935. &\mid& \gray{ \VECTOR{\Exp} } \\
  5936. &\mid& \gray{ \VECREF{\Exp}{\Int} }\\
  5937. &\mid& \gray{ \VECSET{\Exp}{\Int}{\Exp}} \\
  5938. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP } \\
  5939. &\mid& \APPLY{\Exp}{\Exp\ldots}\\
  5940. \Def &::=& \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp}\\
  5941. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{(\Def\ldots)}{\Exp}
  5942. \end{array}
  5943. \]
  5944. \end{minipage}
  5945. }
  5946. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  5947. \label{fig:r4-syntax}
  5948. \end{figure}
  5949. The program in Figure~\ref{fig:r4-function-example} is a
  5950. representative example of defining and using functions in $R_4$. We
  5951. define a function \code{map-vec} that applies some other function
  5952. \code{f} to both elements of a vector and returns a new
  5953. vector containing the results. We also define a function \code{add1}.
  5954. The program applies
  5955. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5956. \code{(vector 1 42)}, from which we return the \code{42}.
  5957. \begin{figure}[tbp]
  5958. \begin{lstlisting}
  5959. (define (map-vec [f : (Integer -> Integer)]
  5960. [v : (Vector Integer Integer)])
  5961. : (Vector Integer Integer)
  5962. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5963. (define (add1 [x : Integer]) : Integer
  5964. (+ x 1))
  5965. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5966. \end{lstlisting}
  5967. \caption{Example of using functions in $R_4$.}
  5968. \label{fig:r4-function-example}
  5969. \end{figure}
  5970. The definitional interpreter for $R_4$ is in
  5971. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  5972. responsible for setting up the mutual recursion between the top-level
  5973. function definitions. We use the classic back-patching approach that
  5974. uses mutable variables and makes two passes over the function
  5975. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5976. top-level environment using a mutable cons cell for each function
  5977. definition. Note that the \code{lambda} value for each function is
  5978. incomplete; it does not yet include the environment. Once the
  5979. top-level environment is constructed, we then iterate over it and
  5980. update the \code{lambda} values to use the top-level environment.
  5981. \begin{figure}[tp]
  5982. \begin{lstlisting}
  5983. (define (interp-exp env)
  5984. (lambda (e)
  5985. (define recur (interp-exp env))
  5986. (match e
  5987. ...
  5988. [(Apply fun args)
  5989. (define fun-val (recur fun))
  5990. (define arg-vals (for/list ([e args]) (recur e)))
  5991. (match fun-val
  5992. [`(lambda (,xs ...) ,body ,fun-env)
  5993. (define new-env (append (map cons xs arg-vals) fun-env))
  5994. ((interp-exp new-env) body)])]
  5995. ...
  5996. )))
  5997. (define (interp-def d)
  5998. (match d
  5999. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6000. (mcons f `(lambda ,xs ,body ()))]
  6001. ))
  6002. (define (interp-R4 p)
  6003. (match p
  6004. [(ProgramDefsExp info ds body)
  6005. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6006. (for/list ([b top-level])
  6007. (set-mcdr! b (match (mcdr b)
  6008. [`(lambda ,xs ,body ())
  6009. `(lambda ,xs ,body ,top-level)])))
  6010. ((interp-exp top-level) body))]
  6011. ))
  6012. \end{lstlisting}
  6013. \caption{Interpreter for the $R_4$ language.}
  6014. \label{fig:interp-R4}
  6015. \end{figure}
  6016. \section{Functions in x86}
  6017. \label{sec:fun-x86}
  6018. \margincomment{\tiny Make sure callee-saved registers are discussed
  6019. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6020. \margincomment{\tiny Talk about the return address on the
  6021. stack and what callq and retq does.\\ --Jeremy }
  6022. The x86 architecture provides a few features to support the
  6023. implementation of functions. We have already seen that x86 provides
  6024. labels so that one can refer to the location of an instruction, as is
  6025. needed for jump instructions. Labels can also be used to mark the
  6026. beginning of the instructions for a function. Going further, we can
  6027. obtain the address of a label by using the \key{leaq} instruction and
  6028. \key{rip}-relative addressing. For example, the following puts the
  6029. address of the \code{add1} label into the \code{rbx} register.
  6030. \begin{lstlisting}
  6031. leaq add1(%rip), %rbx
  6032. \end{lstlisting}
  6033. The instruction pointer register \key{rip} (aka. the program counter
  6034. or PC) always points to the next instruction to be executed. When
  6035. combined with an label, as in \code{add1(\%rip)}, the linker computes
  6036. the distance $d$ between the address of \code{add1} and where the
  6037. \code{rip} would be at that moment and then changes \code{add1(\%rip)}
  6038. to \code{$d$(\%rip)}, which at runtime will compute the address of
  6039. \code{add1}.
  6040. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6041. jump to a function whose location is given by a label. To support
  6042. function calls in this chapter we instead will be jumping to a
  6043. function whose location is given by an address in a register, that is,
  6044. we need to make an \emph{indirect function call}. The x86 syntax for
  6045. this is a \code{callq} instruction but with an asterisk before the
  6046. register name.
  6047. \begin{lstlisting}
  6048. callq *%rbx
  6049. \end{lstlisting}
  6050. \subsection{Calling Conventions}
  6051. The \code{callq} instruction provides partial support for implementing
  6052. functions: it pushes the return address on the stack and it jumps to
  6053. the target. However, \code{callq} does not handle
  6054. \begin{enumerate}
  6055. \item parameter passing,
  6056. \item saving and restoring frames on the procedure call stack, or
  6057. \item determining how registers are shared by different functions.
  6058. \end{enumerate}
  6059. These issues require coordination between the caller and the callee,
  6060. which is often assembly code written by different programmers or
  6061. generated by different compilers. As a result, people have developed
  6062. \emph{conventions} that govern how functions calls are performed.
  6063. Here we use conventions that are compatible with those of the
  6064. \code{gcc} compiler~\citep{Matz:2013aa}.
  6065. Regarding (1) parameter passing, the convention is to use the
  6066. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  6067. \code{rcx}, \code{r8}, and \code{r9}, in that order, to pass arguments
  6068. to a function. If there are more than six arguments, then the
  6069. convention is to use space on the frame of the caller for the rest of
  6070. the arguments. However, to ease the implementation of efficient tail
  6071. calls (Section~\ref{sec:tail-call}), we arrange to never need more
  6072. than six arguments.
  6073. %
  6074. The register \code{rax} is for the return value of the function.
  6075. Regarding (2) frames and the procedure call stack, recall from
  6076. Section~\ref{sec:x86} that the stack grows down, with each function
  6077. call using a chunk of space called a frame. The caller sets the stack
  6078. pointer, register \code{rsp}, to the last data item in its frame. The
  6079. callee must not change anything in the caller's frame, that is,
  6080. anything that is at or above the stack pointer. The callee is free to
  6081. use locations that are below the stack pointer.
  6082. Regarding (3) the sharing of registers between different functions,
  6083. recall from Section~\ref{sec:calling-conventions} that the registers
  6084. are divided into two groups, the caller-saved registers and the
  6085. callee-saved registers. The caller should assume that all the
  6086. caller-saved registers get overwritten with arbitrary values by the
  6087. callee. That is why we recommend in
  6088. Section~\ref{sec:calling-conventions} that variables that are live
  6089. during a function call should not be assigned to caller-saved
  6090. registers.
  6091. On the flip side, if the callee wants to use a callee-saved register,
  6092. the callee must save the contents of those registers on their stack
  6093. frame and then put them back prior to returning to the caller. That
  6094. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6095. the register allocator assigns a variable to a callee-saved register,
  6096. then the prelude of the \code{main} function must save that register
  6097. to the stack and the conclusion of \code{main} must restore it. This
  6098. recommendation now generalizes to all functions.
  6099. Also recall that the base pointer, register \code{rbp}, is used as a
  6100. point-of-reference within a frame, so that each local variable can be
  6101. accessed at a fixed offset from the base pointer
  6102. (Section~\ref{sec:x86}).
  6103. %
  6104. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6105. and callee frames.
  6106. \begin{figure}[tbp]
  6107. \centering
  6108. \begin{tabular}{r|r|l|l} \hline
  6109. Caller View & Callee View & Contents & Frame \\ \hline
  6110. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6111. 0(\key{\%rbp}) & & old \key{rbp} \\
  6112. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6113. \ldots & & \ldots \\
  6114. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6115. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6116. \ldots & & \ldots \\
  6117. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6118. %% & & \\
  6119. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6120. %% & \ldots & \ldots \\
  6121. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6122. \hline
  6123. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6124. & 0(\key{\%rbp}) & old \key{rbp} \\
  6125. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6126. & \ldots & \ldots \\
  6127. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6128. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6129. & \ldots & \ldots \\
  6130. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6131. \end{tabular}
  6132. \caption{Memory layout of caller and callee frames.}
  6133. \label{fig:call-frames}
  6134. \end{figure}
  6135. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6136. %% local variables and for storing the values of callee-saved registers
  6137. %% (we shall refer to all of these collectively as ``locals''), and that
  6138. %% at the beginning of a function we move the stack pointer \code{rsp}
  6139. %% down to make room for them.
  6140. %% We recommend storing the local variables
  6141. %% first and then the callee-saved registers, so that the local variables
  6142. %% can be accessed using \code{rbp} the same as before the addition of
  6143. %% functions.
  6144. %% To make additional room for passing arguments, we shall
  6145. %% move the stack pointer even further down. We count how many stack
  6146. %% arguments are needed for each function call that occurs inside the
  6147. %% body of the function and find their maximum. Adding this number to the
  6148. %% number of locals gives us how much the \code{rsp} should be moved at
  6149. %% the beginning of the function. In preparation for a function call, we
  6150. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6151. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6152. %% so on.
  6153. %% Upon calling the function, the stack arguments are retrieved by the
  6154. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6155. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6156. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6157. %% the layout of the caller and callee frames. Notice how important it is
  6158. %% that we correctly compute the maximum number of arguments needed for
  6159. %% function calls; if that number is too small then the arguments and
  6160. %% local variables will smash into each other!
  6161. \subsection{Efficient Tail Calls}
  6162. \label{sec:tail-call}
  6163. In general, the amount of stack space used by a program is determined
  6164. by the longest chain of nested function calls. That is, if function
  6165. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6166. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6167. $n$ can grow quite large in the case of recursive or mutually
  6168. recursive functions. However, in some cases we can arrange to use only
  6169. constant space, i.e. $O(1)$, instead of $O(n)$.
  6170. If a function call is the last action in a function body, then that
  6171. call is said to be a \emph{tail call}. In such situations, the frame
  6172. of the caller is no longer needed, so we can pop the caller's frame
  6173. before making the tail call. With this approach, a recursive function
  6174. that only makes tail calls will only use $O(1)$ stack space.
  6175. Functional languages like Racket typically rely heavily on recursive
  6176. functions, so they typically guarantee that all tail calls will be
  6177. optimized in this way.
  6178. However, some care is needed with regards to argument passing in tail
  6179. calls. As mentioned above, for arguments beyond the sixth, the
  6180. convention is to use space in the caller's frame for passing
  6181. arguments. But for a tail call we pop the caller's frame and can no
  6182. longer use it. Another alternative is to use space in the callee's
  6183. frame for passing arguments. However, this option is also problematic
  6184. because the caller and callee's frame overlap in memory. As we begin
  6185. to copy the arguments from their sources in the caller's frame, the
  6186. target locations in the callee's frame might overlap with the sources
  6187. for later arguments! We solve this problem by not using the stack for
  6188. passing more than six arguments but instead using the heap, as we
  6189. describe in the Section~\ref{sec:limit-functions-r4}.
  6190. As mentioned above, for a tail call we pop the caller's frame prior to
  6191. making the tail call. The instructions for popping a frame are the
  6192. instructions that we usually place in the conclusion of a
  6193. function. Thus, we also need to place such code immediately before
  6194. each tail call. These instructions include restoring the callee-saved
  6195. registers, so it is good that the argument passing registers are all
  6196. caller-saved registers.
  6197. One last note regarding which instruction to use to make the tail
  6198. call. When the callee is finished, it should not return to the current
  6199. function, but it should return to the function that called the current
  6200. one. Thus, the return address that is already on the stack is the
  6201. right one, and we should not use \key{callq} to make the tail call, as
  6202. that would unnecessarily overwrite the return address. Instead we can
  6203. simply use the \key{jmp} instruction. Like the indirect function call,
  6204. we write an indirect jump with a register prefixed with an asterisk.
  6205. We recommend using \code{rax} to hold the jump target because the
  6206. preceding conclusion overwrites just about everything else.
  6207. \begin{lstlisting}
  6208. jmp *%rax
  6209. \end{lstlisting}
  6210. \section{Shrink $R_4$}
  6211. \label{sec:shrink-r4}
  6212. The \code{shrink} pass performs a minor modifications to ease the
  6213. later passes. This pass introduces an explicit \code{main} function
  6214. and changes the top \code{ProgramDefsExp} form to
  6215. \code{ProgramDefs} as follows.
  6216. \begin{lstlisting}
  6217. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6218. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6219. \end{lstlisting}
  6220. where $\itm{mainDef}$ is
  6221. \begin{lstlisting}
  6222. (Def main () Integer () |$\Exp'$|)
  6223. \end{lstlisting}
  6224. \section{Reveal Functions and the $F_1$ language}
  6225. \label{sec:reveal-functions-r4}
  6226. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  6227. compilation because it conflates the use of function names and local
  6228. variables. This is a problem because we need to compile the use of a
  6229. function name differently than the use of a local variable; we need to
  6230. use \code{leaq} to convert the function name (a label in x86) to an
  6231. address in a register. Thus, it is a good idea to create a new pass
  6232. that changes function references from just a symbol $f$ to
  6233. \code{(FunRef $f$)}. A good name for this pass is
  6234. \code{reveal-functions} and the output language, $F_1$, is defined in
  6235. Figure~\ref{fig:f1-syntax}.
  6236. \begin{figure}[tp]
  6237. \centering
  6238. \fbox{
  6239. \begin{minipage}{0.96\textwidth}
  6240. \[
  6241. \begin{array}{lcl}
  6242. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6243. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} \mid (\Type \ldots \; \key{->}\; \Type)} \\
  6244. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  6245. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  6246. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  6247. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6248. &\mid& \gray{(\key{vector}\;\Exp \ldots) \mid
  6249. (\key{vector-ref}\;\Exp\;\Int)} \\
  6250. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  6251. (\key{app}\; \Exp \; \Exp \ldots)} \\
  6252. &\mid& (\key{fun-ref}\, \itm{label}) \\
  6253. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type] \ldots) \key{:} \Type \; \Exp)} \\
  6254. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def \ldots)}
  6255. \end{array}
  6256. \]
  6257. \end{minipage}
  6258. }
  6259. \caption{The $F_1$ language, an extension of $R_4$
  6260. (Figure~\ref{fig:r4-syntax}).}
  6261. \label{fig:f1-syntax}
  6262. \end{figure}
  6263. %% Distinguishing between calls in tail position and non-tail position
  6264. %% requires the pass to have some notion of context. We recommend using
  6265. %% two mutually recursive functions, one for processing expressions in
  6266. %% tail position and another for the rest.
  6267. Placing this pass after \code{uniquify} is a good idea, because it
  6268. will make sure that there are no local variables and functions that
  6269. share the same name. On the other hand, \code{reveal-functions} needs
  6270. to come before the \code{explicate-control} pass because that pass
  6271. will help us compile \code{fun-ref} into assignment statements.
  6272. \section{Limit Functions}
  6273. \label{sec:limit-functions-r4}
  6274. This pass transforms functions so that they have at most six
  6275. parameters and transforms all function calls so that they pass at most
  6276. six arguments. A simple strategy for imposing an argument limit of
  6277. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  6278. into a vector, making that subsequent vector the $n$th argument.
  6279. \begin{tabular}{lll}
  6280. \begin{minipage}{0.2\textwidth}
  6281. \begin{lstlisting}
  6282. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  6283. \end{lstlisting}
  6284. \end{minipage}
  6285. &
  6286. $\Rightarrow$
  6287. &
  6288. \begin{minipage}{0.4\textwidth}
  6289. \begin{lstlisting}
  6290. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  6291. \end{lstlisting}
  6292. \end{minipage}
  6293. \end{tabular}
  6294. In the body of the function, all occurrences of the $i$th argument in
  6295. which $i>5$ must be replaced with a \code{vector-ref}.
  6296. \section{Remove Complex Operators and Operands}
  6297. \label{sec:rco-r4}
  6298. The primary decisions to make for this pass is whether to classify
  6299. \code{fun-ref} and \code{app} as either simple or complex
  6300. expressions. Recall that a simple expression will eventually end up as
  6301. just an ``immediate'' argument of an x86 instruction. Function
  6302. application will be translated to a sequence of instructions, so
  6303. \code{app} must be classified as complex expression. Regarding
  6304. \code{fun-ref}, as discussed above, the function label needs to
  6305. be converted to an address using the \code{leaq} instruction. Thus,
  6306. even though \code{fun-ref} seems rather simple, it needs to be
  6307. classified as a complex expression so that we generate an assignment
  6308. statement with a left-hand side that can serve as the target of the
  6309. \code{leaq}.
  6310. \section{Explicate Control and the $C_3$ language}
  6311. \label{sec:explicate-control-r4}
  6312. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  6313. \key{explicate-control}. The three mutually recursive functions for
  6314. this pass, for assignment, tail, and predicate contexts, must all be
  6315. updated with cases for \code{fun-ref} and \code{app}. In
  6316. assignment and predicate contexts, \code{app} becomes \code{call},
  6317. whereas in tail position \code{app} becomes \code{tailcall}. We
  6318. recommend defining a new function for processing function definitions.
  6319. This code is similar to the case for \code{program} in $R_3$. The
  6320. top-level \code{explicate-control} function that handles the
  6321. \code{program} form of $R_4$ can then apply this new function to all
  6322. the function definitions.
  6323. \begin{figure}[tp]
  6324. \fbox{
  6325. \begin{minipage}{0.96\textwidth}
  6326. \[
  6327. \begin{array}{lcl}
  6328. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6329. \\
  6330. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6331. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  6332. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  6333. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6334. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  6335. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6336. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg\ldots) \\
  6337. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6338. \mid (\key{collect} \,\itm{int}) }\\
  6339. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6340. &\mid& \gray{(\key{goto}\,\itm{label})
  6341. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6342. &\mid& (\key{tailcall} \,\Arg\,\Arg\ldots) \\
  6343. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6344. C_3 & ::= & (\key{program}\;\itm{info}\;\Def\ldots)
  6345. \end{array}
  6346. \]
  6347. \end{minipage}
  6348. }
  6349. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  6350. \label{fig:c3-syntax}
  6351. \end{figure}
  6352. \section{Uncover Locals}
  6353. \label{sec:uncover-locals-r4}
  6354. The function for processing $\Tail$ should be updated with a case for
  6355. \code{tailcall}. We also recommend creating a new function for
  6356. processing function definitions. Each function definition in $C_3$ has
  6357. its own set of local variables, so the code for function definitions
  6358. should be similar to the case for the \code{program} form in $C_2$.
  6359. \section{Select Instructions and the x86$_3$ Language}
  6360. \label{sec:select-r4}
  6361. The output of select instructions is a program in the x86$_3$
  6362. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6363. \begin{figure}[tp]
  6364. \fbox{
  6365. \begin{minipage}{0.96\textwidth}
  6366. \[
  6367. \begin{array}{lcl}
  6368. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6369. \mid (\key{deref}\,\Reg\,\Int) } \\
  6370. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6371. \mid (\key{global}\; \itm{name}) } \\
  6372. &\mid& (\key{fun-ref}\; \itm{label})\\
  6373. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6374. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6375. (\key{subq} \; \Arg\; \Arg) \mid
  6376. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6377. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6378. (\key{pushq}\;\Arg) \mid
  6379. (\key{popq}\;\Arg) \mid
  6380. (\key{retq}) } \\
  6381. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6382. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6383. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6384. \mid (\key{jmp} \; \itm{label})
  6385. \mid (\key{j}\itm{cc} \; \itm{label})
  6386. \mid (\key{label} \; \itm{label}) } \\
  6387. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6388. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  6389. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6390. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6391. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6392. \end{array}
  6393. \]
  6394. \end{minipage}
  6395. }
  6396. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6397. \label{fig:x86-3}
  6398. \end{figure}
  6399. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  6400. as follows: \\
  6401. \begin{tabular}{lll}
  6402. \begin{minipage}{0.45\textwidth}
  6403. \begin{lstlisting}
  6404. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  6405. \end{lstlisting}
  6406. \end{minipage}
  6407. &
  6408. $\Rightarrow$
  6409. &
  6410. \begin{minipage}{0.4\textwidth}
  6411. \begin{lstlisting}
  6412. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  6413. \end{lstlisting}
  6414. \end{minipage}
  6415. \end{tabular} \\
  6416. Regarding function definitions, we need to remove their parameters and
  6417. instead perform parameter passing in terms of the conventions
  6418. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  6419. in the argument passing registers, and inside the function we should
  6420. generate a \code{movq} instruction for each parameter, to move the
  6421. argument value from the appropriate register to a new local variable
  6422. with the same name as the old parameter.
  6423. Next, consider the compilation of function calls, which have the
  6424. following form upon input to \code{select-instructions}.
  6425. \begin{lstlisting}
  6426. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  6427. \end{lstlisting}
  6428. In the mirror image of handling the parameters of function
  6429. definitions, the arguments \itm{args} need to be moved to the argument
  6430. passing registers.
  6431. %
  6432. Once the instructions for parameter passing have been generated, the
  6433. function call itself can be performed with an indirect function call,
  6434. for which I recommend creating the new instruction
  6435. \code{indirect-callq}. Of course, the return value from the function
  6436. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  6437. \begin{lstlisting}
  6438. (indirect-callq |\itm{fun}|)
  6439. (movq (reg rax) |\itm{lhs}|)
  6440. \end{lstlisting}
  6441. Regarding tail calls, the parameter passing is the same as non-tail
  6442. calls: generate instructions to move the arguments into to the
  6443. argument passing registers. After that we need to pop the frame from
  6444. the procedure call stack. However, we do not yet know how big the
  6445. frame is; that gets determined during register allocation. So instead
  6446. of generating those instructions here, we invent a new instruction
  6447. that means ``pop the frame and then do an indirect jump'', which we
  6448. name \code{tail-jmp}.
  6449. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  6450. using the label \code{start} for the initial block of a program, and
  6451. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  6452. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  6453. can be compiled to an assignment to \code{rax} followed by a jump to
  6454. \code{conclusion}. With the addition of function definitions, we will
  6455. have a starting block and conclusion for each function, but their
  6456. labels need to be unique. We recommend prepending the function's name
  6457. to \code{start} and \code{conclusion}, respectively, to obtain unique
  6458. labels. (Alternatively, one could \code{gensym} labels for the start
  6459. and conclusion and store them in the $\itm{info}$ field of the
  6460. function definition.)
  6461. \section{Uncover Live}
  6462. %% The rest of the passes need only minor modifications to handle the new
  6463. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  6464. %% \code{leaq}.
  6465. Inside \code{uncover-live}, when computing the $W$ set (written
  6466. variables) for an \code{indirect-callq} instruction, we recommend
  6467. including all the caller-saved registers, which will have the affect
  6468. of making sure that no caller-saved register actually needs to be
  6469. saved.
  6470. \section{Build Interference Graph}
  6471. With the addition of function definitions, we compute an interference
  6472. graph for each function (not just one for the whole program).
  6473. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  6474. spill vector-typed variables that are live during a call to the
  6475. \code{collect}. With the addition of functions to our language, we
  6476. need to revisit this issue. Many functions will perform allocation and
  6477. therefore have calls to the collector inside of them. Thus, we should
  6478. not only spill a vector-typed variable when it is live during a call
  6479. to \code{collect}, but we should spill the variable if it is live
  6480. during any function call. Thus, in the \code{build-interference} pass,
  6481. we recommend adding interference edges between call-live vector-typed
  6482. variables and the callee-saved registers (in addition to the usual
  6483. addition of edges between call-live variables and the caller-saved
  6484. registers).
  6485. \section{Patch Instructions}
  6486. In \code{patch-instructions}, you should deal with the x86
  6487. idiosyncrasy that the destination argument of \code{leaq} must be a
  6488. register. Additionally, you should ensure that the argument of
  6489. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  6490. code generation more convenient, because we will be trampling many
  6491. registers before the tail call (as explained below).
  6492. \section{Print x86}
  6493. For the \code{print-x86} pass, we recommend the following translations:
  6494. \begin{lstlisting}
  6495. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  6496. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  6497. \end{lstlisting}
  6498. Handling \code{tail-jmp} requires a bit more care. A straightforward
  6499. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  6500. is what we will want to do, but before the jump we need to pop the
  6501. current frame. So we need to restore the state of the registers to the
  6502. point they were at when the current function was called. This
  6503. sequence of instructions is the same as the code for the conclusion of
  6504. a function.
  6505. Note that your \code{print-x86} pass needs to add the code for saving
  6506. and restoring callee-saved registers, if you have not already
  6507. implemented that. This is necessary when generating code for function
  6508. definitions.
  6509. \section{An Example Translation}
  6510. Figure~\ref{fig:add-fun} shows an example translation of a simple
  6511. function in $R_4$ to x86. The figure also includes the results of the
  6512. \code{explicate-control} and \code{select-instructions} passes. We
  6513. have omitted the \code{has-type} AST nodes for readability. Can you
  6514. see any ways to improve the translation?
  6515. \begin{figure}[tbp]
  6516. \begin{tabular}{ll}
  6517. \begin{minipage}{0.45\textwidth}
  6518. % s3_2.rkt
  6519. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6520. (program
  6521. (define (add [x : Integer]
  6522. [y : Integer])
  6523. : Integer (+ x y))
  6524. (add 40 2))
  6525. \end{lstlisting}
  6526. $\Downarrow$
  6527. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6528. (program ()
  6529. (define (add86 [x87 : Integer]
  6530. [y88 : Integer]) : Integer ()
  6531. ((add86start . (return (+ x87 y88)))))
  6532. (define (main) : Integer ()
  6533. ((mainstart .
  6534. (seq (assign tmp89 (fun-ref add86))
  6535. (tailcall tmp89 40 2))))))
  6536. \end{lstlisting}
  6537. \end{minipage}
  6538. &
  6539. $\Rightarrow$
  6540. \begin{minipage}{0.5\textwidth}
  6541. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6542. (program ()
  6543. (define (add86)
  6544. ((locals (x87 . Integer) (y88 . Integer))
  6545. (num-params . 2))
  6546. ((add86start .
  6547. (block ()
  6548. (movq (reg rcx) (var x87))
  6549. (movq (reg rdx) (var y88))
  6550. (movq (var x87) (reg rax))
  6551. (addq (var y88) (reg rax))
  6552. (jmp add86conclusion)))))
  6553. (define (main)
  6554. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6555. (num-params . 0))
  6556. ((mainstart .
  6557. (block ()
  6558. (leaq (fun-ref add86) (var tmp89))
  6559. (movq (int 40) (reg rcx))
  6560. (movq (int 2) (reg rdx))
  6561. (tail-jmp (var tmp89))))))
  6562. \end{lstlisting}
  6563. $\Downarrow$
  6564. \end{minipage}
  6565. \end{tabular}
  6566. \begin{tabular}{lll}
  6567. \begin{minipage}{0.3\textwidth}
  6568. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6569. _add90start:
  6570. movq %rcx, %rsi
  6571. movq %rdx, %rcx
  6572. movq %rsi, %rax
  6573. addq %rcx, %rax
  6574. jmp _add90conclusion
  6575. .globl _add90
  6576. .align 16
  6577. _add90:
  6578. pushq %rbp
  6579. movq %rsp, %rbp
  6580. pushq %r12
  6581. pushq %rbx
  6582. pushq %r13
  6583. pushq %r14
  6584. subq $0, %rsp
  6585. jmp _add90start
  6586. _add90conclusion:
  6587. addq $0, %rsp
  6588. popq %r14
  6589. popq %r13
  6590. popq %rbx
  6591. popq %r12
  6592. subq $0, %r15
  6593. popq %rbp
  6594. retq
  6595. \end{lstlisting}
  6596. \end{minipage}
  6597. &
  6598. \begin{minipage}{0.3\textwidth}
  6599. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6600. _mainstart:
  6601. leaq _add90(%rip), %rsi
  6602. movq $40, %rcx
  6603. movq $2, %rdx
  6604. movq %rsi, %rax
  6605. addq $0, %rsp
  6606. popq %r14
  6607. popq %r13
  6608. popq %rbx
  6609. popq %r12
  6610. subq $0, %r15
  6611. popq %rbp
  6612. jmp *%rax
  6613. .globl _main
  6614. .align 16
  6615. _main:
  6616. pushq %rbp
  6617. movq %rsp, %rbp
  6618. pushq %r12
  6619. pushq %rbx
  6620. pushq %r13
  6621. pushq %r14
  6622. subq $0, %rsp
  6623. movq $16384, %rdi
  6624. movq $16, %rsi
  6625. callq _initialize
  6626. movq _rootstack_begin(%rip), %r15
  6627. jmp _mainstart
  6628. \end{lstlisting}
  6629. \end{minipage}
  6630. &
  6631. \begin{minipage}{0.3\textwidth}
  6632. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6633. _mainconclusion:
  6634. addq $0, %rsp
  6635. popq %r14
  6636. popq %r13
  6637. popq %rbx
  6638. popq %r12
  6639. subq $0, %r15
  6640. popq %rbp
  6641. retq
  6642. \end{lstlisting}
  6643. \end{minipage}
  6644. \end{tabular}
  6645. \caption{Example compilation of a simple function to x86.}
  6646. \label{fig:add-fun}
  6647. \end{figure}
  6648. \begin{exercise}\normalfont
  6649. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6650. Create 5 new programs that use functions, including examples that pass
  6651. functions and return functions from other functions and including
  6652. recursive functions. Test your compiler on these new programs and all
  6653. of your previously created test programs.
  6654. \end{exercise}
  6655. \begin{figure}[p]
  6656. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6657. \node (R4) at (0,2) {\large $R_4$};
  6658. \node (R4-2) at (3,2) {\large $R_4$};
  6659. \node (R4-3) at (6,2) {\large $R_4$};
  6660. \node (F1-1) at (12,0) {\large $F_1$};
  6661. \node (F1-2) at (9,0) {\large $F_1$};
  6662. \node (F1-3) at (6,0) {\large $F_1$};
  6663. \node (F1-4) at (3,0) {\large $F_1$};
  6664. \node (C3-1) at (6,-2) {\large $C_3$};
  6665. \node (C3-2) at (3,-2) {\large $C_3$};
  6666. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6667. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6668. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  6669. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6670. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6671. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6672. \path[->,bend left=15] (R4) edge [above] node
  6673. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6674. \path[->,bend left=15] (R4-2) edge [above] node
  6675. {\ttfamily\footnotesize uniquify} (R4-3);
  6676. \path[->,bend left=15] (R4-3) edge [right] node
  6677. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6678. \path[->,bend left=15] (F1-1) edge [below] node
  6679. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6680. \path[->,bend right=15] (F1-2) edge [above] node
  6681. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6682. \path[->,bend right=15] (F1-3) edge [above] node
  6683. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6684. \path[->,bend left=15] (F1-4) edge [right] node
  6685. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6686. \path[->,bend left=15] (C3-1) edge [below] node
  6687. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6688. \path[->,bend right=15] (C3-2) edge [left] node
  6689. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6690. \path[->,bend left=15] (x86-2) edge [left] node
  6691. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6692. \path[->,bend right=15] (x86-2-1) edge [below] node
  6693. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6694. \path[->,bend right=15] (x86-2-2) edge [left] node
  6695. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6696. \path[->,bend left=15] (x86-3) edge [above] node
  6697. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6698. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6699. \end{tikzpicture}
  6700. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6701. \label{fig:R4-passes}
  6702. \end{figure}
  6703. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6704. the compilation of $R_4$.
  6705. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6706. \chapter{Lexically Scoped Functions}
  6707. \label{ch:lambdas}
  6708. This chapter studies lexically scoped functions as they appear in
  6709. functional languages such as Racket. By lexical scoping we mean that a
  6710. function's body may refer to variables whose binding site is outside
  6711. of the function, in an enclosing scope.
  6712. %
  6713. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6714. anonymous function defined using the \key{lambda} form. The body of
  6715. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6716. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6717. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6718. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6719. returned from the function \code{f}. Below the definition of \code{f},
  6720. we have two calls to \code{f} with different arguments for \code{x},
  6721. first \code{5} then \code{3}. The functions returned from \code{f} are
  6722. bound to variables \code{g} and \code{h}. Even though these two
  6723. functions were created by the same \code{lambda}, they are really
  6724. different functions because they use different values for
  6725. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6726. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6727. the result of this program is \code{42}.
  6728. \begin{figure}[btp]
  6729. % s4_6.rkt
  6730. \begin{lstlisting}
  6731. (define (f [x : Integer]) : (Integer -> Integer)
  6732. (let ([y 4])
  6733. (lambda: ([z : Integer]) : Integer
  6734. (+ x (+ y z)))))
  6735. (let ([g (f 5)])
  6736. (let ([h (f 3)])
  6737. (+ (g 11) (h 15))))
  6738. \end{lstlisting}
  6739. \caption{Example of a lexically scoped function.}
  6740. \label{fig:lexical-scoping}
  6741. \end{figure}
  6742. \section{The $R_5$ Language}
  6743. The syntax for this language with anonymous functions and lexical
  6744. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6745. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6746. for function application. In this chapter we shall describe how to
  6747. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6748. into a combination of functions (as in $R_4$) and tuples (as in
  6749. $R_3$).
  6750. \begin{figure}[tp]
  6751. \centering
  6752. \fbox{
  6753. \begin{minipage}{0.96\textwidth}
  6754. \[
  6755. \begin{array}{lcl}
  6756. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6757. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  6758. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  6759. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6760. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6761. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6762. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6763. \mid (\key{and}\;\Exp\;\Exp)
  6764. \mid (\key{or}\;\Exp\;\Exp)
  6765. \mid (\key{not}\;\Exp) } \\
  6766. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6767. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6768. (\key{vector-ref}\;\Exp\;\Int)} \\
  6769. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6770. &\mid& \gray{(\Exp \; \Exp\ldots)} \\
  6771. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp) \\
  6772. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  6773. R_5 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  6774. \end{array}
  6775. \]
  6776. \end{minipage}
  6777. }
  6778. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6779. with \key{lambda}.}
  6780. \label{fig:r5-syntax}
  6781. \end{figure}
  6782. To compile lexically-scoped functions to top-level function
  6783. definitions, the compiler will need to provide special treatment to
  6784. variable occurrences such as \code{x} and \code{y} in the body of the
  6785. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6786. of $R_4$ may not refer to variables defined outside the function. To
  6787. identify such variable occurrences, we review the standard notion of
  6788. free variable.
  6789. \begin{definition}
  6790. A variable is \emph{free with respect to an expression} $e$ if the
  6791. variable occurs inside $e$ but does not have an enclosing binding in
  6792. $e$.
  6793. \end{definition}
  6794. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6795. free with respect to the expression \code{(+ x (+ y z))}. On the
  6796. other hand, only \code{x} and \code{y} are free with respect to the
  6797. following expression because \code{z} is bound by the \code{lambda}.
  6798. \begin{lstlisting}
  6799. (lambda: ([z : Integer]) : Integer
  6800. (+ x (+ y z)))
  6801. \end{lstlisting}
  6802. Once we have identified the free variables of a \code{lambda}, we need
  6803. to arrange for some way to transport, at runtime, the values of those
  6804. variables from the point where the \code{lambda} was created to the
  6805. point where the \code{lambda} is applied. Referring again to
  6806. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6807. needs to be used in the application of \code{g} to \code{11}, but the
  6808. binding of \code{x} to \code{3} needs to be used in the application of
  6809. \code{h} to \code{15}. An efficient solution to the problem, due to
  6810. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6811. free variables together with the function pointer for the lambda's
  6812. code, an arrangement called a \emph{flat closure} (which we shorten to
  6813. just ``closure'') . Fortunately, we have all the ingredients to make
  6814. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6815. Chapter~\ref{ch:functions} gave us function pointers. The function
  6816. pointer shall reside at index $0$ and the values for free variables
  6817. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6818. the two closures created by the two calls to \code{f} in
  6819. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6820. the same \key{lambda}, they share the same function pointer but differ
  6821. in the values for the free variable \code{x}.
  6822. \begin{figure}[tbp]
  6823. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6824. \caption{Example closure representation for the \key{lambda}'s
  6825. in Figure~\ref{fig:lexical-scoping}.}
  6826. \label{fig:closures}
  6827. \end{figure}
  6828. \section{Interpreting $R_5$}
  6829. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6830. $R_5$. The clause for \key{lambda} saves the current environment
  6831. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6832. the environment from the \key{lambda}, the \code{lam-env}, when
  6833. interpreting the body of the \key{lambda}. The \code{lam-env}
  6834. environment is extended with the mapping of parameters to argument
  6835. values.
  6836. \begin{figure}[tbp]
  6837. \begin{lstlisting}
  6838. (define (interp-exp env)
  6839. (lambda (e)
  6840. (define recur (interp-exp env))
  6841. (match e
  6842. ...
  6843. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6844. `(lambda ,xs ,body ,env)]
  6845. [`(app ,fun ,args ...)
  6846. (define fun-val ((interp-exp env) fun))
  6847. (define arg-vals (map (interp-exp env) args))
  6848. (match fun-val
  6849. [`(lambda (,xs ...) ,body ,lam-env)
  6850. (define new-env (append (map cons xs arg-vals) lam-env))
  6851. ((interp-exp new-env) body)]
  6852. [else (error "interp-exp, expected function, not" fun-val)])]
  6853. [else (error 'interp-exp "unrecognized expression")]
  6854. )))
  6855. \end{lstlisting}
  6856. \caption{Interpreter for $R_5$.}
  6857. \label{fig:interp-R5}
  6858. \end{figure}
  6859. \section{Type Checking $R_5$}
  6860. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6861. \key{lambda} form. The body of the \key{lambda} is checked in an
  6862. environment that includes the current environment (because it is
  6863. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6864. require the body's type to match the declared return type.
  6865. \begin{figure}[tbp]
  6866. \begin{lstlisting}
  6867. (define (typecheck-R5 env)
  6868. (lambda (e)
  6869. (match e
  6870. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6871. (define new-env (append (map cons xs Ts) env))
  6872. (define bodyT ((typecheck-R5 new-env) body))
  6873. (cond [(equal? rT bodyT)
  6874. `(,@Ts -> ,rT)]
  6875. [else
  6876. (error "mismatch in return type" bodyT rT)])]
  6877. ...
  6878. )))
  6879. \end{lstlisting}
  6880. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6881. \label{fig:typecheck-R5}
  6882. \end{figure}
  6883. \section{Closure Conversion}
  6884. The compiling of lexically-scoped functions into top-level function
  6885. definitions is accomplished in the pass \code{convert-to-closures}
  6886. that comes after \code{reveal-functions} and before
  6887. \code{limit-functions}.
  6888. As usual, we shall implement the pass as a recursive function over the
  6889. AST. All of the action is in the clauses for \key{lambda} and
  6890. \key{app}. We transform a \key{lambda} expression into an expression
  6891. that creates a closure, that is, creates a vector whose first element
  6892. is a function pointer and the rest of the elements are the free
  6893. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6894. generated to identify the function.
  6895. \begin{tabular}{lll}
  6896. \begin{minipage}{0.4\textwidth}
  6897. \begin{lstlisting}
  6898. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6899. \end{lstlisting}
  6900. \end{minipage}
  6901. &
  6902. $\Rightarrow$
  6903. &
  6904. \begin{minipage}{0.4\textwidth}
  6905. \begin{lstlisting}
  6906. (vector |\itm{name}| |\itm{fvs}| ...)
  6907. \end{lstlisting}
  6908. \end{minipage}
  6909. \end{tabular} \\
  6910. %
  6911. In addition to transforming each \key{lambda} into a \key{vector}, we
  6912. must create a top-level function definition for each \key{lambda}, as
  6913. shown below.\\
  6914. \begin{minipage}{0.8\textwidth}
  6915. \begin{lstlisting}
  6916. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6917. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6918. ...
  6919. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6920. |\itm{body'}|)...))
  6921. \end{lstlisting}
  6922. \end{minipage}\\
  6923. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6924. parameters are the normal parameters of the \key{lambda}. The types
  6925. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6926. underscore is a dummy type because it is rather difficult to give a
  6927. type to the function in the closure's type, and it does not matter.
  6928. The sequence of \key{let} forms bind the free variables to their
  6929. values obtained from the closure.
  6930. We transform function application into code that retrieves the
  6931. function pointer from the closure and then calls the function, passing
  6932. in the closure as the first argument. We bind $e'$ to a temporary
  6933. variable to avoid code duplication.
  6934. \begin{tabular}{lll}
  6935. \begin{minipage}{0.3\textwidth}
  6936. \begin{lstlisting}
  6937. (app |$e$| |\itm{es}| ...)
  6938. \end{lstlisting}
  6939. \end{minipage}
  6940. &
  6941. $\Rightarrow$
  6942. &
  6943. \begin{minipage}{0.5\textwidth}
  6944. \begin{lstlisting}
  6945. (let ([|\itm{tmp}| |$e'$|])
  6946. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6947. \end{lstlisting}
  6948. \end{minipage}
  6949. \end{tabular} \\
  6950. There is also the question of what to do with top-level function
  6951. definitions. To maintain a uniform translation of function
  6952. application, we turn function references into closures.
  6953. \begin{tabular}{lll}
  6954. \begin{minipage}{0.3\textwidth}
  6955. \begin{lstlisting}
  6956. (fun-ref |$f$|)
  6957. \end{lstlisting}
  6958. \end{minipage}
  6959. &
  6960. $\Rightarrow$
  6961. &
  6962. \begin{minipage}{0.5\textwidth}
  6963. \begin{lstlisting}
  6964. (vector (fun-ref |$f$|))
  6965. \end{lstlisting}
  6966. \end{minipage}
  6967. \end{tabular} \\
  6968. %
  6969. The top-level function definitions need to be updated as well to take
  6970. an extra closure parameter.
  6971. \section{An Example Translation}
  6972. \label{sec:example-lambda}
  6973. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6974. conversion for the example program demonstrating lexical scoping that
  6975. we discussed at the beginning of this chapter.
  6976. \begin{figure}[h]
  6977. \begin{minipage}{0.8\textwidth}
  6978. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6979. (program
  6980. (define (f [x : Integer]) : (Integer -> Integer)
  6981. (let ([y 4])
  6982. (lambda: ([z : Integer]) : Integer
  6983. (+ x (+ y z)))))
  6984. (let ([g (f 5)])
  6985. (let ([h (f 3)])
  6986. (+ (g 11) (h 15)))))
  6987. \end{lstlisting}
  6988. $\Downarrow$
  6989. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6990. (program (type Integer)
  6991. (define (f (x : Integer)) : (Integer -> Integer)
  6992. (let ((y 4))
  6993. (lambda: ((z : Integer)) : Integer
  6994. (+ x (+ y z)))))
  6995. (let ((g (app (fun-ref f) 5)))
  6996. (let ((h (app (fun-ref f) 3)))
  6997. (+ (app g 11) (app h 15)))))
  6998. \end{lstlisting}
  6999. $\Downarrow$
  7000. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7001. (program (type Integer)
  7002. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  7003. (let ((y 4))
  7004. (vector (fun-ref lam.1) x y)))
  7005. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  7006. (let ((x (vector-ref clos.2 1)))
  7007. (let ((y (vector-ref clos.2 2)))
  7008. (+ x (+ y z)))))
  7009. (let ((g (let ((t.1 (vector (fun-ref f))))
  7010. (app (vector-ref t.1 0) t.1 5))))
  7011. (let ((h (let ((t.2 (vector (fun-ref f))))
  7012. (app (vector-ref t.2 0) t.2 3))))
  7013. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  7014. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  7015. \end{lstlisting}
  7016. \end{minipage}
  7017. \caption{Example of closure conversion.}
  7018. \label{fig:lexical-functions-example}
  7019. \end{figure}
  7020. \begin{figure}[p]
  7021. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7022. \node (R4) at (0,2) {\large $R_4$};
  7023. \node (R4-2) at (3,2) {\large $R_4$};
  7024. \node (R4-3) at (6,2) {\large $R_4$};
  7025. \node (F1-1) at (12,0) {\large $F_1$};
  7026. \node (F1-2) at (9,0) {\large $F_1$};
  7027. \node (F1-3) at (6,0) {\large $F_1$};
  7028. \node (F1-4) at (3,0) {\large $F_1$};
  7029. \node (F1-5) at (0,0) {\large $F_1$};
  7030. \node (C3-1) at (6,-2) {\large $C_3$};
  7031. \node (C3-2) at (3,-2) {\large $C_3$};
  7032. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7033. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7034. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7035. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7036. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7037. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7038. \path[->,bend left=15] (R4) edge [above] node
  7039. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  7040. \path[->,bend left=15] (R4-2) edge [above] node
  7041. {\ttfamily\footnotesize uniquify} (R4-3);
  7042. \path[->] (R4-3) edge [right] node
  7043. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7044. \path[->,bend left=15] (F1-1) edge [below] node
  7045. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7046. \path[->,bend right=15] (F1-2) edge [above] node
  7047. {\ttfamily\footnotesize limit-functions} (F1-3);
  7048. \path[->,bend right=15] (F1-3) edge [above] node
  7049. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7050. \path[->,bend right=15] (F1-4) edge [above] node
  7051. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7052. \path[->] (F1-5) edge [left] node
  7053. {\ttfamily\footnotesize explicate-control} (C3-1);
  7054. \path[->,bend left=15] (C3-1) edge [below] node
  7055. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7056. \path[->,bend right=15] (C3-2) edge [left] node
  7057. {\ttfamily\footnotesize select-instr.} (x86-2);
  7058. \path[->,bend left=15] (x86-2) edge [left] node
  7059. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7060. \path[->,bend right=15] (x86-2-1) edge [below] node
  7061. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7062. \path[->,bend right=15] (x86-2-2) edge [left] node
  7063. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7064. \path[->,bend left=15] (x86-3) edge [above] node
  7065. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7066. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7067. \end{tikzpicture}
  7068. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7069. functions.}
  7070. \label{fig:R5-passes}
  7071. \end{figure}
  7072. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7073. for the compilation of $R_5$.
  7074. \begin{exercise}\normalfont
  7075. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7076. Create 5 new programs that use \key{lambda} functions and make use of
  7077. lexical scoping. Test your compiler on these new programs and all of
  7078. your previously created test programs.
  7079. \end{exercise}
  7080. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7081. \chapter{Dynamic Typing}
  7082. \label{ch:type-dynamic}
  7083. In this chapter we discuss the compilation of a dynamically typed
  7084. language, named $R_7$, that is a subset of the Racket
  7085. language. (Recall that in the previous chapters we have studied
  7086. subsets of the \emph{Typed} Racket language.) In dynamically typed
  7087. languages, an expression may produce values of differing
  7088. type. Consider the following example with a conditional expression
  7089. that may return a Boolean or an integer depending on the input to the
  7090. program.
  7091. \begin{lstlisting}
  7092. (not (if (eq? (read) 1) #f 0))
  7093. \end{lstlisting}
  7094. Languages that allow expressions to produce different kinds of values
  7095. are called \emph{polymorphic}. There are many kinds of polymorphism,
  7096. such as subtype polymorphism and parametric
  7097. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  7098. talking about here does not have a special name, but it is the usual
  7099. kind that arises in dynamically typed languages.
  7100. Another characteristic of dynamically typed languages is that
  7101. primitive operations, such as \code{not}, are often defined to operate
  7102. on many different types of values. In fact, in Racket, the \code{not}
  7103. operator produces a result for any kind of value: given \code{\#f} it
  7104. returns \code{\#t} and given anything else it returns \code{\#f}.
  7105. Furthermore, even when primitive operations restrict their inputs to
  7106. values of a certain type, this restriction is enforced at runtime
  7107. instead of during compilation. For example, the following vector
  7108. reference results in a run-time contract violation.
  7109. \begin{lstlisting}
  7110. (vector-ref (vector 42) #t)
  7111. \end{lstlisting}
  7112. \begin{figure}[tp]
  7113. \centering
  7114. \fbox{
  7115. \begin{minipage}{0.97\textwidth}
  7116. \[
  7117. \begin{array}{rcl}
  7118. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7119. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7120. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  7121. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  7122. &\mid& \key{\#t} \mid \key{\#f}
  7123. \mid (\key{and}\;\Exp\;\Exp)
  7124. \mid (\key{or}\;\Exp\;\Exp)
  7125. \mid (\key{not}\;\Exp) \\
  7126. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  7127. &\mid& (\key{vector}\;\Exp\ldots) \mid
  7128. (\key{vector-ref}\;\Exp\;\Exp) \\
  7129. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  7130. &\mid& (\Exp \; \Exp\ldots) \mid (\key{lambda}\; (\Var\ldots) \; \Exp) \\
  7131. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7132. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7133. \Def &::=& (\key{define}\; (\Var \; \Var\ldots) \; \Exp) \\
  7134. R_7 &::=& (\key{program} \; \Def\ldots\; \Exp)
  7135. \end{array}
  7136. \]
  7137. \end{minipage}
  7138. }
  7139. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7140. \label{fig:r7-syntax}
  7141. \end{figure}
  7142. The syntax of $R_7$, our subset of Racket, is defined in
  7143. Figure~\ref{fig:r7-syntax}.
  7144. %
  7145. The definitional interpreter for $R_7$ is given in
  7146. Figure~\ref{fig:interp-R7}.
  7147. \begin{figure}[tbp]
  7148. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7149. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  7150. (define (valid-op? op) (member op '(+ - and or not)))
  7151. (define (interp-r7 env)
  7152. (lambda (ast)
  7153. (define recur (interp-r7 env))
  7154. (match ast
  7155. [(? symbol?) (lookup ast env)]
  7156. [(? integer?) `(inject ,ast Integer)]
  7157. [#t `(inject #t Boolean)]
  7158. [#f `(inject #f Boolean)]
  7159. [`(read) `(inject ,(read-fixnum) Integer)]
  7160. [`(lambda (,xs ...) ,body)
  7161. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  7162. [`(define (,f ,xs ...) ,body)
  7163. (mcons f `(lambda ,xs ,body))]
  7164. [`(program ,ds ... ,body)
  7165. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  7166. (for/list ([b top-level])
  7167. (set-mcdr! b (match (mcdr b)
  7168. [`(lambda ,xs ,body)
  7169. `(inject (lambda ,xs ,body ,top-level)
  7170. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  7171. ((interp-r7 top-level) body))]
  7172. [`(vector ,(app recur elts) ...)
  7173. (define tys (map get-tagged-type elts))
  7174. `(inject ,(apply vector elts) (Vector ,@tys))]
  7175. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  7176. (match v1
  7177. [`(inject ,vec ,ty)
  7178. (vector-set! vec n v2)
  7179. `(inject (void) Void)])]
  7180. [`(vector-ref ,(app recur v) ,n)
  7181. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  7182. [`(let ([,x ,(app recur v)]) ,body)
  7183. ((interp-r7 (cons (cons x v) env)) body)]
  7184. [`(,op ,es ...) #:when (valid-op? op)
  7185. (interp-r7-op op (for/list ([e es]) (recur e)))]
  7186. [`(eq? ,(app recur l) ,(app recur r))
  7187. `(inject ,(equal? l r) Boolean)]
  7188. [`(if ,(app recur q) ,t ,f)
  7189. (match q
  7190. [`(inject #f Boolean) (recur f)]
  7191. [else (recur t)])]
  7192. [`(,(app recur f-val) ,(app recur vs) ...)
  7193. (match f-val
  7194. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  7195. (define new-env (append (map cons xs vs) lam-env))
  7196. ((interp-r7 new-env) body)]
  7197. [else (error "interp-r7, expected function, not" f-val)])])))
  7198. \end{lstlisting}
  7199. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  7200. \label{fig:interp-R7}
  7201. \end{figure}
  7202. Let us consider how we might compile $R_7$ to x86, thinking about the
  7203. first example above. Our bit-level representation of the Boolean
  7204. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7205. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7206. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7207. general, cannot be determined at compile time, but depends on the
  7208. runtime type of its input, as in the example above that depends on the
  7209. result of \code{(read)}.
  7210. The way around this problem is to include information about a value's
  7211. runtime type in the value itself, so that this information can be
  7212. inspected by operators such as \code{not}. In particular, we shall
  7213. steal the 3 right-most bits from our 64-bit values to encode the
  7214. runtime type. We shall use $001$ to identify integers, $100$ for
  7215. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7216. void value. We shall refer to these 3 bits as the \emph{tag} and we
  7217. define the following auxiliary function.
  7218. \begin{align*}
  7219. \itm{tagof}(\key{Integer}) &= 001 \\
  7220. \itm{tagof}(\key{Boolean}) &= 100 \\
  7221. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7222. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7223. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7224. \itm{tagof}(\key{Void}) &= 101
  7225. \end{align*}
  7226. (We shall say more about the new \key{Vectorof} type shortly.)
  7227. This stealing of 3 bits comes at some
  7228. price: our integers are reduced to ranging from $-2^{60}$ to
  7229. $2^{60}$. The stealing does not adversely affect vectors and
  7230. procedures because those values are addresses, and our addresses are
  7231. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7232. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7233. bits with the tag and we can simply zero-out the tag to recover the
  7234. original address.
  7235. In some sense, these tagged values are a new kind of value. Indeed,
  7236. we can extend our \emph{typed} language with tagged values by adding a
  7237. new type to classify them, called \key{Any}, and with operations for
  7238. creating and using tagged values, yielding the $R_6$ language that we
  7239. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7240. fundamental support for polymorphism and runtime types that we need to
  7241. support dynamic typing.
  7242. There is an interesting interaction between tagged values and garbage
  7243. collection. A variable of type \code{Any} might refer to a vector and
  7244. therefore it might be a root that needs to be inspected and copied
  7245. during garbage collection. Thus, we need to treat variables of type
  7246. \code{Any} in a similar way to variables of type \code{Vector} for
  7247. purposes of register allocation, which we discuss in
  7248. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7249. variable of type \code{Any} is spilled, it must be spilled to the root
  7250. stack. But this means that the garbage collector needs to be able to
  7251. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7252. value that points to a tuple, and (3) a tagged value that is not a
  7253. tuple. We enable this differentiation by choosing not to use the tag
  7254. $000$. Instead, that bit pattern is reserved for identifying plain old
  7255. pointers to tuples. On the other hand, if one of the first three bits
  7256. is set, then we have a tagged value, and inspecting the tag can
  7257. differentiation between vectors ($010$) and the other kinds of values.
  7258. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  7259. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7260. extend our compiler to handle the new features of $R_6$
  7261. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7262. \ref{sec:register-allocation-r6}).
  7263. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7264. \label{sec:r6-lang}
  7265. \begin{figure}[tp]
  7266. \centering
  7267. \fbox{
  7268. \begin{minipage}{0.97\textwidth}
  7269. \[
  7270. \begin{array}{lcl}
  7271. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7272. \mid (\key{Vector}\;\Type\ldots) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  7273. &\mid& \gray{(\Type\ldots \; \key{->}\; \Type)} \mid \key{Any} \\
  7274. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}\ldots) \\
  7275. &\mid& (\key{Any}\ldots \; \key{->}\; \key{Any})\\
  7276. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7277. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  7278. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  7279. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  7280. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7281. \mid (\key{and}\;\Exp\;\Exp)
  7282. \mid (\key{or}\;\Exp\;\Exp)
  7283. \mid (\key{not}\;\Exp)} \\
  7284. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  7285. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7286. (\key{vector-ref}\;\Exp\;\Int)} \\
  7287. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  7288. &\mid& \gray{(\Exp \; \Exp\ldots)
  7289. \mid (\key{lambda:}\; ([\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7290. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  7291. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  7292. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  7293. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; \Exp)} \\
  7294. R_6 &::=& \gray{(\key{program} \; \Def\ldots \; \Exp)}
  7295. \end{array}
  7296. \]
  7297. \end{minipage}
  7298. }
  7299. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7300. with \key{Any}.}
  7301. \label{fig:r6-syntax}
  7302. \end{figure}
  7303. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  7304. $(\key{inject}\; e\; T)$ form converts the value produced by
  7305. expression $e$ of type $T$ into a tagged value. The
  7306. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  7307. expression $e$ into a value of type $T$ or else halts the program if
  7308. the type tag is equivalent to $T$. We treat
  7309. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  7310. $(\key{Vector}\;\key{Any}\;\ldots)$.
  7311. Note that in both \key{inject} and
  7312. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  7313. which simplifies the implementation and corresponds with what is
  7314. needed for compiling untyped Racket. The type predicates,
  7315. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  7316. if the tag corresponds to the predicate, and return \key{\#t}
  7317. otherwise.
  7318. %
  7319. Selections from the type checker for $R_6$ are shown in
  7320. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  7321. Figure~\ref{fig:interp-R6}.
  7322. \begin{figure}[btp]
  7323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7324. (define (flat-ty? ty) ...)
  7325. (define (typecheck-R6 env)
  7326. (lambda (e)
  7327. (define recur (typecheck-R6 env))
  7328. (match e
  7329. [`(inject ,e ,ty)
  7330. (unless (flat-ty? ty)
  7331. (error "may only inject a value of flat type, not ~a" ty))
  7332. (define-values (new-e e-ty) (recur e))
  7333. (cond
  7334. [(equal? e-ty ty)
  7335. (values `(inject ,new-e ,ty) 'Any)]
  7336. [else
  7337. (error "inject expected ~a to have type ~a" e ty)])]
  7338. [`(project ,e ,ty)
  7339. (unless (flat-ty? ty)
  7340. (error "may only project to a flat type, not ~a" ty))
  7341. (define-values (new-e e-ty) (recur e))
  7342. (cond
  7343. [(equal? e-ty 'Any)
  7344. (values `(project ,new-e ,ty) ty)]
  7345. [else
  7346. (error "project expected ~a to have type Any" e)])]
  7347. [`(vector-ref ,e ,i)
  7348. (define-values (new-e e-ty) (recur e))
  7349. (match e-ty
  7350. [`(Vector ,ts ...) ...]
  7351. [`(Vectorof ,ty)
  7352. (unless (exact-nonnegative-integer? i)
  7353. (error 'type-check "invalid index ~a" i))
  7354. (values `(vector-ref ,new-e ,i) ty)]
  7355. [else (error "expected a vector in vector-ref, not" e-ty)])]
  7356. ...
  7357. )))
  7358. \end{lstlisting}
  7359. \caption{Type checker for parts of the $R_6$ language.}
  7360. \label{fig:typecheck-R6}
  7361. \end{figure}
  7362. % to do: add rules for vector-ref, etc. for Vectorof
  7363. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  7364. \begin{figure}[btp]
  7365. \begin{lstlisting}
  7366. (define primitives (set 'boolean? ...))
  7367. (define (interp-op op)
  7368. (match op
  7369. ['boolean? (lambda (v)
  7370. (match v
  7371. [`(tagged ,v1 Boolean) #t]
  7372. [else #f]))]
  7373. ...))
  7374. ;; Equivalence of flat types
  7375. (define (tyeq? t1 t2)
  7376. (match `(,t1 ,t2)
  7377. [`((Vectorof Any) (Vector ,t2s ...))
  7378. (for/and ([t2 t2s]) (eq? t2 'Any))]
  7379. [`((Vector ,t1s ...) (Vectorof Any))
  7380. (for/and ([t1 t1s]) (eq? t1 'Any))]
  7381. [else (equal? t1 t2)]))
  7382. (define (interp-R6 env)
  7383. (lambda (ast)
  7384. (match ast
  7385. [`(inject ,e ,t)
  7386. `(tagged ,((interp-R6 env) e) ,t)]
  7387. [`(project ,e ,t2)
  7388. (define v ((interp-R6 env) e))
  7389. (match v
  7390. [`(tagged ,v1 ,t1)
  7391. (cond [(tyeq? t1 t2)
  7392. v1]
  7393. [else
  7394. (error "in project, type mismatch" t1 t2)])]
  7395. [else
  7396. (error "in project, expected tagged value" v)])]
  7397. ...)))
  7398. \end{lstlisting}
  7399. \caption{Interpreter for $R_6$.}
  7400. \label{fig:interp-R6}
  7401. \end{figure}
  7402. %\clearpage
  7403. \section{Shrinking $R_6$}
  7404. \label{sec:shrink-r6}
  7405. In the \code{shrink} pass we recommend compiling \code{project} into
  7406. an explicit \code{if} expression that uses three new operations:
  7407. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  7408. \code{tag-of-any} operation retrieves the type tag from a tagged value
  7409. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  7410. value from a tagged value. Finally, the \code{exit} operation ends the
  7411. execution of the program by invoking the operating system's
  7412. \code{exit} function. So the translation for \code{project} is as
  7413. follows. (We have omitted the \code{has-type} AST nodes to make this
  7414. output more readable.)
  7415. \begin{tabular}{lll}
  7416. \begin{minipage}{0.3\textwidth}
  7417. \begin{lstlisting}
  7418. (project |$e$| |$\Type$|)
  7419. \end{lstlisting}
  7420. \end{minipage}
  7421. &
  7422. $\Rightarrow$
  7423. &
  7424. \begin{minipage}{0.5\textwidth}
  7425. \begin{lstlisting}
  7426. (let ([|$\itm{tmp}$| |$e'$|])
  7427. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  7428. (value-of-any |$\itm{tmp}$|)
  7429. (exit)))
  7430. \end{lstlisting}
  7431. \end{minipage}
  7432. \end{tabular} \\
  7433. Similarly, we recommend translating the type predicates
  7434. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  7435. \section{Instruction Selection for $R_6$}
  7436. \label{sec:select-r6}
  7437. \paragraph{Inject}
  7438. We recommend compiling an \key{inject} as follows if the type is
  7439. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  7440. destination to the left by the number of bits specified its source
  7441. argument (in this case $3$, the length of the tag) and it preserves
  7442. the sign of the integer. We use the \key{orq} instruction to combine
  7443. the tag and the value to form the tagged value. \\
  7444. \begin{tabular}{lll}
  7445. \begin{minipage}{0.4\textwidth}
  7446. \begin{lstlisting}
  7447. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7448. \end{lstlisting}
  7449. \end{minipage}
  7450. &
  7451. $\Rightarrow$
  7452. &
  7453. \begin{minipage}{0.5\textwidth}
  7454. \begin{lstlisting}
  7455. (movq |$e'$| |\itm{lhs}'|)
  7456. (salq (int 3) |\itm{lhs}'|)
  7457. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7458. \end{lstlisting}
  7459. \end{minipage}
  7460. \end{tabular} \\
  7461. The instruction selection for vectors and procedures is different
  7462. because their is no need to shift them to the left. The rightmost 3
  7463. bits are already zeros as described above. So we just combine the
  7464. value and the tag using \key{orq}. \\
  7465. \begin{tabular}{lll}
  7466. \begin{minipage}{0.4\textwidth}
  7467. \begin{lstlisting}
  7468. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  7469. \end{lstlisting}
  7470. \end{minipage}
  7471. &
  7472. $\Rightarrow$
  7473. &
  7474. \begin{minipage}{0.5\textwidth}
  7475. \begin{lstlisting}
  7476. (movq |$e'$| |\itm{lhs}'|)
  7477. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  7478. \end{lstlisting}
  7479. \end{minipage}
  7480. \end{tabular}
  7481. \paragraph{Tag of Any}
  7482. Recall that the \code{tag-of-any} operation extracts the type tag from
  7483. a value of type \code{Any}. The type tag is the bottom three bits, so
  7484. we obtain the tag by taking the bitwise-and of the value with $111$
  7485. ($7$ in decimal).
  7486. \begin{tabular}{lll}
  7487. \begin{minipage}{0.4\textwidth}
  7488. \begin{lstlisting}
  7489. (assign |\itm{lhs}| (tag-of-any |$e$|))
  7490. \end{lstlisting}
  7491. \end{minipage}
  7492. &
  7493. $\Rightarrow$
  7494. &
  7495. \begin{minipage}{0.5\textwidth}
  7496. \begin{lstlisting}
  7497. (movq |$e'$| |\itm{lhs}'|)
  7498. (andq (int 7) |\itm{lhs}'|)
  7499. \end{lstlisting}
  7500. \end{minipage}
  7501. \end{tabular}
  7502. \paragraph{Value of Any}
  7503. Like \key{inject}, the instructions for \key{value-of-any} are
  7504. different depending on whether the type $T$ is a pointer (vector or
  7505. procedure) or not (Integer or Boolean). The following shows the
  7506. instruction selection for Integer and Boolean. We produce an untagged
  7507. value by shifting it to the right by 3 bits.
  7508. %
  7509. \\
  7510. \begin{tabular}{lll}
  7511. \begin{minipage}{0.4\textwidth}
  7512. \begin{lstlisting}
  7513. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7514. \end{lstlisting}
  7515. \end{minipage}
  7516. &
  7517. $\Rightarrow$
  7518. &
  7519. \begin{minipage}{0.5\textwidth}
  7520. \begin{lstlisting}
  7521. (movq |$e'$| |\itm{lhs}'|)
  7522. (sarq (int 3) |\itm{lhs}'|)
  7523. \end{lstlisting}
  7524. \end{minipage}
  7525. \end{tabular} \\
  7526. %
  7527. In the case for vectors and procedures, there is no need to
  7528. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7529. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7530. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7531. \code{movq} into the destination $\itm{lhs}$. We then generate
  7532. \code{andq} with the tagged value to get the desired result. \\
  7533. %
  7534. \begin{tabular}{lll}
  7535. \begin{minipage}{0.4\textwidth}
  7536. \begin{lstlisting}
  7537. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7538. \end{lstlisting}
  7539. \end{minipage}
  7540. &
  7541. $\Rightarrow$
  7542. &
  7543. \begin{minipage}{0.5\textwidth}
  7544. \begin{lstlisting}
  7545. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7546. (andq |$e'$| |\itm{lhs}'|)
  7547. \end{lstlisting}
  7548. \end{minipage}
  7549. \end{tabular}
  7550. %% \paragraph{Type Predicates} We leave it to the reader to
  7551. %% devise a sequence of instructions to implement the type predicates
  7552. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7553. \section{Register Allocation for $R_6$}
  7554. \label{sec:register-allocation-r6}
  7555. As mentioned above, a variable of type \code{Any} might refer to a
  7556. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7557. of type \code{Any} in the same way that it treats variables of type
  7558. \code{Vector} for purposes of garbage collection. In particular,
  7559. \begin{itemize}
  7560. \item If a variable of type \code{Any} is live during a function call,
  7561. then it must be spilled. One way to accomplish this is to augment
  7562. the pass \code{build-interference} to mark all variables that are
  7563. live after a \code{callq} as interfering with all the registers.
  7564. \item If a variable of type \code{Any} is spilled, it must be spilled
  7565. to the root stack instead of the normal procedure call stack.
  7566. \end{itemize}
  7567. \begin{exercise}\normalfont
  7568. Expand your compiler to handle $R_6$ as discussed in the last few
  7569. sections. Create 5 new programs that use the \code{Any} type and the
  7570. new operations (\code{inject}, \code{project}, \code{boolean?},
  7571. etc.). Test your compiler on these new programs and all of your
  7572. previously created test programs.
  7573. \end{exercise}
  7574. \section{Compiling $R_7$ to $R_6$}
  7575. \label{sec:compile-r7}
  7576. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7577. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7578. given a subexpression $e$ of $R_7$, the pass will produce an
  7579. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7580. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7581. the Boolean \code{\#t}, which must be injected to produce an
  7582. expression of type \key{Any}.
  7583. %
  7584. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7585. addition, is representative of compilation for many operations: the
  7586. arguments have type \key{Any} and must be projected to \key{Integer}
  7587. before the addition can be performed.
  7588. The compilation of \key{lambda} (third row of
  7589. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7590. produce type annotations: we simply use \key{Any}.
  7591. %
  7592. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7593. has to account for some differences in behavior between $R_7$ and
  7594. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7595. kind of values can be used in various places. For example, the
  7596. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7597. the arguments need not be of the same type (but in that case, the
  7598. result will be \code{\#f}).
  7599. \begin{figure}[btp]
  7600. \centering
  7601. \begin{tabular}{|lll|} \hline
  7602. \begin{minipage}{0.25\textwidth}
  7603. \begin{lstlisting}
  7604. #t
  7605. \end{lstlisting}
  7606. \end{minipage}
  7607. &
  7608. $\Rightarrow$
  7609. &
  7610. \begin{minipage}{0.6\textwidth}
  7611. \begin{lstlisting}
  7612. (inject #t Boolean)
  7613. \end{lstlisting}
  7614. \end{minipage}
  7615. \\[2ex]\hline
  7616. \begin{minipage}{0.25\textwidth}
  7617. \begin{lstlisting}
  7618. (+ |$e_1$| |$e_2$|)
  7619. \end{lstlisting}
  7620. \end{minipage}
  7621. &
  7622. $\Rightarrow$
  7623. &
  7624. \begin{minipage}{0.6\textwidth}
  7625. \begin{lstlisting}
  7626. (inject
  7627. (+ (project |$e'_1$| Integer)
  7628. (project |$e'_2$| Integer))
  7629. Integer)
  7630. \end{lstlisting}
  7631. \end{minipage}
  7632. \\[2ex]\hline
  7633. \begin{minipage}{0.25\textwidth}
  7634. \begin{lstlisting}
  7635. (lambda (|$x_1 \ldots$|) |$e$|)
  7636. \end{lstlisting}
  7637. \end{minipage}
  7638. &
  7639. $\Rightarrow$
  7640. &
  7641. \begin{minipage}{0.6\textwidth}
  7642. \begin{lstlisting}
  7643. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7644. (Any|$\ldots$|Any -> Any))
  7645. \end{lstlisting}
  7646. \end{minipage}
  7647. \\[2ex]\hline
  7648. \begin{minipage}{0.25\textwidth}
  7649. \begin{lstlisting}
  7650. (app |$e_0$| |$e_1 \ldots e_n$|)
  7651. \end{lstlisting}
  7652. \end{minipage}
  7653. &
  7654. $\Rightarrow$
  7655. &
  7656. \begin{minipage}{0.6\textwidth}
  7657. \begin{lstlisting}
  7658. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7659. |$e'_1 \ldots e'_n$|)
  7660. \end{lstlisting}
  7661. \end{minipage}
  7662. \\[2ex]\hline
  7663. \begin{minipage}{0.25\textwidth}
  7664. \begin{lstlisting}
  7665. (vector-ref |$e_1$| |$e_2$|)
  7666. \end{lstlisting}
  7667. \end{minipage}
  7668. &
  7669. $\Rightarrow$
  7670. &
  7671. \begin{minipage}{0.6\textwidth}
  7672. \begin{lstlisting}
  7673. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7674. (let ([tmp2 (project |$e'_2$| Integer)])
  7675. (vector-ref tmp1 tmp2)))
  7676. \end{lstlisting}
  7677. \end{minipage}
  7678. \\[2ex]\hline
  7679. \begin{minipage}{0.25\textwidth}
  7680. \begin{lstlisting}
  7681. (if |$e_1$| |$e_2$| |$e_3$|)
  7682. \end{lstlisting}
  7683. \end{minipage}
  7684. &
  7685. $\Rightarrow$
  7686. &
  7687. \begin{minipage}{0.6\textwidth}
  7688. \begin{lstlisting}
  7689. (if (eq? |$e'_1$| (inject #f Boolean))
  7690. |$e'_3$|
  7691. |$e'_2$|)
  7692. \end{lstlisting}
  7693. \end{minipage}
  7694. \\[2ex]\hline
  7695. \begin{minipage}{0.25\textwidth}
  7696. \begin{lstlisting}
  7697. (eq? |$e_1$| |$e_2$|)
  7698. \end{lstlisting}
  7699. \end{minipage}
  7700. &
  7701. $\Rightarrow$
  7702. &
  7703. \begin{minipage}{0.6\textwidth}
  7704. \begin{lstlisting}
  7705. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7706. \end{lstlisting}
  7707. \end{minipage}
  7708. \\[2ex]\hline
  7709. \end{tabular}
  7710. \caption{Compiling $R_7$ to $R_6$.}
  7711. \label{fig:compile-r7-r6}
  7712. \end{figure}
  7713. \begin{exercise}\normalfont
  7714. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7715. Create tests for $R_7$ by adapting all of your previous test programs
  7716. by removing type annotations. Add 5 more tests programs that
  7717. specifically rely on the language being dynamically typed. That is,
  7718. they should not be legal programs in a statically typed language, but
  7719. nevertheless, they should be valid $R_7$ programs that run to
  7720. completion without error.
  7721. \end{exercise}
  7722. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7723. \chapter{Gradual Typing}
  7724. \label{ch:gradual-typing}
  7725. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7726. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7727. \chapter{Parametric Polymorphism}
  7728. \label{ch:parametric-polymorphism}
  7729. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7730. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7731. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7732. \chapter{High-level Optimization}
  7733. \label{ch:high-level-optimization}
  7734. This chapter will present a procedure inlining pass based on the
  7735. algorithm of \citet{Waddell:1997fk}.
  7736. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7737. \chapter{Appendix}
  7738. \section{Interpreters}
  7739. \label{appendix:interp}
  7740. We provide several interpreters in the \key{interp.rkt} file. The
  7741. \key{interp-scheme} function takes an AST in one of the Racket-like
  7742. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7743. the program, returning the result value. The \key{interp-C} function
  7744. interprets an AST for a program in one of the C-like languages ($C_0,
  7745. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7746. for an x86 program.
  7747. \section{Utility Functions}
  7748. \label{appendix:utilities}
  7749. The utility function described in this section can be found in the
  7750. \key{utilities.rkt} file.
  7751. The \key{read-program} function takes a file path and parses that file
  7752. (it must be a Racket program) into an abstract syntax tree with a
  7753. \key{Program} node at the top.
  7754. The \key{parse-program} function takes an S-expression representation
  7755. of an AST and converts it into the struct-based representation.
  7756. The \key{assert} function displays the error message \key{msg} if the
  7757. Boolean \key{bool} is false.
  7758. \begin{lstlisting}
  7759. (define (assert msg bool) ...)
  7760. \end{lstlisting}
  7761. % remove discussion of lookup? -Jeremy
  7762. The \key{lookup} function takes a key and an alist, and returns the
  7763. first value that is associated with the given key, if there is one. If
  7764. not, an error is triggered. The alist may contain both immutable
  7765. pairs (built with \key{cons}) and mutable pairs (built with
  7766. \key{mcons}).
  7767. The \key{map2} function ...
  7768. %% \subsection{Graphs}
  7769. %% \begin{itemize}
  7770. %% \item The \code{make-graph} function takes a list of vertices
  7771. %% (symbols) and returns a graph.
  7772. %% \item The \code{add-edge} function takes a graph and two vertices and
  7773. %% adds an edge to the graph that connects the two vertices. The graph
  7774. %% is updated in-place. There is no return value for this function.
  7775. %% \item The \code{adjacent} function takes a graph and a vertex and
  7776. %% returns the set of vertices that are adjacent to the given
  7777. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7778. %% used with functions from the \code{racket/set} module.
  7779. %% \item The \code{vertices} function takes a graph and returns the list
  7780. %% of vertices in the graph.
  7781. %% \end{itemize}
  7782. \subsection{Testing}
  7783. The \key{interp-tests} function takes a compiler name (a string), a
  7784. description of the passes, an interpreter for the source language, a
  7785. test family name (a string), and a list of test numbers, and runs the
  7786. compiler passes and the interpreters to check whether the passes
  7787. correct. The description of the passes is a list with one entry per
  7788. pass. An entry is a list with three things: a string giving the name
  7789. of the pass, the function that implements the pass (a translator from
  7790. AST to AST), and a function that implements the interpreter (a
  7791. function from AST to result value) for the language of the output of
  7792. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7793. good choice. The \key{interp-tests} function assumes that the
  7794. subdirectory \key{tests} has a collection of Scheme programs whose names
  7795. all start with the family name, followed by an underscore and then the
  7796. test number, ending in \key{.scm}. Also, for each Scheme program there
  7797. is a file with the same number except that it ends with \key{.in} that
  7798. provides the input for the Scheme program.
  7799. \begin{lstlisting}
  7800. (define (interp-tests name passes test-family test-nums) ...)
  7801. \end{lstlisting}
  7802. The compiler-tests function takes a compiler name (a string) a
  7803. description of the passes (as described above for
  7804. \code{interp-tests}), a test family name (a string), and a list of
  7805. test numbers (see the comment for interp-tests), and runs the compiler
  7806. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7807. machine code. It runs the machine code and checks that the output is
  7808. 42.
  7809. \begin{lstlisting}
  7810. (define (compiler-tests name passes test-family test-nums) ...)
  7811. \end{lstlisting}
  7812. The compile-file function takes a description of the compiler passes
  7813. (see the comment for \key{interp-tests}) and returns a function that,
  7814. given a program file name (a string ending in \key{.scm}), applies all
  7815. of the passes and writes the output to a file whose name is the same
  7816. as the program file name but with \key{.scm} replaced with \key{.s}.
  7817. \begin{lstlisting}
  7818. (define (compile-file passes)
  7819. (lambda (prog-file-name) ...))
  7820. \end{lstlisting}
  7821. \section{x86 Instruction Set Quick-Reference}
  7822. \label{sec:x86-quick-reference}
  7823. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7824. do. We write $A \to B$ to mean that the value of $A$ is written into
  7825. location $B$. Address offsets are given in bytes. The instruction
  7826. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7827. registers (such as $\%rax$), or memory references (such as
  7828. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7829. reference per instruction. Other operands must be immediates or
  7830. registers.
  7831. \begin{table}[tbp]
  7832. \centering
  7833. \begin{tabular}{l|l}
  7834. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7835. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7836. \texttt{negq} $A$ & $- A \to A$ \\
  7837. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7838. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7839. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  7840. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7841. \texttt{retq} & Pops the return address and jumps to it \\
  7842. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7843. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7844. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7845. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7846. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7847. matches the condition code of the instruction, otherwise go to the
  7848. next instructions. The condition codes are \key{e} for ``equal'',
  7849. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7850. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7851. \texttt{jl} $L$ & \\
  7852. \texttt{jle} $L$ & \\
  7853. \texttt{jg} $L$ & \\
  7854. \texttt{jge} $L$ & \\
  7855. \texttt{jmp} $L$ & Jump to label $L$ \\
  7856. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7857. \texttt{movzbq} $A$, $B$ &
  7858. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7859. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7860. and the extra bytes of $B$ are set to zero.} \\
  7861. & \\
  7862. & \\
  7863. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7864. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7865. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7866. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7867. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7868. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7869. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7870. description of the condition codes. $A$ must be a single byte register
  7871. (e.g., \texttt{al} or \texttt{cl}).} \\
  7872. \texttt{setl} $A$ & \\
  7873. \texttt{setle} $A$ & \\
  7874. \texttt{setg} $A$ & \\
  7875. \texttt{setge} $A$ &
  7876. \end{tabular}
  7877. \vspace{5pt}
  7878. \caption{Quick-reference for the x86 instructions used in this book.}
  7879. \label{tab:x86-instr}
  7880. \end{table}
  7881. \bibliographystyle{plainnat}
  7882. \bibliography{all}
  7883. \end{document}
  7884. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7885. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7886. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7887. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7888. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7889. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7890. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7891. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7892. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7893. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7894. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7895. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7896. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7897. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7898. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7899. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7900. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7901. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7902. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7903. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7904. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7905. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7906. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7907. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7908. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7909. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7910. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7911. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7912. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7913. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7914. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7915. % LocalWords: struct symtab