book.tex 360 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. (In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency.) Dybvig, with later help from his students Dipanwita
  170. Sarkar and Andrew Keep, developed infrastructure to support this
  171. approach and evolved the course, first to use smaller micro-passes and
  172. then into even smaller
  173. nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student in this
  174. compiler course in the early 2000's as part of his Ph.D. studies at
  175. Indiana University. Needless to say, I enjoyed the course immensely!
  176. During that time, another graduate student named Abdulaziz Ghuloum
  177. observed that the front-to-back organization of the course made it
  178. difficult for students to understand the rationale for the compiler
  179. design. Ghuloum proposed an incremental approach in which the students
  180. build the compiler in stages; they start by implementing a complete
  181. compiler for a very small subset of the input language and in each
  182. subsequent stage they add a language feature and add or modify passes
  183. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  184. students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, I was able to teach much of the
  192. same content from the Indiana compiler course. I very much enjoyed
  193. teaching the course organized in this way, and even better, many of
  194. the students learned a lot and got excited about compilers.
  195. I returned to teach at Indiana University in 2013. In my absence the
  196. compiler course had switched from the front-to-back organization to a
  197. back-to-front organization. Seeing how well the incremental approach
  198. worked at Colorado, I started porting and adapting the structure of
  199. the Colorado course back into the land of Scheme. In the meantime
  200. Indiana University had moved on from Scheme to Racket, so the course
  201. is now about compiling a subset of Racket (and Typed Racket) to the
  202. x86 assembly language. The compiler is implemented in
  203. Racket~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book I
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study compilers at Indiana University. Many of
  209. the compiler design decisions in this book are drawn from the
  210. assignment descriptions of \cite{Dybvig:2010aa}. I have captured what
  211. I think are the most important topics from \cite{Dybvig:2010aa} but
  212. have omitted topics that are less interesting conceptually. I have
  213. also made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we I the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  226. It is helpful but not necessary for the student to have prior exposure
  227. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  228. from a computer systems
  229. course~\citep{Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %
  232. We follow the System V calling
  233. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  234. assembly code that we generate will work properly with our runtime
  235. system (written in C) when it is compiled using the GNU C compiler
  236. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  237. adjustments are needed for MacOS which we note as they arise.)
  238. %
  239. When running on the Microsoft Windows operating system, the GNU C
  240. compiler follows the Microsoft x64 calling
  241. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  242. code that we generate will \emph{not} work properly with our runtime
  243. system on Windows. One option to consider for using a Windows computer
  244. is to run a virtual machine with Linux as the guest operating system.
  245. %\section*{Structure of book}
  246. % You might want to add short description about each chapter in this book.
  247. %\section*{About the companion website}
  248. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  249. %\begin{itemize}
  250. % \item A link to (freely downlodable) latest version of this document.
  251. % \item Link to download LaTeX source for this document.
  252. % \item Miscellaneous material (e.g. suggested readings etc).
  253. %\end{itemize}
  254. \section*{Acknowledgments}
  255. Many people have contributed to the ideas, techniques, and
  256. organization of this book and have taught courses based on it. We
  257. especially thank John Clements, Bor-Yuh Evan Chang, Kent Dybvig,
  258. Daniel P. Friedman, Ronald Garcia, Abdulaziz Ghuloum, Andrew Keep, Jay
  259. McCarthy, Nate Nystrom, Dipanwita Sarkar, Oscar Waddell, and Michael
  260. Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.
  276. \index{concrete syntax}
  277. \index{abstract syntax}
  278. \index{abstract syntax tree}
  279. \index{AST}
  280. \index{program}
  281. \index{parse}
  282. %
  283. The translation from concrete syntax to abstract syntax is a process
  284. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  285. and implementation of parsing in this book. A parser is provided in
  286. the supporting materials for translating from concrete syntax to
  287. abstract syntax for the languages used in this book.
  288. ASTs can be represented in many different ways inside the compiler,
  289. depending on the programming language used to write the compiler.
  290. %
  291. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  292. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  293. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  294. and pattern matching to inspect individual nodes in an AST
  295. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  296. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  297. chapter provides an brief introduction to these ideas.
  298. \index{struct}
  299. \section{Abstract Syntax Trees and Racket Structures}
  300. \label{sec:ast}
  301. Compilers use abstract syntax trees to represent programs because
  302. compilers often need to ask questions like: for a given part of a
  303. program, what kind of language feature is it? What are the sub-parts
  304. of this part of the program? Consider the program on the left and its
  305. AST on the right. This program is an addition and it has two
  306. sub-parts, a read operation and a negation. The negation has another
  307. sub-part, the integer constant \code{8}. By using a tree to represent
  308. the program, we can easily follow the links to go from one part of a
  309. program to its sub-parts.
  310. \begin{center}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{lstlisting}
  313. (+ (read) (- 8))
  314. \end{lstlisting}
  315. \end{minipage}
  316. \begin{minipage}{0.4\textwidth}
  317. \begin{equation}
  318. \begin{tikzpicture}
  319. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  320. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  321. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  322. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  323. \draw[->] (plus) to (read);
  324. \draw[->] (plus) to (minus);
  325. \draw[->] (minus) to (8);
  326. \end{tikzpicture}
  327. \label{eq:arith-prog}
  328. \end{equation}
  329. \end{minipage}
  330. \end{center}
  331. We use the standard terminology for trees to describe ASTs: each
  332. circle above is called a \emph{node}. The arrows connect a node to its
  333. \emph{children} (which are also nodes). The top-most node is the
  334. \emph{root}. Every node except for the root has a \emph{parent} (the
  335. node it is the child of). If a node has no children, it is a
  336. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  337. \index{node}
  338. \index{children}
  339. \index{root}
  340. \index{parent}
  341. \index{leaf}
  342. \index{internal node}
  343. %% Recall that an \emph{symbolic expression} (S-expression) is either
  344. %% \begin{enumerate}
  345. %% \item an atom, or
  346. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  347. %% where $e_1$ and $e_2$ are each an S-expression.
  348. %% \end{enumerate}
  349. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  350. %% null value \code{'()}, etc. We can create an S-expression in Racket
  351. %% simply by writing a backquote (called a quasi-quote in Racket)
  352. %% followed by the textual representation of the S-expression. It is
  353. %% quite common to use S-expressions to represent a list, such as $a, b
  354. %% ,c$ in the following way:
  355. %% \begin{lstlisting}
  356. %% `(a . (b . (c . ())))
  357. %% \end{lstlisting}
  358. %% Each element of the list is in the first slot of a pair, and the
  359. %% second slot is either the rest of the list or the null value, to mark
  360. %% the end of the list. Such lists are so common that Racket provides
  361. %% special notation for them that removes the need for the periods
  362. %% and so many parenthesis:
  363. %% \begin{lstlisting}
  364. %% `(a b c)
  365. %% \end{lstlisting}
  366. %% The following expression creates an S-expression that represents AST
  367. %% \eqref{eq:arith-prog}.
  368. %% \begin{lstlisting}
  369. %% `(+ (read) (- 8))
  370. %% \end{lstlisting}
  371. %% When using S-expressions to represent ASTs, the convention is to
  372. %% represent each AST node as a list and to put the operation symbol at
  373. %% the front of the list. The rest of the list contains the children. So
  374. %% in the above case, the root AST node has operation \code{`+} and its
  375. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  376. %% diagram \eqref{eq:arith-prog}.
  377. %% To build larger S-expressions one often needs to splice together
  378. %% several smaller S-expressions. Racket provides the comma operator to
  379. %% splice an S-expression into a larger one. For example, instead of
  380. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. %% we could have first created an S-expression for AST
  382. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  383. %% S-expression.
  384. %% \begin{lstlisting}
  385. %% (define ast1.4 `(- 8))
  386. %% (define ast1.1 `(+ (read) ,ast1.4))
  387. %% \end{lstlisting}
  388. %% In general, the Racket expression that follows the comma (splice)
  389. %% can be any expression that produces an S-expression.
  390. We define a Racket \code{struct} for each kind of node. For this
  391. chapter we require just two kinds of nodes: one for integer constants
  392. and one for primitive operations. The following is the \code{struct}
  393. definition for integer constants.
  394. \begin{lstlisting}
  395. (struct Int (value))
  396. \end{lstlisting}
  397. An integer node includes just one thing: the integer value.
  398. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  399. \begin{lstlisting}
  400. (define eight (Int 8))
  401. \end{lstlisting}
  402. We say that the value created by \code{(Int 8)} is an
  403. \emph{instance} of the \code{Int} structure.
  404. The following is the \code{struct} definition for primitives operations.
  405. \begin{lstlisting}
  406. (struct Prim (op arg*))
  407. \end{lstlisting}
  408. A primitive operation node includes an operator symbol \code{op}
  409. and a list of children \code{arg*}. For example, to create
  410. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  411. \begin{lstlisting}
  412. (define neg-eight (Prim '- (list eight)))
  413. \end{lstlisting}
  414. Primitive operations may have zero or more children. The \code{read}
  415. operator has zero children:
  416. \begin{lstlisting}
  417. (define rd (Prim 'read '()))
  418. \end{lstlisting}
  419. whereas the addition operator has two children:
  420. \begin{lstlisting}
  421. (define ast1.1 (Prim '+ (list rd neg-eight)))
  422. \end{lstlisting}
  423. We have made a design choice regarding the \code{Prim} structure.
  424. Instead of using one structure for many different operations
  425. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  426. structure for each operation, as follows.
  427. \begin{lstlisting}
  428. (struct Read ())
  429. (struct Add (left right))
  430. (struct Neg (value))
  431. \end{lstlisting}
  432. The reason we choose to use just one structure is that in many parts
  433. of the compiler the code for the different primitive operators is the
  434. same, so we might as well just write that code once, which is enabled
  435. by using a single structure.
  436. When compiling a program such as \eqref{eq:arith-prog}, we need to
  437. know that the operation associated with the root node is addition and
  438. we need to be able to access its two children. Racket provides pattern
  439. matching over structures to support these kinds of queries, as we
  440. see in Section~\ref{sec:pattern-matching}.
  441. In this book, we often write down the concrete syntax of a program
  442. even when we really have in mind the AST because the concrete syntax
  443. is more concise. We recommend that, in your mind, you always think of
  444. programs as abstract syntax trees.
  445. \section{Grammars}
  446. \label{sec:grammar}
  447. \index{integer}
  448. \index{literal}
  449. \index{constant}
  450. A programming language can be thought of as a \emph{set} of programs.
  451. The set is typically infinite (one can always create larger and larger
  452. programs), so one cannot simply describe a language by listing all of
  453. the programs in the language. Instead we write down a set of rules, a
  454. \emph{grammar}, for building programs. Grammars are often used to
  455. define the concrete syntax of a language, but they can also be used to
  456. describe the abstract syntax. We write our rules in a variant of
  457. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  458. \index{Backus-Naur Form}\index{BNF}
  459. As an example, we describe a small language, named $R_0$, that consists of
  460. integers and arithmetic operations.
  461. \index{grammar}
  462. The first grammar rule for the abstract syntax of $R_0$ says that an
  463. instance of the \code{Int} structure is an expression:
  464. \begin{equation}
  465. \Exp ::= \INT{\Int} \label{eq:arith-int}
  466. \end{equation}
  467. %
  468. Each rule has a left-hand-side and a right-hand-side. The way to read
  469. a rule is that if you have all the program parts on the
  470. right-hand-side, then you can create an AST node and categorize it
  471. according to the left-hand-side.
  472. %
  473. A name such as $\Exp$ that is
  474. defined by the grammar rules is a \emph{non-terminal}.
  475. \index{non-terminal}
  476. %
  477. The name $\Int$ is a also a non-terminal, but instead of defining it
  478. with a grammar rule, we define it with the following explanation. We
  479. make the simplifying design decision that all of the languages in this
  480. book only handle machine-representable integers. On most modern
  481. machines this corresponds to integers represented with 64-bits, i.e.,
  482. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  483. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  484. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  485. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  486. that the sequence of decimals represent an integer in range $-2^{62}$
  487. to $2^{62}-1$.
  488. The second grammar rule is the \texttt{read} operation that receives
  489. an input integer from the user of the program.
  490. \begin{equation}
  491. \Exp ::= \READ{} \label{eq:arith-read}
  492. \end{equation}
  493. The third rule says that, given an $\Exp$ node, you can build another
  494. $\Exp$ node by negating it.
  495. \begin{equation}
  496. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  497. \end{equation}
  498. Symbols in typewriter font such as \key{-} and \key{read} are
  499. \emph{terminal} symbols and must literally appear in the program for
  500. the rule to be applicable.
  501. \index{terminal}
  502. We can apply the rules to build ASTs in the $R_0$
  503. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  504. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  505. an $\Exp$.
  506. \begin{center}
  507. \begin{minipage}{0.4\textwidth}
  508. \begin{lstlisting}
  509. (Prim '- (list (Int 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \begin{minipage}{0.25\textwidth}
  513. \begin{equation}
  514. \begin{tikzpicture}
  515. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  516. \node[draw, circle] (8) at (0, -1.2) {$8$};
  517. \draw[->] (minus) to (8);
  518. \end{tikzpicture}
  519. \label{eq:arith-neg8}
  520. \end{equation}
  521. \end{minipage}
  522. \end{center}
  523. The next grammar rule defines addition expressions:
  524. \begin{equation}
  525. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  526. \end{equation}
  527. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  528. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  529. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  530. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  531. to show that
  532. \begin{lstlisting}
  533. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  534. \end{lstlisting}
  535. is an $\Exp$ in the $R_0$ language.
  536. If you have an AST for which the above rules do not apply, then the
  537. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  538. is not in $R_0$ because there are no rules for \code{+} with only one
  539. argument, nor for \key{-} with two arguments. Whenever we define a
  540. language with a grammar, the language only includes those programs
  541. that are justified by the rules.
  542. The last grammar rule for $R_0$ states that there is a \code{Program}
  543. node to mark the top of the whole program:
  544. \[
  545. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  546. \]
  547. The \code{Program} structure is defined as follows
  548. \begin{lstlisting}
  549. (struct Program (info body))
  550. \end{lstlisting}
  551. where \code{body} is an expression. In later chapters, the \code{info}
  552. part will be used to store auxiliary information but for now it is
  553. just the empty list.
  554. It is common to have many grammar rules with the same left-hand side
  555. but different right-hand sides, such as the rules for $\Exp$ in the
  556. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  557. combine several right-hand-sides into a single rule.
  558. We collect all of the grammar rules for the abstract syntax of $R_0$
  559. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  560. defined in Figure~\ref{fig:r0-concrete-syntax}.
  561. The \code{read-program} function provided in \code{utilities.rkt} of
  562. the support materials reads a program in from a file (the sequence of
  563. characters in the concrete syntax of Racket) and parses it into an
  564. abstract syntax tree. See the description of \code{read-program} in
  565. Appendix~\ref{appendix:utilities} for more details.
  566. \begin{figure}[tp]
  567. \fbox{
  568. \begin{minipage}{0.96\textwidth}
  569. \[
  570. \begin{array}{rcl}
  571. \begin{array}{rcl}
  572. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  573. R_0 &::=& \Exp
  574. \end{array}
  575. \end{array}
  576. \]
  577. \end{minipage}
  578. }
  579. \caption{The concrete syntax of $R_0$.}
  580. \label{fig:r0-concrete-syntax}
  581. \end{figure}
  582. \begin{figure}[tp]
  583. \fbox{
  584. \begin{minipage}{0.96\textwidth}
  585. \[
  586. \begin{array}{rcl}
  587. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  588. &\mid& \ADD{\Exp}{\Exp} \\
  589. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  590. \end{array}
  591. \]
  592. \end{minipage}
  593. }
  594. \caption{The abstract syntax of $R_0$.}
  595. \label{fig:r0-syntax}
  596. \end{figure}
  597. \section{Pattern Matching}
  598. \label{sec:pattern-matching}
  599. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  600. the parts of an AST node. Racket provides the \texttt{match} form to
  601. access the parts of a structure. Consider the following example and
  602. the output on the right. \index{match} \index{pattern matching}
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (match ast1.1
  607. [(Prim op (list child1 child2))
  608. (print op)])
  609. \end{lstlisting}
  610. \end{minipage}
  611. \vrule
  612. \begin{minipage}{0.25\textwidth}
  613. \begin{lstlisting}
  614. '+
  615. \end{lstlisting}
  616. \end{minipage}
  617. \end{center}
  618. In the above example, the \texttt{match} form takes the AST
  619. \eqref{eq:arith-prog} and binds its parts to the three pattern
  620. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  621. general, a match clause consists of a \emph{pattern} and a
  622. \emph{body}.
  623. \index{pattern}
  624. Patterns are recursively defined to be either a pattern
  625. variable, a structure name followed by a pattern for each of the
  626. structure's arguments, or an S-expression (symbols, lists, etc.).
  627. (See Chapter 12 of The Racket
  628. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  629. and Chapter 9 of The Racket
  630. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  631. for a complete description of \code{match}.)
  632. %
  633. The body of a match clause may contain arbitrary Racket code. The
  634. pattern variables can be used in the scope of the body.
  635. A \code{match} form may contain several clauses, as in the following
  636. function \code{leaf?} that recognizes when an $R_0$ node is
  637. a leaf. The \code{match} proceeds through the clauses in order,
  638. checking whether the pattern can match the input AST. The
  639. body of the first clause that matches is executed. The output of
  640. \code{leaf?} for several ASTs is shown on the right.
  641. \begin{center}
  642. \begin{minipage}{0.6\textwidth}
  643. \begin{lstlisting}
  644. (define (leaf? arith)
  645. (match arith
  646. [(Int n) #t]
  647. [(Prim 'read '()) #t]
  648. [(Prim '- (list c1)) #f]
  649. [(Prim '+ (list c1 c2)) #f]))
  650. (leaf? (Prim 'read '()))
  651. (leaf? (Prim '- (list (Int 8))))
  652. (leaf? (Int 8))
  653. \end{lstlisting}
  654. \end{minipage}
  655. \vrule
  656. \begin{minipage}{0.25\textwidth}
  657. \begin{lstlisting}
  658. #t
  659. #f
  660. #t
  661. \end{lstlisting}
  662. \end{minipage}
  663. \end{center}
  664. When writing a \code{match}, we refer to the grammar definition to
  665. identify which non-terminal we are expecting to match against, then we
  666. make sure that 1) we have one clause for each alternative of that
  667. non-terminal and 2) that the pattern in each clause corresponds to the
  668. corresponding right-hand side of a grammar rule. For the \code{match}
  669. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  670. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  671. alternatives, so the \code{match} has 4 clauses. The pattern in each
  672. clause corresponds to the right-hand side of a grammar rule. For
  673. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  674. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  675. patterns, replace non-terminals such as $\Exp$ with pattern variables
  676. of your choice (e.g. \code{c1} and \code{c2}).
  677. \section{Recursion}
  678. \label{sec:recursion}
  679. \index{recursive function}
  680. Programs are inherently recursive. For example, an $R_0$ expression is
  681. often made of smaller expressions. Thus, the natural way to process an
  682. entire program is with a recursive function. As a first example of
  683. such a recursive function, we define \texttt{exp?} below, which takes
  684. an arbitrary value and determines whether or not it is an $R_0$
  685. expression.
  686. %
  687. When a recursive function is defined using a sequence of match clauses
  688. that correspond to a grammar, and the body of each clause makes a
  689. recursive call on each child node, then we say the function is defined
  690. by \emph{structural recursion}\footnote{This principle of structuring
  691. code according to the data definition is advocated in the book
  692. \emph{How to Design Programs}
  693. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  694. define a second function, named \code{R0?}, that determines whether a
  695. value is an $R_0$ program. In general we can expect to write one
  696. recursive function to handle each non-terminal in a grammar.
  697. \index{structural recursion}
  698. %
  699. \begin{center}
  700. \begin{minipage}{0.7\textwidth}
  701. \begin{lstlisting}
  702. (define (exp? ast)
  703. (match ast
  704. [(Int n) #t]
  705. [(Prim 'read '()) #t]
  706. [(Prim '- (list e)) (exp? e)]
  707. [(Prim '+ (list e1 e2))
  708. (and (exp? e1) (exp? e2))]
  709. [else #f]))
  710. (define (R0? ast)
  711. (match ast
  712. [(Program '() e) (exp? e)]
  713. [else #f]))
  714. (R0? (Program '() ast1.1)
  715. (R0? (Program '()
  716. (Prim '- (list (Prim 'read '())
  717. (Prim '+ (list (Num 8)))))))
  718. \end{lstlisting}
  719. \end{minipage}
  720. \vrule
  721. \begin{minipage}{0.25\textwidth}
  722. \begin{lstlisting}
  723. #t
  724. #f
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. You may be tempted to merge the two functions into one, like this:
  729. \begin{center}
  730. \begin{minipage}{0.5\textwidth}
  731. \begin{lstlisting}
  732. (define (R0? ast)
  733. (match ast
  734. [(Int n) #t]
  735. [(Prim 'read '()) #t]
  736. [(Prim '- (list e)) (R0? e)]
  737. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  738. [(Program '() e) (R0? e)]
  739. [else #f]))
  740. \end{lstlisting}
  741. \end{minipage}
  742. \end{center}
  743. %
  744. Sometimes such a trick will save a few lines of code, especially when
  745. it comes to the \code{Program} wrapper. Yet this style is generally
  746. \emph{not} recommended because it can get you into trouble.
  747. %
  748. For example, the above function is subtly wrong:
  749. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  750. will return true, when it should return false.
  751. %% NOTE FIXME - must check for consistency on this issue throughout.
  752. \section{Interpreters}
  753. \label{sec:interp-R0}
  754. \index{interpreter}
  755. The meaning, or semantics, of a program is typically defined in the
  756. specification of the language. For example, the Scheme language is
  757. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  758. defined in its reference manual~\citep{plt-tr}. In this book we use an
  759. interpreter to define the meaning of each language that we consider,
  760. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  761. interpreter that is designated (by some people) as the definition of a
  762. language is called a \emph{definitional interpreter}.
  763. \index{definitional interpreter}
  764. We warm up by creating a definitional interpreter for the $R_0$ language, which
  765. serves as a second example of structural recursion. The
  766. \texttt{interp-R0} function is defined in
  767. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  768. input program followed by a call to the \lstinline{interp-exp} helper
  769. function, which in turn has one match clause per grammar rule for
  770. $R_0$ expressions.
  771. \begin{figure}[tp]
  772. \begin{lstlisting}
  773. (define (interp-exp e)
  774. (match e
  775. [(Int n) n]
  776. [(Prim 'read '())
  777. (define r (read))
  778. (cond [(fixnum? r) r]
  779. [else (error 'interp-R0 "expected an integer" r)])]
  780. [(Prim '- (list e))
  781. (define v (interp-exp e))
  782. (fx- 0 v)]
  783. [(Prim '+ (list e1 e2))
  784. (define v1 (interp-exp e1))
  785. (define v2 (interp-exp e2))
  786. (fx+ v1 v2)]
  787. ))
  788. (define (interp-R0 p)
  789. (match p
  790. [(Program '() e) (interp-exp e)]
  791. ))
  792. \end{lstlisting}
  793. \caption{Interpreter for the $R_0$ language.}
  794. \label{fig:interp-R0}
  795. \end{figure}
  796. Let us consider the result of interpreting a few $R_0$ programs. The
  797. following program adds two integers.
  798. \begin{lstlisting}
  799. (+ 10 32)
  800. \end{lstlisting}
  801. The result is \key{42}. We wrote the above program in concrete syntax,
  802. whereas the parsed abstract syntax is:
  803. \begin{lstlisting}
  804. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  805. \end{lstlisting}
  806. The next example demonstrates that expressions may be nested within
  807. each other, in this case nesting several additions and negations.
  808. \begin{lstlisting}
  809. (+ 10 (- (+ 12 20)))
  810. \end{lstlisting}
  811. What is the result of the above program?
  812. As mentioned previously, the $R_0$ language does not support
  813. arbitrarily-large integers, but only $63$-bit integers, so we
  814. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  815. in Racket.
  816. Suppose
  817. \[
  818. n = 999999999999999999
  819. \]
  820. which indeed fits in $63$-bits. What happens when we run the
  821. following program in our interpreter?
  822. \begin{lstlisting}
  823. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  824. \end{lstlisting}
  825. It produces an error:
  826. \begin{lstlisting}
  827. fx+: result is not a fixnum
  828. \end{lstlisting}
  829. We establish the convention that if running the definitional
  830. interpreter on a program produces an error, then the meaning of that
  831. program is \emph{unspecified}. That means a compiler for the language
  832. is under no obligations regarding that program; it may or may not
  833. produce an executable, and if it does, that executable can do
  834. anything. This convention applies to the languages defined in this
  835. book, as a way to simplify the student's task of implementing them,
  836. but this convention is not applicable to all programming languages.
  837. \index{unspecified behavior}
  838. Moving on to the last feature of the $R_0$ language, the \key{read}
  839. operation prompts the user of the program for an integer. Recall that
  840. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  841. \code{8}. So if we run
  842. \begin{lstlisting}
  843. (interp-R0 (Program '() ast1.1))
  844. \end{lstlisting}
  845. and if the input is \code{50}, then we get the answer to life, the
  846. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  847. Guide to the Galaxy} by Douglas Adams.}
  848. We include the \key{read} operation in $R_0$ so a clever student
  849. cannot implement a compiler for $R_0$ that simply runs the interpreter
  850. during compilation to obtain the output and then generates the trivial
  851. code to produce the output. (Yes, a clever student did this in the
  852. first instance of this course.)
  853. The job of a compiler is to translate a program in one language into a
  854. program in another language so that the output program behaves the
  855. same way as the input program does according to its definitional
  856. interpreter. This idea is depicted in the following diagram. Suppose
  857. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  858. interpreter for each language. Suppose that the compiler translates
  859. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  860. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  861. respective interpreters with input $i$ should yield the same output
  862. $o$.
  863. \begin{equation} \label{eq:compile-correct}
  864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  865. \node (p1) at (0, 0) {$P_1$};
  866. \node (p2) at (3, 0) {$P_2$};
  867. \node (o) at (3, -2.5) {$o$};
  868. \path[->] (p1) edge [above] node {compile} (p2);
  869. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  870. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  871. \end{tikzpicture}
  872. \end{equation}
  873. In the next section we see our first example of a compiler.
  874. \section{Example Compiler: a Partial Evaluator}
  875. \label{sec:partial-evaluation}
  876. In this section we consider a compiler that translates $R_0$ programs
  877. into $R_0$ programs that may be more efficient, that is, this compiler
  878. is an optimizer. This optimizer eagerly computes the parts of the
  879. program that do not depend on any inputs, a process known as
  880. \emph{partial evaluation}~\cite{Jones:1993uq}.
  881. \index{partial evaluation}
  882. For example, given the following program
  883. \begin{lstlisting}
  884. (+ (read) (- (+ 5 3)))
  885. \end{lstlisting}
  886. our compiler will translate it into the program
  887. \begin{lstlisting}
  888. (+ (read) -8)
  889. \end{lstlisting}
  890. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  891. evaluator for the $R_0$ language. The output of the partial evaluator
  892. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  893. recursion over $\Exp$ is captured in the \code{pe-exp} function
  894. whereas the code for partially evaluating the negation and addition
  895. operations is factored into two separate helper functions:
  896. \code{pe-neg} and \code{pe-add}. The input to these helper
  897. functions is the output of partially evaluating the children.
  898. \begin{figure}[tp]
  899. \begin{lstlisting}
  900. (define (pe-neg r)
  901. (match r
  902. [(Int n) (Int (fx- 0 n))]
  903. [else (Prim '- (list r))]))
  904. (define (pe-add r1 r2)
  905. (match* (r1 r2)
  906. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  907. [(_ _) (Prim '+ (list r1 r2))]))
  908. (define (pe-exp e)
  909. (match e
  910. [(Int n) (Int n)]
  911. [(Prim 'read '()) (Prim 'read '())]
  912. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  913. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  914. ))
  915. (define (pe-R0 p)
  916. (match p
  917. [(Program '() e) (Program '() (pe-exp e))]
  918. ))
  919. \end{lstlisting}
  920. \caption{A partial evaluator for $R_0$ expressions.}
  921. \label{fig:pe-arith}
  922. \end{figure}
  923. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  924. arguments are integers and if they are, perform the appropriate
  925. arithmetic. Otherwise, they create an AST node for the operation
  926. (either negation or addition).
  927. To gain some confidence that the partial evaluator is correct, we can
  928. test whether it produces programs that get the same result as the
  929. input programs. That is, we can test whether it satisfies Diagram
  930. \eqref{eq:compile-correct}. The following code runs the partial
  931. evaluator on several examples and tests the output program. The
  932. \texttt{parse-program} and \texttt{assert} functions are defined in
  933. Appendix~\ref{appendix:utilities}.\\
  934. \begin{minipage}{1.0\textwidth}
  935. \begin{lstlisting}
  936. (define (test-pe p)
  937. (assert "testing pe-R0"
  938. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  939. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  940. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  941. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  942. \end{lstlisting}
  943. \end{minipage}
  944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  945. \chapter{Integers and Variables}
  946. \label{ch:int-exp}
  947. This chapter is about compiling the subset of Racket that includes
  948. integer arithmetic and local variable binding, which we name $R_1$, to
  949. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  950. to x86-64 simply as x86. The chapter begins with a description of the
  951. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  952. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  953. discuss only what is needed for compiling $R_1$. We introduce more of
  954. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  955. reflect on their differences and come up with a plan to break down the
  956. translation from $R_1$ to x86 into a handful of steps
  957. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  958. chapter give detailed hints regarding each step
  959. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  960. to give enough hints that the well-prepared reader, together with a
  961. few friends, can implement a compiler from $R_1$ to x86 in a couple
  962. weeks while at the same time leaving room for some fun and creativity.
  963. To give the reader a feeling for the scale of this first compiler, the
  964. instructor solution for the $R_1$ compiler is less than 500 lines of
  965. code.
  966. \section{The $R_1$ Language}
  967. \label{sec:s0}
  968. \index{variable}
  969. The $R_1$ language extends the $R_0$ language with variable
  970. definitions. The concrete syntax of the $R_1$ language is defined by
  971. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  972. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  973. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  974. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  975. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  976. \key{Program} struct to mark the top of the program.
  977. %% The $\itm{info}$
  978. %% field of the \key{Program} structure contains an \emph{association
  979. %% list} (a list of key-value pairs) that is used to communicate
  980. %% auxiliary data from one compiler pass the next.
  981. Despite the simplicity of the $R_1$ language, it is rich enough to
  982. exhibit several compilation techniques.
  983. \begin{figure}[tp]
  984. \centering
  985. \fbox{
  986. \begin{minipage}{0.96\textwidth}
  987. \[
  988. \begin{array}{rcl}
  989. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  990. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  991. R_1 &::=& \Exp
  992. \end{array}
  993. \]
  994. \end{minipage}
  995. }
  996. \caption{The concrete syntax of $R_1$.}
  997. \label{fig:r1-concrete-syntax}
  998. \end{figure}
  999. \begin{figure}[tp]
  1000. \centering
  1001. \fbox{
  1002. \begin{minipage}{0.96\textwidth}
  1003. \[
  1004. \begin{array}{rcl}
  1005. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1006. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1007. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1008. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{The abstract syntax of $R_1$.}
  1014. \label{fig:r1-syntax}
  1015. \end{figure}
  1016. Let us dive further into the syntax and semantics of the $R_1$
  1017. language. The \key{Let} feature defines a variable for use within its
  1018. body and initializes the variable with the value of an expression.
  1019. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1020. The concrete syntax for \key{Let} is
  1021. \begin{lstlisting}
  1022. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1023. \end{lstlisting}
  1024. For example, the following program initializes \code{x} to $32$ and then
  1025. evaluates the body \code{(+ 10 x)}, producing $42$.
  1026. \begin{lstlisting}
  1027. (let ([x (+ 12 20)]) (+ 10 x))
  1028. \end{lstlisting}
  1029. When there are multiple \key{let}'s for the same variable, the closest
  1030. enclosing \key{let} is used. That is, variable definitions overshadow
  1031. prior definitions. Consider the following program with two \key{let}'s
  1032. that define variables named \code{x}. Can you figure out the result?
  1033. \begin{lstlisting}
  1034. (let ([x 32]) (+ (let ([x 10]) x) x))
  1035. \end{lstlisting}
  1036. For the purposes of depicting which variable uses correspond to which
  1037. definitions, the following shows the \code{x}'s annotated with
  1038. subscripts to distinguish them. Double check that your answer for the
  1039. above is the same as your answer for this annotated version of the
  1040. program.
  1041. \begin{lstlisting}
  1042. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1043. \end{lstlisting}
  1044. The initializing expression is always evaluated before the body of the
  1045. \key{let}, so in the following, the \key{read} for \code{x} is
  1046. performed before the \key{read} for \code{y}. Given the input
  1047. $52$ then $10$, the following produces $42$ (not $-42$).
  1048. \begin{lstlisting}
  1049. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1050. \end{lstlisting}
  1051. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1052. \small
  1053. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1054. An \emph{association list} (alist) is a list of key-value pairs.
  1055. For example, we can map people to their ages with an alist.
  1056. \index{alist}\index{association list}
  1057. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1058. (define ages
  1059. '((jane . 25) (sam . 24) (kate . 45)))
  1060. \end{lstlisting}
  1061. The \emph{dictionary} interface is for mapping keys to values.
  1062. Every alist implements this interface. \index{dictionary} The package
  1063. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1064. provides many functions for working with dictionaries. Here
  1065. are a few of them:
  1066. \begin{description}
  1067. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1068. returns the value associated with the given $\itm{key}$.
  1069. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1070. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1071. but otherwise is the same as $\itm{dict}$.
  1072. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1073. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1074. of keys and values in $\itm{dict}$. For example, the following
  1075. creates a new alist in which the ages are incremented.
  1076. \end{description}
  1077. \vspace{-10pt}
  1078. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1079. (for/list ([(k v) (in-dict ages)])
  1080. (cons k (add1 v)))
  1081. \end{lstlisting}
  1082. \end{tcolorbox}
  1083. \end{wrapfigure}
  1084. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1085. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1086. \key{match} clauses for variables and for \key{let}. For \key{let},
  1087. we need a way to communicate the value of a variable to all the uses
  1088. of a variable. To accomplish this, we maintain a mapping from
  1089. variables to values. Throughout the compiler we often need to map
  1090. variables to information about them. We refer to these mappings as
  1091. \emph{environments}\index{environment}
  1092. \footnote{Another common term for environment in the compiler
  1093. literature is \emph{symbol table}\index{symbol table}.}.
  1094. For simplicity, we use an
  1095. association list (alist) to represent the environment. The sidebar to
  1096. the right gives a brief introduction to alists and the
  1097. \code{racket/dict} package. The \code{interp-R1} function takes the
  1098. current environment, \code{env}, as an extra parameter. When the
  1099. interpreter encounters a variable, it finds the corresponding value
  1100. using the \code{dict-ref} function. When the interpreter encounters a
  1101. \key{Let}, it evaluates the initializing expression, extends the
  1102. environment with the result value bound to the variable, using
  1103. \code{dict-set}, then evaluates the body of the \key{Let}.
  1104. \begin{figure}[tp]
  1105. \begin{lstlisting}
  1106. (define (interp-exp env)
  1107. (lambda (e)
  1108. (match e
  1109. [(Int n) n]
  1110. [(Prim 'read '())
  1111. (define r (read))
  1112. (cond [(fixnum? r) r]
  1113. [else (error 'interp-R1 "expected an integer" r)])]
  1114. [(Prim '- (list e))
  1115. (define v ((interp-exp env) e))
  1116. (fx- 0 v)]
  1117. [(Prim '+ (list e1 e2))
  1118. (define v1 ((interp-exp env) e1))
  1119. (define v2 ((interp-exp env) e2))
  1120. (fx+ v1 v2)]
  1121. [(Var x) (dict-ref env x)]
  1122. [(Let x e body)
  1123. (define new-env (dict-set env x ((interp-exp env) e)))
  1124. ((interp-exp new-env) body)]
  1125. )))
  1126. (define (interp-R1 p)
  1127. (match p
  1128. [(Program '() e) ((interp-exp '()) e)]
  1129. ))
  1130. \end{lstlisting}
  1131. \caption{Interpreter for the $R_1$ language.}
  1132. \label{fig:interp-R1}
  1133. \end{figure}
  1134. The goal for this chapter is to implement a compiler that translates
  1135. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1136. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1137. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1138. is, they both output the same integer $n$. We depict this correctness
  1139. criteria in the following diagram.
  1140. \[
  1141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1142. \node (p1) at (0, 0) {$P_1$};
  1143. \node (p2) at (4, 0) {$P_2$};
  1144. \node (o) at (4, -2) {$n$};
  1145. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1146. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1147. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1148. \end{tikzpicture}
  1149. \]
  1150. In the next section we introduce enough of the x86 assembly
  1151. language to compile $R_1$.
  1152. \section{The x86$_0$ Assembly Language}
  1153. \label{sec:x86}
  1154. \index{x86}
  1155. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1156. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1157. %
  1158. An x86 program begins with a \code{main} label followed by a sequence
  1159. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1160. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1161. instructions.\index{instruction}
  1162. %
  1163. An x86 program is stored in the computer's memory and the computer has
  1164. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1165. that points to the address of the next
  1166. instruction to be executed. For most instructions, once the
  1167. instruction is executed, the program counter is incremented to point
  1168. to the immediately following instruction in memory. Most x86
  1169. instructions take two operands, where each operand is either an
  1170. integer constant (called \emph{immediate value}\index{immediate value}),
  1171. a \emph{register}\index{register}, or a memory location.
  1172. A register is a special kind of variable. Each
  1173. one holds a 64-bit value; there are 16 registers in the computer and
  1174. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1175. as a mapping of 64-bit addresses to 64-bit values%
  1176. \footnote{This simple story suffices for describing how sequential
  1177. programs access memory but is not sufficient for multi-threaded
  1178. programs. However, multi-threaded execution is beyond the scope of
  1179. this book.}.
  1180. %
  1181. We use the AT\&T syntax expected by the GNU assembler, which comes
  1182. with the \key{gcc} compiler that we use for compiling assembly code to
  1183. machine code.
  1184. %
  1185. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1186. the x86 instructions used in this book.
  1187. % to do: finish treatment of imulq
  1188. % it's needed for vector's in R6/R7
  1189. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1190. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1191. && \key{r8} \mid \key{r9} \mid \key{r10}
  1192. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1193. \mid \key{r14} \mid \key{r15}}
  1194. \begin{figure}[tp]
  1195. \fbox{
  1196. \begin{minipage}{0.96\textwidth}
  1197. \[
  1198. \begin{array}{lcl}
  1199. \Reg &::=& \allregisters{} \\
  1200. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1201. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1202. \key{subq} \; \Arg\key{,} \Arg \mid
  1203. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1204. && \key{callq} \; \mathit{label} \mid
  1205. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1206. && \itm{label}\key{:}\; \Instr \\
  1207. x86_0 &::= & \key{.globl main}\\
  1208. & & \key{main:} \; \Instr\ldots
  1209. \end{array}
  1210. \]
  1211. \end{minipage}
  1212. }
  1213. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1214. \label{fig:x86-0-concrete}
  1215. \end{figure}
  1216. An immediate value is written using the notation \key{\$}$n$ where $n$
  1217. is an integer.
  1218. %
  1219. A register is written with a \key{\%} followed by the register name,
  1220. such as \key{\%rax}.
  1221. %
  1222. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1223. which obtains the address stored in register $r$ and then adds $n$
  1224. bytes to the address. The resulting address is used to either load or
  1225. store to memory depending on whether it occurs as a source or
  1226. destination argument of an instruction.
  1227. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1228. source $s$ and destination $d$, applies the arithmetic operation, then
  1229. writes the result back to the destination $d$.
  1230. %
  1231. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1232. stores the result in $d$.
  1233. %
  1234. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1235. specified by the label and $\key{retq}$ returns from a procedure to
  1236. its caller. The abstract syntax for \code{callq} includes an extra
  1237. integer field that represents the arity (number of parameters) of the
  1238. function being called.
  1239. %
  1240. We discuss procedure calls in more detail later in this
  1241. chapter and in Chapter~\ref{ch:functions}. The
  1242. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1243. the address of the instruction after the specified label.
  1244. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1245. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1246. \key{main} procedure is externally visible, which is necessary so
  1247. that the operating system can call it. The label \key{main:}
  1248. indicates the beginning of the \key{main} procedure which is where
  1249. the operating system starts executing this program. The instruction
  1250. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1251. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1252. $10$ in \key{rax} and puts the result, $42$, back into
  1253. \key{rax}.
  1254. %
  1255. The last instruction, \key{retq}, finishes the \key{main} function by
  1256. returning the integer in \key{rax} to the operating system. The
  1257. operating system interprets this integer as the program's exit
  1258. code. By convention, an exit code of 0 indicates that a program
  1259. completed successfully, and all other exit codes indicate various
  1260. errors. Nevertheless, we return the result of the program as the exit
  1261. code.
  1262. %\begin{wrapfigure}{r}{2.25in}
  1263. \begin{figure}[tbp]
  1264. \begin{lstlisting}
  1265. .globl main
  1266. main:
  1267. movq $10, %rax
  1268. addq $32, %rax
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p0-x86}
  1273. %\end{wrapfigure}
  1274. \end{figure}
  1275. Unfortunately, x86 varies in a couple ways depending on what operating
  1276. system it is assembled in. The code examples shown here are correct on
  1277. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1278. labels like \key{main} must be prefixed with an underscore, as in
  1279. \key{\_main}.
  1280. We exhibit the use of memory for storing intermediate results in the
  1281. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1282. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1283. memory called the \emph{procedure call stack} (or \emph{stack} for
  1284. short). \index{stack}\index{procedure call stack} The stack consists
  1285. of a separate \emph{frame}\index{frame} for each procedure call. The
  1286. memory layout for an individual frame is shown in
  1287. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1288. \emph{stack pointer}\index{stack pointer} and points to the item at
  1289. the top of the stack. The stack grows downward in memory, so we
  1290. increase the size of the stack by subtracting from the stack pointer.
  1291. In the context of a procedure call, the \emph{return
  1292. address}\index{return address} is the instruction after the call
  1293. instruction on the caller side. The function call inststruction,
  1294. \code{callq}, pushes the return address onto the stack. The register
  1295. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1296. to access variables associated with the current procedure call. The
  1297. base pointer of the caller is pushed onto the stack after the return
  1298. address. We number the variables from $1$ to $n$. Variable $1$ is
  1299. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1300. $-16\key{(\%rbp)}$, etc.
  1301. \begin{figure}[tbp]
  1302. \begin{lstlisting}
  1303. start:
  1304. movq $10, -8(%rbp)
  1305. negq -8(%rbp)
  1306. movq -8(%rbp), %rax
  1307. addq $52, %rax
  1308. jmp conclusion
  1309. .globl main
  1310. main:
  1311. pushq %rbp
  1312. movq %rsp, %rbp
  1313. subq $16, %rsp
  1314. jmp start
  1315. conclusion:
  1316. addq $16, %rsp
  1317. popq %rbp
  1318. retq
  1319. \end{lstlisting}
  1320. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1321. \label{fig:p1-x86}
  1322. \end{figure}
  1323. \begin{figure}[tbp]
  1324. \centering
  1325. \begin{tabular}{|r|l|} \hline
  1326. Position & Contents \\ \hline
  1327. 8(\key{\%rbp}) & return address \\
  1328. 0(\key{\%rbp}) & old \key{rbp} \\
  1329. -8(\key{\%rbp}) & variable $1$ \\
  1330. -16(\key{\%rbp}) & variable $2$ \\
  1331. \ldots & \ldots \\
  1332. 0(\key{\%rsp}) & variable $n$\\ \hline
  1333. \end{tabular}
  1334. \caption{Memory layout of a frame.}
  1335. \label{fig:frame}
  1336. \end{figure}
  1337. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1338. control is transfered from the operating system to the \code{main}
  1339. function. The operating system issues a \code{callq main} instruction
  1340. which pushes its return address on the stack and then jumps to
  1341. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1342. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1343. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1344. alignment (because the \code{callq} pushed the return address). The
  1345. first three instructions are the typical \emph{prelude}\index{prelude}
  1346. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1347. pointer for the caller onto the stack and subtracts $8$ from the stack
  1348. pointer. At this point the stack pointer is back to being 16-byte
  1349. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1350. base pointer so that it points the location of the old base
  1351. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1352. pointer down to make enough room for storing variables. This program
  1353. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1354. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1355. we are ready to make calls to other functions. The last instruction of
  1356. the prelude is \code{jmp start}, which transfers control to the
  1357. instructions that were generated from the Racket expression \code{(+
  1358. 10 32)}.
  1359. The four instructions under the label \code{start} carry out the work
  1360. of computing \code{(+ 52 (- 10)))}.
  1361. %
  1362. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1363. variable $1$.
  1364. %
  1365. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1366. %
  1367. The following instruction moves the $-10$ from variable $1$ into the
  1368. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1369. the value in \code{rax}, updating its contents to $42$.
  1370. The three instructions under the label \code{conclusion} are the
  1371. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1372. two instructions are necessary to get the state of the machine back to
  1373. where it was at the beginning of the procedure. The instruction
  1374. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1375. old base pointer. The amount added here needs to match the amount that
  1376. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1377. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1378. pointer. The last instruction, \key{retq}, jumps back to the
  1379. procedure that called this one and adds 8 to the stack pointer, which
  1380. returns the stack pointer to where it was prior to the procedure call.
  1381. The compiler needs a convenient representation for manipulating x86
  1382. programs, so we define an abstract syntax for x86 in
  1383. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1384. a subscript $0$ because later we introduce extended versions of this
  1385. assembly language. The main difference compared to the concrete syntax
  1386. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1387. labeled instructions to appear anywhere, but instead organizes
  1388. instructions into a group called a
  1389. \emph{block}\index{block}\index{basic block} and associates a label
  1390. with every block, which is why the \key{CFG} struct (for control-flow
  1391. graph) includes an alist mapping labels to blocks. The reason for this
  1392. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1393. introduce conditional branching. The \code{Block} structure includes
  1394. an $\itm{info}$ field that is not needed for this chapter, but will
  1395. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1396. the $\itm{info}$ field should just contain an empty list. Also,
  1397. regarding the abstract syntax for \code{callq}, the \code{Callq}
  1398. struct includes an integer for representing the arity of the function,
  1399. i.e., the number of arguments, which is helpful to know during
  1400. register allocation (Chapter~\ref{ch:register-allocation-r1}).
  1401. \begin{figure}[tp]
  1402. \fbox{
  1403. \begin{minipage}{0.96\textwidth}
  1404. \small
  1405. \[
  1406. \begin{array}{lcl}
  1407. \Reg &::=& \allregisters{} \\
  1408. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1409. \mid \DEREF{\Reg}{\Int} \\
  1410. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1411. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1412. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1413. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1414. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1415. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1416. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1417. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1418. \end{array}
  1419. \]
  1420. \end{minipage}
  1421. }
  1422. \caption{The abstract syntax of x86$_0$ assembly.}
  1423. \label{fig:x86-0-ast}
  1424. \end{figure}
  1425. \section{Planning the trip to x86 via the $C_0$ language}
  1426. \label{sec:plan-s0-x86}
  1427. To compile one language to another it helps to focus on the
  1428. differences between the two languages because the compiler will need
  1429. to bridge those differences. What are the differences between $R_1$
  1430. and x86 assembly? Here are some of the most important ones:
  1431. \begin{enumerate}
  1432. \item[(a)] x86 arithmetic instructions typically have two arguments
  1433. and update the second argument in place. In contrast, $R_1$
  1434. arithmetic operations take two arguments and produce a new value.
  1435. An x86 instruction may have at most one memory-accessing argument.
  1436. Furthermore, some instructions place special restrictions on their
  1437. arguments.
  1438. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1439. whereas x86 instructions restrict their arguments to be integers
  1440. constants, registers, and memory locations.
  1441. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1442. sequence of instructions and jumps to labeled positions, whereas in
  1443. $R_1$ the order of evaluation is a left-to-right depth-first
  1444. traversal of the abstract syntax tree.
  1445. \item[(d)] An $R_1$ program can have any number of variables whereas
  1446. x86 has 16 registers and the procedure calls stack.
  1447. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1448. same name. The registers and memory locations of x86 all have unique
  1449. names or addresses.
  1450. \end{enumerate}
  1451. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1452. the problem into several steps, dealing with the above differences one
  1453. at a time. Each of these steps is called a \emph{pass} of the
  1454. compiler.\index{pass}\index{compiler pass}
  1455. %
  1456. This terminology comes from each step traverses (i.e. passes over) the
  1457. AST of the program.
  1458. %
  1459. We begin by sketching how we might implement each pass, and give them
  1460. names. We then figure out an ordering of the passes and the
  1461. input/output language for each pass. The very first pass has $R_1$ as
  1462. its input language and the last pass has x86 as its output
  1463. language. In between we can choose whichever language is most
  1464. convenient for expressing the output of each pass, whether that be
  1465. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1466. Finally, to implement each pass we write one recursive function per
  1467. non-terminal in the grammar of the input language of the pass.
  1468. \index{intermediate language}
  1469. \begin{description}
  1470. \item[Pass \key{select-instructions}] To handle the difference between
  1471. $R_1$ operations and x86 instructions we convert each $R_1$
  1472. operation to a short sequence of instructions that accomplishes the
  1473. same task.
  1474. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1475. subexpression (i.e. operator and operand, and hence the name
  1476. \key{opera*}) is an \emph{atomic} expression (a variable or
  1477. integer), we introduce temporary variables to hold the results
  1478. of subexpressions.\index{atomic expression}
  1479. \item[Pass \key{explicate-control}] To make the execution order of the
  1480. program explicit, we convert from the abstract syntax tree
  1481. representation into a control-flow graph in which each node
  1482. contains a sequence of statements and the edges between nodes say
  1483. where to go at the end of the sequence.
  1484. \item[Pass \key{assign-homes}] To handle the difference between the
  1485. variables in $R_1$ versus the registers and stack locations in x86,
  1486. we map each variable to a register or stack location.
  1487. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1488. by renaming every variable to a unique name, so that shadowing no
  1489. longer occurs.
  1490. \end{description}
  1491. The next question is: in what order should we apply these passes? This
  1492. question can be challenging because it is difficult to know ahead of
  1493. time which orders will be better (easier to implement, produce more
  1494. efficient code, etc.) so oftentimes trial-and-error is
  1495. involved. Nevertheless, we can try to plan ahead and make educated
  1496. choices regarding the ordering.
  1497. Let us consider the ordering of \key{uniquify} and
  1498. \key{remove-complex-opera*}. The assignment of subexpressions to
  1499. temporary variables involves introducing new variables and moving
  1500. subexpressions, which might change the shadowing of variables and
  1501. inadvertently change the behavior of the program. But if we apply
  1502. \key{uniquify} first, this will not be an issue. Of course, this means
  1503. that in \key{remove-complex-opera*}, we need to ensure that the
  1504. temporary variables that it creates are unique.
  1505. What should be the ordering of \key{explicate-control} with respect to
  1506. \key{uniquify}? The \key{uniquify} pass should come first because
  1507. \key{explicate-control} changes all the \key{let}-bound variables to
  1508. become local variables whose scope is the entire program, which would
  1509. confuse variables with the same name.
  1510. %
  1511. Likewise, we place \key{explicate-control} after
  1512. \key{remove-complex-opera*} because \key{explicate-control} removes
  1513. the \key{let} form, but it is convenient to use \key{let} in the
  1514. output of \key{remove-complex-opera*}.
  1515. %
  1516. Regarding \key{assign-homes}, it is helpful to place
  1517. \key{explicate-control} first because \key{explicate-control} changes
  1518. \key{let}-bound variables into program-scope variables. This means
  1519. that the \key{assign-homes} pass can read off the variables from the
  1520. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1521. entire program in search of \key{let}-bound variables.
  1522. Last, we need to decide on the ordering of \key{select-instructions}
  1523. and \key{assign-homes}. These two passes are intertwined, creating a
  1524. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1525. have already determined which instructions will be used, because x86
  1526. instructions have restrictions about which of their arguments can be
  1527. registers versus stack locations. One might want to give preferential
  1528. treatment to variables that occur in register-argument positions. On
  1529. the other hand, it may turn out to be impossible to make sure that all
  1530. such variables are assigned to registers, and then one must redo the
  1531. selection of instructions. Some compilers handle this problem by
  1532. iteratively repeating these two passes until a good solution is found.
  1533. We use a simpler approach in which \key{select-instructions}
  1534. comes first, followed by the \key{assign-homes}, then a third
  1535. pass named \key{patch-instructions} that uses a reserved register to
  1536. patch-up outstanding problems regarding instructions with too many
  1537. memory accesses. The disadvantage of this approach is some programs
  1538. may not execute as efficiently as they would if we used the iterative
  1539. approach and used all of the registers for variables.
  1540. \begin{figure}[tbp]
  1541. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1542. \node (R1) at (0,2) {\large $R_1$};
  1543. \node (R1-2) at (3,2) {\large $R_1$};
  1544. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1545. %\node (C0-1) at (6,0) {\large $C_0$};
  1546. \node (C0-2) at (3,0) {\large $C_0$};
  1547. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1548. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1549. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1550. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1551. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1552. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1553. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1554. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1555. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1556. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1557. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1558. \end{tikzpicture}
  1559. \caption{Overview of the passes for compiling $R_1$. }
  1560. \label{fig:R1-passes}
  1561. \end{figure}
  1562. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1563. passes in the form of a graph. Each pass is an edge and the
  1564. input/output language of each pass is a node in the graph. The output
  1565. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1566. are still in the $R_1$ language, but the output of the pass
  1567. \key{explicate-control} is in a different language $C_0$ that is
  1568. designed to make the order of evaluation explicit in its syntax, which
  1569. we introduce in the next section. The \key{select-instruction} pass
  1570. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1571. \key{patch-instructions} passes input and output variants of x86
  1572. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1573. \key{print-x86}, which converts from the abstract syntax of
  1574. $\text{x86}_0$ to the concrete syntax of x86.
  1575. In the next sections we discuss the $C_0$ language and the
  1576. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1577. remainder of this chapter gives hints regarding the implementation of
  1578. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1579. \subsection{The $C_0$ Intermediate Language}
  1580. The output of \key{explicate-control} is similar to the $C$
  1581. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1582. categories for expressions and statements, so we name it $C_0$. The
  1583. concrete syntax for $C_0$ is defined in
  1584. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1585. is defined in Figure~\ref{fig:c0-syntax}.
  1586. %
  1587. The $C_0$ language supports the same operators as $R_1$ but the
  1588. arguments of operators are restricted to atomic expressions (variables
  1589. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1590. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1591. executed in sequence using the \key{Seq} form. A sequence of
  1592. statements always ends with \key{Return}, a guarantee that is baked
  1593. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1594. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1595. which refers to an expression that is the last one to execute within a
  1596. function. (An expression in tail position may contain subexpressions,
  1597. and those may or may not be in tail position depending on the kind of
  1598. expression.)
  1599. A $C_0$ program consists of a control-flow graph (represented as an
  1600. alist mapping labels to tails). This is more general than
  1601. necessary for the present chapter, as we do not yet need to introduce
  1602. \key{goto} for jumping to labels, but it saves us from having to
  1603. change the syntax of the program construct in
  1604. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1605. \key{start}, and the whole program is its tail.
  1606. %
  1607. The $\itm{info}$ field of the \key{Program} form, after the
  1608. \key{explicate-control} pass, contains a mapping from the symbol
  1609. \key{locals} to a list of variables, that is, a list of all the
  1610. variables used in the program. At the start of the program, these
  1611. variables are uninitialized; they become initialized on their first
  1612. assignment.
  1613. \begin{figure}[tbp]
  1614. \fbox{
  1615. \begin{minipage}{0.96\textwidth}
  1616. \[
  1617. \begin{array}{lcl}
  1618. \Atm &::=& \Int \mid \Var \\
  1619. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1620. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1621. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1622. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1623. \end{array}
  1624. \]
  1625. \end{minipage}
  1626. }
  1627. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1628. \label{fig:c0-concrete-syntax}
  1629. \end{figure}
  1630. \begin{figure}[tbp]
  1631. \fbox{
  1632. \begin{minipage}{0.96\textwidth}
  1633. \[
  1634. \begin{array}{lcl}
  1635. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1636. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1637. &\mid& \ADD{\Atm}{\Atm}\\
  1638. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1639. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1640. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1641. \end{array}
  1642. \]
  1643. \end{minipage}
  1644. }
  1645. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1646. \label{fig:c0-syntax}
  1647. \end{figure}
  1648. \subsection{The dialects of x86}
  1649. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1650. the pass \key{select-instructions}. It extends x86$_0$ with an
  1651. unbounded number of program-scope variables and has looser rules
  1652. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1653. output of \key{print-x86}, is the concrete syntax for x86.
  1654. \section{Uniquify Variables}
  1655. \label{sec:uniquify-s0}
  1656. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1657. programs in which every \key{let} uses a unique variable name. For
  1658. example, the \code{uniquify} pass should translate the program on the
  1659. left into the program on the right. \\
  1660. \begin{tabular}{lll}
  1661. \begin{minipage}{0.4\textwidth}
  1662. \begin{lstlisting}
  1663. (let ([x 32])
  1664. (+ (let ([x 10]) x) x))
  1665. \end{lstlisting}
  1666. \end{minipage}
  1667. &
  1668. $\Rightarrow$
  1669. &
  1670. \begin{minipage}{0.4\textwidth}
  1671. \begin{lstlisting}
  1672. (let ([x.1 32])
  1673. (+ (let ([x.2 10]) x.2) x.1))
  1674. \end{lstlisting}
  1675. \end{minipage}
  1676. \end{tabular} \\
  1677. %
  1678. The following is another example translation, this time of a program
  1679. with a \key{let} nested inside the initializing expression of another
  1680. \key{let}.\\
  1681. \begin{tabular}{lll}
  1682. \begin{minipage}{0.4\textwidth}
  1683. \begin{lstlisting}
  1684. (let ([x (let ([x 4])
  1685. (+ x 1))])
  1686. (+ x 2))
  1687. \end{lstlisting}
  1688. \end{minipage}
  1689. &
  1690. $\Rightarrow$
  1691. &
  1692. \begin{minipage}{0.4\textwidth}
  1693. \begin{lstlisting}
  1694. (let ([x.2 (let ([x.1 4])
  1695. (+ x.1 1))])
  1696. (+ x.2 2))
  1697. \end{lstlisting}
  1698. \end{minipage}
  1699. \end{tabular}
  1700. We recommend implementing \code{uniquify} by creating a function named
  1701. \code{uniquify-exp} that is structurally recursive function and mostly
  1702. just copies the input program. However, when encountering a \key{let},
  1703. it should generate a unique name for the variable (the Racket function
  1704. \code{gensym} is handy for this) and associate the old name with the
  1705. new unique name in an alist. The \code{uniquify-exp}
  1706. function will need to access this alist when it gets to a
  1707. variable reference, so we add another parameter to \code{uniquify-exp}
  1708. for the alist.
  1709. The skeleton of the \code{uniquify-exp} function is shown in
  1710. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1711. convenient to partially apply it to a symbol table and then apply it
  1712. to different expressions, as in the last clause for primitive
  1713. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1714. form is useful for applying a function to each element of a list to produce
  1715. a new list.
  1716. \index{for/list}
  1717. \begin{exercise}
  1718. \normalfont % I don't like the italics for exercises. -Jeremy
  1719. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1720. implement the clauses for variables and for the \key{let} form.
  1721. \end{exercise}
  1722. \begin{figure}[tbp]
  1723. \begin{lstlisting}
  1724. (define (uniquify-exp symtab)
  1725. (lambda (e)
  1726. (match e
  1727. [(Var x) ___]
  1728. [(Int n) (Int n)]
  1729. [(Let x e body) ___]
  1730. [(Prim op es)
  1731. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1732. )))
  1733. (define (uniquify p)
  1734. (match p
  1735. [(Program '() e)
  1736. (Program '() ((uniquify-exp '()) e))]
  1737. )))
  1738. \end{lstlisting}
  1739. \caption{Skeleton for the \key{uniquify} pass.}
  1740. \label{fig:uniquify-s0}
  1741. \end{figure}
  1742. \begin{exercise}
  1743. \normalfont % I don't like the italics for exercises. -Jeremy
  1744. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1745. and checking whether the output programs produce the same result as
  1746. the input programs. The $R_1$ programs should be designed to test the
  1747. most interesting parts of the \key{uniquify} pass, that is, the
  1748. programs should include \key{let} forms, variables, and variables that
  1749. overshadow each other. The five programs should be in a subdirectory
  1750. named \key{tests} and they should have the same file name except for a
  1751. different integer at the end of the name, followed by the ending
  1752. \key{.rkt}. Use the \key{interp-tests} function
  1753. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1754. your \key{uniquify} pass on the example programs. See the
  1755. \key{run-tests.rkt} script in the support code for an example of how
  1756. to use \key{interp-tests}. The support code is in a \code{github}
  1757. repository at the following URL:
  1758. \begin{center}\footnotesize
  1759. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1760. \end{center}
  1761. \end{exercise}
  1762. \section{Remove Complex Operands}
  1763. \label{sec:remove-complex-opera-R1}
  1764. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1765. $R_1$ programs in which the arguments of operations are atomic
  1766. expressions. Put another way, this pass removes complex
  1767. operands\index{complex operand}, such as the expression \code{(- 10)}
  1768. in the program below. This is accomplished by introducing a new
  1769. \key{let}-bound variable, binding the complex operand to the new
  1770. variable, and then using the new variable in place of the complex
  1771. operand, as shown in the output of \code{remove-complex-opera*} on the
  1772. right.\\
  1773. \begin{tabular}{lll}
  1774. \begin{minipage}{0.4\textwidth}
  1775. % s0_19.rkt
  1776. \begin{lstlisting}
  1777. (+ 52 (- 10))
  1778. \end{lstlisting}
  1779. \end{minipage}
  1780. &
  1781. $\Rightarrow$
  1782. &
  1783. \begin{minipage}{0.4\textwidth}
  1784. \begin{lstlisting}
  1785. (let ([tmp.1 (- 10)])
  1786. (+ 52 tmp.1))
  1787. \end{lstlisting}
  1788. \end{minipage}
  1789. \end{tabular}
  1790. \begin{figure}[tp]
  1791. \centering
  1792. \fbox{
  1793. \begin{minipage}{0.96\textwidth}
  1794. \[
  1795. \begin{array}{rcl}
  1796. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1797. \Exp &::=& \Atm \mid \READ{} \\
  1798. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1799. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1800. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1801. \end{array}
  1802. \]
  1803. \end{minipage}
  1804. }
  1805. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1806. \label{fig:r1-anf-syntax}
  1807. \end{figure}
  1808. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1809. this pass, language $R_1^{\dagger}$. The main difference is that
  1810. operator arguments are required to be atomic expressions. In the
  1811. literature, this is called \emph{administrative normal form}, or ANF
  1812. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1813. \index{administrative normal form}
  1814. \index{ANF}
  1815. We recommend implementing this pass with two mutually recursive
  1816. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1817. \code{rco-atom} to subexpressions that are required to be atomic and
  1818. to apply \code{rco-exp} to subexpressions that can be atomic or
  1819. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1820. $R_1$ expression as input. The \code{rco-exp} function returns an
  1821. expression. The \code{rco-atom} function returns two things: an
  1822. atomic expression and alist mapping temporary variables to complex
  1823. subexpressions. You can return multiple things from a function using
  1824. Racket's \key{values} form and you can receive multiple things from a
  1825. function call using the \key{define-values} form. If you are not
  1826. familiar with these features, review the Racket documentation. Also,
  1827. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1828. form is useful for applying a function to each
  1829. element of a list, in the case where the function returns multiple
  1830. values.
  1831. \index{for/lists}
  1832. The following shows the output of \code{rco-atom} on the expression
  1833. \code{(- 10)} (using concrete syntax to be concise).
  1834. \begin{tabular}{lll}
  1835. \begin{minipage}{0.4\textwidth}
  1836. \begin{lstlisting}
  1837. (- 10)
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. &
  1841. $\Rightarrow$
  1842. &
  1843. \begin{minipage}{0.4\textwidth}
  1844. \begin{lstlisting}
  1845. tmp.1
  1846. ((tmp.1 . (- 10)))
  1847. \end{lstlisting}
  1848. \end{minipage}
  1849. \end{tabular}
  1850. Take special care of programs such as the next one that \key{let}-bind
  1851. variables with integers or other variables. You should leave them
  1852. unchanged, as shown in to the program on the right \\
  1853. \begin{tabular}{lll}
  1854. \begin{minipage}{0.4\textwidth}
  1855. % s0_20.rkt
  1856. \begin{lstlisting}
  1857. (let ([a 42])
  1858. (let ([b a])
  1859. b))
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. &
  1863. $\Rightarrow$
  1864. &
  1865. \begin{minipage}{0.4\textwidth}
  1866. \begin{lstlisting}
  1867. (let ([a 42])
  1868. (let ([b a])
  1869. b))
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \end{tabular} \\
  1873. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1874. produce the following output.\\
  1875. \begin{minipage}{0.4\textwidth}
  1876. \begin{lstlisting}
  1877. (let ([tmp.1 42])
  1878. (let ([a tmp.1])
  1879. (let ([tmp.2 a])
  1880. (let ([b tmp.2])
  1881. b))))
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \begin{exercise}
  1885. \normalfont Implement the \code{remove-complex-opera*} pass.
  1886. Test the new pass on all of the example programs that you created to test the
  1887. \key{uniquify} pass and create three new example programs that are
  1888. designed to exercise the interesting code in the
  1889. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1890. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1891. your passes on the example programs.
  1892. \end{exercise}
  1893. \section{Explicate Control}
  1894. \label{sec:explicate-control-r1}
  1895. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1896. programs that make the order of execution explicit in their
  1897. syntax. For now this amounts to flattening \key{let} constructs into a
  1898. sequence of assignment statements. For example, consider the following
  1899. $R_1$ program.\\
  1900. % s0_11.rkt
  1901. \begin{minipage}{0.96\textwidth}
  1902. \begin{lstlisting}
  1903. (let ([y (let ([x 20])
  1904. (+ x (let ([x 22]) x)))])
  1905. y)
  1906. \end{lstlisting}
  1907. \end{minipage}\\
  1908. %
  1909. The output of the previous pass and of \code{explicate-control} is
  1910. shown below. Recall that the right-hand-side of a \key{let} executes
  1911. before its body, so the order of evaluation for this program is to
  1912. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1913. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1914. output of \code{explicate-control} makes this ordering explicit.\\
  1915. \begin{tabular}{lll}
  1916. \begin{minipage}{0.4\textwidth}
  1917. \begin{lstlisting}
  1918. (let ([y (let ([x.1 20])
  1919. (let ([x.2 22])
  1920. (+ x.1 x.2)))])
  1921. y)
  1922. \end{lstlisting}
  1923. \end{minipage}
  1924. &
  1925. $\Rightarrow$
  1926. &
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. start:
  1930. x.1 = 20;
  1931. x.2 = 22;
  1932. y = (+ x.1 x.2);
  1933. return y;
  1934. \end{lstlisting}
  1935. \end{minipage}
  1936. \end{tabular}
  1937. We recommend implementing \code{explicate-control} using two mutually
  1938. recursive functions: \code{explicate-tail} and
  1939. \code{explicate-assign}. The first function should be applied to
  1940. expressions in tail position whereas the second should be applied to
  1941. expressions that occur on the right-hand-side of a \key{let}.
  1942. %
  1943. The \code{explicate-tail} function takes an $R_1$ expression as input
  1944. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}).
  1945. %
  1946. The \code{explicate-assign} function takes an $R_1$ expression, the
  1947. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1948. should come after the assignment (e.g., the code generated for the
  1949. body of the \key{let}) and returns a $\Tail$. The
  1950. \code{explicate-assign} function is in accumulator-passing style in
  1951. that its third parameter is some $C_0$ code that it adds to and
  1952. returns. The reader might be tempted to instead organize
  1953. \code{explicate-assign} in a more direct fashion, without the third
  1954. parameter and perhaps using \code{append} to combine statements. We
  1955. warn against that alternative because the accumulator-passing style is
  1956. key to how we generate high-quality code for conditional expressions
  1957. in Chapter~\ref{ch:bool-types}.
  1958. The top-level \code{explicate-control} function should invoke
  1959. \code{explicate-tail} on the body of the \key{Program} AST node.
  1960. \section{Select Instructions}
  1961. \label{sec:select-r1}
  1962. \index{instruction selection}
  1963. In the \code{select-instructions} pass we begin the work of
  1964. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1965. this pass is a variant of x86 that still uses variables, so we add an
  1966. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1967. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1968. \code{select-instructions} in terms of three auxiliary functions, one
  1969. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1970. The cases for $\Atm$ are straightforward, variables stay
  1971. the same and integer constants are changed to immediates:
  1972. $\INT{n}$ changes to $\IMM{n}$.
  1973. Next we consider the cases for $\Stmt$, starting with arithmetic
  1974. operations. For example, in $C_0$ an addition operation can take the
  1975. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1976. need to use the \key{addq} instruction which does an in-place
  1977. update. So we must first move \code{10} to \code{x}. \\
  1978. \begin{tabular}{lll}
  1979. \begin{minipage}{0.4\textwidth}
  1980. \begin{lstlisting}
  1981. x = (+ 10 32);
  1982. \end{lstlisting}
  1983. \end{minipage}
  1984. &
  1985. $\Rightarrow$
  1986. &
  1987. \begin{minipage}{0.4\textwidth}
  1988. \begin{lstlisting}
  1989. movq $10, x
  1990. addq $32, x
  1991. \end{lstlisting}
  1992. \end{minipage}
  1993. \end{tabular} \\
  1994. %
  1995. There are cases that require special care to avoid generating
  1996. needlessly complicated code. If one of the arguments of the addition
  1997. is the same as the left-hand side of the assignment, then there is no
  1998. need for the extra move instruction. For example, the following
  1999. assignment statement can be translated into a single \key{addq}
  2000. instruction.\\
  2001. \begin{tabular}{lll}
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}
  2004. x = (+ 10 x);
  2005. \end{lstlisting}
  2006. \end{minipage}
  2007. &
  2008. $\Rightarrow$
  2009. &
  2010. \begin{minipage}{0.4\textwidth}
  2011. \begin{lstlisting}
  2012. addq $10, x
  2013. \end{lstlisting}
  2014. \end{minipage}
  2015. \end{tabular} \\
  2016. The \key{read} operation does not have a direct counterpart in x86
  2017. assembly, so we have instead implemented this functionality in the C
  2018. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2019. in the file \code{runtime.c}. In general, we refer to all of the
  2020. functionality in this file as the \emph{runtime system}\index{runtime system},
  2021. or simply the \emph{runtime} for short. When compiling your generated x86
  2022. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2023. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2024. the executable. For our purposes of code generation, all you need to
  2025. do is translate an assignment of \key{read} into some variable
  2026. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2027. function followed by a move from \code{rax} to the left-hand side.
  2028. The move from \code{rax} is needed because the return value from
  2029. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2030. \begin{tabular}{lll}
  2031. \begin{minipage}{0.3\textwidth}
  2032. \begin{lstlisting}
  2033. |$\itm{var}$| = (read);
  2034. \end{lstlisting}
  2035. \end{minipage}
  2036. &
  2037. $\Rightarrow$
  2038. &
  2039. \begin{minipage}{0.3\textwidth}
  2040. \begin{lstlisting}
  2041. callq read_int
  2042. movq %rax, |$\itm{var}$|
  2043. \end{lstlisting}
  2044. \end{minipage}
  2045. \end{tabular} \\
  2046. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2047. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2048. assignment to the \key{rax} register followed by a jump to the
  2049. conclusion of the program (so the conclusion needs to be labeled).
  2050. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2051. recursively and append the resulting instructions.
  2052. \begin{exercise}
  2053. \normalfont
  2054. Implement the \key{select-instructions} pass and test it on all of the
  2055. example programs that you created for the previous passes and create
  2056. three new example programs that are designed to exercise all of the
  2057. interesting code in this pass. Use the \key{interp-tests} function
  2058. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2059. your passes on the example programs.
  2060. \end{exercise}
  2061. \section{Assign Homes}
  2062. \label{sec:assign-r1}
  2063. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2064. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2065. Thus, the \key{assign-homes} pass is responsible for placing all of
  2066. the program variables in registers or on the stack. For runtime
  2067. efficiency, it is better to place variables in registers, but as there
  2068. are only 16 registers, some programs must necessarily resort to
  2069. placing some variables on the stack. In this chapter we focus on the
  2070. mechanics of placing variables on the stack. We study an algorithm for
  2071. placing variables in registers in
  2072. Chapter~\ref{ch:register-allocation-r1}.
  2073. Consider again the following $R_1$ program.
  2074. % s0_20.rkt
  2075. \begin{lstlisting}
  2076. (let ([a 42])
  2077. (let ([b a])
  2078. b))
  2079. \end{lstlisting}
  2080. For reference, we repeat the output of \code{select-instructions} on
  2081. the left and show the output of \code{assign-homes} on the right.
  2082. %
  2083. %% Recall that \key{explicate-control} associated the list of
  2084. %% variables with the \code{locals} symbol in the program's $\itm{info}$
  2085. %% field, so \code{assign-homes} has convenient access to the them.
  2086. %
  2087. In this example, we assign variable \code{a} to stack location
  2088. \code{-8(\%rbp)} and variable \code{b} to location
  2089. \code{-16(\%rbp)}.\\
  2090. \begin{tabular}{l}
  2091. \begin{minipage}{0.4\textwidth}
  2092. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2093. locals-types:
  2094. a : 'Integer, b : 'Integer
  2095. start:
  2096. movq $42, a
  2097. movq a, b
  2098. movq b, %rax
  2099. jmp conclusion
  2100. \end{lstlisting}
  2101. \end{minipage}
  2102. {$\Rightarrow$}
  2103. \begin{minipage}{0.4\textwidth}
  2104. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2105. stack-space: 16
  2106. start:
  2107. movq $42, -8(%rbp)
  2108. movq -8(%rbp), -16(%rbp)
  2109. movq -16(%rbp), %rax
  2110. jmp conclusion
  2111. \end{lstlisting}
  2112. \end{minipage}
  2113. \end{tabular} \\
  2114. In the output of \code{select-instructions}, there is a entry for
  2115. \code{locals-types} in the $\itm{info}$ of the \code{Program} node,
  2116. which is needed here so that we have the list of variables that should
  2117. be assigned to homes. The support code computes the
  2118. \code{locals-types} entry. In particular, \code{type-check-C0}
  2119. installs it in the $\itm{info}$ field of the \code{Program} node.
  2120. When using \code{interp-tests} or \code{compiler-tests} (see Appendix,
  2121. Section~\ref{appendix:utilities}), specify \code{type-check-C0} as the
  2122. type checker to use after \code{explicate-control}.
  2123. In the process of assigning variables to stack locations, it is
  2124. convenient for you to compute and store the size of the frame (in
  2125. bytes) in the $\itm{info}$ field of the \key{Program} node, with the
  2126. key \code{stack-space}, which is needed later to generate the
  2127. conclusion of the \code{main} procedure. The x86-64 standard requires
  2128. the frame size to be a multiple of 16 bytes. \index{frame}
  2129. \begin{exercise}
  2130. \normalfont Implement the \key{assign-homes} pass and test it on all
  2131. of the example programs that you created for the previous passes pass.
  2132. We recommend that \key{assign-homes} take an extra parameter that is a
  2133. mapping of variable names to homes (stack locations for now). Use the
  2134. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2135. \key{utilities.rkt} to test your passes on the example programs.
  2136. \end{exercise}
  2137. \section{Patch Instructions}
  2138. \label{sec:patch-s0}
  2139. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2140. programs to $\text{x86}_0$ programs by making sure that each
  2141. instruction adheres to the restrictions of the x86 assembly language.
  2142. In particular, at most one argument of an instruction may be a memory
  2143. reference.
  2144. We return to the following running example.
  2145. % s0_20.rkt
  2146. \begin{lstlisting}
  2147. (let ([a 42])
  2148. (let ([b a])
  2149. b))
  2150. \end{lstlisting}
  2151. After the \key{assign-homes} pass, the above program has been translated to
  2152. the following. \\
  2153. \begin{minipage}{0.5\textwidth}
  2154. \begin{lstlisting}
  2155. stack-space: 16
  2156. start:
  2157. movq $42, -8(%rbp)
  2158. movq -8(%rbp), -16(%rbp)
  2159. movq -16(%rbp), %rax
  2160. jmp conclusion
  2161. \end{lstlisting}
  2162. \end{minipage}\\
  2163. The second \key{movq} instruction is problematic because both
  2164. arguments are stack locations. We suggest fixing this problem by
  2165. moving from the source location to the register \key{rax} and then
  2166. from \key{rax} to the destination location, as follows.
  2167. \begin{lstlisting}
  2168. movq -8(%rbp), %rax
  2169. movq %rax, -16(%rbp)
  2170. \end{lstlisting}
  2171. \begin{exercise}
  2172. \normalfont
  2173. Implement the \key{patch-instructions} pass and test it on all of the
  2174. example programs that you created for the previous passes and create
  2175. three new example programs that are designed to exercise all of the
  2176. interesting code in this pass. Use the \key{interp-tests} function
  2177. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2178. your passes on the example programs.
  2179. \end{exercise}
  2180. \section{Print x86}
  2181. \label{sec:print-x86}
  2182. The last step of the compiler from $R_1$ to x86 is to convert the
  2183. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2184. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2185. \key{format} and \key{string-append} functions are useful in this
  2186. regard. The main work that this step needs to perform is to create the
  2187. \key{main} function and the standard instructions for its prelude and
  2188. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2189. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2190. variables, so we suggest computing it in the \key{assign-homes} pass
  2191. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2192. of the \key{program} node.
  2193. %% Your compiled code should print the result of the program's execution
  2194. %% by using the \code{print\_int} function provided in
  2195. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2196. %% far, this final result should be stored in the \key{rax} register.
  2197. %% We'll talk more about how to perform function calls with arguments in
  2198. %% general later on, but for now, place the following after the compiled
  2199. %% code for the $R_1$ program but before the conclusion:
  2200. %% \begin{lstlisting}
  2201. %% movq %rax, %rdi
  2202. %% callq print_int
  2203. %% \end{lstlisting}
  2204. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2205. %% stores the first argument to be passed into \key{print\_int}.
  2206. If you want your program to run on Mac OS X, your code needs to
  2207. determine whether or not it is running on a Mac, and prefix
  2208. underscores to labels like \key{main}. You can determine the platform
  2209. with the Racket call \code{(system-type 'os)}, which returns
  2210. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2211. %% In addition to
  2212. %% placing underscores on \key{main}, you need to put them in front of
  2213. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2214. %% \_print\_int}).
  2215. \begin{exercise}
  2216. \normalfont Implement the \key{print-x86} pass and test it on all of
  2217. the example programs that you created for the previous passes. Use the
  2218. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2219. \key{utilities.rkt} to test your complete compiler on the example
  2220. programs. See the \key{run-tests.rkt} script in the student support
  2221. code for an example of how to use \key{compiler-tests}. Also, remember
  2222. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2223. \key{gcc}.
  2224. \end{exercise}
  2225. \section{Challenge: Partial Evaluator for $R_1$}
  2226. \label{sec:pe-R1}
  2227. \index{partial evaluation}
  2228. This section describes optional challenge exercises that involve
  2229. adapting and improving the partial evaluator for $R_0$ that was
  2230. introduced in Section~\ref{sec:partial-evaluation}.
  2231. \begin{exercise}\label{ex:pe-R1}
  2232. \normalfont
  2233. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2234. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2235. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2236. and variables to the $R_0$ language, so you will need to add cases for
  2237. them in the \code{pe-exp} function. Also, note that the \key{program}
  2238. form changes slightly to include an $\itm{info}$ field. Once
  2239. complete, add the partial evaluation pass to the front of your
  2240. compiler and make sure that your compiler still passes all of the
  2241. tests.
  2242. \end{exercise}
  2243. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2244. \begin{exercise}
  2245. \normalfont
  2246. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2247. \code{pe-add} auxiliary functions with functions that know more about
  2248. arithmetic. For example, your partial evaluator should translate
  2249. \begin{lstlisting}
  2250. (+ 1 (+ (read) 1))
  2251. \end{lstlisting}
  2252. into
  2253. \begin{lstlisting}
  2254. (+ 2 (read))
  2255. \end{lstlisting}
  2256. To accomplish this, the \code{pe-exp} function should produce output
  2257. in the form of the $\itm{residual}$ non-terminal of the following
  2258. grammar.
  2259. \[
  2260. \begin{array}{lcl}
  2261. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2262. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2263. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2264. \end{array}
  2265. \]
  2266. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2267. that their inputs are $\itm{residual}$ expressions and they should
  2268. return $\itm{residual}$ expressions. Once the improvements are
  2269. complete, make sure that your compiler still passes all of the tests.
  2270. After all, fast code is useless if it produces incorrect results!
  2271. \end{exercise}
  2272. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2273. \chapter{Register Allocation}
  2274. \label{ch:register-allocation-r1}
  2275. \index{register allocation}
  2276. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2277. make our life easier. However, we can improve the performance of the
  2278. generated code if we instead place some variables into registers. The
  2279. CPU can access a register in a single cycle, whereas accessing the
  2280. stack takes many cycles if the relevant data is in cache or many more
  2281. to access main memory if the data is not in cache.
  2282. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2283. serves as a running example. We show the source program and also the
  2284. output of instruction selection. At that point the program is almost
  2285. x86 assembly but not quite; it still contains variables instead of
  2286. stack locations or registers.
  2287. \begin{figure}
  2288. \begin{minipage}{0.45\textwidth}
  2289. Example $R_1$ program:
  2290. % s0_28.rkt
  2291. \begin{lstlisting}
  2292. (let ([v 1])
  2293. (let ([w 42])
  2294. (let ([x (+ v 7)])
  2295. (let ([y x])
  2296. (let ([z (+ x w)])
  2297. (+ z (- y)))))))
  2298. \end{lstlisting}
  2299. \end{minipage}
  2300. \begin{minipage}{0.45\textwidth}
  2301. After instruction selection:
  2302. \begin{lstlisting}
  2303. locals-types:
  2304. x : Integer, y : Integer,
  2305. z : Integer, t : Integer,
  2306. v : Integer, w : Integer
  2307. start:
  2308. movq $1, v
  2309. movq $42, w
  2310. movq v, x
  2311. addq $7, x
  2312. movq x, y
  2313. movq x, z
  2314. addq w, z
  2315. movq y, t
  2316. negq t
  2317. movq z, %rax
  2318. addq t, %rax
  2319. jmp conclusion
  2320. \end{lstlisting}
  2321. \end{minipage}
  2322. \caption{A running example program for register allocation.}
  2323. \label{fig:reg-eg}
  2324. \end{figure}
  2325. The goal of register allocation is to fit as many variables into
  2326. registers as possible. A program sometimes has more variables than
  2327. registers, so we cannot map each variable to a different
  2328. register. Fortunately, it is common for different variables to be
  2329. needed during different periods of time during program execution, and
  2330. in such cases several variables can be mapped to the same register.
  2331. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2332. After the variable \code{x} is moved to \code{z} it is no longer
  2333. needed. Variable \code{y}, on the other hand, is used only after this
  2334. point, so \code{x} and \code{y} could share the same register. The
  2335. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2336. where a variable is needed. Once we have that information, we compute
  2337. which variables are needed at the same time, i.e., which ones
  2338. \emph{interfere} with each other, and represent this relation as an
  2339. undirected graph whose vertices are variables and edges indicate when
  2340. two variables interfere (Section~\ref{sec:build-interference}). We
  2341. then model register allocation as a graph coloring problem, which we
  2342. discuss in Section~\ref{sec:graph-coloring}.
  2343. In the event that we run out of registers despite these efforts, we
  2344. place the remaining variables on the stack, similar to what we did in
  2345. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2346. for assigning a variable to a stack location. The process of spilling
  2347. variables is handled as part of the graph coloring process described
  2348. in \ref{sec:graph-coloring}.
  2349. We make the simplifying assumption that each variable is assigned to
  2350. one location (a register or stack address). A more sophisticated
  2351. approach is to assign a variable to one or more locations in different
  2352. regions of the program. For example, if a variable is used many times
  2353. in short sequence and then only used again after many other
  2354. instructions, it could be more efficient to assign the variable to a
  2355. register during the intial sequence and then move it to the stack for
  2356. the rest of its lifetime. We refer the interested reader to
  2357. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2358. about this approach.
  2359. % discuss prioritizing variables based on how much they are used.
  2360. \section{Registers and Calling Conventions}
  2361. \label{sec:calling-conventions}
  2362. \index{calling conventions}
  2363. As we perform register allocation, we need to be aware of the
  2364. \emph{calling conventions} \index{calling conventions} that govern how
  2365. functions calls are performed in x86. Function calls require
  2366. coordination between the caller and the callee, which is often
  2367. assembly code written by different programmers or generated by
  2368. different compilers. Here we follow the System V calling conventions
  2369. that are used by the \code{gcc} compiler on Linux and
  2370. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2371. %
  2372. Even though $R_1$ does not include programmer-defined functions, our
  2373. generated code will 1) include a \code{main} function that the
  2374. operating system will call to initiate execution, and 2) make calls to
  2375. the \code{read\_int} function in our runtime system.
  2376. The calling conventions include rules about how functions share the
  2377. use of registers. In particular, the caller is responsible for freeing
  2378. up some registers prior to the function call for use by the callee.
  2379. These are called the \emph{caller-saved registers}
  2380. \index{caller-saved registers}
  2381. and they are
  2382. \begin{lstlisting}
  2383. rax rcx rdx rsi rdi r8 r9 r10 r11
  2384. \end{lstlisting}
  2385. On the other hand, the callee is responsible for preserving the values
  2386. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2387. which are
  2388. \begin{lstlisting}
  2389. rsp rbp rbx r12 r13 r14 r15
  2390. \end{lstlisting}
  2391. We can think about this caller/callee convention from two points of
  2392. view, the caller view and the callee view:
  2393. \begin{itemize}
  2394. \item The caller should assume that all the caller-saved registers get
  2395. overwritten with arbitrary values by the callee. On the other hand,
  2396. the caller can safely assume that all the callee-saved registers
  2397. contain the same values after the call that they did before the
  2398. call.
  2399. \item The callee can freely use any of the caller-saved registers.
  2400. However, if the callee wants to use a callee-saved register, the
  2401. callee must arrange to put the original value back in the register
  2402. prior to returning to the caller, which is usually accomplished by
  2403. saving the value to the stack in the prelude of the function and
  2404. restoring the value in the conclusion of the function.
  2405. \end{itemize}
  2406. In x86, registers are also used for passing arguments to a function
  2407. and for the return value. In particular, the first six arguments of a
  2408. function are passed in the following six registers, in the order
  2409. given.
  2410. \begin{lstlisting}
  2411. rdi rsi rdx rcx r8 r9
  2412. \end{lstlisting}
  2413. If there are more than six arguments, then the convention is to use
  2414. space on the frame of the caller for the rest of the
  2415. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2416. need more than six arguments. For now, the only function we care about
  2417. is \code{read\_int} and it takes zero argument.
  2418. %
  2419. The register \code{rax} is for the return value of a function.
  2420. The next question is how these calling conventions impact register
  2421. allocation. Consider the $R_1$ program in
  2422. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2423. example from the caller point of view and then from the callee point
  2424. of view.
  2425. The program makes two calls to the \code{read} function. Also, the
  2426. variable \code{x} is in-use during the second call to \code{read}, so
  2427. we need to make sure that the value in \code{x} does not get
  2428. accidentally wiped out by the call to \code{read}. One obvious
  2429. approach is to save all the values in caller-saved registers to the
  2430. stack prior to each function call, and restore them after each
  2431. call. That way, if the register allocator chooses to assign \code{x}
  2432. to a caller-saved register, its value will be preserved accross the
  2433. call to \code{read}. However, the disadvantage of this approach is
  2434. that saving and restoring to the stack is relatively slow. If \code{x}
  2435. is not used many times, it may be better to assign \code{x} to a stack
  2436. location in the first place. Or better yet, if we can arrange for
  2437. \code{x} to be placed in a callee-saved register, then it won't need
  2438. to be saved and restored during function calls.
  2439. The approach that we recommend for variables that are in-use during a
  2440. function call is to either assign them to callee-saved registers or to
  2441. spill them to the stack. On the other hand, for variables that are not
  2442. in-use during a function call, we try the following alternatives in
  2443. order 1) look for an available caller-saved register (to leave room
  2444. for other variables in the callee-saved register), 2) look for a
  2445. callee-saved register, and 3) spill the variable to the stack.
  2446. It is straightforward to implement this approach in a graph coloring
  2447. register allocator. First, we know which variables are in-use during
  2448. every function call because we compute that information for every
  2449. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2450. build the interference graph (Section~\ref{sec:build-interference}),
  2451. we can place an edge between each of these variables and the
  2452. caller-saved registers in the interference graph. This will prevent
  2453. the graph coloring algorithm from assigning those variables to
  2454. caller-saved registers.
  2455. Returning to the example in
  2456. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2457. generated x86 code on the right-hand side, focusing on the
  2458. \code{start} block. Notice that variable \code{x} is assigned to
  2459. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2460. place during the second call to \code{read\_int}. Next, notice that
  2461. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2462. because there are no function calls in the remainder of the block.
  2463. Next we analyze the example from the callee point of view, focusing on
  2464. the prelude and conclusion of the \code{main} function. As usual the
  2465. prelude begins with saving the \code{rbp} register to the stack and
  2466. setting the \code{rbp} to the current stack pointer. We now know why
  2467. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2468. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2469. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2470. variable (\code{x}). There are several more callee-saved register that
  2471. are not saved in the prelude because they were not assigned to
  2472. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2473. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2474. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2475. from the stack with a \code{popq} instruction.
  2476. \index{prelude}\index{conclusion}
  2477. \begin{figure}[tp]
  2478. \begin{minipage}{0.45\textwidth}
  2479. Example $R_1$ program:
  2480. %s0_14.rkt
  2481. \begin{lstlisting}
  2482. (let ([x (read)])
  2483. (let ([y (read)])
  2484. (+ (+ x y) 42)))
  2485. \end{lstlisting}
  2486. \end{minipage}
  2487. \begin{minipage}{0.45\textwidth}
  2488. Generated x86 assembly:
  2489. \begin{lstlisting}
  2490. start:
  2491. callq read_int
  2492. movq %rax, %rbx
  2493. callq read_int
  2494. movq %rax, %rcx
  2495. addq %rcx, %rbx
  2496. movq %rbx, %rax
  2497. addq $42, %rax
  2498. jmp _conclusion
  2499. .globl main
  2500. main:
  2501. pushq %rbp
  2502. movq %rsp, %rbp
  2503. pushq %rbx
  2504. subq $8, %rsp
  2505. jmp start
  2506. conclusion:
  2507. addq $8, %rsp
  2508. popq %rbx
  2509. popq %rbp
  2510. retq
  2511. \end{lstlisting}
  2512. \end{minipage}
  2513. \caption{An example with function calls.}
  2514. \label{fig:example-calling-conventions}
  2515. \end{figure}
  2516. \clearpage
  2517. \section{Liveness Analysis}
  2518. \label{sec:liveness-analysis-r1}
  2519. \index{liveness analysis}
  2520. A variable or register is \emph{live} at a program point if its
  2521. current value is used at some later point in the program. We
  2522. refer to variables and registers collectively as \emph{locations}.
  2523. %
  2524. Consider the following code fragment in which there are two writes to
  2525. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2526. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2527. movq $5, a
  2528. movq $30, b
  2529. movq a, c
  2530. movq $10, b
  2531. addq b, c
  2532. \end{lstlisting}
  2533. The answer is no because the integer \code{30} written to \code{b} on
  2534. line 2 is never used. The variable \code{b} is read on line 5 and
  2535. there is an intervening write to \code{b} on line 4, so the read on
  2536. line 5 receives the value written on line 4, not line 2.
  2537. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2538. \small
  2539. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2540. A \emph{set} is an unordered collection of elements without duplicates.
  2541. \index{set}
  2542. \begin{description}
  2543. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2544. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2545. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2546. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2547. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2548. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2549. \end{description}
  2550. \end{tcolorbox}
  2551. \end{wrapfigure}
  2552. The live locations can be computed by traversing the instruction
  2553. sequence back to front (i.e., backwards in execution order). Let
  2554. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2555. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2556. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2557. locations before instruction $I_k$. The live locations after an
  2558. instruction are always the same as the live locations before the next
  2559. instruction. \index{live-after} \index{live-before}
  2560. \begin{equation} \label{eq:live-after-before-next}
  2561. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2562. \end{equation}
  2563. To start things off, there are no live locations after the last
  2564. instruction\footnote{Technically, the \code{rax} register is live
  2565. but we do not use it for register allocation.}, so
  2566. \begin{equation}\label{eq:live-last-empty}
  2567. L_{\mathsf{after}}(n) = \emptyset
  2568. \end{equation}
  2569. We then apply the following rule repeatedly, traversing the
  2570. instruction sequence back to front.
  2571. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2572. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2573. \end{equation}
  2574. where $W(k)$ are the locations written to by instruction $I_k$ and
  2575. $R(k)$ are the locations read by instruction $I_k$.
  2576. Let us walk through the above example, applying these formulas
  2577. starting with the instruction on line 5. We collect the answers in the
  2578. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2579. instruction is $\emptyset$ because it is the last instruction
  2580. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2581. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2582. variables \code{b} and \code{c}
  2583. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2584. \[
  2585. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2586. \]
  2587. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2588. the live-before set from line 5 to be the live-after set for this
  2589. instruction (formula~\ref{eq:live-after-before-next}).
  2590. \[
  2591. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2592. \]
  2593. This move instruction writes to \code{b} and does not read from any
  2594. variables, so we have the following live-before set
  2595. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2596. \[
  2597. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2598. \]
  2599. The live-before for instruction \code{movq a, c}
  2600. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2601. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2602. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2603. variable that is not live and does not read from a variable.
  2604. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2605. because it writes to variable \code{a}.
  2606. \begin{center}
  2607. \begin{minipage}{0.45\textwidth}
  2608. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2609. movq $5, a
  2610. movq $30, b
  2611. movq a, c
  2612. movq $10, b
  2613. addq b, c
  2614. \end{lstlisting}
  2615. \end{minipage}
  2616. \vrule\hspace{10pt}
  2617. \begin{minipage}{0.45\textwidth}
  2618. \begin{align*}
  2619. L_{\mathsf{before}}(1)= \emptyset,
  2620. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2621. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2622. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2623. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2624. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2625. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2626. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2627. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2628. L_{\mathsf{after}}(5)= \emptyset
  2629. \end{align*}
  2630. \end{minipage}
  2631. \end{center}
  2632. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2633. the running example program, with the live-before and live-after sets
  2634. shown between each instruction to make the figure easy to read.
  2635. \begin{figure}[tp]
  2636. \hspace{20pt}
  2637. \begin{minipage}{0.45\textwidth}
  2638. \begin{lstlisting}
  2639. |$\{\}$|
  2640. movq $1, v
  2641. |$\{\ttm{v}\}$|
  2642. movq $42, w
  2643. |$\{\ttm{v},\ttm{w}\}$|
  2644. movq v, x
  2645. |$\{\ttm{w},\ttm{x}\}$|
  2646. addq $7, x
  2647. |$\{\ttm{w},\ttm{x}\}$|
  2648. movq x, y
  2649. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2650. movq x, z
  2651. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2652. addq w, z
  2653. |$\{\ttm{y},\ttm{z}\}$|
  2654. movq y, t
  2655. |$\{\ttm{t},\ttm{z}\}$|
  2656. negq t
  2657. |$\{\ttm{t},\ttm{z}\}$|
  2658. movq z, %rax
  2659. |$\{\ttm{rax},\ttm{t}\}$|
  2660. addq t, %rax
  2661. |$\{\}$|
  2662. jmp conclusion
  2663. |$\{\}$|
  2664. \end{lstlisting}
  2665. \end{minipage}
  2666. \caption{The running example annotated with live-after sets.}
  2667. \label{fig:live-eg}
  2668. \end{figure}
  2669. \begin{exercise}\normalfont
  2670. Implement the compiler pass named \code{uncover-live} that computes
  2671. the live-after sets. We recommend storing the live-after sets (a list
  2672. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2673. structure.
  2674. %
  2675. We recommend organizing your code to use a helper function that takes
  2676. a list of instructions and an initial live-after set (typically empty)
  2677. and returns the list of live-after sets.
  2678. %
  2679. We recommend creating helper functions to 1) compute the set of
  2680. locations that appear in an argument (of an instruction), 2) compute
  2681. the locations read by an instruction which corresponds to the $R$
  2682. function discussed above, and 3) the locations written by an
  2683. instruction which corresponds to $W$. The \code{callq} instruction
  2684. should include all of the caller-saved registers in its write-set $W$
  2685. because the calling convention says that those registers may be
  2686. written to during the function call. Likewise, the \code{callq}
  2687. instruction should include the appropriate number of argument passing
  2688. registers in its read-set $R$, depending on the arity of the function
  2689. being called. (This is why the abstract syntax for \code{callq}
  2690. includes the arity.)
  2691. \end{exercise}
  2692. \section{Building the Interference Graph}
  2693. \label{sec:build-interference}
  2694. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2695. \small
  2696. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2697. A \emph{graph} is a collection of vertices and edges where each
  2698. edge connects two vertices. A graph is \emph{directed} if each
  2699. edge points from a source to a target. Otherwise the graph is
  2700. \emph{undirected}.
  2701. \index{graph}\index{directed graph}\index{undirected graph}
  2702. \begin{description}
  2703. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2704. directed graph from a list of edges. Each edge is a list
  2705. containing the source and target vertex.
  2706. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2707. undirected graph from a list of edges. Each edge is represented by
  2708. a list containing two vertices.
  2709. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2710. inserts a vertex into the graph.
  2711. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2712. inserts an edge between the two vertices into the graph.
  2713. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2714. returns a sequence of all the neighbors of the given vertex.
  2715. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2716. returns a sequence of all the vertices in the graph.
  2717. \end{description}
  2718. \end{tcolorbox}
  2719. \end{wrapfigure}
  2720. Based on the liveness analysis, we know where each variable is needed.
  2721. However, during register allocation, we need to answer questions of
  2722. the specific form: are variables $u$ and $v$ live at the same time?
  2723. (And therefore cannot be assigned to the same register.) To make this
  2724. question easier to answer, we create an explicit data structure, an
  2725. \emph{interference graph}\index{interference graph}. An interference
  2726. graph is an undirected graph that has an edge between two variables if
  2727. they are live at the same time, that is, if they interfere with each
  2728. other.
  2729. The most obvious way to compute the interference graph is to look at
  2730. the set of live location between each statement in the program and add
  2731. an edge to the graph for every pair of variables in the same set.
  2732. This approach is less than ideal for two reasons. First, it can be
  2733. expensive because it takes $O(n^2)$ time to look at every pair in a
  2734. set of $n$ live locations. Second, there is a special case in which
  2735. two locations that are live at the same time do not actually interfere
  2736. with each other: when they both contain the same value because we have
  2737. assigned one to the other.
  2738. A better way to compute the interference graph is to focus on the
  2739. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2740. instruction to overwrite something in a live location. So for each
  2741. instruction, we create an edge between the locations being written to
  2742. and all the other live locations. (Except that one should not create
  2743. self edges.) Recall that for a \key{callq} instruction, we consider
  2744. all of the caller-saved registers as being written to, so an edge will
  2745. be added between every live variable and every caller-saved
  2746. register. For \key{movq}, we deal with the above-mentioned special
  2747. case by not adding an edge between a live variable $v$ and destination
  2748. $d$ if $v$ matches the source of the move. So we have the following
  2749. two rules.
  2750. \begin{enumerate}
  2751. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2752. $d$, then add the edge $(d,v)$ for every $v \in
  2753. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2754. \item For any other instruction $I_k$, for every $d \in W(k)$
  2755. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2756. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2757. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2758. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2759. %% \item If instruction $I_k$ is of the form \key{callq}
  2760. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2761. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2762. \end{enumerate}
  2763. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2764. the above rules to each instruction. We highlight a few of the
  2765. instructions and then refer the reader to
  2766. Figure~\ref{fig:interference-results} for all the interference
  2767. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2768. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2769. interference edges because the one live variable \code{v} is also the
  2770. destination of this instruction.
  2771. %
  2772. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2773. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2774. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2775. %
  2776. Next we skip forward to the instruction \lstinline{movq x, y}.
  2777. \begin{figure}[tbp]
  2778. \begin{quote}
  2779. \begin{tabular}{ll}
  2780. \lstinline!movq $1, v!& no interference by rule 3,\\
  2781. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2782. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2783. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2784. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2785. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2786. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2787. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2788. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2789. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2790. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2791. \lstinline!jmp conclusion!& no interference.
  2792. \end{tabular}
  2793. \end{quote}
  2794. \caption{Interference results for the running example.}
  2795. \label{fig:interference-results}
  2796. \end{figure}
  2797. The resulting interference graph is shown in
  2798. Figure~\ref{fig:interfere}.
  2799. \begin{figure}[tbp]
  2800. \large
  2801. \[
  2802. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2803. \node (rax) at (0,0) {$\ttm{rax}$};
  2804. \node (t1) at (0,2) {$\ttm{t}$};
  2805. \node (z) at (3,2) {$\ttm{z}$};
  2806. \node (x) at (6,2) {$\ttm{x}$};
  2807. \node (y) at (3,0) {$\ttm{y}$};
  2808. \node (w) at (6,0) {$\ttm{w}$};
  2809. \node (v) at (9,0) {$\ttm{v}$};
  2810. \draw (t1) to (rax);
  2811. \draw (t1) to (z);
  2812. \draw (z) to (y);
  2813. \draw (z) to (w);
  2814. \draw (x) to (w);
  2815. \draw (y) to (w);
  2816. \draw (v) to (w);
  2817. \end{tikzpicture}
  2818. \]
  2819. \caption{The interference graph of the example program.}
  2820. \label{fig:interfere}
  2821. \end{figure}
  2822. %% Our next concern is to choose a data structure for representing the
  2823. %% interference graph. There are many choices for how to represent a
  2824. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2825. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2826. %% data structure is to study the algorithm that uses the data structure,
  2827. %% determine what operations need to be performed, and then choose the
  2828. %% data structure that provide the most efficient implementations of
  2829. %% those operations. Often times the choice of data structure can have an
  2830. %% effect on the time complexity of the algorithm, as it does here. If
  2831. %% you skim the next section, you will see that the register allocation
  2832. %% algorithm needs to ask the graph for all of its vertices and, given a
  2833. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2834. %% correct choice of graph representation is that of an adjacency
  2835. %% list. There are helper functions in \code{utilities.rkt} for
  2836. %% representing graphs using the adjacency list representation:
  2837. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2838. %% (Appendix~\ref{appendix:utilities}).
  2839. %% %
  2840. %% \margincomment{\footnotesize To do: change to use the
  2841. %% Racket graph library. \\ --Jeremy}
  2842. %% %
  2843. %% In particular, those functions use a hash table to map each vertex to
  2844. %% the set of adjacent vertices, and the sets are represented using
  2845. %% Racket's \key{set}, which is also a hash table.
  2846. \begin{exercise}\normalfont
  2847. Implement the compiler pass named \code{build-interference} according
  2848. to the algorithm suggested above. We recommend using the \code{graph}
  2849. package to create and inspect the interference graph. The output
  2850. graph of this pass should be stored in the $\itm{info}$ field of the
  2851. program, under the key \code{conflicts}.
  2852. \end{exercise}
  2853. \section{Graph Coloring via Sudoku}
  2854. \label{sec:graph-coloring}
  2855. \index{graph coloring}
  2856. \index{Sudoku}
  2857. \index{color}
  2858. We come to the main event, mapping variables to registers (or to stack
  2859. locations in the event that we run out of registers). We need to make
  2860. sure that two variables do not get mapped to the same register if the
  2861. two variables interfere with each other. Thinking about the
  2862. interference graph, this means that adjacent vertices must be mapped
  2863. to different registers. If we think of registers as colors, the
  2864. register allocation problem becomes the widely-studied graph coloring
  2865. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2866. The reader may be more familiar with the graph coloring problem than he
  2867. or she realizes; the popular game of Sudoku is an instance of the
  2868. graph coloring problem. The following describes how to build a graph
  2869. out of an initial Sudoku board.
  2870. \begin{itemize}
  2871. \item There is one vertex in the graph for each Sudoku square.
  2872. \item There is an edge between two vertices if the corresponding squares
  2873. are in the same row, in the same column, or if the squares are in
  2874. the same $3\times 3$ region.
  2875. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2876. \item Based on the initial assignment of numbers to squares in the
  2877. Sudoku board, assign the corresponding colors to the corresponding
  2878. vertices in the graph.
  2879. \end{itemize}
  2880. If you can color the remaining vertices in the graph with the nine
  2881. colors, then you have also solved the corresponding game of Sudoku.
  2882. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2883. the corresponding graph with colored vertices. We map the Sudoku
  2884. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2885. sampling of the vertices (the colored ones) because showing edges for
  2886. all of the vertices would make the graph unreadable.
  2887. \begin{figure}[tbp]
  2888. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2889. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2890. \caption{A Sudoku game board and the corresponding colored graph.}
  2891. \label{fig:sudoku-graph}
  2892. \end{figure}
  2893. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2894. strategies to come up with an algorithm for allocating registers. For
  2895. example, one of the basic techniques for Sudoku is called Pencil
  2896. Marks. The idea is to use a process of elimination to determine what
  2897. numbers no longer make sense for a square and write down those
  2898. numbers in the square (writing very small). For example, if the number
  2899. $1$ is assigned to a square, then by process of elimination, you can
  2900. write the pencil mark $1$ in all the squares in the same row, column,
  2901. and region. Many Sudoku computer games provide automatic support for
  2902. Pencil Marks.
  2903. %
  2904. The Pencil Marks technique corresponds to the notion of
  2905. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2906. The saturation of a
  2907. vertex, in Sudoku terms, is the set of numbers that are no longer
  2908. available. In graph terminology, we have the following definition:
  2909. \begin{equation*}
  2910. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2911. \text{ and } \mathrm{color}(v) = c \}
  2912. \end{equation*}
  2913. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2914. edge with $u$.
  2915. Using the Pencil Marks technique leads to a simple strategy for
  2916. filling in numbers: if there is a square with only one possible number
  2917. left, then choose that number! But what if there are no squares with
  2918. only one possibility left? One brute-force approach is to try them
  2919. all: choose the first and if it ultimately leads to a solution,
  2920. great. If not, backtrack and choose the next possibility. One good
  2921. thing about Pencil Marks is that it reduces the degree of branching in
  2922. the search tree. Nevertheless, backtracking can be horribly time
  2923. consuming. One way to reduce the amount of backtracking is to use the
  2924. most-constrained-first heuristic. That is, when choosing a square,
  2925. always choose one with the fewest possibilities left (the vertex with
  2926. the highest saturation). The idea is that choosing highly constrained
  2927. squares earlier rather than later is better because later on there may
  2928. not be any possibilities left for those squares.
  2929. However, register allocation is easier than Sudoku because the
  2930. register allocator can map variables to stack locations when the
  2931. registers run out. Thus, it makes sense to drop backtracking in favor
  2932. of greedy search, that is, make the best choice at the time and keep
  2933. going. We still wish to minimize the number of colors needed, so
  2934. keeping the most-constrained-first heuristic is a good idea.
  2935. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2936. algorithm for register allocation based on saturation and the
  2937. most-constrained-first heuristic. It is roughly equivalent to the
  2938. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2939. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2940. Sudoku, the algorithm represents colors with integers. The integers
  2941. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2942. register allocation. The integers $k$ and larger correspond to stack
  2943. locations. The registers that are not used for register allocation,
  2944. such as \code{rax}, are assigned to negative integers. In particular,
  2945. we assign $-1$ to \code{rax}.
  2946. \begin{figure}[btp]
  2947. \centering
  2948. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2949. Algorithm: DSATUR
  2950. Input: a graph |$G$|
  2951. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2952. |$W \gets \mathrm{vertices}(G)$|
  2953. while |$W \neq \emptyset$| do
  2954. pick a vertex |$u$| from |$W$| with the highest saturation,
  2955. breaking ties randomly
  2956. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2957. |$\mathrm{color}[u] \gets c$|
  2958. |$W \gets W - \{u\}$|
  2959. \end{lstlisting}
  2960. \caption{The saturation-based greedy graph coloring algorithm.}
  2961. \label{fig:satur-algo}
  2962. \end{figure}
  2963. With this algorithm in hand, let us return to the running example and
  2964. consider how to color the interference graph in
  2965. Figure~\ref{fig:interfere}.
  2966. %
  2967. We color the vertices for registers with their own color. For example,
  2968. \code{rax} is assigned the color $-1$. We then update the saturation
  2969. for their neighboring vertices. In this case, the saturation for
  2970. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2971. so they annotated with a dash, and their saturation sets are empty.
  2972. \[
  2973. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2974. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2975. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2976. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2977. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2978. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2979. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2980. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2981. \draw (t1) to (rax);
  2982. \draw (t1) to (z);
  2983. \draw (z) to (y);
  2984. \draw (z) to (w);
  2985. \draw (x) to (w);
  2986. \draw (y) to (w);
  2987. \draw (v) to (w);
  2988. \end{tikzpicture}
  2989. \]
  2990. The algorithm says to select a maximally saturated vertex. So we pick
  2991. $\ttm{t}$ and color it with the first available integer, which is
  2992. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2993. because they interfere with $\ttm{t}$.
  2994. \[
  2995. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2996. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2997. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2998. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2999. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3000. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  3001. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  3002. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3003. \draw (t1) to (rax);
  3004. \draw (t1) to (z);
  3005. \draw (z) to (y);
  3006. \draw (z) to (w);
  3007. \draw (x) to (w);
  3008. \draw (y) to (w);
  3009. \draw (v) to (w);
  3010. \end{tikzpicture}
  3011. \]
  3012. We repeat the process, selecting another maximally saturated
  3013. vertex, which is \code{z}, and color it with the first available
  3014. number, which is $1$. We add $1$ to the saturations for the
  3015. neighboring vertices \code{t}, \code{y}, and \code{w}.
  3016. \[
  3017. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3018. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3019. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3020. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3021. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3022. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3023. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3024. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3025. \draw (t1) to (rax);
  3026. \draw (t1) to (z);
  3027. \draw (z) to (y);
  3028. \draw (z) to (w);
  3029. \draw (x) to (w);
  3030. \draw (y) to (w);
  3031. \draw (v) to (w);
  3032. \end{tikzpicture}
  3033. \]
  3034. The most saturated vertices are now \code{w} and \code{y}. We color
  3035. \code{w} with the first available color, which is $0$.
  3036. \[
  3037. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3038. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3039. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3040. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3041. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3042. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3043. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3044. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3045. \draw (t1) to (rax);
  3046. \draw (t1) to (z);
  3047. \draw (z) to (y);
  3048. \draw (z) to (w);
  3049. \draw (x) to (w);
  3050. \draw (y) to (w);
  3051. \draw (v) to (w);
  3052. \end{tikzpicture}
  3053. \]
  3054. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3055. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3056. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3057. and \code{z}, whose colors are $0$ and $1$ respectively.
  3058. \[
  3059. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3060. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3061. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3062. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3063. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3064. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3065. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3066. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3067. \draw (t1) to (rax);
  3068. \draw (t1) to (z);
  3069. \draw (z) to (y);
  3070. \draw (z) to (w);
  3071. \draw (x) to (w);
  3072. \draw (y) to (w);
  3073. \draw (v) to (w);
  3074. \end{tikzpicture}
  3075. \]
  3076. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3077. \[
  3078. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3079. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3080. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3081. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3082. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3083. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3084. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3085. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3086. \draw (t1) to (rax);
  3087. \draw (t1) to (z);
  3088. \draw (z) to (y);
  3089. \draw (z) to (w);
  3090. \draw (x) to (w);
  3091. \draw (y) to (w);
  3092. \draw (v) to (w);
  3093. \end{tikzpicture}
  3094. \]
  3095. In the last step of the algorithm, we color \code{x} with $1$.
  3096. \[
  3097. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3098. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3099. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3100. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3101. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3102. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3103. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3104. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3105. \draw (t1) to (rax);
  3106. \draw (t1) to (z);
  3107. \draw (z) to (y);
  3108. \draw (z) to (w);
  3109. \draw (x) to (w);
  3110. \draw (y) to (w);
  3111. \draw (v) to (w);
  3112. \end{tikzpicture}
  3113. \]
  3114. With the coloring complete, we finalize the assignment of variables to
  3115. registers and stack locations. Recall that if we have $k$ registers to
  3116. use for allocation, we map the first $k$ colors to registers and the
  3117. rest to stack locations. Suppose for the moment that we have just one
  3118. register to use for register allocation, \key{rcx}. Then the following
  3119. is the mapping of colors to registers and stack allocations.
  3120. \[
  3121. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3122. \]
  3123. Putting this mapping together with the above coloring of the
  3124. variables, we arrive at the following assignment of variables to
  3125. registers and stack locations.
  3126. \begin{gather*}
  3127. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3128. \ttm{w} \mapsto \key{\%rcx}, \,
  3129. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3130. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3131. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3132. \ttm{t} \mapsto \key{\%rcx} \}
  3133. \end{gather*}
  3134. Applying this assignment to our running example, on the left, yields
  3135. the program on the right.
  3136. % why frame size of 32? -JGS
  3137. \begin{center}
  3138. \begin{minipage}{0.3\textwidth}
  3139. \begin{lstlisting}
  3140. movq $1, v
  3141. movq $42, w
  3142. movq v, x
  3143. addq $7, x
  3144. movq x, y
  3145. movq x, z
  3146. addq w, z
  3147. movq y, t
  3148. negq t
  3149. movq z, %rax
  3150. addq t, %rax
  3151. jmp conclusion
  3152. \end{lstlisting}
  3153. \end{minipage}
  3154. $\Rightarrow\qquad$
  3155. \begin{minipage}{0.45\textwidth}
  3156. \begin{lstlisting}
  3157. movq $1, %rcx
  3158. movq $42, %rcx
  3159. movq %rcx, -8(%rbp)
  3160. addq $7, -8(%rbp)
  3161. movq -8(%rbp), -16(%rbp)
  3162. movq -8(%rbp), -8(%rbp)
  3163. addq %rcx, -8(%rbp)
  3164. movq -16(%rbp), %rcx
  3165. negq %rcx
  3166. movq -8(%rbp), %rax
  3167. addq %rcx, %rax
  3168. jmp conclusion
  3169. \end{lstlisting}
  3170. \end{minipage}
  3171. \end{center}
  3172. The resulting program is almost an x86 program. The remaining step is
  3173. the patch instructions pass. In this example, the trivial move of
  3174. \code{-8(\%rbp)} to itself is deleted and the addition of
  3175. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3176. \code{rax} as follows.
  3177. \begin{lstlisting}
  3178. movq -8(%rbp), %rax
  3179. addq %rax, -16(%rbp)
  3180. \end{lstlisting}
  3181. An overview of all of the passes involved in register allocation is
  3182. shown in Figure~\ref{fig:reg-alloc-passes}.
  3183. \begin{figure}[tbp]
  3184. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3185. \node (R1) at (0,2) {\large $R_1$};
  3186. \node (R1-2) at (3,2) {\large $R_1$};
  3187. \node (R1-3) at (6,2) {\large $R_1$};
  3188. \node (C0-1) at (3,0) {\large $C_0$};
  3189. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3190. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3191. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3192. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3193. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3194. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3195. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3196. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3197. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3198. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3199. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3200. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3201. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3202. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3203. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3204. \end{tikzpicture}
  3205. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3206. \label{fig:reg-alloc-passes}
  3207. \end{figure}
  3208. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3209. \small
  3210. \begin{tcolorbox}[title=Priority Queue]
  3211. A \emph{priority queue} is a collection of items in which the
  3212. removal of items is governed by priority. In a ``min'' queue,
  3213. lower priority items are removed first. An implementation is in
  3214. \code{priority\_queue.rkt} of the support code. \index{priority
  3215. queue} \index{minimum priority queue}
  3216. \begin{description}
  3217. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3218. priority queue that uses the $\itm{cmp}$ predicate to determine
  3219. whether its first argument has lower or equal priority to its
  3220. second argument.
  3221. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3222. items in the queue.
  3223. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3224. the item into the queue and returns a handle for the item in the
  3225. queue.
  3226. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3227. the lowest priority.
  3228. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3229. notifices the queue the the priority has decreased for the item
  3230. associated with the given handle.
  3231. \end{description}
  3232. \end{tcolorbox}
  3233. \end{wrapfigure}
  3234. We recommend creating a helper function named \code{color-graph} that
  3235. takes an interference graph and a list of all the variables in the
  3236. program. This function should return a mapping of variables to their
  3237. colors (represented as natural numbers). By creating this helper
  3238. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3239. when you add support for functions. To prioritize the process of
  3240. highly saturated nodes inside your \code{color-graph} function, we
  3241. recommend using the priority queue data structure (see the side bar on
  3242. the right). Note that you will also need to maintain a mapping from
  3243. variables to their ``handles'' in the priority queue so that you can
  3244. notify the priority queue when their saturation changes.
  3245. Once you have obtained the coloring from \code{color-graph}, you can
  3246. assign the variables to registers or stack locations and then reuse
  3247. code from the \code{assign-homes} pass from
  3248. Section~\ref{sec:assign-r1} to replace the variables with their
  3249. assigned location.
  3250. \begin{exercise}\normalfont
  3251. Implement the compiler pass \code{allocate-registers}, which should come
  3252. after the \code{build-interference} pass. The three new passes,
  3253. \code{uncover-live}, \code{build-interference}, and
  3254. \code{allocate-registers} replace the \code{assign-homes} pass of
  3255. Section~\ref{sec:assign-r1}.
  3256. Test your updated compiler by creating new example programs that
  3257. exercise all of the register allocation algorithm, such as forcing
  3258. variables to be spilled to the stack.
  3259. \end{exercise}
  3260. \section{Print x86 and Conventions for Registers}
  3261. \label{sec:print-x86-reg-alloc}
  3262. \index{calling conventions}
  3263. \index{prelude}\index{conclusion}
  3264. Recall that the \code{print-x86} pass generates the prelude and
  3265. conclusion instructions for the \code{main} function.
  3266. %
  3267. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3268. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3269. reason for this is that our \code{main} function must adhere to the
  3270. x86 calling conventions that we described in
  3271. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3272. allocator assigned variables to other callee-saved registers
  3273. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3274. saved to the stack in the prelude and restored in the conclusion. The
  3275. simplest approach is to save and restore all of the callee-saved
  3276. registers. The more efficient approach is to keep track of which
  3277. callee-saved registers were used and only save and restore
  3278. them. Either way, make sure to take this use of stack space into
  3279. account when you are calculating the size of the frame and adjusting
  3280. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3281. frame needs to be a multiple of 16 bytes!
  3282. \section{Challenge: Move Biasing}
  3283. \label{sec:move-biasing}
  3284. \index{move biasing}
  3285. This section describes an optional enhancement to register allocation
  3286. for those students who are looking for an extra challenge or who have
  3287. a deeper interest in register allocation.
  3288. We return to the running example, but we remove the supposition that
  3289. we only have one register to use. So we have the following mapping of
  3290. color numbers to registers.
  3291. \[
  3292. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3293. \]
  3294. Using the same assignment of variables to color numbers that was
  3295. produced by the register allocator described in the last section, we
  3296. get the following program.
  3297. \begin{minipage}{0.3\textwidth}
  3298. \begin{lstlisting}
  3299. movq $1, v
  3300. movq $42, w
  3301. movq v, x
  3302. addq $7, x
  3303. movq x, y
  3304. movq x, z
  3305. addq w, z
  3306. movq y, t
  3307. negq t
  3308. movq z, %rax
  3309. addq t, %rax
  3310. jmp conclusion
  3311. \end{lstlisting}
  3312. \end{minipage}
  3313. $\Rightarrow\qquad$
  3314. \begin{minipage}{0.45\textwidth}
  3315. \begin{lstlisting}
  3316. movq $1, %rcx
  3317. movq $42, $rbx
  3318. movq %rcx, %rcx
  3319. addq $7, %rcx
  3320. movq %rcx, %rdx
  3321. movq %rcx, %rcx
  3322. addq %rbx, %rcx
  3323. movq %rdx, %rbx
  3324. negq %rbx
  3325. movq %rcx, %rax
  3326. addq %rbx, %rax
  3327. jmp conclusion
  3328. \end{lstlisting}
  3329. \end{minipage}
  3330. In the above output code there are two \key{movq} instructions that
  3331. can be removed because their source and target are the same. However,
  3332. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3333. register, we could instead remove three \key{movq} instructions. We
  3334. can accomplish this by taking into account which variables appear in
  3335. \key{movq} instructions with which other variables.
  3336. We say that two variables $p$ and $q$ are \emph{move
  3337. related}\index{move related} if they participate together in a
  3338. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3339. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3340. for a variable, it should prefer a color that has already been used
  3341. for a move-related variable (assuming that they do not interfere). Of
  3342. course, this preference should not override the preference for
  3343. registers over stack locations. This preference should be used as a
  3344. tie breaker when choosing between registers or when choosing between
  3345. stack locations.
  3346. We recommend representing the move relationships in a graph, similar
  3347. to how we represented interference. The following is the \emph{move
  3348. graph} for our running example.
  3349. \[
  3350. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3351. \node (rax) at (0,0) {$\ttm{rax}$};
  3352. \node (t) at (0,2) {$\ttm{t}$};
  3353. \node (z) at (3,2) {$\ttm{z}$};
  3354. \node (x) at (6,2) {$\ttm{x}$};
  3355. \node (y) at (3,0) {$\ttm{y}$};
  3356. \node (w) at (6,0) {$\ttm{w}$};
  3357. \node (v) at (9,0) {$\ttm{v}$};
  3358. \draw (v) to (x);
  3359. \draw (x) to (y);
  3360. \draw (x) to (z);
  3361. \draw (y) to (t);
  3362. \end{tikzpicture}
  3363. \]
  3364. Now we replay the graph coloring, pausing to see the coloring of
  3365. \code{y}. Recall the following configuration. The most saturated vertices
  3366. were \code{w} and \code{y}.
  3367. \[
  3368. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3369. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3370. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3371. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3372. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3373. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3374. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3375. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3376. \draw (t1) to (rax);
  3377. \draw (t1) to (z);
  3378. \draw (z) to (y);
  3379. \draw (z) to (w);
  3380. \draw (x) to (w);
  3381. \draw (y) to (w);
  3382. \draw (v) to (w);
  3383. \end{tikzpicture}
  3384. \]
  3385. %
  3386. Last time we chose to color \code{w} with $0$. But this time we see
  3387. that \code{w} is not move related to any vertex, but \code{y} is move
  3388. related to \code{t}. So we choose to color \code{y} the same color,
  3389. $0$.
  3390. \[
  3391. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3392. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3393. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3394. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3395. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3396. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3397. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3398. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3399. \draw (t1) to (rax);
  3400. \draw (t1) to (z);
  3401. \draw (z) to (y);
  3402. \draw (z) to (w);
  3403. \draw (x) to (w);
  3404. \draw (y) to (w);
  3405. \draw (v) to (w);
  3406. \end{tikzpicture}
  3407. \]
  3408. Now \code{w} is the most saturated, so we color it $2$.
  3409. \[
  3410. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3411. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3412. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3413. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3414. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3415. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3416. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3417. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3418. \draw (t1) to (rax);
  3419. \draw (t1) to (z);
  3420. \draw (z) to (y);
  3421. \draw (z) to (w);
  3422. \draw (x) to (w);
  3423. \draw (y) to (w);
  3424. \draw (v) to (w);
  3425. \end{tikzpicture}
  3426. \]
  3427. At this point, vertices \code{x} and \code{v} are most saturated, but
  3428. \code{x} is move related to \code{y} and \code{z}, so we color
  3429. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3430. \[
  3431. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3432. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3433. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3434. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3435. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3436. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3437. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3438. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3439. \draw (t1) to (rax);
  3440. \draw (t) to (z);
  3441. \draw (z) to (y);
  3442. \draw (z) to (w);
  3443. \draw (x) to (w);
  3444. \draw (y) to (w);
  3445. \draw (v) to (w);
  3446. \end{tikzpicture}
  3447. \]
  3448. So we have the following assignment of variables to registers.
  3449. \begin{gather*}
  3450. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3451. \ttm{w} \mapsto \key{\%rdx}, \,
  3452. \ttm{x} \mapsto \key{\%rbx}, \,
  3453. \ttm{y} \mapsto \key{\%rbx}, \,
  3454. \ttm{z} \mapsto \key{\%rcx}, \,
  3455. \ttm{t} \mapsto \key{\%rbx} \}
  3456. \end{gather*}
  3457. We apply this register assignment to the running example, on the left,
  3458. to obtain the code on right.
  3459. \begin{minipage}{0.3\textwidth}
  3460. \begin{lstlisting}
  3461. movq $1, v
  3462. movq $42, w
  3463. movq v, x
  3464. addq $7, x
  3465. movq x, y
  3466. movq x, z
  3467. addq w, z
  3468. movq y, t
  3469. negq t
  3470. movq z, %rax
  3471. addq t, %rax
  3472. jmp conclusion
  3473. \end{lstlisting}
  3474. \end{minipage}
  3475. $\Rightarrow\qquad$
  3476. \begin{minipage}{0.45\textwidth}
  3477. \begin{lstlisting}
  3478. movq $1, %rbx
  3479. movq $42, %rdx
  3480. movq %rbx, %rbx
  3481. addq $7, %rbx
  3482. movq %rbx, %rbx
  3483. movq %rbx, %rcx
  3484. addq %rdx, %rcx
  3485. movq %rbx, %rbx
  3486. negq %rbx
  3487. movq %rcx, %rax
  3488. addq %rbx, %rax
  3489. jmp conclusion
  3490. \end{lstlisting}
  3491. \end{minipage}
  3492. The \code{patch-instructions} then removes the three trivial moves
  3493. from \key{rbx} to \key{rbx} to obtain the following result.
  3494. \begin{minipage}{0.45\textwidth}
  3495. \begin{lstlisting}
  3496. movq $1, %rbx
  3497. movq $42, %rdx
  3498. addq $7, %rbx
  3499. movq %rbx, %rcx
  3500. addq %rdx, %rcx
  3501. negq %rbx
  3502. movq %rcx, %rax
  3503. addq %rbx, %rax
  3504. jmp conclusion
  3505. \end{lstlisting}
  3506. \end{minipage}
  3507. \begin{exercise}\normalfont
  3508. Change your implementation of \code{allocate-registers} to take move
  3509. biasing into account. Make sure that your compiler still passes all of
  3510. the previous tests. Create two new tests that include at least one
  3511. opportunity for move biasing and visually inspect the output x86
  3512. programs to make sure that your move biasing is working properly.
  3513. \end{exercise}
  3514. \margincomment{\footnotesize To do: another neat challenge would be to do
  3515. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3516. \section{Output of the Running Example}
  3517. \label{sec:reg-alloc-output}
  3518. \index{prelude}\index{conclusion}
  3519. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3520. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3521. and move biasing. To demonstrate both the use of registers and the
  3522. stack, we have limited the register allocator to use just two
  3523. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3524. \code{main} function, we push \code{rbx} onto the stack because it is
  3525. a callee-saved register and it was assigned to variable by the
  3526. register allocator. We substract \code{8} from the \code{rsp} at the
  3527. end of the prelude to reserve space for the one spilled variable.
  3528. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3529. Moving on the the \code{start} block, we see how the registers were
  3530. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3531. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3532. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3533. that the prelude saved the callee-save register \code{rbx} onto the
  3534. stack. The spilled variables must be placed lower on the stack than
  3535. the saved callee-save registers, so in this case \code{w} is placed at
  3536. \code{-16(\%rbp)}.
  3537. In the \code{conclusion}, we undo the work that was done in the
  3538. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3539. spilled variables), then we pop the old values of \code{rbx} and
  3540. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3541. return control to the operating system.
  3542. \begin{figure}[tbp]
  3543. % s0_28.rkt
  3544. % (use-minimal-set-of-registers! #t)
  3545. % and only rbx rcx
  3546. % tmp 0 rbx
  3547. % z 1 rcx
  3548. % y 0 rbx
  3549. % w 2 16(%rbp)
  3550. % v 0 rbx
  3551. % x 0 rbx
  3552. \begin{lstlisting}
  3553. start:
  3554. movq $1, %rbx
  3555. movq $42, -16(%rbp)
  3556. addq $7, %rbx
  3557. movq %rbx, %rcx
  3558. addq -16(%rbp), %rcx
  3559. negq %rbx
  3560. movq %rcx, %rax
  3561. addq %rbx, %rax
  3562. jmp conclusion
  3563. .globl main
  3564. main:
  3565. pushq %rbp
  3566. movq %rsp, %rbp
  3567. pushq %rbx
  3568. subq $8, %rsp
  3569. jmp start
  3570. conclusion:
  3571. addq $8, %rsp
  3572. popq %rbx
  3573. popq %rbp
  3574. retq
  3575. \end{lstlisting}
  3576. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3577. \label{fig:running-example-x86}
  3578. \end{figure}
  3579. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3580. \chapter{Booleans and Control Flow}
  3581. \label{ch:bool-types}
  3582. \index{Boolean}
  3583. \index{control flow}
  3584. \index{conditional expression}
  3585. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3586. integers. In this chapter we add a second kind of value, the Booleans,
  3587. to create the $R_2$ language. The Boolean values \emph{true} and
  3588. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3589. Racket. The $R_2$ language includes several operations that involve
  3590. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3591. conditional \key{if} expression. With the addition of \key{if}
  3592. expressions, programs can have non-trivial control flow which which
  3593. significantly impacts the \code{explicate-control} and the liveness
  3594. analysis for register allocation. Also, because we now have two kinds
  3595. of values, we need to handle programs that apply an operation to the
  3596. wrong kind of value, such as \code{(not 1)}.
  3597. There are two language design options for such situations. One option
  3598. is to signal an error and the other is to provide a wider
  3599. interpretation of the operation. The Racket language uses a mixture of
  3600. these two options, depending on the operation and the kind of
  3601. value. For example, the result of \code{(not 1)} in Racket is
  3602. \code{\#f} because Racket treats non-zero integers as if they were
  3603. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3604. error in Racket stating that \code{car} expects a pair.
  3605. The Typed Racket language makes similar design choices as Racket,
  3606. except much of the error detection happens at compile time instead of
  3607. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3608. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3609. reports a compile-time error because Typed Racket expects the type of
  3610. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3611. For the $R_2$ language we choose to be more like Typed Racket in that
  3612. we perform type checking during compilation. In
  3613. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3614. is, how to compile a dynamically typed language like Racket. The
  3615. $R_2$ language is a subset of Typed Racket but by no means includes
  3616. all of Typed Racket. For many operations we take a narrower
  3617. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3618. This chapter is organized as follows. We begin by defining the syntax
  3619. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3620. then introduce the idea of type checking and build a type checker for
  3621. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3622. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3623. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3624. how our compiler passes need to change to accommodate Booleans and
  3625. conditional control flow.
  3626. \section{The $R_2$ Language}
  3627. \label{sec:r2-lang}
  3628. The concrete syntax of the $R_2$ language is defined in
  3629. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3630. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3631. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3632. and the conditional \code{if} expression. Also, we expand the
  3633. operators to include
  3634. \begin{enumerate}
  3635. \item subtraction on integers,
  3636. \item the logical operators \key{and}, \key{or} and \key{not},
  3637. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3638. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3639. comparing integers.
  3640. \end{enumerate}
  3641. We reorganize the abstract syntax for the primitive operations in
  3642. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3643. them. This means that the grammar no longer checks whether the arity
  3644. of an operators matches the number of arguments. That responsibility
  3645. is moved to the type checker for $R_2$, which we introduce in
  3646. Section~\ref{sec:type-check-r2}.
  3647. \begin{figure}[tp]
  3648. \centering
  3649. \fbox{
  3650. \begin{minipage}{0.96\textwidth}
  3651. \[
  3652. \begin{array}{lcl}
  3653. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3654. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3655. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3656. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3657. &\mid& \itm{bool}
  3658. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3659. \mid (\key{not}\;\Exp) \\
  3660. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3661. R_2 &::=& \Exp
  3662. \end{array}
  3663. \]
  3664. \end{minipage}
  3665. }
  3666. \caption{The concrete syntax of $R_2$, extending $R_1$
  3667. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3668. \label{fig:r2-concrete-syntax}
  3669. \end{figure}
  3670. \begin{figure}[tp]
  3671. \centering
  3672. \fbox{
  3673. \begin{minipage}{0.96\textwidth}
  3674. \[
  3675. \begin{array}{lcl}
  3676. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3677. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3678. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3679. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3680. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3681. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3682. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3683. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3684. \end{array}
  3685. \]
  3686. \end{minipage}
  3687. }
  3688. \caption{The abstract syntax of $R_2$.}
  3689. \label{fig:r2-syntax}
  3690. \end{figure}
  3691. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3692. the parts that are the same as the interpreter for $R_1$
  3693. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3694. evaluate to the corresponding Boolean values. The conditional
  3695. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3696. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3697. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3698. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3699. you might expect, but note that the \code{and} operation is
  3700. short-circuiting. That is, given the expression
  3701. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3702. $e_1$ evaluates to \code{\#f}.
  3703. With the increase in the number of primitive operations, the
  3704. interpreter code for them could become repetitive without some
  3705. care. In Figure~\ref{fig:interp-R2} we factor out the different parts
  3706. of the code for primitive operations into the \code{interp-op}
  3707. function and the similar parts of the code into the match clause for
  3708. \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3709. \code{interp-op} for the \code{and} operation because of the
  3710. short-circuiting behavior in the order of evaluation of its arguments.
  3711. \begin{figure}[tbp]
  3712. \begin{lstlisting}
  3713. (define (interp-op op)
  3714. (match op
  3715. ...
  3716. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3717. ['eq? (lambda (v1 v2)
  3718. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3719. (and (boolean? v1) (boolean? v2)))
  3720. (eq? v1 v2)]))]
  3721. ['< (lambda (v1 v2)
  3722. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3723. ['<= (lambda (v1 v2)
  3724. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3725. ['> (lambda (v1 v2)
  3726. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3727. ['>= (lambda (v1 v2)
  3728. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3729. [else (error 'interp-op "unknown operator")]))
  3730. (define (interp-exp env)
  3731. (lambda (e)
  3732. (define recur (interp-exp env))
  3733. (match e
  3734. ...
  3735. [(Bool b) b]
  3736. [(If cnd thn els)
  3737. (define b (recur cnd))
  3738. (match b
  3739. [#t (recur thn)]
  3740. [#f (recur els)])]
  3741. [(Prim 'and (list e1 e2))
  3742. (define v1 (recur e1))
  3743. (match v1
  3744. [#t (match (recur e2) [#t #t] [#f #f])]
  3745. [#f #f])]
  3746. [(Prim op args)
  3747. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3748. )))
  3749. (define (interp-R2 p)
  3750. (match p
  3751. [(Program info e)
  3752. ((interp-exp '()) e)]
  3753. ))
  3754. \end{lstlisting}
  3755. \caption{Interpreter for the $R_2$ language.}
  3756. \label{fig:interp-R2}
  3757. \end{figure}
  3758. \section{Type Checking $R_2$ Programs}
  3759. \label{sec:type-check-r2}
  3760. \index{type checking}
  3761. \index{semantic analysis}
  3762. It is helpful to think about type checking in two complementary
  3763. ways. A type checker predicts the type of value that will be produced
  3764. by each expression in the program. For $R_2$, we have just two types,
  3765. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3766. \begin{lstlisting}
  3767. (+ 10 (- (+ 12 20)))
  3768. \end{lstlisting}
  3769. produces an \key{Integer} while
  3770. \begin{lstlisting}
  3771. (and (not #f) #t)
  3772. \end{lstlisting}
  3773. produces a \key{Boolean}.
  3774. Another way to think about type checking is that it enforces a set of
  3775. rules about which operators can be applied to which kinds of
  3776. values. For example, our type checker for $R_2$ will signal an error
  3777. for the below expression because, as we have seen above, the
  3778. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3779. checker enforces the rule that the argument of \code{not} must be a
  3780. \key{Boolean}.
  3781. \begin{lstlisting}
  3782. (not (+ 10 (- (+ 12 20))))
  3783. \end{lstlisting}
  3784. The type checker for $R_2$ is a structurally recursive function over
  3785. the AST. Figure~\ref{fig:type-check-R2} defines the
  3786. \code{type-check-exp} function. The code for the type checker is in
  3787. the file \code{type-check-R2.rkt} of the support code.
  3788. %
  3789. Given an input expression \code{e}, the type checker either returns a
  3790. type (\key{Integer} or \key{Boolean}) or it signals an error. The
  3791. type of an integer literal is \code{Integer} and the type of a Boolean
  3792. literal is \code{Boolean}. To handle variables, the type checker uses
  3793. the environment \code{env} to map variables to types. Consider the
  3794. clause for \key{let}. We type check the initializing expression to
  3795. obtain its type \key{T} and then associate type \code{T} with the
  3796. variable \code{x} in the environment used to type check the body of
  3797. the \key{let}. Thus, when the type checker encounters a use of
  3798. variable \code{x}, it can find its type in the environment.
  3799. \begin{figure}[tbp]
  3800. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3801. (define (type-check-exp env)
  3802. (lambda (e)
  3803. (match e
  3804. [(Var x)
  3805. (let ([t (dict-ref env x)])
  3806. (values (Var x) t))]
  3807. [(Int n) (values (Int n) 'Integer)]
  3808. [(Bool b) (values (Bool b) 'Boolean)]
  3809. [(Let x e body)
  3810. (define-values (e^ Te) ((type-check-exp env) e))
  3811. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  3812. (values (Let x e^ b) Tb)]
  3813. [(If cnd thn els)
  3814. (define-values (c Tc) ((type-check-exp env) cnd))
  3815. (define-values (t Tt) ((type-check-exp env) thn))
  3816. (define-values (e Te) ((type-check-exp env) els))
  3817. (unless (type-equal? Tc 'Boolean)
  3818. (error 'type-check-exp "condition should be Boolean, not ~a" Tc))
  3819. (unless (type-equal? Tt Te)
  3820. (error 'type-check-exp "types of branches not equal, ~a != ~a" Tt Te))
  3821. (values (If c t e) Te)]
  3822. [(Prim 'eq? (list e1 e2))
  3823. (define-values (e1^ T1) ((type-check-exp env) e1))
  3824. (define-values (e2^ T2) ((type-check-exp env) e2))
  3825. (unless (type-equal? T1 T2)
  3826. (error 'type-check-exp "argument types of eq?: ~a != ~a" T1 T2))
  3827. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  3828. [(Prim op es)
  3829. (define-values (new-es ts)
  3830. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  3831. (define t-ret (type-check-op op ts))
  3832. (values (Prim op new-es) t-ret)]
  3833. [else
  3834. (error 'type-check-exp "couldn't match" e)])))
  3835. (define (type-check-R2 e)
  3836. (match e
  3837. [(Program info body)
  3838. (define-values (body^ Tb) ((type-check-exp '()) body))
  3839. (unless (type-equal? Tb 'Integer)
  3840. (error 'type-check-R2 "result type must be Integer, not ~a" Tb))
  3841. (Program info body^)]
  3842. [else (error 'type-check-R2 "couldn't match ~a" e)]))
  3843. \end{lstlisting}
  3844. \caption{Type checker for the $R_2$ language.}
  3845. \label{fig:type-check-R2}
  3846. \end{figure}
  3847. Figure~\ref{fig:type-check-aux-R2} defines three auxilliary functions
  3848. that are used in the type checker. The \code{operator-types} function
  3849. defines a dictionary that maps the operator names to their parameter
  3850. and return types. The \code{type-equal?} function determines whether
  3851. two types are equal, which for now simply dispatches to \code{equal?}
  3852. (deep equality). The \code{type-check-op} function looks up the
  3853. operator in the \code{operator-types} dictionary and then checks
  3854. whether the argument types are equal to the parameter types. The
  3855. result is the return type of the operator.
  3856. \begin{figure}[tbp]
  3857. \begin{lstlisting}
  3858. (define (operator-types)
  3859. '((+ . ((Integer Integer) . Integer))
  3860. (- . ((Integer Integer) . Integer))
  3861. (and . ((Boolean Boolean) . Boolean))
  3862. (or . ((Boolean Boolean) . Boolean))
  3863. (< . ((Integer Integer) . Boolean))
  3864. (<= . ((Integer Integer) . Boolean))
  3865. (> . ((Integer Integer) . Boolean))
  3866. (>= . ((Integer Integer) . Boolean))
  3867. (- . ((Integer) . Integer))
  3868. (not . ((Boolean) . Boolean))
  3869. (read . (() . Integer))
  3870. ))
  3871. (define (type-equal? t1 t2)
  3872. (equal? t1 t2))
  3873. (define (type-check-op op arg-types)
  3874. (match (dict-ref (operator-types) op)
  3875. [`(,param-types . ,return-type)
  3876. (for ([at arg-types] [pt param-types])
  3877. (unless (type-equal? at pt)
  3878. (error 'type-check-op
  3879. "argument and parameter mismatch, ~a != ~a" at pt)))
  3880. return-type]
  3881. [else
  3882. (error 'type-check-op "unrecognized operator ~a" op)]))
  3883. \end{lstlisting}
  3884. \caption{Auxilliary functions for type checking.}
  3885. \label{fig:type-check-aux-R2}
  3886. \end{figure}
  3887. \begin{exercise}\normalfont
  3888. Create 10 new example programs in $R_2$. Half of the example programs
  3889. should have a type error. For those programs, to signal that a type
  3890. error is expected, create an empty file with the same base name but
  3891. with file extension \code{.tyerr}. For example, if the test
  3892. \code{r2\_14.rkt} is expected to error, then create an empty file
  3893. named \code{r2\_14.tyerr}. The other half of the example programs
  3894. should not have type errors. Note that if the type checker does not
  3895. signal an error for a program, then interpreting that program should
  3896. not encounter an error.
  3897. \end{exercise}
  3898. \section{Shrink the $R_2$ Language}
  3899. \label{sec:shrink-r2}
  3900. The $R_2$ language includes several operators that are easily
  3901. expressible in terms of other operators. For example, subtraction is
  3902. expressible in terms of addition and negation.
  3903. \[
  3904. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3905. \]
  3906. Several of the comparison operations are expressible in terms of
  3907. less-than and logical negation.
  3908. \[
  3909. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3910. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3911. \]
  3912. The \key{let} is needed in the above translation to ensure that
  3913. expression $e_1$ is evaluated before $e_2$.
  3914. By performing these translations near the front-end of the compiler,
  3915. the later passes of the compiler do not need to deal with these
  3916. constructs, making those passes shorter. On the other hand, sometimes
  3917. these translations make it more difficult to generate the most
  3918. efficient code with respect to the number of instructions. However,
  3919. these differences typically do not affect the number of accesses to
  3920. memory, which is the primary factor that determines execution time on
  3921. modern computer architectures.
  3922. \begin{exercise}\normalfont
  3923. Implement the pass \code{shrink} that removes subtraction,
  3924. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3925. by translating them to other constructs in $R_2$. Create tests to
  3926. make sure that the behavior of all of these constructs stays the
  3927. same after translation.
  3928. \end{exercise}
  3929. \section{The x86$_1$ Language}
  3930. \label{sec:x86-1}
  3931. \index{x86}
  3932. To implement the new logical operations, the comparison operations,
  3933. and the \key{if} expression, we need to delve further into the x86
  3934. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3935. the concrete and abstract syntax for a larger subset of x86 that
  3936. includes instructions for logical operations, comparisons, and
  3937. conditional jumps.
  3938. One small challenge is that x86 does not provide an instruction that
  3939. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3940. However, the \code{xorq} instruction can be used to encode \code{not}.
  3941. The \key{xorq} instruction takes two arguments, performs a pairwise
  3942. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3943. and writes the results into its second argument. Recall the truth
  3944. table for exclusive-or:
  3945. \begin{center}
  3946. \begin{tabular}{l|cc}
  3947. & 0 & 1 \\ \hline
  3948. 0 & 0 & 1 \\
  3949. 1 & 1 & 0
  3950. \end{tabular}
  3951. \end{center}
  3952. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3953. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3954. for the bit $1$, the result is the opposite of the second bit. Thus,
  3955. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3956. the first argument:
  3957. \[
  3958. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3959. \qquad\Rightarrow\qquad
  3960. \begin{array}{l}
  3961. \key{movq}~ \Arg\key{,} \Var\\
  3962. \key{xorq}~ \key{\$1,} \Var
  3963. \end{array}
  3964. \]
  3965. \begin{figure}[tp]
  3966. \fbox{
  3967. \begin{minipage}{0.96\textwidth}
  3968. \[
  3969. \begin{array}{lcl}
  3970. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3971. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3972. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3973. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3974. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3975. \key{subq} \; \Arg\key{,} \Arg \mid
  3976. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3977. && \gray{ \key{callq} \; \itm{label} \mid
  3978. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3979. && \gray{ \itm{label}\key{:}\; \Instr }
  3980. \mid \key{xorq}~\Arg\key{,}~\Arg
  3981. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3982. && \key{set}cc~\Arg
  3983. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3984. \mid \key{j}cc~\itm{label}
  3985. \\
  3986. x86_1 &::= & \gray{ \key{.globl main} }\\
  3987. & & \gray{ \key{main:} \; \Instr\ldots }
  3988. \end{array}
  3989. \]
  3990. \end{minipage}
  3991. }
  3992. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3993. \label{fig:x86-1-concrete}
  3994. \end{figure}
  3995. \begin{figure}[tp]
  3996. \fbox{
  3997. \begin{minipage}{0.96\textwidth}
  3998. \small
  3999. \[
  4000. \begin{array}{lcl}
  4001. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4002. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4003. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4004. \mid \BYTEREG{\itm{bytereg}} \\
  4005. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4006. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4007. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4008. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4009. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4010. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4011. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4012. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4013. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4014. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4015. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4016. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4017. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4018. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4019. \end{array}
  4020. \]
  4021. \end{minipage}
  4022. }
  4023. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4024. \label{fig:x86-1}
  4025. \end{figure}
  4026. Next we consider the x86 instructions that are relevant for compiling
  4027. the comparison operations. The \key{cmpq} instruction compares its two
  4028. arguments to determine whether one argument is less than, equal, or
  4029. greater than the other argument. The \key{cmpq} instruction is unusual
  4030. regarding the order of its arguments and where the result is
  4031. placed. The argument order is backwards: if you want to test whether
  4032. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4033. \key{cmpq} is placed in the special EFLAGS register. This register
  4034. cannot be accessed directly but it can be queried by a number of
  4035. instructions, including the \key{set} instruction. The \key{set}
  4036. instruction puts a \key{1} or \key{0} into its destination depending
  4037. on whether the comparison came out according to the condition code
  4038. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4039. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4040. The \key{set} instruction has an annoying quirk in that its
  4041. destination argument must be single byte register, such as \code{al}
  4042. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4043. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4044. then be used to move from a single byte register to a normal 64-bit
  4045. register.
  4046. The x86 instruction for conditional jump are relevant to the
  4047. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4048. updates the program counter to point to the instruction after the
  4049. indicated label depending on whether the result in the EFLAGS register
  4050. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4051. instruction falls through to the next instruction. The abstract
  4052. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4053. that it separates the instruction name from the condition code. For
  4054. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4055. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4056. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4057. instruction to set the EFLAGS register.
  4058. \section{The $C_1$ Intermediate Language}
  4059. \label{sec:c1}
  4060. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4061. we need to grow that intermediate language to handle the new features
  4062. in $R_2$: Booleans and conditional expressions.
  4063. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4064. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4065. particular, we add logical and comparison operators to the $\Exp$
  4066. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4067. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4068. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4069. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4070. sequence of statements may now end with a \code{goto} or a conditional
  4071. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4072. depending on the outcome of the comparison. In
  4073. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4074. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4075. and \key{goto}'s.
  4076. \begin{figure}[tbp]
  4077. \fbox{
  4078. \begin{minipage}{0.96\textwidth}
  4079. \small
  4080. \[
  4081. \begin{array}{lcl}
  4082. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4083. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4084. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4085. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4086. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4087. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4088. \mid \key{goto}~\itm{label}\key{;}\\
  4089. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4090. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4091. \end{array}
  4092. \]
  4093. \end{minipage}
  4094. }
  4095. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4096. \label{fig:c1-concrete-syntax}
  4097. \end{figure}
  4098. \begin{figure}[tp]
  4099. \fbox{
  4100. \begin{minipage}{0.96\textwidth}
  4101. \small
  4102. \[
  4103. \begin{array}{lcl}
  4104. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4105. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4106. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4107. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4108. &\mid& \UNIOP{\key{'not}}{\Atm}
  4109. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4110. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4111. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4112. \mid \GOTO{\itm{label}} \\
  4113. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4114. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4115. \end{array}
  4116. \]
  4117. \end{minipage}
  4118. }
  4119. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4120. (Figure~\ref{fig:c0-syntax}).}
  4121. \label{fig:c1-syntax}
  4122. \end{figure}
  4123. \clearpage
  4124. \section{Remove Complex Operands}
  4125. \label{sec:remove-complex-opera-R2}
  4126. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4127. \code{rco-atom} functions according to the definition of the output
  4128. language for this pass, $R_2^{\dagger}$, the administrative normal
  4129. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4130. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4131. three sub-expressions of an \code{If} are allowed to be complex
  4132. expressions in the output of \code{remove-complex-opera*}, but the
  4133. operands of \code{not} and the comparisons must be atoms. Regarding
  4134. the \code{If} form, it is particularly important to \textbf{not}
  4135. replace its condition with a temporary variable because that would
  4136. interfere with the generation of high-quality output in the
  4137. \code{explicate-control} pass.
  4138. \begin{figure}[tp]
  4139. \centering
  4140. \fbox{
  4141. \begin{minipage}{0.96\textwidth}
  4142. \[
  4143. \begin{array}{rcl}
  4144. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4145. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4146. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4147. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4148. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4149. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4150. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4151. \end{array}
  4152. \]
  4153. \end{minipage}
  4154. }
  4155. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4156. \label{fig:r2-anf-syntax}
  4157. \end{figure}
  4158. \section{Explicate Control}
  4159. \label{sec:explicate-control-r2}
  4160. Recall that the purpose of \code{explicate-control} is to make the
  4161. order of evaluation explicit in the syntax of the program. With the
  4162. addition of \key{if} in $R_2$ this get more interesting.
  4163. As a motivating example, consider the following program that has an
  4164. \key{if} expression nested in the predicate of another \key{if}.
  4165. % s1_41.rkt
  4166. \begin{center}
  4167. \begin{minipage}{0.96\textwidth}
  4168. \begin{lstlisting}
  4169. (let ([x (read)])
  4170. (let ([y (read)])
  4171. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4172. (+ y 2)
  4173. (+ y 10))))
  4174. \end{lstlisting}
  4175. \end{minipage}
  4176. \end{center}
  4177. %
  4178. The naive way to compile \key{if} and the comparison would be to
  4179. handle each of them in isolation, regardless of their context. Each
  4180. comparison would be translated into a \key{cmpq} instruction followed
  4181. by a couple instructions to move the result from the EFLAGS register
  4182. into a general purpose register or stack location. Each \key{if} would
  4183. be translated into the combination of a \key{cmpq} and a conditional
  4184. jump. The generated code for the inner \key{if} in the above example
  4185. would be as follows.
  4186. \begin{center}
  4187. \begin{minipage}{0.96\textwidth}
  4188. \begin{lstlisting}
  4189. ...
  4190. cmpq $1, x ;; (< x 1)
  4191. setl %al
  4192. movzbq %al, tmp
  4193. cmpq $1, tmp ;; (if (< x 1) ...)
  4194. je then_branch_1
  4195. jmp else_branch_1
  4196. ...
  4197. \end{lstlisting}
  4198. \end{minipage}
  4199. \end{center}
  4200. However, if we take context into account we can do better and reduce
  4201. the use of \key{cmpq} and EFLAG-accessing instructions.
  4202. One idea is to try and reorganize the code at the level of $R_2$,
  4203. pushing the outer \key{if} inside the inner one. This would yield the
  4204. following code.
  4205. \begin{center}
  4206. \begin{minipage}{0.96\textwidth}
  4207. \begin{lstlisting}
  4208. (let ([x (read)])
  4209. (let ([y (read)])
  4210. (if (< x 1)
  4211. (if (eq? x 0)
  4212. (+ y 2)
  4213. (+ y 10))
  4214. (if (eq? x 2)
  4215. (+ y 2)
  4216. (+ y 10)))))
  4217. \end{lstlisting}
  4218. \end{minipage}
  4219. \end{center}
  4220. Unfortunately, this approach duplicates the two branches, and a
  4221. compiler must never duplicate code!
  4222. We need a way to perform the above transformation, but without
  4223. duplicating code. That is, we need a way for different parts of a
  4224. program to refer to the same piece of code, that is, to \emph{share}
  4225. code. At the level of x86 assembly this is straightforward because we
  4226. can label the code for each of the branches and insert jumps in all
  4227. the places that need to execute the branches. At the higher level of
  4228. our intermediate languages, we need to move away from abstract syntax
  4229. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4230. standard program representation called a \emph{control flow graph}
  4231. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4232. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4233. called a \emph{basic block}, and each edge represents a jump to
  4234. another block. The \key{Program} construct of $C_0$ and $C_1$ contains
  4235. a control flow graph represented as an alist mapping labels to basic
  4236. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4237. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4238. \code{remove-complex-opera*} pass and then the
  4239. \code{explicate-control} pass on the example program. We walk through
  4240. the output program and then discuss the algorithm.
  4241. %
  4242. Following the order of evaluation in the output of
  4243. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4244. and then the less-than-comparison to \code{1} in the predicate of the
  4245. inner \key{if}. In the output of \code{explicate-control}, in the
  4246. block labeled \code{start}, this becomes two assignment statements
  4247. followed by a conditional \key{goto} to label \code{block40} or
  4248. \code{block41}. The blocks associated with those labels contain the
  4249. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4250. respectively. Regarding the block labeled with \code{block40}, we
  4251. start with the comparison to \code{0} and then have a conditional
  4252. goto, either to label \code{block38} or label \code{block39}, which
  4253. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4254. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4255. similar.
  4256. \begin{figure}[tbp]
  4257. \begin{tabular}{lll}
  4258. \begin{minipage}{0.4\textwidth}
  4259. % s1_41.rkt
  4260. \begin{lstlisting}
  4261. (let ([x (read)])
  4262. (let ([y (read)])
  4263. (if (if (< x 1)
  4264. (eq? x 0)
  4265. (eq? x 2))
  4266. (+ y 2)
  4267. (+ y 10))))
  4268. \end{lstlisting}
  4269. \hspace{40pt}$\Downarrow$
  4270. \begin{lstlisting}
  4271. (let ([x (read)])
  4272. (let ([y (read)])
  4273. (if (if (< x 1)
  4274. (eq? x 0)
  4275. (eq? x 2))
  4276. (+ y 2)
  4277. (+ y 10))))
  4278. \end{lstlisting}
  4279. \end{minipage}
  4280. &
  4281. $\Rightarrow$
  4282. &
  4283. \begin{minipage}{0.55\textwidth}
  4284. \begin{lstlisting}
  4285. start:
  4286. x = (read);
  4287. y = (read);
  4288. if (< x 1)
  4289. goto block40;
  4290. else
  4291. goto block41;
  4292. block40:
  4293. if (eq? x 0)
  4294. goto block38;
  4295. else
  4296. goto block39;
  4297. block41:
  4298. if (eq? x 2)
  4299. goto block38;
  4300. else
  4301. goto block39;
  4302. block38:
  4303. return (+ y 2);
  4304. block39:
  4305. return (+ y 10);
  4306. \end{lstlisting}
  4307. \end{minipage}
  4308. \end{tabular}
  4309. \caption{Translation from $R_2$ to $C_1$
  4310. via the \code{explicate-control}.}
  4311. \label{fig:explicate-control-s1-38}
  4312. \end{figure}
  4313. The nice thing about the output of \code{explicate-control} is that
  4314. there are no unnecessary comparisons and every comparison is part of a
  4315. conditional jump.
  4316. %% The down-side of this output is that it includes
  4317. %% trivial blocks, such as the blocks labeled \code{block92} through
  4318. %% \code{block95}, that only jump to another block. We discuss a solution
  4319. %% to this problem in Section~\ref{sec:opt-jumps}.
  4320. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4321. \code{explicate-control} for $R_1$ using two mutually recursive
  4322. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4323. former function translates expressions in tail position whereas the
  4324. later function translates expressions on the right-hand-side of a
  4325. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4326. new kind of context to deal with: the predicate position of the
  4327. \key{if}. We need another function, \code{explicate-pred}, that takes
  4328. an $R_2$ expression and two blocks for the then-branch and
  4329. else-branch. The output of \code{explicate-pred} is a block.
  4330. %
  4331. %% Note that the three explicate functions need to construct a
  4332. %% control-flow graph, which we recommend they do via updates to a global
  4333. %% variable.
  4334. %
  4335. In the following paragraphs we discuss specific cases in the
  4336. \code{explicate-pred} function as well as the additions to the
  4337. \code{explicate-tail} and \code{explicate-assign} functions.
  4338. The function \code{explicate-pred} will need a case for every
  4339. expression that can have type \code{Boolean}. We detail a few cases
  4340. here and leave the rest for the reader. The input to this function is
  4341. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4342. the enclosing \key{if}, though some care will be needed regarding how
  4343. we represent the blocks. Suppose the expression is the Boolean
  4344. \code{\#t}. Then we can perform a kind of partial evaluation
  4345. \index{partial evaluation} and translate it to the ``then'' branch
  4346. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4347. \[
  4348. \key{\#t} \quad\Rightarrow\quad B_1,
  4349. \qquad\qquad\qquad
  4350. \key{\#f} \quad\Rightarrow\quad B_2
  4351. \]
  4352. These two cases demonstrate that we sometimes discard one of the
  4353. blocks that are input to \code{explicate-pred}. We will need to
  4354. arrange for the blocks that we actually use to appear in the resulting
  4355. control-flow graph, but not the discarded blocks.
  4356. The case for \key{if} in \code{explicate-pred} is particularly
  4357. illuminating as it deals with the challenges that we discussed above
  4358. regarding the example of the nested \key{if} expressions. The
  4359. ``then'' and ``else'' branches of the current \key{if} inherit their
  4360. context from the current one, that is, predicate context. So we
  4361. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4362. branches. For both of those recursive calls, we shall pass the blocks
  4363. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4364. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4365. duplicating code, we need to add these blocks to the control-flow
  4366. graph so that we can instead refer to them by name and execute them
  4367. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4368. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4369. we don't want to prematurely add them to the control-flow graph if
  4370. they end up being discarded.
  4371. The solution to this conundrum is to use \emph{lazy evaluation} to
  4372. delay adding the blocks to the control-flow graph until the points
  4373. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4374. evaluation} Racket provides support for lazy evaluation with the
  4375. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4376. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4377. \index{delay} creates a \emph{promise}\index{promise} in which the
  4378. evaluation of the expressions is postponed. When \key{(force}
  4379. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4380. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4381. $e_n$ is cached in the promise and returned. If \code{force} is
  4382. applied again to the same promise, then the cached result is returned.
  4383. We use lazy evaluation for the input and output blocks of the
  4384. functions \code{explicate-pred} and \code{explicate-assign} and for
  4385. the output block of \code{explicate-tail}. So instead of taking and
  4386. returns blocks, they take and return promised blocks. Furthermore,
  4387. when we come to a situation in which we a block might be used more
  4388. than once, as in the case for \code{if} above, we can transform the
  4389. promise into a new promise that will add the block to the control-flow
  4390. graph and return a \code{goto}. The following auxiliary function
  4391. accomplishes this task. It begins with \code{delay} to create a
  4392. promise. When forced, it will in turn force the input block. If that
  4393. block is already a \code{goto} (because it was already added to the
  4394. control-flow graph), then we return that \code{goto}. Otherwise we add
  4395. the block to the control-flow graph with another auxiliary function
  4396. named \code{add-node} that returns the new label, and then return the
  4397. \code{goto}.
  4398. \begin{lstlisting}
  4399. (define (block->goto block)
  4400. (delay
  4401. (define b (force block))
  4402. (match b
  4403. [(Goto label) (Goto label)]
  4404. [else (Goto (add-node b))]
  4405. )))
  4406. \end{lstlisting}
  4407. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4408. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4409. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4410. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4411. results from the two recursive calls. We complete the case for
  4412. \code{if} by recursively apply \code{explicate-pred} to the condition
  4413. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4414. the result $B_5$.
  4415. \[
  4416. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4417. \quad\Rightarrow\quad
  4418. B_5
  4419. \]
  4420. Next, consider the case for a less-than comparison in
  4421. \code{explicate-pred}. We translate it to an \code{if} statement,
  4422. whose two branches are required to be \code{goto}'s. So we apply
  4423. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4424. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4425. $G_2$. The translation of the less-than comparison is as follows.
  4426. \[
  4427. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4428. \begin{array}{l}
  4429. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4430. \key{else} \; G_2
  4431. \end{array}
  4432. \]
  4433. The \code{explicate-tail} function needs to be updated to use lazy
  4434. evaluation and it needs an additional case for \key{if}. Each of the
  4435. cases that return an AST node need use \code{delay} to instead return
  4436. a promise of an AST node. Recall that \code{explicate-tail} has an
  4437. accumulator parameter that is a block, which now becomes a promise of
  4438. a block, which we refer to as $B_0$.
  4439. In the case for \code{if} in \code{explicate-tail}, the two branches
  4440. inherit the current context, so they are in tail position. Thus, the
  4441. recursive calls on the ``then'' and ``else'' branch should be calls to
  4442. \code{explicate-tail}.
  4443. %
  4444. We need to pass $B_0$ as the accumulator argument for both of these
  4445. recursive calls, but we need to be careful not to duplicate $B_0$.
  4446. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4447. to the control-flow graph and obtain a promised goto $G_0$.
  4448. %
  4449. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4450. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4451. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4452. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4453. $B_2$. Then the \key{if} as a whole translates to $B_3$.
  4454. \[
  4455. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4456. \]
  4457. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4458. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4459. %% should not be confused with the labels for the blocks that appear in
  4460. %% the generated code. We initially construct unlabeled blocks; we only
  4461. %% attach labels to blocks when we add them to the control-flow graph, as
  4462. %% we see in the next case.
  4463. Next consider the case for \key{if} in the \code{explicate-assign}
  4464. function. The context of the \key{if} is an assignment to some
  4465. variable $x$ and then the control continues to some promised block
  4466. $B_1$. The code that we generate for both the ``then'' and ``else''
  4467. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4468. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4469. branches of the \key{if} inherit the current context, so they are in
  4470. assignment positions. Let $B_2$ be the result of applying
  4471. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4472. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4473. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4474. the result of applying \code{explicate-pred} to the predicate
  4475. $\itm{cnd}$ and the blocks $B_2$ and $B_3$. The \key{if} as a whole
  4476. translates to the block $B_4$.
  4477. \[
  4478. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4479. \]
  4480. This completes the description of \code{explicate-control} for $R_2$.
  4481. The way in which the \code{shrink} pass transforms logical operations
  4482. such as \code{and} and \code{or} can impact the quality of code
  4483. generated by \code{explicate-control}. For example, consider the
  4484. following program.
  4485. % s1_21.rkt
  4486. \begin{lstlisting}
  4487. (if (and (eq? (read) 0) (eq? (read) 1))
  4488. 0
  4489. 42)
  4490. \end{lstlisting}
  4491. The \code{and} operation should transform into something that the
  4492. \code{explicat-pred} function can still analyze and descend through to
  4493. reach the underlying \code{eq?} conditions. Ideally, your
  4494. \code{explicate-control} pass should generate code similar to the
  4495. following for the above program.
  4496. \begin{center}
  4497. \begin{lstlisting}
  4498. start:
  4499. tmp1 = (read);
  4500. if (eq? tmp1 0)
  4501. goto block40;
  4502. else
  4503. goto block39;
  4504. block40:
  4505. tmp2 = (read);
  4506. if (eq? tmp2 1)
  4507. goto block38;
  4508. else
  4509. goto block39;
  4510. block38:
  4511. return 0;
  4512. block39:
  4513. return 42;
  4514. \end{lstlisting}
  4515. \end{center}
  4516. \begin{exercise}\normalfont
  4517. Implement the pass \code{explicate-control} by adding the cases for
  4518. \key{if} to the functions for tail and assignment contexts, and
  4519. implement \code{explicate-pred} for predicate contexts. Create test
  4520. cases that exercise all of the new cases in the code for this pass.
  4521. \end{exercise}
  4522. \section{Select Instructions}
  4523. \label{sec:select-r2}
  4524. \index{instruction selection}
  4525. Recall that the \code{select-instructions} pass lowers from our
  4526. $C$-like intermediate representation to the pseudo-x86 language, which
  4527. is suitable for conducting register allocation. The pass is
  4528. implemented using three auxiliary functions, one for each of the
  4529. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4530. For $\Atm$, we have new cases for the Booleans. We take the usual
  4531. approach of encoding them as integers, with true as 1 and false as 0.
  4532. \[
  4533. \key{\#t} \Rightarrow \key{1}
  4534. \qquad
  4535. \key{\#f} \Rightarrow \key{0}
  4536. \]
  4537. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4538. be implemented in terms of \code{xorq} as we discussed at the
  4539. beginning of this section. Given an assignment
  4540. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4541. if the left-hand side $\itm{var}$ is
  4542. the same as $\Atm$, then just the \code{xorq} suffices.
  4543. \[
  4544. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4545. \quad\Rightarrow\quad
  4546. \key{xorq}~\key{\$}1\key{,}~\Var
  4547. \]
  4548. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4549. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4550. x86. Then we have
  4551. \[
  4552. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4553. \quad\Rightarrow\quad
  4554. \begin{array}{l}
  4555. \key{movq}~\Arg\key{,}~\Var\\
  4556. \key{xorq}~\key{\$}1\key{,}~\Var
  4557. \end{array}
  4558. \]
  4559. Next consider the cases for \code{eq?} and less-than comparison.
  4560. Translating these operations to x86 is slightly involved due to the
  4561. unusual nature of the \key{cmpq} instruction discussed above. We
  4562. recommend translating an assignment from \code{eq?} into the following
  4563. sequence of three instructions. \\
  4564. \begin{tabular}{lll}
  4565. \begin{minipage}{0.4\textwidth}
  4566. \begin{lstlisting}
  4567. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4568. \end{lstlisting}
  4569. \end{minipage}
  4570. &
  4571. $\Rightarrow$
  4572. &
  4573. \begin{minipage}{0.4\textwidth}
  4574. \begin{lstlisting}
  4575. cmpq |$\Arg_2$|, |$\Arg_1$|
  4576. sete %al
  4577. movzbq %al, |$\Var$|
  4578. \end{lstlisting}
  4579. \end{minipage}
  4580. \end{tabular} \\
  4581. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4582. and conditional \key{goto}. Both are straightforward to handle. A
  4583. \key{goto} becomes a jump instruction.
  4584. \[
  4585. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4586. \]
  4587. A conditional \key{goto} becomes a compare instruction followed
  4588. by a conditional jump (for ``then'') and the fall-through is
  4589. to a regular jump (for ``else'').\\
  4590. \begin{tabular}{lll}
  4591. \begin{minipage}{0.4\textwidth}
  4592. \begin{lstlisting}
  4593. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4594. goto |$\ell_1$|;
  4595. else
  4596. goto |$\ell_2$|;
  4597. \end{lstlisting}
  4598. \end{minipage}
  4599. &
  4600. $\Rightarrow$
  4601. &
  4602. \begin{minipage}{0.4\textwidth}
  4603. \begin{lstlisting}
  4604. cmpq |$\Arg_2$|, |$\Arg_1$|
  4605. je |$\ell_1$|
  4606. jmp |$\ell_2$|
  4607. \end{lstlisting}
  4608. \end{minipage}
  4609. \end{tabular} \\
  4610. \begin{exercise}\normalfont
  4611. Expand your \code{select-instructions} pass to handle the new features
  4612. of the $R_2$ language. Test the pass on all the examples you have
  4613. created and make sure that you have some test programs that use the
  4614. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4615. the output using the \code{interp-x86} interpreter
  4616. (Appendix~\ref{appendix:interp}).
  4617. \end{exercise}
  4618. \section{Register Allocation}
  4619. \label{sec:register-allocation-r2}
  4620. \index{register allocation}
  4621. The changes required for $R_2$ affect liveness analysis, building the
  4622. interference graph, and assigning homes, but the graph coloring
  4623. algorithm itself does not change.
  4624. \subsection{Liveness Analysis}
  4625. \label{sec:liveness-analysis-r2}
  4626. \index{liveness analysis}
  4627. Recall that for $R_1$ we implemented liveness analysis for a single
  4628. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4629. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4630. produces many basic blocks arranged in a control-flow graph. The first
  4631. question we need to consider is: what order should we process the
  4632. basic blocks? Recall that to perform liveness analysis, we need to
  4633. know the live-after set. If a basic block has no successor blocks
  4634. (i.e. no out-edges in the control flow graph), then it has an empty
  4635. live-after set and we can immediately apply liveness analysis to
  4636. it. If a basic block has some successors, then we need to complete
  4637. liveness analysis on those blocks first. Furthermore, we know that
  4638. the control flow graph does not contain any cycles because $R_2$ does
  4639. not include loops
  4640. %
  4641. \footnote{If we were to add loops to the language, then the CFG could
  4642. contain cycles and we would instead need to use the classic worklist
  4643. algorithm for computing the fixed point of the liveness
  4644. analysis~\citep{Aho:1986qf}.}.
  4645. %
  4646. Returning to the question of what order should we process the basic
  4647. blocks, the answer is reverse topological order. We recommend using
  4648. the \code{tsort} (topological sort) and \code{transpose} functions of
  4649. the Racket \code{graph} package to obtain this ordering.
  4650. \index{topological order}
  4651. \index{topological sort}
  4652. The next question is how to compute the live-after set of a block
  4653. given the live-before sets of all its successor blocks. (There can be
  4654. more than one because of conditional jumps.) During compilation we do
  4655. not know which way a conditional jump will go, so we do not know which
  4656. of the successor's live-before set to use. The solution to this
  4657. challenge is based on the observation that there is no harm to the
  4658. correctness of the compiler if we classify more variables as live than
  4659. the ones that are truly live during a particular execution of the
  4660. block. Thus, we can take the union of the live-before sets from all
  4661. the successors to be the live-after set for the block. Once we have
  4662. computed the live-after set, we can proceed to perform liveness
  4663. analysis on the block just as we did in
  4664. Section~\ref{sec:liveness-analysis-r1}.
  4665. The helper functions for computing the variables in an instruction's
  4666. argument and for computing the variables read-from ($R$) or written-to
  4667. ($W$) by an instruction need to be updated to handle the new kinds of
  4668. arguments and instructions in x86$_1$.
  4669. \subsection{Build Interference}
  4670. \label{sec:build-interference-r2}
  4671. Many of the new instructions in x86$_1$ can be handled in the same way
  4672. as the instructions in x86$_0$. Thus, if your code was already quite
  4673. general, it will not need to be changed to handle the new
  4674. instructions. If you code is not general enough, I recommend that you
  4675. change your code to be more general. For example, you can factor out
  4676. the computing of the the read and write sets for each kind of
  4677. instruction into two auxiliary functions.
  4678. Note that the \key{movzbq} instruction requires some special care,
  4679. just like the \key{movq} instruction. See rule number 3 in
  4680. Section~\ref{sec:build-interference}.
  4681. %% \subsection{Assign Homes}
  4682. %% \label{sec:assign-homes-r2}
  4683. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4684. %% to be updated to handle the \key{if} statement, simply by recursively
  4685. %% processing the child nodes. Hopefully your code already handles the
  4686. %% other new instructions, but if not, you can generalize your code.
  4687. \begin{exercise}\normalfont
  4688. Update the \code{register-allocation} pass so that it works for $R_2$
  4689. and test your compiler using your previously created programs on the
  4690. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4691. \end{exercise}
  4692. \section{Patch Instructions}
  4693. The second argument of the \key{cmpq} instruction must not be an
  4694. immediate value (such as an integer). So if you are comparing two
  4695. immediates, we recommend inserting a \key{movq} instruction to put the
  4696. second argument in \key{rax}.
  4697. %
  4698. The second argument of the \key{movzbq} must be a register.
  4699. %
  4700. There are no special restrictions on the x86 instructions \key{JmpIf}
  4701. and \key{Jmp}.
  4702. \begin{exercise}\normalfont
  4703. Update \code{patch-instructions} to handle the new x86 instructions.
  4704. Test your compiler using your previously created programs on the
  4705. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4706. \end{exercise}
  4707. \section{An Example Translation}
  4708. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4709. $R_2$ translated to x86, showing the results of
  4710. \code{explicate-control}, \code{select-instructions}, and the final
  4711. x86 assembly code.
  4712. \begin{figure}[tbp]
  4713. \begin{tabular}{lll}
  4714. \begin{minipage}{0.5\textwidth}
  4715. % s1_20.rkt
  4716. \begin{lstlisting}
  4717. (if (eq? (read) 1) 42 0)
  4718. \end{lstlisting}
  4719. $\Downarrow$
  4720. \begin{lstlisting}
  4721. start:
  4722. tmp7951 = (read);
  4723. if (eq? tmp7951 1) then
  4724. goto block7952;
  4725. else
  4726. goto block7953;
  4727. block7952:
  4728. return 42;
  4729. block7953:
  4730. return 0;
  4731. \end{lstlisting}
  4732. $\Downarrow$
  4733. \begin{lstlisting}
  4734. start:
  4735. callq read_int
  4736. movq %rax, tmp7951
  4737. cmpq $1, tmp7951
  4738. je block7952
  4739. jmp block7953
  4740. block7953:
  4741. movq $0, %rax
  4742. jmp conclusion
  4743. block7952:
  4744. movq $42, %rax
  4745. jmp conclusion
  4746. \end{lstlisting}
  4747. \end{minipage}
  4748. &
  4749. $\Rightarrow\qquad$
  4750. \begin{minipage}{0.4\textwidth}
  4751. \begin{lstlisting}
  4752. start:
  4753. callq read_int
  4754. movq %rax, %rcx
  4755. cmpq $1, %rcx
  4756. je block7952
  4757. jmp block7953
  4758. block7953:
  4759. movq $0, %rax
  4760. jmp conclusion
  4761. block7952:
  4762. movq $42, %rax
  4763. jmp conclusion
  4764. .globl main
  4765. main:
  4766. pushq %rbp
  4767. movq %rsp, %rbp
  4768. pushq %r13
  4769. pushq %r12
  4770. pushq %rbx
  4771. pushq %r14
  4772. subq $0, %rsp
  4773. jmp start
  4774. conclusion:
  4775. addq $0, %rsp
  4776. popq %r14
  4777. popq %rbx
  4778. popq %r12
  4779. popq %r13
  4780. popq %rbp
  4781. retq
  4782. \end{lstlisting}
  4783. \end{minipage}
  4784. \end{tabular}
  4785. \caption{Example compilation of an \key{if} expression to x86.}
  4786. \label{fig:if-example-x86}
  4787. \end{figure}
  4788. \begin{figure}[p]
  4789. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4790. \node (R2) at (0,2) {\large $R_2$};
  4791. \node (R2-2) at (3,2) {\large $R_2$};
  4792. \node (R2-3) at (6,2) {\large $R_2$};
  4793. \node (R2-4) at (9,2) {\large $R_2$};
  4794. \node (R2-5) at (9,0) {\large $R_2$};
  4795. \node (C1-1) at (3,-2) {\large $C_1$};
  4796. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4797. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4798. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4799. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4800. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4801. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4802. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4803. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4804. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4805. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4806. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4807. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4808. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4809. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4810. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4811. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4812. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4813. \end{tikzpicture}
  4814. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4815. \label{fig:R2-passes}
  4816. \end{figure}
  4817. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4818. compilation of $R_2$.
  4819. \section{Challenge: Optimize and Remove Jumps}
  4820. \label{sec:opt-jumps}
  4821. Recall that in the example output of \code{explicate-control} in
  4822. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4823. \code{block60} are trivial blocks, they do nothing but jump to another
  4824. block. The first goal of this challenge assignment is to remove those
  4825. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4826. \code{explicate-control} on the left and shows the result of bypassing
  4827. the trivial blocks on the right. Let us focus on \code{block61}. The
  4828. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4829. \code{block55}. The optimized code on the right of
  4830. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4831. \code{then} branch jumping directly to \code{block55}. The story is
  4832. similar for the \code{else} branch, as well as for the two branches in
  4833. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4834. have been optimized in this way, there are no longer any jumps to
  4835. blocks \code{block57} through \code{block60}, so they can be removed.
  4836. \begin{figure}[tbp]
  4837. \begin{tabular}{lll}
  4838. \begin{minipage}{0.4\textwidth}
  4839. \begin{lstlisting}
  4840. block62:
  4841. tmp54 = (read);
  4842. if (eq? tmp54 2) then
  4843. goto block59;
  4844. else
  4845. goto block60;
  4846. block61:
  4847. tmp53 = (read);
  4848. if (eq? tmp53 0) then
  4849. goto block57;
  4850. else
  4851. goto block58;
  4852. block60:
  4853. goto block56;
  4854. block59:
  4855. goto block55;
  4856. block58:
  4857. goto block56;
  4858. block57:
  4859. goto block55;
  4860. block56:
  4861. return (+ 700 77);
  4862. block55:
  4863. return (+ 10 32);
  4864. start:
  4865. tmp52 = (read);
  4866. if (eq? tmp52 1) then
  4867. goto block61;
  4868. else
  4869. goto block62;
  4870. \end{lstlisting}
  4871. \end{minipage}
  4872. &
  4873. $\Rightarrow$
  4874. &
  4875. \begin{minipage}{0.55\textwidth}
  4876. \begin{lstlisting}
  4877. block62:
  4878. tmp54 = (read);
  4879. if (eq? tmp54 2) then
  4880. goto block55;
  4881. else
  4882. goto block56;
  4883. block61:
  4884. tmp53 = (read);
  4885. if (eq? tmp53 0) then
  4886. goto block55;
  4887. else
  4888. goto block56;
  4889. block56:
  4890. return (+ 700 77);
  4891. block55:
  4892. return (+ 10 32);
  4893. start:
  4894. tmp52 = (read);
  4895. if (eq? tmp52 1) then
  4896. goto block61;
  4897. else
  4898. goto block62;
  4899. \end{lstlisting}
  4900. \end{minipage}
  4901. \end{tabular}
  4902. \caption{Optimize jumps by removing trivial blocks.}
  4903. \label{fig:optimize-jumps}
  4904. \end{figure}
  4905. The name of this pass is \code{optimize-jumps}. We recommend
  4906. implementing this pass in two phases. The first phrase builds a hash
  4907. table that maps labels to possibly improved labels. The second phase
  4908. changes the target of each \code{goto} to use the improved label. If
  4909. the label is for a trivial block, then the hash table should map the
  4910. label to the first non-trivial block that can be reached from this
  4911. label by jumping through trivial blocks. If the label is for a
  4912. non-trivial block, then the hash table should map the label to itself;
  4913. we do not want to change jumps to non-trivial blocks.
  4914. The first phase can be accomplished by constructing an empty hash
  4915. table, call it \code{short-cut}, and then iterating over the control
  4916. flow graph. Each time you encouter a block that is just a \code{goto},
  4917. then update the hash table, mapping the block's source to the target
  4918. of the \code{goto}. Also, the hash table may already have mapped some
  4919. labels to the block's source, to you must iterate through the hash
  4920. table and update all of those so that they instead map to the target
  4921. of the \code{goto}.
  4922. For the second phase, we recommend iterating through the $\Tail$ of
  4923. each block in the program, updating the target of every \code{goto}
  4924. according to the mapping in \code{short-cut}.
  4925. \begin{exercise}\normalfont
  4926. Implement the \code{optimize-jumps} pass as a transformation from
  4927. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4928. Check that \code{optimize-jumps} removes trivial blocks in a few
  4929. example programs. Then check that your compiler still passes all of
  4930. your tests.
  4931. \end{exercise}
  4932. There is another opportunity for optimizing jumps that is apparent in
  4933. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4934. end with a jump to \code{block7953} and there are no other jumps to
  4935. \code{block7953} in the rest of the program. In this situation we can
  4936. avoid the runtime overhead of this jump by merging \code{block7953}
  4937. into the preceeding block, in this case the \code{start} block.
  4938. Figure~\ref{fig:remove-jumps} shows the output of
  4939. \code{select-instructions} on the left and the result of this
  4940. optimization on the right.
  4941. \begin{figure}[tbp]
  4942. \begin{tabular}{lll}
  4943. \begin{minipage}{0.5\textwidth}
  4944. % s1_20.rkt
  4945. \begin{lstlisting}
  4946. start:
  4947. callq read_int
  4948. movq %rax, tmp7951
  4949. cmpq $1, tmp7951
  4950. je block7952
  4951. jmp block7953
  4952. block7953:
  4953. movq $0, %rax
  4954. jmp conclusion
  4955. block7952:
  4956. movq $42, %rax
  4957. jmp conclusion
  4958. \end{lstlisting}
  4959. \end{minipage}
  4960. &
  4961. $\Rightarrow\qquad$
  4962. \begin{minipage}{0.4\textwidth}
  4963. \begin{lstlisting}
  4964. start:
  4965. callq read_int
  4966. movq %rax, tmp7951
  4967. cmpq $1, tmp7951
  4968. je block7952
  4969. movq $0, %rax
  4970. jmp conclusion
  4971. block7952:
  4972. movq $42, %rax
  4973. jmp conclusion
  4974. \end{lstlisting}
  4975. \end{minipage}
  4976. \end{tabular}
  4977. \caption{Merging basic blocks by removing unnecessary jumps.}
  4978. \label{fig:remove-jumps}
  4979. \end{figure}
  4980. \begin{exercise}\normalfont
  4981. Implement a pass named \code{remove-jumps} that merges basic blocks
  4982. into their preceeding basic block, when there is only one preceeding
  4983. block. The pass should translate from psuedo $x86_1$ to pseudo
  4984. $x86_1$ and it should come immediately after
  4985. \code{select-instructions}. Check that \code{remove-jumps}
  4986. accomplishes the goal of merging basic blocks on several test
  4987. programs and check that your compiler passes all of your tests.
  4988. \end{exercise}
  4989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4990. \chapter{Tuples and Garbage Collection}
  4991. \label{ch:tuples}
  4992. \index{tuple}
  4993. \index{vector}
  4994. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4995. add simple structures. \\ --Jeremy}
  4996. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4997. things to discuss in this chapter. \\ --Jeremy}
  4998. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4999. all the IR grammars are spelled out! \\ --Jeremy}
  5000. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5001. but keep type annotations on vector creation and local variables, function
  5002. parameters, etc. \\ --Jeremy}
  5003. \margincomment{\scriptsize Be more explicit about how to deal with
  5004. the root stack. \\ --Jeremy}
  5005. In this chapter we study the implementation of mutable tuples (called
  5006. ``vectors'' in Racket). This language feature is the first to use the
  5007. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5008. indefinite, that is, a tuple lives forever from the programmer's
  5009. viewpoint. Of course, from an implementer's viewpoint, it is important
  5010. to reclaim the space associated with a tuple when it is no longer
  5011. needed, which is why we also study \emph{garbage collection}
  5012. \emph{garbage collection}
  5013. techniques in this chapter.
  5014. Section~\ref{sec:r3} introduces the $R_3$ language including its
  5015. interpreter and type checker. The $R_3$ language extends the $R_2$
  5016. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5017. \code{void} value. The reason for including the later is that the
  5018. \code{vector-set!} operation returns a value of type
  5019. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5020. called the \code{Unit} type in the programming languages
  5021. literature. Racket's \code{Void} type is inhabited by a single value
  5022. \code{void} which corresponds to \code{unit} or \code{()} in the
  5023. literature~\citep{Pierce:2002hj}.}.
  5024. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5025. copying live objects back and forth between two halves of the
  5026. heap. The garbage collector requires coordination with the compiler so
  5027. that it can see all of the \emph{root} pointers, that is, pointers in
  5028. registers or on the procedure call stack.
  5029. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5030. discuss all the necessary changes and additions to the compiler
  5031. passes, including a new compiler pass named \code{expose-allocation}.
  5032. \section{The $R_3$ Language}
  5033. \label{sec:r3}
  5034. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5035. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5036. $R_3$ language includes three new forms: \code{vector} for creating a
  5037. tuple, \code{vector-ref} for reading an element of a tuple, and
  5038. \code{vector-set!} for writing to an element of a tuple. The program
  5039. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5040. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5041. the 3-tuple, demonstrating that tuples are first-class values. The
  5042. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5043. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5044. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5045. 1-tuple. So the result of the program is \code{42}.
  5046. \begin{figure}[tbp]
  5047. \centering
  5048. \fbox{
  5049. \begin{minipage}{0.96\textwidth}
  5050. \[
  5051. \begin{array}{lcl}
  5052. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5053. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  5054. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5055. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5056. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5057. \mid (\key{and}\;\Exp\;\Exp)
  5058. \mid (\key{or}\;\Exp\;\Exp)
  5059. \mid (\key{not}\;\Exp) } \\
  5060. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5061. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5062. &\mid& (\key{vector}\;\Exp\ldots)
  5063. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  5064. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  5065. \mid (\key{vector-length}\;\Exp) \\
  5066. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  5067. R_3 &::=& \Exp
  5068. \end{array}
  5069. \]
  5070. \end{minipage}
  5071. }
  5072. \caption{The concrete syntax of $R_3$, extending $R_2$
  5073. (Figure~\ref{fig:r2-concrete-syntax}).}
  5074. \label{fig:r3-concrete-syntax}
  5075. \end{figure}
  5076. \begin{figure}[tbp]
  5077. \begin{lstlisting}
  5078. (let ([t (vector 40 #t (vector 2))])
  5079. (if (vector-ref t 1)
  5080. (+ (vector-ref t 0)
  5081. (vector-ref (vector-ref t 2) 0))
  5082. 44))
  5083. \end{lstlisting}
  5084. \caption{Example program that creates tuples and reads from them.}
  5085. \label{fig:vector-eg}
  5086. \end{figure}
  5087. \begin{figure}[tp]
  5088. \centering
  5089. \fbox{
  5090. \begin{minipage}{0.96\textwidth}
  5091. \[
  5092. \begin{array}{lcl}
  5093. \itm{op} &::=& \ldots
  5094. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5095. \mid \code{vector-length} \\
  5096. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5097. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5098. \mid \BOOL{\itm{bool}}
  5099. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5100. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5101. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5102. \end{array}
  5103. \]
  5104. \end{minipage}
  5105. }
  5106. \caption{The abstract syntax of $R_3$.}
  5107. \label{fig:r3-syntax}
  5108. \end{figure}
  5109. \index{allocate}
  5110. \index{heap allocate}
  5111. Tuples are our first encounter with heap-allocated data, which raises
  5112. several interesting issues. First, variable binding performs a
  5113. shallow-copy when dealing with tuples, which means that different
  5114. variables can refer to the same tuple, that is, different variables
  5115. can be \emph{aliases} for the same entity. Consider the following
  5116. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5117. Thus, the mutation through \code{t2} is visible when referencing the
  5118. tuple from \code{t1}, so the result of this program is \code{42}.
  5119. \index{alias}\index{mutation}
  5120. \begin{center}
  5121. \begin{minipage}{0.96\textwidth}
  5122. \begin{lstlisting}
  5123. (let ([t1 (vector 3 7)])
  5124. (let ([t2 t1])
  5125. (let ([_ (vector-set! t2 0 42)])
  5126. (vector-ref t1 0))))
  5127. \end{lstlisting}
  5128. \end{minipage}
  5129. \end{center}
  5130. The next issue concerns the lifetime of tuples. Of course, they are
  5131. created by the \code{vector} form, but when does their lifetime end?
  5132. Notice that $R_3$ does not include an operation for deleting
  5133. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5134. of static scoping. For example, the following program returns
  5135. \code{42} even though the variable \code{w} goes out of scope prior to
  5136. the \code{vector-ref} that reads from the vector it was bound to.
  5137. \begin{center}
  5138. \begin{minipage}{0.96\textwidth}
  5139. \begin{lstlisting}
  5140. (let ([v (vector (vector 44))])
  5141. (let ([x (let ([w (vector 42)])
  5142. (let ([_ (vector-set! v 0 w)])
  5143. 0))])
  5144. (+ x (vector-ref (vector-ref v 0) 0))))
  5145. \end{lstlisting}
  5146. \end{minipage}
  5147. \end{center}
  5148. From the perspective of programmer-observable behavior, tuples live
  5149. forever. Of course, if they really lived forever, then many programs
  5150. would run out of memory.\footnote{The $R_3$ language does not have
  5151. looping or recursive functions, so it is nigh impossible to write a
  5152. program in $R_3$ that will run out of memory. However, we add
  5153. recursive functions in the next Chapter!} A Racket implementation
  5154. must therefore perform automatic garbage collection.
  5155. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5156. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5157. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5158. operations in Racket. One subtle point is that the \code{vector-set!}
  5159. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5160. can be passed around just like other values inside an $R_3$ program
  5161. and a \code{\#<void>} value can be compared for equality with another
  5162. \code{\#<void>} value. However, there are no other operations specific
  5163. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5164. the \code{void?} predicate that returns \code{\#t} when applied to
  5165. \code{\#<void>} and \code{\#f} otherwise.
  5166. \begin{figure}[tbp]
  5167. \begin{lstlisting}
  5168. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5169. (define (interp-op op)
  5170. (match op
  5171. ...
  5172. ['vector vector]
  5173. ['vector-ref vector-ref]
  5174. ['vector-set! vector-set!]
  5175. [else (error 'interp-op "unknown operator")]))
  5176. (define (interp-exp env)
  5177. (lambda (e)
  5178. (define recur (interp-exp env))
  5179. (match e
  5180. ...
  5181. )))
  5182. (define (interp-R3 p)
  5183. (match p
  5184. [(Program '() e)
  5185. ((interp-exp '()) e)]
  5186. ))
  5187. \end{lstlisting}
  5188. \caption{Interpreter for the $R_3$ language.}
  5189. \label{fig:interp-R3}
  5190. \end{figure}
  5191. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5192. deserves some explanation. When allocating a vector, we need to know
  5193. which elements of the vector are pointers (i.e. are also vectors). We
  5194. can obtain this information during type checking. The type checker in
  5195. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5196. expression, it also wraps every \key{vector} creation with the form
  5197. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5198. %
  5199. To create the s-expression for the \code{Vector} type in
  5200. Figure~\ref{fig:type-check-R3}, we use the
  5201. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5202. operator} \code{,@} to insert the list \code{t*} without its usual
  5203. start and end parentheses. \index{unquote-slicing}
  5204. \begin{figure}[tp]
  5205. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5206. (define (type-check-exp env)
  5207. (lambda (e)
  5208. (define recur (type-check-exp env))
  5209. (match e
  5210. ...
  5211. [(Void) (values (Void) 'Void)]
  5212. [(Prim 'vector es)
  5213. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5214. (let ([t `(Vector ,@t*)])
  5215. (values (HasType (Prim 'vector e*) t) t))]
  5216. [(Prim 'vector-ref (list e (Int i)))
  5217. (define-values (e^ t) (recur e))
  5218. (match t
  5219. [`(Vector ,ts ...)
  5220. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5221. (error 'type-check-exp "invalid index ~a" i))
  5222. (let ([t (list-ref ts i)])
  5223. (values (Prim 'vector-ref (list e^ (Int i))) t))]
  5224. [else (error 'type-check-exp
  5225. "expected a vector in vector-ref, not ~a" t)])]
  5226. [(Prim 'vector-set! (list e (Int i) arg) )
  5227. (define-values (e-vec t-vec) (recur e))
  5228. (define-values (e-arg^ t-arg) (recur arg))
  5229. (match t-vec
  5230. [`(Vector ,ts ...)
  5231. (unless (and (exact-nonnegative-integer? i) (i . < . (length ts)))
  5232. (error 'type-check-exp "invalid index ~a" i))
  5233. (unless (type-equal? (list-ref ts i) t-arg)
  5234. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  5235. (list-ref ts i) t-arg))
  5236. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5237. [else (error 'type-check-exp
  5238. "expected a vector in vector-set!, not ~a" t-vec)])]
  5239. [(Prim 'vector-length (list e))
  5240. (define-values (e^ t) (recur e))
  5241. (match t
  5242. [`(Vector ,ts ...)
  5243. (values (Prim 'vector-length (list e^)) 'Integer)]
  5244. [else (error 'type-check-exp
  5245. "expected a vector in vector-lenfth, not ~a" t)])]
  5246. [(Prim 'eq? (list arg1 arg2))
  5247. (define-values (e1 t1) (recur arg1))
  5248. (define-values (e2 t2) (recur arg2))
  5249. (match* (t1 t2)
  5250. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5251. [(other wise)
  5252. (unless (type-equal? t1 t2)
  5253. (error 'type-check-exp
  5254. "type error: different argument types of eq?: ~a != ~a" t1 t2))])
  5255. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5256. [(HasType (Prim 'vector es) t)
  5257. ((type-check-exp env) (Prim 'vector es))]
  5258. [(HasType e t)
  5259. (define-values (e^ t^) (recur e))
  5260. (unless (type-equal? t t^)
  5261. (error 'type-check-exp "type mismatch in HasType" t t^))
  5262. (values (HasType e^ t) t)]
  5263. ...
  5264. [else (error 'type-check-exp "R3/unmatched ~a" e)]
  5265. )))
  5266. \end{lstlisting}
  5267. \caption{Type checker for the $R_3$ language.}
  5268. \label{fig:type-check-R3}
  5269. \end{figure}
  5270. \section{Garbage Collection}
  5271. \label{sec:GC}
  5272. Here we study a relatively simple algorithm for garbage collection
  5273. that is the basis of state-of-the-art garbage
  5274. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5275. particular, we describe a two-space copying
  5276. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5277. perform the
  5278. copy~\citep{Cheney:1970aa}.
  5279. \index{copying collector}
  5280. \index{two-space copying collector}
  5281. Figure~\ref{fig:copying-collector} gives a
  5282. coarse-grained depiction of what happens in a two-space collector,
  5283. showing two time steps, prior to garbage collection (on the top) and
  5284. after garbage collection (on the bottom). In a two-space collector,
  5285. the heap is divided into two parts named the FromSpace and the
  5286. ToSpace. Initially, all allocations go to the FromSpace until there is
  5287. not enough room for the next allocation request. At that point, the
  5288. garbage collector goes to work to make more room.
  5289. \index{ToSpace}
  5290. \index{FromSpace}
  5291. The garbage collector must be careful not to reclaim tuples that will
  5292. be used by the program in the future. Of course, it is impossible in
  5293. general to predict what a program will do, but we can over approximate
  5294. the will-be-used tuples by preserving all tuples that could be
  5295. accessed by \emph{any} program given the current computer state. A
  5296. program could access any tuple whose address is in a register or on
  5297. the procedure call stack. These addresses are called the \emph{root
  5298. set}\index{root set}. In addition, a program could access any tuple that is
  5299. transitively reachable from the root set. Thus, it is safe for the
  5300. garbage collector to reclaim the tuples that are not reachable in this
  5301. way.
  5302. So the goal of the garbage collector is twofold:
  5303. \begin{enumerate}
  5304. \item preserve all tuple that are reachable from the root set via a
  5305. path of pointers, that is, the \emph{live} tuples, and
  5306. \item reclaim the memory of everything else, that is, the
  5307. \emph{garbage}.
  5308. \end{enumerate}
  5309. A copying collector accomplishes this by copying all of the live
  5310. objects from the FromSpace into the ToSpace and then performs a slight
  5311. of hand, treating the ToSpace as the new FromSpace and the old
  5312. FromSpace as the new ToSpace. In the example of
  5313. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5314. root set, one in a register and two on the stack. All of the live
  5315. objects have been copied to the ToSpace (the right-hand side of
  5316. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5317. pointer relationships. For example, the pointer in the register still
  5318. points to a 2-tuple whose first element is a 3-tuple and whose second
  5319. element is a 2-tuple. There are four tuples that are not reachable
  5320. from the root set and therefore do not get copied into the ToSpace.
  5321. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5322. created by a well-typed program in $R_3$ because it contains a
  5323. cycle. However, creating cycles will be possible once we get to $R_6$.
  5324. We design the garbage collector to deal with cycles to begin with so
  5325. we will not need to revisit this issue.
  5326. \begin{figure}[tbp]
  5327. \centering
  5328. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5329. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5330. \caption{A copying collector in action.}
  5331. \label{fig:copying-collector}
  5332. \end{figure}
  5333. There are many alternatives to copying collectors (and their bigger
  5334. siblings, the generational collectors) when its comes to garbage
  5335. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5336. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5337. collectors are that allocation is fast (just a comparison and pointer
  5338. increment), there is no fragmentation, cyclic garbage is collected,
  5339. and the time complexity of collection only depends on the amount of
  5340. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5341. main disadvantages of a two-space copying collector is that it uses a
  5342. lot of space and takes a long time to perform the copy, though these
  5343. problems are ameliorated in generational collectors. Racket and
  5344. Scheme programs tend to allocate many small objects and generate a lot
  5345. of garbage, so copying and generational collectors are a good fit.
  5346. Garbage collection is an active research topic, especially concurrent
  5347. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5348. developing new techniques and revisiting old
  5349. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5350. meet every year at the International Symposium on Memory Management to
  5351. present these findings.
  5352. \subsection{Graph Copying via Cheney's Algorithm}
  5353. \label{sec:cheney}
  5354. \index{Cheney's algorithm}
  5355. Let us take a closer look at the copying of the live objects. The
  5356. allocated objects and pointers can be viewed as a graph and we need to
  5357. copy the part of the graph that is reachable from the root set. To
  5358. make sure we copy all of the reachable vertices in the graph, we need
  5359. an exhaustive graph traversal algorithm, such as depth-first search or
  5360. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5361. such algorithms take into account the possibility of cycles by marking
  5362. which vertices have already been visited, so as to ensure termination
  5363. of the algorithm. These search algorithms also use a data structure
  5364. such as a stack or queue as a to-do list to keep track of the vertices
  5365. that need to be visited. We use breadth-first search and a trick
  5366. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5367. and copying tuples into the ToSpace.
  5368. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5369. copy progresses. The queue is represented by a chunk of contiguous
  5370. memory at the beginning of the ToSpace, using two pointers to track
  5371. the front and the back of the queue. The algorithm starts by copying
  5372. all tuples that are immediately reachable from the root set into the
  5373. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5374. old tuple to indicate that it has been visited. We discuss how this
  5375. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5376. pointers inside the copied tuples in the queue still point back to the
  5377. FromSpace. Once the initial queue has been created, the algorithm
  5378. enters a loop in which it repeatedly processes the tuple at the front
  5379. of the queue and pops it off the queue. To process a tuple, the
  5380. algorithm copies all the tuple that are directly reachable from it to
  5381. the ToSpace, placing them at the back of the queue. The algorithm then
  5382. updates the pointers in the popped tuple so they point to the newly
  5383. copied tuples.
  5384. \begin{figure}[tbp]
  5385. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5386. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5387. \label{fig:cheney}
  5388. \end{figure}
  5389. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5390. tuple whose second element is $42$ to the back of the queue. The other
  5391. pointer goes to a tuple that has already been copied, so we do not
  5392. need to copy it again, but we do need to update the pointer to the new
  5393. location. This can be accomplished by storing a \emph{forwarding
  5394. pointer} to the new location in the old tuple, back when we initially
  5395. copied the tuple into the ToSpace. This completes one step of the
  5396. algorithm. The algorithm continues in this way until the front of the
  5397. queue is empty, that is, until the front catches up with the back.
  5398. \subsection{Data Representation}
  5399. \label{sec:data-rep-gc}
  5400. The garbage collector places some requirements on the data
  5401. representations used by our compiler. First, the garbage collector
  5402. needs to distinguish between pointers and other kinds of data. There
  5403. are several ways to accomplish this.
  5404. \begin{enumerate}
  5405. \item Attached a tag to each object that identifies what type of
  5406. object it is~\citep{McCarthy:1960dz}.
  5407. \item Store different types of objects in different
  5408. regions~\citep{Steele:1977ab}.
  5409. \item Use type information from the program to either generate
  5410. type-specific code for collecting or to generate tables that can
  5411. guide the
  5412. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5413. \end{enumerate}
  5414. Dynamically typed languages, such as Lisp, need to tag objects
  5415. anyways, so option 1 is a natural choice for those languages.
  5416. However, $R_3$ is a statically typed language, so it would be
  5417. unfortunate to require tags on every object, especially small and
  5418. pervasive objects like integers and Booleans. Option 3 is the
  5419. best-performing choice for statically typed languages, but comes with
  5420. a relatively high implementation complexity. To keep this chapter
  5421. within a 2-week time budget, we recommend a combination of options 1
  5422. and 2, using separate strategies for the stack and the heap.
  5423. Regarding the stack, we recommend using a separate stack for pointers,
  5424. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5425. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5426. is, when a local variable needs to be spilled and is of type
  5427. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5428. stack instead of the normal procedure call stack. Furthermore, we
  5429. always spill vector-typed variables if they are live during a call to
  5430. the collector, thereby ensuring that no pointers are in registers
  5431. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5432. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5433. the data layout using a root stack. The root stack contains the two
  5434. pointers from the regular stack and also the pointer in the second
  5435. register.
  5436. \begin{figure}[tbp]
  5437. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5438. \caption{Maintaining a root stack to facilitate garbage collection.}
  5439. \label{fig:shadow-stack}
  5440. \end{figure}
  5441. The problem of distinguishing between pointers and other kinds of data
  5442. also arises inside of each tuple on the heap. We solve this problem by
  5443. attaching a tag, an extra 64-bits, to each
  5444. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5445. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5446. that we have drawn the bits in a big-endian way, from right-to-left,
  5447. with bit location 0 (the least significant bit) on the far right,
  5448. which corresponds to the direction of the x86 shifting instructions
  5449. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5450. is dedicated to specifying which elements of the tuple are pointers,
  5451. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5452. indicates there is a pointer and a 0 bit indicates some other kind of
  5453. data. The pointer mask starts at bit location 7. We have limited
  5454. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5455. the pointer mask. The tag also contains two other pieces of
  5456. information. The length of the tuple (number of elements) is stored in
  5457. bits location 1 through 6. Finally, the bit at location 0 indicates
  5458. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5459. value 1, then this tuple has not yet been copied. If the bit has
  5460. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5461. of a pointer are always zero anyways because our tuples are 8-byte
  5462. aligned.)
  5463. \begin{figure}[tbp]
  5464. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5465. \caption{Representation of tuples in the heap.}
  5466. \label{fig:tuple-rep}
  5467. \end{figure}
  5468. \subsection{Implementation of the Garbage Collector}
  5469. \label{sec:organize-gz}
  5470. \index{prelude}
  5471. An implementation of the copying collector is provided in the
  5472. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5473. interface to the garbage collector that is used by the compiler. The
  5474. \code{initialize} function creates the FromSpace, ToSpace, and root
  5475. stack and should be called in the prelude of the \code{main}
  5476. function. The arguments of \code{initialize} are the root stack size
  5477. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5478. good choice for both. The \code{initialize} function puts the address
  5479. of the beginning of the FromSpace into the global variable
  5480. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5481. the address that is 1-past the last element of the FromSpace. (We use
  5482. half-open intervals to represent chunks of
  5483. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5484. points to the first element of the root stack.
  5485. As long as there is room left in the FromSpace, your generated code
  5486. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5487. %
  5488. The amount of room left in FromSpace is the difference between the
  5489. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5490. function should be called when there is not enough room left in the
  5491. FromSpace for the next allocation. The \code{collect} function takes
  5492. a pointer to the current top of the root stack (one past the last item
  5493. that was pushed) and the number of bytes that need to be
  5494. allocated. The \code{collect} function performs the copying collection
  5495. and leaves the heap in a state such that the next allocation will
  5496. succeed.
  5497. \begin{figure}[tbp]
  5498. \begin{lstlisting}
  5499. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5500. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5501. int64_t* free_ptr;
  5502. int64_t* fromspace_begin;
  5503. int64_t* fromspace_end;
  5504. int64_t** rootstack_begin;
  5505. \end{lstlisting}
  5506. \caption{The compiler's interface to the garbage collector.}
  5507. \label{fig:gc-header}
  5508. \end{figure}
  5509. %% \begin{exercise}
  5510. %% In the file \code{runtime.c} you will find the implementation of
  5511. %% \code{initialize} and a partial implementation of \code{collect}.
  5512. %% The \code{collect} function calls another function, \code{cheney},
  5513. %% to perform the actual copy, and that function is left to the reader
  5514. %% to implement. The following is the prototype for \code{cheney}.
  5515. %% \begin{lstlisting}
  5516. %% static void cheney(int64_t** rootstack_ptr);
  5517. %% \end{lstlisting}
  5518. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5519. %% rootstack (which is an array of pointers). The \code{cheney} function
  5520. %% also communicates with \code{collect} through the global
  5521. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5522. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5523. %% the ToSpace:
  5524. %% \begin{lstlisting}
  5525. %% static int64_t* tospace_begin;
  5526. %% static int64_t* tospace_end;
  5527. %% \end{lstlisting}
  5528. %% The job of the \code{cheney} function is to copy all the live
  5529. %% objects (reachable from the root stack) into the ToSpace, update
  5530. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5531. %% update the root stack so that it points to the objects in the
  5532. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5533. %% and ToSpace.
  5534. %% \end{exercise}
  5535. %% \section{Compiler Passes}
  5536. %% \label{sec:code-generation-gc}
  5537. The introduction of garbage collection has a non-trivial impact on our
  5538. compiler passes. We introduce a new compiler pass named
  5539. \code{expose-allocation}. We make
  5540. significant changes to \code{select-instructions},
  5541. \code{build-interference}, \code{allocate-registers}, and
  5542. \code{print-x86} and make minor changes in severl more passes. The
  5543. following program will serve as our running example. It creates two
  5544. tuples, one nested inside the other. Both tuples have length one. The
  5545. program accesses the element in the inner tuple tuple via two vector
  5546. references.
  5547. % tests/s2_17.rkt
  5548. \begin{lstlisting}
  5549. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5550. \end{lstlisting}
  5551. \section{Shrink}
  5552. \label{sec:shrink-R3}
  5553. Recall that the \code{shrink} pass translates the primitives operators
  5554. into a smaller set of primitives. Because this pass comes after type
  5555. checking, but before the passes that require the type information in
  5556. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5557. to wrap \code{HasType} around each AST node that it generates.
  5558. \section{Expose Allocation}
  5559. \label{sec:expose-allocation}
  5560. The pass \code{expose-allocation} lowers the \code{vector} creation
  5561. form into a conditional call to the collector followed by the
  5562. allocation. We choose to place the \code{expose-allocation} pass
  5563. before \code{remove-complex-opera*} because the code generated by
  5564. \code{expose-allocation} contains complex operands. We also place
  5565. \code{expose-allocation} before \code{explicate-control} because
  5566. \code{expose-allocation} introduces new variables using \code{let},
  5567. but \code{let} is gone after \code{explicate-control}.
  5568. The output of \code{expose-allocation} is a language $R'_3$ that
  5569. extends $R_3$ with the three new forms that we use in the translation
  5570. of the \code{vector} form.
  5571. \[
  5572. \begin{array}{lcl}
  5573. \Exp &::=& \cdots
  5574. \mid (\key{collect} \,\itm{int})
  5575. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5576. \mid (\key{global-value} \,\itm{name})
  5577. \end{array}
  5578. \]
  5579. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5580. $n$ bytes. It will become a call to the \code{collect} function in
  5581. \code{runtime.c} in \code{select-instructions}. The
  5582. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5583. \index{allocate}
  5584. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5585. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5586. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5587. a global variable, such as \code{free\_ptr}.
  5588. In the following, we show the transformation for the \code{vector}
  5589. form into 1) a sequence of let-bindings for the initializing
  5590. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5591. \code{allocate}, and 4) the initialization of the vector. In the
  5592. following, \itm{len} refers to the length of the vector and
  5593. \itm{bytes} is how many total bytes need to be allocated for the
  5594. vector, which is 8 for the tag plus \itm{len} times 8.
  5595. \begin{lstlisting}
  5596. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5597. |$\Longrightarrow$|
  5598. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5599. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5600. (global-value fromspace_end))
  5601. (void)
  5602. (collect |\itm{bytes}|))])
  5603. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5604. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5605. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5606. |$v$|) ... )))) ...)
  5607. \end{lstlisting}
  5608. In the above, we suppressed all of the \code{has-type} forms in the
  5609. output for the sake of readability. The placement of the initializing
  5610. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5611. sequence of \code{vector-set!} is important, as those expressions may
  5612. trigger garbage collection and we cannot have an allocated but
  5613. uninitialized tuple on the heap during a collection.
  5614. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5615. \code{expose-allocation} pass on our running example.
  5616. \begin{figure}[tbp]
  5617. % tests/s2_17.rkt
  5618. \begin{lstlisting}
  5619. (vector-ref
  5620. (vector-ref
  5621. (let ([vecinit7976
  5622. (let ([vecinit7972 42])
  5623. (let ([collectret7974
  5624. (if (< (+ (global-value free_ptr) 16)
  5625. (global-value fromspace_end))
  5626. (void)
  5627. (collect 16)
  5628. )])
  5629. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5630. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5631. alloc7971)
  5632. )
  5633. )
  5634. )
  5635. ])
  5636. (let ([collectret7978
  5637. (if (< (+ (global-value free_ptr) 16)
  5638. (global-value fromspace_end))
  5639. (void)
  5640. (collect 16)
  5641. )])
  5642. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5643. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5644. alloc7975)
  5645. )
  5646. )
  5647. )
  5648. 0)
  5649. 0)
  5650. \end{lstlisting}
  5651. \caption{Output of the \code{expose-allocation} pass, minus
  5652. all of the \code{has-type} forms.}
  5653. \label{fig:expose-alloc-output}
  5654. \end{figure}
  5655. \section{Remove Complex Operands}
  5656. \label{sec:remove-complex-opera-R3}
  5657. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5658. should all be treated as complex operands. A new case for
  5659. \code{HasType} is needed and the case for \code{Prim} needs to be
  5660. handled carefully to prevent the \code{Prim} node from being separated
  5661. from its enclosing \code{HasType}.
  5662. \section{Explicate Control and the $C_2$ language}
  5663. \label{sec:explicate-control-r3}
  5664. \begin{figure}[tbp]
  5665. \fbox{
  5666. \begin{minipage}{0.96\textwidth}
  5667. \small
  5668. \[
  5669. \begin{array}{lcl}
  5670. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5671. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5672. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5673. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5674. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5675. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5676. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5677. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5678. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5679. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5680. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5681. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5682. \end{array}
  5683. \]
  5684. \end{minipage}
  5685. }
  5686. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5687. \label{fig:c2-concrete-syntax}
  5688. \end{figure}
  5689. \begin{figure}[tp]
  5690. \fbox{
  5691. \begin{minipage}{0.96\textwidth}
  5692. \small
  5693. \[
  5694. \begin{array}{lcl}
  5695. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5696. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5697. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5698. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5699. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5700. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5701. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5702. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5703. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5704. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5705. \mid (\key{Collect} \,\itm{int}) \\
  5706. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5707. \mid \GOTO{\itm{label}} } \\
  5708. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5709. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5710. \end{array}
  5711. \]
  5712. \end{minipage}
  5713. }
  5714. \caption{The abstract syntax of $C_2$, extending $C_1$
  5715. (Figure~\ref{fig:c1-syntax}).}
  5716. \label{fig:c2-syntax}
  5717. \end{figure}
  5718. The output of \code{explicate-control} is a program in the
  5719. intermediate language $C_2$, whose concrete syntax is defined in
  5720. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5721. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5722. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5723. \key{global-value} expressions and the \code{collect} statement. The
  5724. \code{explicate-control} pass can treat these new forms much like the
  5725. other forms.
  5726. \section{Select Instructions and the x86$_2$ Language}
  5727. \label{sec:select-instructions-gc}
  5728. \index{instruction selection}
  5729. %% void (rep as zero)
  5730. %% allocate
  5731. %% collect (callq collect)
  5732. %% vector-ref
  5733. %% vector-set!
  5734. %% global (postpone)
  5735. In this pass we generate x86 code for most of the new operations that
  5736. were needed to compile tuples, including \code{Allocate},
  5737. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5738. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5739. the later has a different concrete syntax (see
  5740. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5741. \index{x86}
  5742. The \code{vector-ref} and \code{vector-set!} forms translate into
  5743. \code{movq} instructions. (The plus one in the offset is to get past
  5744. the tag at the beginning of the tuple representation.)
  5745. \begin{lstlisting}
  5746. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5747. |$\Longrightarrow$|
  5748. movq |$\itm{vec}'$|, %r11
  5749. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5750. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5751. |$\Longrightarrow$|
  5752. movq |$\itm{vec}'$|, %r11
  5753. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5754. movq $0, |$\itm{lhs'}$|
  5755. \end{lstlisting}
  5756. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5757. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5758. register \code{r11} ensures that offset expression
  5759. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5760. removing \code{r11} from consideration by the register allocating.
  5761. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5762. \code{rax}. Then the generated code for \code{vector-set!} would be
  5763. \begin{lstlisting}
  5764. movq |$\itm{vec}'$|, %rax
  5765. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5766. movq $0, |$\itm{lhs}'$|
  5767. \end{lstlisting}
  5768. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5769. \code{patch-instructions} would insert a move through \code{rax}
  5770. as follows.
  5771. \begin{lstlisting}
  5772. movq |$\itm{vec}'$|, %rax
  5773. movq |$\itm{arg}'$|, %rax
  5774. movq %rax, |$8(n+1)$|(%rax)
  5775. movq $0, |$\itm{lhs}'$|
  5776. \end{lstlisting}
  5777. But the above sequence of instructions does not work because we're
  5778. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5779. $\itm{arg}'$) at the same time!
  5780. We compile the \code{allocate} form to operations on the
  5781. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5782. is the next free address in the FromSpace, so we copy it into
  5783. \code{r11} and then move it forward by enough space for the tuple
  5784. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5785. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5786. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5787. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5788. tag is organized. We recommend using the Racket operations
  5789. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5790. during compilation. The type annotation in the \code{vector} form is
  5791. used to determine the pointer mask region of the tag.
  5792. \begin{lstlisting}
  5793. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5794. |$\Longrightarrow$|
  5795. movq free_ptr(%rip), %r11
  5796. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5797. movq $|$\itm{tag}$|, 0(%r11)
  5798. movq %r11, |$\itm{lhs}'$|
  5799. \end{lstlisting}
  5800. The \code{collect} form is compiled to a call to the \code{collect}
  5801. function in the runtime. The arguments to \code{collect} are 1) the
  5802. top of the root stack and 2) the number of bytes that need to be
  5803. allocated. We use another dedicated register, \code{r15}, to
  5804. store the pointer to the top of the root stack. So \code{r15} is not
  5805. available for use by the register allocator.
  5806. \begin{lstlisting}
  5807. (collect |$\itm{bytes}$|)
  5808. |$\Longrightarrow$|
  5809. movq %r15, %rdi
  5810. movq $|\itm{bytes}|, %rsi
  5811. callq collect
  5812. \end{lstlisting}
  5813. \begin{figure}[tp]
  5814. \fbox{
  5815. \begin{minipage}{0.96\textwidth}
  5816. \[
  5817. \begin{array}{lcl}
  5818. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5819. x86_1 &::= & \gray{ \key{.globl main} }\\
  5820. & & \gray{ \key{main:} \; \Instr\ldots }
  5821. \end{array}
  5822. \]
  5823. \end{minipage}
  5824. }
  5825. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5826. \label{fig:x86-2-concrete}
  5827. \end{figure}
  5828. \begin{figure}[tp]
  5829. \fbox{
  5830. \begin{minipage}{0.96\textwidth}
  5831. \small
  5832. \[
  5833. \begin{array}{lcl}
  5834. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5835. \mid \BYTEREG{\Reg}} \\
  5836. &\mid& (\key{Global}~\Var) \\
  5837. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5838. \end{array}
  5839. \]
  5840. \end{minipage}
  5841. }
  5842. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5843. \label{fig:x86-2}
  5844. \end{figure}
  5845. The concrete and abstract syntax of the $x86_2$ language is defined in
  5846. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5847. x86$_1$ just in the addition of the form for global variables.
  5848. %
  5849. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5850. \code{select-instructions} pass on the running example.
  5851. \begin{figure}[tbp]
  5852. \centering
  5853. % tests/s2_17.rkt
  5854. \begin{minipage}[t]{0.5\textwidth}
  5855. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5856. block35:
  5857. movq free_ptr(%rip), alloc9024
  5858. addq $16, free_ptr(%rip)
  5859. movq alloc9024, %r11
  5860. movq $131, 0(%r11)
  5861. movq alloc9024, %r11
  5862. movq vecinit9025, 8(%r11)
  5863. movq $0, initret9026
  5864. movq alloc9024, %r11
  5865. movq 8(%r11), tmp9034
  5866. movq tmp9034, %r11
  5867. movq 8(%r11), %rax
  5868. jmp conclusion
  5869. block36:
  5870. movq $0, collectret9027
  5871. jmp block35
  5872. block38:
  5873. movq free_ptr(%rip), alloc9020
  5874. addq $16, free_ptr(%rip)
  5875. movq alloc9020, %r11
  5876. movq $3, 0(%r11)
  5877. movq alloc9020, %r11
  5878. movq vecinit9021, 8(%r11)
  5879. movq $0, initret9022
  5880. movq alloc9020, vecinit9025
  5881. movq free_ptr(%rip), tmp9031
  5882. movq tmp9031, tmp9032
  5883. addq $16, tmp9032
  5884. movq fromspace_end(%rip), tmp9033
  5885. cmpq tmp9033, tmp9032
  5886. jl block36
  5887. jmp block37
  5888. block37:
  5889. movq %r15, %rdi
  5890. movq $16, %rsi
  5891. callq 'collect
  5892. jmp block35
  5893. block39:
  5894. movq $0, collectret9023
  5895. jmp block38
  5896. \end{lstlisting}
  5897. \end{minipage}
  5898. \begin{minipage}[t]{0.45\textwidth}
  5899. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5900. start:
  5901. movq $42, vecinit9021
  5902. movq free_ptr(%rip), tmp9028
  5903. movq tmp9028, tmp9029
  5904. addq $16, tmp9029
  5905. movq fromspace_end(%rip), tmp9030
  5906. cmpq tmp9030, tmp9029
  5907. jl block39
  5908. jmp block40
  5909. block40:
  5910. movq %r15, %rdi
  5911. movq $16, %rsi
  5912. callq 'collect
  5913. jmp block38
  5914. \end{lstlisting}
  5915. \end{minipage}
  5916. \caption{Output of the \code{select-instructions} pass.}
  5917. \label{fig:select-instr-output-gc}
  5918. \end{figure}
  5919. \clearpage
  5920. \section{Register Allocation}
  5921. \label{sec:reg-alloc-gc}
  5922. \index{register allocation}
  5923. As discussed earlier in this chapter, the garbage collector needs to
  5924. access all the pointers in the root set, that is, all variables that
  5925. are vectors. It will be the responsibility of the register allocator
  5926. to make sure that:
  5927. \begin{enumerate}
  5928. \item the root stack is used for spilling vector-typed variables, and
  5929. \item if a vector-typed variable is live during a call to the
  5930. collector, it must be spilled to ensure it is visible to the
  5931. collector.
  5932. \end{enumerate}
  5933. The later responsibility can be handled during construction of the
  5934. interference graph, by adding interference edges between the call-live
  5935. vector-typed variables and all the callee-saved registers. (They
  5936. already interfere with the caller-saved registers.) The type
  5937. information for variables is in the \code{Program} form, so we
  5938. recommend adding another parameter to the \code{build-interference}
  5939. function to communicate this alist.
  5940. The spilling of vector-typed variables to the root stack can be
  5941. handled after graph coloring, when choosing how to assign the colors
  5942. (integers) to registers and stack locations. The \code{Program} output
  5943. of this pass changes to also record the number of spills to the root
  5944. stack.
  5945. % build-interference
  5946. %
  5947. % callq
  5948. % extra parameter for var->type assoc. list
  5949. % update 'program' and 'if'
  5950. % allocate-registers
  5951. % allocate spilled vectors to the rootstack
  5952. % don't change color-graph
  5953. \section{Print x86}
  5954. \label{sec:print-x86-gc}
  5955. \index{prelude}\index{conclusion}
  5956. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5957. \code{print-x86} pass on the running example. In the prelude and
  5958. conclusion of the \code{main} function, we treat the root stack very
  5959. much like the regular stack in that we move the root stack pointer
  5960. (\code{r15}) to make room for the spills to the root stack, except
  5961. that the root stack grows up instead of down. For the running
  5962. example, there was just one spill so we increment \code{r15} by 8
  5963. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5964. One issue that deserves special care is that there may be a call to
  5965. \code{collect} prior to the initializing assignments for all the
  5966. variables in the root stack. We do not want the garbage collector to
  5967. accidentally think that some uninitialized variable is a pointer that
  5968. needs to be followed. Thus, we zero-out all locations on the root
  5969. stack in the prelude of \code{main}. In
  5970. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5971. %
  5972. \lstinline{movq $0, (%r15)}
  5973. %
  5974. accomplishes this task. The garbage collector tests each root to see
  5975. if it is null prior to dereferencing it.
  5976. \begin{figure}[htbp]
  5977. \begin{minipage}[t]{0.5\textwidth}
  5978. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5979. block35:
  5980. movq free_ptr(%rip), %rcx
  5981. addq $16, free_ptr(%rip)
  5982. movq %rcx, %r11
  5983. movq $131, 0(%r11)
  5984. movq %rcx, %r11
  5985. movq -8(%r15), %rax
  5986. movq %rax, 8(%r11)
  5987. movq $0, %rdx
  5988. movq %rcx, %r11
  5989. movq 8(%r11), %rcx
  5990. movq %rcx, %r11
  5991. movq 8(%r11), %rax
  5992. jmp conclusion
  5993. block36:
  5994. movq $0, %rcx
  5995. jmp block35
  5996. block38:
  5997. movq free_ptr(%rip), %rcx
  5998. addq $16, free_ptr(%rip)
  5999. movq %rcx, %r11
  6000. movq $3, 0(%r11)
  6001. movq %rcx, %r11
  6002. movq %rbx, 8(%r11)
  6003. movq $0, %rdx
  6004. movq %rcx, -8(%r15)
  6005. movq free_ptr(%rip), %rcx
  6006. addq $16, %rcx
  6007. movq fromspace_end(%rip), %rdx
  6008. cmpq %rdx, %rcx
  6009. jl block36
  6010. movq %r15, %rdi
  6011. movq $16, %rsi
  6012. callq collect
  6013. jmp block35
  6014. block39:
  6015. movq $0, %rcx
  6016. jmp block38
  6017. \end{lstlisting}
  6018. \end{minipage}
  6019. \begin{minipage}[t]{0.45\textwidth}
  6020. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6021. start:
  6022. movq $42, %rbx
  6023. movq free_ptr(%rip), %rdx
  6024. addq $16, %rdx
  6025. movq fromspace_end(%rip), %rcx
  6026. cmpq %rcx, %rdx
  6027. jl block39
  6028. movq %r15, %rdi
  6029. movq $16, %rsi
  6030. callq collect
  6031. jmp block38
  6032. .globl main
  6033. main:
  6034. pushq %rbp
  6035. movq %rsp, %rbp
  6036. pushq %r13
  6037. pushq %r12
  6038. pushq %rbx
  6039. pushq %r14
  6040. subq $0, %rsp
  6041. movq $16384, %rdi
  6042. movq $16384, %rsi
  6043. callq initialize
  6044. movq rootstack_begin(%rip), %r15
  6045. movq $0, (%r15)
  6046. addq $8, %r15
  6047. jmp start
  6048. conclusion:
  6049. subq $8, %r15
  6050. addq $0, %rsp
  6051. popq %r14
  6052. popq %rbx
  6053. popq %r12
  6054. popq %r13
  6055. popq %rbp
  6056. retq
  6057. \end{lstlisting}
  6058. \end{minipage}
  6059. \caption{Output of the \code{print-x86} pass.}
  6060. \label{fig:print-x86-output-gc}
  6061. \end{figure}
  6062. \begin{figure}[p]
  6063. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6064. \node (R3) at (0,2) {\large $R_3$};
  6065. \node (R3-2) at (3,2) {\large $R_3$};
  6066. \node (R3-3) at (6,2) {\large $R_3$};
  6067. \node (R3-4) at (9,2) {\large $R_3$};
  6068. \node (R3-5) at (9,0) {\large $R'_3$};
  6069. \node (R3-6) at (6,0) {\large $R'_3$};
  6070. \node (C2-4) at (3,-2) {\large $C_2$};
  6071. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  6072. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  6073. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  6074. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  6075. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  6076. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  6077. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6078. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  6079. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  6080. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  6081. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  6082. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6083. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6084. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6085. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6086. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6087. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6088. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6089. \end{tikzpicture}
  6090. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6091. \label{fig:R3-passes}
  6092. \end{figure}
  6093. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6094. for the compilation of $R_3$.
  6095. \section{Challenge: Simple Structures}
  6096. \label{sec:simple-structures}
  6097. \index{struct}
  6098. \index{structure}
  6099. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6100. $R^s_3$, which extends $R^3$ with support for simple structures.
  6101. Recall that a \code{struct} in Typed Racket is a user-defined data
  6102. type that contains named fields and that is heap allocated, similar to
  6103. a vector. The following is an example of a structure definition, in
  6104. this case the definition of a \code{point} type.
  6105. \begin{lstlisting}
  6106. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6107. \end{lstlisting}
  6108. \begin{figure}[tbp]
  6109. \centering
  6110. \fbox{
  6111. \begin{minipage}{0.96\textwidth}
  6112. \[
  6113. \begin{array}{lcl}
  6114. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6115. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6116. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6117. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6118. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6119. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6120. \mid (\key{and}\;\Exp\;\Exp)
  6121. \mid (\key{or}\;\Exp\;\Exp)
  6122. \mid (\key{not}\;\Exp) } \\
  6123. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6124. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6125. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6126. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6127. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6128. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6129. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6130. R_3 &::=& \Def \ldots \; \Exp
  6131. \end{array}
  6132. \]
  6133. \end{minipage}
  6134. }
  6135. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6136. (Figure~\ref{fig:r3-concrete-syntax}).}
  6137. \label{fig:r3s-concrete-syntax}
  6138. \end{figure}
  6139. An instance of a structure is created using function call syntax, with
  6140. the name of the structure in the function position:
  6141. \begin{lstlisting}
  6142. (point 7 12)
  6143. \end{lstlisting}
  6144. Function-call syntax is also used to read the value in a field of a
  6145. structure. The function name is formed by the structure name, a dash,
  6146. and the field name. The following example uses \code{point-x} and
  6147. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6148. instances.
  6149. \begin{center}
  6150. \begin{lstlisting}
  6151. (let ([pt1 (point 7 12)])
  6152. (let ([pt2 (point 4 3)])
  6153. (+ (- (point-x pt1) (point-x pt2))
  6154. (- (point-y pt1) (point-y pt2)))))
  6155. \end{lstlisting}
  6156. \end{center}
  6157. Similarly, to write to a field of a structure, use its set function,
  6158. whose name starts with \code{set-}, followed by the structure name,
  6159. then a dash, then the field name, and conclused with an exclamation
  6160. mark. The folowing example uses \code{set-point-x!} to change the
  6161. \code{x} field from \code{7} to \code{42}.
  6162. \begin{center}
  6163. \begin{lstlisting}
  6164. (let ([pt (point 7 12)])
  6165. (let ([_ (set-point-x! pt 42)])
  6166. (point-x pt)))
  6167. \end{lstlisting}
  6168. \end{center}
  6169. \begin{exercise}\normalfont
  6170. Extend your compiler with support for simple structures, compiling
  6171. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6172. structures and test your compiler.
  6173. \end{exercise}
  6174. \section{Challenge: Generational Collection}
  6175. The copying collector described in Section~\ref{sec:GC} can incur
  6176. significant runtime overhead because the call to \code{collect} takes
  6177. time proportional to all of the live data. One way to reduce this
  6178. overhead is to reduce how much data is inspected in each call to
  6179. \code{collect}. In particular, researchers have observed that recently
  6180. allocated data is more likely to become garbage then data that has
  6181. survived one or more previous calls to \code{collect}. This insight
  6182. motivated the creation of \emph{generational garbage collectors}
  6183. \index{generational garbage collector} that
  6184. 1) segragates data according to its age into two or more generations,
  6185. 2) allocates less space for younger generations, so collecting them is
  6186. faster, and more space for the older generations, and 3) performs
  6187. collection on the younger generations more frequently then for older
  6188. generations~\citep{Wilson:1992fk}.
  6189. For this challenge assignment, the goal is to adapt the copying
  6190. collector implemented in \code{runtime.c} to use two generations, one
  6191. for young data and one for old data. Each generation consists of a
  6192. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6193. \code{collect} function to use the two generations.
  6194. \begin{enumerate}
  6195. \item Copy the young generation's FromSpace to its ToSpace then switch
  6196. the role of the ToSpace and FromSpace
  6197. \item If there is enough space for the requested number of bytes in
  6198. the young FromSpace, then return from \code{collect}.
  6199. \item If there is not enough space in the young FromSpace for the
  6200. requested bytes, then move the data from the young generation to the
  6201. old one with the following steps:
  6202. \begin{enumerate}
  6203. \item If there is enough room in the old FromSpace, copy the young
  6204. FromSpace to the old FromSpace and then return.
  6205. \item If there is not enough room in the old FromSpace, then collect
  6206. the old generation by copying the old FromSpace to the old ToSpace
  6207. and swap the roles of the old FromSpace and ToSpace.
  6208. \item If there is enough room now, copy the young FromSpace to the
  6209. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6210. and ToSpace for the old generation. Copy the young FromSpace and
  6211. the old FromSpace into the larger FromSpace for the old
  6212. generation and then return.
  6213. \end{enumerate}
  6214. \end{enumerate}
  6215. We recommend that you generalize the \code{cheney} function so that it
  6216. can be used for all the copies mentioned above: between the young
  6217. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6218. between the young FromSpace and old FromSpace. This can be
  6219. accomplished by adding parameters to \code{cheney} that replace its
  6220. use of the global variables \code{fromspace\_begin},
  6221. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6222. Note that the collection of the young generation does not traverse the
  6223. old generation. This introduces a potential problem: there may be
  6224. young data that is only reachable through pointers in the old
  6225. generation. If these pointers are not taken into account, the
  6226. collector could throw away young data that is live! One solution,
  6227. called \emph{pointer recording}, is to maintain a set of all the
  6228. pointers from the old generation into the new generation and consider
  6229. this set as part of the root set. To maintain this set, the compiler
  6230. must insert extra instructions around every \code{vector-set!}. If the
  6231. vector being modified is in the old generation, and if the value being
  6232. written is a pointer into the new generation, than that pointer must
  6233. be added to the set. Also, if the value being overwritten was a
  6234. pointer into the new generation, then that pointer should be removed
  6235. from the set.
  6236. \begin{exercise}\normalfont
  6237. Adapt the \code{collect} function in \code{runtime.c} to implement
  6238. generational garbage collection, as outlined in this section.
  6239. Update the code generation for \code{vector-set!} to implement
  6240. pointer recording. Make sure that your new compiler and runtime
  6241. passes your test suite.
  6242. \end{exercise}
  6243. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6244. \chapter{Functions}
  6245. \label{ch:functions}
  6246. \index{function}
  6247. This chapter studies the compilation of functions similar to those
  6248. found in the C language. This corresponds to a subset of Typed Racket
  6249. in which only top-level function definitions are allowed. This kind of
  6250. function is an important stepping stone to implementing
  6251. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6252. is the topic of Chapter~\ref{ch:lambdas}.
  6253. \section{The $R_4$ Language}
  6254. The concrete and abstract syntax for function definitions and function
  6255. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6256. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6257. $R_4$ begin with zero or more function definitions. The function
  6258. names from these definitions are in-scope for the entire program,
  6259. including all other function definitions (so the ordering of function
  6260. definitions does not matter). The concrete syntax for function
  6261. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6262. where the first expression must
  6263. evaluate to a function and the rest are the arguments.
  6264. The abstract syntax for function application is
  6265. $\APPLY{\Exp}{\Exp\ldots}$.
  6266. %% The syntax for function application does not include an explicit
  6267. %% keyword, which is error prone when using \code{match}. To alleviate
  6268. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6269. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6270. Functions are first-class in the sense that a function pointer
  6271. \index{function pointer} is data and can be stored in memory or passed
  6272. as a parameter to another function. Thus, we introduce a function
  6273. type, written
  6274. \begin{lstlisting}
  6275. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6276. \end{lstlisting}
  6277. for a function whose $n$ parameters have the types $\Type_1$ through
  6278. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6279. these functions (with respect to Racket functions) is that they are
  6280. not lexically scoped. That is, the only external entities that can be
  6281. referenced from inside a function body are other globally-defined
  6282. functions. The syntax of $R_4$ prevents functions from being nested
  6283. inside each other.
  6284. \begin{figure}[tp]
  6285. \centering
  6286. \fbox{
  6287. \begin{minipage}{0.96\textwidth}
  6288. \small
  6289. \[
  6290. \begin{array}{lcl}
  6291. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6292. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6293. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6294. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6295. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6296. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6297. \mid (\key{and}\;\Exp\;\Exp)
  6298. \mid (\key{or}\;\Exp\;\Exp)
  6299. \mid (\key{not}\;\Exp)} \\
  6300. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6301. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6302. (\key{vector-ref}\;\Exp\;\Int)} \\
  6303. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6304. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6305. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6306. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6307. R_4 &::=& \Def \ldots \; \Exp
  6308. \end{array}
  6309. \]
  6310. \end{minipage}
  6311. }
  6312. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6313. \label{fig:r4-concrete-syntax}
  6314. \end{figure}
  6315. \begin{figure}[tp]
  6316. \centering
  6317. \fbox{
  6318. \begin{minipage}{0.96\textwidth}
  6319. \small
  6320. \[
  6321. \begin{array}{lcl}
  6322. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6323. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6324. &\mid& \gray{ \BOOL{\itm{bool}}
  6325. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6326. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6327. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6328. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6329. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6330. \end{array}
  6331. \]
  6332. \end{minipage}
  6333. }
  6334. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6335. \label{fig:r4-syntax}
  6336. \end{figure}
  6337. The program in Figure~\ref{fig:r4-function-example} is a
  6338. representative example of defining and using functions in $R_4$. We
  6339. define a function \code{map-vec} that applies some other function
  6340. \code{f} to both elements of a vector and returns a new
  6341. vector containing the results. We also define a function \code{add1}.
  6342. The program applies
  6343. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6344. \code{(vector 1 42)}, from which we return the \code{42}.
  6345. \begin{figure}[tbp]
  6346. \begin{lstlisting}
  6347. (define (map-vec [f : (Integer -> Integer)]
  6348. [v : (Vector Integer Integer)])
  6349. : (Vector Integer Integer)
  6350. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6351. (define (add1 [x : Integer]) : Integer
  6352. (+ x 1))
  6353. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6354. \end{lstlisting}
  6355. \caption{Example of using functions in $R_4$.}
  6356. \label{fig:r4-function-example}
  6357. \end{figure}
  6358. The definitional interpreter for $R_4$ is in
  6359. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6360. responsible for setting up the mutual recursion between the top-level
  6361. function definitions. We use the classic back-patching \index{back-patching}
  6362. approach that uses mutable variables and makes two passes over the function
  6363. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6364. top-level environment using a mutable cons cell for each function
  6365. definition. Note that the \code{lambda} value for each function is
  6366. incomplete; it does not yet include the environment. Once the
  6367. top-level environment is constructed, we then iterate over it and
  6368. update the \code{lambda} values to use the top-level environment.
  6369. \begin{figure}[tp]
  6370. \begin{lstlisting}
  6371. (define (interp-exp env)
  6372. (lambda (e)
  6373. (define recur (interp-exp env))
  6374. (match e
  6375. ...
  6376. [(Apply fun args)
  6377. (define fun-val (recur fun))
  6378. (define arg-vals (for/list ([e args]) (recur e)))
  6379. (match fun-val
  6380. [`(lambda (,xs ...) ,body ,fun-env)
  6381. (define new-env (append (map cons xs arg-vals) fun-env))
  6382. ((interp-exp new-env) body)])]
  6383. ...
  6384. )))
  6385. (define (interp-def d)
  6386. (match d
  6387. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6388. (mcons f `(lambda ,xs ,body ()))]
  6389. ))
  6390. (define (interp-R4 p)
  6391. (match p
  6392. [(ProgramDefsExp info ds body)
  6393. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6394. (for/list ([b top-level])
  6395. (set-mcdr! b (match (mcdr b)
  6396. [`(lambda ,xs ,body ())
  6397. `(lambda ,xs ,body ,top-level)])))
  6398. ((interp-exp top-level) body))]
  6399. ))
  6400. \end{lstlisting}
  6401. \caption{Interpreter for the $R_4$ language.}
  6402. \label{fig:interp-R4}
  6403. \end{figure}
  6404. \margincomment{TODO: explain type checker}
  6405. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6406. \begin{figure}[tp]
  6407. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6408. (define (fun-def-name d)
  6409. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6410. (define (fun-def-type d)
  6411. (match d
  6412. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6413. (define (type-check-exp env)
  6414. (lambda (e)
  6415. (match e
  6416. ...
  6417. [(Apply e es)
  6418. (define-values (e^ ty) ((type-check-exp env) e))
  6419. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6420. ((type-check-exp env) e)))
  6421. (match ty
  6422. [`(,ty^* ... -> ,rt)
  6423. (for ([arg-ty ty*] [prm-ty ty^*])
  6424. (unless (equal? arg-ty prm-ty)
  6425. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6426. (values (HasType (Apply e^ e*) rt) rt)]
  6427. [else (error "expected a function, not" ty)])])))
  6428. (define (type-check-def env)
  6429. (lambda (e)
  6430. (match e
  6431. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6432. (define new-env (append (map cons xs ps) env))
  6433. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6434. (unless (equal? ty^ rt)
  6435. (error "body type ~a not equal to return type ~a" ty^ rt))
  6436. (Def f p:t* rt info body^)])))
  6437. (define (type-check env)
  6438. (lambda (e)
  6439. (match e
  6440. [(ProgramDefsExp info ds body)
  6441. (define new-env (for/list ([d ds])
  6442. (cons (fun-def-name d) (fun-def-type d))))
  6443. (define ds^ (for/list ([d ds])
  6444. ((type-check-def new-env) d)))
  6445. (define-values (body^ ty) ((type-check-exp new-env) body))
  6446. (unless (equal? ty 'Integer)
  6447. (error "result of the program must be an integer, not " ty))
  6448. (ProgramDefsExp info ds^ body^)]
  6449. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6450. \end{lstlisting}
  6451. \caption{Type checker for the $R_4$ language.}
  6452. \label{fig:type-check-R4}
  6453. \end{figure}
  6454. \section{Functions in x86}
  6455. \label{sec:fun-x86}
  6456. \margincomment{\tiny Make sure callee-saved registers are discussed
  6457. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6458. \margincomment{\tiny Talk about the return address on the
  6459. stack and what callq and retq does.\\ --Jeremy }
  6460. The x86 architecture provides a few features to support the
  6461. implementation of functions. We have already seen that x86 provides
  6462. labels so that one can refer to the location of an instruction, as is
  6463. needed for jump instructions. Labels can also be used to mark the
  6464. beginning of the instructions for a function. Going further, we can
  6465. obtain the address of a label by using the \key{leaq} instruction and
  6466. PC-relative addressing. For example, the following puts the
  6467. address of the \code{add1} label into the \code{rbx} register.
  6468. \begin{lstlisting}
  6469. leaq add1(%rip), %rbx
  6470. \end{lstlisting}
  6471. The instruction pointer register \key{rip} (aka. the program counter
  6472. \index{program counter}) always points to the next instruction to be
  6473. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6474. linker computes the distance $d$ between the address of \code{add1}
  6475. and where the \code{rip} would be at that moment and then changes
  6476. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6477. the address of \code{add1}.
  6478. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6479. jump to a function whose location is given by a label. To support
  6480. function calls in this chapter we instead will be jumping to a
  6481. function whose location is given by an address in a register, that is,
  6482. we need to make an \emph{indirect function call}. The x86 syntax for
  6483. this is a \code{callq} instruction but with an asterisk before the
  6484. register name.\index{indirect function call}
  6485. \begin{lstlisting}
  6486. callq *%rbx
  6487. \end{lstlisting}
  6488. \subsection{Calling Conventions}
  6489. \index{calling conventions}
  6490. The \code{callq} instruction provides partial support for implementing
  6491. functions: it pushes the return address on the stack and it jumps to
  6492. the target. However, \code{callq} does not handle
  6493. \begin{enumerate}
  6494. \item parameter passing,
  6495. \item pushing frames on the procedure call stack and popping them off,
  6496. or
  6497. \item determining how registers are shared by different functions.
  6498. \end{enumerate}
  6499. Regarding (1) parameter passing, recall that the following six
  6500. registers are used to pass arguments to a function, in this order.
  6501. \begin{lstlisting}
  6502. rdi rsi rdx rcx r8 r9
  6503. \end{lstlisting}
  6504. If there are
  6505. more than six arguments, then the convention is to use space on the
  6506. frame of the caller for the rest of the arguments. However, to ease
  6507. the implementation of efficient tail calls
  6508. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6509. arguments.
  6510. %
  6511. Also recall that the register \code{rax} is for the return value of
  6512. the function.
  6513. \index{prelude}\index{conclusion}
  6514. Regarding (2) frames \index{frame} and the procedure call stack,
  6515. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6516. the stack grows down, with each function call using a chunk of space
  6517. called a frame. The caller sets the stack pointer, register
  6518. \code{rsp}, to the last data item in its frame. The callee must not
  6519. change anything in the caller's frame, that is, anything that is at or
  6520. above the stack pointer. The callee is free to use locations that are
  6521. below the stack pointer.
  6522. Recall that we are storing variables of vector type on the root stack.
  6523. So the prelude needs to move the root stack pointer \code{r15} up and
  6524. the conclusion needs to move the root stack pointer back down. Also,
  6525. the prelude must initialize to \code{0} this frame's slots in the root
  6526. stack to signal to the garbage collector that those slots do not yet
  6527. contain a pointer to a vector. Otherwise the garbage collector will
  6528. interpret the garbage bits in those slots as memory addresses and try
  6529. to traverse them, causing serious mayhem!
  6530. Regarding (3) the sharing of registers between different functions,
  6531. recall from Section~\ref{sec:calling-conventions} that the registers
  6532. are divided into two groups, the caller-saved registers and the
  6533. callee-saved registers. The caller should assume that all the
  6534. caller-saved registers get overwritten with arbitrary values by the
  6535. callee. That is why we recommend in
  6536. Section~\ref{sec:calling-conventions} that variables that are live
  6537. during a function call should not be assigned to caller-saved
  6538. registers.
  6539. On the flip side, if the callee wants to use a callee-saved register,
  6540. the callee must save the contents of those registers on their stack
  6541. frame and then put them back prior to returning to the caller. That
  6542. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6543. the register allocator assigns a variable to a callee-saved register,
  6544. then the prelude of the \code{main} function must save that register
  6545. to the stack and the conclusion of \code{main} must restore it. This
  6546. recommendation now generalizes to all functions.
  6547. Also recall that the base pointer, register \code{rbp}, is used as a
  6548. point-of-reference within a frame, so that each local variable can be
  6549. accessed at a fixed offset from the base pointer
  6550. (Section~\ref{sec:x86}).
  6551. %
  6552. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6553. and callee frames.
  6554. \begin{figure}[tbp]
  6555. \centering
  6556. \begin{tabular}{r|r|l|l} \hline
  6557. Caller View & Callee View & Contents & Frame \\ \hline
  6558. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6559. 0(\key{\%rbp}) & & old \key{rbp} \\
  6560. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6561. \ldots & & \ldots \\
  6562. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6563. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6564. \ldots & & \ldots \\
  6565. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6566. %% & & \\
  6567. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6568. %% & \ldots & \ldots \\
  6569. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6570. \hline
  6571. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6572. & 0(\key{\%rbp}) & old \key{rbp} \\
  6573. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6574. & \ldots & \ldots \\
  6575. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6576. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6577. & \ldots & \ldots \\
  6578. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6579. \end{tabular}
  6580. \caption{Memory layout of caller and callee frames.}
  6581. \label{fig:call-frames}
  6582. \end{figure}
  6583. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6584. %% local variables and for storing the values of callee-saved registers
  6585. %% (we shall refer to all of these collectively as ``locals''), and that
  6586. %% at the beginning of a function we move the stack pointer \code{rsp}
  6587. %% down to make room for them.
  6588. %% We recommend storing the local variables
  6589. %% first and then the callee-saved registers, so that the local variables
  6590. %% can be accessed using \code{rbp} the same as before the addition of
  6591. %% functions.
  6592. %% To make additional room for passing arguments, we shall
  6593. %% move the stack pointer even further down. We count how many stack
  6594. %% arguments are needed for each function call that occurs inside the
  6595. %% body of the function and find their maximum. Adding this number to the
  6596. %% number of locals gives us how much the \code{rsp} should be moved at
  6597. %% the beginning of the function. In preparation for a function call, we
  6598. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6599. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6600. %% so on.
  6601. %% Upon calling the function, the stack arguments are retrieved by the
  6602. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6603. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6604. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6605. %% the layout of the caller and callee frames. Notice how important it is
  6606. %% that we correctly compute the maximum number of arguments needed for
  6607. %% function calls; if that number is too small then the arguments and
  6608. %% local variables will smash into each other!
  6609. \subsection{Efficient Tail Calls}
  6610. \label{sec:tail-call}
  6611. In general, the amount of stack space used by a program is determined
  6612. by the longest chain of nested function calls. That is, if function
  6613. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6614. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6615. $n$ can grow quite large in the case of recursive or mutually
  6616. recursive functions. However, in some cases we can arrange to use only
  6617. constant space, i.e. $O(1)$, instead of $O(n)$.
  6618. If a function call is the last action in a function body, then that
  6619. call is said to be a \emph{tail call}\index{tail call}.
  6620. For example, in the following
  6621. program, the recursive call to \code{tail-sum} is a tail call.
  6622. \begin{center}
  6623. \begin{lstlisting}
  6624. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6625. (if (eq? n 0)
  6626. r
  6627. (tail-sum (- n 1) (+ n r))))
  6628. (+ (tail-sum 5 0) 27)
  6629. \end{lstlisting}
  6630. \end{center}
  6631. At a tail call, the frame of the caller is no longer needed, so we
  6632. can pop the caller's frame before making the tail call. With this
  6633. approach, a recursive function that only makes tail calls will only
  6634. use $O(1)$ stack space. Functional languages like Racket typically
  6635. rely heavily on recursive functions, so they typically guarantee that
  6636. all tail calls will be optimized in this way.
  6637. \index{frame}
  6638. However, some care is needed with regards to argument passing in tail
  6639. calls. As mentioned above, for arguments beyond the sixth, the
  6640. convention is to use space in the caller's frame for passing
  6641. arguments. But for a tail call we pop the caller's frame and can no
  6642. longer use it. Another alternative is to use space in the callee's
  6643. frame for passing arguments. However, this option is also problematic
  6644. because the caller and callee's frame overlap in memory. As we begin
  6645. to copy the arguments from their sources in the caller's frame, the
  6646. target locations in the callee's frame might overlap with the sources
  6647. for later arguments! We solve this problem by not using the stack for
  6648. passing more than six arguments but instead using the heap, as we
  6649. describe in the Section~\ref{sec:limit-functions-r4}.
  6650. As mentioned above, for a tail call we pop the caller's frame prior to
  6651. making the tail call. The instructions for popping a frame are the
  6652. instructions that we usually place in the conclusion of a
  6653. function. Thus, we also need to place such code immediately before
  6654. each tail call. These instructions include restoring the callee-saved
  6655. registers, so it is good that the argument passing registers are all
  6656. caller-saved registers.
  6657. One last note regarding which instruction to use to make the tail
  6658. call. When the callee is finished, it should not return to the current
  6659. function, but it should return to the function that called the current
  6660. one. Thus, the return address that is already on the stack is the
  6661. right one, and we should not use \key{callq} to make the tail call, as
  6662. that would unnecessarily overwrite the return address. Instead we can
  6663. simply use the \key{jmp} instruction. Like the indirect function call,
  6664. we write an \emph{indirect jump}\index{indirect jump} with a register
  6665. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6666. jump target because the preceding conclusion overwrites just about
  6667. everything else.
  6668. \begin{lstlisting}
  6669. jmp *%rax
  6670. \end{lstlisting}
  6671. \section{Shrink $R_4$}
  6672. \label{sec:shrink-r4}
  6673. The \code{shrink} pass performs a minor modification to ease the
  6674. later passes. This pass introduces an explicit \code{main} function
  6675. and changes the top \code{ProgramDefsExp} form to
  6676. \code{ProgramDefs} as follows.
  6677. \begin{lstlisting}
  6678. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6679. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6680. \end{lstlisting}
  6681. where $\itm{mainDef}$ is
  6682. \begin{lstlisting}
  6683. (Def 'main '() 'Integer '() |$\Exp'$|)
  6684. \end{lstlisting}
  6685. \section{Reveal Functions and the $F_1$ language}
  6686. \label{sec:reveal-functions-r4}
  6687. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6688. respect: it conflates the use of function names and local
  6689. variables. This is a problem because we need to compile the use of a
  6690. function name differently than the use of a local variable; we need to
  6691. use \code{leaq} to convert the function name (a label in x86) to an
  6692. address in a register. Thus, it is a good idea to create a new pass
  6693. that changes function references from just a symbol $f$ to
  6694. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6695. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6696. \begin{figure}[tp]
  6697. \centering
  6698. \fbox{
  6699. \begin{minipage}{0.96\textwidth}
  6700. \[
  6701. \begin{array}{lcl}
  6702. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6703. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6704. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6705. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6706. &\mid& \gray{ \BOOL{\itm{bool}}
  6707. \mid \AND{\Exp}{\Exp} }\\
  6708. &\mid& \gray{ \OR{\Exp}{\Exp}
  6709. \mid \NOT{\Exp} } \\
  6710. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6711. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6712. &\mid& \gray{ \VECTOR{\Exp} } \\
  6713. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6714. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6715. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6716. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6717. &\mid& \FUNREF{\Var}\\
  6718. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6719. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6720. \end{array}
  6721. \]
  6722. \end{minipage}
  6723. }
  6724. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6725. (Figure~\ref{fig:r4-syntax}).}
  6726. \label{fig:f1-syntax}
  6727. \end{figure}
  6728. %% Distinguishing between calls in tail position and non-tail position
  6729. %% requires the pass to have some notion of context. We recommend using
  6730. %% two mutually recursive functions, one for processing expressions in
  6731. %% tail position and another for the rest.
  6732. Placing this pass after \code{uniquify} will make sure that there are
  6733. no local variables and functions that share the same name. On the
  6734. other hand, \code{reveal-functions} needs to come before the
  6735. \code{explicate-control} pass because that pass helps us compile
  6736. \code{FunRef} forms into assignment statements.
  6737. \section{Limit Functions}
  6738. \label{sec:limit-functions-r4}
  6739. Recall that we wish to limit the number of function parameters to six
  6740. so that we do not need to use the stack for argument passing, which
  6741. makes it easier to implement efficient tail calls. However, because
  6742. the input language $R_4$ supports arbitrary numbers of function
  6743. arguments, we have some work to do!
  6744. This pass transforms functions and function calls that involve more
  6745. than six arguments to pass the first five arguments as usual, but it
  6746. packs the rest of the arguments into a vector and passes it as the
  6747. sixth argument.
  6748. Each function definition with too many parameters is transformed as
  6749. follows.
  6750. \begin{lstlisting}
  6751. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6752. |$\Rightarrow$|
  6753. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6754. \end{lstlisting}
  6755. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6756. the occurences of the later parameters with vector references.
  6757. \begin{lstlisting}
  6758. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6759. \end{lstlisting}
  6760. For function calls with too many arguments, the \code{limit-functions}
  6761. pass transforms them in the following way.
  6762. \begin{tabular}{lll}
  6763. \begin{minipage}{0.2\textwidth}
  6764. \begin{lstlisting}
  6765. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6766. \end{lstlisting}
  6767. \end{minipage}
  6768. &
  6769. $\Rightarrow$
  6770. &
  6771. \begin{minipage}{0.4\textwidth}
  6772. \begin{lstlisting}
  6773. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6774. \end{lstlisting}
  6775. \end{minipage}
  6776. \end{tabular}
  6777. \section{Remove Complex Operators and Operands}
  6778. \label{sec:rco-r4}
  6779. The primary decisions to make for this pass is whether to classify
  6780. \code{FunRef} and \code{Apply} as either simple or complex
  6781. expressions. Recall that a simple expression will eventually end up as
  6782. just an ``immediate'' argument of an x86 instruction. Function
  6783. application will be translated to a sequence of instructions, so
  6784. \code{Apply} must be classified as complex expression. Regarding
  6785. \code{FunRef}, as discussed above, the function label needs to
  6786. be converted to an address using the \code{leaq} instruction. Thus,
  6787. even though \code{FunRef} seems rather simple, it needs to be
  6788. classified as a complex expression so that we generate an assignment
  6789. statement with a left-hand side that can serve as the target of the
  6790. \code{leaq}.
  6791. \section{Explicate Control and the $C_3$ language}
  6792. \label{sec:explicate-control-r4}
  6793. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6794. the concrete and abstract syntax for $C_3$, the output of
  6795. \key{explicate-control}. The auxiliary functions for assignment and
  6796. tail contexts should be updated with cases for \code{Apply} and
  6797. \code{FunRef} and the function for predicate context should be updated
  6798. for \code{Apply} but not \code{FunRef}. (A \code{FunRef} can't be a
  6799. Boolean.) In assignment and predicate contexts, \code{Apply} becomes
  6800. \code{Call}, whereas in tail position \code{Apply} becomes
  6801. \code{TailCall}. We recommend defining a new auxiliary function for
  6802. processing function definitions. This code is similar to the case for
  6803. \code{Program} in $R_3$. The top-level \code{explicate-control}
  6804. function that handles the \code{ProgramDefs} form of $R_4$ can then
  6805. apply this new function to all the function definitions.
  6806. \begin{figure}[tp]
  6807. \fbox{
  6808. \begin{minipage}{0.96\textwidth}
  6809. \[
  6810. \begin{array}{lcl}
  6811. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6812. \\
  6813. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6814. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  6815. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  6816. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  6817. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  6818. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  6819. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  6820. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6821. \mid \LP\key{collect} \,\itm{int}\RP }\\
  6822. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  6823. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  6824. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  6825. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  6826. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  6827. C_3 & ::= & \Def\ldots
  6828. \end{array}
  6829. \]
  6830. \end{minipage}
  6831. }
  6832. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6833. \label{fig:c3-concrete-syntax}
  6834. \end{figure}
  6835. \begin{figure}[tp]
  6836. \fbox{
  6837. \begin{minipage}{0.96\textwidth}
  6838. \small
  6839. \[
  6840. \begin{array}{lcl}
  6841. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6842. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6843. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6844. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6845. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6846. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6847. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6848. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6849. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6850. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  6851. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6852. \mid (\key{Collect} \,\itm{int}) } \\
  6853. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6854. \mid \GOTO{\itm{label}} } \\
  6855. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6856. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6857. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{\itm{info}}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6858. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6859. \end{array}
  6860. \]
  6861. \end{minipage}
  6862. }
  6863. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6864. \label{fig:c3-syntax}
  6865. \end{figure}
  6866. \section{Select Instructions and the x86$_3$ Language}
  6867. \label{sec:select-r4}
  6868. \index{instruction selection}
  6869. The output of select instructions is a program in the x86$_3$
  6870. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6871. \index{x86}
  6872. \begin{figure}[tp]
  6873. \fbox{
  6874. \begin{minipage}{0.96\textwidth}
  6875. \small
  6876. \[
  6877. \begin{array}{lcl}
  6878. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  6879. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  6880. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6881. \Instr &::=& \ldots
  6882. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  6883. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  6884. \Block &::= & \Instr\ldots \\
  6885. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  6886. x86_3 &::= & \Def\ldots
  6887. \end{array}
  6888. \]
  6889. \end{minipage}
  6890. }
  6891. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2-concrete}).}
  6892. \label{fig:x86-3-concrete}
  6893. \end{figure}
  6894. \begin{figure}[tp]
  6895. \fbox{
  6896. \begin{minipage}{0.96\textwidth}
  6897. \small
  6898. \[
  6899. \begin{array}{lcl}
  6900. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6901. \mid \BYTEREG{\Reg} } \\
  6902. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6903. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  6904. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6905. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6906. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  6907. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  6908. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  6909. \end{array}
  6910. \]
  6911. \end{minipage}
  6912. }
  6913. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6914. \label{fig:x86-3}
  6915. \end{figure}
  6916. An assignment of a function reference to a variable becomes a
  6917. load-effective-address instruction as follows: \\
  6918. \begin{tabular}{lcl}
  6919. \begin{minipage}{0.35\textwidth}
  6920. \begin{lstlisting}
  6921. |$\itm{lhs}$| = (fun-ref |$f$|);
  6922. \end{lstlisting}
  6923. \end{minipage}
  6924. &
  6925. $\Rightarrow$\qquad\qquad
  6926. &
  6927. \begin{minipage}{0.3\textwidth}
  6928. \begin{lstlisting}
  6929. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  6930. \end{lstlisting}
  6931. \end{minipage}
  6932. \end{tabular} \\
  6933. Regarding function definitions, we need to remove the parameters and
  6934. instead perform parameter passing using the conventions discussed in
  6935. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  6936. registers. We recommend turning the parameters into local variables
  6937. and generating instructions at the beginning of the function to move
  6938. from the argument passing registers to these local variables.
  6939. \begin{lstlisting}
  6940. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6941. |$\Rightarrow$|
  6942. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6943. \end{lstlisting}
  6944. The $G'$ control-flow graph is the same as $G$ except that the
  6945. \code{start} block is modified to add the instructions for moving from
  6946. the argument registers to the parameter variables. So the \code{start}
  6947. block of $G$ shown on the left is changed to the code on the right.
  6948. \begin{center}
  6949. \begin{minipage}{0.3\textwidth}
  6950. \begin{lstlisting}
  6951. start:
  6952. |$\itm{instr}_1$|
  6953. |$\vdots$|
  6954. |$\itm{instr}_n$|
  6955. \end{lstlisting}
  6956. \end{minipage}
  6957. $\Rightarrow$
  6958. \begin{minipage}{0.3\textwidth}
  6959. \begin{lstlisting}
  6960. start:
  6961. movq %rdi, |$x_1$|
  6962. movq %rsi, |$x_2$|
  6963. |$\vdots$|
  6964. |$\itm{instr}_1$|
  6965. |$\vdots$|
  6966. |$\itm{instr}_n$|
  6967. \end{lstlisting}
  6968. \end{minipage}
  6969. \end{center}
  6970. By changing the parameters to local variables, we are giving the
  6971. register allocator control over which registers or stack locations to
  6972. use for them. If you implemented the move-biasing challenge
  6973. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6974. assign the parameter variables to the corresponding argument register,
  6975. in which case the \code{patch-instructions} pass will remove the
  6976. \code{movq} instruction. This happens in the example translation in
  6977. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  6978. the \code{add} function.
  6979. %
  6980. Also, note that the register allocator will perform liveness analysis
  6981. on this sequence of move instructions and build the interference
  6982. graph. So, for example, $x_1$ will be marked as interfering with
  6983. \code{rsi} and that will prevent the assignment of $x_1$ to
  6984. \code{rsi}, which is good, because that would overwrite the argument
  6985. that needs to move into $x_2$.
  6986. Next, consider the compilation of function calls. In the mirror image
  6987. of handling the parameters of function definitions, the arguments need
  6988. to be moved to the argument passing registers. The function call
  6989. itself is performed with an indirect function call. The return value
  6990. from the function is stored in \code{rax}, so it needs to be moved
  6991. into the \itm{lhs}.
  6992. \begin{lstlisting}
  6993. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  6994. |$\Rightarrow$|
  6995. movq |$\itm{arg}_1$|, %rdi
  6996. movq |$\itm{arg}_2$|, %rsi
  6997. |$\vdots$|
  6998. callq *|\itm{fun}|
  6999. movq %rax, |\itm{lhs}|
  7000. \end{lstlisting}
  7001. The \code{IndirectCallq} AST node includes an integer for the arity of
  7002. the function, i.e., the number of parameters. That information is
  7003. useful in the \code{uncover-live} pass for determining which
  7004. argument-passing registers are potentially read during the call.
  7005. For tail calls, the parameter passing is the same as non-tail calls:
  7006. generate instructions to move the arguments into to the argument
  7007. passing registers. After that we need to pop the frame from the
  7008. procedure call stack. However, we do not yet know how big the frame
  7009. is; that gets determined during register allocation. So instead of
  7010. generating those instructions here, we invent a new instruction that
  7011. means ``pop the frame and then do an indirect jump'', which we name
  7012. \code{TailJmp}. The abstract syntax for this instruction includes an
  7013. argument that specifies where to jump and an integer that represents
  7014. the arity of the function being called.
  7015. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7016. using the label \code{start} for the initial block of a program, and
  7017. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7018. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7019. can be compiled to an assignment to \code{rax} followed by a jump to
  7020. \code{conclusion}. With the addition of function definitions, we will
  7021. have a starting block and conclusion for each function, but their
  7022. labels need to be unique. We recommend prepending the function's name
  7023. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7024. labels. (Alternatively, one could \code{gensym} labels for the start
  7025. and conclusion and store them in the $\itm{info}$ field of the
  7026. function definition.)
  7027. \section{Uncover Live}
  7028. %% The rest of the passes need only minor modifications to handle the new
  7029. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7030. %% \code{leaq}.
  7031. The \code{IndirectCallq} instruction should be treated like
  7032. \code{Callq} regarding its written locations $W$, in that they should
  7033. include all the caller-saved registers. Recall that the reason for
  7034. that is to force call-live variables to be assigned to callee-saved
  7035. registers or to be spilled to the stack. Also, the arity field of
  7036. \code{IndirectCallq} determines how many of the argument-passing
  7037. registers should be considered in the set of read locations $R$.
  7038. \section{Build Interference Graph}
  7039. With the addition of function definitions, we compute an interference
  7040. graph for each function (not just one for the whole program).
  7041. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7042. spill vector-typed variables that are live during a call to the
  7043. \code{collect}. With the addition of functions to our language, we
  7044. need to revisit this issue. Many functions perform allocation and
  7045. therefore have calls to the collector inside of them. Thus, we should
  7046. not only spill a vector-typed variable when it is live during a call
  7047. to \code{collect}, but we should spill the variable if it is live
  7048. during any function call. Thus, in the \code{build-interference} pass,
  7049. we recommend adding interference edges between call-live vector-typed
  7050. variables and the callee-saved registers (in addition to the usual
  7051. addition of edges between call-live variables and the caller-saved
  7052. registers).
  7053. \section{Allocate Registers}
  7054. The primary change to the \code{allocate-registers} pass is adding an
  7055. auxiliary function for handling definitions (the \Def{} non-terminal
  7056. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7057. logic is the same as described in
  7058. Chapter~\ref{ch:register-allocation-r1}, except now register
  7059. allocation is performed many times, once for each function definition,
  7060. instead of just once for the whole program.
  7061. \section{Patch Instructions}
  7062. In \code{patch-instructions}, you should deal with the x86
  7063. idiosyncrasy that the destination argument of \code{leaq} must be a
  7064. register. Additionally, you should ensure that the argument of
  7065. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7066. code generation more convenient, because we trample many registers
  7067. before the tail call (as explained in the next section).
  7068. \section{Print x86}
  7069. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7070. \code{IndirectCallq} are straightforward: output their concrete
  7071. syntax.
  7072. \begin{lstlisting}
  7073. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7074. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7075. \end{lstlisting}
  7076. The \code{TailJmp} node requires a bit work. A straightforward
  7077. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7078. before the jump we need to pop the current frame. This sequence of
  7079. instructions is the same as the code for the conclusion of a function,
  7080. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7081. Regarding function definitions, you will need to generate a prelude
  7082. and conclusion for each one. This code is similar to the prelude and
  7083. conclusion that you generated for the \code{main} function in
  7084. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7085. should carry out the following steps.
  7086. \begin{enumerate}
  7087. \item Start with \code{.global} and \code{.align} directives followed
  7088. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7089. example.)
  7090. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7091. pointer.
  7092. \item Push to the stack all of the callee-saved registers that were
  7093. used for register allocation.
  7094. \item Move the stack pointer \code{rsp} down by the size of the stack
  7095. frame for this function, which depends on the number of regular
  7096. spills. (Aligned to 16 bytes.)
  7097. \item Move the root stack pointer \code{r15} up by the size of the
  7098. root-stack frame for this function, which depends on the number of
  7099. spilled vectors. \label{root-stack-init}
  7100. \item Initialize to zero all of the entries in the root-stack frame.
  7101. \item Jump to the start block.
  7102. \end{enumerate}
  7103. The prelude of the \code{main} function has one additional task: call
  7104. the \code{initialize} function to set up the garbage collector and
  7105. move the value of the global \code{rootstack\_begin} in
  7106. \code{r15}. This should happen before step \ref{root-stack-init}
  7107. above, which depends on \code{r15}.
  7108. The conclusion of every function should do the following.
  7109. \begin{enumerate}
  7110. \item Move the stack pointer back up by the size of the stack frame
  7111. for this function.
  7112. \item Restore the callee-saved registers by popping them from the
  7113. stack.
  7114. \item Move the root stack pointer back down by the size of the
  7115. root-stack frame for this function.
  7116. \item Restore \code{rbp} by popping it from the stack.
  7117. \item Return to the caller with the \code{retq} instruction.
  7118. \end{enumerate}
  7119. \begin{exercise}\normalfont
  7120. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7121. Create 5 new programs that use functions, including examples that pass
  7122. functions and return functions from other functions, recursive
  7123. functions, functions that create vectors, and functions that make tail
  7124. calls. Test your compiler on these new programs and all of your
  7125. previously created test programs.
  7126. \end{exercise}
  7127. \begin{figure}[tbp]
  7128. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7129. \node (R4) at (0,2) {\large $R_4$};
  7130. \node (R4-2) at (3,2) {\large $R_4$};
  7131. \node (R4-3) at (6,2) {\large $R_4$};
  7132. \node (F1-1) at (12,0) {\large $F_1$};
  7133. \node (F1-2) at (9,0) {\large $F_1$};
  7134. \node (F1-3) at (6,0) {\large $F_1$};
  7135. \node (F1-4) at (3,0) {\large $F_1$};
  7136. \node (C3-2) at (3,-2) {\large $C_3$};
  7137. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7138. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7139. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7140. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7141. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7142. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7143. \path[->,bend left=15] (R4) edge [above] node
  7144. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7145. \path[->,bend left=15] (R4-2) edge [above] node
  7146. {\ttfamily\footnotesize uniquify} (R4-3);
  7147. \path[->,bend left=15] (R4-3) edge [right] node
  7148. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7149. \path[->,bend left=15] (F1-1) edge [below] node
  7150. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7151. \path[->,bend right=15] (F1-2) edge [above] node
  7152. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7153. \path[->,bend right=15] (F1-3) edge [above] node
  7154. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7155. \path[->,bend left=15] (F1-4) edge [right] node
  7156. {\ttfamily\footnotesize\color{red} explicate-control} (C3-2);
  7157. \path[->,bend right=15] (C3-2) edge [left] node
  7158. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7159. \path[->,bend left=15] (x86-2) edge [left] node
  7160. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7161. \path[->,bend right=15] (x86-2-1) edge [below] node
  7162. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7163. \path[->,bend right=15] (x86-2-2) edge [left] node
  7164. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7165. \path[->,bend left=15] (x86-3) edge [above] node
  7166. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7167. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7168. \end{tikzpicture}
  7169. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7170. \label{fig:R4-passes}
  7171. \end{figure}
  7172. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7173. compiling $R_4$ to x86.
  7174. \section{An Example Translation}
  7175. \label{sec:functions-example}
  7176. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7177. function in $R_4$ to x86. The figure also includes the results of the
  7178. \code{explicate-control} and \code{select-instructions} passes.
  7179. \begin{figure}[htbp]
  7180. \begin{tabular}{ll}
  7181. \begin{minipage}{0.5\textwidth}
  7182. % s3_2.rkt
  7183. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7184. (define (add [x : Integer] [y : Integer])
  7185. : Integer
  7186. (+ x y))
  7187. (add 40 2)
  7188. \end{lstlisting}
  7189. $\Downarrow$
  7190. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7191. (define (add86 [x87 : Integer]
  7192. [y88 : Integer]) : Integer
  7193. add86start:
  7194. return (+ x87 y88);
  7195. )
  7196. (define (main) : Integer ()
  7197. mainstart:
  7198. tmp89 = (fun-ref add86);
  7199. (tail-call tmp89 40 2)
  7200. )
  7201. \end{lstlisting}
  7202. \end{minipage}
  7203. &
  7204. $\Rightarrow$
  7205. \begin{minipage}{0.5\textwidth}
  7206. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7207. (define (add86) : Integer
  7208. add86start:
  7209. movq %rdi, x87
  7210. movq %rsi, y88
  7211. movq x87, %rax
  7212. addq y88, %rax
  7213. jmp add11389conclusion
  7214. )
  7215. (define (main) : Integer
  7216. mainstart:
  7217. leaq (fun-ref add86), tmp89
  7218. movq $40, %rdi
  7219. movq $2, %rsi
  7220. tail-jmp tmp89
  7221. )
  7222. \end{lstlisting}
  7223. $\Downarrow$
  7224. \end{minipage}
  7225. \end{tabular}
  7226. \begin{tabular}{ll}
  7227. \begin{minipage}{0.3\textwidth}
  7228. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7229. .globl add86
  7230. .align 16
  7231. add86:
  7232. pushq %rbp
  7233. movq %rsp, %rbp
  7234. jmp add86start
  7235. add86start:
  7236. movq %rdi, %rax
  7237. addq %rsi, %rax
  7238. jmp add86conclusion
  7239. add86conclusion:
  7240. popq %rbp
  7241. retq
  7242. \end{lstlisting}
  7243. \end{minipage}
  7244. &
  7245. \begin{minipage}{0.5\textwidth}
  7246. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7247. .globl main
  7248. .align 16
  7249. main:
  7250. pushq %rbp
  7251. movq %rsp, %rbp
  7252. movq $16384, %rdi
  7253. movq $16384, %rsi
  7254. callq initialize
  7255. movq rootstack_begin(%rip), %r15
  7256. jmp mainstart
  7257. mainstart:
  7258. leaq add86(%rip), %rcx
  7259. movq $40, %rdi
  7260. movq $2, %rsi
  7261. movq %rcx, %rax
  7262. popq %rbp
  7263. jmp *%rax
  7264. mainconclusion:
  7265. popq %rbp
  7266. retq
  7267. \end{lstlisting}
  7268. \end{minipage}
  7269. \end{tabular}
  7270. \caption{Example compilation of a simple function to x86.}
  7271. \label{fig:add-fun}
  7272. \end{figure}
  7273. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7274. \chapter{Lexically Scoped Functions}
  7275. \label{ch:lambdas}
  7276. \index{lambda}
  7277. \index{lexical scoping}
  7278. This chapter studies lexically scoped functions as they appear in
  7279. functional languages such as Racket. By lexical scoping we mean that a
  7280. function's body may refer to variables whose binding site is outside
  7281. of the function, in an enclosing scope.
  7282. %
  7283. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7284. $R_5$, which extends $R_4$ with anonymous functions using the
  7285. \key{lambda} form. The body of the \key{lambda}, refers to three
  7286. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7287. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7288. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7289. parameter of function \code{f}. The \key{lambda} is returned from the
  7290. function \code{f}. The main expression of the program includes two
  7291. calls to \code{f} with different arguments for \code{x}, first
  7292. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7293. to variables \code{g} and \code{h}. Even though these two functions
  7294. were created by the same \code{lambda}, they are really different
  7295. functions because they use different values for \code{x}. Applying
  7296. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7297. \code{15} produces \code{22}. The result of this program is \code{42}.
  7298. \begin{figure}[btp]
  7299. % s4_6.rkt
  7300. \begin{lstlisting}
  7301. (define (f [x : Integer]) : (Integer -> Integer)
  7302. (let ([y 4])
  7303. (lambda: ([z : Integer]) : Integer
  7304. (+ x (+ y z)))))
  7305. (let ([g (f 5)])
  7306. (let ([h (f 3)])
  7307. (+ (g 11) (h 15))))
  7308. \end{lstlisting}
  7309. \caption{Example of a lexically scoped function.}
  7310. \label{fig:lexical-scoping}
  7311. \end{figure}
  7312. The approach that we take for implementing lexically scoped
  7313. functions is to compile them into top-level function definitions,
  7314. translating from $R_5$ into $R_4$. However, the compiler will need to
  7315. provide special treatment for variable occurrences such as \code{x}
  7316. and \code{y} in the body of the \code{lambda} of
  7317. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7318. refer to variables defined outside of it. To identify such variable
  7319. occurrences, we review the standard notion of free variable.
  7320. \begin{definition}
  7321. A variable is \emph{free in expression} $e$ if the variable occurs
  7322. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7323. variable}
  7324. \end{definition}
  7325. For example, in the expression \code{(+ x (+ y z))} the variables
  7326. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7327. only \code{x} and \code{y} are free in the following expression
  7328. because \code{z} is bound by the \code{lambda}.
  7329. \begin{lstlisting}
  7330. (lambda: ([z : Integer]) : Integer
  7331. (+ x (+ y z)))
  7332. \end{lstlisting}
  7333. So the free variables of a \code{lambda} are the ones that will need
  7334. special treatment. We need to arrange for some way to transport, at
  7335. runtime, the values of those variables from the point where the
  7336. \code{lambda} was created to the point where the \code{lambda} is
  7337. applied. An efficient solution to the problem, due to
  7338. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7339. free variables together with the function pointer for the lambda's
  7340. code, an arrangement called a \emph{flat closure} (which we shorten to
  7341. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7342. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7343. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7344. pointers. The function pointer resides at index $0$ and the
  7345. values for the free variables will fill in the rest of the vector.
  7346. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7347. how closures work. It's a three-step dance. The program first calls
  7348. function \code{f}, which creates a closure for the \code{lambda}. The
  7349. closure is a vector whose first element is a pointer to the top-level
  7350. function that we will generate for the \code{lambda}, the second
  7351. element is the value of \code{x}, which is \code{5}, and the third
  7352. element is \code{4}, the value of \code{y}. The closure does not
  7353. contain an element for \code{z} because \code{z} is not a free
  7354. variable of the \code{lambda}. Creating the closure is step 1 of the
  7355. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7356. shown in Figure~\ref{fig:closures}.
  7357. %
  7358. The second call to \code{f} creates another closure, this time with
  7359. \code{3} in the second slot (for \code{x}). This closure is also
  7360. returned from \code{f} but bound to \code{h}, which is also shown in
  7361. Figure~\ref{fig:closures}.
  7362. \begin{figure}[tbp]
  7363. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7364. \caption{Example closure representation for the \key{lambda}'s
  7365. in Figure~\ref{fig:lexical-scoping}.}
  7366. \label{fig:closures}
  7367. \end{figure}
  7368. Continuing with the example, consider the application of \code{g} to
  7369. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7370. obtain the function pointer in the first element of the closure and
  7371. call it, passing in the closure itself and then the regular arguments,
  7372. in this case \code{11}. This technique for applying a closure is step
  7373. 2 of the dance.
  7374. %
  7375. But doesn't this \code{lambda} only take 1 argument, for parameter
  7376. \code{z}? The third and final step of the dance is generating a
  7377. top-level function for a \code{lambda}. We add an additional
  7378. parameter for the closure and we insert a \code{let} at the beginning
  7379. of the function for each free variable, to bind those variables to the
  7380. appropriate elements from the closure parameter.
  7381. %
  7382. This three-step dance is known as \emph{closure conversion}. We
  7383. discuss the details of closure conversion in
  7384. Section~\ref{sec:closure-conversion} and the code generated from the
  7385. example in Section~\ref{sec:example-lambda}. But first we define the
  7386. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7387. \section{The $R_5$ Language}
  7388. \label{sec:r5}
  7389. The concrete and abstract syntax for $R_5$, a language with anonymous
  7390. functions and lexical scoping, is defined in
  7391. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7392. the \key{lambda} form to the grammar for $R_4$, which already has
  7393. syntax for function application.
  7394. \begin{figure}[tp]
  7395. \centering
  7396. \fbox{
  7397. \begin{minipage}{0.96\textwidth}
  7398. \small
  7399. \[
  7400. \begin{array}{lcl}
  7401. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7402. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7403. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7404. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7405. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7406. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7407. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7408. \mid (\key{and}\;\Exp\;\Exp)
  7409. \mid (\key{or}\;\Exp\;\Exp)
  7410. \mid (\key{not}\;\Exp) } \\
  7411. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7412. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7413. (\key{vector-ref}\;\Exp\;\Int)} \\
  7414. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7415. \mid (\Exp \; \Exp\ldots) } \\
  7416. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7417. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7418. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7419. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7420. \end{array}
  7421. \]
  7422. \end{minipage}
  7423. }
  7424. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7425. with \key{lambda}.}
  7426. \label{fig:r5-concrete-syntax}
  7427. \end{figure}
  7428. \begin{figure}[tp]
  7429. \centering
  7430. \fbox{
  7431. \begin{minipage}{0.96\textwidth}
  7432. \small
  7433. \[
  7434. \begin{array}{lcl}
  7435. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7436. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7437. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7438. &\mid& \gray{ \BOOL{\itm{bool}}
  7439. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7440. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7441. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7442. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7443. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7444. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7445. \end{array}
  7446. \]
  7447. \end{minipage}
  7448. }
  7449. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7450. \label{fig:r5-syntax}
  7451. \end{figure}
  7452. \index{interpreter}
  7453. \label{sec:interp-R5}
  7454. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7455. $R_5$. The clause for \key{lambda} saves the current environment
  7456. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7457. the environment from the \key{lambda}, the \code{lam-env}, when
  7458. interpreting the body of the \key{lambda}. The \code{lam-env}
  7459. environment is extended with the mapping of parameters to argument
  7460. values.
  7461. \begin{figure}[tbp]
  7462. \begin{lstlisting}
  7463. UPDATE ME
  7464. \end{lstlisting}
  7465. \caption{Interpreter for $R_5$.}
  7466. \label{fig:interp-R5}
  7467. \end{figure}
  7468. \label{sec:type-check-r5}
  7469. \index{type checking}
  7470. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7471. \key{lambda} form. The body of the \key{lambda} is checked in an
  7472. environment that includes the current environment (because it is
  7473. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7474. require the body's type to match the declared return type.
  7475. \begin{figure}[tbp]
  7476. \begin{lstlisting}
  7477. (define (type-check-R5 env)
  7478. (lambda (e)
  7479. (match e
  7480. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7481. (define-values (new-body bodyT)
  7482. ((type-check-exp (append (map cons xs Ts) env)) body))
  7483. (define ty `(,@Ts -> ,rT))
  7484. (cond
  7485. [(equal? rT bodyT)
  7486. (values (HasType (Lambda params rT new-body) ty) ty)]
  7487. [else
  7488. (error "mismatch in return type" bodyT rT)])]
  7489. ...
  7490. )))
  7491. \end{lstlisting}
  7492. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7493. \label{fig:type-check-R5}
  7494. \end{figure}
  7495. \section{Closure Conversion}
  7496. \label{sec:closure-conversion}
  7497. \index{closure conversion}
  7498. The compiling of lexically-scoped functions into top-level function
  7499. definitions is accomplished in the pass \code{convert-to-closures}
  7500. that comes after \code{reveal-functions} and before
  7501. \code{limit-functions}.
  7502. As usual, we implement the pass as a recursive function over the
  7503. AST. All of the action is in the clauses for \key{lambda} and
  7504. \key{Apply}. We transform a \key{lambda} expression into an expression
  7505. that creates a closure, that is, creates a vector whose first element
  7506. is a function pointer and the rest of the elements are the free
  7507. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7508. generated to identify the function.
  7509. \begin{tabular}{lll}
  7510. \begin{minipage}{0.4\textwidth}
  7511. \begin{lstlisting}
  7512. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7513. \end{lstlisting}
  7514. \end{minipage}
  7515. &
  7516. $\Rightarrow$
  7517. &
  7518. \begin{minipage}{0.4\textwidth}
  7519. \begin{lstlisting}
  7520. (vector |\itm{name}| |\itm{fvs}| ...)
  7521. \end{lstlisting}
  7522. \end{minipage}
  7523. \end{tabular} \\
  7524. %
  7525. In addition to transforming each \key{lambda} into a \key{vector}, we
  7526. must create a top-level function definition for each \key{lambda}, as
  7527. shown below.\\
  7528. \begin{minipage}{0.8\textwidth}
  7529. \begin{lstlisting}
  7530. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7531. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7532. ...
  7533. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7534. |\itm{body'}|)...))
  7535. \end{lstlisting}
  7536. \end{minipage}\\
  7537. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7538. parameters are the normal parameters of the \key{lambda}. The types
  7539. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7540. underscore is a dummy type because it is rather difficult to give a
  7541. type to the function in the closure's type, and it does not matter.
  7542. The sequence of \key{let} forms bind the free variables to their
  7543. values obtained from the closure.
  7544. We transform function application into code that retrieves the
  7545. function pointer from the closure and then calls the function, passing
  7546. in the closure as the first argument. We bind $e'$ to a temporary
  7547. variable to avoid code duplication.
  7548. \begin{tabular}{lll}
  7549. \begin{minipage}{0.3\textwidth}
  7550. \begin{lstlisting}
  7551. (app |$e$| |\itm{es}| ...)
  7552. \end{lstlisting}
  7553. \end{minipage}
  7554. &
  7555. $\Rightarrow$
  7556. &
  7557. \begin{minipage}{0.5\textwidth}
  7558. \begin{lstlisting}
  7559. (let ([|\itm{tmp}| |$e'$|])
  7560. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7561. \end{lstlisting}
  7562. \end{minipage}
  7563. \end{tabular} \\
  7564. There is also the question of what to do with top-level function
  7565. definitions. To maintain a uniform translation of function
  7566. application, we turn function references into closures.
  7567. \begin{tabular}{lll}
  7568. \begin{minipage}{0.3\textwidth}
  7569. \begin{lstlisting}
  7570. (fun-ref |$f$|)
  7571. \end{lstlisting}
  7572. \end{minipage}
  7573. &
  7574. $\Rightarrow$
  7575. &
  7576. \begin{minipage}{0.5\textwidth}
  7577. \begin{lstlisting}
  7578. (vector (fun-ref |$f$|))
  7579. \end{lstlisting}
  7580. \end{minipage}
  7581. \end{tabular} \\
  7582. %
  7583. The top-level function definitions need to be updated as well to take
  7584. an extra closure parameter.
  7585. \section{An Example Translation}
  7586. \label{sec:example-lambda}
  7587. Figure~\ref{fig:lexical-functions-example} shows the result of
  7588. \code{reveal-functions} and then \code{convert-to-closures} for the
  7589. example program demonstrating lexical scoping that we discussed at the
  7590. beginning of this chapter.
  7591. \begin{figure}[h]
  7592. \begin{minipage}{0.8\textwidth}
  7593. % tests/s4_6.rkt
  7594. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7595. (define (f74 [x75 : Integer]) : (Integer -> Integer)
  7596. (let ([y76 4])
  7597. (lambda: ( [z77 : Integer]) : Integer
  7598. (+ x75 (+ y76 z77)))))
  7599. (define (main) : Integer
  7600. (let ([g78 ((fun-ref f74) 5)])
  7601. (let ([h79 ((fun-ref f74) 3)])
  7602. (+ (g78 11) (h79 15)))))
  7603. \end{lstlisting}
  7604. $\Downarrow$
  7605. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7606. (define (f74 [fvs82 : _] [x75 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7607. (let ([y76 4])
  7608. (vector (fun-ref lambda80) x75 y76)))
  7609. (define (lambda80 [fvs81 : (Vector _ Integer Integer)] [z77 : Integer]) : Integer
  7610. (let ([x75 (vector-ref fvs81 1)])
  7611. (let ([y76 (vector-ref fvs81 2)])
  7612. (+ x75 (+ y76 z77)))))
  7613. (define (main) : Integer
  7614. (let ([g78 (let ([app83 (vector (fun-ref f74))])
  7615. ((vector-ref app83 0) app83 5))])
  7616. (let ([h79 (let ([app84 (vector (fun-ref f74))])
  7617. ((vector-ref app84 0) app84 3))])
  7618. (+ (let ([app85 g78])
  7619. ((vector-ref app85 0) app85 11))
  7620. (let ([app86 h79])
  7621. ((vector-ref app86 0) app86 15))))))
  7622. \end{lstlisting}
  7623. \end{minipage}
  7624. \caption{Example of closure conversion.}
  7625. \label{fig:lexical-functions-example}
  7626. \end{figure}
  7627. \begin{figure}[p]
  7628. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7629. \node (R4) at (0,2) {\large $R_4$};
  7630. \node (R4-2) at (3,2) {\large $R_4$};
  7631. %\node (R4-3) at (6,2) {\large $R_4$};
  7632. \node (F1-1) at (12,0) {\large $F_1$};
  7633. \node (F1-2) at (9,0) {\large $F_1$};
  7634. \node (F1-3) at (6,0) {\large $F_1$};
  7635. \node (F1-4) at (3,0) {\large $F_1$};
  7636. \node (F1-5) at (0,0) {\large $F_1$};
  7637. \node (C3-2) at (3,-2) {\large $C_3$};
  7638. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7639. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7640. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7641. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7642. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7643. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7644. %% \path[->,bend left=15] (R4) edge [above] node
  7645. %% {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7646. \path[->,bend left=15] (R4) edge [above] node
  7647. {\ttfamily\footnotesize uniquify} (R4-2);
  7648. \path[->,bend left=15] (R4-2) edge [right] node
  7649. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7650. \path[->,bend left=15] (F1-1) edge [below] node
  7651. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7652. \path[->,bend right=15] (F1-2) edge [above] node
  7653. {\ttfamily\footnotesize limit-functions} (F1-3);
  7654. \path[->,bend right=15] (F1-3) edge [above] node
  7655. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7656. \path[->,bend right=15] (F1-4) edge [above] node
  7657. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7658. \path[->] (F1-5) edge [left] node
  7659. {\ttfamily\footnotesize explicate-control} (C3-2);
  7660. \path[->,bend right=15] (C3-2) edge [left] node
  7661. {\ttfamily\footnotesize select-instr.} (x86-2);
  7662. \path[->,bend left=15] (x86-2) edge [left] node
  7663. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7664. \path[->,bend right=15] (x86-2-1) edge [below] node
  7665. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7666. \path[->,bend right=15] (x86-2-2) edge [left] node
  7667. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7668. \path[->,bend left=15] (x86-3) edge [above] node
  7669. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7670. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7671. \end{tikzpicture}
  7672. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7673. functions.}
  7674. \label{fig:R5-passes}
  7675. \end{figure}
  7676. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7677. for the compilation of $R_5$.
  7678. \begin{exercise}\normalfont
  7679. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7680. Create 5 new programs that use \key{lambda} functions and make use of
  7681. lexical scoping. Test your compiler on these new programs and all of
  7682. your previously created test programs.
  7683. \end{exercise}
  7684. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7685. \chapter{Dynamic Typing}
  7686. \label{ch:type-dynamic}
  7687. \index{dynamic typing}
  7688. In this chapter we discuss the compilation $R_7$, a dynamically typed
  7689. language and a subset of the Racket language. Recall that in the
  7690. previous chapters we have compiled subsets of the \emph{Typed} Racket
  7691. language. In dynamically typed languages, each evaluation of an
  7692. expression may produce a value of a different type. Consider the
  7693. following example with a conditional expression that may return a
  7694. Boolean or an integer depending on the input to the program.
  7695. \begin{lstlisting}
  7696. (not (if (eq? (read) 1) #f 0))
  7697. \end{lstlisting}
  7698. Languages that allow expressions to produce different kinds of values
  7699. are called \emph{polymorphic}, a word composed of the Greek roots
  7700. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  7701. are several kinds of polymorphism in programming languages, such as
  7702. subtype polymorphism and parametric
  7703. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  7704. study in this chapter does not have a special name but it is the kind
  7705. that arises in dynamically typed languages.
  7706. Another characteristic of dynamically typed languages is that
  7707. primitive operations, such as \code{not}, are often defined to operate
  7708. on many different types of values. In fact, in Racket, the \code{not}
  7709. operator produces a result for any kind of value: given \code{\#f} it
  7710. returns \code{\#t} and given anything else it returns \code{\#f}.
  7711. Furthermore, even when primitive operations restrict their inputs to
  7712. values of a certain type, this restriction is enforced at runtime
  7713. instead of during compilation. For example, the following vector
  7714. reference results in a run-time contract violation because the index
  7715. must be in integer, not a Boolean such as \code{\#t}.
  7716. \begin{lstlisting}
  7717. (vector-ref (vector 42) #t)
  7718. \end{lstlisting}
  7719. \begin{figure}[tp]
  7720. \centering
  7721. \fbox{
  7722. \begin{minipage}{0.97\textwidth}
  7723. \[
  7724. \begin{array}{rcl}
  7725. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7726. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7727. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  7728. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  7729. &\mid& \key{\#t} \mid \key{\#f}
  7730. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  7731. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  7732. \mid \CUNIOP{\key{not}}{\Exp} \\
  7733. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  7734. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  7735. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  7736. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  7737. &\mid& \LP\Exp \; \Exp\ldots\RP
  7738. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  7739. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7740. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7741. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  7742. R_7 &::=& \Def\ldots\; \Exp
  7743. \end{array}
  7744. \]
  7745. \end{minipage}
  7746. }
  7747. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7748. \label{fig:r7-concrete-syntax}
  7749. \end{figure}
  7750. \begin{figure}[tp]
  7751. \centering
  7752. \fbox{
  7753. \begin{minipage}{0.96\textwidth}
  7754. \small
  7755. \[
  7756. \begin{array}{lcl}
  7757. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  7758. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  7759. &\mid& \BOOL{\itm{bool}}
  7760. \mid \IF{\Exp}{\Exp}{\Exp} \\
  7761. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  7762. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  7763. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  7764. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  7765. \end{array}
  7766. \]
  7767. \end{minipage}
  7768. }
  7769. \caption{The abstract syntax of $R_7$.}
  7770. \label{fig:r7-syntax}
  7771. \end{figure}
  7772. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  7773. defined in Figures~\ref{fig:r7-concrete-syntax} and
  7774. \ref{fig:r7-syntax}.
  7775. %
  7776. There is no type checker for $R_7$ because it is not a statically
  7777. typed language (it's dynamically typed!).
  7778. %
  7779. The definitional interpreter for $R_7$ is presented in
  7780. Figure~\ref{fig:interp-R7}.
  7781. \begin{figure}[tbp]
  7782. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7783. (define (interp-R7-exp env)
  7784. (lambda (ast)
  7785. (define recur (interp-R7-exp env))
  7786. (match ast
  7787. [(Var x) (lookup x env)]
  7788. [(Int n) `(tagged ,n Integer)]
  7789. [(Bool b) `(tagged ,b Boolean)]
  7790. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  7791. [(Lambda xs rt body)
  7792. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  7793. [(Prim 'vector es)
  7794. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  7795. (Vector ,@(for/list ([e es]) 'Any)))]
  7796. [(Prim 'vector-set! (list e1 n e2))
  7797. (define vec (value-of-any (recur e1)))
  7798. (define i (value-of-any (recur n)))
  7799. (vector-set! vec i (recur e2))
  7800. `(tagged ,(void) Void)]
  7801. [(Prim 'vector-ref (list e1 n))
  7802. (define vec (value-of-any (recur e1)))
  7803. (define i (value-of-any (recur n)))
  7804. (vector-ref vec i)]
  7805. [(Let x e body)
  7806. (define v (recur e))
  7807. ((interp-R7-exp (cons (cons x v) env)) body)]
  7808. [(Prim 'and (list e1 e2))
  7809. (recur (If e1 e2 (Bool #f)))]
  7810. [(Prim 'or (list e1 e2))
  7811. (define v1 (recur e1))
  7812. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  7813. [(Prim 'eq? (list l r))
  7814. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  7815. [(If q t f)
  7816. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  7817. [(Prim op es)
  7818. (tag-value
  7819. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  7820. [(Apply f es)
  7821. (define new-args (map recur es))
  7822. (let ([f-val (value-of-any (recur f))])
  7823. (match f-val
  7824. [`(lambda (,xs ...) ,body ,lam-env)
  7825. (define new-env (append (map cons xs new-args) lam-env))
  7826. ((interp-R7-exp new-env) body)]
  7827. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  7828. )))
  7829. \end{lstlisting}
  7830. \caption{Interpreter for the $R_7$ language.}
  7831. \label{fig:interp-R7}
  7832. \end{figure}
  7833. Let us consider how we might compile $R_7$ to x86, thinking about the
  7834. first example above. Our bit-level representation of the Boolean
  7835. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7836. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7837. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7838. general, cannot be determined at compile time, but depends on the
  7839. runtime type of its input, as in the example above that depends on the
  7840. result of \code{(read)}.
  7841. The way around this problem is to include information about a value's
  7842. runtime type in the value itself, so that this information can be
  7843. inspected by operators such as \code{not}. In particular, we
  7844. steal the 3 right-most bits from our 64-bit values to encode the
  7845. runtime type. We use $001$ to identify integers, $100$ for
  7846. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7847. void value. We refer to these 3 bits as the \emph{tag} and we
  7848. define the following auxiliary function.
  7849. \begin{align*}
  7850. \itm{tagof}(\key{Integer}) &= 001 \\
  7851. \itm{tagof}(\key{Boolean}) &= 100 \\
  7852. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7853. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7854. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7855. \itm{tagof}(\key{Void}) &= 101
  7856. \end{align*}
  7857. (We say more about the new \key{Vectorof} type shortly.)
  7858. This stealing of 3 bits comes at some
  7859. price: our integers are reduced to ranging from $-2^{60}$ to
  7860. $2^{60}$. The stealing does not adversely affect vectors and
  7861. procedures because those values are addresses, and our addresses are
  7862. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7863. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7864. bits with the tag and we can simply zero-out the tag to recover the
  7865. original address.
  7866. In some sense, these tagged values are a new kind of value. Indeed,
  7867. we can extend our \emph{typed} language with tagged values by adding a
  7868. new type to classify them, called \key{Any}, and with operations for
  7869. creating and using tagged values, yielding the $R_6$ language that we
  7870. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7871. fundamental support for polymorphism and runtime types that we need to
  7872. support dynamic typing.
  7873. There is an interesting interaction between tagged values and garbage
  7874. collection. A variable of type \code{Any} might refer to a vector and
  7875. therefore it might be a root that needs to be inspected and copied
  7876. during garbage collection. Thus, we need to treat variables of type
  7877. \code{Any} in a similar way to variables of type \code{Vector} for
  7878. purposes of register allocation, which we discuss in
  7879. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7880. variable of type \code{Any} is spilled, it must be spilled to the root
  7881. stack. But this means that the garbage collector needs to be able to
  7882. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7883. value that points to a tuple, and (3) a tagged value that is not a
  7884. tuple. We enable this differentiation by choosing not to use the tag
  7885. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  7886. identifying plain old pointers to tuples. That way, if one of the
  7887. first three bits is set, then we have a tagged value and inspecting
  7888. the tag can differentiation between vectors ($010$) and the other
  7889. kinds of values.
  7890. We implement our untyped language $R_7$ by compiling it to $R_6$
  7891. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7892. extend our compiler to handle the new features of $R_6$
  7893. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7894. \ref{sec:register-allocation-r6}).
  7895. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7896. \label{sec:r6-lang}
  7897. \begin{figure}[tp]
  7898. \centering
  7899. \fbox{
  7900. \begin{minipage}{0.97\textwidth}\small
  7901. \[
  7902. \begin{array}{lcl}
  7903. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7904. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  7905. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  7906. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  7907. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  7908. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7909. \Exp &::=& \ldots
  7910. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  7911. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7912. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7913. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7914. R_6 &::=& \gray{\Def\ldots \; \Exp}
  7915. \end{array}
  7916. \]
  7917. \end{minipage}
  7918. }
  7919. \caption{Concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7920. with \key{Any}.}
  7921. \label{fig:r6-concrete-syntax}
  7922. \end{figure}
  7923. \begin{figure}[tp]
  7924. \centering
  7925. \fbox{
  7926. \begin{minipage}{0.96\textwidth}
  7927. \small
  7928. \[
  7929. \begin{array}{lcl}
  7930. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  7931. \mid \code{procedure?} \mid \code{void?} \\
  7932. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7933. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7934. &\mid& \gray{ \BOOL{\itm{bool}}
  7935. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7936. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7937. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7938. &\mid& \gray{ \LAMBDA{\LP[\Var\code{:}\Type]\ldots\RP}{\Type}{\Exp} }\\
  7939. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  7940. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7941. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7942. \end{array}
  7943. \]
  7944. \end{minipage}
  7945. }
  7946. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  7947. \label{fig:r6-syntax}
  7948. \end{figure}
  7949. The concrete and abstract syntax of $R_6$ is defined in
  7950. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  7951. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  7952. expression $e$ of type $T$ into a tagged value. The
  7953. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  7954. expression $e$ into a value of type $T$ or else halts the program if
  7955. the type tag is not equivalent to $T$. We treat
  7956. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  7957. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  7958. %
  7959. Note that in both \key{inject} and \key{project}, the type $T$ is
  7960. restricted to the flat types $\FType$, which simplifies the
  7961. implementation and corresponds with what is needed for compiling
  7962. untyped Racket.
  7963. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  7964. expression $e$ to produce a tagged value; they return \key{\#t} if the
  7965. tag corresponds to the predicate and they return \key{\#f} otherwise.
  7966. The type checker for $R_6$ is shown in Figures~\ref{fig:type-check-R6-part-1}
  7967. and \ref{fig:type-check-R6-part-2}.
  7968. The interpreter for $R_6$ is in Figure~\ref{fig:interp-R6}.
  7969. \begin{figure}[btp]
  7970. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7971. (define (operator-types)
  7972. '(...
  7973. (integer? . ((Any) . Boolean))
  7974. (vector? . ((Any) . Boolean))
  7975. (procedure? . ((Any) . Boolean))
  7976. (void? . ((Any) . Boolean))
  7977. ))
  7978. (define (type-check-exp env)
  7979. (lambda (e)
  7980. (define recur (type-check-exp env))
  7981. (match e
  7982. ...
  7983. [(Inject e ty)
  7984. (unless (flat-ty? ty)
  7985. (error 'type-check-exp
  7986. "may only inject a value of flat type, not ~a" ty))
  7987. (define-values (new-e e-ty) (recur e))
  7988. (cond
  7989. [(type-equal? e-ty ty)
  7990. (values (Inject new-e ty) 'Any)]
  7991. [else
  7992. (error 'type-check-exp
  7993. "injected expression does not have expected type"
  7994. e e-ty ty)])]
  7995. [(Project e ty)
  7996. (unless (flat-ty? ty)
  7997. (error 'type-check-exp
  7998. "may only project to a flat type, not ~a" ty))
  7999. (define-values (new-e e-ty) (recur e))
  8000. (cond
  8001. [(type-equal? e-ty 'Any)
  8002. (values (Project new-e ty) ty)]
  8003. [else
  8004. (error 'type-check-exp
  8005. "project expression does not have type Any" e)])]
  8006. [(Prim pred (list e))
  8007. #:when (set-member? type-predicates pred)
  8008. (define-values (new-e e-ty) (recur e))
  8009. (cond
  8010. [(type-equal? e-ty 'Any)
  8011. (values (Prim pred (list new-e)) 'Boolean)]
  8012. [else
  8013. (error 'type-check-exp
  8014. "type predicate expected argument of type Any, not ~a" e-ty)])]
  8015. ...
  8016. \end{lstlisting}
  8017. \caption{Type checker for the $R_6$ language, part 1.}
  8018. \label{fig:type-check-R6-part-1}
  8019. \end{figure}
  8020. \begin{figure}[btp]
  8021. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]U
  8022. UNDER CONSTRUCTION (vectors)
  8023. [else
  8024. (error 'type-check-exp "R6/unmatched ~a" e)]
  8025. )))
  8026. \end{lstlisting}
  8027. \caption{Type checker for the $R_6$ language, part 2.}
  8028. \label{fig:type-check-R6-part-2}
  8029. \end{figure}
  8030. % to do: add rules for vector-ref, etc. for Vectorof
  8031. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  8032. \begin{figure}[btp]
  8033. \begin{lstlisting}
  8034. (define (interp-op op)
  8035. (match op
  8036. ...
  8037. ['boolean? (lambda (v)
  8038. (match v
  8039. [`(tagged ,v1 ,tg)
  8040. (equal? tg (any-tag 'Boolean))]
  8041. [else #f]))]
  8042. ['integer? (lambda (v)
  8043. (match v
  8044. [`(tagged ,v1 ,tg)
  8045. (equal? tg (any-tag 'Integer))]
  8046. [else #f]))]
  8047. ['vector? (lambda (v)
  8048. (match v
  8049. [`(tagged ,v1 ,tg)
  8050. (equal? tg (any-tag `(Vector Any)))]
  8051. [else #f]))]
  8052. ['procedure? (lambda (v)
  8053. (match v
  8054. [`(tagged ,v1 ,tg)
  8055. (equal? tg (any-tag `(Any -> Any)))]
  8056. [else #f]))]
  8057. ...
  8058. ))
  8059. (define (interp-exp env)
  8060. (lambda (e)
  8061. (define recur (interp-exp env))
  8062. (let ([ret
  8063. (match e
  8064. ...
  8065. [(Inject e ty)
  8066. (apply-inject ((interp-exp env) e) (any-tag ty))]
  8067. [(Project e ty2)
  8068. (define v (recur e))
  8069. (apply-project v ty2)]
  8070. [(Exit)
  8071. (error 'interp-exp "exiting")]
  8072. [else (error 'interp-exp "unrecognized expression ~a" e)]
  8073. )])
  8074. (verbose "R6/interp-exp ==>" ret)
  8075. ret)))
  8076. \end{lstlisting}
  8077. \caption{Interpreter for $R_6$.}
  8078. \label{fig:interp-R6}
  8079. \end{figure}
  8080. %\clearpage
  8081. \section{Shrinking $R_6$}
  8082. \label{sec:shrink-r6}
  8083. In the \code{shrink} pass we recommend compiling \code{Project} into
  8084. an explicit \code{If} expression that uses two new forms,
  8085. \code{ValueOf} and \code{Exit}, and a new primitive operation,
  8086. \code{tag-of-any}. The \code{tag-of-any} operation retrieves the type
  8087. tag from a tagged value of type \code{Any}. The \code{ValueOf} form
  8088. retrieves the underlying value from a tagged value. The
  8089. \code{ValueOf} form includes the type for the underlying value which
  8090. is used by the type checker. Finally, the \code{Exit} form ends the
  8091. execution of the program.
  8092. %
  8093. If the target type of the projection is \code{Boolean} or
  8094. \code{Integer}, then \code{Project} can be translated as follows.
  8095. %(We have omitted the \code{has-type} AST nodes to make this
  8096. %output more readable.)
  8097. \begin{center}
  8098. \begin{minipage}{1.0\textwidth}
  8099. \begin{lstlisting}
  8100. (Project |$e$| |$\FType$|)
  8101. |$\Rightarrow$|
  8102. (Let |$\itm{tmp}$| |$e'$|
  8103. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8104. (Int |$\itm{tagof}(\FType)$|)))
  8105. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8106. (Exit)))
  8107. \end{lstlisting}
  8108. \end{minipage}
  8109. \end{center}
  8110. If the target type of the projection is a vector or function type,
  8111. then there is a bit more work to do. For vectors, check that the
  8112. length of the vector (use the \code{vector-length} primitive) matches
  8113. the length of the vector type. For functions, check that its arity
  8114. (\code{procedure-arity}) matches the number of parameters in the
  8115. function type.
  8116. Regarding \code{Inject}, we recommend compiling it to a slightly
  8117. lower-level primitive operation named \code{make-any}. This operation
  8118. takes a tag instead of a type. \\
  8119. \begin{center}
  8120. \begin{minipage}{1.0\textwidth}
  8121. \begin{lstlisting}
  8122. (Inject |$e$| |$\FType$|)
  8123. |$\Rightarrow$|
  8124. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8125. \end{lstlisting}
  8126. \end{minipage}
  8127. \end{center}
  8128. We recommend translating the type predicates (\code{boolean?}, etc.)
  8129. into uses of \code{tag-of-any} and \code{eq?}.
  8130. \section{Closure Conversion for $R_6$}
  8131. \label{sec:closure-conversion-R6}
  8132. \section{Instruction Selection for $R_6$}
  8133. \label{sec:select-r6}
  8134. \paragraph{Inject}
  8135. We recommend compiling an \key{inject} as follows if the type is
  8136. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  8137. destination to the left by the number of bits specified its source
  8138. argument (in this case $3$, the length of the tag) and it preserves
  8139. the sign of the integer. We use the \key{orq} instruction to combine
  8140. the tag and the value to form the tagged value. \\
  8141. \begin{tabular}{lll}
  8142. \begin{minipage}{0.4\textwidth}
  8143. \begin{lstlisting}
  8144. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8145. \end{lstlisting}
  8146. \end{minipage}
  8147. &
  8148. $\Rightarrow$
  8149. &
  8150. \begin{minipage}{0.5\textwidth}
  8151. \begin{lstlisting}
  8152. (movq |$e'$| |\itm{lhs}'|)
  8153. (salq (int 3) |\itm{lhs}'|)
  8154. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8155. \end{lstlisting}
  8156. \end{minipage}
  8157. \end{tabular} \\
  8158. The instruction selection for vectors and procedures is different
  8159. because their is no need to shift them to the left. The rightmost 3
  8160. bits are already zeros as described above. So we just combine the
  8161. value and the tag using \key{orq}. \\
  8162. \begin{tabular}{lll}
  8163. \begin{minipage}{0.4\textwidth}
  8164. \begin{lstlisting}
  8165. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8166. \end{lstlisting}
  8167. \end{minipage}
  8168. &
  8169. $\Rightarrow$
  8170. &
  8171. \begin{minipage}{0.5\textwidth}
  8172. \begin{lstlisting}
  8173. (movq |$e'$| |\itm{lhs}'|)
  8174. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8175. \end{lstlisting}
  8176. \end{minipage}
  8177. \end{tabular}
  8178. \paragraph{Tag of Any}
  8179. Recall that the \code{tag-of-any} operation extracts the type tag from
  8180. a value of type \code{Any}. The type tag is the bottom three bits, so
  8181. we obtain the tag by taking the bitwise-and of the value with $111$
  8182. ($7$ in decimal).
  8183. \begin{tabular}{lll}
  8184. \begin{minipage}{0.4\textwidth}
  8185. \begin{lstlisting}
  8186. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8187. \end{lstlisting}
  8188. \end{minipage}
  8189. &
  8190. $\Rightarrow$
  8191. &
  8192. \begin{minipage}{0.5\textwidth}
  8193. \begin{lstlisting}
  8194. (movq |$e'$| |\itm{lhs}'|)
  8195. (andq (int 7) |\itm{lhs}'|)
  8196. \end{lstlisting}
  8197. \end{minipage}
  8198. \end{tabular}
  8199. \paragraph{Value of Any}
  8200. Like \key{inject}, the instructions for \key{value-of-any} are
  8201. different depending on whether the type $T$ is a pointer (vector or
  8202. procedure) or not (Integer or Boolean). The following shows the
  8203. instruction selection for Integer and Boolean. We produce an untagged
  8204. value by shifting it to the right by 3 bits.
  8205. %
  8206. \\
  8207. \begin{tabular}{lll}
  8208. \begin{minipage}{0.4\textwidth}
  8209. \begin{lstlisting}
  8210. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8211. \end{lstlisting}
  8212. \end{minipage}
  8213. &
  8214. $\Rightarrow$
  8215. &
  8216. \begin{minipage}{0.5\textwidth}
  8217. \begin{lstlisting}
  8218. (movq |$e'$| |\itm{lhs}'|)
  8219. (sarq (int 3) |\itm{lhs}'|)
  8220. \end{lstlisting}
  8221. \end{minipage}
  8222. \end{tabular} \\
  8223. %
  8224. In the case for vectors and procedures, there is no need to
  8225. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8226. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8227. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8228. \code{movq} into the destination $\itm{lhs}$. We then generate
  8229. \code{andq} with the tagged value to get the desired result. \\
  8230. %
  8231. \begin{tabular}{lll}
  8232. \begin{minipage}{0.4\textwidth}
  8233. \begin{lstlisting}
  8234. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8235. \end{lstlisting}
  8236. \end{minipage}
  8237. &
  8238. $\Rightarrow$
  8239. &
  8240. \begin{minipage}{0.5\textwidth}
  8241. \begin{lstlisting}
  8242. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8243. (andq |$e'$| |\itm{lhs}'|)
  8244. \end{lstlisting}
  8245. \end{minipage}
  8246. \end{tabular}
  8247. %% \paragraph{Type Predicates} We leave it to the reader to
  8248. %% devise a sequence of instructions to implement the type predicates
  8249. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8250. \section{Register Allocation for $R_6$}
  8251. \label{sec:register-allocation-r6}
  8252. \index{register allocation}
  8253. As mentioned above, a variable of type \code{Any} might refer to a
  8254. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8255. of type \code{Any} in the same way that it treats variables of type
  8256. \code{Vector} for purposes of garbage collection. In particular,
  8257. \begin{itemize}
  8258. \item If a variable of type \code{Any} is live during a function call,
  8259. then it must be spilled. One way to accomplish this is to augment
  8260. the pass \code{build-interference} to mark all variables that are
  8261. live after a \code{callq} as interfering with all the registers.
  8262. \item If a variable of type \code{Any} is spilled, it must be spilled
  8263. to the root stack instead of the normal procedure call stack.
  8264. \end{itemize}
  8265. \begin{exercise}\normalfont
  8266. Expand your compiler to handle $R_6$ as discussed in the last few
  8267. sections. Create 5 new programs that use the \code{Any} type and the
  8268. new operations (\code{inject}, \code{project}, \code{boolean?},
  8269. etc.). Test your compiler on these new programs and all of your
  8270. previously created test programs.
  8271. \end{exercise}
  8272. \section{Compiling $R_7$ to $R_6$}
  8273. \label{sec:compile-r7}
  8274. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8275. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8276. given a subexpression $e$ of $R_7$, the pass will produce an
  8277. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8278. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8279. the Boolean \code{\#t}, which must be injected to produce an
  8280. expression of type \key{Any}.
  8281. %
  8282. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8283. addition, is representative of compilation for many operations: the
  8284. arguments have type \key{Any} and must be projected to \key{Integer}
  8285. before the addition can be performed.
  8286. The compilation of \key{lambda} (third row of
  8287. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8288. produce type annotations: we simply use \key{Any}.
  8289. %
  8290. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8291. has to account for some differences in behavior between $R_7$ and
  8292. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8293. kind of values can be used in various places. For example, the
  8294. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8295. the arguments need not be of the same type (but in that case, the
  8296. result will be \code{\#f}).
  8297. \begin{figure}[btp]
  8298. \centering
  8299. \begin{tabular}{|lll|} \hline
  8300. \begin{minipage}{0.25\textwidth}
  8301. \begin{lstlisting}
  8302. #t
  8303. \end{lstlisting}
  8304. \end{minipage}
  8305. &
  8306. $\Rightarrow$
  8307. &
  8308. \begin{minipage}{0.6\textwidth}
  8309. \begin{lstlisting}
  8310. (inject #t Boolean)
  8311. \end{lstlisting}
  8312. \end{minipage}
  8313. \\[2ex]\hline
  8314. \begin{minipage}{0.25\textwidth}
  8315. \begin{lstlisting}
  8316. (+ |$e_1$| |$e_2$|)
  8317. \end{lstlisting}
  8318. \end{minipage}
  8319. &
  8320. $\Rightarrow$
  8321. &
  8322. \begin{minipage}{0.6\textwidth}
  8323. \begin{lstlisting}
  8324. (inject
  8325. (+ (project |$e'_1$| Integer)
  8326. (project |$e'_2$| Integer))
  8327. Integer)
  8328. \end{lstlisting}
  8329. \end{minipage}
  8330. \\[2ex]\hline
  8331. \begin{minipage}{0.25\textwidth}
  8332. \begin{lstlisting}
  8333. (lambda (|$x_1 \ldots$|) |$e$|)
  8334. \end{lstlisting}
  8335. \end{minipage}
  8336. &
  8337. $\Rightarrow$
  8338. &
  8339. \begin{minipage}{0.6\textwidth}
  8340. \begin{lstlisting}
  8341. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8342. (Any|$\ldots$|Any -> Any))
  8343. \end{lstlisting}
  8344. \end{minipage}
  8345. \\[2ex]\hline
  8346. \begin{minipage}{0.25\textwidth}
  8347. \begin{lstlisting}
  8348. (app |$e_0$| |$e_1 \ldots e_n$|)
  8349. \end{lstlisting}
  8350. \end{minipage}
  8351. &
  8352. $\Rightarrow$
  8353. &
  8354. \begin{minipage}{0.6\textwidth}
  8355. \begin{lstlisting}
  8356. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8357. |$e'_1 \ldots e'_n$|)
  8358. \end{lstlisting}
  8359. \end{minipage}
  8360. \\[2ex]\hline
  8361. \begin{minipage}{0.25\textwidth}
  8362. \begin{lstlisting}
  8363. (vector-ref |$e_1$| |$e_2$|)
  8364. \end{lstlisting}
  8365. \end{minipage}
  8366. &
  8367. $\Rightarrow$
  8368. &
  8369. \begin{minipage}{0.6\textwidth}
  8370. \begin{lstlisting}
  8371. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8372. (let ([tmp2 (project |$e'_2$| Integer)])
  8373. (vector-ref tmp1 tmp2)))
  8374. \end{lstlisting}
  8375. \end{minipage}
  8376. \\[2ex]\hline
  8377. \begin{minipage}{0.25\textwidth}
  8378. \begin{lstlisting}
  8379. (if |$e_1$| |$e_2$| |$e_3$|)
  8380. \end{lstlisting}
  8381. \end{minipage}
  8382. &
  8383. $\Rightarrow$
  8384. &
  8385. \begin{minipage}{0.6\textwidth}
  8386. \begin{lstlisting}
  8387. (if (eq? |$e'_1$| (inject #f Boolean))
  8388. |$e'_3$|
  8389. |$e'_2$|)
  8390. \end{lstlisting}
  8391. \end{minipage}
  8392. \\[2ex]\hline
  8393. \begin{minipage}{0.25\textwidth}
  8394. \begin{lstlisting}
  8395. (eq? |$e_1$| |$e_2$|)
  8396. \end{lstlisting}
  8397. \end{minipage}
  8398. &
  8399. $\Rightarrow$
  8400. &
  8401. \begin{minipage}{0.6\textwidth}
  8402. \begin{lstlisting}
  8403. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8404. \end{lstlisting}
  8405. \end{minipage}
  8406. \\[2ex]\hline
  8407. \end{tabular}
  8408. \caption{Compiling $R_7$ to $R_6$.}
  8409. \label{fig:compile-r7-r6}
  8410. \end{figure}
  8411. \begin{exercise}\normalfont
  8412. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8413. Create tests for $R_7$ by adapting all of your previous test programs
  8414. by removing type annotations. Add 5 more tests programs that
  8415. specifically rely on the language being dynamically typed. That is,
  8416. they should not be legal programs in a statically typed language, but
  8417. nevertheless, they should be valid $R_7$ programs that run to
  8418. completion without error.
  8419. \end{exercise}
  8420. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8421. \chapter{Gradual Typing}
  8422. \label{ch:gradual-typing}
  8423. \index{gradual typing}
  8424. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8425. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8426. \chapter{Parametric Polymorphism}
  8427. \label{ch:parametric-polymorphism}
  8428. \index{parametric polymorphism}
  8429. \index{generics}
  8430. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8431. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8432. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8433. \chapter{High-level Optimization}
  8434. \label{ch:high-level-optimization}
  8435. This chapter will present a procedure inlining pass based on the
  8436. algorithm of \citet{Waddell:1997fk}.
  8437. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8438. \chapter{Appendix}
  8439. \section{Interpreters}
  8440. \label{appendix:interp}
  8441. \index{interpreter}
  8442. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8443. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8444. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8445. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8446. the rest of the intermediate languages, including pseudo-x86 and x86
  8447. are in the \key{interp.rkt} file.
  8448. \section{Utility Functions}
  8449. \label{appendix:utilities}
  8450. The utility functions described here are in the \key{utilities.rkt}
  8451. file.
  8452. \paragraph{\code{interp-tests}}
  8453. The \key{interp-tests} function runs the compiler passes and the
  8454. interpreters on each of the specified tests to check whether each pass
  8455. is correct. The \key{interp-tests} function has the following
  8456. parameters:
  8457. \begin{description}
  8458. \item[name (a string)] a name to identify the compiler,
  8459. \item[typechecker] a function of exactly one argument that either
  8460. raises an error using the \code{error} function when it encounters a
  8461. type error, or returns \code{\#f} when it encounters a type
  8462. error. If there is no type error, the type checker returns the
  8463. program.
  8464. \item[passes] a list with one entry per pass. An entry is a list with
  8465. four things:
  8466. \begin{enumerate}
  8467. \item a string giving the name of the pass,
  8468. \item the function that implements the pass (a translator from AST
  8469. to AST),
  8470. \item a function that implements the interpreter (a function from
  8471. AST to result value) for the output language,
  8472. \item and a type checker for the output language. Type checkers for
  8473. the $R$ and $C$ languages are provided in the support code. For
  8474. example, the type checkers for $R_1$ and $C_0$ are in
  8475. \code{type-check-R1.rkt}. The type checker entry is optional. The
  8476. support code does not provide type checkers for the x86 languages.
  8477. \end{enumerate}
  8478. \item[source-interp] an interpreter for the source language. The
  8479. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8480. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8481. \item[tests] a list of test numbers that specifies which tests to
  8482. run. (see below)
  8483. \end{description}
  8484. %
  8485. The \key{interp-tests} function assumes that the subdirectory
  8486. \key{tests} has a collection of Racket programs whose names all start
  8487. with the family name, followed by an underscore and then the test
  8488. number, ending with the file extension \key{.rkt}. Also, for each test
  8489. program that calls \code{read} one or more times, there is a file with
  8490. the same name except that the file extension is \key{.in} that
  8491. provides the input for the Racket program. If the test program is
  8492. expected to fail type checking, then there should be an empty file of
  8493. the same name but with extension \key{.tyerr}.
  8494. \paragraph{\code{compiler-tests}}
  8495. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8496. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8497. machine code and checks that the output is $42$. The parameters to the
  8498. \code{compiler-tests} function are similar to those of the
  8499. \code{interp-tests} function, and consist of
  8500. \begin{itemize}
  8501. \item a compiler name (a string),
  8502. \item a type checker,
  8503. \item description of the passes,
  8504. \item name of a test-family, and
  8505. \item a list of test numbers.
  8506. \end{itemize}
  8507. \paragraph{\code{compile-file}}
  8508. takes a description of the compiler passes (see the comment for
  8509. \key{interp-tests}) and returns a function that, given a program file
  8510. name (a string ending in \key{.rkt}), applies all of the passes and
  8511. writes the output to a file whose name is the same as the program file
  8512. name but with \key{.rkt} replaced with \key{.s}.
  8513. \paragraph{\code{read-program}}
  8514. takes a file path and parses that file (it must be a Racket program)
  8515. into an abstract syntax tree.
  8516. \paragraph{\code{parse-program}}
  8517. takes an S-expression representation of an abstract syntax tree and converts it into
  8518. the struct-based representation.
  8519. \paragraph{\code{assert}}
  8520. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8521. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8522. \paragraph{\code{lookup}}
  8523. % remove discussion of lookup? -Jeremy
  8524. takes a key and an alist, and returns the first value that is
  8525. associated with the given key, if there is one. If not, an error is
  8526. triggered. The alist may contain both immutable pairs (built with
  8527. \key{cons}) and mutable pairs (built with \key{mcons}).
  8528. %The \key{map2} function ...
  8529. \section{x86 Instruction Set Quick-Reference}
  8530. \label{sec:x86-quick-reference}
  8531. \index{x86}
  8532. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8533. do. We write $A \to B$ to mean that the value of $A$ is written into
  8534. location $B$. Address offsets are given in bytes. The instruction
  8535. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8536. registers (such as \code{\%rax}), or memory references (such as
  8537. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8538. reference per instruction. Other operands must be immediates or
  8539. registers.
  8540. \begin{table}[tbp]
  8541. \centering
  8542. \begin{tabular}{l|l}
  8543. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8544. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8545. \texttt{negq} $A$ & $- A \to A$ \\
  8546. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8547. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8548. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8549. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8550. \texttt{retq} & Pops the return address and jumps to it \\
  8551. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8552. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8553. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8554. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8555. be an immediate) \\
  8556. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8557. matches the condition code of the instruction, otherwise go to the
  8558. next instructions. The condition codes are \key{e} for ``equal'',
  8559. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8560. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8561. \texttt{jl} $L$ & \\
  8562. \texttt{jle} $L$ & \\
  8563. \texttt{jg} $L$ & \\
  8564. \texttt{jge} $L$ & \\
  8565. \texttt{jmp} $L$ & Jump to label $L$ \\
  8566. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8567. \texttt{movzbq} $A$, $B$ &
  8568. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8569. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8570. and the extra bytes of $B$ are set to zero.} \\
  8571. & \\
  8572. & \\
  8573. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8574. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8575. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8576. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8577. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8578. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8579. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8580. description of the condition codes. $A$ must be a single byte register
  8581. (e.g., \texttt{al} or \texttt{cl}).} \\
  8582. \texttt{setl} $A$ & \\
  8583. \texttt{setle} $A$ & \\
  8584. \texttt{setg} $A$ & \\
  8585. \texttt{setge} $A$ &
  8586. \end{tabular}
  8587. \vspace{5pt}
  8588. \caption{Quick-reference for the x86 instructions used in this book.}
  8589. \label{tab:x86-instr}
  8590. \end{table}
  8591. \cleardoublepage
  8592. \addcontentsline{toc}{chapter}{Index}
  8593. \printindex
  8594. \cleardoublepage
  8595. \bibliographystyle{plainnat}
  8596. \bibliography{all}
  8597. \addcontentsline{toc}{chapter}{Bibliography}
  8598. \end{document}
  8599. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8600. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8601. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8602. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8603. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8604. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8605. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8606. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8607. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8608. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8609. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8610. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8611. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  8612. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8613. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8614. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8615. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8616. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8617. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8618. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8619. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8620. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8621. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8622. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8623. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8624. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8625. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8626. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8627. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8628. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8629. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8630. % LocalWords: struct symtab