book.tex 301 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \usepackage{upquote}
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. %% For pictures
  55. \usepackage{tikz}
  56. \usetikzlibrary{arrows.meta}
  57. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  58. % Computer Modern is already the default. -Jeremy
  59. %\renewcommand{\ttdefault}{cmtt}
  60. \definecolor{comment-red}{rgb}{0.8,0,0}
  61. \if{0}
  62. % Peanut gallery comments:
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{#1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match},
  73. deletekeywords={read},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~}
  77. }
  78. \newtheorem{theorem}{Theorem}
  79. \newtheorem{lemma}[theorem]{Lemma}
  80. \newtheorem{corollary}[theorem]{Corollary}
  81. \newtheorem{proposition}[theorem]{Proposition}
  82. \newtheorem{constraint}[theorem]{Constraint}
  83. \newtheorem{definition}[theorem]{Definition}
  84. \newtheorem{exercise}[theorem]{Exercise}
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. % 'dedication' environment: To add a dedication paragraph at the start of book %
  87. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. \newenvironment{dedication}
  90. {
  91. \cleardoublepage
  92. \thispagestyle{empty}
  93. \vspace*{\stretch{1}}
  94. \hfill\begin{minipage}[t]{0.66\textwidth}
  95. \raggedright
  96. }
  97. {
  98. \end{minipage}
  99. \vspace*{\stretch{3}}
  100. \clearpage
  101. }
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % Chapter quote at the start of chapter %
  104. % Source: http://tex.stackexchange.com/a/53380 %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \makeatletter
  107. \renewcommand{\@chapapp}{}% Not necessary...
  108. \newenvironment{chapquote}[2][2em]
  109. {\setlength{\@tempdima}{#1}%
  110. \def\chapquote@author{#2}%
  111. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  112. \itshape}
  113. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  114. \makeatother
  115. \input{defs}
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \title{\Huge \textbf{Essentials of Compilation} \\
  118. \huge An Incremental Approach}
  119. \author{\textsc{Jeremy G. Siek} \\
  120. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  121. Indiana University \\
  122. \\
  123. with contributions from: \\
  124. Carl Factora \\
  125. Andre Kuhlenschmidt \\
  126. Ryan R. Newton \\
  127. Ryan Scott \\
  128. Cameron Swords \\
  129. Michael M. Vitousek \\
  130. Michael Vollmer
  131. }
  132. \begin{document}
  133. \frontmatter
  134. \maketitle
  135. \begin{dedication}
  136. This book is dedicated to the programming language wonks at Indiana
  137. University.
  138. \end{dedication}
  139. \tableofcontents
  140. \listoffigures
  141. %\listoftables
  142. \mainmatter
  143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  144. \chapter*{Preface}
  145. The tradition of compiler writing at Indiana University goes back to
  146. research and courses about programming languages by Daniel Friedman in
  147. the 1970's and 1980's. Dan conducted research on lazy
  148. evaluation~\citep{Friedman:1976aa} in the context of
  149. Lisp~\citep{McCarthy:1960dz} and then studied
  150. continuations~\citep{Felleisen:kx} and
  151. macros~\citep{Kohlbecker:1986dk} in the context of the
  152. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  153. of those courses, Kent Dybvig, went on to build Chez
  154. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  155. compiler for Scheme. After completing his Ph.D. at the University of
  156. North Carolina, Kent returned to teach at Indiana University.
  157. Throughout the 1990's and 2000's, Kent continued development of Chez
  158. Scheme and taught the compiler course.
  159. The compiler course evolved to incorporate novel pedagogical ideas
  160. while also including elements of effective real-world compilers. One
  161. of Dan's ideas was to split the compiler into many small ``passes'' so
  162. that the code for each pass would be easy to understood in isolation.
  163. (In contrast, most compilers of the time were organized into only a
  164. few monolithic passes for reasons of compile-time efficiency.) Kent,
  165. with later help from his students Dipanwita Sarkar and Andrew Keep,
  166. developed infrastructure to support this approach and evolved the
  167. course, first to use micro-sized passes and then into even smaller
  168. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  169. student in this compiler course in the early 2000's, as part of his
  170. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  171. the course immensely!
  172. During that time, another student named Abdulaziz Ghuloum observed
  173. that the front-to-back organization of the course made it difficult
  174. for students to understand the rationale for the compiler
  175. design. Abdulaziz proposed an incremental approach in which the
  176. students build the compiler in stages; they start by implementing a
  177. complete compiler for a very small subset of the input language and in
  178. each subsequent stage they add a language feature and add or modify
  179. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  180. the students see how the language features motivate aspects of the
  181. compiler design.
  182. After graduating from Indiana University in 2005, Jeremy went on to
  183. teach at the University of Colorado. He adapted the nano pass and
  184. incremental approaches to compiling a subset of the Python
  185. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  186. on the surface but there is a large overlap in the compiler techniques
  187. required for the two languages. Thus, Jeremy was able to teach much of
  188. the same content from the Indiana compiler course. He very much
  189. enjoyed teaching the course organized in this way, and even better,
  190. many of the students learned a lot and got excited about compilers.
  191. Jeremy returned to teach at Indiana University in 2013. In his
  192. absence the compiler course had switched from the front-to-back
  193. organization to a back-to-front organization. Seeing how well the
  194. incremental approach worked at Colorado, he started porting and
  195. adapting the structure of the Colorado course back into the land of
  196. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  197. the course is now about compiling a subset of Racket (and Typed
  198. Racket) to the x86 assembly language. The compiler is implemented in
  199. Racket 7.1~\citep{plt-tr}.
  200. This is the textbook for the incremental version of the compiler
  201. course at Indiana University (Spring 2016 - present) and it is the
  202. first open textbook for an Indiana compiler course. With this book we
  203. hope to make the Indiana compiler course available to people that have
  204. not had the chance to study in Bloomington in person. Many of the
  205. compiler design decisions in this book are drawn from the assignment
  206. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  207. are the most important topics from \cite{Dybvig:2010aa} but we have
  208. omitted topics that we think are less interesting conceptually and we
  209. have made simplifications to reduce complexity. In this way, this
  210. book leans more towards pedagogy than towards the efficiency of the
  211. generated code. Also, the book differs in places where we saw the
  212. opportunity to make the topics more fun, such as in relating register
  213. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  214. \section*{Prerequisites}
  215. The material in this book is challenging but rewarding. It is meant to
  216. prepare students for a lifelong career in programming languages.
  217. The book uses the Racket language both for the implementation of the
  218. compiler and for the language that is compiled, so a student should be
  219. proficient with Racket (or Scheme) prior to reading this book. There
  220. are many excellent resources for learning Scheme and
  221. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  222. is helpful but not necessary for the student to have prior exposure to
  223. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  224. obtain from a computer systems
  225. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  226. parts of x86-64 assembly language that are needed.
  227. %\section*{Structure of book}
  228. % You might want to add short description about each chapter in this book.
  229. %\section*{About the companion website}
  230. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  231. %\begin{itemize}
  232. % \item A link to (freely downlodable) latest version of this document.
  233. % \item Link to download LaTeX source for this document.
  234. % \item Miscellaneous material (e.g. suggested readings etc).
  235. %\end{itemize}
  236. \section*{Acknowledgments}
  237. Many people have contributed to the ideas, techniques, organization,
  238. and teaching of the materials in this book. We especially thank the
  239. following people.
  240. \begin{itemize}
  241. \item Bor-Yuh Evan Chang
  242. \item Kent Dybvig
  243. \item Daniel P. Friedman
  244. \item Ronald Garcia
  245. \item Abdulaziz Ghuloum
  246. \item Jay McCarthy
  247. \item Dipanwita Sarkar
  248. \item Andrew Keep
  249. \item Oscar Waddell
  250. \item Michael Wollowski
  251. \end{itemize}
  252. \mbox{}\\
  253. \noindent Jeremy G. Siek \\
  254. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  255. %\noindent Spring 2016
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257. \chapter{Preliminaries}
  258. \label{ch:trees-recur}
  259. In this chapter we review the basic tools that are needed to implement
  260. a compiler. We use \emph{abstract syntax trees} (ASTs), which are data
  261. structures in computer memory, in contrast to how programs are
  262. typically stored in text files on disk, as \emph{concrete syntax}.
  263. %
  264. ASTs can be represented in many different ways, depending on the programming
  265. language used to write the compiler.
  266. %
  267. We use Racket's \code{struct} feature to conveniently represent
  268. ASTs (Section~\ref{sec:ast}). We use grammars to defined the abstract
  269. syntax of programming languages (Section~\ref{sec:grammar}) and
  270. pattern matching to inspect individual nodes in an AST
  271. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  272. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  273. chapter provides an brief introduction to these ideas.
  274. \section{Abstract Syntax Trees and Racket Structures}
  275. \label{sec:ast}
  276. The primary data structure that is commonly used for representing
  277. programs is the \emph{abstract syntax tree} (AST). When considering
  278. some part of a program, a compiler needs to ask what kind of thing it
  279. is and what sub-parts it contains. For example, the program on the
  280. left corresponds to the AST on the right.
  281. \begin{center}
  282. \begin{minipage}{0.4\textwidth}
  283. \begin{lstlisting}
  284. (+ (read) (- 8))
  285. \end{lstlisting}
  286. \end{minipage}
  287. \begin{minipage}{0.4\textwidth}
  288. \begin{equation}
  289. \begin{tikzpicture}
  290. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  291. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  292. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  293. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  294. \draw[->] (plus) to (read);
  295. \draw[->] (plus) to (minus);
  296. \draw[->] (minus) to (8);
  297. \end{tikzpicture}
  298. \label{eq:arith-prog}
  299. \end{equation}
  300. \end{minipage}
  301. \end{center}
  302. We shall use the standard terminology for trees: each circle above is
  303. called a \emph{node}. The arrows connect a node to its \emph{children}
  304. (which are also nodes). The top-most node is the \emph{root}. Every
  305. node except for the root has a \emph{parent} (the node it is the child
  306. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  307. it is an \emph{internal} node.
  308. %% Recall that an \emph{symbolic expression} (S-expression) is either
  309. %% \begin{enumerate}
  310. %% \item an atom, or
  311. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  312. %% where $e_1$ and $e_2$ are each an S-expression.
  313. %% \end{enumerate}
  314. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  315. %% null value \code{'()}, etc. We can create an S-expression in Racket
  316. %% simply by writing a backquote (called a quasi-quote in Racket)
  317. %% followed by the textual representation of the S-expression. It is
  318. %% quite common to use S-expressions to represent a list, such as $a, b
  319. %% ,c$ in the following way:
  320. %% \begin{lstlisting}
  321. %% `(a . (b . (c . ())))
  322. %% \end{lstlisting}
  323. %% Each element of the list is in the first slot of a pair, and the
  324. %% second slot is either the rest of the list or the null value, to mark
  325. %% the end of the list. Such lists are so common that Racket provides
  326. %% special notation for them that removes the need for the periods
  327. %% and so many parenthesis:
  328. %% \begin{lstlisting}
  329. %% `(a b c)
  330. %% \end{lstlisting}
  331. %% The following expression creates an S-expression that represents AST
  332. %% \eqref{eq:arith-prog}.
  333. %% \begin{lstlisting}
  334. %% `(+ (read) (- 8))
  335. %% \end{lstlisting}
  336. %% When using S-expressions to represent ASTs, the convention is to
  337. %% represent each AST node as a list and to put the operation symbol at
  338. %% the front of the list. The rest of the list contains the children. So
  339. %% in the above case, the root AST node has operation \code{`+} and its
  340. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  341. %% diagram \eqref{eq:arith-prog}.
  342. %% To build larger S-expressions one often needs to splice together
  343. %% several smaller S-expressions. Racket provides the comma operator to
  344. %% splice an S-expression into a larger one. For example, instead of
  345. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  346. %% we could have first created an S-expression for AST
  347. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  348. %% S-expression.
  349. %% \begin{lstlisting}
  350. %% (define ast1.4 `(- 8))
  351. %% (define ast1.1 `(+ (read) ,ast1.4))
  352. %% \end{lstlisting}
  353. %% In general, the Racket expression that follows the comma (splice)
  354. %% can be any expression that produces an S-expression.
  355. We define a Racket \code{struct} for each kind of node. For this
  356. chapter we require just two kinds of nodes: one for integer constants
  357. and one for primitive operations. The following is the \code{struct}
  358. definition for integer constants.
  359. \begin{lstlisting}
  360. (struct Int (value))
  361. \end{lstlisting}
  362. An integer node includes just one thing: the integer value.
  363. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  364. \begin{lstlisting}
  365. (define eight (Int 8))
  366. \end{lstlisting}
  367. We say that the value created by \code{(Int 8)} is an
  368. \emph{instance} of the \code{Int} structure.
  369. The following is the \code{struct} definition for primitives operations.
  370. \begin{lstlisting}
  371. (struct Prim (op arg*))
  372. \end{lstlisting}
  373. A primitive operation node includes an operator symbol \code{op}
  374. and a list of children \code{arg*}. For example, to create
  375. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  376. \begin{lstlisting}
  377. (define neg-eight (Prim '- (list eight)))
  378. \end{lstlisting}
  379. Primitive operations may have zero or more children. The \code{read}
  380. operator has zero children:
  381. \begin{lstlisting}
  382. (define rd (Prim 'read '()))
  383. \end{lstlisting}
  384. whereas the addition operator has two children:
  385. \begin{lstlisting}
  386. (define ast1.1 (Prim '+ (list rd neg-eight)))
  387. \end{lstlisting}
  388. We have made a design choice regarding the \code{Prim} structure.
  389. Instead of using one structure for many different operations
  390. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  391. structure for each operation, as follows.
  392. \begin{lstlisting}
  393. (struct Read ())
  394. (struct Add (left right))
  395. (struct Neg (value))
  396. \end{lstlisting}
  397. The reason we choose to use just one structure is that in many parts
  398. of the compiler, the code for the different primitive operators is the
  399. same, so we might as well just write that code once, which is enabled
  400. by using a single structure.
  401. When compiling a program such as \eqref{eq:arith-prog}, we need to
  402. know that the operation associated with the root node is addition and
  403. that it has two children: \texttt{read} and a negation. The AST data
  404. structure directly supports these queries, as we shall see in
  405. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  406. in compilers.
  407. In this book, we often write down the concrete syntax of a program
  408. even when we really have in mind the AST because the concrete syntax
  409. is more concise. We recommend that, in your mind, you always think of
  410. programs as abstract syntax trees.
  411. \section{Grammars}
  412. \label{sec:grammar}
  413. A programming language can be thought of as a \emph{set} of programs.
  414. The set is typically infinite (one can always create larger and larger
  415. programs), so one cannot simply describe a language by listing all of
  416. the programs in the language. Instead we write down a set of rules, a
  417. \emph{grammar}, for building programs. Grammars are often used to
  418. define the concrete syntax of a language, but they can also be used to
  419. describe the abstract syntax. We shall write our rules in a variant of
  420. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  421. example, we describe a small language, named $R_0$, that consists of
  422. integers and arithmetic operations.
  423. The first grammar rule says that an instance of the \code{Int}
  424. structure is an expression:
  425. \begin{equation}
  426. \Exp ::= \INT{\Int} \label{eq:arith-int}
  427. \end{equation}
  428. %
  429. Each rule has a left-hand-side and a right-hand-side. The way to read
  430. a rule is that if you have all the program parts on the
  431. right-hand-side, then you can create an AST node and categorize it
  432. according to the left-hand-side.
  433. %
  434. A name such as $\Exp$ that is
  435. defined by the grammar rules is a \emph{non-terminal}.
  436. %
  437. The name $\Int$ is a also a non-terminal, but instead of defining it
  438. with a grammar rule, we define it with the following explanation. We
  439. make the simplifying design decision that all of the languages in this
  440. book only handle machine-representable integers. On most modern
  441. machines this corresponds to integers represented with 64-bits, i.e.,
  442. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  443. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  444. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  445. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  446. that the sequence of decimals represent an integer in range $-2^{62}$
  447. to $2^{62}-1$.
  448. The second grammar rule is the \texttt{read} operation that receives
  449. an input integer from the user of the program.
  450. \begin{equation}
  451. \Exp ::= \READ{} \label{eq:arith-read}
  452. \end{equation}
  453. The third rule says that, given an $\Exp$ node, you can build another
  454. $\Exp$ node by negating it.
  455. \begin{equation}
  456. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  457. \end{equation}
  458. Symbols in typewriter font such as \key{-} and \key{read} are
  459. \emph{terminal} symbols and must literally appear in the program for
  460. the rule to be applicable.
  461. We can apply the rules to build ASTs in the $R_0$
  462. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  463. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  464. an $\Exp$.
  465. \begin{center}
  466. \begin{minipage}{0.4\textwidth}
  467. \begin{lstlisting}
  468. (Prim '- (list (Int 8)))
  469. \end{lstlisting}
  470. \end{minipage}
  471. \begin{minipage}{0.25\textwidth}
  472. \begin{equation}
  473. \begin{tikzpicture}
  474. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  475. \node[draw, circle] (8) at (0, -1.2) {$8$};
  476. \draw[->] (minus) to (8);
  477. \end{tikzpicture}
  478. \label{eq:arith-neg8}
  479. \end{equation}
  480. \end{minipage}
  481. \end{center}
  482. The next grammar rule defines addition expressions:
  483. \begin{equation}
  484. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  485. \end{equation}
  486. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  487. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  488. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  489. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  490. to show that
  491. \begin{lstlisting}
  492. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  493. \end{lstlisting}
  494. is an $\Exp$ in the $R_0$ language.
  495. If you have an AST for which the above rules do not apply, then the
  496. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  497. is not in $R_0$ because there are no rules for \code{+} with only one
  498. argument, nor for \key{-} with two arguments. Whenever we define a
  499. language with a grammar, the language only includes those programs
  500. that are justified by the rules.
  501. The last grammar rule for $R_0$ states that there is a \code{Program}
  502. node to mark the top of the whole program:
  503. \[
  504. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  505. \]
  506. The \code{Program} structure is defined as follows
  507. \begin{lstlisting}
  508. (struct Program (info body))
  509. \end{lstlisting}
  510. where \code{body} is an expression. In later chapters, the \code{info}
  511. part will be used to store auxilliary information but for now it is
  512. just the empty list.
  513. The \code{read-program} function provided in \code{utilities.rkt}
  514. reads programs in from a file (the sequence of characters in the
  515. concrete syntax of Racket) and parses them into the abstract syntax
  516. tree. The concrete syntax does not include a \key{program} form; that
  517. is added by the \code{read-program} function as it creates the
  518. AST. See the description of \code{read-program} in
  519. Appendix~\ref{appendix:utilities} for more details.
  520. It is common to have many rules with the same left-hand side, such as
  521. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  522. for gathering several rules, as shown in
  523. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  524. called an {\em alternative}.
  525. \begin{figure}[tp]
  526. \fbox{
  527. \begin{minipage}{0.96\textwidth}
  528. \[
  529. \begin{array}{rcl}
  530. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  531. &\mid& \ADD{\Exp}{\Exp} \\
  532. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  533. \end{array}
  534. \]
  535. \end{minipage}
  536. }
  537. \caption{The abstract syntax of $R_0$, a language of integer arithmetic.}
  538. \label{fig:r0-syntax}
  539. \end{figure}
  540. \section{Pattern Matching}
  541. \label{sec:pattern-matching}
  542. As mentioned above, compilers often need to access the children of an
  543. AST node. Racket provides the \texttt{match} form to access the parts
  544. of a structure. Consider the following example and the output on the
  545. right.
  546. \begin{center}
  547. \begin{minipage}{0.5\textwidth}
  548. \begin{lstlisting}
  549. (match ast1.1
  550. [(Prim op (list child1 child2))
  551. (print op)])
  552. \end{lstlisting}
  553. \end{minipage}
  554. \vrule
  555. \begin{minipage}{0.25\textwidth}
  556. \begin{lstlisting}
  557. '+
  558. \end{lstlisting}
  559. \end{minipage}
  560. \end{center}
  561. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  562. parts to the three variables \texttt{op}, \texttt{child1}, and
  563. \texttt{child2}. In general, a match clause consists of a
  564. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  565. that may also contain pattern-variables (each one preceded by a comma).
  566. %
  567. The pattern is not the same thing as a quasiquote expression used to
  568. \emph{construct} ASTs, however, the similarity is intentional:
  569. constructing and deconstructing ASTs uses similar syntax.
  570. %
  571. While the pattern uses a restricted syntax, the body of the match
  572. clause may contain any Racket code whatsoever.
  573. A \code{match} form may contain several clauses, as in the following
  574. function \code{leaf?} that recognizes when an $R_0$ node is
  575. a leaf. The \code{match} proceeds through the clauses in order,
  576. checking whether the pattern can match the input AST. The
  577. body of the first clause that matches is executed. The output of
  578. \code{leaf?} for several ASTs is shown on the right.
  579. \begin{center}
  580. \begin{minipage}{0.6\textwidth}
  581. \begin{lstlisting}
  582. (define (leaf? arith)
  583. (match arith
  584. [(Int n) #t]
  585. [(Prim 'read '()) #t]
  586. [(Prim '- (list c1)) #f]
  587. [(Prim '+ (list c1 c2)) #f]))
  588. (leaf? (Prim 'read '()))
  589. (leaf? (Prim '- (list (Int 8))))
  590. (leaf? (Int 8))
  591. \end{lstlisting}
  592. \end{minipage}
  593. \vrule
  594. \begin{minipage}{0.25\textwidth}
  595. \begin{lstlisting}
  596. #t
  597. #f
  598. #t
  599. \end{lstlisting}
  600. \end{minipage}
  601. \end{center}
  602. When writing a \code{match}, we always refer to the grammar definition
  603. for the language and identify which non-terminal we're expecting to
  604. match against, then we make sure that 1) we have one clause for each
  605. alternative of that non-terminal and 2) that the pattern in each
  606. clause corresponds to the corresponding right-hand side of a grammar
  607. rule. For the \code{match} in the \code{leaf?} function, we refer to
  608. the grammar for $R_0$ in Figure~\ref{fig:r0-syntax}. The $\Exp$
  609. non-terminal has 4 alternatives, so the \code{match} has 4 clauses.
  610. The pattern in each clause corresponds to the right-hand side of a
  611. grammar rule. For example, the pattern \code{(Prim '+ (list c1 c2))}
  612. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When translating
  613. from grammars to patterns, replace non-terminals such as $\Exp$ with
  614. pattern variables (e.g. \code{c1} and \code{c2}).
  615. \section{Recursion}
  616. \label{sec:recursion}
  617. Programs are inherently recursive. For example, an $R_0$ expression is
  618. often made of smaller expressions. Thus, the natural way to process an
  619. entire program is with a recursive function. As a first example of
  620. such a recursive function, we define \texttt{exp?} below, which takes
  621. an arbitrary S-expression and determines whether or not it is an $R_0$
  622. expression. As discussed in the previous section, each match clause
  623. corresponds to one grammar rule. The body of each clause makes a
  624. recursive call for each child node. This kind of recursive function is
  625. so common that it has a name: \emph{structural recursion}. In
  626. general, when a recursive function is defined using a sequence of
  627. match clauses that correspond to a grammar, and the body of each
  628. clause makes a recursive call on each child node, then we say the
  629. function is defined by structural recursion\footnote{This principle of
  630. structuring code according to the data definition is advocated in
  631. the book \emph{How to Design Programs}
  632. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  633. define a second function, named \code{R0?}, that determines whether an
  634. S-expression is an $R_0$ program. In general we can expect to write
  635. one recursive function to handle each non-terminal in the grammar.
  636. %
  637. \begin{center}
  638. \begin{minipage}{0.7\textwidth}
  639. \begin{lstlisting}
  640. (define (exp? ast)
  641. (match ast
  642. [(Int n) #t]
  643. [(Prim 'read '()) #t]
  644. [(Prim '- (list e)) (exp? e)]
  645. [(Prim '+ (list e1 e2))
  646. (and (exp? e1) (exp? e2))]
  647. [else #f]))
  648. (define (R0? ast)
  649. (match ast
  650. [(Program '() e) (exp? e)]
  651. [else #f]))
  652. (R0? (Program '() ast1.1)
  653. (R0? (Program '()
  654. (Prim '- (list (Prim 'read '())
  655. (Prim '+ (list (Num 8)))))))
  656. \end{lstlisting}
  657. \end{minipage}
  658. \vrule
  659. \begin{minipage}{0.25\textwidth}
  660. \begin{lstlisting}
  661. #t
  662. #f
  663. \end{lstlisting}
  664. \end{minipage}
  665. \end{center}
  666. You may be tempted to merge the two functions into one, like this:
  667. \begin{center}
  668. \begin{minipage}{0.5\textwidth}
  669. \begin{lstlisting}
  670. (define (R0? ast)
  671. (match ast
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e)) (R0? e)]
  675. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  676. [(Program '() e) (R0? e)]
  677. [else #f]))
  678. \end{lstlisting}
  679. \end{minipage}
  680. \end{center}
  681. %
  682. Sometimes such a trick will save a few lines of code, especially when it comes
  683. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  684. recommended because it can get you into trouble.
  685. %
  686. For instance, the above function is subtly wrong:
  687. \lstinline{(R0? (Program '() (Program '() (Int 3))))} will return true, when it
  688. should return false.
  689. %% NOTE FIXME - must check for consistency on this issue throughout.
  690. \section{Interpreters}
  691. \label{sec:interp-R0}
  692. The meaning, or semantics, of a program is typically defined in the
  693. specification of the language. For example, the Scheme language is
  694. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  695. defined in its reference manual~\citep{plt-tr}. In this book we use an
  696. interpreter to define the meaning of each language that we consider,
  697. following Reynolds' advice in this
  698. regard~\citep{reynolds72:_def_interp}. An interpreter that is
  699. designated (by some people) as the definition of a language is called
  700. a \emph{definitional interpreter}. Here we warm up by creating a
  701. definitional interpreter for the $R_0$ language, which serves as a
  702. second example of structural recursion. The \texttt{interp-R0}
  703. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  704. function is a match on the input program followed by a call to the
  705. \lstinline{interp-exp} helper function, which in turn has one match
  706. clause per grammar rule for $R_0$ expressions.
  707. \begin{figure}[tbp]
  708. \begin{lstlisting}
  709. (define (interp-exp e)
  710. (match e
  711. [(Int n) n]
  712. [(Prim 'read '())
  713. (define r (read))
  714. (cond [(fixnum? r) r]
  715. [else (error 'interp-R1 "expected an integer" r)])]
  716. [(Prim '- (list e))
  717. (define v (interp-exp e))
  718. (fx- 0 v)]
  719. [(Prim '+ (list e1 e2))
  720. (define v1 (interp-exp e1))
  721. (define v2 (interp-exp e2))
  722. (fx+ v1 v2)]
  723. )))
  724. (define (interp-R0 p)
  725. (match p
  726. [(Program '() e) (interp-exp e)]
  727. ))
  728. \end{lstlisting}
  729. \caption{Interpreter for the $R_0$ language.}
  730. \label{fig:interp-R0}
  731. \end{figure}
  732. Let us consider the result of interpreting a few $R_0$ programs. The
  733. following program adds two integers.
  734. \begin{lstlisting}
  735. (+ 10 32)
  736. \end{lstlisting}
  737. The result is \key{42}. We wrote the above program in concrete syntax,
  738. whereas the parsed abstract syntax is:
  739. \begin{lstlisting}
  740. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  741. \end{lstlisting}
  742. The next example demonstrates that expressions may be nested within
  743. each other, in this case nesting several additions and negations.
  744. \begin{lstlisting}
  745. (+ 10 (- (+ 12 20)))
  746. \end{lstlisting}
  747. What is the result of the above program?
  748. As mentioned previously, the $R_0$ language does not support
  749. arbitrarily-large integers, but only $63$-bit integers, so we
  750. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  751. in Racket.
  752. Suppose $n = 999999999999999999$, which indeed fits in $63$-bits.
  753. What happens when we run the following program in our interpreter?
  754. \begin{lstlisting}
  755. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  756. \end{lstlisting}
  757. It produces an error:
  758. \begin{lstlisting}
  759. fx+: result is not a fixnum
  760. \end{lstlisting}
  761. We establish the convention that if running the definitional
  762. interpreter on a program produces an error, then the meaning of that
  763. program is \emph{unspecified}. That means a compiler for the language
  764. is under no obligations regarding that program; it may or may not
  765. produce an executable, and if it does, that executable can do
  766. anything. This convention applies to the languages defined in this
  767. book, as a way to simplify the student's task of implementing them,
  768. but this convention is not applicable to all programming languages.
  769. Moving on to the last feature of the $R_0$ language, the \key{read}
  770. operation prompts the user of the program for an integer. Recall that
  771. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  772. \code{8}. So if we run
  773. \begin{lstlisting}
  774. (interp-R0 ast1.1)
  775. \end{lstlisting}
  776. and the input the integer \code{50} we get the answer to life, the
  777. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  778. Guide to the Galaxy} by Douglas Adams.}
  779. We include the \key{read} operation in $R_0$ so a clever student
  780. cannot implement a compiler for $R_0$ that simply runs the interpreter
  781. during compilation to obtain the output and then generates the trivial
  782. code to produce the output. (Yes, a clever student did this in a
  783. previous version of the course.)
  784. The job of a compiler is to translate a program in one language into a
  785. program in another language so that the output program behaves the
  786. same way as the input program does according to its definitional
  787. interpreter. This idea is depicted in the following diagram. Suppose
  788. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  789. interpreter for each language. Suppose that the compiler translates
  790. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  791. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  792. respective interpreters with input $i$ should yield the same output
  793. $o$.
  794. \begin{equation} \label{eq:compile-correct}
  795. \begin{tikzpicture}[baseline=(current bounding box.center)]
  796. \node (p1) at (0, 0) {$P_1$};
  797. \node (p2) at (3, 0) {$P_2$};
  798. \node (o) at (3, -2.5) {$o$};
  799. \path[->] (p1) edge [above] node {compile} (p2);
  800. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  801. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  802. \end{tikzpicture}
  803. \end{equation}
  804. In the next section we see our first example of a compiler.
  805. \section{Example Compiler: a Partial Evaluator}
  806. \label{sec:partial-evaluation}
  807. In this section we consider a compiler that translates $R_0$
  808. programs into $R_0$ programs that may be more efficient, that is,
  809. this compiler is an optimizer. Our optimizer will accomplish this by
  810. trying to eagerly compute the parts of the program that do not depend
  811. on any inputs. For example, given the following program
  812. \begin{lstlisting}
  813. (+ (read) (- (+ 5 3)))
  814. \end{lstlisting}
  815. our compiler will translate it into the program
  816. \begin{lstlisting}
  817. (+ (read) -8)
  818. \end{lstlisting}
  819. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  820. evaluator for the $R_0$ language. The output of the partial evaluator
  821. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  822. recursion over $\Exp$ is captured in the \code{pe-exp} function
  823. whereas the code for partially evaluating the negation and addition
  824. operations is factored into two separate helper functions:
  825. \code{pe-neg} and \code{pe-add}. The input to these helper
  826. functions is the output of partially evaluating the children.
  827. \begin{figure}[tbp]
  828. \begin{lstlisting}
  829. (define (pe-neg r)
  830. (match r
  831. [(Int n) (Int (fx- 0 n))]
  832. [else (Prim '- (list r))]))
  833. (define (pe-add r1 r2)
  834. (match* (r1 r2)
  835. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  836. [(_ _) (Prim '+ (list r1 r2))]))
  837. (define (pe-exp e)
  838. (match e
  839. [(Int n) (Int n)]
  840. [(Prim 'read '()) (Prim 'read '())]
  841. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  842. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  843. ))
  844. (define (pe-R0 p)
  845. (match p
  846. [(Program info e) (Program info (pe-exp e))]
  847. ))
  848. \end{lstlisting}
  849. \caption{A partial evaluator for $R_0$ expressions.}
  850. \label{fig:pe-arith}
  851. \end{figure}
  852. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  853. arguments are integers and if they are, perform the appropriate
  854. arithmetic. Otherwise, they use quasiquote to create an AST node for
  855. the operation (either negation or addition) and use comma to splice in
  856. the children.
  857. To gain some confidence that the partial evaluator is correct, we can
  858. test whether it produces programs that get the same result as the
  859. input programs. That is, we can test whether it satisfies Diagram
  860. \eqref{eq:compile-correct}. The following code runs the partial
  861. evaluator on several examples and tests the output program. The
  862. \texttt{parse-program} and \texttt{assert} functions are defined in
  863. Appendix~\ref{appendix:utilities}.\\
  864. \begin{minipage}{1.0\textwidth}
  865. \begin{lstlisting}
  866. (define (test-pe p)
  867. (assert "testing pe-R0"
  868. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  869. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  870. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  871. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  872. \end{lstlisting}
  873. \end{minipage}
  874. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  875. \chapter{Integers and Variables}
  876. \label{ch:int-exp}
  877. This chapter is about compiling the subset of Racket that includes
  878. integer arithmetic and local variable binding, which we name $R_1$, to
  879. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  880. to x86-64 simply as x86. The chapter begins with a description of the
  881. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  882. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  883. discuss only what is needed for compiling $R_1$. We introduce more of
  884. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  885. reflect on their differences and come up with a plan to break down the
  886. translation from $R_1$ to x86 into a handful of steps
  887. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  888. chapter give detailed hints regarding each step
  889. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  890. to give enough hints that the well-prepared reader, together with a
  891. few friends, can implement a compiler from $R_1$ to x86 in a couple
  892. weeks while at the same time leaving room for some fun and creativity.
  893. To give the reader a feeling for the scale of this first compiler, the
  894. instructor solution for the $R_1$ compiler is less than 500 lines of
  895. code.
  896. \section{The $R_1$ Language}
  897. \label{sec:s0}
  898. The $R_1$ language extends the $R_0$ language
  899. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  900. the $R_1$ language is defined by the grammar in
  901. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  902. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  903. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  904. the $R_1$ language includes the \key{Program} struct to mark the top
  905. of the program. The $\itm{info}$ field of the \key{Program} struct
  906. contains an \emph{association list} (a list of key-value pairs) that
  907. is used to communicate auxiliary data from one compiler pass the
  908. next. Despite the simplicity of the $R_1$ language, it is rich enough
  909. to exhibit several compilation techniques.
  910. \begin{figure}[btp]
  911. \centering
  912. \fbox{
  913. \begin{minipage}{0.96\textwidth}
  914. \[
  915. \begin{array}{rcl}
  916. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  917. &\mid& \ADD{\Exp}{\Exp}
  918. \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  919. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  920. \end{array}
  921. \]
  922. \end{minipage}
  923. }
  924. \caption{The abstract syntax of $R_1$, a language of integers and variables.}
  925. \label{fig:r1-syntax}
  926. \end{figure}
  927. Let us dive further into the syntax and semantics of the $R_1$
  928. language. The \key{Let} feature defines a variable for use within its
  929. body and initializes the variable with the value of an expression.
  930. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  931. The concrete syntax for \key{Let} is
  932. \begin{lstlisting}
  933. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  934. \end{lstlisting}
  935. For example, the following program initializes \code{x} to $32$ and then
  936. evaluates the body \code{(+ 10 x)}, producing $42$.
  937. \begin{lstlisting}
  938. (let ([x (+ 12 20)]) (+ 10 x))
  939. \end{lstlisting}
  940. When there are multiple \key{let}'s for the same variable, the closest
  941. enclosing \key{let} is used. That is, variable definitions overshadow
  942. prior definitions. Consider the following program with two \key{let}'s
  943. that define variables named \code{x}. Can you figure out the result?
  944. \begin{lstlisting}
  945. (let ([x 32]) (+ (let ([x 10]) x) x))
  946. \end{lstlisting}
  947. For the purposes of depicting which variable uses correspond to which
  948. definitions, the following shows the \code{x}'s annotated with
  949. subscripts to distinguish them. Double check that your answer for the
  950. above is the same as your answer for this annotated version of the
  951. program.
  952. \begin{lstlisting}
  953. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  954. \end{lstlisting}
  955. The initializing expression is always evaluated before the body of the
  956. \key{let}, so in the following, the \key{read} for \code{x} is
  957. performed before the \key{read} for \code{y}. Given the input
  958. $52$ then $10$, the following produces $42$ (not $-42$).
  959. \begin{lstlisting}
  960. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  961. \end{lstlisting}
  962. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  963. $R_1$ language. It extends the interpreter for $R_0$ with two new
  964. \key{match} clauses for variables and for \key{let}. For \key{let},
  965. we need a way to communicate the value of a variable to all the uses
  966. of a variable. To accomplish this, we maintain a mapping from
  967. variables to values, which is called an \emph{environment}. For
  968. simplicity, here we use an association list to represent the
  969. environment. The \code{interp-R1} function takes the current
  970. environment, \code{env}, as an extra parameter. When the interpreter
  971. encounters a variable, it finds the corresponding value using the
  972. \code{lookup} function (Appendix~\ref{appendix:utilities}). When the
  973. interpreter encounters a \key{Let}, it evaluates the initializing
  974. expression, extends the environment with the result value bound to the
  975. variable, then evaluates the body of the \key{Let}.
  976. \begin{figure}[tbp]
  977. \begin{lstlisting}
  978. (define (interp-exp env)
  979. (lambda (e)
  980. (match e
  981. [(Int n) n]
  982. [(Prim 'read '())
  983. (define r (read))
  984. (cond [(fixnum? r) r]
  985. [else (error 'interp-R1 "expected an integer" r)])]
  986. [(Prim '- (list e))
  987. (define v ((interp-exp env) e))
  988. (fx- 0 v)]
  989. [(Prim '+ (list e1 e2))
  990. (define v1 ((interp-exp env) e1))
  991. (define v2 ((interp-exp env) e2))
  992. (fx+ v1 v2)]
  993. [(Var x) (lookup x env)]
  994. [(Let x e body)
  995. (define new-env (cons (cons x ((interp-exp env) e)) env))
  996. ((interp-exp new-env) body)]
  997. )))
  998. (define (interp-R1 p)
  999. (match p
  1000. [(Program info e) ((interp-exp '()) e)]
  1001. ))
  1002. \end{lstlisting}
  1003. \caption{Interpreter for the $R_1$ language.}
  1004. \label{fig:interp-R1}
  1005. \end{figure}
  1006. The goal for this chapter is to implement a compiler that translates
  1007. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1008. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1009. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1010. is, they both output the same integer $n$. We depict this correctness
  1011. criteria in the following diagram.
  1012. \[
  1013. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1014. \node (p1) at (0, 0) {$P_1$};
  1015. \node (p2) at (4, 0) {$P_2$};
  1016. \node (o) at (4, -2) {$n$};
  1017. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1018. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1019. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1020. \end{tikzpicture}
  1021. \]
  1022. In the next section we introduce enough of the x86 assembly
  1023. language to compile $R_1$.
  1024. \section{The x86 Assembly Language}
  1025. \label{sec:x86}
  1026. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1027. the x86 assembly language needed for this chapter.
  1028. %
  1029. An x86 program is a sequence of instructions. The program is stored in
  1030. the computer's memory and the computer has a \emph{program counter}
  1031. that points to the address of the next instruction to be executed. For
  1032. most instructions, once the instruction is executed, the program
  1033. counter is incremented to point to the immediately following
  1034. instruction in memory. Most x86 instructions take two operands, where
  1035. each operand is either an integer constant (called \emph{immediate
  1036. value}), a \emph{register}, or a \emph{memory} location. A register
  1037. is a special kind of variable. Each one holds a 64-bit value; there
  1038. are 16 registers in the computer and their names are given in
  1039. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1040. addresses to 64-bit values%
  1041. \footnote{This simple story suffices for describing how sequential
  1042. programs access memory but is not sufficient for multi-threaded
  1043. programs. However, multi-threaded execution is beyond the scope of
  1044. this book.}.
  1045. %
  1046. We use the AT\&T syntax expected by the GNU assembler, which comes
  1047. with the \key{gcc} compiler that we use for compiling assembly code to
  1048. machine code.
  1049. %
  1050. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1051. the x86 instructions used in this book.
  1052. % to do: finish treatment of imulq
  1053. % it's needed for vector's in R6/R7
  1054. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1055. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1056. && \key{r8} \mid \key{r9} \mid \key{r10}
  1057. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1058. \mid \key{r14} \mid \key{r15}}
  1059. \begin{figure}[tp]
  1060. \fbox{
  1061. \begin{minipage}{0.96\textwidth}
  1062. \[
  1063. \begin{array}{lcl}
  1064. \Reg &::=& \allregisters{} \\
  1065. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  1066. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  1067. \key{subq} \; \Arg, \Arg \mid
  1068. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  1069. && \key{callq} \; \mathit{label} \mid
  1070. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1071. \Prog &::= & \key{.globl main}\\
  1072. & & \key{main:} \; \Instr^{+}
  1073. \end{array}
  1074. \]
  1075. \end{minipage}
  1076. }
  1077. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1078. \label{fig:x86-a}
  1079. \end{figure}
  1080. An immediate value is written using the notation \key{\$}$n$ where $n$
  1081. is an integer.
  1082. %
  1083. A register is written with a \key{\%} followed by the register name,
  1084. such as \key{\%rax}.
  1085. %
  1086. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1087. which obtains the address stored in register $r$ and then adds $n$
  1088. bytes to the address. The resulting address is used to either load or
  1089. store to memory depending on whether it occurs as a source or
  1090. destination argument of an instruction.
  1091. An arithmetic instruction such as $\key{addq}\,s,\,d$ reads from the
  1092. source $s$ and destination $d$, applies the arithmetic operation, then
  1093. writes the result back to the destination $d$.
  1094. %
  1095. The move instruction $\key{movq}\,s\,d$ reads from $s$ and stores the
  1096. result in $d$.
  1097. %
  1098. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1099. specified by the label. We discuss procedure calls in more detail
  1100. later in this chapter and in Chapter~\ref{ch:functions}.
  1101. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1102. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1103. \key{main} procedure is externally visible, which is necessary so
  1104. that the operating system can call it. The label \key{main:}
  1105. indicates the beginning of the \key{main} procedure which is where
  1106. the operating system starts executing this program. The instruction
  1107. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1108. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1109. $10$ in \key{rax} and puts the result, $42$, back into
  1110. \key{rax}.
  1111. %
  1112. The last instruction, \key{retq}, finishes the \key{main} function by
  1113. returning the integer in \key{rax} to the operating system. The
  1114. operating system interprets this integer as the program's exit
  1115. code. By convention, an exit code of 0 indicates that a program
  1116. completed successfully, and all other exit codes indicate various
  1117. errors. Nevertheless, we return the result of the program as the exit
  1118. code.
  1119. %\begin{wrapfigure}{r}{2.25in}
  1120. \begin{figure}[tbp]
  1121. \begin{lstlisting}
  1122. .globl main
  1123. main:
  1124. movq $10, %rax
  1125. addq $32, %rax
  1126. retq
  1127. \end{lstlisting}
  1128. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1129. \label{fig:p0-x86}
  1130. %\end{wrapfigure}
  1131. \end{figure}
  1132. Unfortunately, x86 varies in a couple ways depending on what operating
  1133. system it is assembled in. The code examples shown here are correct on
  1134. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1135. labels like \key{main} must be prefixed with an underscore, as in
  1136. \key{\_main}.
  1137. We exhibit the use of memory for storing intermediate results in the
  1138. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1139. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1140. region of memory called the \emph{procedure call stack} (or
  1141. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1142. for each procedure call. The memory layout for an individual frame is
  1143. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1144. \emph{stack pointer} and points to the item at the top of the
  1145. stack. The stack grows downward in memory, so we increase the size of
  1146. the stack by subtracting from the stack pointer. Some operating
  1147. systems require the frame size to be a multiple of 16 bytes. In the
  1148. context of a procedure call, the \emph{return address} is the next
  1149. instruction after the call instruction on the caller side. During a
  1150. function call, the return address is pushed onto the stack. The
  1151. register \key{rbp} is the \emph{base pointer} which serves two
  1152. purposes: 1) it saves the location of the stack pointer for the
  1153. calling procedure and 2) it is used to access variables associated
  1154. with the current procedure. The base pointer of the calling procedure
  1155. is pushed onto the stack after the return address. We number the
  1156. variables from $1$ to $n$. Variable $1$ is stored at address
  1157. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1158. \begin{figure}[tbp]
  1159. \begin{lstlisting}
  1160. start:
  1161. movq $10, -8(%rbp)
  1162. negq -8(%rbp)
  1163. movq -8(%rbp), %rax
  1164. addq $52, %rax
  1165. jmp conclusion
  1166. .globl main
  1167. main:
  1168. pushq %rbp
  1169. movq %rsp, %rbp
  1170. subq $16, %rsp
  1171. jmp start
  1172. conclusion:
  1173. addq $16, %rsp
  1174. popq %rbp
  1175. retq
  1176. \end{lstlisting}
  1177. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1178. \label{fig:p1-x86}
  1179. \end{figure}
  1180. \begin{figure}[tbp]
  1181. \centering
  1182. \begin{tabular}{|r|l|} \hline
  1183. Position & Contents \\ \hline
  1184. 8(\key{\%rbp}) & return address \\
  1185. 0(\key{\%rbp}) & old \key{rbp} \\
  1186. -8(\key{\%rbp}) & variable $1$ \\
  1187. -16(\key{\%rbp}) & variable $2$ \\
  1188. \ldots & \ldots \\
  1189. 0(\key{\%rsp}) & variable $n$\\ \hline
  1190. \end{tabular}
  1191. \caption{Memory layout of a frame.}
  1192. \label{fig:frame}
  1193. \end{figure}
  1194. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1195. three instructions are the typical \emph{prelude} for a procedure.
  1196. The instruction \key{pushq \%rbp} saves the base pointer for the
  1197. caller onto the stack and subtracts $8$ from the stack pointer. The
  1198. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1199. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1200. stack pointer down to make enough room for storing variables. This
  1201. program needs one variable ($8$ bytes) but because the frame size is
  1202. required to be a multiple of 16 bytes, the space for variables is
  1203. rounded to 16 bytes.
  1204. The four instructions under the label \code{start} carry out the work
  1205. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1206. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1207. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1208. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1209. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1210. \key{rax}, at which point \key{rax} contains $42$.
  1211. The three instructions under the label \code{conclusion} are the
  1212. typical \emph{finale} of a procedure. The first two instructions are
  1213. necessary to get the state of the machine back to where it was at the
  1214. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1215. moves the stack pointer back to point at the old base pointer. The
  1216. amount added here needs to match the amount that was subtracted in the
  1217. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1218. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1219. instruction, \key{retq}, jumps back to the procedure that called this
  1220. one and adds 8 to the stack pointer, which returns the stack pointer
  1221. to where it was prior to the procedure call.
  1222. The compiler will need a convenient representation for manipulating
  1223. x86 programs, so we define an abstract syntax for x86 in
  1224. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1225. a subscript $0$ because later we introduce extended versions of this
  1226. assembly language. The main difference compared to the concrete syntax
  1227. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1228. instructions to appear anywhere, but instead organizes instructions
  1229. into groups called \emph{blocks} and associates a label with every
  1230. block, which is why the \key{CFG} struct (for control-flow graph)
  1231. includes an association list mapping labels to blocks. The reason for
  1232. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1233. we introduce conditional branching.
  1234. \begin{figure}[tp]
  1235. \fbox{
  1236. \begin{minipage}{0.96\textwidth}
  1237. \[
  1238. \begin{array}{lcl}
  1239. \itm{reg} &::=& \allregisters{} \\
  1240. \Arg &::=& \IMM{\Int} \mid \REG{\itm{reg}}
  1241. \mid \DEREF{\itm{reg}}{\Int} \\
  1242. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg} \\
  1243. &\mid& \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1244. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}\\
  1245. &\mid& \UNIINSTR{\code{'negq}}{\Arg}\\
  1246. &\mid& \CALLQ{\itm{label}} \mid \RETQ{} \\
  1247. &\mid& \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1248. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1249. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1250. \end{array}
  1251. \]
  1252. \end{minipage}
  1253. }
  1254. \caption{Abstract syntax for $x86_0$ assembly.}
  1255. \label{fig:x86-ast-a}
  1256. \end{figure}
  1257. \section{Planning the trip to x86 via the $C_0$ language}
  1258. \label{sec:plan-s0-x86}
  1259. To compile one language to another it helps to focus on the
  1260. differences between the two languages because the compiler will need
  1261. to bridge those differences. What are the differences between $R_1$
  1262. and x86 assembly? Here are some of the most important ones:
  1263. \begin{enumerate}
  1264. \item[(a)] x86 arithmetic instructions typically have two arguments
  1265. and update the second argument in place. In contrast, $R_1$
  1266. arithmetic operations take two arguments and produce a new value.
  1267. An x86 instruction may have at most one memory-accessing argument.
  1268. Furthermore, some instructions place special restrictions on their
  1269. arguments.
  1270. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1271. whereas x86 instructions restrict their arguments to be integers
  1272. constants, registers, and memory locations.
  1273. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1274. sequence of instructions and jumps to labeled positions, whereas in
  1275. $R_1$ the order of evaluation is a left-to-right depth-first
  1276. traversal of the abstract syntax tree.
  1277. \item[(d)] An $R_1$ program can have any number of variables whereas
  1278. x86 has 16 registers and the procedure calls stack.
  1279. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1280. same name. The registers and memory locations of x86 all have unique
  1281. names or addresses.
  1282. \end{enumerate}
  1283. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1284. the problem into several steps, dealing with the above differences one
  1285. at a time. Each of these steps is called a \emph{pass} of the
  1286. compiler.
  1287. %
  1288. This terminology comes from each step traverses (i.e. passes over) the
  1289. AST of the program.
  1290. %
  1291. We begin by sketching how we might implement each pass, and give them
  1292. names. We then figure out an ordering of the passes and the
  1293. input/output language for each pass. The very first pass has $R_1$ as
  1294. its input language and the last pass has x86 as its output
  1295. language. In between we can choose whichever language is most
  1296. convenient for expressing the output of each pass, whether that be
  1297. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1298. Finally, to implement each pass we write one recursive function per
  1299. non-terminal in the grammar of the input language of the pass.
  1300. \begin{description}
  1301. \item[Pass \key{select-instructions}] To handle the difference between
  1302. $R_1$ operations and x86 instructions we convert each $R_1$
  1303. operation to a short sequence of instructions that accomplishes the
  1304. same task.
  1305. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1306. subexpression (i.e. operator and operand, and hence the name
  1307. \key{opera*}) is an \emph{atomic} expression (a variable or
  1308. integer), we introduce temporary variables to hold the results
  1309. of subexpressions.
  1310. \item[Pass \key{explicate-control}] To make the execution order of the
  1311. program explicit, we convert from the abstract syntax tree
  1312. representation into a \emph{control-flow graph} in which each node
  1313. contains a sequence of statements and the edges between nodes say
  1314. where to go at the end of the sequence.
  1315. \item[Pass \key{assign-homes}] To handle the difference between the
  1316. variables in $R_1$ versus the registers and stack locations in x86,
  1317. we assignment of each variable to a register or stack location.
  1318. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1319. by renaming every variable to a unique name, so that shadowing no
  1320. longer occurs.
  1321. \end{description}
  1322. The next question is: in what order should we apply these passes? This
  1323. question can be challenging because it is difficult to know ahead of
  1324. time which orders will be better (easier to implement, produce more
  1325. efficient code, etc.) so oftentimes trial-and-error is
  1326. involved. Nevertheless, we can try to plan ahead and make educated
  1327. choices regarding the ordering.
  1328. Let us consider the ordering of \key{uniquify} and
  1329. \key{remove-complex-opera*}. The assignment of subexpressions to
  1330. temporary variables involves introducing new variables and moving
  1331. subexpressions, which might change the shadowing of variables and
  1332. inadvertently change the behavior of the program. But if we apply
  1333. \key{uniquify} first, this will not be an issue. Of course, this means
  1334. that in \key{remove-complex-opera*}, we need to ensure that the
  1335. temporary variables that it creates are unique.
  1336. What should be the ordering of \key{explicate-control} with respect to
  1337. \key{uniquify}? The \key{uniquify} pass should come first because
  1338. \key{explicate-control} changes all the \key{let}-bound variables to
  1339. become local variables whose scope is the entire program, which would
  1340. confuse variables with the same name.
  1341. %
  1342. Likewise, we place \key{explicate-control} after
  1343. \key{remove-complex-opera*} because \key{explicate-control} removes
  1344. the \key{let} form, but it is convenient to use \key{let} in the
  1345. output of \key{remove-complex-opera*}.
  1346. %
  1347. Regarding \key{assign-homes}, it is helpful to place
  1348. \key{explicate-control} first because \key{explicate-control} changes
  1349. \key{let}-bound variables into program-scope variables. This means
  1350. that the \key{assign-homes} pass can read off the variables from the
  1351. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1352. entire program in search of \key{let}-bound variables.
  1353. Last, we need to decide on the ordering of \key{select-instructions}
  1354. and \key{assign-homes}. These two passes are intertwined, creating a
  1355. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1356. have already determined which instructions will be used, because x86
  1357. instructions have restrictions about which of their arguments can be
  1358. registers versus stack locations. One might want to give preferential
  1359. treatment to variables that occur in register-argument positions. On
  1360. the other hand, it may turn out to be impossible to make sure that all
  1361. such variables are assigned to registers, and then one must redo the
  1362. selection of instructions. Some compilers handle this problem by
  1363. iteratively repeating these two passes until a good solution is found.
  1364. We shall use a simpler approach in which \key{select-instructions}
  1365. comes first, followed by the \key{assign-homes}, then a third
  1366. pass named \key{patch-instructions} that uses a reserved register to
  1367. patch-up outstanding problems regarding instructions with too many
  1368. memory accesses. The disadvantage of this approach is some programs
  1369. may not execute as efficiently as they would if we used the iterative
  1370. approach and used all of the registers for variables.
  1371. \begin{figure}[tbp]
  1372. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1373. \node (R1) at (0,2) {\large $R_1$};
  1374. \node (R1-2) at (3,2) {\large $R_1$};
  1375. \node (R1-3) at (6,2) {\large $R_1$};
  1376. %\node (C0-1) at (6,0) {\large $C_0$};
  1377. \node (C0-2) at (3,0) {\large $C_0$};
  1378. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1379. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1380. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1381. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1382. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1383. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1384. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1385. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1386. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1387. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1388. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1389. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1390. \end{tikzpicture}
  1391. \caption{Overview of the passes for compiling $R_1$. }
  1392. \label{fig:R1-passes}
  1393. \end{figure}
  1394. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1395. passes in the form of a graph. Each pass is an edge and the
  1396. input/output language of each pass is a node in the graph. The output
  1397. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1398. are still in the $R_1$ language, but the output of the pass
  1399. \key{explicate-control} is in a different language $C_0$ that is
  1400. designed to make the order of evaluation explicit in its syntax, which
  1401. we introduce in the next section. The \key{select-instruction} pass
  1402. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1403. \key{patch-instructions} passes input and output variants of x86
  1404. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1405. \key{print-x86}, which converts from the abstract syntax of
  1406. $\text{x86}_0$ to the concrete syntax of x86.
  1407. In the next sections we discuss the $C_0$ language and the
  1408. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1409. remainder of this chapter gives hints regarding the implementation of
  1410. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1411. \subsection{The $C_0$ Intermediate Language}
  1412. The output of \key{explicate-control} is similar to the $C$
  1413. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1414. categories for expressions and statements, so we name it $C_0$. The
  1415. concrete syntax for $C_0$ is define din
  1416. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1417. is defined in Figure~\ref{fig:c0-syntax}.
  1418. %
  1419. The $C_0$ language supports the same operators as $R_1$ but the
  1420. arguments of operators are restricted to atomic expressions (variables
  1421. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1422. literature this style of intermediate language is called
  1423. administrative normal form, or ANF for
  1424. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1425. expressions, $C_0$ has assignment statements which can be executed in
  1426. sequence using the \key{Seq} form. A sequence of statements always
  1427. ends with \key{Return}, a guarantee that is baked into the grammar
  1428. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1429. comes from the term \emph{tail position}, which refers to an
  1430. expression that is the last one to execute within a function. (A
  1431. expression in tail position may contain subexpressions, and those may
  1432. or may not be in tail position depending on the kind of expression.)
  1433. A $C_0$ program consists of a control-flow graph (represented as an
  1434. association list mapping labels to tails). This is more general than
  1435. necessary for the present chapter, as we do not yet need to introduce
  1436. \key{goto} for jumping to labels, but it saves us from having to
  1437. change the syntax of the program construct in
  1438. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1439. \key{start}, and the whole program is its tail.
  1440. %
  1441. The $\itm{info}$ field of the \key{Program} form, after the
  1442. \key{explicate-control} pass, contains a mapping from the symbol
  1443. \key{locals} to a list of variables, that is, a list of all the
  1444. variables used in the program. At the start of the program, these
  1445. variables are uninitialized; they become initialized on their first
  1446. assignment.
  1447. \begin{figure}[tbp]
  1448. \fbox{
  1449. \begin{minipage}{0.96\textwidth}
  1450. \[
  1451. \begin{array}{lcl}
  1452. \Arg &::=& \Int \mid \Var \\
  1453. \Exp &::=& \Arg \mid \key{(read)} \mid \key{(-}~\Arg\key{)} \mid \key{(+}~\Arg~\Arg\key{)}\\
  1454. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1455. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1456. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1457. \end{array}
  1458. \]
  1459. \end{minipage}
  1460. }
  1461. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1462. \label{fig:c0-concrete-syntax}
  1463. \end{figure}
  1464. \begin{figure}[tbp]
  1465. \fbox{
  1466. \begin{minipage}{0.96\textwidth}
  1467. \[
  1468. \begin{array}{lcl}
  1469. \Arg &::=& \INT{\Int} \mid \VAR{\Var} \\
  1470. \Exp &::=& \Arg \mid \READ{} \mid \NEG{\Arg} \\
  1471. &\mid& \ADD{\Arg}{\Arg}\\
  1472. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1473. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1474. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1475. \end{array}
  1476. \]
  1477. \end{minipage}
  1478. }
  1479. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1480. \label{fig:c0-syntax}
  1481. \end{figure}
  1482. %% The \key{select-instructions} pass is optimistic in the sense that it
  1483. %% treats variables as if they were all mapped to registers. The
  1484. %% \key{select-instructions} pass generates a program that consists of
  1485. %% x86 instructions but that still uses variables, so it is an
  1486. %% intermediate language that is technically different than x86, which
  1487. %% explains the asterisks in the diagram above.
  1488. %% In this Chapter we shall take the easy road to implementing
  1489. %% \key{assign-homes} and simply map all variables to stack locations.
  1490. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1491. %% smarter approach in which we make a best-effort to map variables to
  1492. %% registers, resorting to the stack only when necessary.
  1493. %% Once variables have been assigned to their homes, we can finalize the
  1494. %% instruction selection by dealing with an idiosyncrasy of x86
  1495. %% assembly. Many x86 instructions have two arguments but only one of the
  1496. %% arguments may be a memory reference (and the stack is a part of
  1497. %% memory). Because some variables may get mapped to stack locations,
  1498. %% some of our generated instructions may violate this restriction. The
  1499. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1500. %% replacing every violating instruction with a short sequence of
  1501. %% instructions that use the \key{rax} register. Once we have implemented
  1502. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1503. %% need to patch instructions will be relatively rare.
  1504. \subsection{The dialects of x86}
  1505. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1506. the pass \key{select-instructions}. It extends $x86_0$ with an
  1507. unbounded number of program-scope variables and has looser rules
  1508. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1509. output of \key{print-x86}, is the concrete syntax for x86.
  1510. \section{Uniquify Variables}
  1511. \label{sec:uniquify-s0}
  1512. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1513. programs in which every \key{let} uses a unique variable name. For
  1514. example, the \code{uniquify} pass should translate the program on the
  1515. left into the program on the right. \\
  1516. \begin{tabular}{lll}
  1517. \begin{minipage}{0.4\textwidth}
  1518. \begin{lstlisting}
  1519. (let ([x 32])
  1520. (+ (let ([x 10]) x) x))
  1521. \end{lstlisting}
  1522. \end{minipage}
  1523. &
  1524. $\Rightarrow$
  1525. &
  1526. \begin{minipage}{0.4\textwidth}
  1527. \begin{lstlisting}
  1528. (let ([x.1 32])
  1529. (+ (let ([x.2 10]) x.2) x.1))
  1530. \end{lstlisting}
  1531. \end{minipage}
  1532. \end{tabular} \\
  1533. %
  1534. The following is another example translation, this time of a program
  1535. with a \key{let} nested inside the initializing expression of another
  1536. \key{let}.\\
  1537. \begin{tabular}{lll}
  1538. \begin{minipage}{0.4\textwidth}
  1539. \begin{lstlisting}
  1540. (let ([x (let ([x 4])
  1541. (+ x 1))])
  1542. (+ x 2))
  1543. \end{lstlisting}
  1544. \end{minipage}
  1545. &
  1546. $\Rightarrow$
  1547. &
  1548. \begin{minipage}{0.4\textwidth}
  1549. \begin{lstlisting}
  1550. (let ([x.2 (let ([x.1 4])
  1551. (+ x.1 1))])
  1552. (+ x.2 2))
  1553. \end{lstlisting}
  1554. \end{minipage}
  1555. \end{tabular}
  1556. We recommend implementing \code{uniquify} by creating a function named
  1557. \code{uniquify-exp} that is structurally recursive function and mostly
  1558. just copies the input program. However, when encountering a \key{let},
  1559. it should generate a unique name for the variable (the Racket function
  1560. \code{gensym} is handy for this) and associate the old name with the
  1561. new unique name in an association list. The \code{uniquify-exp}
  1562. function will need to access this association list when it gets to a
  1563. variable reference, so we add another parameter to \code{uniquify-exp}
  1564. for the association list. It is quite common for a compiler pass to
  1565. need a map to store extra information about variables. Such maps are
  1566. traditionally called \emph{symbol tables}.
  1567. The skeleton of the \code{uniquify-exp} function is shown in
  1568. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1569. convenient to partially apply it to a symbol table and then apply it
  1570. to different expressions, as in the last clause for primitive
  1571. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1572. is useful for applying a function to each element of a list to produce
  1573. a new list.
  1574. \begin{exercise}
  1575. \normalfont % I don't like the italics for exercises. -Jeremy
  1576. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1577. implement the clauses for variables and for the \key{let} form.
  1578. \end{exercise}
  1579. \begin{figure}[tbp]
  1580. \begin{lstlisting}
  1581. (define (uniquify-exp symtab)
  1582. (lambda (e)
  1583. (match e
  1584. [(Var x) ___]
  1585. [(Int n) (Int n)]
  1586. [(Let x e body) ___]
  1587. [(Prim op es)
  1588. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1589. )))
  1590. (define (uniquify p)
  1591. (match p
  1592. [(Program info e)
  1593. (Program info ((uniquify-exp '()) e))]
  1594. )))
  1595. \end{lstlisting}
  1596. \caption{Skeleton for the \key{uniquify} pass.}
  1597. \label{fig:uniquify-s0}
  1598. \end{figure}
  1599. \begin{exercise}
  1600. \normalfont % I don't like the italics for exercises. -Jeremy
  1601. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1602. and checking whether the output programs produce the same result as
  1603. the input programs. The $R_1$ programs should be designed to test the
  1604. most interesting parts of the \key{uniquify} pass, that is, the
  1605. programs should include \key{let} forms, variables, and variables
  1606. that overshadow each other. The five programs should be in a
  1607. subdirectory named \key{tests} and they should have the same file name
  1608. except for a different integer at the end of the name, followed by the
  1609. ending \key{.rkt}. Use the \key{interp-tests} function
  1610. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1611. your \key{uniquify} pass on the example programs. See the
  1612. \key{run-tests.rkt} script in the student support code for an example
  1613. of how to use \key{interp-tests}.
  1614. \end{exercise}
  1615. \section{Remove Complex Operands}
  1616. \label{sec:remove-complex-opera-r1}
  1617. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1618. $R_1$ programs in which the arguments of operations are atomic
  1619. expressions. Put another way, this pass removes complex operands,
  1620. such as the expression \code{(- 10)} in the program below. This is
  1621. accomplished by introducing a new \key{let}-bound variable, binding
  1622. the complex operand to the new variable, and then using the new
  1623. variable in place of the complex operand, as shown in the output of
  1624. \code{remove-complex-opera*} on the right.\\
  1625. \begin{tabular}{lll}
  1626. \begin{minipage}{0.4\textwidth}
  1627. % s0_19.rkt
  1628. \begin{lstlisting}
  1629. (+ 52 (- 10))
  1630. \end{lstlisting}
  1631. \end{minipage}
  1632. &
  1633. $\Rightarrow$
  1634. &
  1635. \begin{minipage}{0.4\textwidth}
  1636. \begin{lstlisting}
  1637. (let ([tmp.1 (- 10)])
  1638. (+ 52 tmp.1))
  1639. \end{lstlisting}
  1640. \end{minipage}
  1641. \end{tabular}
  1642. We recommend implementing this pass with two mutually recursive
  1643. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1644. \code{rco-atom} to subexpressions that need to become atomic and to
  1645. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1646. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1647. function returns an expression. The \code{rco-atom} function returns
  1648. two things: an atomic expression and association list mapping
  1649. temporary variables to complex subexpressions. You can return multiple
  1650. things from a function using Racket's \key{values} form and you can
  1651. receive multiple things from a function call using the
  1652. \key{define-values} form. If you are not familiar with these features,
  1653. review the Racket documentation. Also, the \key{for/lists} form is
  1654. useful for applying a function to each element of a list, in the case
  1655. where the function returns multiple values.
  1656. The following shows the output of \code{rco-atom} on the expression
  1657. \code{(- 10)} (using concrete syntax to be concise).
  1658. \begin{tabular}{lll}
  1659. \begin{minipage}{0.4\textwidth}
  1660. \begin{lstlisting}
  1661. (- 10)
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. &
  1665. $\Rightarrow$
  1666. &
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. tmp.1
  1670. ((tmp.1 . (- 10)))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \end{tabular}
  1674. Take special care of programs such as the next one that \key{let}-bind
  1675. variables with integers or other variables. You should leave them
  1676. unchanged, as shown in to the program on the right \\
  1677. \begin{tabular}{lll}
  1678. \begin{minipage}{0.4\textwidth}
  1679. % s0_20.rkt
  1680. \begin{lstlisting}
  1681. (let ([a 42])
  1682. (let ([b a])
  1683. b))
  1684. \end{lstlisting}
  1685. \end{minipage}
  1686. &
  1687. $\Rightarrow$
  1688. &
  1689. \begin{minipage}{0.4\textwidth}
  1690. \begin{lstlisting}
  1691. (let ([a 42])
  1692. (let ([b a])
  1693. b))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular} \\
  1697. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1698. produce the following output.\\
  1699. \begin{minipage}{0.4\textwidth}
  1700. \begin{lstlisting}
  1701. (let ([tmp.1 42])
  1702. (let ([a tmp.1])
  1703. (let ([tmp.2 a])
  1704. (let ([b tmp.2])
  1705. b))))
  1706. \end{lstlisting}
  1707. \end{minipage}
  1708. \begin{exercise}
  1709. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1710. it on all of the example programs that you created to test the
  1711. \key{uniquify} pass and create three new example programs that are
  1712. designed to exercise the interesting code in the
  1713. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1714. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1715. your passes on the example programs.
  1716. \end{exercise}
  1717. \section{Explicate Control}
  1718. \label{sec:explicate-control-r1}
  1719. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1720. programs that make the order of execution explicit in their
  1721. syntax. For now this amounts to flattening \key{let} constructs into a
  1722. sequence of assignment statements. For example, consider the following
  1723. $R_1$ program.\\
  1724. % s0_11.rkt
  1725. \begin{minipage}{0.96\textwidth}
  1726. \begin{lstlisting}
  1727. (let ([y (let ([x 20])
  1728. (+ x (let ([x 22]) x)))])
  1729. y)
  1730. \end{lstlisting}
  1731. \end{minipage}\\
  1732. %
  1733. The output of the previous pass and of \code{explicate-control} is
  1734. shown below. Recall that the right-hand-side of a \key{let} executes
  1735. before its body, so the order of evaluation for this program is to
  1736. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1737. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1738. output of \code{explicate-control} makes this ordering explicit.\\
  1739. \begin{tabular}{lll}
  1740. \begin{minipage}{0.4\textwidth}
  1741. \begin{lstlisting}
  1742. (let ([y (let ([x.1 20])
  1743. (let ([x.2 22])
  1744. (+ x.1 x.2)))])
  1745. y)
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. &
  1749. $\Rightarrow$
  1750. &
  1751. \begin{minipage}{0.4\textwidth}
  1752. \begin{lstlisting}
  1753. locals: y x.1 x.2
  1754. start:
  1755. x.1 = 20;
  1756. x.2 = 22;
  1757. y = (+ x.1 x.2);
  1758. return y;
  1759. \end{lstlisting}
  1760. \end{minipage}
  1761. \end{tabular}
  1762. We recommend implementing \code{explicate-control} using two mutually
  1763. recursive functions: \code{explicate-tail} and
  1764. \code{explicate-assign}. The first function should be applied to
  1765. expressions in tail position whereas the second should be applied to
  1766. expressions that occur on the right-hand-side of a \key{let}. The
  1767. \code{explicate-tail} function takes an $R_1$ expression as input and
  1768. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1769. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1770. function takes an $R_1$ expression, the variable that it is to be
  1771. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1772. assignment (e.g., the code generated for the body of the \key{let}).
  1773. It returns a $\Tail$ and a list of variables. The top-level
  1774. \code{explicate-control} function should invoke \code{explicate-tail}
  1775. on the body of the \key{program} and then associate the \code{locals}
  1776. symbol with the resulting list of variables in the $\itm{info}$ field,
  1777. as in the above example.
  1778. %% \section{Uncover Locals}
  1779. %% \label{sec:uncover-locals-r1}
  1780. %% The pass \code{uncover-locals} simply collects all of the variables in
  1781. %% the program and places then in the $\itm{info}$ of the program
  1782. %% construct. Here is the output for the example program of the last
  1783. %% section.
  1784. %% \begin{minipage}{0.4\textwidth}
  1785. %% \begin{lstlisting}
  1786. %% (program ((locals . (x.1 x.2 y)))
  1787. %% ((start .
  1788. %% (seq (assign x.1 20)
  1789. %% (seq (assign x.2 22)
  1790. %% (seq (assign y (+ x.1 x.2))
  1791. %% (return y)))))))
  1792. %% \end{lstlisting}
  1793. %% \end{minipage}
  1794. \section{Select Instructions}
  1795. \label{sec:select-r1}
  1796. In the \code{select-instructions} pass we begin the work of
  1797. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1798. this pass is a variable of x86 that still uses variables, so we add an
  1799. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1800. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1801. \code{select-instructions} in terms of three auxiliary functions, one
  1802. for each of the non-terminals of $C_0$: $\Arg$, $\Stmt$, and $\Tail$.
  1803. The cases for $\Arg$ are straightforward, variables stay
  1804. the same and integer constants are changed to immediates:
  1805. $\INT{n}$ changes to $\IMM{n}$.
  1806. Next we consider the cases for $\Stmt$, starting with arithmetic
  1807. operations. For example, in $C_0$ an addition operation can take the
  1808. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1809. need to use the \key{addq} instruction which does an in-place
  1810. update. So we must first move \code{10} to \code{x}. \\
  1811. \begin{tabular}{lll}
  1812. \begin{minipage}{0.4\textwidth}
  1813. \begin{lstlisting}
  1814. x = (+ 10 32);
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. &
  1818. $\Rightarrow$
  1819. &
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. movq $10, x
  1823. addq $32, x
  1824. \end{lstlisting}
  1825. \end{minipage}
  1826. \end{tabular} \\
  1827. %
  1828. There are cases that require special care to avoid generating
  1829. needlessly complicated code. If one of the arguments of the addition
  1830. is the same as the left-hand side of the assignment, then there is no
  1831. need for the extra move instruction. For example, the following
  1832. assignment statement can be translated into a single \key{addq}
  1833. instruction.\\
  1834. \begin{tabular}{lll}
  1835. \begin{minipage}{0.4\textwidth}
  1836. \begin{lstlisting}
  1837. x = (+ 10 x);
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. &
  1841. $\Rightarrow$
  1842. &
  1843. \begin{minipage}{0.4\textwidth}
  1844. \begin{lstlisting}
  1845. addq $10, x
  1846. \end{lstlisting}
  1847. \end{minipage}
  1848. \end{tabular} \\
  1849. The \key{read} operation does not have a direct counterpart in x86
  1850. assembly, so we have instead implemented this functionality in the C
  1851. language, with the function \code{read\_int} in the file
  1852. \code{runtime.c}. In general, we refer to all of the functionality in
  1853. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1854. for short. When compiling your generated x86 assembly code, you need
  1855. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1856. using \code{gcc} option \code{-c}) and link it into the
  1857. executable. For our purposes of code generation, all you need to do is
  1858. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1859. (for left-hand side) into a call to the \code{read\_int} function
  1860. followed by a move from \code{rax} to the left-hand side. The move
  1861. from \code{rax} is needed because the return value from
  1862. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1863. \begin{tabular}{lll}
  1864. \begin{minipage}{0.4\textwidth}
  1865. \begin{lstlisting}
  1866. |$\itm{lhs}$| = (read);
  1867. \end{lstlisting}
  1868. \end{minipage}
  1869. &
  1870. $\Rightarrow$
  1871. &
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. callq read_int
  1875. movq %rax, |$\itm{lhs}$|
  1876. \end{lstlisting}
  1877. \end{minipage}
  1878. \end{tabular} \\
  1879. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1880. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1881. assignment to the \key{rax} register followed by a jump to the
  1882. conclusion of the program (so the conclusion needs to be labeled).
  1883. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1884. recursively and append the resulting instructions.
  1885. \begin{exercise}
  1886. \normalfont
  1887. Implement the \key{select-instructions} pass and test it on all of the
  1888. example programs that you created for the previous passes and create
  1889. three new example programs that are designed to exercise all of the
  1890. interesting code in this pass. Use the \key{interp-tests} function
  1891. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1892. your passes on the example programs.
  1893. \end{exercise}
  1894. \section{Assign Homes}
  1895. \label{sec:assign-r1}
  1896. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1897. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1898. Thus, the \key{assign-homes} pass is responsible for placing all of
  1899. the program variables in registers or on the stack. For runtime
  1900. efficiency, it is better to place variables in registers, but as there
  1901. are only 16 registers, some programs must necessarily resort to
  1902. placing some variables on the stack. In this chapter we focus on the
  1903. mechanics of placing variables on the stack. We study an algorithm for
  1904. placing variables in registers in
  1905. Chapter~\ref{ch:register-allocation-r1}.
  1906. Consider again the following $R_1$ program.
  1907. % s0_20.rkt
  1908. \begin{lstlisting}
  1909. (let ([a 42])
  1910. (let ([b a])
  1911. b))
  1912. \end{lstlisting}
  1913. For reference, we repeat the output of \code{select-instructions} on
  1914. the left and show the output of \code{assign-homes} on the right.
  1915. Recall that \key{explicate-control} associated the list of
  1916. variables with the \code{locals} symbol in the program's $\itm{info}$
  1917. field, so \code{assign-homes} has convenient access to the them. In
  1918. this example, we assign variable \code{a} to stack location
  1919. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1920. \begin{tabular}{l}
  1921. \begin{minipage}{0.4\textwidth}
  1922. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1923. locals: a b
  1924. start:
  1925. movq $42, a
  1926. movq a, b
  1927. movq b, %rax
  1928. jmp conclusion
  1929. \end{lstlisting}
  1930. \end{minipage}
  1931. {$\Rightarrow$}
  1932. \begin{minipage}{0.4\textwidth}
  1933. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1934. stack-space: 16
  1935. start:
  1936. movq $42, -8(%rbp)
  1937. movq -8(%rbp), -16(%rbp)
  1938. movq -16(%rbp), %rax
  1939. jmp conclusion
  1940. \end{lstlisting}
  1941. \end{minipage}
  1942. \end{tabular} \\
  1943. In the process of assigning variables to stack locations, it is
  1944. convenient to compute and store the size of the frame (in bytes) in
  1945. the $\itm{info}$ field of the \key{Program} node, with the key
  1946. \code{stack-space}, which will be needed later to generate the
  1947. procedure conclusion. Some operating systems place restrictions on
  1948. the frame size. For example, Mac OS X requires the frame size to be a
  1949. multiple of 16 bytes.
  1950. \begin{exercise}
  1951. \normalfont Implement the \key{assign-homes} pass and test it on all
  1952. of the example programs that you created for the previous passes pass.
  1953. We recommend that \key{assign-homes} take an extra parameter that is a
  1954. mapping of variable names to homes (stack locations for now). Use the
  1955. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1956. \key{utilities.rkt} to test your passes on the example programs.
  1957. \end{exercise}
  1958. \section{Patch Instructions}
  1959. \label{sec:patch-s0}
  1960. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1961. programs to $\text{x86}_0$ programs by making sure that each
  1962. instruction adheres to the restrictions of the x86 assembly language.
  1963. In particular, at most one argument of an instruction may be a memory
  1964. reference.
  1965. We return to the following running example.
  1966. % s0_20.rkt
  1967. \begin{lstlisting}
  1968. (let ([a 42])
  1969. (let ([b a])
  1970. b))
  1971. \end{lstlisting}
  1972. After the \key{assign-homes} pass, the above program has been translated to
  1973. the following. \\
  1974. \begin{minipage}{0.5\textwidth}
  1975. \begin{lstlisting}
  1976. stack-space: 16
  1977. start:
  1978. movq $42, -8(%rbp)
  1979. movq -8(%rbp), -16(%rbp)
  1980. movq -16(%rbp), %rax
  1981. jmp conclusion
  1982. \end{lstlisting}
  1983. \end{minipage}\\
  1984. The second \key{movq} instruction is problematic because both
  1985. arguments are stack locations. We suggest fixing this problem by
  1986. moving from the source location to the register \key{rax} and then
  1987. from \key{rax} to the destination location, as follows.
  1988. \begin{lstlisting}
  1989. movq -8(%rbp), %rax
  1990. movq %rax, -16(%rbp)
  1991. \end{lstlisting}
  1992. \begin{exercise}
  1993. \normalfont
  1994. Implement the \key{patch-instructions} pass and test it on all of the
  1995. example programs that you created for the previous passes and create
  1996. three new example programs that are designed to exercise all of the
  1997. interesting code in this pass. Use the \key{interp-tests} function
  1998. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1999. your passes on the example programs.
  2000. \end{exercise}
  2001. \section{Print x86}
  2002. \label{sec:print-x86}
  2003. The last step of the compiler from $R_1$ to x86 is to convert the
  2004. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2005. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2006. \key{format} and \key{string-append} functions are useful in this
  2007. regard. The main work that this step needs to perform is to create the
  2008. \key{main} function and the standard instructions for its prelude and
  2009. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2010. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2011. variables, so we suggest computing it in the \key{assign-homes} pass
  2012. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2013. of the \key{program} node.
  2014. %% Your compiled code should print the result of the program's execution
  2015. %% by using the \code{print\_int} function provided in
  2016. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2017. %% far, this final result should be stored in the \key{rax} register.
  2018. %% We'll talk more about how to perform function calls with arguments in
  2019. %% general later on, but for now, place the following after the compiled
  2020. %% code for the $R_1$ program but before the conclusion:
  2021. %% \begin{lstlisting}
  2022. %% movq %rax, %rdi
  2023. %% callq print_int
  2024. %% \end{lstlisting}
  2025. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2026. %% stores the first argument to be passed into \key{print\_int}.
  2027. If you want your program to run on Mac OS X, your code needs to
  2028. determine whether or not it is running on a Mac, and prefix
  2029. underscores to labels like \key{main}. You can determine the platform
  2030. with the Racket call \code{(system-type 'os)}, which returns
  2031. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2032. %% In addition to
  2033. %% placing underscores on \key{main}, you need to put them in front of
  2034. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2035. %% \_print\_int}).
  2036. \begin{exercise}
  2037. \normalfont Implement the \key{print-x86} pass and test it on all of
  2038. the example programs that you created for the previous passes. Use the
  2039. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2040. \key{utilities.rkt} to test your complete compiler on the example
  2041. programs. See the \key{run-tests.rkt} script in the student support
  2042. code for an example of how to use \key{compiler-tests}. Also, remember
  2043. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2044. \key{gcc}.
  2045. \end{exercise}
  2046. \section{Challenge: Partial Evaluator for $R_1$}
  2047. \label{sec:pe-R1}
  2048. This section describes optional challenge exercises that involve
  2049. adapting and improving the partial evaluator for $R_0$ that was
  2050. introduced in Section~\ref{sec:partial-evaluation}.
  2051. \begin{exercise}\label{ex:pe-R1}
  2052. \normalfont
  2053. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2054. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2055. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2056. and variables to the $R_0$ language, so you will need to add cases for
  2057. them in the \code{pe-exp} function. Also, note that the \key{program}
  2058. form changes slightly to include an $\itm{info}$ field. Once
  2059. complete, add the partial evaluation pass to the front of your
  2060. compiler and make sure that your compiler still passes all of the
  2061. tests.
  2062. \end{exercise}
  2063. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2064. \begin{exercise}
  2065. \normalfont
  2066. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2067. \code{pe-add} auxiliary functions with functions that know more about
  2068. arithmetic. For example, your partial evaluator should translate
  2069. \begin{lstlisting}
  2070. (+ 1 (+ (read) 1))
  2071. \end{lstlisting}
  2072. into
  2073. \begin{lstlisting}
  2074. (+ 2 (read))
  2075. \end{lstlisting}
  2076. To accomplish this, the \code{pe-exp} function should produce output
  2077. in the form of the $\itm{residual}$ non-terminal of the following
  2078. grammar.
  2079. \[
  2080. \begin{array}{lcl}
  2081. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2082. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2083. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2084. \end{array}
  2085. \]
  2086. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2087. that their inputs are $\itm{residual}$ expressions and they should
  2088. return $\itm{residual}$ expressions. Once the improvements are
  2089. complete, make sure that your compiler still passes all of the tests.
  2090. After all, fast code is useless if it produces incorrect results!
  2091. \end{exercise}
  2092. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2093. \chapter{Register Allocation}
  2094. \label{ch:register-allocation-r1}
  2095. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2096. make our life easier. However, we can improve the performance of the
  2097. generated code if we instead place some variables into registers. The
  2098. CPU can access a register in a single cycle, whereas accessing the
  2099. stack takes many cycles if the relevant data is in cache or many more
  2100. to access main memory if the data is not in cache.
  2101. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2102. serves as a running example. We show the source program and also the
  2103. output of instruction selection. At that point the program is almost
  2104. x86 assembly but not quite; it still contains variables instead of
  2105. stack locations or registers.
  2106. \begin{figure}
  2107. \begin{minipage}{0.45\textwidth}
  2108. Example $R_1$ program:
  2109. % s0_22.rkt
  2110. \begin{lstlisting}
  2111. (let ([v 1])
  2112. (let ([w 46])
  2113. (let ([x (+ v 7)])
  2114. (let ([y (+ 4 x)])
  2115. (let ([z (+ x w)])
  2116. (+ z (- y)))))))
  2117. \end{lstlisting}
  2118. \end{minipage}
  2119. \begin{minipage}{0.45\textwidth}
  2120. After instruction selection:
  2121. \begin{lstlisting}
  2122. locals: v w x y z t.1
  2123. start:
  2124. movq $1, v
  2125. movq $46, w
  2126. movq v, x
  2127. addq $7, x
  2128. movq x, y
  2129. addq $4, y
  2130. movq x, z
  2131. addq w, z
  2132. movq y, t.1
  2133. negq t.1
  2134. movq z, %rax
  2135. addq t.1, %rax
  2136. jmp conclusion
  2137. \end{lstlisting}
  2138. \end{minipage}
  2139. \caption{An example program for register allocation.}
  2140. \label{fig:reg-eg}
  2141. \end{figure}
  2142. The goal of register allocation is to fit as many variables into
  2143. registers as possible. A program sometimes has more variables than
  2144. registers, so we cannot map each variable to a different
  2145. register. Fortunately, it is common for different variables to be
  2146. needed during different periods of time during program execution, and
  2147. in such cases several variables can be mapped to the same register.
  2148. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2149. After the variable \code{x} is moved to \code{z} it is no longer
  2150. needed. Variable \code{y}, on the other hand, is used only after this
  2151. point, so \code{x} and \code{y} could share the same register. The
  2152. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2153. where a variable is needed. Once we have that information, we compute
  2154. which variables are needed at the same time, i.e., which ones
  2155. \emph{interfere}, and represent this relation as an undirected graph
  2156. whose vertices are variables and edges indicate when two variables
  2157. interfere with each other (Section~\ref{sec:build-interference}). We
  2158. then model register allocation as a graph coloring problem, which we
  2159. discuss in Section~\ref{sec:graph-coloring}.
  2160. In the event that we run out of registers despite these efforts, we
  2161. place the remaining variables on the stack, similar to what we did in
  2162. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2163. for assigning a variable to a stack location. The process of spilling
  2164. variables is handled as part of the graph coloring process described
  2165. in \ref{sec:graph-coloring}.
  2166. \section{Registers and Calling Conventions}
  2167. \label{sec:calling-conventions}
  2168. As we perform register allocation, we need to be aware of the
  2169. conventions that govern the way in which registers interact with
  2170. function calls, such as calls to the \code{read\_int} function. The
  2171. convention for x86 is that the caller is responsible for freeing up
  2172. some registers, the \emph{caller-saved registers}, prior to the
  2173. function call, and the callee is responsible for saving and restoring
  2174. some other registers, the \emph{callee-saved registers}, before and
  2175. after using them. The caller-saved registers are
  2176. \begin{lstlisting}
  2177. rax rdx rcx rsi rdi r8 r9 r10 r11
  2178. \end{lstlisting}
  2179. while the callee-saved registers are
  2180. \begin{lstlisting}
  2181. rsp rbp rbx r12 r13 r14 r15
  2182. \end{lstlisting}
  2183. Another way to think about this caller/callee convention is the
  2184. following. The caller should assume that all the caller-saved registers
  2185. get overwritten with arbitrary values by the callee. On the other
  2186. hand, the caller can safely assume that all the callee-saved registers
  2187. contain the same values after the call that they did before the call.
  2188. The callee can freely use any of the caller-saved registers. However,
  2189. if the callee wants to use a callee-saved register, the callee must
  2190. arrange to put the original value back in the register prior to
  2191. returning to the caller, which is usually accomplished by saving and
  2192. restoring the value from the stack.
  2193. \section{Liveness Analysis}
  2194. \label{sec:liveness-analysis-r1}
  2195. A variable is \emph{live} if the variable is used at some later point
  2196. in the program and there is not an intervening assignment to the
  2197. variable.
  2198. %
  2199. To understand the latter condition, consider the following code
  2200. fragment in which there are two writes to \code{b}. Are \code{a} and
  2201. \code{b} both live at the same time?
  2202. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2203. movq $5, a
  2204. movq $30, b
  2205. movq a, c
  2206. movq $10, b
  2207. addq b, c
  2208. \end{lstlisting}
  2209. The answer is no because the integer \code{30} written to \code{b} on
  2210. line 2 is never used. The variable \code{b} is read on line 5 and
  2211. there is an intervening write to \code{b} on line 4, so the read on
  2212. line 5 receives the value written on line 4, not line 2.
  2213. The live variables can be computed by traversing the instruction
  2214. sequence back to front (i.e., backwards in execution order). Let
  2215. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2216. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2217. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2218. variables before instruction $I_k$. The live variables after an
  2219. instruction are always the same as the live variables before the next
  2220. instruction.
  2221. \begin{equation} \label{eq:live-after-before-next}
  2222. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2223. \end{equation}
  2224. To start things off, there are no live variables after the last
  2225. instruction, so
  2226. \begin{equation}\label{eq:live-last-empty}
  2227. L_{\mathsf{after}}(n) = \emptyset
  2228. \end{equation}
  2229. We then apply the following rule repeatedly, traversing the
  2230. instruction sequence back to front.
  2231. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2232. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2233. \end{equation}
  2234. where $W(k)$ are the variables written to by instruction $I_k$ and
  2235. $R(k)$ are the variables read by instruction $I_k$.
  2236. Let us walk through the above example, applying these formulas
  2237. starting with the instruction on line 5. We collect the answers in the
  2238. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2239. instruction is $\emptyset$ because it is the last instruction
  2240. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2241. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2242. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2243. is
  2244. \[
  2245. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2246. \]
  2247. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2248. the live-before set from line 5 to be the live-after set for this
  2249. instruction (formula~\ref{eq:live-after-before-next}).
  2250. \[
  2251. L_{\mathsf{after}}(4) = \{ b, c \}
  2252. \]
  2253. This move instruction writes to $b$ and does not read from any
  2254. variables, so we have the following live-before set
  2255. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2256. \[
  2257. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2258. \]
  2259. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2260. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2261. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2262. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2263. variable that is not live and does not read from a variable.
  2264. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2265. because it writes to variable $a$.
  2266. \begin{minipage}{0.45\textwidth}
  2267. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2268. movq $5, a
  2269. movq $30, b
  2270. movq a, c
  2271. movq $10, b
  2272. addq b, c
  2273. \end{lstlisting}
  2274. \end{minipage}
  2275. \vrule\hspace{10pt}
  2276. \begin{minipage}{0.45\textwidth}
  2277. \begin{align*}
  2278. L_{\mathsf{before}}(1)= \emptyset,
  2279. L_{\mathsf{after}}(1)= \{a\}\\
  2280. L_{\mathsf{before}}(2)= \{a\},
  2281. L_{\mathsf{after}}(2)= \{a\}\\
  2282. L_{\mathsf{before}}(3)= \{a\},
  2283. L_{\mathsf{after}}(2)= \{c\}\\
  2284. L_{\mathsf{before}}(4)= \{c\},
  2285. L_{\mathsf{after}}(4)= \{b,c\}\\
  2286. L_{\mathsf{before}}(5)= \{b,c\},
  2287. L_{\mathsf{after}}(5)= \emptyset
  2288. \end{align*}
  2289. \end{minipage}
  2290. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2291. for the running example program, with each instruction aligned with
  2292. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2293. \begin{figure}[tbp]
  2294. \hspace{20pt}
  2295. \begin{minipage}{0.45\textwidth}
  2296. \begin{lstlisting}[numbers=left]
  2297. movq $1, v
  2298. movq $46, w
  2299. movq v, x
  2300. addq $7, x
  2301. movq x, y
  2302. addq $4, y
  2303. movq x, z
  2304. addq w, z
  2305. movq y, t.1
  2306. negq t.1)
  2307. movq z, %rax
  2308. addq t.1, %rax
  2309. jmp conclusion
  2310. \end{lstlisting}
  2311. \end{minipage}
  2312. \vrule\hspace{10pt}
  2313. \begin{minipage}{0.45\textwidth}
  2314. \begin{lstlisting}
  2315. |$\{\}$|
  2316. |$\{v \}$|
  2317. |$\{v,w\}$|
  2318. |$\{w,x\}$|
  2319. |$\{w,x\}$|
  2320. |$\{w,x,y\}$|
  2321. |$\{w,x,y\}$|
  2322. |$\{w,y,z\}$|
  2323. |$\{y,z\}$|
  2324. |$\{z,t.1\}$|
  2325. |$\{z,t.1\}$|
  2326. |$\{t.1\}$|
  2327. |$\{\}$|
  2328. |$\{\}$|
  2329. \end{lstlisting}
  2330. \end{minipage}
  2331. \caption{The running example annotated with live-after sets.}
  2332. \label{fig:live-eg}
  2333. \end{figure}
  2334. \begin{exercise}\normalfont
  2335. Implement the compiler pass named \code{uncover-live} that computes
  2336. the live-after sets. We recommend storing the live-after sets (a list
  2337. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2338. structure.
  2339. %
  2340. We recommend organizing your code to use a helper function that takes
  2341. a list of instructions and an initial live-after set (typically empty)
  2342. and returns the list of live-after sets.
  2343. %
  2344. We recommend creating helper functions to 1) compute the set of
  2345. variables that appear in an argument (of an instruction), 2) compute
  2346. the variables read by an instruction which corresponds to the $R$
  2347. function discussed above, and 3) the variables written by an
  2348. instruction which corresponds to $W$.
  2349. \end{exercise}
  2350. \section{Building the Interference Graph}
  2351. \label{sec:build-interference}
  2352. Based on the liveness analysis, we know where each variable is needed.
  2353. However, during register allocation, we need to answer questions of
  2354. the specific form: are variables $u$ and $v$ live at the same time?
  2355. (And therefore cannot be assigned to the same register.) To make this
  2356. question easier to answer, we create an explicit data structure, an
  2357. \emph{interference graph}. An interference graph is an undirected
  2358. graph that has an edge between two variables if they are live at the
  2359. same time, that is, if they interfere with each other.
  2360. The most obvious way to compute the interference graph is to look at
  2361. the set of live variables between each statement in the program and
  2362. add an edge to the graph for every pair of variables in the same set.
  2363. This approach is less than ideal for two reasons. First, it can be
  2364. expensive because it takes $O(n^2)$ time to look at every pair in a
  2365. set of $n$ live variables. Second, there is a special case in which
  2366. two variables that are live at the same time do not actually interfere
  2367. with each other: when they both contain the same value because we have
  2368. assigned one to the other.
  2369. A better way to compute the interference graph is to focus on the
  2370. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2371. instruction to overwrite something in a live variable. So for each
  2372. instruction, we create an edge between the variable being written to
  2373. and all the \emph{other} live variables. (One should not create self
  2374. edges.) For a \key{callq} instruction, think of all caller-saved
  2375. registers as being written to, so an edge must be added between every
  2376. live variable and every caller-saved register. For \key{movq}, we deal
  2377. with the above-mentioned special case by not adding an edge between a
  2378. live variable $v$ and destination $d$ if $v$ matches the source of the
  2379. move. So we have the following three rules.
  2380. \begin{enumerate}
  2381. \item If instruction $I_k$ is an arithmetic instruction such as
  2382. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2383. L_{\mathsf{after}}(k)$ unless $v = d$.
  2384. \item If instruction $I_k$ is of the form \key{callq}
  2385. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2386. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2387. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2388. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2389. d$ or $v = s$.
  2390. \end{enumerate}
  2391. \margincomment{JM: I think you could give examples of each one of these
  2392. using the example program and use those to help explain why these
  2393. rules are correct.\\
  2394. JS: Agreed.}
  2395. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2396. the following interference for the instruction at the specified line
  2397. number.
  2398. \begin{quote}
  2399. Line 2: no interference,\\
  2400. Line 3: $w$ interferes with $v$,\\
  2401. Line 4: $x$ interferes with $w$,\\
  2402. Line 5: $x$ interferes with $w$,\\
  2403. Line 6: $y$ interferes with $w$,\\
  2404. Line 7: $y$ interferes with $w$ and $x$,\\
  2405. Line 8: $z$ interferes with $w$ and $y$,\\
  2406. Line 9: $z$ interferes with $y$, \\
  2407. Line 10: $t.1$ interferes with $z$, \\
  2408. Line 11: $t.1$ interferes with $z$, \\
  2409. Line 12: no interference, \\
  2410. Line 13: no interference. \\
  2411. Line 14: no interference.
  2412. \end{quote}
  2413. The resulting interference graph is shown in
  2414. Figure~\ref{fig:interfere}.
  2415. \begin{figure}[tbp]
  2416. \large
  2417. \[
  2418. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2419. \node (v) at (0,0) {$v$};
  2420. \node (w) at (2,0) {$w$};
  2421. \node (x) at (4,0) {$x$};
  2422. \node (t1) at (6,-2) {$t.1$};
  2423. \node (y) at (2,-2) {$y$};
  2424. \node (z) at (4,-2) {$z$};
  2425. \draw (v) to (w);
  2426. \foreach \i in {w,x,y}
  2427. {
  2428. \foreach \j in {w,x,y}
  2429. {
  2430. \draw (\i) to (\j);
  2431. }
  2432. }
  2433. \draw (z) to (w);
  2434. \draw (z) to (y);
  2435. \draw (t1) to (z);
  2436. \end{tikzpicture}
  2437. \]
  2438. \caption{The interference graph of the example program.}
  2439. \label{fig:interfere}
  2440. \end{figure}
  2441. %% Our next concern is to choose a data structure for representing the
  2442. %% interference graph. There are many choices for how to represent a
  2443. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2444. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2445. %% data structure is to study the algorithm that uses the data structure,
  2446. %% determine what operations need to be performed, and then choose the
  2447. %% data structure that provide the most efficient implementations of
  2448. %% those operations. Often times the choice of data structure can have an
  2449. %% effect on the time complexity of the algorithm, as it does here. If
  2450. %% you skim the next section, you will see that the register allocation
  2451. %% algorithm needs to ask the graph for all of its vertices and, given a
  2452. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2453. %% correct choice of graph representation is that of an adjacency
  2454. %% list. There are helper functions in \code{utilities.rkt} for
  2455. %% representing graphs using the adjacency list representation:
  2456. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2457. %% (Appendix~\ref{appendix:utilities}).
  2458. %% %
  2459. %% \margincomment{\footnotesize To do: change to use the
  2460. %% Racket graph library. \\ --Jeremy}
  2461. %% %
  2462. %% In particular, those functions use a hash table to map each vertex to
  2463. %% the set of adjacent vertices, and the sets are represented using
  2464. %% Racket's \key{set}, which is also a hash table.
  2465. \begin{exercise}\normalfont
  2466. Implement the compiler pass named \code{build-interference} according
  2467. to the algorithm suggested above. We recommend using the Racket
  2468. \code{graph} package to create and inspect the interference graph.
  2469. The output graph of this pass should be stored in the $\itm{info}$
  2470. field of the program, under the key \code{conflicts}.
  2471. \end{exercise}
  2472. \section{Graph Coloring via Sudoku}
  2473. \label{sec:graph-coloring}
  2474. We come to the main event, mapping variables to registers (or to stack
  2475. locations in the event that we run out of registers). We need to make
  2476. sure not to map two variables to the same register if the two
  2477. variables interfere with each other. Thiking about the interference
  2478. graph, this means that adjacent vertices must be mapped to different
  2479. registers. If we think of registers as colors, the register
  2480. allocation problem becomes the widely-studied graph coloring
  2481. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2482. The reader may be more familiar with the graph coloring problem than he
  2483. or she realizes; the popular game of Sudoku is an instance of the
  2484. graph coloring problem. The following describes how to build a graph
  2485. out of an initial Sudoku board.
  2486. \begin{itemize}
  2487. \item There is one vertex in the graph for each Sudoku square.
  2488. \item There is an edge between two vertices if the corresponding squares
  2489. are in the same row, in the same column, or if the squares are in
  2490. the same $3\times 3$ region.
  2491. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2492. \item Based on the initial assignment of numbers to squares in the
  2493. Sudoku board, assign the corresponding colors to the corresponding
  2494. vertices in the graph.
  2495. \end{itemize}
  2496. If you can color the remaining vertices in the graph with the nine
  2497. colors, then you have also solved the corresponding game of Sudoku.
  2498. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2499. the corresponding graph with colored vertices. We map the Sudoku
  2500. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2501. sampling of the vertices (those that are colored) because showing
  2502. edges for all of the vertices would make the graph unreadable.
  2503. \begin{figure}[tbp]
  2504. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2505. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2506. \caption{A Sudoku game board and the corresponding colored graph.}
  2507. \label{fig:sudoku-graph}
  2508. \end{figure}
  2509. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2510. strategies to come up with an algorithm for allocating registers. For
  2511. example, one of the basic techniques for Sudoku is called Pencil
  2512. Marks. The idea is to use a process of elimination to determine what
  2513. numbers no longer make sense for a square and write down those
  2514. numbers in the square (writing very small). For example, if the number
  2515. $1$ is assigned to a square, then by process of elimination, you can
  2516. write the pencil mark $1$ in all the squares in the same row, column,
  2517. and region. Many Sudoku computer games provide automatic support for
  2518. Pencil Marks.
  2519. %
  2520. The Pencil Marks technique corresponds to the notion of
  2521. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2522. vertex, in Sudoku terms, is the set of numbers that are no longer
  2523. available. In graph terminology, we have the following definition:
  2524. \begin{equation*}
  2525. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2526. \text{ and } \mathrm{color}(v) = c \}
  2527. \end{equation*}
  2528. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2529. edge with $u$.
  2530. Using the Pencil Marks technique leads to a simple strategy for
  2531. filling in numbers: if there is a square with only one possible number
  2532. left, then write down that number! But what if there are no squares
  2533. with only one possibility left? One brute-force approach is to just
  2534. make a guess. If that guess ultimately leads to a solution, great. If
  2535. not, backtrack to the guess and make a different guess. One good
  2536. thing about Pencil Marks is that it reduces the degree of branching in
  2537. the search tree. Nevertheless, backtracking can be horribly time
  2538. consuming. One way to reduce the amount of backtracking is to use the
  2539. most-constrained-first heuristic. That is, when making a guess, always
  2540. choose a square with the fewest possibilities left (the vertex with
  2541. the highest saturation). The idea is that choosing highly constrained
  2542. squares earlier rather than later is better because later on there may
  2543. not be any possibilities left for those squares.
  2544. In some sense, register allocation is easier than Sudoku because we
  2545. can always cheat and add more numbers by mapping variables to the
  2546. stack. We would like to minimize the time needed to color the graph,
  2547. and backtracking is expensive. Thus, it makes sense to keep the
  2548. most-constrained-first heuristic but drop backtracking in favor of
  2549. greedy search (guess and just keep going).
  2550. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2551. greedy algorithm for register allocation based on saturation and the
  2552. most-constrained-first heuristic, which is roughly equivalent to the
  2553. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2554. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2555. Sudoku, the algorithm represents colors with integers, with the first
  2556. $k$ colors corresponding to the $k$ registers in a given machine and
  2557. the rest of the integers corresponding to stack locations.
  2558. \begin{figure}[btp]
  2559. \centering
  2560. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2561. Algorithm: DSATUR
  2562. Input: a graph |$G$|
  2563. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2564. |$W \gets \mathit{vertices}(G)$|
  2565. while |$W \neq \emptyset$| do
  2566. pick a vertex |$u$| from |$W$| with the highest saturation,
  2567. breaking ties randomly
  2568. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2569. |$\mathrm{color}[u] \gets c$|
  2570. |$W \gets W - \{u\}$|
  2571. \end{lstlisting}
  2572. \caption{The saturation-based greedy graph coloring algorithm.}
  2573. \label{fig:satur-algo}
  2574. \end{figure}
  2575. With this algorithm in hand, let us return to the running example and
  2576. consider how to color the interference graph in
  2577. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2578. colored and they are unsaturated, so we annotate each of them with a
  2579. dash for their color and an empty set for the saturation.
  2580. \[
  2581. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2582. \node (v) at (0,0) {$v:-,\{\}$};
  2583. \node (w) at (3,0) {$w:-,\{\}$};
  2584. \node (x) at (6,0) {$x:-,\{\}$};
  2585. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2586. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2587. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2588. \draw (v) to (w);
  2589. \foreach \i in {w,x,y}
  2590. {
  2591. \foreach \j in {w,x,y}
  2592. {
  2593. \draw (\i) to (\j);
  2594. }
  2595. }
  2596. \draw (z) to (w);
  2597. \draw (z) to (y);
  2598. \draw (t1) to (z);
  2599. \end{tikzpicture}
  2600. \]
  2601. We select a maximally saturated vertex and color it $0$. In this case we
  2602. have a 7-way tie, so we arbitrarily pick $t.1$. We then mark color $0$
  2603. as no longer available for $z$ because it interferes
  2604. with $t.1$.
  2605. \[
  2606. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2607. \node (v) at (0,0) {$v:-,\{\}$};
  2608. \node (w) at (3,0) {$w:-,\{\}$};
  2609. \node (x) at (6,0) {$x:-,\{\}$};
  2610. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2611. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2612. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2613. \draw (v) to (w);
  2614. \foreach \i in {w,x,y}
  2615. {
  2616. \foreach \j in {w,x,y}
  2617. {
  2618. \draw (\i) to (\j);
  2619. }
  2620. }
  2621. \draw (z) to (w);
  2622. \draw (z) to (y);
  2623. \draw (t1) to (z);
  2624. \end{tikzpicture}
  2625. \]
  2626. Next we repeat the process, selecting another maximally saturated
  2627. vertex, in this case is $z$, and color it with the first available
  2628. number, which is $1$.
  2629. \[
  2630. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2631. \node (v) at (0,0) {$v:-,\{\}$};
  2632. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2633. \node (x) at (6,0) {$x:-,\{\}$};
  2634. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2635. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2636. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2637. \draw (t1) to (z);
  2638. \draw (v) to (w);
  2639. \foreach \i in {w,x,y}
  2640. {
  2641. \foreach \j in {w,x,y}
  2642. {
  2643. \draw (\i) to (\j);
  2644. }
  2645. }
  2646. \draw (z) to (w);
  2647. \draw (z) to (y);
  2648. \end{tikzpicture}
  2649. \]
  2650. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2651. first available color, which is $0$.
  2652. \[
  2653. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2654. \node (v) at (0,0) {$v:-,\{\}$};
  2655. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2656. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2657. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2658. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2659. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2660. \draw (t1) to (z);
  2661. \draw (v) to (w);
  2662. \foreach \i in {w,x,y}
  2663. {
  2664. \foreach \j in {w,x,y}
  2665. {
  2666. \draw (\i) to (\j);
  2667. }
  2668. }
  2669. \draw (z) to (w);
  2670. \draw (z) to (y);
  2671. \end{tikzpicture}
  2672. \]
  2673. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2674. \[
  2675. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2676. \node (v) at (0,0) {$v:-,\{2\}$};
  2677. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2678. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2679. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2680. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2681. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2682. \draw (t1) to (z);
  2683. \draw (v) to (w);
  2684. \foreach \i in {w,x,y}
  2685. {
  2686. \foreach \j in {w,x,y}
  2687. {
  2688. \draw (\i) to (\j);
  2689. }
  2690. }
  2691. \draw (z) to (w);
  2692. \draw (z) to (y);
  2693. \end{tikzpicture}
  2694. \]
  2695. Now $x$ has the highest saturation, so we color it $1$.
  2696. \[
  2697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2698. \node (v) at (0,0) {$v:-,\{2\}$};
  2699. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2700. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2701. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2702. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2703. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2704. \draw (t1) to (z);
  2705. \draw (v) to (w);
  2706. \foreach \i in {w,x,y}
  2707. {
  2708. \foreach \j in {w,x,y}
  2709. {
  2710. \draw (\i) to (\j);
  2711. }
  2712. }
  2713. \draw (z) to (w);
  2714. \draw (z) to (y);
  2715. \end{tikzpicture}
  2716. \]
  2717. In the last step of the algorithm, we color $v$ with $0$.
  2718. \[
  2719. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2720. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2721. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2722. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2723. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2724. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2725. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2726. \draw (t1) to (z);
  2727. \draw (v) to (w);
  2728. \foreach \i in {w,x,y}
  2729. {
  2730. \foreach \j in {w,x,y}
  2731. {
  2732. \draw (\i) to (\j);
  2733. }
  2734. }
  2735. \draw (z) to (w);
  2736. \draw (z) to (y);
  2737. \end{tikzpicture}
  2738. \]
  2739. With the coloring complete, we can finalize the assignment of
  2740. variables to registers and stack locations. Recall that if we have $k$
  2741. registers, we map the first $k$ colors to registers and the rest to
  2742. stack locations. Suppose for the moment that we have just one
  2743. register to use for register allocation, \key{rcx}. Then the following
  2744. is the mapping of colors to registers and stack allocations.
  2745. \[
  2746. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2747. \]
  2748. Putting this mapping together with the above coloring of the variables, we
  2749. arrive at the following assignment.
  2750. \begin{gather*}
  2751. \{ v \mapsto \key{\%rcx}, \,
  2752. w \mapsto \key{-16(\%rbp)}, \,
  2753. x \mapsto \key{-8(\%rbp)}, \\
  2754. y \mapsto \key{\%rcx}, \,
  2755. z\mapsto \key{-8(\%rbp)},
  2756. t.1\mapsto \key{\%rcx} \}
  2757. \end{gather*}
  2758. Applying this assignment to our running example, on the left, yields
  2759. the program on the right.
  2760. % why frame size of 32? -JGS
  2761. \begin{center}
  2762. \begin{minipage}{0.3\textwidth}
  2763. \begin{lstlisting}
  2764. movq $1, v
  2765. movq $46, w
  2766. movq v, x
  2767. addq $7, x
  2768. movq x, y
  2769. addq $4, y
  2770. movq x, z
  2771. addq w, z
  2772. movq y, t.1
  2773. negq t.1
  2774. movq z, %rax
  2775. addq t.1, %rax
  2776. jmp conclusion
  2777. \end{lstlisting}
  2778. \end{minipage}
  2779. $\Rightarrow\qquad$
  2780. \begin{minipage}{0.45\textwidth}
  2781. \begin{lstlisting}
  2782. movq $1, %rcx
  2783. movq $46, -16(%rbp)
  2784. movq %rcx, -8(%rbp)
  2785. addq $7, -8(%rbp)
  2786. movq -8(%rbp), %rcx
  2787. addq $4, %rcx
  2788. movq -8(%rbp), -8(%rbp)
  2789. addq -16(%rbp), -8(%rbp)
  2790. movq %rcx, %rcx
  2791. negq %rcx
  2792. movq -8(%rbp), %rax
  2793. addq %rcx, %rax
  2794. jmp conclusion
  2795. \end{lstlisting}
  2796. \end{minipage}
  2797. \end{center}
  2798. The resulting program is almost an x86 program. The remaining step is
  2799. the patch instructions pass. In this example, the trivial move of
  2800. \code{-8(\%rbp)} to itself is deleted and the addition of
  2801. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2802. \code{rax} as follows.
  2803. \begin{lstlisting}
  2804. movq -16(%rbp), %rax
  2805. addq %rax, -8(%rbp)
  2806. \end{lstlisting}
  2807. An overview of all of the passes involved in register allocation is
  2808. shown in Figure~\ref{fig:reg-alloc-passes}.
  2809. \begin{figure}[tbp]
  2810. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2811. \node (R1) at (0,2) {\large $R_1$};
  2812. \node (R1-2) at (3,2) {\large $R_1$};
  2813. \node (R1-3) at (6,2) {\large $R_1$};
  2814. \node (C0-1) at (6,0) {\large $C_0$};
  2815. \node (C0-2) at (3,0) {\large $C_0$};
  2816. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2817. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2818. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2819. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2820. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2821. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2822. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2823. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2824. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2825. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2826. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2827. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2828. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2829. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2830. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2831. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2832. \end{tikzpicture}
  2833. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2834. \label{fig:reg-alloc-passes}
  2835. \end{figure}
  2836. \begin{exercise}\normalfont
  2837. Implement the pass \code{allocate-registers}, which should come
  2838. after the \code{build-interference} pass. The three new passes,
  2839. \code{uncover-live}, \code{build-interference}, and
  2840. \code{allocate-registers} replace the \code{assign-homes} pass of
  2841. Section~\ref{sec:assign-r1}.
  2842. We recommend that you create a helper function named
  2843. \code{color-graph} that takes an interference graph and a list of
  2844. all the variables in the program. This function should return a
  2845. mapping of variables to their colors (represented as natural
  2846. numbers). By creating this helper function, you will be able to
  2847. reuse it in Chapter~\ref{ch:functions} when you add support for
  2848. functions.
  2849. Once you have obtained the coloring from \code{color-graph}, you can
  2850. assign the variables to registers or stack locations and then reuse
  2851. code from the \code{assign-homes} pass from
  2852. Section~\ref{sec:assign-r1} to replace the variables with their
  2853. assigned location.
  2854. Test your updated compiler by creating new example programs that
  2855. exercise all of the register allocation algorithm, such as forcing
  2856. variables to be spilled to the stack.
  2857. \end{exercise}
  2858. \section{Print x86 and Conventions for Registers}
  2859. \label{sec:print-x86-reg-alloc}
  2860. Recall the \code{print-x86} pass generates the prelude and
  2861. conclusion instructions for the \code{main} function.
  2862. %
  2863. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2864. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2865. reason for this is that our \code{main} function must adhere to the
  2866. x86 calling conventions that we described in
  2867. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2868. function needs to restore (in the conclusion) any callee-saved
  2869. registers that get used during register allocation. The simplest
  2870. approach is to save and restore all of the callee-saved registers. The
  2871. more efficient approach is to keep track of which callee-saved
  2872. registers were used and only save and restore them. Either way, make
  2873. sure to take this use of stack space into account when you are
  2874. calculating the size of the frame. Also, don't forget that the size of
  2875. the frame needs to be a multiple of 16 bytes.
  2876. \section{Challenge: Move Biasing$^{*}$}
  2877. \label{sec:move-biasing}
  2878. This section describes an optional enhancement to register allocation
  2879. for those students who are looking for an extra challenge or who have
  2880. a deeper interest in register allocation.
  2881. We return to the running example, but we remove the supposition that
  2882. we only have one register to use. So we have the following mapping of
  2883. color numbers to registers.
  2884. \[
  2885. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2886. \]
  2887. Using the same assignment that was produced by register allocator
  2888. described in the last section, we get the following program.
  2889. \begin{minipage}{0.3\textwidth}
  2890. \begin{lstlisting}
  2891. movq $1, v
  2892. movq $46, w
  2893. movq v, x
  2894. addq $7, x
  2895. movq x, y
  2896. addq $4, y
  2897. movq x, z
  2898. addq w, z
  2899. movq y, t.1
  2900. negq t.1
  2901. movq z, %rax
  2902. addq t.1, %rax
  2903. jmp conclusion
  2904. \end{lstlisting}
  2905. \end{minipage}
  2906. $\Rightarrow\qquad$
  2907. \begin{minipage}{0.45\textwidth}
  2908. \begin{lstlisting}
  2909. movq $1, %rbx
  2910. movq $46, %rdx
  2911. movq %rbx, %rcx
  2912. addq $7, %rcx
  2913. movq %rcx, %rbx
  2914. addq $4, %rbx
  2915. movq %rcx, %rcx
  2916. addq %rdx, %rcx
  2917. movq %rbx, %rbx
  2918. negq %rbx
  2919. movq %rcx, %rax
  2920. addq %rbx, %rax
  2921. jmp conclusion
  2922. \end{lstlisting}
  2923. \end{minipage}
  2924. While this allocation is quite good, we could do better. For example,
  2925. the variables \key{v} and \key{x} ended up in different registers, but
  2926. if they had been placed in the same register, then the move from
  2927. \key{v} to \key{x} could be removed.
  2928. We say that two variables $p$ and $q$ are \emph{move related} if they
  2929. participate together in a \key{movq} instruction, that is, \key{movq}
  2930. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2931. color for a variable, it should prefer a color that has already been
  2932. used for a move-related variable (assuming that they do not
  2933. interfere). Of course, this preference should not override the
  2934. preference for registers over stack locations, but should only be used
  2935. as a tie breaker when choosing between registers or when choosing
  2936. between stack locations.
  2937. We recommend that you represent the move relationships in a graph,
  2938. similar to how we represented interference. The following is the
  2939. \emph{move graph} for our running example.
  2940. \[
  2941. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2942. \node (v) at (0,0) {$v$};
  2943. \node (w) at (3,0) {$w$};
  2944. \node (x) at (6,0) {$x$};
  2945. \node (y) at (3,-1.5) {$y$};
  2946. \node (z) at (6,-1.5) {$z$};
  2947. \node (t1) at (9,-1.5) {$t.1$};
  2948. \draw[bend left=15] (t1) to (y);
  2949. \draw[bend left=15] (v) to (x);
  2950. \draw (x) to (y);
  2951. \draw (x) to (z);
  2952. \end{tikzpicture}
  2953. \]
  2954. Now we replay the graph coloring, pausing to see the coloring of $x$
  2955. and $v$. So we have the following coloring and the most saturated
  2956. vertex is $x$.
  2957. \[
  2958. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2959. \node (v) at (0,0) {$v:-,\{2\}$};
  2960. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2961. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2962. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2963. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2964. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2965. \draw (t1) to (z);
  2966. \draw (v) to (w);
  2967. \foreach \i in {w,x,y}
  2968. {
  2969. \foreach \j in {w,x,y}
  2970. {
  2971. \draw (\i) to (\j);
  2972. }
  2973. }
  2974. \draw (z) to (w);
  2975. \draw (z) to (y);
  2976. \end{tikzpicture}
  2977. \]
  2978. Last time we chose to color $x$ with $1$,
  2979. %
  2980. which so happens to be the color of $z$, and $x$ is move related to
  2981. $z$. This was rather lucky, and if the program had been a little
  2982. different, and say $z$ had been already assigned to $2$, then $x$
  2983. would still get $1$ and our luck would have run out. With move
  2984. biasing, we use the fact that $x$ and $z$ are move related to
  2985. influence the choice of color for $x$, in this case choosing $1$
  2986. because that's the color of $z$.
  2987. \[
  2988. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2989. \node (v) at (0,0) {$v:-,\{2\}$};
  2990. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2991. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2992. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2993. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2994. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2995. \draw (t1) to (z);
  2996. \draw (v) to (w);
  2997. \foreach \i in {w,x,y}
  2998. {
  2999. \foreach \j in {w,x,y}
  3000. {
  3001. \draw (\i) to (\j);
  3002. }
  3003. }
  3004. \draw (z) to (w);
  3005. \draw (z) to (y);
  3006. \end{tikzpicture}
  3007. \]
  3008. Next we consider coloring the variable $v$, and we just need to avoid
  3009. choosing $2$ because of the interference with $w$. Last time we choose
  3010. the color $0$, simply because it was the lowest, but this time we know
  3011. that $v$ is move related to $x$, so we choose the color $1$.
  3012. \[
  3013. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3014. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3015. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3016. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3017. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3018. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3019. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3020. \draw (t1) to (z);
  3021. \draw (v) to (w);
  3022. \foreach \i in {w,x,y}
  3023. {
  3024. \foreach \j in {w,x,y}
  3025. {
  3026. \draw (\i) to (\j);
  3027. }
  3028. }
  3029. \draw (z) to (w);
  3030. \draw (z) to (y);
  3031. \end{tikzpicture}
  3032. \]
  3033. We apply this register assignment to the running example, on the left,
  3034. to obtain the code on right.
  3035. \begin{minipage}{0.45\textwidth}
  3036. \begin{lstlisting}
  3037. (block ()
  3038. (movq $1 v)
  3039. (movq $46 (var w))
  3040. (movq (var v) (var x))
  3041. (addq $7 (var x))
  3042. (movq (var x) (var y))
  3043. (addq $4 (var y))
  3044. (movq (var x) (var z))
  3045. (addq (var w) (var z))
  3046. (movq (var y) (var t.1))
  3047. (negq (var t.1))
  3048. (movq (var z) (reg rax))
  3049. (addq (var t.1) (reg rax))
  3050. (jmp conclusion))
  3051. \end{lstlisting}
  3052. \end{minipage}
  3053. $\Rightarrow$
  3054. \begin{minipage}{0.45\textwidth}
  3055. \begin{lstlisting}
  3056. (block ()
  3057. (movq $1 (reg rcx))
  3058. (movq $46 (reg rbx))
  3059. (movq (reg rcx) (reg rcx))
  3060. (addq $7 (reg rcx))
  3061. (movq (reg rcx) (reg rdx))
  3062. (addq $4 (reg rdx))
  3063. (movq (reg rcx) (reg rcx))
  3064. (addq (reg rbx) (reg rcx))
  3065. (movq (reg rdx) (reg rbx))
  3066. (negq (reg rbx))
  3067. (movq (reg rcx) (reg rax))
  3068. (addq (reg rbx) (reg rax))
  3069. (jmp conclusion))
  3070. \end{lstlisting}
  3071. \end{minipage}
  3072. The \code{patch-instructions} then removes the trivial moves from
  3073. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3074. result.
  3075. \begin{minipage}{0.45\textwidth}
  3076. \begin{lstlisting}
  3077. (block ()
  3078. (movq $1 (reg rcx))
  3079. (movq $46 (reg rbx))
  3080. (addq $7 (reg rcx))
  3081. (movq (reg rcx) (reg rdx))
  3082. (addq $4 (reg rdx))
  3083. (addq (reg rbx) (reg rcx))
  3084. (movq (reg rdx) (reg rbx))
  3085. (negq (reg rbx))
  3086. (movq (reg rcx) (reg rax))
  3087. (addq (reg rbx) (reg rax))
  3088. (jmp conclusion))
  3089. \end{lstlisting}
  3090. \end{minipage}
  3091. \begin{exercise}\normalfont
  3092. Change your implementation of \code{allocate-registers} to take move
  3093. biasing into account. Make sure that your compiler still passes all of
  3094. the previous tests. Create two new tests that include at least one
  3095. opportunity for move biasing and visually inspect the output x86
  3096. programs to make sure that your move biasing is working properly.
  3097. \end{exercise}
  3098. \margincomment{\footnotesize To do: another neat challenge would be to do
  3099. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3101. \chapter{Booleans and Control Flow}
  3102. \label{ch:bool-types}
  3103. The $R_0$ and $R_1$ languages only had a single kind of value, the
  3104. integers. In this Chapter we add a second kind of value, the Booleans,
  3105. to create the $R_2$ language. The Boolean values \emph{true} and
  3106. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3107. Racket. We also introduce several operations that involve Booleans
  3108. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  3109. \key{if} expression. With the addition of \key{if} expressions,
  3110. programs can have non-trivial control flow which has an impact on
  3111. several parts of the compiler. Also, because we now have two kinds of
  3112. values, we need to worry about programs that apply an operation to the
  3113. wrong kind of value, such as \code{(not 1)}.
  3114. There are two language design options for such situations. One option
  3115. is to signal an error and the other is to provide a wider
  3116. interpretation of the operation. The Racket language uses a mixture of
  3117. these two options, depending on the operation and the kind of
  3118. value. For example, the result of \code{(not 1)} in Racket is
  3119. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  3120. the other hand, \code{(car 1)} results in a run-time error in Racket
  3121. stating that \code{car} expects a pair.
  3122. The Typed Racket language makes similar design choices as Racket,
  3123. except much of the error detection happens at compile time instead of
  3124. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3125. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3126. reports a compile-time error because Typed Racket expects the type of
  3127. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3128. For the $R_2$ language we choose to be more like Typed Racket in that
  3129. we shall perform type checking during compilation. In
  3130. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3131. is, how to compile a dynamically typed language like Racket. The
  3132. $R_2$ language is a subset of Typed Racket but by no means includes
  3133. all of Typed Racket. Furthermore, for many of the operations we shall
  3134. take a narrower interpretation than Typed Racket, for example,
  3135. rejecting \code{(not 1)}.
  3136. This chapter is organized as follows. We begin by defining the syntax
  3137. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3138. then introduce the idea of type checking and build a type checker for
  3139. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3140. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3141. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3142. how our compiler passes need to change to accommodate Booleans and
  3143. conditional control flow.
  3144. \section{The $R_2$ Language}
  3145. \label{sec:r2-lang}
  3146. The syntax of the $R_2$ language is defined in
  3147. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  3148. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  3149. \code{if} expression. Also, we expand the operators to include
  3150. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  3151. operations for comparing two integers or two Booleans, and the
  3152. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  3153. integers.
  3154. \begin{figure}[tp]
  3155. \centering
  3156. \fbox{
  3157. \begin{minipage}{0.96\textwidth}
  3158. \[
  3159. \begin{array}{lcl}
  3160. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3161. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  3162. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  3163. &\mid& \key{\#t} \mid \key{\#f}
  3164. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3165. \mid (\key{not}\;\Exp) \\
  3166. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  3167. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  3168. \end{array}
  3169. \]
  3170. \end{minipage}
  3171. }
  3172. \caption{The syntax of $R_2$, extending $R_1$
  3173. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  3174. \label{fig:r2-syntax}
  3175. \end{figure}
  3176. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3177. the parts that are the same as the interpreter for $R_1$
  3178. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3179. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3180. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3181. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3182. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3183. operations \code{not} and \code{and} behave as you might expect, but
  3184. note that the \code{and} operation is short-circuiting. That is, given
  3185. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3186. evaluated if $e_1$ evaluates to \code{\#f}.
  3187. With the addition of the comparison operations, there are quite a few
  3188. primitive operations and the interpreter code for them is somewhat
  3189. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3190. parts into the \code{interp-op} function and the similar parts into
  3191. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3192. use \code{interp-op} for the \code{and} operation because of the
  3193. short-circuiting behavior in the order of evaluation of its arguments.
  3194. \begin{figure}[tbp]
  3195. \begin{lstlisting}
  3196. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  3197. (define (interp-op op)
  3198. (match op
  3199. ...
  3200. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3201. ['eq? (lambda (v1 v2)
  3202. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3203. (and (boolean? v1) (boolean? v2)))
  3204. (eq? v1 v2)]))]
  3205. ['< (lambda (v1 v2)
  3206. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3207. ['<= (lambda (v1 v2)
  3208. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3209. ['> (lambda (v1 v2)
  3210. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3211. ['>= (lambda (v1 v2)
  3212. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3213. [else (error 'interp-op "unknown operator")]))
  3214. (define (interp-exp env)
  3215. (lambda (e)
  3216. (define recur (interp-exp env))
  3217. (match e
  3218. ...
  3219. [(? boolean?) e]
  3220. [`(if ,cnd ,thn ,els)
  3221. (define b (recur cnd))
  3222. (match b
  3223. [#t (recur thn)]
  3224. [#f (recur els)])]
  3225. [`(and ,e1 ,e2)
  3226. (define v1 (recur e1))
  3227. (match v1
  3228. [#t (match (recur e2) [#t #t] [#f #f])]
  3229. [#f #f])]
  3230. [`(,op ,args ...)
  3231. #:when (set-member? primitives op)
  3232. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3233. )))
  3234. (define (interp-R2 env)
  3235. (lambda (p)
  3236. (match p
  3237. [`(program ,info ,e)
  3238. ((interp-exp '()) e)])))
  3239. \end{lstlisting}
  3240. \caption{Interpreter for the $R_2$ language.}
  3241. \label{fig:interp-R2}
  3242. \end{figure}
  3243. \section{Type Checking $R_2$ Programs}
  3244. \label{sec:type-check-r2}
  3245. It is helpful to think about type checking in two complementary
  3246. ways. A type checker predicts the \emph{type} of value that will be
  3247. produced by each expression in the program. For $R_2$, we have just
  3248. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3249. predict that
  3250. \begin{lstlisting}
  3251. (+ 10 (- (+ 12 20)))
  3252. \end{lstlisting}
  3253. produces an \key{Integer} while
  3254. \begin{lstlisting}
  3255. (and (not #f) #t)
  3256. \end{lstlisting}
  3257. produces a \key{Boolean}.
  3258. As mentioned at the beginning of this chapter, a type checker also
  3259. rejects programs that apply operators to the wrong type of value. Our
  3260. type checker for $R_2$ will signal an error for the following
  3261. expression because, as we have seen above, the expression \code{(+ 10
  3262. ...)} has type \key{Integer}, and we require the argument of a
  3263. \code{not} to have type \key{Boolean}.
  3264. \begin{lstlisting}
  3265. (not (+ 10 (- (+ 12 20))))
  3266. \end{lstlisting}
  3267. The type checker for $R_2$ is best implemented as a structurally
  3268. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3269. many of the clauses for the \code{type-check-exp} function. Given an
  3270. input expression \code{e}, the type checker either returns the type
  3271. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3272. the type of an integer literal is \code{Integer} and the type of a
  3273. Boolean literal is \code{Boolean}. To handle variables, the type
  3274. checker, like the interpreter, uses an association list. However, in
  3275. this case the association list maps variables to types instead of
  3276. values. Consider the clause for \key{let}. We type check the
  3277. initializing expression to obtain its type \key{T} and then associate
  3278. type \code{T} with the variable \code{x}. When the type checker
  3279. encounters the use of a variable, it can find its type in the
  3280. association list.
  3281. \begin{figure}[tbp]
  3282. \begin{lstlisting}
  3283. (define (type-check-exp env)
  3284. (lambda (e)
  3285. (define recur (type-check-exp env))
  3286. (match e
  3287. [(? fixnum?) 'Integer]
  3288. [(? boolean?) 'Boolean]
  3289. [(? symbol? x) (dict-ref env x)]
  3290. [`(read) 'Integer]
  3291. [`(let ([,x ,e]) ,body)
  3292. (define T (recur e))
  3293. (define new-env (cons (cons x T) env))
  3294. (type-check-exp new-env body)]
  3295. ...
  3296. [`(not ,e)
  3297. (match (recur e)
  3298. ['Boolean 'Boolean]
  3299. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3300. ...
  3301. )))
  3302. (define (type-check-R2 env)
  3303. (lambda (e)
  3304. (match e
  3305. [`(program ,info ,body)
  3306. (define ty ((type-check-exp '()) body))
  3307. `(program ,info ,body)]
  3308. )))
  3309. \end{lstlisting}
  3310. \caption{Skeleton of a type checker for the $R_2$ language.}
  3311. \label{fig:type-check-R2}
  3312. \end{figure}
  3313. %% To print the resulting value correctly, the overall type of the
  3314. %% program must be threaded through the remainder of the passes. We can
  3315. %% store the type within the \key{program} form as shown in Figure
  3316. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3317. %% intermediate language produced by the type checker, which we define as
  3318. %% follows: \\[1ex]
  3319. %% \fbox{
  3320. %% \begin{minipage}{0.87\textwidth}
  3321. %% \[
  3322. %% \begin{array}{lcl}
  3323. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3324. %% \end{array}
  3325. %% \]
  3326. %% \end{minipage}
  3327. %% }
  3328. \begin{exercise}\normalfont
  3329. Complete the implementation of \code{type-check-R2} and test it on 10
  3330. new example programs in $R_2$ that you choose based on how thoroughly
  3331. they test the type checking algorithm. Half of the example programs
  3332. should have a type error, to make sure that your type checker properly
  3333. rejects them. The other half of the example programs should not have
  3334. type errors. Your testing should check that the result of the type
  3335. checker agrees with the value returned by the interpreter, that is, if
  3336. the type checker returns \key{Integer}, then the interpreter should
  3337. return an integer. Likewise, if the type checker returns
  3338. \key{Boolean}, then the interpreter should return \code{\#t} or
  3339. \code{\#f}. Note that if your type checker does not signal an error
  3340. for a program, then interpreting that program should not encounter an
  3341. error. If it does, there is something wrong with your type checker.
  3342. \end{exercise}
  3343. \section{Shrink the $R_2$ Language}
  3344. \label{sec:shrink-r2}
  3345. The $R_2$ language includes several operators that are easily
  3346. expressible in terms of other operators. For example, subtraction is
  3347. expressible in terms of addition and negation.
  3348. \[
  3349. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3350. \]
  3351. Several of the comparison operations are expressible in terms of
  3352. less-than and logical negation.
  3353. \[
  3354. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3355. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3356. \]
  3357. By performing these translations near the front-end of the compiler,
  3358. the later passes of the compiler will not need to deal with these
  3359. constructs, making those passes shorter. On the other hand, sometimes
  3360. these translations make it more difficult to generate the most
  3361. efficient code with respect to the number of instructions. However,
  3362. these differences typically do not affect the number of accesses to
  3363. memory, which is the primary factor that determines execution time on
  3364. modern computer architectures.
  3365. \begin{exercise}\normalfont
  3366. Implement the pass \code{shrink} that removes subtraction,
  3367. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3368. by translating them to other constructs in $R_2$. Create tests to
  3369. make sure that the behavior of all of these constructs stays the
  3370. same after translation.
  3371. \end{exercise}
  3372. \section{XOR, Comparisons, and Control Flow in x86}
  3373. \label{sec:x86-1}
  3374. To implement the new logical operations, the comparison operations,
  3375. and the \key{if} expression, we need to delve further into the x86
  3376. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3377. larger subset of x86 that includes instructions for logical
  3378. operations, comparisons, and jumps.
  3379. One small challenge is that x86 does not provide an instruction that
  3380. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3381. However, the \code{xorq} instruction can be used to encode \code{not}.
  3382. The \key{xorq} instruction takes two arguments, performs a pairwise
  3383. exclusive-or operation on each bit of its arguments, and writes the
  3384. results into its second argument. Recall the truth table for
  3385. exclusive-or:
  3386. \begin{center}
  3387. \begin{tabular}{l|cc}
  3388. & 0 & 1 \\ \hline
  3389. 0 & 0 & 1 \\
  3390. 1 & 1 & 0
  3391. \end{tabular}
  3392. \end{center}
  3393. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3394. in row of the table for the bit $1$, the result is the opposite of the
  3395. second bit. Thus, the \code{not} operation can be implemented by
  3396. \code{xorq} with $1$ as the first argument: $0001
  3397. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3398. 0001 = 0000$.
  3399. \begin{figure}[tp]
  3400. \fbox{
  3401. \begin{minipage}{0.96\textwidth}
  3402. \[
  3403. \begin{array}{lcl}
  3404. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3405. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3406. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3407. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3408. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3409. (\key{subq} \; \Arg\; \Arg) \mid
  3410. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3411. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3412. (\key{pushq}\;\Arg) \mid
  3413. (\key{popq}\;\Arg) \mid
  3414. (\key{retq})} \\
  3415. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3416. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3417. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3418. \mid (\key{jmp} \; \itm{label})
  3419. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3420. &\mid& (\key{label} \; \itm{label}) \\
  3421. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3422. \end{array}
  3423. \]
  3424. \end{minipage}
  3425. }
  3426. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3427. \label{fig:x86-1}
  3428. \end{figure}
  3429. Next we consider the x86 instructions that are relevant for
  3430. compiling the comparison operations. The \key{cmpq} instruction
  3431. compares its two arguments to determine whether one argument is less
  3432. than, equal, or greater than the other argument. The \key{cmpq}
  3433. instruction is unusual regarding the order of its arguments and where
  3434. the result is placed. The argument order is backwards: if you want to
  3435. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3436. \key{cmpq} is placed in the special EFLAGS register. This register
  3437. cannot be accessed directly but it can be queried by a number of
  3438. instructions, including the \key{set} instruction. The \key{set}
  3439. instruction puts a \key{1} or \key{0} into its destination depending
  3440. on whether the comparison came out according to the condition code
  3441. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3442. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3443. The set instruction has an annoying quirk in that its destination
  3444. argument must be single byte register, such as \code{al}, which is
  3445. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3446. instruction can then be used to move from a single byte register to a
  3447. normal 64-bit register.
  3448. For compiling the \key{if} expression, the x86 instructions for
  3449. jumping are relevant. The \key{jmp} instruction updates the program
  3450. counter to point to the instruction after the indicated label. The
  3451. \key{jmp-if} instruction updates the program counter to point to the
  3452. instruction after the indicated label depending on whether the result
  3453. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3454. the \key{jmp-if} instruction falls through to the next
  3455. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3456. register, it is quite common for the \key{jmp-if} to be immediately
  3457. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3458. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3459. for x86 to separate the instruction name from the condition code. For
  3460. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3461. \section{The $C_1$ Intermediate Language}
  3462. \label{sec:c1}
  3463. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3464. language, but we need to grow that intermediate language to handle the
  3465. new features in $R_2$: Booleans and conditional expressions.
  3466. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3467. logic and comparison operators to the $\Exp$ non-terminal, the
  3468. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3469. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3470. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3471. goto's in the grammar for $\Tail$. This means that a sequence of
  3472. statements may now end with a \code{goto} or a conditional
  3473. \code{goto}, which jumps to one of two labeled pieces of code
  3474. depending on the outcome of the comparison. In
  3475. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3476. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3477. and \key{goto}'s.
  3478. \begin{figure}[tp]
  3479. \fbox{
  3480. \begin{minipage}{0.96\textwidth}
  3481. \[
  3482. \begin{array}{lcl}
  3483. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3484. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3485. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3486. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3487. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3488. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3489. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3490. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3491. \end{array}
  3492. \]
  3493. \end{minipage}
  3494. }
  3495. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3496. \label{fig:c1-syntax}
  3497. \end{figure}
  3498. \section{Explicate Control}
  3499. \label{sec:explicate-control-r2}
  3500. Recall that the purpose of \code{explicate-control} is to make the
  3501. order of evaluation explicit in the syntax of the program. With the
  3502. addition of \key{if} in $R_2$, things get more interesting.
  3503. As a motivating example, consider the following program that has an
  3504. \key{if} expression nested in the predicate of another \key{if}.
  3505. % s1_38.rkt
  3506. \begin{lstlisting}
  3507. (program ()
  3508. (if (if (eq? (read) 1)
  3509. (eq? (read) 0)
  3510. (eq? (read) 2))
  3511. (+ 10 32)
  3512. (+ 700 77)))
  3513. \end{lstlisting}
  3514. %
  3515. The naive way to compile \key{if} and \key{eq?} would be to handle
  3516. each of them in isolation, regardless of their context. Each
  3517. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3518. by a couple instructions to move the result from the EFLAGS register
  3519. into a general purpose register or stack location. Each \key{if} would
  3520. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3521. However, if we take context into account we can do better and reduce
  3522. the use of \key{cmpq} and EFLAG-accessing instructions.
  3523. One idea is to try and reorganize the code at the level of $R_2$,
  3524. pushing the outer \key{if} inside the inner one. This would yield the
  3525. following code.
  3526. \begin{lstlisting}
  3527. (if (eq? (read) 1)
  3528. (if (eq? (read) 0)
  3529. (+ 10 32)
  3530. (+ 700 77))
  3531. (if (eq? (read) 2))
  3532. (+ 10 32)
  3533. (+ 700 77))
  3534. \end{lstlisting}
  3535. Unfortunately, this approach duplicates the two branches, and a
  3536. compiler must never duplicate code!
  3537. We need a way to perform the above transformation, but without
  3538. duplicating code. The solution is straightforward if we think at the
  3539. level of x86 assembly: we can label the code for each of the branches
  3540. and insert \key{goto}'s in all the places that need to execute the
  3541. branches. Put another way, we need to move away from abstract syntax
  3542. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3543. use a standard program representation called a \emph{control flow
  3544. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3545. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3546. each edge represents a jump to another block. The \key{program}
  3547. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3548. association list mapping labels to basic blocks. Each block is
  3549. represented by the $\Tail$ non-terminal.
  3550. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3551. \code{remove-complex-opera*} pass and then the
  3552. \code{explicate-control} pass on the example program. We shall walk
  3553. through the output program and then discuss the algorithm.
  3554. %
  3555. Following the order of evaluation in the output of
  3556. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3557. comparison to \code{1} from the predicate of the inner \key{if}. In
  3558. the output of \code{explicate-control}, in the \code{start} block,
  3559. this becomes a \code{(read)} followed by a conditional goto to either
  3560. \code{block61} or \code{block62}. Each of these contains the
  3561. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3562. 1)}, respectively. Regarding \code{block61}, we start with the
  3563. \code{(read)} and comparison to \code{0} and then have a conditional
  3564. goto, either to \code{block59} or \code{block60}, which indirectly
  3565. take us to \code{block55} and \code{block56}, the two branches of the
  3566. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3567. story for \code{block62} is similar.
  3568. \begin{figure}[tbp]
  3569. \begin{tabular}{lll}
  3570. \begin{minipage}{0.4\textwidth}
  3571. \begin{lstlisting}
  3572. (program ()
  3573. (if (if (eq? (read) 1)
  3574. (eq? (read) 0)
  3575. (eq? (read) 2))
  3576. (+ 10 32)
  3577. (+ 700 77)))
  3578. \end{lstlisting}
  3579. \hspace{40pt}$\Downarrow$
  3580. \begin{lstlisting}
  3581. (program ()
  3582. (if (if (let ([tmp52 (read)])
  3583. (eq? tmp52 1))
  3584. (let ([tmp53 (read)])
  3585. (eq? tmp53 0))
  3586. (let ([tmp54 (read)])
  3587. (eq? tmp54 2)))
  3588. (+ 10 32)
  3589. (+ 700 77)))
  3590. \end{lstlisting}
  3591. \end{minipage}
  3592. &
  3593. $\Rightarrow$
  3594. &
  3595. \begin{minipage}{0.55\textwidth}
  3596. \begin{lstlisting}
  3597. (program ()
  3598. ((block62 .
  3599. (seq (assign tmp54 (read))
  3600. (if (eq? tmp54 2)
  3601. (goto block59)
  3602. (goto block60))))
  3603. (block61 .
  3604. (seq (assign tmp53 (read))
  3605. (if (eq? tmp53 0)
  3606. (goto block57)
  3607. (goto block58))))
  3608. (block60 . (goto block56))
  3609. (block59 . (goto block55))
  3610. (block58 . (goto block56))
  3611. (block57 . (goto block55))
  3612. (block56 . (return (+ 700 77)))
  3613. (block55 . (return (+ 10 32)))
  3614. (start .
  3615. (seq (assign tmp52 (read))
  3616. (if (eq? tmp52 1)
  3617. (goto block61)
  3618. (goto block62))))))
  3619. \end{lstlisting}
  3620. \end{minipage}
  3621. \end{tabular}
  3622. \caption{Example translation from $R_2$ to $C_1$
  3623. via the \code{explicate-control}.}
  3624. \label{fig:explicate-control-s1-38}
  3625. \end{figure}
  3626. The nice thing about the output of \code{explicate-control} is that
  3627. there are no unnecessary uses of \code{eq?} and every use of
  3628. \code{eq?} is part of a conditional jump. The down-side of this output
  3629. is that it includes trivial blocks, such as \code{block57} through
  3630. \code{block60}, that only jump to another block. We discuss a solution
  3631. to this problem in Section~\ref{sec:opt-jumps}.
  3632. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3633. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3634. functions, \code{explicate-tail} and
  3635. \code{explicate-assign}. The former function translated
  3636. expressions in tail position whereas the later function translated
  3637. expressions on the right-hand-side of a \key{let}. With the addition
  3638. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3639. with: the predicate position of the \key{if}. So we shall need another
  3640. function, \code{explicate-pred}, that takes an $R_2$
  3641. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3642. then-branch and else-branch. The output of
  3643. \code{explicate-pred} is a $C_1$ $\Tail$. However, these
  3644. three functions also need to construct the control-flow graph, which we
  3645. recommend they do via updates to a global variable. Next we consider
  3646. the specific additions to the tail and assign functions, and some of
  3647. cases for the pred function.
  3648. The \code{explicate-tail} function needs an additional case
  3649. for \key{if}. The branches of the \key{if} inherit the current
  3650. context, so they are in tail position. Let $B_1$ be the result of
  3651. \code{explicate-tail} on the $\itm{thn}$ branch and $B_2$ be
  3652. the result of apply \code{explicate-tail} to the $\itm{else}$
  3653. branch. Then the \key{if} translates to the block $B_3$ which is the
  3654. result of applying \code{explicate-pred} to the predicate
  3655. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3656. \[
  3657. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3658. \]
  3659. Next we consider the case for \key{if} in the
  3660. \code{explicate-assign} function. So the context of the
  3661. \key{if} is an assignment to some variable $x$ and then the control
  3662. continues to some block $B_1$. The code that we generate for both the
  3663. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3664. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3665. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3666. context, so that are in assignment positions. Let $B_2$ be the result
  3667. of applying \code{explicate-assign} to the $\itm{thn}$ branch,
  3668. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3669. result of applying \code{explicate-assign} to the $\itm{else}$
  3670. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3671. \key{if} translates to the block $B_4$ which is the result of applying
  3672. \code{explicate-pred} to the predicate $\itm{cnd}$ and the
  3673. blocks $B_2$ and $B_3$.
  3674. \[
  3675. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3676. \]
  3677. The function \code{explicate-pred} will need a case for every
  3678. expression that can have type \code{Boolean}. We detail a few cases
  3679. here and leave the rest for the reader. The input to this function is
  3680. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3681. enclosing \key{if}. One of the base cases of this function is when the
  3682. expression is a less-than comparison. We translate it to a
  3683. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3684. $B_2$, so we add them to the control flow graph and obtain some labels
  3685. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3686. as follows.
  3687. \[
  3688. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3689. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3690. \]
  3691. The case for \key{if} in \code{explicate-pred} is particularly
  3692. illuminating, as it deals with the challenges that we discussed above
  3693. regarding the example of the nested \key{if} expressions. Again, we
  3694. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3695. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3696. and $\itm{els}$ of the current \key{if} inherit their context from the
  3697. current one, i.e., predicate context. So we apply
  3698. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3699. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3700. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3701. Finally, we apply \code{explicate-pred} to
  3702. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3703. to obtain the result $B_5$.
  3704. \[
  3705. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3706. \quad\Rightarrow\quad
  3707. B_5
  3708. \]
  3709. \begin{exercise}\normalfont
  3710. Implement the pass \code{explicate-code} by adding the cases for
  3711. \key{if} to the functions for tail and assignment contexts, and
  3712. implement the function for predicate contexts. Create test cases
  3713. that exercise all of the new cases in the code for this pass.
  3714. \end{exercise}
  3715. \section{Select Instructions}
  3716. \label{sec:select-r2}
  3717. Recall that the \code{select-instructions} pass lowers from our
  3718. $C$-like intermediate representation to the pseudo-x86 language, which
  3719. is suitable for conducting register allocation. The pass is
  3720. implemented using three auxiliary functions, one for each of the
  3721. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3722. For $\Arg$, we have new cases for the Booleans. We take the usual
  3723. approach of encoding them as integers, with true as 1 and false as 0.
  3724. \[
  3725. \key{\#t} \Rightarrow \key{1}
  3726. \qquad
  3727. \key{\#f} \Rightarrow \key{0}
  3728. \]
  3729. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3730. be implemented in terms of \code{xorq} as we discussed at the
  3731. beginning of this section. Given an assignment \code{(assign
  3732. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3733. the same as $\Arg$, then just the \code{xorq} suffices:
  3734. \[
  3735. (\key{assign}\; x\; (\key{not}\; x))
  3736. \quad\Rightarrow\quad
  3737. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3738. \]
  3739. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3740. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3741. $\Arg$. Then we have
  3742. \[
  3743. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3744. \quad\Rightarrow\quad
  3745. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3746. \]
  3747. Next consider the cases for \code{eq?} and less-than comparison.
  3748. Translating these operations to x86 is slightly involved due to the
  3749. unusual nature of the \key{cmpq} instruction discussed above. We
  3750. recommend translating an assignment from \code{eq?} into the following
  3751. sequence of three instructions. \\
  3752. \begin{tabular}{lll}
  3753. \begin{minipage}{0.4\textwidth}
  3754. \begin{lstlisting}
  3755. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3756. \end{lstlisting}
  3757. \end{minipage}
  3758. &
  3759. $\Rightarrow$
  3760. &
  3761. \begin{minipage}{0.4\textwidth}
  3762. \begin{lstlisting}
  3763. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3764. (set e (byte-reg al))
  3765. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3766. \end{lstlisting}
  3767. \end{minipage}
  3768. \end{tabular} \\
  3769. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3770. \key{goto} and conditional \key{goto}. Both are straightforward
  3771. to handle. A \key{goto} becomes a jump instruction.
  3772. \[
  3773. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3774. \]
  3775. A conditional \key{goto} becomes a compare instruction followed
  3776. by a conditional jump (for ``then'') and the fall-through is
  3777. to a regular jump (for ``else'').\\
  3778. \begin{tabular}{lll}
  3779. \begin{minipage}{0.4\textwidth}
  3780. \begin{lstlisting}
  3781. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3782. (goto |$\ell_1$|)
  3783. (goto |$\ell_2$|))
  3784. \end{lstlisting}
  3785. \end{minipage}
  3786. &
  3787. $\Rightarrow$
  3788. &
  3789. \begin{minipage}{0.4\textwidth}
  3790. \begin{lstlisting}
  3791. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3792. (jmp-if e |$\ell_1$|)
  3793. (jmp |$\ell_2$|))
  3794. \end{lstlisting}
  3795. \end{minipage}
  3796. \end{tabular} \\
  3797. \begin{exercise}\normalfont
  3798. Expand your \code{select-instructions} pass to handle the new features
  3799. of the $R_2$ language. Test the pass on all the examples you have
  3800. created and make sure that you have some test programs that use the
  3801. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3802. the output using the \code{interp-x86} interpreter
  3803. (Appendix~\ref{appendix:interp}).
  3804. \end{exercise}
  3805. \section{Register Allocation}
  3806. \label{sec:register-allocation-r2}
  3807. The changes required for $R_2$ affect the liveness analysis, building
  3808. the interference graph, and assigning homes, but the graph coloring
  3809. algorithm itself does not need to change.
  3810. \subsection{Liveness Analysis}
  3811. \label{sec:liveness-analysis-r2}
  3812. Recall that for $R_1$ we implemented liveness analysis for a single
  3813. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3814. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3815. now produces many basic blocks arranged in a control-flow graph. The
  3816. first question we need to consider is in what order should we process
  3817. the basic blocks? Recall that to perform liveness analysis, we need to
  3818. know the live-after set. If a basic block has no successor blocks,
  3819. then it has an empty live-after set and we can immediately apply
  3820. liveness analysis to it. If a basic block has some successors, then we
  3821. need to complete liveness analysis on those blocks first.
  3822. Furthermore, we know that the control flow graph does not contain any
  3823. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3824. were to add loops to the language, then the CFG could contain cycles
  3825. and we would instead need to use the classic worklist algorithm for
  3826. computing the fixed point of the liveness
  3827. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3828. need to process the basic blocks in reverse topological order. We
  3829. recommend using the \code{tsort} and \code{transpose} functions of the
  3830. Racket \code{graph} package to obtain this ordering.
  3831. The next question is how to compute the live-after set of a block
  3832. given the live-before sets of all its successor blocks. During
  3833. compilation we do not know which way the branch will go, so we do not
  3834. know which of the successor's live-before set to use. The solution
  3835. comes from the observation that there is no harm in identifying more
  3836. variables as live than absolutely necessary. Thus, we can take the
  3837. union of the live-before sets from all the successors to be the
  3838. live-after set for the block. Once we have computed the live-after
  3839. set, we can proceed to perform liveness analysis on the block just as
  3840. we did in Section~\ref{sec:liveness-analysis-r1}.
  3841. The helper functions for computing the variables in an instruction's
  3842. argument and for computing the variables read-from ($R$) or written-to
  3843. ($W$) by an instruction need to be updated to handle the new kinds of
  3844. arguments and instructions in x86$_1$.
  3845. \subsection{Build Interference}
  3846. \label{sec:build-interference-r2}
  3847. Many of the new instructions in x86$_1$ can be handled in the same way
  3848. as the instructions in x86$_0$. Thus, if your code was already quite
  3849. general, it will not need to be changed to handle the new
  3850. instructions. If not, I recommend that you change your code to be more
  3851. general. The \key{movzbq} instruction should be handled like the
  3852. \key{movq} instruction.
  3853. %% \subsection{Assign Homes}
  3854. %% \label{sec:assign-homes-r2}
  3855. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3856. %% to be updated to handle the \key{if} statement, simply by recursively
  3857. %% processing the child nodes. Hopefully your code already handles the
  3858. %% other new instructions, but if not, you can generalize your code.
  3859. \begin{exercise}\normalfont
  3860. Update the \code{register-allocation} pass so that it works for $R_2$
  3861. and test your compiler using your previously created programs on the
  3862. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3863. \end{exercise}
  3864. %% \section{Lower Conditionals (New Pass)}
  3865. %% \label{sec:lower-conditionals}
  3866. %% In the \code{select-instructions} pass we decided to procrastinate in
  3867. %% the lowering of the \key{if} statement, thereby making liveness
  3868. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3869. %% statement into the appropriate instruction sequence. The following
  3870. %% translation gives the general idea. If the condition is true, we need
  3871. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3872. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3873. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3874. %% is appropriate for the comparison operator \itm{cmp}. If the
  3875. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3876. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3877. %% through to the $\itm{thns}$ branch. So we jump to the
  3878. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3879. %% created with \code{gensym}.
  3880. %% \begin{tabular}{lll}
  3881. %% \begin{minipage}{0.4\textwidth}
  3882. %% \begin{lstlisting}
  3883. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3884. %% \end{lstlisting}
  3885. %% \end{minipage}
  3886. %% &
  3887. %% $\Rightarrow$
  3888. %% &
  3889. %% \begin{minipage}{0.4\textwidth}
  3890. %% \begin{lstlisting}
  3891. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3892. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3893. %% |$\itm{elss}$|
  3894. %% (jmp |$\itm{endlabel}$|)
  3895. %% (label |$\itm{thenlabel}$|)
  3896. %% |$\itm{thns}$|
  3897. %% (label |$\itm{endlabel}$|)
  3898. %% \end{lstlisting}
  3899. %% \end{minipage}
  3900. %% \end{tabular}
  3901. %% \begin{exercise}\normalfont
  3902. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3903. %% your previously created programs on the \code{interp-x86} interpreter
  3904. %% (Appendix~\ref{appendix:interp}).
  3905. %% \end{exercise}
  3906. \section{Patch Instructions}
  3907. The second argument of the \key{cmpq} instruction must not be an
  3908. immediate value (such as a literal integer). So if you are comparing
  3909. two immediates, we recommend inserting a \key{movq} instruction to put
  3910. the second argument in \key{rax}.
  3911. %
  3912. The second argument of the \key{movzbq} must be a register.
  3913. %
  3914. There are no special restrictions on the x86 instructions
  3915. \key{jmp-if}, \key{jmp}, and \key{label}.
  3916. \begin{exercise}\normalfont
  3917. Update \code{patch-instructions} to handle the new x86 instructions.
  3918. Test your compiler using your previously created programs on the
  3919. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3920. \end{exercise}
  3921. \section{An Example Translation}
  3922. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3923. $R_2$ translated to x86, showing the results of
  3924. \code{explicate-control}, \code{select-instructions}, and the final
  3925. x86 assembly code.
  3926. \begin{figure}[tbp]
  3927. \begin{tabular}{lll}
  3928. \begin{minipage}{0.5\textwidth}
  3929. % s1_20.rkt
  3930. \begin{lstlisting}
  3931. (program ()
  3932. (if (eq? (read) 1) 42 0))
  3933. \end{lstlisting}
  3934. $\Downarrow$
  3935. \begin{lstlisting}
  3936. (program ()
  3937. ((block32 . (return 0))
  3938. (block31 . (return 42))
  3939. (start .
  3940. (seq (assign tmp30 (read))
  3941. (if (eq? tmp30 1)
  3942. (goto block31)
  3943. (goto block32))))))
  3944. \end{lstlisting}
  3945. $\Downarrow$
  3946. \begin{lstlisting}
  3947. (program ((locals . (tmp30)))
  3948. ((block32 .
  3949. (block ()
  3950. (movq (int 0) (reg rax))
  3951. (jmp conclusion)))
  3952. (block31 .
  3953. (block ()
  3954. (movq (int 42) (reg rax))
  3955. (jmp conclusion)))
  3956. (start .
  3957. (block ()
  3958. (callq read_int)
  3959. (movq (reg rax) (var tmp30))
  3960. (cmpq (int 1) (var tmp30))
  3961. (jmp-if e block31)
  3962. (jmp block32)))))
  3963. \end{lstlisting}
  3964. \end{minipage}
  3965. &
  3966. $\Rightarrow$
  3967. \begin{minipage}{0.4\textwidth}
  3968. \begin{lstlisting}
  3969. _block31:
  3970. movq $42, %rax
  3971. jmp _conclusion
  3972. _block32:
  3973. movq $0, %rax
  3974. jmp _conclusion
  3975. _start:
  3976. callq _read_int
  3977. movq %rax, %rcx
  3978. cmpq $1, %rcx
  3979. je _block31
  3980. jmp _block32
  3981. .globl _main
  3982. _main:
  3983. pushq %rbp
  3984. movq %rsp, %rbp
  3985. pushq %r12
  3986. pushq %rbx
  3987. pushq %r13
  3988. pushq %r14
  3989. subq $0, %rsp
  3990. jmp _start
  3991. _conclusion:
  3992. addq $0, %rsp
  3993. popq %r14
  3994. popq %r13
  3995. popq %rbx
  3996. popq %r12
  3997. popq %rbp
  3998. retq
  3999. \end{lstlisting}
  4000. \end{minipage}
  4001. \end{tabular}
  4002. \caption{Example compilation of an \key{if} expression to x86.}
  4003. \label{fig:if-example-x86}
  4004. \end{figure}
  4005. \begin{figure}[p]
  4006. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4007. \node (R2) at (0,2) {\large $R_2$};
  4008. \node (R2-2) at (3,2) {\large $R_2$};
  4009. \node (R2-3) at (6,2) {\large $R_2$};
  4010. \node (R2-4) at (9,2) {\large $R_2$};
  4011. \node (R2-5) at (12,2) {\large $R_2$};
  4012. \node (C1-1) at (6,0) {\large $C_1$};
  4013. \node (C1-2) at (3,0) {\large $C_1$};
  4014. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4015. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4016. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4017. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4018. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4019. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4020. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4021. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4022. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4023. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4024. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4025. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4026. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4027. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4028. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4029. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4030. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4031. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4032. \end{tikzpicture}
  4033. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4034. \label{fig:R2-passes}
  4035. \end{figure}
  4036. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4037. compilation of $R_2$.
  4038. \section{Challenge: Optimize Jumps$^{*}$}
  4039. \label{sec:opt-jumps}
  4040. UNDER CONSTRUCTION
  4041. %% \section{Challenge: Optimizing Conditions$^{*}$}
  4042. %% \label{sec:opt-if}
  4043. %% A close inspection of the x86 code generated in
  4044. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  4045. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  4046. %% twice using \key{cmpq} as follows.
  4047. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  4048. %% % Does it have to do with page breaks?
  4049. %% \begin{lstlisting}
  4050. %% \end{lstlisting}
  4051. %% \begin{lstlisting}
  4052. %% cmpq $1, %rcx
  4053. %% sete %al
  4054. %% movzbq %al, %rcx
  4055. %% cmpq $1, %rcx
  4056. %% je then21288
  4057. %% \end{lstlisting}
  4058. %% The reason for this non-optimal code has to do with the \code{flatten}
  4059. %% pass earlier in this Chapter. We recommended flattening the condition
  4060. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  4061. %% is already an \code{eq?} test, then we would like to use that
  4062. %% directly. In fact, for many of the expressions of Boolean type, we can
  4063. %% generate more optimized code. For example, if the condition is
  4064. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  4065. %% all. If the condition is a \code{let}, we can optimize based on the
  4066. %% form of its body. If the condition is a \code{not}, then we can flip
  4067. %% the two branches.
  4068. %% %
  4069. %% \margincomment{\tiny We could do even better by converting to basic
  4070. %% blocks.\\ --Jeremy}
  4071. %% %
  4072. %% On the other hand, if the condition is a \code{and}
  4073. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  4074. %% code duplication.
  4075. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  4076. %% applying the above suggested optimizations.
  4077. %% \begin{exercise}\normalfont
  4078. %% Change the \code{flatten} pass to improve the code that gets
  4079. %% generated for \code{if} expressions. We recommend writing a helper
  4080. %% function that recursively traverses the condition of the \code{if}.
  4081. %% \end{exercise}
  4082. %% \begin{figure}[tbp]
  4083. %% \begin{tabular}{lll}
  4084. %% \begin{minipage}{0.5\textwidth}
  4085. %% \begin{lstlisting}
  4086. %% (program
  4087. %% (if (let ([x 1])
  4088. %% (not (eq? x (read))))
  4089. %% 777
  4090. %% 42))
  4091. %% \end{lstlisting}
  4092. %% $\Downarrow$
  4093. %% \begin{lstlisting}
  4094. %% (program (x.1 if.2 tmp.3)
  4095. %% (type Integer)
  4096. %% (assign x.1 1)
  4097. %% (assign tmp.3 (read))
  4098. %% (if (eq? x.1 tmp.3)
  4099. %% ((assign if.2 42))
  4100. %% ((assign if.2 777)))
  4101. %% (return if.2))
  4102. %% \end{lstlisting}
  4103. %% $\Downarrow$
  4104. %% \begin{lstlisting}
  4105. %% (program (x.1 if.2 tmp.3)
  4106. %% (type Integer)
  4107. %% (movq (int 1) (var x.1))
  4108. %% (callq read_int)
  4109. %% (movq (reg rax) (var tmp.3))
  4110. %% (if (eq? (var x.1) (var tmp.3))
  4111. %% ((movq (int 42) (var if.2)))
  4112. %% ((movq (int 777) (var if.2))))
  4113. %% (movq (var if.2) (reg rax)))
  4114. %% \end{lstlisting}
  4115. %% \end{minipage}
  4116. %% &
  4117. %% $\Rightarrow$
  4118. %% \begin{minipage}{0.4\textwidth}
  4119. %% \begin{lstlisting}
  4120. %% .globl _main
  4121. %% _main:
  4122. %% pushq %rbp
  4123. %% movq %rsp, %rbp
  4124. %% pushq %r13
  4125. %% pushq %r14
  4126. %% pushq %r12
  4127. %% pushq %rbx
  4128. %% subq $0, %rsp
  4129. %% movq $1, %rbx
  4130. %% callq _read_int
  4131. %% movq %rax, %rcx
  4132. %% cmpq %rcx, %rbx
  4133. %% je then35989
  4134. %% movq $777, %rbx
  4135. %% jmp if_end35990
  4136. %% then35989:
  4137. %% movq $42, %rbx
  4138. %% if_end35990:
  4139. %% movq %rbx, %rax
  4140. %% movq %rax, %rdi
  4141. %% callq _print_int
  4142. %% movq $0, %rax
  4143. %% addq $0, %rsp
  4144. %% popq %rbx
  4145. %% popq %r12
  4146. %% popq %r14
  4147. %% popq %r13
  4148. %% popq %rbp
  4149. %% retq
  4150. %% \end{lstlisting}
  4151. %% \end{minipage}
  4152. %% \end{tabular}
  4153. %% \caption{Example program with optimized conditionals.}
  4154. %% \label{fig:opt-if}
  4155. %% \end{figure}
  4156. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4157. \chapter{Tuples and Garbage Collection}
  4158. \label{ch:tuples}
  4159. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4160. things to discuss in this chapter. \\ --Jeremy}
  4161. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4162. all the IR grammars are spelled out! \\ --Jeremy}
  4163. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4164. but keep type annotations on vector creation and local variables, function
  4165. parameters, etc. \\ --Jeremy}
  4166. \margincomment{\scriptsize Be more explicit about how to deal with
  4167. the root stack. \\ --Jeremy}
  4168. In this chapter we study the implementation of mutable tuples (called
  4169. ``vectors'' in Racket). This language feature is the first to use the
  4170. computer's \emph{heap} because the lifetime of a Racket tuple is
  4171. indefinite, that is, a tuple lives forever from the programmer's
  4172. viewpoint. Of course, from an implementer's viewpoint, it is important
  4173. to reclaim the space associated with a tuple when it is no longer
  4174. needed, which is why we also study \emph{garbage collection}
  4175. techniques in this chapter.
  4176. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4177. interpreter and type checker. The $R_3$ language extends the $R_2$
  4178. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4179. ``void'' value. The reason for including the later is that the
  4180. \code{vector-set!} operation returns a value of type
  4181. \code{Void}\footnote{This may sound contradictory, but Racket's
  4182. \code{Void} type corresponds to what is more commonly called the
  4183. \code{Unit} type. This type is inhabited by a single value that is
  4184. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  4185. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4186. copying live objects back and forth between two halves of the
  4187. heap. The garbage collector requires coordination with the compiler so
  4188. that it can see all of the \emph{root} pointers, that is, pointers in
  4189. registers or on the procedure call stack.
  4190. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4191. discuss all the necessary changes and additions to the compiler
  4192. passes, including a new compiler pass named \code{expose-allocation}.
  4193. \section{The $R_3$ Language}
  4194. \label{sec:r3}
  4195. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  4196. includes three new forms for creating a tuple, reading an element of a
  4197. tuple, and writing to an element of a tuple. The program in
  4198. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4199. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  4200. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  4201. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  4202. ``then'' branch is taken. The element at index $0$ of \code{t} is
  4203. $40$, to which we add the $2$, the element at index $0$ of the
  4204. 1-tuple.
  4205. \begin{figure}[tbp]
  4206. \begin{lstlisting}
  4207. (let ([t (vector 40 #t (vector 2))])
  4208. (if (vector-ref t 1)
  4209. (+ (vector-ref t 0)
  4210. (vector-ref (vector-ref t 2) 0))
  4211. 44))
  4212. \end{lstlisting}
  4213. \caption{Example program that creates tuples and reads from them.}
  4214. \label{fig:vector-eg}
  4215. \end{figure}
  4216. \begin{figure}[tbp]
  4217. \centering
  4218. \fbox{
  4219. \begin{minipage}{0.96\textwidth}
  4220. \[
  4221. \begin{array}{lcl}
  4222. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4223. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4224. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4225. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4226. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4227. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4228. \mid (\key{and}\;\Exp\;\Exp)
  4229. \mid (\key{or}\;\Exp\;\Exp)
  4230. \mid (\key{not}\;\Exp) } \\
  4231. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4232. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4233. &\mid& (\key{vector}\;\Exp^{+})
  4234. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4235. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4236. &\mid& (\key{void}) \\
  4237. R_3 &::=& (\key{program} \; \Exp)
  4238. \end{array}
  4239. \]
  4240. \end{minipage}
  4241. }
  4242. \caption{The syntax of $R_3$, extending $R_2$
  4243. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4244. \label{fig:r3-syntax}
  4245. \end{figure}
  4246. Tuples are our first encounter with heap-allocated data, which raises
  4247. several interesting issues. First, variable binding performs a
  4248. shallow-copy when dealing with tuples, which means that different
  4249. variables can refer to the same tuple, i.e., different variables can
  4250. be \emph{aliases} for the same thing. Consider the following example
  4251. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4252. the mutation through \code{t2} is visible when referencing the tuple
  4253. from \code{t1}, so the result of this program is \code{42}.
  4254. \begin{lstlisting}
  4255. (let ([t1 (vector 3 7)])
  4256. (let ([t2 t1])
  4257. (let ([_ (vector-set! t2 0 42)])
  4258. (vector-ref t1 0))))
  4259. \end{lstlisting}
  4260. The next issue concerns the lifetime of tuples. Of course, they are
  4261. created by the \code{vector} form, but when does their lifetime end?
  4262. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4263. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4264. is not tied to any notion of static scoping. For example, the
  4265. following program returns \code{3} even though the variable \code{t}
  4266. goes out of scope prior to accessing the vector.
  4267. \begin{lstlisting}
  4268. (vector-ref
  4269. (let ([t (vector 3 7)])
  4270. t)
  4271. 0)
  4272. \end{lstlisting}
  4273. From the perspective of programmer-observable behavior, tuples live
  4274. forever. Of course, if they really lived forever, then many programs
  4275. would run out of memory.\footnote{The $R_3$ language does not have
  4276. looping or recursive function, so it is nigh impossible to write a
  4277. program in $R_3$ that will run out of memory. However, we add
  4278. recursive functions in the next Chapter!} A Racket implementation
  4279. must therefore perform automatic garbage collection.
  4280. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4281. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4282. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4283. operations in Racket. One subtle point is that the \code{vector-set!}
  4284. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4285. can be passed around just like other values inside an $R_3$ program,
  4286. but there are no operations specific to the the \code{\#<void>} value
  4287. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4288. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4289. otherwise.
  4290. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$ , which
  4291. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4292. need to know which variables are pointers into the heap, that is,
  4293. which variables are vectors. Also, when allocating a vector, we shall
  4294. need to know which elements of the vector are pointers. We can obtain
  4295. this information during type checking and when we uncover local
  4296. variables. The type checker in Figure~\ref{fig:typecheck-R3} not only
  4297. computes the type of an expression, it also wraps every sub-expression
  4298. $e$ with the form $(\key{has-type}\; e\; T)$, where $T$ is $e$'s
  4299. type. Subsequently, in the \code{uncover-locals} pass
  4300. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4301. propagated to all variables (including the temporaries generated by
  4302. \code{remove-complex-opera*}).
  4303. \begin{figure}[tbp]
  4304. \begin{lstlisting}
  4305. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4306. (define (interp-op op)
  4307. (match op
  4308. ...
  4309. ['vector vector]
  4310. ['vector-ref vector-ref]
  4311. ['vector-set! vector-set!]
  4312. [else (error 'interp-op "unknown operator")]))
  4313. (define (interp-R3 env)
  4314. (lambda (e)
  4315. (match e
  4316. ...
  4317. [else (error 'interp-R3 "unrecognized expression")]
  4318. )))
  4319. \end{lstlisting}
  4320. \caption{Interpreter for the $R_3$ language.}
  4321. \label{fig:interp-R3}
  4322. \end{figure}
  4323. \begin{figure}[tbp]
  4324. \begin{lstlisting}
  4325. (define (type-check-exp env)
  4326. (lambda (e)
  4327. (define recur (type-check-exp env))
  4328. (match e
  4329. ...
  4330. ['(void) (values '(has-type (void) Void) 'Void)]
  4331. [`(vector ,es ...)
  4332. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4333. (recur e)))
  4334. (let ([t `(Vector ,@t*)])
  4335. (debug "vector/type-check-exp finished vector" t)
  4336. (values `(has-type (vector ,@e*) ,t) t))]
  4337. [`(vector-ref ,e ,i)
  4338. (define-values (e^ t) (recur e))
  4339. (match t
  4340. [`(Vector ,ts ...)
  4341. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4342. (error 'type-check-exp "invalid index ~a" i))
  4343. (let ([t (list-ref ts i)])
  4344. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4345. t))]
  4346. [else (error "expected a vector in vector-ref, not" t)])]
  4347. [`(eq? ,arg1 ,arg2)
  4348. (define-values (e1 t1) (recur arg1))
  4349. (define-values (e2 t2) (recur arg2))
  4350. (match* (t1 t2)
  4351. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4352. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4353. [(other wise) ((super type-check-exp env) e)])]
  4354. ...
  4355. )))
  4356. \end{lstlisting}
  4357. \caption{Type checker for the $R_3$ language.}
  4358. \label{fig:typecheck-R3}
  4359. \end{figure}
  4360. \section{Garbage Collection}
  4361. \label{sec:GC}
  4362. Here we study a relatively simple algorithm for garbage collection
  4363. that is the basis of state-of-the-art garbage
  4364. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4365. particular, we describe a two-space copying
  4366. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4367. perform the
  4368. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4369. coarse-grained depiction of what happens in a two-space collector,
  4370. showing two time steps, prior to garbage collection on the top and
  4371. after garbage collection on the bottom. In a two-space collector, the
  4372. heap is divided into two parts, the FromSpace and the
  4373. ToSpace. Initially, all allocations go to the FromSpace until there is
  4374. not enough room for the next allocation request. At that point, the
  4375. garbage collector goes to work to make more room.
  4376. The garbage collector must be careful not to reclaim tuples that will
  4377. be used by the program in the future. Of course, it is impossible in
  4378. general to predict what a program will do, but we can over approximate
  4379. the will-be-used tuples by preserving all tuples that could be
  4380. accessed by \emph{any} program given the current computer state. A
  4381. program could access any tuple whose address is in a register or on
  4382. the procedure call stack. These addresses are called the \emph{root
  4383. set}. In addition, a program could access any tuple that is
  4384. transitively reachable from the root set. Thus, it is safe for the
  4385. garbage collector to reclaim the tuples that are not reachable in this
  4386. way.
  4387. So the goal of the garbage collector is twofold:
  4388. \begin{enumerate}
  4389. \item preserve all tuple that are reachable from the root set via a
  4390. path of pointers, that is, the \emph{live} tuples, and
  4391. \item reclaim the memory of everything else, that is, the
  4392. \emph{garbage}.
  4393. \end{enumerate}
  4394. A copying collector accomplishes this by copying all of the live
  4395. objects from the FromSpace into the ToSpace and then performs a slight
  4396. of hand, treating the ToSpace as the new FromSpace and the old
  4397. FromSpace as the new ToSpace. In the example of
  4398. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4399. root set, one in a register and two on the stack. All of the live
  4400. objects have been copied to the ToSpace (the right-hand side of
  4401. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4402. pointer relationships. For example, the pointer in the register still
  4403. points to a 2-tuple whose first element is a 3-tuple and second
  4404. element is a 2-tuple. There are four tuples that are not reachable
  4405. from the root set and therefore do not get copied into the ToSpace.
  4406. (The situation in Figure~\ref{fig:copying-collector}, with a
  4407. cycle, cannot be created by a well-typed program in $R_3$. However,
  4408. creating cycles will be possible once we get to $R_6$. We design
  4409. the garbage collector to deal with cycles to begin with, so we will
  4410. not need to revisit this issue.)
  4411. \begin{figure}[tbp]
  4412. \centering
  4413. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4414. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4415. \caption{A copying collector in action.}
  4416. \label{fig:copying-collector}
  4417. \end{figure}
  4418. There are many alternatives to copying collectors (and their older
  4419. siblings, the generational collectors) when its comes to garbage
  4420. collection, such as mark-and-sweep and reference counting. The
  4421. strengths of copying collectors are that allocation is fast (just a
  4422. test and pointer increment), there is no fragmentation, cyclic garbage
  4423. is collected, and the time complexity of collection only depends on
  4424. the amount of live data, and not on the amount of
  4425. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4426. copying collectors is that they use a lot of space, though that
  4427. problem is ameliorated in generational collectors. Racket and Scheme
  4428. programs tend to allocate many small objects and generate a lot of
  4429. garbage, so copying and generational collectors are a good fit. Of
  4430. course, garbage collection is an active research topic, especially
  4431. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4432. continuously developing new techniques and revisiting old
  4433. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4434. \subsection{Graph Copying via Cheney's Algorithm}
  4435. \label{sec:cheney}
  4436. Let us take a closer look at how the copy works. The allocated objects
  4437. and pointers can be viewed as a graph and we need to copy the part of
  4438. the graph that is reachable from the root set. To make sure we copy
  4439. all of the reachable vertices in the graph, we need an exhaustive
  4440. graph traversal algorithm, such as depth-first search or breadth-first
  4441. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4442. take into account the possibility of cycles by marking which vertices
  4443. have already been visited, so as to ensure termination of the
  4444. algorithm. These search algorithms also use a data structure such as a
  4445. stack or queue as a to-do list to keep track of the vertices that need
  4446. to be visited. We shall use breadth-first search and a trick due to
  4447. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4448. copying tuples into the ToSpace.
  4449. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4450. copy progresses. The queue is represented by a chunk of contiguous
  4451. memory at the beginning of the ToSpace, using two pointers to track
  4452. the front and the back of the queue. The algorithm starts by copying
  4453. all tuples that are immediately reachable from the root set into the
  4454. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4455. old tuple to indicate that it has been visited. (We discuss the
  4456. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4457. inside the copied tuples in the queue still point back to the
  4458. FromSpace. Once the initial queue has been created, the algorithm
  4459. enters a loop in which it repeatedly processes the tuple at the front
  4460. of the queue and pops it off the queue. To process a tuple, the
  4461. algorithm copies all the tuple that are directly reachable from it to
  4462. the ToSpace, placing them at the back of the queue. The algorithm then
  4463. updates the pointers in the popped tuple so they point to the newly
  4464. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4465. step we copy the tuple whose second element is $42$ to the back of the
  4466. queue. The other pointer goes to a tuple that has already been copied,
  4467. so we do not need to copy it again, but we do need to update the
  4468. pointer to the new location. This can be accomplished by storing a
  4469. \emph{forwarding} pointer to the new location in the old tuple, back
  4470. when we initially copied the tuple into the ToSpace. This completes
  4471. one step of the algorithm. The algorithm continues in this way until
  4472. the front of the queue is empty, that is, until the front catches up
  4473. with the back.
  4474. \begin{figure}[tbp]
  4475. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4476. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4477. \label{fig:cheney}
  4478. \end{figure}
  4479. \subsection{Data Representation}
  4480. \label{sec:data-rep-gc}
  4481. The garbage collector places some requirements on the data
  4482. representations used by our compiler. First, the garbage collector
  4483. needs to distinguish between pointers and other kinds of data. There
  4484. are several ways to accomplish this.
  4485. \begin{enumerate}
  4486. \item Attached a tag to each object that identifies what type of
  4487. object it is~\citep{McCarthy:1960dz}.
  4488. \item Store different types of objects in different
  4489. regions~\citep{Steele:1977ab}.
  4490. \item Use type information from the program to either generate
  4491. type-specific code for collecting or to generate tables that can
  4492. guide the
  4493. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4494. \end{enumerate}
  4495. Dynamically typed languages, such as Lisp, need to tag objects
  4496. anyways, so option 1 is a natural choice for those languages.
  4497. However, $R_3$ is a statically typed language, so it would be
  4498. unfortunate to require tags on every object, especially small and
  4499. pervasive objects like integers and Booleans. Option 3 is the
  4500. best-performing choice for statically typed languages, but comes with
  4501. a relatively high implementation complexity. To keep this chapter to a
  4502. 2-week time budget, we recommend a combination of options 1 and 2,
  4503. with separate strategies used for the stack and the heap.
  4504. Regarding the stack, we recommend using a separate stack for
  4505. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4506. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4507. local variable needs to be spilled and is of type \code{(Vector
  4508. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4509. of the normal procedure call stack. Furthermore, we always spill
  4510. vector-typed variables if they are live during a call to the
  4511. collector, thereby ensuring that no pointers are in registers during a
  4512. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4513. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4514. layout using a root stack. The root stack contains the two pointers
  4515. from the regular stack and also the pointer in the second
  4516. register.
  4517. \begin{figure}[tbp]
  4518. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4519. \caption{Maintaining a root stack to facilitate garbage collection.}
  4520. \label{fig:shadow-stack}
  4521. \end{figure}
  4522. The problem of distinguishing between pointers and other kinds of data
  4523. also arises inside of each tuple. We solve this problem by attaching a
  4524. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4525. in on the tags for two of the tuples in the example from
  4526. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4527. in a big-endian way, from right-to-left, with bit location 0 (the
  4528. least significant bit) on the far right, which corresponds to the
  4529. directional of the x86 shifting instructions \key{salq} (shift
  4530. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4531. specifying which elements of the tuple are pointers, the part labeled
  4532. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4533. a pointer and a 0 bit indicates some other kind of data. The pointer
  4534. mask starts at bit location 7. We have limited tuples to a maximum
  4535. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4536. tag also contains two other pieces of information. The length of the
  4537. tuple (number of elements) is stored in bits location 1 through
  4538. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4539. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4540. has not yet been copied. If the bit has value 0 then the entire tag
  4541. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4542. always zero anyways because our tuples are 8-byte aligned.)
  4543. \begin{figure}[tbp]
  4544. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4545. \caption{Representation for tuples in the heap.}
  4546. \label{fig:tuple-rep}
  4547. \end{figure}
  4548. \subsection{Implementation of the Garbage Collector}
  4549. \label{sec:organize-gz}
  4550. The implementation of the garbage collector needs to do a lot of
  4551. bit-level data manipulation and we need to link it with our
  4552. compiler-generated x86 code. Thus, we recommend implementing the
  4553. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4554. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4555. interface to the garbage collector. The \code{initialize} function
  4556. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4557. function is meant to be called near the beginning of \code{main},
  4558. before the rest of the program executes. The \code{initialize}
  4559. function puts the address of the beginning of the FromSpace into the
  4560. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4561. points to the address that is 1-past the last element of the
  4562. FromSpace. (We use half-open intervals to represent chunks of
  4563. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4564. points to the first element of the root stack.
  4565. As long as there is room left in the FromSpace, your generated code
  4566. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4567. %
  4568. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4569. --Jeremy}
  4570. %
  4571. The amount of room left in FromSpace is the difference between the
  4572. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4573. function should be called when there is not enough room left in the
  4574. FromSpace for the next allocation. The \code{collect} function takes
  4575. a pointer to the current top of the root stack (one past the last item
  4576. that was pushed) and the number of bytes that need to be
  4577. allocated. The \code{collect} function performs the copying collection
  4578. and leaves the heap in a state such that the next allocation will
  4579. succeed.
  4580. \begin{figure}[tbp]
  4581. \begin{lstlisting}
  4582. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4583. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4584. int64_t* free_ptr;
  4585. int64_t* fromspace_begin;
  4586. int64_t* fromspace_end;
  4587. int64_t** rootstack_begin;
  4588. \end{lstlisting}
  4589. \caption{The compiler's interface to the garbage collector.}
  4590. \label{fig:gc-header}
  4591. \end{figure}
  4592. \begin{exercise}
  4593. In the file \code{runtime.c} you will find the implementation of
  4594. \code{initialize} and a partial implementation of \code{collect}.
  4595. The \code{collect} function calls another function, \code{cheney},
  4596. to perform the actual copy, and that function is left to the reader
  4597. to implement. The following is the prototype for \code{cheney}.
  4598. \begin{lstlisting}
  4599. static void cheney(int64_t** rootstack_ptr);
  4600. \end{lstlisting}
  4601. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4602. rootstack (which is an array of pointers). The \code{cheney} function
  4603. also communicates with \code{collect} through the global
  4604. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4605. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4606. the ToSpace:
  4607. \begin{lstlisting}
  4608. static int64_t* tospace_begin;
  4609. static int64_t* tospace_end;
  4610. \end{lstlisting}
  4611. The job of the \code{cheney} function is to copy all the live
  4612. objects (reachable from the root stack) into the ToSpace, update
  4613. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4614. update the root stack so that it points to the objects in the
  4615. ToSpace, and finally to swap the global pointers for the FromSpace
  4616. and ToSpace.
  4617. \end{exercise}
  4618. %% \section{Compiler Passes}
  4619. %% \label{sec:code-generation-gc}
  4620. The introduction of garbage collection has a non-trivial impact on our
  4621. compiler passes. We introduce one new compiler pass called
  4622. \code{expose-allocation} and make non-trivial changes to
  4623. \code{type-check}, \code{flatten}, \code{select-instructions},
  4624. \code{allocate-registers}, and \code{print-x86}. The following
  4625. program will serve as our running example. It creates two tuples, one
  4626. nested inside the other. Both tuples have length one. The example then
  4627. accesses the element in the inner tuple tuple via two vector
  4628. references.
  4629. % tests/s2_17.rkt
  4630. \begin{lstlisting}
  4631. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4632. \end{lstlisting}
  4633. Next we proceed to discuss the new \code{expose-allocation} pass.
  4634. \section{Expose Allocation}
  4635. \label{sec:expose-allocation}
  4636. The pass \code{expose-allocation} lowers the \code{vector} creation
  4637. form into a conditional call to the collector followed by the
  4638. allocation. We choose to place the \code{expose-allocation} pass
  4639. before \code{flatten} because \code{expose-allocation} introduces new
  4640. variables, which can be done locally with \code{let}, but \code{let}
  4641. is gone after \code{flatten}. In the following, we show the
  4642. transformation for the \code{vector} form into let-bindings for the
  4643. initializing expressions, by a conditional \code{collect}, an
  4644. \code{allocate}, and the initialization of the vector.
  4645. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4646. total bytes need to be allocated for the vector, which is 8 for the
  4647. tag plus \itm{len} times 8.)
  4648. \begin{lstlisting}
  4649. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4650. |$\Longrightarrow$|
  4651. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4652. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4653. (global-value fromspace_end))
  4654. (void)
  4655. (collect |\itm{bytes}|))])
  4656. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4657. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4658. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4659. |$v$|) ... )))) ...)
  4660. \end{lstlisting}
  4661. (In the above, we suppressed all of the \code{has-type} forms in the
  4662. output for the sake of readability.) The placement of the initializing
  4663. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4664. the sequence of \code{vector-set!}'s is important, as those expressions
  4665. may trigger garbage collection and we do not want an allocated but
  4666. uninitialized tuple to be present during a garbage collection.
  4667. The output of \code{expose-allocation} is a language that extends
  4668. $R_3$ with the three new forms that we use above in the translation of
  4669. \code{vector}.
  4670. \[
  4671. \begin{array}{lcl}
  4672. \Exp &::=& \cdots
  4673. \mid (\key{collect} \,\itm{int})
  4674. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4675. \mid (\key{global-value} \,\itm{name})
  4676. \end{array}
  4677. \]
  4678. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4679. %% the beginning of the program which will instruct the garbage collector
  4680. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4681. %% two arguments of \code{initialize} specify the initial allocated space
  4682. %% for the root stack and for the heap.
  4683. %
  4684. %% The \code{expose-allocation} pass annotates all of the local variables
  4685. %% in the \code{program} form with their type.
  4686. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4687. \code{expose-allocation} pass on our running example.
  4688. \begin{figure}[tbp]
  4689. \begin{lstlisting}
  4690. (program ()
  4691. (vector-ref
  4692. (vector-ref
  4693. (let ((vecinit48
  4694. (let ((vecinit44 42))
  4695. (let ((collectret46
  4696. (if (<
  4697. (+ (global-value free_ptr) 16)
  4698. (global-value fromspace_end))
  4699. (void)
  4700. (collect 16))))
  4701. (let ((alloc43 (allocate 1 (Vector Integer))))
  4702. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4703. alloc43))))))
  4704. (let ((collectret50
  4705. (if (< (+ (global-value free_ptr) 16)
  4706. (global-value fromspace_end))
  4707. (void)
  4708. (collect 16))))
  4709. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4710. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4711. alloc47))))
  4712. 0)
  4713. 0))
  4714. \end{lstlisting}
  4715. \caption{Output of the \code{expose-allocation} pass, minus
  4716. all of the \code{has-type} forms.}
  4717. \label{fig:expose-alloc-output}
  4718. \end{figure}
  4719. %\clearpage
  4720. \section{Explicate Control and the $C_2$ language}
  4721. \label{sec:explicate-control-r3}
  4722. \begin{figure}[tp]
  4723. \fbox{
  4724. \begin{minipage}{0.96\textwidth}
  4725. \[
  4726. \begin{array}{lcl}
  4727. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4728. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4729. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4730. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4731. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4732. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4733. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4734. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4735. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4736. \mid (\key{collect} \,\itm{int}) \\
  4737. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4738. &\mid& \gray{(\key{goto}\,\itm{label})
  4739. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4740. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4741. \end{array}
  4742. \]
  4743. \end{minipage}
  4744. }
  4745. \caption{The $C_2$ language, extending $C_1$
  4746. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4747. \label{fig:c2-syntax}
  4748. \end{figure}
  4749. The output of \code{explicate-control} is a program in the
  4750. intermediate language $C_2$, whose syntax is defined in
  4751. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4752. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4753. \key{global-value} expressions and the \code{collect} statement. The
  4754. \code{explicate-control} pass can treat these new forms much like the
  4755. other forms.
  4756. \section{Uncover Locals}
  4757. \label{sec:uncover-locals-r3}
  4758. Recall that the \code{uncover-locals} function collects all of the
  4759. local variables so that it can store them in the $\itm{info}$ field of
  4760. the \code{program} form. Also recall that we need to know the types of
  4761. all the local variables for purposes of identifying the root set for
  4762. the garbage collector. Thus, we change \code{uncover-locals} to
  4763. collect not just the variables, but the variables and their types in
  4764. the form of an association list. Thanks to the \code{has-type} forms,
  4765. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4766. lists the output of the \code{uncover-locals} pass on the running
  4767. example.
  4768. \begin{figure}[tbp]
  4769. \begin{lstlisting}
  4770. (program
  4771. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4772. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4773. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4774. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4775. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4776. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4777. (collectret50 . Void))))
  4778. ((block63 . (seq (collect 16) (goto block61)))
  4779. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4780. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4781. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4782. (seq (assign vecinit48 alloc43)
  4783. (seq (assign tmp54 (global-value free_ptr))
  4784. (seq (assign tmp55 (+ tmp54 16))
  4785. (seq (assign tmp56 (global-value fromspace_end))
  4786. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4787. (block60 . (seq (collect 16) (goto block58)))
  4788. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4789. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4790. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4791. (seq (assign tmp57 (vector-ref alloc47 0))
  4792. (return (vector-ref tmp57 0))))))
  4793. (start . (seq (assign vecinit44 42)
  4794. (seq (assign tmp51 (global-value free_ptr))
  4795. (seq (assign tmp52 (+ tmp51 16))
  4796. (seq (assign tmp53 (global-value fromspace_end))
  4797. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4798. \end{lstlisting}
  4799. \caption{Output of \code{uncover-locals} for the running example.}
  4800. \label{fig:uncover-locals-r3}
  4801. \end{figure}
  4802. \clearpage
  4803. \section{Select Instructions}
  4804. \label{sec:select-instructions-gc}
  4805. %% void (rep as zero)
  4806. %% allocate
  4807. %% collect (callq collect)
  4808. %% vector-ref
  4809. %% vector-set!
  4810. %% global-value (postpone)
  4811. In this pass we generate x86 code for most of the new operations that
  4812. were needed to compile tuples, including \code{allocate},
  4813. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4814. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4815. The \code{vector-ref} and \code{vector-set!} forms translate into
  4816. \code{movq} instructions with the appropriate \key{deref}. (The
  4817. plus one is to get past the tag at the beginning of the tuple
  4818. representation.)
  4819. \begin{lstlisting}
  4820. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4821. |$\Longrightarrow$|
  4822. (movq |$\itm{vec}'$| (reg r11))
  4823. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4824. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4825. |$\Longrightarrow$|
  4826. (movq |$\itm{vec}'$| (reg r11))
  4827. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4828. (movq (int 0) |$\itm{lhs}$|)
  4829. \end{lstlisting}
  4830. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4831. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4832. register \code{r11} ensures that offsets are only performed with
  4833. register operands. This requires removing \code{r11} from
  4834. consideration by the register allocating.
  4835. We compile the \code{allocate} form to operations on the
  4836. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4837. is the next free address in the FromSpace, so we move it into the
  4838. \itm{lhs} and then move it forward by enough space for the tuple being
  4839. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4840. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4841. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4842. how the tag is organized. We recommend using the Racket operations
  4843. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4844. The type annotation in the \code{vector} form is used to determine the
  4845. pointer mask region of the tag.
  4846. \begin{lstlisting}
  4847. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4848. |$\Longrightarrow$|
  4849. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4850. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4851. (movq |$\itm{lhs}'$| (reg r11))
  4852. (movq (int |$\itm{tag}$|) (deref r11 0))
  4853. \end{lstlisting}
  4854. The \code{collect} form is compiled to a call to the \code{collect}
  4855. function in the runtime. The arguments to \code{collect} are the top
  4856. of the root stack and the number of bytes that need to be allocated.
  4857. We shall use a dedicated register, \code{r15}, to store the pointer to
  4858. the top of the root stack. So \code{r15} is not available for use by
  4859. the register allocator.
  4860. \begin{lstlisting}
  4861. (collect |$\itm{bytes}$|)
  4862. |$\Longrightarrow$|
  4863. (movq (reg r15) (reg rdi))
  4864. (movq |\itm{bytes}| (reg rsi))
  4865. (callq collect)
  4866. \end{lstlisting}
  4867. \begin{figure}[tp]
  4868. \fbox{
  4869. \begin{minipage}{0.96\textwidth}
  4870. \[
  4871. \begin{array}{lcl}
  4872. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4873. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4874. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4875. \mid (\key{global-value}\; \itm{name}) \\
  4876. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4877. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4878. (\key{subq} \; \Arg\; \Arg) \mid
  4879. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4880. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4881. (\key{pushq}\;\Arg) \mid
  4882. (\key{popq}\;\Arg) \mid
  4883. (\key{retq})} \\
  4884. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4885. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4886. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4887. \mid (\key{jmp} \; \itm{label})
  4888. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4889. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4890. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4891. \end{array}
  4892. \]
  4893. \end{minipage}
  4894. }
  4895. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4896. \label{fig:x86-2}
  4897. \end{figure}
  4898. The syntax of the $x86_2$ language is defined in
  4899. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4900. of the form for global variables.
  4901. %
  4902. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4903. \code{select-instructions} pass on the running example.
  4904. \begin{figure}[tbp]
  4905. \centering
  4906. \begin{minipage}{0.75\textwidth}
  4907. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4908. (program
  4909. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4910. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4911. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4912. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4913. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4914. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4915. ((block63 . (block ()
  4916. (movq (reg r15) (reg rdi))
  4917. (movq (int 16) (reg rsi))
  4918. (callq collect)
  4919. (jmp block61)))
  4920. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4921. (block61 . (block ()
  4922. (movq (global-value free_ptr) (var alloc43))
  4923. (addq (int 16) (global-value free_ptr))
  4924. (movq (var alloc43) (reg r11))
  4925. (movq (int 3) (deref r11 0))
  4926. (movq (var alloc43) (reg r11))
  4927. (movq (var vecinit44) (deref r11 8))
  4928. (movq (int 0) (var initret45))
  4929. (movq (var alloc43) (var vecinit48))
  4930. (movq (global-value free_ptr) (var tmp54))
  4931. (movq (var tmp54) (var tmp55))
  4932. (addq (int 16) (var tmp55))
  4933. (movq (global-value fromspace_end) (var tmp56))
  4934. (cmpq (var tmp56) (var tmp55))
  4935. (jmp-if l block59)
  4936. (jmp block60)))
  4937. (block60 . (block ()
  4938. (movq (reg r15) (reg rdi))
  4939. (movq (int 16) (reg rsi))
  4940. (callq collect)
  4941. (jmp block58))
  4942. (block59 . (block ()
  4943. (movq (int 0) (var collectret50))
  4944. (jmp block58)))
  4945. (block58 . (block ()
  4946. (movq (global-value free_ptr) (var alloc47))
  4947. (addq (int 16) (global-value free_ptr))
  4948. (movq (var alloc47) (reg r11))
  4949. (movq (int 131) (deref r11 0))
  4950. (movq (var alloc47) (reg r11))
  4951. (movq (var vecinit48) (deref r11 8))
  4952. (movq (int 0) (var initret49))
  4953. (movq (var alloc47) (reg r11))
  4954. (movq (deref r11 8) (var tmp57))
  4955. (movq (var tmp57) (reg r11))
  4956. (movq (deref r11 8) (reg rax))
  4957. (jmp conclusion)))
  4958. (start . (block ()
  4959. (movq (int 42) (var vecinit44))
  4960. (movq (global-value free_ptr) (var tmp51))
  4961. (movq (var tmp51) (var tmp52))
  4962. (addq (int 16) (var tmp52))
  4963. (movq (global-value fromspace_end) (var tmp53))
  4964. (cmpq (var tmp53) (var tmp52))
  4965. (jmp-if l block62)
  4966. (jmp block63))))))
  4967. \end{lstlisting}
  4968. \end{minipage}
  4969. \caption{Output of the \code{select-instructions} pass.}
  4970. \label{fig:select-instr-output-gc}
  4971. \end{figure}
  4972. \clearpage
  4973. \section{Register Allocation}
  4974. \label{sec:reg-alloc-gc}
  4975. As discussed earlier in this chapter, the garbage collector needs to
  4976. access all the pointers in the root set, that is, all variables that
  4977. are vectors. It will be the responsibility of the register allocator
  4978. to make sure that:
  4979. \begin{enumerate}
  4980. \item the root stack is used for spilling vector-typed variables, and
  4981. \item if a vector-typed variable is live during a call to the
  4982. collector, it must be spilled to ensure it is visible to the
  4983. collector.
  4984. \end{enumerate}
  4985. The later responsibility can be handled during construction of the
  4986. inference graph, by adding interference edges between the call-live
  4987. vector-typed variables and all the callee-saved registers. (They
  4988. already interfere with the caller-saved registers.) The type
  4989. information for variables is in the \code{program} form, so we
  4990. recommend adding another parameter to the \code{build-interference}
  4991. function to communicate this association list.
  4992. The spilling of vector-typed variables to the root stack can be
  4993. handled after graph coloring, when choosing how to assign the colors
  4994. (integers) to registers and stack locations. The \code{program} output
  4995. of this pass changes to also record the number of spills to the root
  4996. stack.
  4997. % build-interference
  4998. %
  4999. % callq
  5000. % extra parameter for var->type assoc. list
  5001. % update 'program' and 'if'
  5002. % allocate-registers
  5003. % allocate spilled vectors to the rootstack
  5004. % don't change color-graph
  5005. \section{Print x86}
  5006. \label{sec:print-x86-gc}
  5007. \margincomment{\scriptsize We need to show the translation to x86 and what
  5008. to do about global-value. \\ --Jeremy}
  5009. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5010. \code{print-x86} pass on the running example. In the prelude and
  5011. conclusion of the \code{main} function, we treat the root stack very
  5012. much like the regular stack in that we move the root stack pointer
  5013. (\code{r15}) to make room for all of the spills to the root stack,
  5014. except that the root stack grows up instead of down. For the running
  5015. example, there was just one spill so we increment \code{r15} by 8
  5016. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5017. One issue that deserves special care is that there may be a call to
  5018. \code{collect} prior to the initializing assignments for all the
  5019. variables in the root stack. We do not want the garbage collector to
  5020. accidentally think that some uninitialized variable is a pointer that
  5021. needs to be followed. Thus, we zero-out all locations on the root
  5022. stack in the prelude of \code{main}. In
  5023. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5024. %
  5025. \lstinline{movq $0, (%r15)}
  5026. %
  5027. accomplishes this task. The garbage collector tests each root to see
  5028. if it is null prior to dereferencing it.
  5029. \begin{figure}[htbp]
  5030. \begin{minipage}[t]{0.5\textwidth}
  5031. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5032. _block58:
  5033. movq _free_ptr(%rip), %rcx
  5034. addq $16, _free_ptr(%rip)
  5035. movq %rcx, %r11
  5036. movq $131, 0(%r11)
  5037. movq %rcx, %r11
  5038. movq -8(%r15), %rax
  5039. movq %rax, 8(%r11)
  5040. movq $0, %rdx
  5041. movq %rcx, %r11
  5042. movq 8(%r11), %rcx
  5043. movq %rcx, %r11
  5044. movq 8(%r11), %rax
  5045. jmp _conclusion
  5046. _block59:
  5047. movq $0, %rcx
  5048. jmp _block58
  5049. _block62:
  5050. movq $0, %rcx
  5051. jmp _block61
  5052. _block60:
  5053. movq %r15, %rdi
  5054. movq $16, %rsi
  5055. callq _collect
  5056. jmp _block58
  5057. _block63:
  5058. movq %r15, %rdi
  5059. movq $16, %rsi
  5060. callq _collect
  5061. jmp _block61
  5062. _start:
  5063. movq $42, %rbx
  5064. movq _free_ptr(%rip), %rdx
  5065. addq $16, %rdx
  5066. movq _fromspace_end(%rip), %rcx
  5067. cmpq %rcx, %rdx
  5068. jl _block62
  5069. jmp _block63
  5070. \end{lstlisting}
  5071. \end{minipage}
  5072. \begin{minipage}[t]{0.45\textwidth}
  5073. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5074. _block61:
  5075. movq _free_ptr(%rip), %rcx
  5076. addq $16, _free_ptr(%rip)
  5077. movq %rcx, %r11
  5078. movq $3, 0(%r11)
  5079. movq %rcx, %r11
  5080. movq %rbx, 8(%r11)
  5081. movq $0, %rdx
  5082. movq %rcx, -8(%r15)
  5083. movq _free_ptr(%rip), %rcx
  5084. addq $16, %rcx
  5085. movq _fromspace_end(%rip), %rdx
  5086. cmpq %rdx, %rcx
  5087. jl _block59
  5088. jmp _block60
  5089. .globl _main
  5090. _main:
  5091. pushq %rbp
  5092. movq %rsp, %rbp
  5093. pushq %r12
  5094. pushq %rbx
  5095. pushq %r13
  5096. pushq %r14
  5097. subq $0, %rsp
  5098. movq $16384, %rdi
  5099. movq $16, %rsi
  5100. callq _initialize
  5101. movq _rootstack_begin(%rip), %r15
  5102. movq $0, (%r15)
  5103. addq $8, %r15
  5104. jmp _start
  5105. _conclusion:
  5106. subq $8, %r15
  5107. addq $0, %rsp
  5108. popq %r14
  5109. popq %r13
  5110. popq %rbx
  5111. popq %r12
  5112. popq %rbp
  5113. retq
  5114. \end{lstlisting}
  5115. \end{minipage}
  5116. \caption{Output of the \code{print-x86} pass.}
  5117. \label{fig:print-x86-output-gc}
  5118. \end{figure}
  5119. \margincomment{\scriptsize Suggest an implementation strategy
  5120. in which the students first do the code gen and test that
  5121. without GC (just use a big heap), then after that is debugged,
  5122. implement the GC. \\ --Jeremy}
  5123. \begin{figure}[p]
  5124. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5125. \node (R3) at (0,2) {\large $R_3$};
  5126. \node (R3-2) at (3,2) {\large $R_3$};
  5127. \node (R3-3) at (6,2) {\large $R_3$};
  5128. \node (R3-4) at (9,2) {\large $R_3$};
  5129. \node (R3-5) at (12,2) {\large $R_3$};
  5130. \node (C2-4) at (3,0) {\large $C_2$};
  5131. \node (C2-3) at (6,0) {\large $C_2$};
  5132. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5133. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5134. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5135. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5136. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5137. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5138. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5139. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5140. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5141. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5142. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5143. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5144. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5145. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5146. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5147. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5148. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5149. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5150. \end{tikzpicture}
  5151. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5152. \label{fig:R3-passes}
  5153. \end{figure}
  5154. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5155. for the compilation of $R_3$.
  5156. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5157. \chapter{Functions}
  5158. \label{ch:functions}
  5159. This chapter studies the compilation of functions at the level of
  5160. abstraction of the C language. This corresponds to a subset of Typed
  5161. Racket in which only top-level function definitions are allowed. These
  5162. kind of functions are an important stepping stone to implementing
  5163. lexically-scoped functions in the form of \key{lambda} abstractions,
  5164. which is the topic of Chapter~\ref{ch:lambdas}.
  5165. \section{The $R_4$ Language}
  5166. The syntax for function definitions and function application is shown
  5167. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5168. Programs in $R_4$ start with zero or more function definitions. The
  5169. function names from these definitions are in-scope for the entire
  5170. program, including all other function definitions (so the ordering of
  5171. function definitions does not matter). The syntax for function
  5172. application does not include an explicit keyword, which is error prone
  5173. when using \code{match}. To alleviate this problem, we change the
  5174. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5175. during type checking.
  5176. Functions are first-class in the sense that a function pointer is data
  5177. and can be stored in memory or passed as a parameter to another
  5178. function. Thus, we introduce a function type, written
  5179. \begin{lstlisting}
  5180. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5181. \end{lstlisting}
  5182. for a function whose $n$ parameters have the types $\Type_1$ through
  5183. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5184. these functions (with respect to Racket functions) is that they are
  5185. not lexically scoped. That is, the only external entities that can be
  5186. referenced from inside a function body are other globally-defined
  5187. functions. The syntax of $R_4$ prevents functions from being nested
  5188. inside each other.
  5189. \begin{figure}[tp]
  5190. \centering
  5191. \fbox{
  5192. \begin{minipage}{0.96\textwidth}
  5193. \[
  5194. \begin{array}{lcl}
  5195. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5196. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5197. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5198. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5199. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5200. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5201. \mid (\key{and}\;\Exp\;\Exp)
  5202. \mid (\key{or}\;\Exp\;\Exp)
  5203. \mid (\key{not}\;\Exp)} \\
  5204. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5205. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5206. (\key{vector-ref}\;\Exp\;\Int)} \\
  5207. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5208. &\mid& (\Exp \; \Exp^{*}) \\
  5209. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5210. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5211. \end{array}
  5212. \]
  5213. \end{minipage}
  5214. }
  5215. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5216. with functions.}
  5217. \label{fig:r4-syntax}
  5218. \end{figure}
  5219. The program in Figure~\ref{fig:r4-function-example} is a
  5220. representative example of defining and using functions in $R_4$. We
  5221. define a function \code{map-vec} that applies some other function
  5222. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5223. vector containing the results. We also define a function \code{add1}
  5224. that does what its name suggests. The program then applies
  5225. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5226. \code{(vector 1 42)}, from which we return the \code{42}.
  5227. \begin{figure}[tbp]
  5228. \begin{lstlisting}
  5229. (program ()
  5230. (define (map-vec [f : (Integer -> Integer)]
  5231. [v : (Vector Integer Integer)])
  5232. : (Vector Integer Integer)
  5233. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5234. (define (add1 [x : Integer]) : Integer
  5235. (+ x 1))
  5236. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5237. )
  5238. \end{lstlisting}
  5239. \caption{Example of using functions in $R_4$.}
  5240. \label{fig:r4-function-example}
  5241. \end{figure}
  5242. The definitional interpreter for $R_4$ is in
  5243. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5244. responsible for setting up the mutual recursion between the top-level
  5245. function definitions. We use the classic back-patching approach that
  5246. uses mutable variables and makes two passes over the function
  5247. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5248. top-level environment using a mutable cons cell for each function
  5249. definition. Note that the \code{lambda} value for each function is
  5250. incomplete; it does not yet include the environment. Once the
  5251. top-level environment is constructed, we then iterate over it and
  5252. update the \code{lambda} value's to use the top-level environment.
  5253. \begin{figure}[tp]
  5254. \begin{lstlisting}
  5255. (define (interp-exp env)
  5256. (lambda (e)
  5257. (define recur (interp-exp env))
  5258. (match e
  5259. ...
  5260. [`(,fun ,args ...)
  5261. (define arg-vals (for/list ([e args]) (recur e)))
  5262. (define fun-val (recur fun))
  5263. (match fun-val
  5264. [`(lambda (,xs ...) ,body ,fun-env)
  5265. (define new-env (append (map cons xs arg-vals) fun-env))
  5266. ((interp-exp new-env) body)]
  5267. [else (error "interp-exp, expected function, not" fun-val)])]
  5268. [else (error 'interp-exp "unrecognized expression")]
  5269. )))
  5270. (define (interp-def d)
  5271. (match d
  5272. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5273. (mcons f `(lambda ,xs ,body ()))]
  5274. ))
  5275. (define (interp-R4 p)
  5276. (match p
  5277. [`(program ,ds ... ,body)
  5278. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5279. (for/list ([b top-level])
  5280. (set-mcdr! b (match (mcdr b)
  5281. [`(lambda ,xs ,body ())
  5282. `(lambda ,xs ,body ,top-level)])))
  5283. ((interp-exp top-level) body))]
  5284. ))
  5285. \end{lstlisting}
  5286. \caption{Interpreter for the $R_4$ language.}
  5287. \label{fig:interp-R4}
  5288. \end{figure}
  5289. \section{Functions in x86}
  5290. \label{sec:fun-x86}
  5291. \margincomment{\tiny Make sure callee-saved registers are discussed
  5292. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5293. \margincomment{\tiny Talk about the return address on the
  5294. stack and what callq and retq does.\\ --Jeremy }
  5295. The x86 architecture provides a few features to support the
  5296. implementation of functions. We have already seen that x86 provides
  5297. labels so that one can refer to the location of an instruction, as is
  5298. needed for jump instructions. Labels can also be used to mark the
  5299. beginning of the instructions for a function. Going further, we can
  5300. obtain the address of a label by using the \key{leaq} instruction and
  5301. \key{rip}-relative addressing. For example, the following puts the
  5302. address of the \code{add1} label into the \code{rbx} register.
  5303. \begin{lstlisting}
  5304. leaq add1(%rip), %rbx
  5305. \end{lstlisting}
  5306. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5307. instruction for jumping to a function whose location is given by a
  5308. label. Here we instead will be jumping to a function whose location is
  5309. given by an address, that is, we need to make an \emph{indirect
  5310. function call}. The x86 syntax is to give the register name prefixed
  5311. with an asterisk.
  5312. \begin{lstlisting}
  5313. callq *%rbx
  5314. \end{lstlisting}
  5315. \subsection{Calling Conventions}
  5316. The \code{callq} instruction provides partial support for implementing
  5317. functions, but it does not handle (1) parameter passing, (2) saving
  5318. and restoring frames on the procedure call stack, or (3) determining
  5319. how registers are shared by different functions. These issues require
  5320. coordination between the caller and the callee, which is often
  5321. assembly code written by different programmers or generated by
  5322. different compilers. As a result, people have developed
  5323. \emph{conventions} that govern how functions calls are performed.
  5324. Here we shall use the same conventions used by the \code{gcc}
  5325. compiler~\citep{Matz:2013aa}.
  5326. Regarding (1) parameter passing, the convention is to use the
  5327. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5328. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5329. than six arguments, then the convention is to use space on the frame
  5330. of the caller for the rest of the arguments. However, to ease the
  5331. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5332. we shall arrange to never have more than six arguments.
  5333. %
  5334. The register \code{rax} is for the return value of the function.
  5335. Regarding (2) frames and the procedure call stack, the convention is
  5336. that the stack grows down, with each function call using a chunk of
  5337. space called a frame. The caller sets the stack pointer, register
  5338. \code{rsp}, to the last data item in its frame. The callee must not
  5339. change anything in the caller's frame, that is, anything that is at or
  5340. above the stack pointer. The callee is free to use locations that are
  5341. below the stack pointer.
  5342. Regarding (3) the sharing of registers between different functions,
  5343. recall from Section~\ref{sec:calling-conventions} that the registers
  5344. are divided into two groups, the caller-saved registers and the
  5345. callee-saved registers. The caller should assume that all the
  5346. caller-saved registers get overwritten with arbitrary values by the
  5347. callee. Thus, the caller should either 1) not put values that are live
  5348. across a call in caller-saved registers, or 2) save and restore values
  5349. that are live across calls. We shall recommend option 1). On the flip
  5350. side, if the callee wants to use a callee-saved register, the callee
  5351. must save the contents of those registers on their stack frame and
  5352. then put them back prior to returning to the caller. The base
  5353. pointer, register \code{rbp}, is used as a point-of-reference within a
  5354. frame, so that each local variable can be accessed at a fixed offset
  5355. from the base pointer.
  5356. %
  5357. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5358. frames.
  5359. %% If we were to use stack arguments, they would be between the
  5360. %% caller locals and the callee return address.
  5361. \begin{figure}[tbp]
  5362. \centering
  5363. \begin{tabular}{r|r|l|l} \hline
  5364. Caller View & Callee View & Contents & Frame \\ \hline
  5365. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5366. 0(\key{\%rbp}) & & old \key{rbp} \\
  5367. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5368. \ldots & & \ldots \\
  5369. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5370. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5371. \ldots & & \ldots \\
  5372. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5373. %% & & \\
  5374. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5375. %% & \ldots & \ldots \\
  5376. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5377. \hline
  5378. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5379. & 0(\key{\%rbp}) & old \key{rbp} \\
  5380. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5381. & \ldots & \ldots \\
  5382. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5383. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5384. & \ldots & \ldots \\
  5385. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5386. \end{tabular}
  5387. \caption{Memory layout of caller and callee frames.}
  5388. \label{fig:call-frames}
  5389. \end{figure}
  5390. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5391. %% local variables and for storing the values of callee-saved registers
  5392. %% (we shall refer to all of these collectively as ``locals''), and that
  5393. %% at the beginning of a function we move the stack pointer \code{rsp}
  5394. %% down to make room for them.
  5395. %% We recommend storing the local variables
  5396. %% first and then the callee-saved registers, so that the local variables
  5397. %% can be accessed using \code{rbp} the same as before the addition of
  5398. %% functions.
  5399. %% To make additional room for passing arguments, we shall
  5400. %% move the stack pointer even further down. We count how many stack
  5401. %% arguments are needed for each function call that occurs inside the
  5402. %% body of the function and find their maximum. Adding this number to the
  5403. %% number of locals gives us how much the \code{rsp} should be moved at
  5404. %% the beginning of the function. In preparation for a function call, we
  5405. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5406. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5407. %% so on.
  5408. %% Upon calling the function, the stack arguments are retrieved by the
  5409. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5410. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5411. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5412. %% the layout of the caller and callee frames. Notice how important it is
  5413. %% that we correctly compute the maximum number of arguments needed for
  5414. %% function calls; if that number is too small then the arguments and
  5415. %% local variables will smash into each other!
  5416. \subsection{Efficient Tail Calls}
  5417. \label{sec:tail-call}
  5418. In general, the amount of stack space used by a program is determined
  5419. by the longest chain of nested function calls. That is, if function
  5420. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5421. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5422. $n$ can grow quite large in the case of recursive or mutually
  5423. recursive functions. However, in some cases we can arrange to use only
  5424. constant space, i.e. $O(1)$, instead of $O(n)$.
  5425. If a function call is the last action in a function body, then that
  5426. call is said to be a \emph{tail call}. In such situations, the frame
  5427. of the caller is no longer needed, so we can pop the caller's frame
  5428. before making the tail call. With this approach, a recursive function
  5429. that only makes tail calls will only use $O(1)$ stack space.
  5430. Functional languages like Racket typically rely heavily on recursive
  5431. functions, so they typically guarantee that all tail calls will be
  5432. optimized in this way.
  5433. However, some care is needed with regards to argument passing in tail
  5434. calls. As mentioned above, for arguments beyond the sixth, the
  5435. convention is to use space in the caller's frame for passing
  5436. arguments. But here we've popped the caller's frame and can no longer
  5437. use it. Another alternative is to use space in the callee's frame for
  5438. passing arguments. However, this option is also problematic because
  5439. the caller and callee's frame overlap in memory. As we begin to copy
  5440. the arguments from their sources in the caller's frame, the target
  5441. locations in the callee's frame might overlap with the sources for
  5442. later arguments! We solve this problem by not using the stack for
  5443. parameter passing but instead use the heap, as we describe in the
  5444. Section~\ref{sec:limit-functions-r4}.
  5445. As mentioned above, for a tail call we pop the caller's frame prior to
  5446. making the tail call. The instructions for popping a frame are the
  5447. instructions that we usually place in the conclusion of a
  5448. function. Thus, we also need to place such code immediately before
  5449. each tail call. These instructions include restoring the callee-saved
  5450. registers, so it is good that the argument passing registers are all
  5451. caller-saved registers.
  5452. One last note regarding which instruction to use to make the tail
  5453. call. When the callee is finished, it should not return to the current
  5454. function, but it should return to the function that called the current
  5455. one. Thus, the return address that is already on the stack is the
  5456. right one, and we should not use \key{callq} to make the tail call, as
  5457. that would unnecessarily overwrite the return address. Instead we can
  5458. simply use the \key{jmp} instruction. Like the indirect function call,
  5459. we write an indirect jump with a register prefixed with an asterisk.
  5460. We recommend using \code{rax} to hold the jump target because the
  5461. preceding ``conclusion'' overwrites just about everything else.
  5462. \begin{lstlisting}
  5463. jmp *%rax
  5464. \end{lstlisting}
  5465. %% Now that we have a good understanding of functions as they appear in
  5466. %% $R_4$ and the support for functions in x86, we need to plan the
  5467. %% changes to our compiler, that is, do we need any new passes and/or do
  5468. %% we need to change any existing passes? Also, do we need to add new
  5469. %% kinds of AST nodes to any of the intermediate languages?
  5470. \section{Shrink $R_4$}
  5471. \label{sec:shrink-r4}
  5472. The \code{shrink} pass performs a couple minor modifications to the
  5473. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5474. field to each function definition:
  5475. \begin{lstlisting}
  5476. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5477. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5478. \end{lstlisting}
  5479. and introduces an explicit \code{main} function.\\
  5480. \begin{tabular}{lll}
  5481. \begin{minipage}{0.45\textwidth}
  5482. \begin{lstlisting}
  5483. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5484. \end{lstlisting}
  5485. \end{minipage}
  5486. &
  5487. $\Rightarrow$
  5488. &
  5489. \begin{minipage}{0.45\textwidth}
  5490. \begin{lstlisting}
  5491. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5492. \end{lstlisting}
  5493. \end{minipage}
  5494. \end{tabular} \\
  5495. where $\itm{mainDef}$ is
  5496. \begin{lstlisting}
  5497. (define (main) : Integer () |$\Exp'$|)
  5498. \end{lstlisting}
  5499. \section{Reveal Functions}
  5500. \label{sec:reveal-functions-r4}
  5501. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5502. compilation because it conflates the use of function names and local
  5503. variables. This is a problem because we need to compile the use of a
  5504. function name differently than the use of a local variable; we need to
  5505. use \code{leaq} to convert the function name (a label in x86) to an
  5506. address in a register. Thus, it is a good idea to create a new pass
  5507. that changes function references from just a symbol $f$ to
  5508. \code{(fun-ref $f$)}. A good name for this pass is
  5509. \code{reveal-functions} and the output language, $F_1$, is defined in
  5510. Figure~\ref{fig:f1-syntax}.
  5511. \begin{figure}[tp]
  5512. \centering
  5513. \fbox{
  5514. \begin{minipage}{0.96\textwidth}
  5515. \[
  5516. \begin{array}{lcl}
  5517. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5518. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5519. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5520. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5521. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5522. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5523. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5524. (\key{vector-ref}\;\Exp\;\Int)} \\
  5525. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5526. (\key{app}\; \Exp \; \Exp^{*})} \\
  5527. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5528. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5529. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5530. \end{array}
  5531. \]
  5532. \end{minipage}
  5533. }
  5534. \caption{The $F_1$ language, an extension of $R_4$
  5535. (Figure~\ref{fig:r4-syntax}).}
  5536. \label{fig:f1-syntax}
  5537. \end{figure}
  5538. %% Distinguishing between calls in tail position and non-tail position
  5539. %% requires the pass to have some notion of context. We recommend using
  5540. %% two mutually recursive functions, one for processing expressions in
  5541. %% tail position and another for the rest.
  5542. Placing this pass after \code{uniquify} is a good idea, because it
  5543. will make sure that there are no local variables and functions that
  5544. share the same name. On the other hand, \code{reveal-functions} needs
  5545. to come before the \code{explicate-control} pass because that pass
  5546. will help us compile \code{fun-ref} into assignment statements.
  5547. \section{Limit Functions}
  5548. \label{sec:limit-functions-r4}
  5549. This pass transforms functions so that they have at most six
  5550. parameters and transforms all function calls so that they pass at most
  5551. six arguments. A simple strategy for imposing an argument limit of
  5552. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5553. into a vector, making that subsequent vector the $n$th argument.
  5554. \begin{tabular}{lll}
  5555. \begin{minipage}{0.2\textwidth}
  5556. \begin{lstlisting}
  5557. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5558. \end{lstlisting}
  5559. \end{minipage}
  5560. &
  5561. $\Rightarrow$
  5562. &
  5563. \begin{minipage}{0.4\textwidth}
  5564. \begin{lstlisting}
  5565. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5566. \end{lstlisting}
  5567. \end{minipage}
  5568. \end{tabular}
  5569. In the body of the function, all occurrences of the $i$th argument in
  5570. which $i>5$ must be replaced with a \code{vector-ref}.
  5571. \section{Remove Complex Operators and Operands}
  5572. \label{sec:rco-r4}
  5573. The primary decisions to make for this pass is whether to classify
  5574. \code{fun-ref} and \code{app} as either simple or complex
  5575. expressions. Recall that a simple expression will eventually end up as
  5576. just an ``immediate'' argument of an x86 instruction. Function
  5577. application will be translated to a sequence of instructions, so
  5578. \code{app} must be classified as complex expression. Regarding
  5579. \code{fun-ref}, as discussed above, the function label needs to
  5580. be converted to an address using the \code{leaq} instruction. Thus,
  5581. even though \code{fun-ref} seems rather simple, it needs to be
  5582. classified as a complex expression so that we generate an assignment
  5583. statement with a left-hand side that can serve as the target of the
  5584. \code{leaq}.
  5585. \section{Explicate Control and the $C_3$ language}
  5586. \label{sec:explicate-control-r4}
  5587. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5588. \key{explicate-control}. The three mutually recursive functions for
  5589. this pass, for assignment, tail, and predicate contexts, must all be
  5590. updated with cases for \code{fun-ref} and \code{app}. In
  5591. assignment and predicate contexts, \code{app} becomes \code{call},
  5592. whereas in tail position \code{app} becomes \code{tailcall}. We
  5593. recommend defining a new function for processing function definitions.
  5594. This code is similar to the case for \code{program} in $R_3$. The
  5595. top-level \code{explicate-control} function that handles the
  5596. \code{program} form of $R_4$ can then apply this new function to all
  5597. the function definitions.
  5598. \begin{figure}[tp]
  5599. \fbox{
  5600. \begin{minipage}{0.96\textwidth}
  5601. \[
  5602. \begin{array}{lcl}
  5603. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5604. \\
  5605. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5606. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5607. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5608. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5609. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5610. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5611. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5612. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5613. \mid (\key{collect} \,\itm{int}) }\\
  5614. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5615. &\mid& \gray{(\key{goto}\,\itm{label})
  5616. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5617. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5618. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5619. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5620. \end{array}
  5621. \]
  5622. \end{minipage}
  5623. }
  5624. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5625. \label{fig:c3-syntax}
  5626. \end{figure}
  5627. \section{Uncover Locals}
  5628. \label{sec:uncover-locals-r4}
  5629. The function for processing $\Tail$ should be updated with a case for
  5630. \code{tailcall}. We also recommend creating a new function for
  5631. processing function definitions. Each function definition in $C_3$ has
  5632. its own set of local variables, so the code for function definitions
  5633. should be similar to the case for the \code{program} form in $C_2$.
  5634. \section{Select Instructions}
  5635. \label{sec:select-r4}
  5636. The output of select instructions is a program in the x86$_3$
  5637. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5638. \begin{figure}[tp]
  5639. \fbox{
  5640. \begin{minipage}{0.96\textwidth}
  5641. \[
  5642. \begin{array}{lcl}
  5643. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5644. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5645. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5646. \mid (\key{global-value}\; \itm{name}) } \\
  5647. &\mid& (\key{fun-ref}\; \itm{label})\\
  5648. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5649. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5650. (\key{subq} \; \Arg\; \Arg) \mid
  5651. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5652. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5653. (\key{pushq}\;\Arg) \mid
  5654. (\key{popq}\;\Arg) \mid
  5655. (\key{retq}) } \\
  5656. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5657. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5658. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5659. \mid (\key{jmp} \; \itm{label})
  5660. \mid (\key{j}\itm{cc} \; \itm{label})
  5661. \mid (\key{label} \; \itm{label}) } \\
  5662. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5663. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5664. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5665. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5666. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5667. \end{array}
  5668. \]
  5669. \end{minipage}
  5670. }
  5671. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5672. \label{fig:x86-3}
  5673. \end{figure}
  5674. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5675. as follows: \\
  5676. \begin{tabular}{lll}
  5677. \begin{minipage}{0.45\textwidth}
  5678. \begin{lstlisting}
  5679. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5680. \end{lstlisting}
  5681. \end{minipage}
  5682. &
  5683. $\Rightarrow$
  5684. &
  5685. \begin{minipage}{0.4\textwidth}
  5686. \begin{lstlisting}
  5687. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5688. \end{lstlisting}
  5689. \end{minipage}
  5690. \end{tabular} \\
  5691. Regarding function definitions, we need to remove their parameters and
  5692. instead perform parameter passing in terms of the conventions
  5693. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5694. in the argument passing registers, and inside the function we should
  5695. generate a \code{movq} instruction for each parameter, to move the
  5696. argument value from the appropriate register to a new local variable
  5697. with the same name as the old parameter.
  5698. Next, consider the compilation of function calls, which have the
  5699. following form upon input to \code{select-instructions}.
  5700. \begin{lstlisting}
  5701. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5702. \end{lstlisting}
  5703. In the mirror image of handling the parameters of function
  5704. definitions, the arguments \itm{args} need to be moved to the argument
  5705. passing registers.
  5706. %
  5707. Once the instructions for parameter passing have been generated, the
  5708. function call itself can be performed with an indirect function call,
  5709. for which I recommend creating the new instruction
  5710. \code{indirect-callq}. Of course, the return value from the function
  5711. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5712. \begin{lstlisting}
  5713. (indirect-callq |\itm{fun}|)
  5714. (movq (reg rax) |\itm{lhs}|)
  5715. \end{lstlisting}
  5716. Regarding tail calls, the parameter passing is the same as non-tail
  5717. calls: generate instructions to move the arguments into to the
  5718. argument passing registers. After that we need to pop the frame from
  5719. the procedure call stack. However, we do not yet know how big the
  5720. frame is; that gets determined during register allocation. So instead
  5721. of generating those instructions here, we invent a new instruction
  5722. that means ``pop the frame and then do an indirect jump'', which we
  5723. name \code{tail-jmp}.
  5724. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5725. using the label \code{start} for the initial block of a program, and
  5726. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5727. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5728. can be compiled to an assignment to \code{rax} followed by a jump to
  5729. \code{conclusion}. With the addition of function definitions, we will
  5730. have a starting block and conclusion for each function, but their
  5731. labels need to be unique. We recommend prepending the function's name
  5732. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5733. labels. (Alternatively, one could \code{gensym} labels for the start
  5734. and conclusion and store them in the $\itm{info}$ field of the
  5735. function definition.)
  5736. \section{Uncover Live}
  5737. %% The rest of the passes need only minor modifications to handle the new
  5738. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5739. %% \code{leaq}.
  5740. Inside \code{uncover-live}, when computing the $W$ set (written
  5741. variables) for an \code{indirect-callq} instruction, we recommend
  5742. including all the caller-saved registers, which will have the affect
  5743. of making sure that no caller-saved register actually needs to be
  5744. saved.
  5745. \section{Build Interference Graph}
  5746. With the addition of function definitions, we compute an interference
  5747. graph for each function (not just one for the whole program).
  5748. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5749. spill vector-typed variables that are live during a call to the
  5750. \code{collect}. With the addition of functions to our language, we
  5751. need to revisit this issue. Many functions will perform allocation and
  5752. therefore have calls to the collector inside of them. Thus, we should
  5753. not only spill a vector-typed variable when it is live during a call
  5754. to \code{collect}, but we should spill the variable if it is live
  5755. during any function call. Thus, in the \code{build-interference} pass,
  5756. we recommend adding interference edges between call-live vector-typed
  5757. variables and the callee-saved registers (in addition to the usual
  5758. addition of edges between call-live variables and the caller-saved
  5759. registers).
  5760. \section{Patch Instructions}
  5761. In \code{patch-instructions}, you should deal with the x86
  5762. idiosyncrasy that the destination argument of \code{leaq} must be a
  5763. register. Additionally, you should ensure that the argument of
  5764. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5765. code generation more convenient, because we will be trampling many
  5766. registers before the tail call (as explained below).
  5767. \section{Print x86}
  5768. For the \code{print-x86} pass, we recommend the following translations:
  5769. \begin{lstlisting}
  5770. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5771. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5772. \end{lstlisting}
  5773. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5774. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5775. is what we will want to do, but before the jump we need to pop the
  5776. current frame. So we need to restore the state of the registers to the
  5777. point they were at when the current function was called. This
  5778. sequence of instructions is the same as the code for the conclusion of
  5779. a function.
  5780. Note that your \code{print-x86} pass needs to add the code for saving
  5781. and restoring callee-saved registers, if you have not already
  5782. implemented that. This is necessary when generating code for function
  5783. definitions.
  5784. \section{An Example Translation}
  5785. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5786. function in $R_4$ to x86. The figure also includes the results of the
  5787. \code{explicate-control} and \code{select-instructions} passes. We
  5788. have omitted the \code{has-type} AST nodes for readability. Can you
  5789. see any ways to improve the translation?
  5790. \begin{figure}[tbp]
  5791. \begin{tabular}{ll}
  5792. \begin{minipage}{0.45\textwidth}
  5793. % s3_2.rkt
  5794. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5795. (program
  5796. (define (add [x : Integer]
  5797. [y : Integer])
  5798. : Integer (+ x y))
  5799. (add 40 2))
  5800. \end{lstlisting}
  5801. $\Downarrow$
  5802. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5803. (program ()
  5804. (define (add86 [x87 : Integer]
  5805. [y88 : Integer]) : Integer ()
  5806. ((add86start . (return (+ x87 y88)))))
  5807. (define (main) : Integer ()
  5808. ((mainstart .
  5809. (seq (assign tmp89 (fun-ref add86))
  5810. (tailcall tmp89 40 2))))))
  5811. \end{lstlisting}
  5812. \end{minipage}
  5813. &
  5814. $\Rightarrow$
  5815. \begin{minipage}{0.5\textwidth}
  5816. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5817. (program ()
  5818. (define (add86)
  5819. ((locals (x87 . Integer) (y88 . Integer))
  5820. (num-params . 2))
  5821. ((add86start .
  5822. (block ()
  5823. (movq (reg rcx) (var x87))
  5824. (movq (reg rdx) (var y88))
  5825. (movq (var x87) (reg rax))
  5826. (addq (var y88) (reg rax))
  5827. (jmp add86conclusion)))))
  5828. (define (main)
  5829. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5830. (num-params . 0))
  5831. ((mainstart .
  5832. (block ()
  5833. (leaq (fun-ref add86) (var tmp89))
  5834. (movq (int 40) (reg rcx))
  5835. (movq (int 2) (reg rdx))
  5836. (tail-jmp (var tmp89))))))
  5837. \end{lstlisting}
  5838. $\Downarrow$
  5839. \end{minipage}
  5840. \end{tabular}
  5841. \begin{tabular}{lll}
  5842. \begin{minipage}{0.3\textwidth}
  5843. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5844. _add90start:
  5845. movq %rcx, %rsi
  5846. movq %rdx, %rcx
  5847. movq %rsi, %rax
  5848. addq %rcx, %rax
  5849. jmp _add90conclusion
  5850. .globl _add90
  5851. .align 16
  5852. _add90:
  5853. pushq %rbp
  5854. movq %rsp, %rbp
  5855. pushq %r12
  5856. pushq %rbx
  5857. pushq %r13
  5858. pushq %r14
  5859. subq $0, %rsp
  5860. jmp _add90start
  5861. _add90conclusion:
  5862. addq $0, %rsp
  5863. popq %r14
  5864. popq %r13
  5865. popq %rbx
  5866. popq %r12
  5867. subq $0, %r15
  5868. popq %rbp
  5869. retq
  5870. \end{lstlisting}
  5871. \end{minipage}
  5872. &
  5873. \begin{minipage}{0.3\textwidth}
  5874. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5875. _mainstart:
  5876. leaq _add90(%rip), %rsi
  5877. movq $40, %rcx
  5878. movq $2, %rdx
  5879. movq %rsi, %rax
  5880. addq $0, %rsp
  5881. popq %r14
  5882. popq %r13
  5883. popq %rbx
  5884. popq %r12
  5885. subq $0, %r15
  5886. popq %rbp
  5887. jmp *%rax
  5888. .globl _main
  5889. .align 16
  5890. _main:
  5891. pushq %rbp
  5892. movq %rsp, %rbp
  5893. pushq %r12
  5894. pushq %rbx
  5895. pushq %r13
  5896. pushq %r14
  5897. subq $0, %rsp
  5898. movq $16384, %rdi
  5899. movq $16, %rsi
  5900. callq _initialize
  5901. movq _rootstack_begin(%rip), %r15
  5902. jmp _mainstart
  5903. \end{lstlisting}
  5904. \end{minipage}
  5905. &
  5906. \begin{minipage}{0.3\textwidth}
  5907. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5908. _mainconclusion:
  5909. addq $0, %rsp
  5910. popq %r14
  5911. popq %r13
  5912. popq %rbx
  5913. popq %r12
  5914. subq $0, %r15
  5915. popq %rbp
  5916. retq
  5917. \end{lstlisting}
  5918. \end{minipage}
  5919. \end{tabular}
  5920. \caption{Example compilation of a simple function to x86.}
  5921. \label{fig:add-fun}
  5922. \end{figure}
  5923. \begin{exercise}\normalfont
  5924. Expand your compiler to handle $R_4$ as outlined in this chapter.
  5925. Create 5 new programs that use functions, including examples that pass
  5926. functions and return functions from other functions and including
  5927. recursive functions. Test your compiler on these new programs and all
  5928. of your previously created test programs.
  5929. \end{exercise}
  5930. \begin{figure}[p]
  5931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5932. \node (R4) at (0,2) {\large $R_4$};
  5933. \node (R4-2) at (3,2) {\large $R_4$};
  5934. \node (R4-3) at (6,2) {\large $R_4$};
  5935. \node (F1-1) at (12,0) {\large $F_1$};
  5936. \node (F1-2) at (9,0) {\large $F_1$};
  5937. \node (F1-3) at (6,0) {\large $F_1$};
  5938. \node (F1-4) at (3,0) {\large $F_1$};
  5939. \node (C3-1) at (6,-2) {\large $C_3$};
  5940. \node (C3-2) at (3,-2) {\large $C_3$};
  5941. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5942. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5943. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5944. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5945. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5946. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5947. \path[->,bend left=15] (R4) edge [above] node
  5948. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5949. \path[->,bend left=15] (R4-2) edge [above] node
  5950. {\ttfamily\footnotesize uniquify} (R4-3);
  5951. \path[->,bend left=15] (R4-3) edge [right] node
  5952. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5953. \path[->,bend left=15] (F1-1) edge [below] node
  5954. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5955. \path[->,bend right=15] (F1-2) edge [above] node
  5956. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5957. \path[->,bend right=15] (F1-3) edge [above] node
  5958. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5959. \path[->,bend left=15] (F1-4) edge [right] node
  5960. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5961. \path[->,bend left=15] (C3-1) edge [below] node
  5962. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5963. \path[->,bend right=15] (C3-2) edge [left] node
  5964. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5965. \path[->,bend left=15] (x86-2) edge [left] node
  5966. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5967. \path[->,bend right=15] (x86-2-1) edge [below] node
  5968. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5969. \path[->,bend right=15] (x86-2-2) edge [left] node
  5970. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5971. \path[->,bend left=15] (x86-3) edge [above] node
  5972. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5973. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5974. \end{tikzpicture}
  5975. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5976. \label{fig:R4-passes}
  5977. \end{figure}
  5978. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5979. the compilation of $R_4$.
  5980. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5981. \chapter{Lexically Scoped Functions}
  5982. \label{ch:lambdas}
  5983. This chapter studies lexically scoped functions as they appear in
  5984. functional languages such as Racket. By lexical scoping we mean that a
  5985. function's body may refer to variables whose binding site is outside
  5986. of the function, in an enclosing scope.
  5987. %
  5988. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5989. anonymous function defined using the \key{lambda} form. The body of
  5990. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5991. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5992. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5993. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5994. returned from the function \code{f}. Below the definition of \code{f},
  5995. we have two calls to \code{f} with different arguments for \code{x},
  5996. first \code{5} then \code{3}. The functions returned from \code{f} are
  5997. bound to variables \code{g} and \code{h}. Even though these two
  5998. functions were created by the same \code{lambda}, they are really
  5999. different functions because they use different values for
  6000. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6001. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6002. the result of this program is \code{42}.
  6003. \begin{figure}[btp]
  6004. % s4_6.rkt
  6005. \begin{lstlisting}
  6006. (define (f [x : Integer]) : (Integer -> Integer)
  6007. (let ([y 4])
  6008. (lambda: ([z : Integer]) : Integer
  6009. (+ x (+ y z)))))
  6010. (let ([g (f 5)])
  6011. (let ([h (f 3)])
  6012. (+ (g 11) (h 15))))
  6013. \end{lstlisting}
  6014. \caption{Example of a lexically scoped function.}
  6015. \label{fig:lexical-scoping}
  6016. \end{figure}
  6017. \section{The $R_5$ Language}
  6018. The syntax for this language with anonymous functions and lexical
  6019. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6020. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6021. for function application. In this chapter we shall describe how to
  6022. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6023. into a combination of functions (as in $R_4$) and tuples (as in
  6024. $R_3$).
  6025. \begin{figure}[tp]
  6026. \centering
  6027. \fbox{
  6028. \begin{minipage}{0.96\textwidth}
  6029. \[
  6030. \begin{array}{lcl}
  6031. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6032. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6033. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6034. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6035. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6036. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6037. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6038. \mid (\key{and}\;\Exp\;\Exp)
  6039. \mid (\key{or}\;\Exp\;\Exp)
  6040. \mid (\key{not}\;\Exp) } \\
  6041. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6042. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6043. (\key{vector-ref}\;\Exp\;\Int)} \\
  6044. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6045. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6046. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6047. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6048. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6049. \end{array}
  6050. \]
  6051. \end{minipage}
  6052. }
  6053. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6054. with \key{lambda}.}
  6055. \label{fig:r5-syntax}
  6056. \end{figure}
  6057. To compile lexically-scoped functions to top-level function
  6058. definitions, the compiler will need to provide special treatment to
  6059. variable occurrences such as \code{x} and \code{y} in the body of the
  6060. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6061. of $R_4$ may not refer to variables defined outside the function. To
  6062. identify such variable occurrences, we review the standard notion of
  6063. free variable.
  6064. \begin{definition}
  6065. A variable is \emph{free with respect to an expression} $e$ if the
  6066. variable occurs inside $e$ but does not have an enclosing binding in
  6067. $e$.
  6068. \end{definition}
  6069. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6070. free with respect to the expression \code{(+ x (+ y z))}. On the
  6071. other hand, only \code{x} and \code{y} are free with respect to the
  6072. following expression because \code{z} is bound by the \code{lambda}.
  6073. \begin{lstlisting}
  6074. (lambda: ([z : Integer]) : Integer
  6075. (+ x (+ y z)))
  6076. \end{lstlisting}
  6077. Once we have identified the free variables of a \code{lambda}, we need
  6078. to arrange for some way to transport, at runtime, the values of those
  6079. variables from the point where the \code{lambda} was created to the
  6080. point where the \code{lambda} is applied. Referring again to
  6081. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6082. needs to be used in the application of \code{g} to \code{11}, but the
  6083. binding of \code{x} to \code{3} needs to be used in the application of
  6084. \code{h} to \code{15}. An efficient solution to the problem, due to
  6085. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6086. free variables together with the function pointer for the lambda's
  6087. code, an arrangement called a \emph{flat closure} (which we shorten to
  6088. just ``closure'') . Fortunately, we have all the ingredients to make
  6089. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6090. Chapter~\ref{ch:functions} gave us function pointers. The function
  6091. pointer shall reside at index $0$ and the values for free variables
  6092. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6093. the two closures created by the two calls to \code{f} in
  6094. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6095. the same \key{lambda}, they share the same function pointer but differ
  6096. in the values for the free variable \code{x}.
  6097. \begin{figure}[tbp]
  6098. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6099. \caption{Example closure representation for the \key{lambda}'s
  6100. in Figure~\ref{fig:lexical-scoping}.}
  6101. \label{fig:closures}
  6102. \end{figure}
  6103. \section{Interpreting $R_5$}
  6104. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6105. $R_5$. The clause for \key{lambda} saves the current environment
  6106. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6107. the environment from the \key{lambda}, the \code{lam-env}, when
  6108. interpreting the body of the \key{lambda}. The \code{lam-env}
  6109. environment is extended with the mapping of parameters to argument
  6110. values.
  6111. \begin{figure}[tbp]
  6112. \begin{lstlisting}
  6113. (define (interp-exp env)
  6114. (lambda (e)
  6115. (define recur (interp-exp env))
  6116. (match e
  6117. ...
  6118. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6119. `(lambda ,xs ,body ,env)]
  6120. [`(app ,fun ,args ...)
  6121. (define fun-val ((interp-exp env) fun))
  6122. (define arg-vals (map (interp-exp env) args))
  6123. (match fun-val
  6124. [`(lambda (,xs ...) ,body ,lam-env)
  6125. (define new-env (append (map cons xs arg-vals) lam-env))
  6126. ((interp-exp new-env) body)]
  6127. [else (error "interp-exp, expected function, not" fun-val)])]
  6128. [else (error 'interp-exp "unrecognized expression")]
  6129. )))
  6130. \end{lstlisting}
  6131. \caption{Interpreter for $R_5$.}
  6132. \label{fig:interp-R5}
  6133. \end{figure}
  6134. \section{Type Checking $R_5$}
  6135. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6136. \key{lambda} form. The body of the \key{lambda} is checked in an
  6137. environment that includes the current environment (because it is
  6138. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6139. require the body's type to match the declared return type.
  6140. \begin{figure}[tbp]
  6141. \begin{lstlisting}
  6142. (define (typecheck-R5 env)
  6143. (lambda (e)
  6144. (match e
  6145. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6146. (define new-env (append (map cons xs Ts) env))
  6147. (define bodyT ((typecheck-R5 new-env) body))
  6148. (cond [(equal? rT bodyT)
  6149. `(,@Ts -> ,rT)]
  6150. [else
  6151. (error "mismatch in return type" bodyT rT)])]
  6152. ...
  6153. )))
  6154. \end{lstlisting}
  6155. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6156. \label{fig:typecheck-R5}
  6157. \end{figure}
  6158. \section{Closure Conversion}
  6159. The compiling of lexically-scoped functions into top-level function
  6160. definitions is accomplished in the pass \code{convert-to-closures}
  6161. that comes after \code{reveal-functions} and before
  6162. \code{limit-functions}.
  6163. As usual, we shall implement the pass as a recursive function over the
  6164. AST. All of the action is in the clauses for \key{lambda} and
  6165. \key{app}. We transform a \key{lambda} expression into an expression
  6166. that creates a closure, that is, creates a vector whose first element
  6167. is a function pointer and the rest of the elements are the free
  6168. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6169. generated to identify the function.
  6170. \begin{tabular}{lll}
  6171. \begin{minipage}{0.4\textwidth}
  6172. \begin{lstlisting}
  6173. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6174. \end{lstlisting}
  6175. \end{minipage}
  6176. &
  6177. $\Rightarrow$
  6178. &
  6179. \begin{minipage}{0.4\textwidth}
  6180. \begin{lstlisting}
  6181. (vector |\itm{name}| |\itm{fvs}| ...)
  6182. \end{lstlisting}
  6183. \end{minipage}
  6184. \end{tabular} \\
  6185. %
  6186. In addition to transforming each \key{lambda} into a \key{vector}, we
  6187. must create a top-level function definition for each \key{lambda}, as
  6188. shown below.\\
  6189. \begin{minipage}{0.8\textwidth}
  6190. \begin{lstlisting}
  6191. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6192. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6193. ...
  6194. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6195. |\itm{body'}|)...))
  6196. \end{lstlisting}
  6197. \end{minipage}\\
  6198. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6199. parameters are the normal parameters of the \key{lambda}. The types
  6200. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6201. underscore is a dummy type because it is rather difficult to give a
  6202. type to the function in the closure's type, and it does not matter.
  6203. The sequence of \key{let} forms bind the free variables to their
  6204. values obtained from the closure.
  6205. We transform function application into code that retrieves the
  6206. function pointer from the closure and then calls the function, passing
  6207. in the closure as the first argument. We bind $e'$ to a temporary
  6208. variable to avoid code duplication.
  6209. \begin{tabular}{lll}
  6210. \begin{minipage}{0.3\textwidth}
  6211. \begin{lstlisting}
  6212. (app |$e$| |\itm{es}| ...)
  6213. \end{lstlisting}
  6214. \end{minipage}
  6215. &
  6216. $\Rightarrow$
  6217. &
  6218. \begin{minipage}{0.5\textwidth}
  6219. \begin{lstlisting}
  6220. (let ([|\itm{tmp}| |$e'$|])
  6221. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6222. \end{lstlisting}
  6223. \end{minipage}
  6224. \end{tabular} \\
  6225. There is also the question of what to do with top-level function
  6226. definitions. To maintain a uniform translation of function
  6227. application, we turn function references into closures.
  6228. \begin{tabular}{lll}
  6229. \begin{minipage}{0.3\textwidth}
  6230. \begin{lstlisting}
  6231. (fun-ref |$f$|)
  6232. \end{lstlisting}
  6233. \end{minipage}
  6234. &
  6235. $\Rightarrow$
  6236. &
  6237. \begin{minipage}{0.5\textwidth}
  6238. \begin{lstlisting}
  6239. (vector (fun-ref |$f$|))
  6240. \end{lstlisting}
  6241. \end{minipage}
  6242. \end{tabular} \\
  6243. %
  6244. The top-level function definitions need to be updated as well to take
  6245. an extra closure parameter.
  6246. \section{An Example Translation}
  6247. \label{sec:example-lambda}
  6248. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6249. conversion for the example program demonstrating lexical scoping that
  6250. we discussed at the beginning of this chapter.
  6251. \begin{figure}[h]
  6252. \begin{minipage}{0.8\textwidth}
  6253. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6254. (program
  6255. (define (f [x : Integer]) : (Integer -> Integer)
  6256. (let ([y 4])
  6257. (lambda: ([z : Integer]) : Integer
  6258. (+ x (+ y z)))))
  6259. (let ([g (f 5)])
  6260. (let ([h (f 3)])
  6261. (+ (g 11) (h 15)))))
  6262. \end{lstlisting}
  6263. $\Downarrow$
  6264. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6265. (program (type Integer)
  6266. (define (f (x : Integer)) : (Integer -> Integer)
  6267. (let ((y 4))
  6268. (lambda: ((z : Integer)) : Integer
  6269. (+ x (+ y z)))))
  6270. (let ((g (app (fun-ref f) 5)))
  6271. (let ((h (app (fun-ref f) 3)))
  6272. (+ (app g 11) (app h 15)))))
  6273. \end{lstlisting}
  6274. $\Downarrow$
  6275. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6276. (program (type Integer)
  6277. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6278. (let ((y 4))
  6279. (vector (fun-ref lam.1) x y)))
  6280. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6281. (let ((x (vector-ref clos.2 1)))
  6282. (let ((y (vector-ref clos.2 2)))
  6283. (+ x (+ y z)))))
  6284. (let ((g (let ((t.1 (vector (fun-ref f))))
  6285. (app (vector-ref t.1 0) t.1 5))))
  6286. (let ((h (let ((t.2 (vector (fun-ref f))))
  6287. (app (vector-ref t.2 0) t.2 3))))
  6288. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6289. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6290. \end{lstlisting}
  6291. \end{minipage}
  6292. \caption{Example of closure conversion.}
  6293. \label{fig:lexical-functions-example}
  6294. \end{figure}
  6295. \begin{figure}[p]
  6296. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6297. \node (R4) at (0,2) {\large $R_4$};
  6298. \node (R4-2) at (3,2) {\large $R_4$};
  6299. \node (R4-3) at (6,2) {\large $R_4$};
  6300. \node (F1-1) at (12,0) {\large $F_1$};
  6301. \node (F1-2) at (9,0) {\large $F_1$};
  6302. \node (F1-3) at (6,0) {\large $F_1$};
  6303. \node (F1-4) at (3,0) {\large $F_1$};
  6304. \node (F1-5) at (0,0) {\large $F_1$};
  6305. \node (C3-1) at (6,-2) {\large $C_3$};
  6306. \node (C3-2) at (3,-2) {\large $C_3$};
  6307. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6308. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6309. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6310. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6311. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6312. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6313. \path[->,bend left=15] (R4) edge [above] node
  6314. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6315. \path[->,bend left=15] (R4-2) edge [above] node
  6316. {\ttfamily\footnotesize uniquify} (R4-3);
  6317. \path[->] (R4-3) edge [right] node
  6318. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6319. \path[->,bend left=15] (F1-1) edge [below] node
  6320. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6321. \path[->,bend right=15] (F1-2) edge [above] node
  6322. {\ttfamily\footnotesize limit-functions} (F1-3);
  6323. \path[->,bend right=15] (F1-3) edge [above] node
  6324. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6325. \path[->,bend right=15] (F1-4) edge [above] node
  6326. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6327. \path[->] (F1-5) edge [left] node
  6328. {\ttfamily\footnotesize explicate-control} (C3-1);
  6329. \path[->,bend left=15] (C3-1) edge [below] node
  6330. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6331. \path[->,bend right=15] (C3-2) edge [left] node
  6332. {\ttfamily\footnotesize select-instr.} (x86-2);
  6333. \path[->,bend left=15] (x86-2) edge [left] node
  6334. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6335. \path[->,bend right=15] (x86-2-1) edge [below] node
  6336. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6337. \path[->,bend right=15] (x86-2-2) edge [left] node
  6338. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6339. \path[->,bend left=15] (x86-3) edge [above] node
  6340. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6341. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6342. \end{tikzpicture}
  6343. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6344. functions.}
  6345. \label{fig:R5-passes}
  6346. \end{figure}
  6347. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6348. for the compilation of $R_5$.
  6349. \begin{exercise}\normalfont
  6350. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6351. Create 5 new programs that use \key{lambda} functions and make use of
  6352. lexical scoping. Test your compiler on these new programs and all of
  6353. your previously created test programs.
  6354. \end{exercise}
  6355. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6356. \chapter{Dynamic Typing}
  6357. \label{ch:type-dynamic}
  6358. In this chapter we discuss the compilation of a dynamically typed
  6359. language, named $R_7$, that is a subset of the Racket
  6360. language. (Recall that in the previous chapters we have studied
  6361. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6362. languages, an expression may produce values of differing
  6363. type. Consider the following example with a conditional expression
  6364. that may return a Boolean or an integer depending on the input to the
  6365. program.
  6366. \begin{lstlisting}
  6367. (not (if (eq? (read) 1) #f 0))
  6368. \end{lstlisting}
  6369. Languages that allow expressions to produce different kinds of values
  6370. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6371. such as subtype polymorphism and parametric
  6372. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6373. talking about here does not have a special name, but it is the usual
  6374. kind that arises in dynamically typed languages.
  6375. Another characteristic of dynamically typed languages is that
  6376. primitive operations, such as \code{not}, are often defined to operate
  6377. on many different types of values. In fact, in Racket, the \code{not}
  6378. operator produces a result for any kind of value: given \code{\#f} it
  6379. returns \code{\#t} and given anything else it returns \code{\#f}.
  6380. Furthermore, even when primitive operations restrict their inputs to
  6381. values of a certain type, this restriction is enforced at runtime
  6382. instead of during compilation. For example, the following vector
  6383. reference results in a run-time contract violation.
  6384. \begin{lstlisting}
  6385. (vector-ref (vector 42) #t)
  6386. \end{lstlisting}
  6387. \begin{figure}[tp]
  6388. \centering
  6389. \fbox{
  6390. \begin{minipage}{0.97\textwidth}
  6391. \[
  6392. \begin{array}{rcl}
  6393. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6394. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6395. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6396. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6397. &\mid& \key{\#t} \mid \key{\#f}
  6398. \mid (\key{and}\;\Exp\;\Exp)
  6399. \mid (\key{or}\;\Exp\;\Exp)
  6400. \mid (\key{not}\;\Exp) \\
  6401. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6402. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6403. (\key{vector-ref}\;\Exp\;\Exp) \\
  6404. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6405. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6406. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6407. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6408. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6409. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6410. \end{array}
  6411. \]
  6412. \end{minipage}
  6413. }
  6414. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6415. \label{fig:r7-syntax}
  6416. \end{figure}
  6417. The syntax of $R_7$, our subset of Racket, is defined in
  6418. Figure~\ref{fig:r7-syntax}.
  6419. %
  6420. The definitional interpreter for $R_7$ is given in
  6421. Figure~\ref{fig:interp-R7}.
  6422. \begin{figure}[tbp]
  6423. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6424. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6425. (define (valid-op? op) (member op '(+ - and or not)))
  6426. (define (interp-r7 env)
  6427. (lambda (ast)
  6428. (define recur (interp-r7 env))
  6429. (match ast
  6430. [(? symbol?) (lookup ast env)]
  6431. [(? integer?) `(inject ,ast Integer)]
  6432. [#t `(inject #t Boolean)]
  6433. [#f `(inject #f Boolean)]
  6434. [`(read) `(inject ,(read-fixnum) Integer)]
  6435. [`(lambda (,xs ...) ,body)
  6436. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6437. [`(define (,f ,xs ...) ,body)
  6438. (mcons f `(lambda ,xs ,body))]
  6439. [`(program ,ds ... ,body)
  6440. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6441. (for/list ([b top-level])
  6442. (set-mcdr! b (match (mcdr b)
  6443. [`(lambda ,xs ,body)
  6444. `(inject (lambda ,xs ,body ,top-level)
  6445. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6446. ((interp-r7 top-level) body))]
  6447. [`(vector ,(app recur elts) ...)
  6448. (define tys (map get-tagged-type elts))
  6449. `(inject ,(apply vector elts) (Vector ,@tys))]
  6450. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6451. (match v1
  6452. [`(inject ,vec ,ty)
  6453. (vector-set! vec n v2)
  6454. `(inject (void) Void)])]
  6455. [`(vector-ref ,(app recur v) ,n)
  6456. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6457. [`(let ([,x ,(app recur v)]) ,body)
  6458. ((interp-r7 (cons (cons x v) env)) body)]
  6459. [`(,op ,es ...) #:when (valid-op? op)
  6460. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6461. [`(eq? ,(app recur l) ,(app recur r))
  6462. `(inject ,(equal? l r) Boolean)]
  6463. [`(if ,(app recur q) ,t ,f)
  6464. (match q
  6465. [`(inject #f Boolean) (recur f)]
  6466. [else (recur t)])]
  6467. [`(,(app recur f-val) ,(app recur vs) ...)
  6468. (match f-val
  6469. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6470. (define new-env (append (map cons xs vs) lam-env))
  6471. ((interp-r7 new-env) body)]
  6472. [else (error "interp-r7, expected function, not" f-val)])])))
  6473. \end{lstlisting}
  6474. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6475. \label{fig:interp-R7}
  6476. \end{figure}
  6477. Let us consider how we might compile $R_7$ to x86, thinking about the
  6478. first example above. Our bit-level representation of the Boolean
  6479. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6480. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6481. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6482. general, cannot be determined at compile time, but depends on the
  6483. runtime type of its input, as in the example above that depends on the
  6484. result of \code{(read)}.
  6485. The way around this problem is to include information about a value's
  6486. runtime type in the value itself, so that this information can be
  6487. inspected by operators such as \code{not}. In particular, we shall
  6488. steal the 3 right-most bits from our 64-bit values to encode the
  6489. runtime type. We shall use $001$ to identify integers, $100$ for
  6490. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6491. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6492. define the following auxiliary function.
  6493. \begin{align*}
  6494. \itm{tagof}(\key{Integer}) &= 001 \\
  6495. \itm{tagof}(\key{Boolean}) &= 100 \\
  6496. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6497. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6498. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6499. \itm{tagof}(\key{Void}) &= 101
  6500. \end{align*}
  6501. (We shall say more about the new \key{Vectorof} type shortly.)
  6502. This stealing of 3 bits comes at some
  6503. price: our integers are reduced to ranging from $-2^{60}$ to
  6504. $2^{60}$. The stealing does not adversely affect vectors and
  6505. procedures because those values are addresses, and our addresses are
  6506. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6507. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6508. bits with the tag and we can simply zero-out the tag to recover the
  6509. original address.
  6510. In some sense, these tagged values are a new kind of value. Indeed,
  6511. we can extend our \emph{typed} language with tagged values by adding a
  6512. new type to classify them, called \key{Any}, and with operations for
  6513. creating and using tagged values, yielding the $R_6$ language that we
  6514. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6515. fundamental support for polymorphism and runtime types that we need to
  6516. support dynamic typing.
  6517. There is an interesting interaction between tagged values and garbage
  6518. collection. A variable of type \code{Any} might refer to a vector and
  6519. therefore it might be a root that needs to be inspected and copied
  6520. during garbage collection. Thus, we need to treat variables of type
  6521. \code{Any} in a similar way to variables of type \code{Vector} for
  6522. purposes of register allocation, which we discuss in
  6523. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6524. variable of type \code{Any} is spilled, it must be spilled to the root
  6525. stack. But this means that the garbage collector needs to be able to
  6526. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6527. value that points to a tuple, and (3) a tagged value that is not a
  6528. tuple. We enable this differentiation by choosing not to use the tag
  6529. $000$. Instead, that bit pattern is reserved for identifying plain old
  6530. pointers to tuples. On the other hand, if one of the first three bits
  6531. is set, then we have a tagged value, and inspecting the tag can
  6532. differentiation between vectors ($010$) and the other kinds of values.
  6533. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6534. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6535. extend our compiler to handle the new features of $R_6$
  6536. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6537. \ref{sec:register-allocation-r6}).
  6538. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6539. \label{sec:r6-lang}
  6540. \begin{figure}[tp]
  6541. \centering
  6542. \fbox{
  6543. \begin{minipage}{0.97\textwidth}
  6544. \[
  6545. \begin{array}{lcl}
  6546. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6547. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6548. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6549. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6550. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6551. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6552. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6553. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6554. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6555. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6556. \mid (\key{and}\;\Exp\;\Exp)
  6557. \mid (\key{or}\;\Exp\;\Exp)
  6558. \mid (\key{not}\;\Exp)} \\
  6559. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6560. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6561. (\key{vector-ref}\;\Exp\;\Int)} \\
  6562. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6563. &\mid& \gray{(\Exp \; \Exp^{*})
  6564. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6565. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6566. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6567. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6568. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6569. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6570. \end{array}
  6571. \]
  6572. \end{minipage}
  6573. }
  6574. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6575. with \key{Any}.}
  6576. \label{fig:r6-syntax}
  6577. \end{figure}
  6578. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6579. $(\key{inject}\; e\; T)$ form converts the value produced by
  6580. expression $e$ of type $T$ into a tagged value. The
  6581. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6582. expression $e$ into a value of type $T$ or else halts the program if
  6583. the type tag is equivalent to $T$. We treat
  6584. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6585. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6586. Note that in both \key{inject} and
  6587. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6588. which simplifies the implementation and corresponds with what is
  6589. needed for compiling untyped Racket. The type predicates,
  6590. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6591. if the tag corresponds to the predicate, and return \key{\#t}
  6592. otherwise.
  6593. %
  6594. Selections from the type checker for $R_6$ are shown in
  6595. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6596. Figure~\ref{fig:interp-R6}.
  6597. \begin{figure}[btp]
  6598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6599. (define (flat-ty? ty) ...)
  6600. (define (typecheck-R6 env)
  6601. (lambda (e)
  6602. (define recur (typecheck-R6 env))
  6603. (match e
  6604. [`(inject ,e ,ty)
  6605. (unless (flat-ty? ty)
  6606. (error "may only inject a value of flat type, not ~a" ty))
  6607. (define-values (new-e e-ty) (recur e))
  6608. (cond
  6609. [(equal? e-ty ty)
  6610. (values `(inject ,new-e ,ty) 'Any)]
  6611. [else
  6612. (error "inject expected ~a to have type ~a" e ty)])]
  6613. [`(project ,e ,ty)
  6614. (unless (flat-ty? ty)
  6615. (error "may only project to a flat type, not ~a" ty))
  6616. (define-values (new-e e-ty) (recur e))
  6617. (cond
  6618. [(equal? e-ty 'Any)
  6619. (values `(project ,new-e ,ty) ty)]
  6620. [else
  6621. (error "project expected ~a to have type Any" e)])]
  6622. [`(vector-ref ,e ,i)
  6623. (define-values (new-e e-ty) (recur e))
  6624. (match e-ty
  6625. [`(Vector ,ts ...) ...]
  6626. [`(Vectorof ,ty)
  6627. (unless (exact-nonnegative-integer? i)
  6628. (error 'type-check "invalid index ~a" i))
  6629. (values `(vector-ref ,new-e ,i) ty)]
  6630. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6631. ...
  6632. )))
  6633. \end{lstlisting}
  6634. \caption{Type checker for parts of the $R_6$ language.}
  6635. \label{fig:typecheck-R6}
  6636. \end{figure}
  6637. % to do: add rules for vector-ref, etc. for Vectorof
  6638. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6639. \begin{figure}[btp]
  6640. \begin{lstlisting}
  6641. (define primitives (set 'boolean? ...))
  6642. (define (interp-op op)
  6643. (match op
  6644. ['boolean? (lambda (v)
  6645. (match v
  6646. [`(tagged ,v1 Boolean) #t]
  6647. [else #f]))]
  6648. ...))
  6649. ;; Equivalence of flat types
  6650. (define (tyeq? t1 t2)
  6651. (match `(,t1 ,t2)
  6652. [`((Vectorof Any) (Vector ,t2s ...))
  6653. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6654. [`((Vector ,t1s ...) (Vectorof Any))
  6655. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6656. [else (equal? t1 t2)]))
  6657. (define (interp-R6 env)
  6658. (lambda (ast)
  6659. (match ast
  6660. [`(inject ,e ,t)
  6661. `(tagged ,((interp-R6 env) e) ,t)]
  6662. [`(project ,e ,t2)
  6663. (define v ((interp-R6 env) e))
  6664. (match v
  6665. [`(tagged ,v1 ,t1)
  6666. (cond [(tyeq? t1 t2)
  6667. v1]
  6668. [else
  6669. (error "in project, type mismatch" t1 t2)])]
  6670. [else
  6671. (error "in project, expected tagged value" v)])]
  6672. ...)))
  6673. \end{lstlisting}
  6674. \caption{Interpreter for $R_6$.}
  6675. \label{fig:interp-R6}
  6676. \end{figure}
  6677. %\clearpage
  6678. \section{Shrinking $R_6$}
  6679. \label{sec:shrink-r6}
  6680. In the \code{shrink} pass we recommend compiling \code{project} into
  6681. an explicit \code{if} expression that uses three new operations:
  6682. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6683. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6684. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6685. value from a tagged value. Finally, the \code{exit} operation ends the
  6686. execution of the program by invoking the operating system's
  6687. \code{exit} function. So the translation for \code{project} is as
  6688. follows. (We have omitted the \code{has-type} AST nodes to make this
  6689. output more readable.)
  6690. \begin{tabular}{lll}
  6691. \begin{minipage}{0.3\textwidth}
  6692. \begin{lstlisting}
  6693. (project |$e$| |$\Type$|)
  6694. \end{lstlisting}
  6695. \end{minipage}
  6696. &
  6697. $\Rightarrow$
  6698. &
  6699. \begin{minipage}{0.5\textwidth}
  6700. \begin{lstlisting}
  6701. (let ([|$\itm{tmp}$| |$e'$|])
  6702. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6703. (value-of-any |$\itm{tmp}$|)
  6704. (exit)))
  6705. \end{lstlisting}
  6706. \end{minipage}
  6707. \end{tabular} \\
  6708. Similarly, we recommend translating the type predicates
  6709. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6710. \section{Instruction Selection for $R_6$}
  6711. \label{sec:select-r6}
  6712. \paragraph{Inject}
  6713. We recommend compiling an \key{inject} as follows if the type is
  6714. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6715. destination to the left by the number of bits specified its source
  6716. argument (in this case $3$, the length of the tag) and it preserves
  6717. the sign of the integer. We use the \key{orq} instruction to combine
  6718. the tag and the value to form the tagged value. \\
  6719. \begin{tabular}{lll}
  6720. \begin{minipage}{0.4\textwidth}
  6721. \begin{lstlisting}
  6722. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6723. \end{lstlisting}
  6724. \end{minipage}
  6725. &
  6726. $\Rightarrow$
  6727. &
  6728. \begin{minipage}{0.5\textwidth}
  6729. \begin{lstlisting}
  6730. (movq |$e'$| |\itm{lhs}'|)
  6731. (salq (int 3) |\itm{lhs}'|)
  6732. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6733. \end{lstlisting}
  6734. \end{minipage}
  6735. \end{tabular} \\
  6736. The instruction selection for vectors and procedures is different
  6737. because their is no need to shift them to the left. The rightmost 3
  6738. bits are already zeros as described above. So we just combine the
  6739. value and the tag using \key{orq}. \\
  6740. \begin{tabular}{lll}
  6741. \begin{minipage}{0.4\textwidth}
  6742. \begin{lstlisting}
  6743. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6744. \end{lstlisting}
  6745. \end{minipage}
  6746. &
  6747. $\Rightarrow$
  6748. &
  6749. \begin{minipage}{0.5\textwidth}
  6750. \begin{lstlisting}
  6751. (movq |$e'$| |\itm{lhs}'|)
  6752. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6753. \end{lstlisting}
  6754. \end{minipage}
  6755. \end{tabular}
  6756. \paragraph{Tag of Any}
  6757. Recall that the \code{tag-of-any} operation extracts the type tag from
  6758. a value of type \code{Any}. The type tag is the bottom three bits, so
  6759. we obtain the tag by taking the bitwise-and of the value with $111$
  6760. ($7$ in decimal).
  6761. \begin{tabular}{lll}
  6762. \begin{minipage}{0.4\textwidth}
  6763. \begin{lstlisting}
  6764. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6765. \end{lstlisting}
  6766. \end{minipage}
  6767. &
  6768. $\Rightarrow$
  6769. &
  6770. \begin{minipage}{0.5\textwidth}
  6771. \begin{lstlisting}
  6772. (movq |$e'$| |\itm{lhs}'|)
  6773. (andq (int 7) |\itm{lhs}'|)
  6774. \end{lstlisting}
  6775. \end{minipage}
  6776. \end{tabular}
  6777. \paragraph{Value of Any}
  6778. Like \key{inject}, the instructions for \key{value-of-any} are
  6779. different depending on whether the type $T$ is a pointer (vector or
  6780. procedure) or not (Integer or Boolean). The following shows the
  6781. instruction selection for Integer and Boolean. We produce an untagged
  6782. value by shifting it to the right by 3 bits.
  6783. %
  6784. \\
  6785. \begin{tabular}{lll}
  6786. \begin{minipage}{0.4\textwidth}
  6787. \begin{lstlisting}
  6788. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6789. \end{lstlisting}
  6790. \end{minipage}
  6791. &
  6792. $\Rightarrow$
  6793. &
  6794. \begin{minipage}{0.5\textwidth}
  6795. \begin{lstlisting}
  6796. (movq |$e'$| |\itm{lhs}'|)
  6797. (sarq (int 3) |\itm{lhs}'|)
  6798. \end{lstlisting}
  6799. \end{minipage}
  6800. \end{tabular} \\
  6801. %
  6802. In the case for vectors and procedures, there is no need to
  6803. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6804. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6805. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6806. \code{movq} into the destination $\itm{lhs}$. We then generate
  6807. \code{andq} with the tagged value to get the desired result. \\
  6808. %
  6809. \begin{tabular}{lll}
  6810. \begin{minipage}{0.4\textwidth}
  6811. \begin{lstlisting}
  6812. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6813. \end{lstlisting}
  6814. \end{minipage}
  6815. &
  6816. $\Rightarrow$
  6817. &
  6818. \begin{minipage}{0.5\textwidth}
  6819. \begin{lstlisting}
  6820. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6821. (andq |$e'$| |\itm{lhs}'|)
  6822. \end{lstlisting}
  6823. \end{minipage}
  6824. \end{tabular}
  6825. %% \paragraph{Type Predicates} We leave it to the reader to
  6826. %% devise a sequence of instructions to implement the type predicates
  6827. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6828. \section{Register Allocation for $R_6$}
  6829. \label{sec:register-allocation-r6}
  6830. As mentioned above, a variable of type \code{Any} might refer to a
  6831. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6832. of type \code{Any} in the same way that it treats variables of type
  6833. \code{Vector} for purposes of garbage collection. In particular,
  6834. \begin{itemize}
  6835. \item If a variable of type \code{Any} is live during a function call,
  6836. then it must be spilled. One way to accomplish this is to augment
  6837. the pass \code{build-interference} to mark all variables that are
  6838. live after a \code{callq} as interfering with all the registers.
  6839. \item If a variable of type \code{Any} is spilled, it must be spilled
  6840. to the root stack instead of the normal procedure call stack.
  6841. \end{itemize}
  6842. \begin{exercise}\normalfont
  6843. Expand your compiler to handle $R_6$ as discussed in the last few
  6844. sections. Create 5 new programs that use the \code{Any} type and the
  6845. new operations (\code{inject}, \code{project}, \code{boolean?},
  6846. etc.). Test your compiler on these new programs and all of your
  6847. previously created test programs.
  6848. \end{exercise}
  6849. \section{Compiling $R_7$ to $R_6$}
  6850. \label{sec:compile-r7}
  6851. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6852. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6853. given a subexpression $e$ of $R_7$, the pass will produce an
  6854. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6855. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6856. the Boolean \code{\#t}, which must be injected to produce an
  6857. expression of type \key{Any}.
  6858. %
  6859. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6860. addition, is representative of compilation for many operations: the
  6861. arguments have type \key{Any} and must be projected to \key{Integer}
  6862. before the addition can be performed.
  6863. The compilation of \key{lambda} (third row of
  6864. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6865. produce type annotations: we simply use \key{Any}.
  6866. %
  6867. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6868. has to account for some differences in behavior between $R_7$ and
  6869. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6870. kind of values can be used in various places. For example, the
  6871. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6872. the arguments need not be of the same type (but in that case, the
  6873. result will be \code{\#f}).
  6874. \begin{figure}[btp]
  6875. \centering
  6876. \begin{tabular}{|lll|} \hline
  6877. \begin{minipage}{0.25\textwidth}
  6878. \begin{lstlisting}
  6879. #t
  6880. \end{lstlisting}
  6881. \end{minipage}
  6882. &
  6883. $\Rightarrow$
  6884. &
  6885. \begin{minipage}{0.6\textwidth}
  6886. \begin{lstlisting}
  6887. (inject #t Boolean)
  6888. \end{lstlisting}
  6889. \end{minipage}
  6890. \\[2ex]\hline
  6891. \begin{minipage}{0.25\textwidth}
  6892. \begin{lstlisting}
  6893. (+ |$e_1$| |$e_2$|)
  6894. \end{lstlisting}
  6895. \end{minipage}
  6896. &
  6897. $\Rightarrow$
  6898. &
  6899. \begin{minipage}{0.6\textwidth}
  6900. \begin{lstlisting}
  6901. (inject
  6902. (+ (project |$e'_1$| Integer)
  6903. (project |$e'_2$| Integer))
  6904. Integer)
  6905. \end{lstlisting}
  6906. \end{minipage}
  6907. \\[2ex]\hline
  6908. \begin{minipage}{0.25\textwidth}
  6909. \begin{lstlisting}
  6910. (lambda (|$x_1 \ldots$|) |$e$|)
  6911. \end{lstlisting}
  6912. \end{minipage}
  6913. &
  6914. $\Rightarrow$
  6915. &
  6916. \begin{minipage}{0.6\textwidth}
  6917. \begin{lstlisting}
  6918. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6919. (Any|$\ldots$|Any -> Any))
  6920. \end{lstlisting}
  6921. \end{minipage}
  6922. \\[2ex]\hline
  6923. \begin{minipage}{0.25\textwidth}
  6924. \begin{lstlisting}
  6925. (app |$e_0$| |$e_1 \ldots e_n$|)
  6926. \end{lstlisting}
  6927. \end{minipage}
  6928. &
  6929. $\Rightarrow$
  6930. &
  6931. \begin{minipage}{0.6\textwidth}
  6932. \begin{lstlisting}
  6933. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6934. |$e'_1 \ldots e'_n$|)
  6935. \end{lstlisting}
  6936. \end{minipage}
  6937. \\[2ex]\hline
  6938. \begin{minipage}{0.25\textwidth}
  6939. \begin{lstlisting}
  6940. (vector-ref |$e_1$| |$e_2$|)
  6941. \end{lstlisting}
  6942. \end{minipage}
  6943. &
  6944. $\Rightarrow$
  6945. &
  6946. \begin{minipage}{0.6\textwidth}
  6947. \begin{lstlisting}
  6948. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6949. (let ([tmp2 (project |$e'_2$| Integer)])
  6950. (vector-ref tmp1 tmp2)))
  6951. \end{lstlisting}
  6952. \end{minipage}
  6953. \\[2ex]\hline
  6954. \begin{minipage}{0.25\textwidth}
  6955. \begin{lstlisting}
  6956. (if |$e_1$| |$e_2$| |$e_3$|)
  6957. \end{lstlisting}
  6958. \end{minipage}
  6959. &
  6960. $\Rightarrow$
  6961. &
  6962. \begin{minipage}{0.6\textwidth}
  6963. \begin{lstlisting}
  6964. (if (eq? |$e'_1$| (inject #f Boolean))
  6965. |$e'_3$|
  6966. |$e'_2$|)
  6967. \end{lstlisting}
  6968. \end{minipage}
  6969. \\[2ex]\hline
  6970. \begin{minipage}{0.25\textwidth}
  6971. \begin{lstlisting}
  6972. (eq? |$e_1$| |$e_2$|)
  6973. \end{lstlisting}
  6974. \end{minipage}
  6975. &
  6976. $\Rightarrow$
  6977. &
  6978. \begin{minipage}{0.6\textwidth}
  6979. \begin{lstlisting}
  6980. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6981. \end{lstlisting}
  6982. \end{minipage}
  6983. \\[2ex]\hline
  6984. \end{tabular}
  6985. \caption{Compiling $R_7$ to $R_6$.}
  6986. \label{fig:compile-r7-r6}
  6987. \end{figure}
  6988. \begin{exercise}\normalfont
  6989. Expand your compiler to handle $R_7$ as outlined in this chapter.
  6990. Create tests for $R_7$ by adapting all of your previous test programs
  6991. by removing type annotations. Add 5 more tests programs that
  6992. specifically rely on the language being dynamically typed. That is,
  6993. they should not be legal programs in a statically typed language, but
  6994. nevertheless, they should be valid $R_7$ programs that run to
  6995. completion without error.
  6996. \end{exercise}
  6997. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6998. \chapter{Gradual Typing}
  6999. \label{ch:gradual-typing}
  7000. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7001. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7002. \chapter{Parametric Polymorphism}
  7003. \label{ch:parametric-polymorphism}
  7004. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7005. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7006. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7007. \chapter{High-level Optimization}
  7008. \label{ch:high-level-optimization}
  7009. This chapter will present a procedure inlining pass based on the
  7010. algorithm of \citet{Waddell:1997fk}.
  7011. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7012. \chapter{Appendix}
  7013. \section{Interpreters}
  7014. \label{appendix:interp}
  7015. We provide several interpreters in the \key{interp.rkt} file. The
  7016. \key{interp-scheme} function takes an AST in one of the Racket-like
  7017. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7018. the program, returning the result value. The \key{interp-C} function
  7019. interprets an AST for a program in one of the C-like languages ($C_0,
  7020. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7021. for an x86 program.
  7022. \section{Utility Functions}
  7023. \label{appendix:utilities}
  7024. The utility function described in this section can be found in the
  7025. \key{utilities.rkt} file.
  7026. The \key{read-program} function takes a file path and parses that file
  7027. (it must be a Racket program) into an abstract syntax tree (as an
  7028. S-expression) with a \key{program} AST at the top.
  7029. The \key{assert} function displays the error message \key{msg} if the
  7030. Boolean \key{bool} is false.
  7031. \begin{lstlisting}
  7032. (define (assert msg bool) ...)
  7033. \end{lstlisting}
  7034. The \key{lookup} function takes a key and an association list (a list
  7035. of key-value pairs), and returns the first value that is associated
  7036. with the given key, if there is one. If not, an error is triggered.
  7037. The association list may contain both immutable pairs (built with
  7038. \key{cons}) and mutable pairs (built with \key{mcons}).
  7039. The \key{map2} function ...
  7040. %% \subsection{Graphs}
  7041. %% \begin{itemize}
  7042. %% \item The \code{make-graph} function takes a list of vertices
  7043. %% (symbols) and returns a graph.
  7044. %% \item The \code{add-edge} function takes a graph and two vertices and
  7045. %% adds an edge to the graph that connects the two vertices. The graph
  7046. %% is updated in-place. There is no return value for this function.
  7047. %% \item The \code{adjacent} function takes a graph and a vertex and
  7048. %% returns the set of vertices that are adjacent to the given
  7049. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7050. %% used with functions from the \code{racket/set} module.
  7051. %% \item The \code{vertices} function takes a graph and returns the list
  7052. %% of vertices in the graph.
  7053. %% \end{itemize}
  7054. \subsection{Testing}
  7055. The \key{interp-tests} function takes a compiler name (a string), a
  7056. description of the passes, an interpreter for the source language, a
  7057. test family name (a string), and a list of test numbers, and runs the
  7058. compiler passes and the interpreters to check whether the passes
  7059. correct. The description of the passes is a list with one entry per
  7060. pass. An entry is a list with three things: a string giving the name
  7061. of the pass, the function that implements the pass (a translator from
  7062. AST to AST), and a function that implements the interpreter (a
  7063. function from AST to result value) for the language of the output of
  7064. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7065. good choice. The \key{interp-tests} function assumes that the
  7066. subdirectory \key{tests} has a collection of Scheme programs whose names
  7067. all start with the family name, followed by an underscore and then the
  7068. test number, ending in \key{.scm}. Also, for each Scheme program there
  7069. is a file with the same number except that it ends with \key{.in} that
  7070. provides the input for the Scheme program.
  7071. \begin{lstlisting}
  7072. (define (interp-tests name passes test-family test-nums) ...)
  7073. \end{lstlisting}
  7074. The compiler-tests function takes a compiler name (a string) a
  7075. description of the passes (as described above for
  7076. \code{interp-tests}), a test family name (a string), and a list of
  7077. test numbers (see the comment for interp-tests), and runs the compiler
  7078. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7079. machine code. It runs the machine code and checks that the output is
  7080. 42.
  7081. \begin{lstlisting}
  7082. (define (compiler-tests name passes test-family test-nums) ...)
  7083. \end{lstlisting}
  7084. The compile-file function takes a description of the compiler passes
  7085. (see the comment for \key{interp-tests}) and returns a function that,
  7086. given a program file name (a string ending in \key{.scm}), applies all
  7087. of the passes and writes the output to a file whose name is the same
  7088. as the program file name but with \key{.scm} replaced with \key{.s}.
  7089. \begin{lstlisting}
  7090. (define (compile-file passes)
  7091. (lambda (prog-file-name) ...))
  7092. \end{lstlisting}
  7093. \section{x86 Instruction Set Quick-Reference}
  7094. \label{sec:x86-quick-reference}
  7095. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7096. do. We write $A \to B$ to mean that the value of $A$ is written into
  7097. location $B$. Address offsets are given in bytes. The instruction
  7098. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7099. registers (such as $\%rax$), or memory references (such as
  7100. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7101. reference per instruction. Other operands must be immediates or
  7102. registers.
  7103. \begin{table}[tbp]
  7104. \centering
  7105. \begin{tabular}{l|l}
  7106. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7107. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7108. \texttt{negq} $A$ & $- A \to A$ \\
  7109. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7110. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7111. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7112. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7113. \texttt{retq} & Pops the return address and jumps to it \\
  7114. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7115. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7116. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7117. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7118. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7119. matches the condition code of the instruction, otherwise go to the
  7120. next instructions. The condition codes are \key{e} for ``equal'',
  7121. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7122. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7123. \texttt{jl} $L$ & \\
  7124. \texttt{jle} $L$ & \\
  7125. \texttt{jg} $L$ & \\
  7126. \texttt{jge} $L$ & \\
  7127. \texttt{jmp} $L$ & Jump to label $L$ \\
  7128. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7129. \texttt{movzbq} $A$, $B$ &
  7130. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7131. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7132. and the extra bytes of $B$ are set to zero.} \\
  7133. & \\
  7134. & \\
  7135. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7136. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7137. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7138. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7139. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7140. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7141. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7142. description of the condition codes. $A$ must be a single byte register
  7143. (e.g., \texttt{al} or \texttt{cl}).} \\
  7144. \texttt{setl} $A$ & \\
  7145. \texttt{setle} $A$ & \\
  7146. \texttt{setg} $A$ & \\
  7147. \texttt{setge} $A$ &
  7148. \end{tabular}
  7149. \vspace{5pt}
  7150. \caption{Quick-reference for the x86 instructions used in this book.}
  7151. \label{tab:x86-instr}
  7152. \end{table}
  7153. \bibliographystyle{plainnat}
  7154. \bibliography{all}
  7155. \end{document}
  7156. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7157. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7158. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7159. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7160. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7161. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7162. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7163. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7164. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7165. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7166. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7167. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7168. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7169. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7170. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7171. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7172. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7173. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7174. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7175. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7176. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7177. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7178. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7179. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7180. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7181. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7182. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7183. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7184. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7185. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7186. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge