book.tex 537 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[T1]{fontenc}
  5. \usepackage[utf8]{inputenc}
  6. \usepackage{listings}
  7. \usepackage{amsmath}
  8. \usepackage{amsthm}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. \usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. \definecolor{lightgray}{gray}{1}
  16. \newcommand{\black}[1]{{\color{black} #1}}
  17. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  18. \newcommand{\gray}[1]{{\color{gray} #1}}
  19. %% For multiple indices:
  20. \usepackage{multind}
  21. \makeindex{subject}
  22. \makeindex{authors}
  23. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  24. \lstset{%
  25. language=Lisp,
  26. basicstyle=\ttfamily\small,
  27. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  28. deletekeywords={read,mapping,vector},
  29. escapechar=|,
  30. columns=flexible,
  31. moredelim=[is][\color{red}]{~}{~},
  32. showstringspaces=false
  33. }
  34. %%% Any shortcut own defined macros place here
  35. %% sample of author macro:
  36. \input{defs}
  37. \newtheorem{exercise}[theorem]{Exercise}
  38. % Adjusted settings
  39. \setlength{\columnsep}{4pt}
  40. %% \begingroup
  41. %% \setlength{\intextsep}{0pt}%
  42. %% \setlength{\columnsep}{0pt}%
  43. %% \begin{wrapfigure}{r}{0.5\textwidth}
  44. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  45. %% \caption{Basic layout}
  46. %% \end{wrapfigure}
  47. %% \lipsum[1]
  48. %% \endgroup
  49. \newbox\oiintbox
  50. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  51. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  52. \def\oiint{\copy\oiintbox}
  53. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  54. %\usepackage{showframe}
  55. \def\ShowFrameLinethickness{0.125pt}
  56. \addbibresource{book-MIT.bib}
  57. \addbibresource{bibsamp.bib}
  58. \begin{document}
  59. \frontmatter
  60. \HalfTitle{Essentials of Compilation}
  61. \halftitlepage
  62. %% \begin{seriespage}
  63. %% \seriestitle{Industrial Economics}
  64. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  65. %% \title{Engineering and Economics}
  66. %% \author{Samuel Endgrove}
  67. %% \title{Structural Economics: From Beginning to End}
  68. %% \author{Guang Xi}
  69. %% \end{seriespage}
  70. \Title{Essentials of Compilation}
  71. \Booksubtitle{The Incremental, Nano-Pass Approach}
  72. \edition{First Edition}
  73. \BookAuthor{Jeremy G. Siek}
  74. \imprint{The MIT Press\\
  75. Cambridge, Massachusetts\\
  76. London, England}
  77. \begin{copyrightpage}
  78. \textcopyright\ [YEAR] Massachusetts Institute of Technology
  79. All rights reserved. No part of this book may be reproduced in any
  80. form by any electronic or mechanical means (including photocopying,
  81. recording, or information storage and retrieval) without permission in
  82. writing from the publisher.
  83. This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  84. United States of America.
  85. Library of Congress Cataloging-in-Publication Data is available.
  86. ISBN:
  87. 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  88. \end{copyrightpage}
  89. \dedication{This book is dedicated to the programming language wonks
  90. at Indiana University.}
  91. %% \begin{epigraphpage}
  92. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  93. %% \textit{Book Name if any}}
  94. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  95. %% \end{epigraphpage}
  96. \tableofcontents
  97. \listoffigures
  98. \listoftables
  99. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  100. \chapter*{Preface}
  101. \addcontentsline{toc}{fmbm}{Preface}
  102. There is a magical moment when a programmer presses the ``run'' button
  103. and the software begins to execute. Somehow a program written in a
  104. high-level language is running on a computer that is only capable of
  105. shuffling bits. Here we reveal the wizardry that makes that moment
  106. possible. Beginning with the groundbreaking work of Backus and
  107. colleagues in the 1950s, computer scientists discovered techniques for
  108. constructing programs, called \emph{compilers}, that automatically
  109. translate high-level programs into machine code.
  110. We take you on a journey by constructing your own compiler for a small
  111. but powerful language. Along the way we explain the essential
  112. concepts, algorithms, and data structures that underlie compilers. We
  113. develop your understanding of how programs are mapped onto computer
  114. hardware, which is helpful when reasoning about properties at the
  115. junction between hardware and software such as execution time,
  116. software errors, and security vulnerabilities. For those interested
  117. in pursuing compiler construction, our goal is to provide a
  118. stepping-stone to advanced topics such as just-in-time compilation,
  119. program analysis, and program optimization. For those interested in
  120. designing and implementing programming languages, we connect
  121. language design choices to their impact on the compiler and the generated
  122. code.
  123. A compiler is typically organized as a sequence of stages that
  124. progressively translates a program to code that runs on hardware. We
  125. take this approach to the extreme by partitioning our compiler into a
  126. large number of \emph{nanopasses}, each of which performs a single
  127. task. This allows us to test the output of each pass in isolation, and
  128. furthermore, allows us to focus our attention making the compiler far
  129. easier to understand.
  130. %% [TODO: easier to understand/debug for those maintaining the compiler,
  131. %% proving correctness]
  132. The most familiar approach to describing compilers is with one pass
  133. per chapter. The problem with that is it obfuscates how language
  134. features motivate design choices in a compiler. We take an
  135. \emph{incremental} approach in which we build a complete compiler in
  136. each chapter, starting with arithmetic and variables and add new
  137. features in subsequent chapters.
  138. Our choice of language features is designed to elicit the fundamental
  139. concepts and algorithms used in compilers.
  140. \begin{itemize}
  141. \item We begin with integer arithmetic and local variables in
  142. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  143. the fundamental tools of compiler construction: \emph{abstract
  144. syntax trees} and \emph{recursive functions}.
  145. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  146. \emph{graph coloring} to assign variables to machine registers.
  147. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  148. an elegant recursive algorithm for mapping expressions to
  149. \emph{control-flow graphs}.
  150. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  151. \emph{garbage collection}.
  152. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  153. but lack lexical scoping, similar to the C programming
  154. language~\citep{Kernighan:1988nx} except that we generate efficient
  155. tail calls. The reader learns about the procedure call stack,
  156. \emph{calling conventions}, and their interaction with register
  157. allocation and garbage collection.
  158. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  159. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  160. \emph{closure conversion}, in which lambdas are translated into a
  161. combination of functions and tuples.
  162. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  163. point the input languages are statically typed. The reader extends
  164. the statically typed language with an \code{Any} type which serves
  165. as a target for compiling the dynamically typed language.
  166. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  167. programming languages with the addition of loops and mutable
  168. variables. These additions elicit the need for \emph{dataflow
  169. analysis} in the register allocator.
  170. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  171. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  172. in which different regions of a program may be static or dynamically
  173. typed. The reader implements runtime support for \emph{proxies} that
  174. allow values to safely move between regions.
  175. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  176. leveraging the \code{Any} type and type casts developed in Chapters
  177. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  178. \end{itemize}
  179. There are many language features that we do not include. Our choices
  180. weigh the incidental complexity of a feature against the fundamental
  181. concepts that it exposes. For example, we include tuples and not
  182. records because they both elicit the study of heap allocation and
  183. garbage collection but records come with more incidental complexity.
  184. Since 2016 this book has served as the textbook for the compiler
  185. course at Indiana University, a 16-week course for upper-level
  186. undergraduates and first-year graduate students.
  187. %
  188. Prior to this course, students learn to program in both imperative and
  189. functional languages, study data structures and algorithms, and take
  190. discrete mathematics.
  191. %
  192. At the beginning of the course, students form groups of 2-4 people.
  193. The groups complete one chapter every two weeks, starting with
  194. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  195. chapters include a challenge problem that we assign to the graduate
  196. students. The last two weeks of the course involve a final project in
  197. which students design and implement a compiler extension of their
  198. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  199. \ref{ch:Rpoly} can be used in support of these projects or they can
  200. replace some of the earlier chapters. For example, a course with an
  201. emphasis on statically-typed imperative languages would skip
  202. Chapter~\ref{ch:Rdyn} in favor of
  203. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  204. the dependencies between chapters.
  205. This book has also been used in compiler courses at California
  206. Polytechnic State University, Rose–Hulman Institute of Technology, and
  207. University of Massachusetts Lowell.
  208. \begin{figure}[tp]
  209. \begin{tikzpicture}[baseline=(current bounding box.center)]
  210. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  211. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  212. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  213. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  214. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  215. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  216. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  217. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  218. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  219. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  220. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  221. \path[->] (C1) edge [above] node {} (C2);
  222. \path[->] (C2) edge [above] node {} (C3);
  223. \path[->] (C3) edge [above] node {} (C4);
  224. \path[->] (C4) edge [above] node {} (C5);
  225. \path[->] (C5) edge [above] node {} (C6);
  226. \path[->] (C6) edge [above] node {} (C7);
  227. \path[->] (C4) edge [above] node {} (C8);
  228. \path[->] (C4) edge [above] node {} (C9);
  229. \path[->] (C8) edge [above] node {} (C10);
  230. \path[->] (C10) edge [above] node {} (C11);
  231. \end{tikzpicture}
  232. \caption{Diagram of chapter dependencies.}
  233. \label{fig:chapter-dependences}
  234. \end{figure}
  235. We use the \href{https://racket-lang.org/}{Racket} language both for
  236. the implementation of the compiler and for the input language, so the
  237. reader should be proficient with Racket or Scheme. There are many
  238. excellent resources for learning Scheme and
  239. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  240. support code for this book is in the \code{github} repository at the
  241. following URL:
  242. \begin{center}\small
  243. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  244. \end{center}
  245. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  246. is helpful but not necessary for the reader to have taken a computer
  247. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  248. of x86-64 assembly language that are needed.
  249. %
  250. We follow the System V calling
  251. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  252. that we generate works with the runtime system (written in C) when it
  253. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  254. operating systems.
  255. %
  256. On the Windows operating system, \code{gcc} uses the Microsoft x64
  257. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  258. assembly code that we generate does \emph{not} work with the runtime
  259. system on Windows. One workaround is to use a virtual machine with
  260. Linux as the guest operating system.
  261. \section*{Acknowledgments}
  262. The tradition of compiler construction at Indiana University goes back
  263. to research and courses on programming languages by Daniel Friedman in
  264. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  265. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  266. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  267. the compiler course and continued the development of Chez Scheme.
  268. %
  269. The compiler course evolved to incorporate novel pedagogical ideas
  270. while also including elements of efficient real-world compilers. One
  271. of Friedman's ideas was to split the compiler into many small
  272. passes. Another idea, called ``the game'', was to test the code
  273. generated by each pass on interpreters.
  274. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  275. developed infrastructure to support this approach and evolved the
  276. course to use even smaller
  277. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  278. design decisions in this book are inspired by the assignment
  279. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  280. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  281. organization of the course made it difficult for students to
  282. understand the rationale for the compiler design. Ghuloum proposed the
  283. incremental approach~\citep{Ghuloum:2006bh}.
  284. We thank the many graduate students who served as teaching assistants
  285. for the compiler course at IU. In particular, we thank Andre
  286. Kuhlenschmidt for his work on the garbage collector, Michael Vollmer
  287. for his work on efficient tail calls, and Michael Vitousek for his
  288. help running the first offering of the incremental compiler course at
  289. IU.
  290. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  291. Nystrom, and Michael Wollowski for teaching courses based on early
  292. drafts of this book.
  293. We thank Ronald Garcia for being Jeremy's partner when they took the
  294. compiler course in the early 2000's and especially for finding the bug
  295. that sent the garbage collector on a wild goose chase!
  296. \mbox{}\\
  297. \noindent Jeremy G. Siek \\
  298. Bloomington, Indiana
  299. \mainmatter
  300. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  301. \chapter{Preliminaries}
  302. \label{ch:trees-recur}
  303. In this chapter we review the basic tools that are needed to implement
  304. a compiler. Programs are typically input by a programmer as text,
  305. i.e., a sequence of characters. The program-as-text representation is
  306. called \emph{concrete syntax}. We use concrete syntax to concisely
  307. write down and talk about programs. Inside the compiler, we use
  308. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  309. that efficiently supports the operations that the compiler needs to
  310. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  311. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  312. from concrete syntax to abstract syntax is a process called
  313. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  314. implementation of parsing in this book. A parser is provided in the
  315. support code for translating from concrete to abstract syntax.
  316. ASTs can be represented in many different ways inside the compiler,
  317. depending on the programming language used to write the compiler.
  318. %
  319. We use Racket's
  320. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  321. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  322. define the abstract syntax of programming languages
  323. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  324. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  325. recursive functions to construct and deconstruct ASTs
  326. (Section~\ref{sec:recursion}). This chapter provides an brief
  327. introduction to these ideas. \index{subject}{struct}
  328. \section{Abstract Syntax Trees and Racket Structures}
  329. \label{sec:ast}
  330. Compilers use abstract syntax trees to represent programs because they
  331. often need to ask questions like: for a given part of a program, what
  332. kind of language feature is it? What are its sub-parts? Consider the
  333. program on the left and its AST on the right. This program is an
  334. addition operation and it has two sub-parts, a read operation and a
  335. negation. The negation has another sub-part, the integer constant
  336. \code{8}. By using a tree to represent the program, we can easily
  337. follow the links to go from one part of a program to its sub-parts.
  338. \begin{center}
  339. \begin{minipage}{0.4\textwidth}
  340. \begin{lstlisting}
  341. (+ (read) (- 8))
  342. \end{lstlisting}
  343. \end{minipage}
  344. \begin{minipage}{0.4\textwidth}
  345. \begin{equation}
  346. \begin{tikzpicture}
  347. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  348. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  349. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  350. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  351. \draw[->] (plus) to (read);
  352. \draw[->] (plus) to (minus);
  353. \draw[->] (minus) to (8);
  354. \end{tikzpicture}
  355. \label{eq:arith-prog}
  356. \end{equation}
  357. \end{minipage}
  358. \end{center}
  359. We use the standard terminology for trees to describe ASTs: each
  360. circle above is called a \emph{node}. The arrows connect a node to its
  361. \emph{children} (which are also nodes). The top-most node is the
  362. \emph{root}. Every node except for the root has a \emph{parent} (the
  363. node it is the child of). If a node has no children, it is a
  364. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  365. \index{subject}{node}
  366. \index{subject}{children}
  367. \index{subject}{root}
  368. \index{subject}{parent}
  369. \index{subject}{leaf}
  370. \index{subject}{internal node}
  371. %% Recall that an \emph{symbolic expression} (S-expression) is either
  372. %% \begin{enumerate}
  373. %% \item an atom, or
  374. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  375. %% where $e_1$ and $e_2$ are each an S-expression.
  376. %% \end{enumerate}
  377. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  378. %% null value \code{'()}, etc. We can create an S-expression in Racket
  379. %% simply by writing a backquote (called a quasi-quote in Racket)
  380. %% followed by the textual representation of the S-expression. It is
  381. %% quite common to use S-expressions to represent a list, such as $a, b
  382. %% ,c$ in the following way:
  383. %% \begin{lstlisting}
  384. %% `(a . (b . (c . ())))
  385. %% \end{lstlisting}
  386. %% Each element of the list is in the first slot of a pair, and the
  387. %% second slot is either the rest of the list or the null value, to mark
  388. %% the end of the list. Such lists are so common that Racket provides
  389. %% special notation for them that removes the need for the periods
  390. %% and so many parenthesis:
  391. %% \begin{lstlisting}
  392. %% `(a b c)
  393. %% \end{lstlisting}
  394. %% The following expression creates an S-expression that represents AST
  395. %% \eqref{eq:arith-prog}.
  396. %% \begin{lstlisting}
  397. %% `(+ (read) (- 8))
  398. %% \end{lstlisting}
  399. %% When using S-expressions to represent ASTs, the convention is to
  400. %% represent each AST node as a list and to put the operation symbol at
  401. %% the front of the list. The rest of the list contains the children. So
  402. %% in the above case, the root AST node has operation \code{`+} and its
  403. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  404. %% diagram \eqref{eq:arith-prog}.
  405. %% To build larger S-expressions one often needs to splice together
  406. %% several smaller S-expressions. Racket provides the comma operator to
  407. %% splice an S-expression into a larger one. For example, instead of
  408. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  409. %% we could have first created an S-expression for AST
  410. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  411. %% S-expression.
  412. %% \begin{lstlisting}
  413. %% (define ast1.4 `(- 8))
  414. %% (define ast1.1 `(+ (read) ,ast1.4))
  415. %% \end{lstlisting}
  416. %% In general, the Racket expression that follows the comma (splice)
  417. %% can be any expression that produces an S-expression.
  418. We define a Racket \code{struct} for each kind of node. For this
  419. chapter we require just two kinds of nodes: one for integer constants
  420. and one for primitive operations. The following is the \code{struct}
  421. definition for integer constants.
  422. \begin{lstlisting}
  423. (struct Int (value))
  424. \end{lstlisting}
  425. An integer node includes just one thing: the integer value.
  426. To create an AST node for the integer $8$, we write \code{(Int 8)}.
  427. \begin{lstlisting}
  428. (define eight (Int 8))
  429. \end{lstlisting}
  430. We say that the value created by \code{(Int 8)} is an
  431. \emph{instance} of the \code{Int} structure.
  432. The following is the \code{struct} definition for primitive operations.
  433. \begin{lstlisting}
  434. (struct Prim (op args))
  435. \end{lstlisting}
  436. A primitive operation node includes an operator symbol \code{op}
  437. and a list of child \code{args}. For example, to create
  438. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  439. \begin{lstlisting}
  440. (define neg-eight (Prim '- (list eight)))
  441. \end{lstlisting}
  442. Primitive operations may have zero or more children. The \code{read}
  443. operator has zero children:
  444. \begin{lstlisting}
  445. (define rd (Prim 'read '()))
  446. \end{lstlisting}
  447. whereas the addition operator has two children:
  448. \begin{lstlisting}
  449. (define ast1.1 (Prim '+ (list rd neg-eight)))
  450. \end{lstlisting}
  451. We have made a design choice regarding the \code{Prim} structure.
  452. Instead of using one structure for many different operations
  453. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  454. structure for each operation, as follows.
  455. \begin{lstlisting}
  456. (struct Read ())
  457. (struct Add (left right))
  458. (struct Neg (value))
  459. \end{lstlisting}
  460. The reason we choose to use just one structure is that in many parts
  461. of the compiler the code for the different primitive operators is the
  462. same, so we might as well just write that code once, which is enabled
  463. by using a single structure.
  464. When compiling a program such as \eqref{eq:arith-prog}, we need to
  465. know that the operation associated with the root node is addition and
  466. we need to be able to access its two children. Racket provides pattern
  467. matching to support these kinds of queries, as we see in
  468. Section~\ref{sec:pattern-matching}.
  469. In this book, we often write down the concrete syntax of a program
  470. even when we really have in mind the AST because the concrete syntax
  471. is more concise. We recommend that, in your mind, you always think of
  472. programs as abstract syntax trees.
  473. \section{Grammars}
  474. \label{sec:grammar}
  475. \index{subject}{integer}
  476. \index{subject}{literal}
  477. \index{subject}{constant}
  478. A programming language can be thought of as a \emph{set} of programs.
  479. The set is typically infinite (one can always create larger and larger
  480. programs), so one cannot simply describe a language by listing all of
  481. the programs in the language. Instead we write down a set of rules, a
  482. \emph{grammar}, for building programs. Grammars are often used to
  483. define the concrete syntax of a language, but they can also be used to
  484. describe the abstract syntax. We write our rules in a variant of
  485. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  486. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  487. As an example, we describe a small language, named \LangInt{}, that consists of
  488. integers and arithmetic operations.
  489. \index{subject}{grammar}
  490. The first grammar rule for the abstract syntax of \LangInt{} says that an
  491. instance of the \code{Int} structure is an expression:
  492. \begin{equation}
  493. \Exp ::= \INT{\Int} \label{eq:arith-int}
  494. \end{equation}
  495. %
  496. Each rule has a left-hand-side and a right-hand-side. The way to read
  497. a rule is that if you have an AST node that matches the
  498. right-hand-side, then you can categorize it according to the
  499. left-hand-side.
  500. %
  501. A name such as $\Exp$ that is defined by the grammar rules is a
  502. \emph{non-terminal}. \index{subject}{non-terminal}
  503. %
  504. The name $\Int$ is also a non-terminal, but instead of defining it
  505. with a grammar rule, we define it with the following explanation. We
  506. make the simplifying design decision that all of the languages in this
  507. book only handle machine-representable integers. On most modern
  508. machines this corresponds to integers represented with 64-bits, i.e.,
  509. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  510. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  511. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  512. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  513. that the sequence of decimals represent an integer in range $-2^{62}$
  514. to $2^{62}-1$.
  515. The second grammar rule is the \texttt{read} operation that receives
  516. an input integer from the user of the program.
  517. \begin{equation}
  518. \Exp ::= \READ{} \label{eq:arith-read}
  519. \end{equation}
  520. The third rule says that, given an $\Exp$ node, the negation of that
  521. node is also an $\Exp$.
  522. \begin{equation}
  523. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  524. \end{equation}
  525. Symbols in typewriter font such as \key{-} and \key{read} are
  526. \emph{terminal} symbols and must literally appear in the program for
  527. the rule to be applicable.
  528. \index{subject}{terminal}
  529. We can apply these rules to categorize the ASTs that are in the
  530. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  531. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  532. following AST is an $\Exp$.
  533. \begin{center}
  534. \begin{minipage}{0.4\textwidth}
  535. \begin{lstlisting}
  536. (Prim '- (list (Int 8)))
  537. \end{lstlisting}
  538. \end{minipage}
  539. \begin{minipage}{0.25\textwidth}
  540. \begin{equation}
  541. \begin{tikzpicture}
  542. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  543. \node[draw, circle] (8) at (0, -1.2) {$8$};
  544. \draw[->] (minus) to (8);
  545. \end{tikzpicture}
  546. \label{eq:arith-neg8}
  547. \end{equation}
  548. \end{minipage}
  549. \end{center}
  550. The next grammar rule is for addition expressions:
  551. \begin{equation}
  552. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  553. \end{equation}
  554. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  555. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  556. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  557. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  558. to show that
  559. \begin{lstlisting}
  560. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  561. \end{lstlisting}
  562. is an $\Exp$ in the \LangInt{} language.
  563. If you have an AST for which the above rules do not apply, then the
  564. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  565. is not in \LangInt{} because there are no rules for \code{+} with only one
  566. argument, nor for \key{-} with two arguments. Whenever we define a
  567. language with a grammar, the language only includes those programs
  568. that are justified by the rules.
  569. The last grammar rule for \LangInt{} states that there is a \code{Program}
  570. node to mark the top of the whole program:
  571. \[
  572. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  573. \]
  574. The \code{Program} structure is defined as follows
  575. \begin{lstlisting}
  576. (struct Program (info body))
  577. \end{lstlisting}
  578. where \code{body} is an expression. In later chapters, the \code{info}
  579. part will be used to store auxiliary information but for now it is
  580. just the empty list.
  581. It is common to have many grammar rules with the same left-hand side
  582. but different right-hand sides, such as the rules for $\Exp$ in the
  583. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  584. combine several right-hand-sides into a single rule.
  585. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  586. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  587. defined in Figure~\ref{fig:r0-concrete-syntax}.
  588. The \code{read-program} function provided in \code{utilities.rkt} of
  589. the support code reads a program in from a file (the sequence of
  590. characters in the concrete syntax of Racket) and parses it into an
  591. abstract syntax tree. See the description of \code{read-program} in
  592. Appendix~\ref{appendix:utilities} for more details.
  593. \begin{figure}[tp]
  594. \fbox{
  595. \begin{minipage}{0.96\textwidth}
  596. \[
  597. \begin{array}{rcl}
  598. \begin{array}{rcl}
  599. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  600. \LangInt{} &::=& \Exp
  601. \end{array}
  602. \end{array}
  603. \]
  604. \end{minipage}
  605. }
  606. \caption{The concrete syntax of \LangInt{}.}
  607. \label{fig:r0-concrete-syntax}
  608. \end{figure}
  609. \begin{figure}[tp]
  610. \fbox{
  611. \begin{minipage}{0.96\textwidth}
  612. \[
  613. \begin{array}{rcl}
  614. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  615. &\mid& \ADD{\Exp}{\Exp} \\
  616. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  617. \end{array}
  618. \]
  619. \end{minipage}
  620. }
  621. \caption{The abstract syntax of \LangInt{}.}
  622. \label{fig:r0-syntax}
  623. \end{figure}
  624. \section{Pattern Matching}
  625. \label{sec:pattern-matching}
  626. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  627. the parts of an AST node. Racket provides the \texttt{match} form to
  628. access the parts of a structure. Consider the following example and
  629. the output on the right. \index{subject}{match} \index{subject}{pattern matching}
  630. \begin{center}
  631. \begin{minipage}{0.5\textwidth}
  632. \begin{lstlisting}
  633. (match ast1.1
  634. [(Prim op (list child1 child2))
  635. (print op)])
  636. \end{lstlisting}
  637. \end{minipage}
  638. \vrule
  639. \begin{minipage}{0.25\textwidth}
  640. \begin{lstlisting}
  641. '+
  642. \end{lstlisting}
  643. \end{minipage}
  644. \end{center}
  645. In the above example, the \texttt{match} form takes an AST
  646. \eqref{eq:arith-prog} and binds its parts to the three pattern
  647. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  648. prints out the operator. In general, a match clause consists of a
  649. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  650. recursively defined to be either a pattern variable, a structure name
  651. followed by a pattern for each of the structure's arguments, or an
  652. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  653. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  654. and Chapter 9 of The Racket
  655. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  656. for a complete description of \code{match}.)
  657. %
  658. The body of a match clause may contain arbitrary Racket code. The
  659. pattern variables can be used in the scope of the body, such as
  660. \code{op} in \code{(print op)}.
  661. A \code{match} form may contain several clauses, as in the following
  662. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  663. the AST. The \code{match} proceeds through the clauses in order,
  664. checking whether the pattern can match the input AST. The body of the
  665. first clause that matches is executed. The output of \code{leaf?} for
  666. several ASTs is shown on the right.
  667. \begin{center}
  668. \begin{minipage}{0.6\textwidth}
  669. \begin{lstlisting}
  670. (define (leaf? arith)
  671. (match arith
  672. [(Int n) #t]
  673. [(Prim 'read '()) #t]
  674. [(Prim '- (list e1)) #f]
  675. [(Prim '+ (list e1 e2)) #f]))
  676. (leaf? (Prim 'read '()))
  677. (leaf? (Prim '- (list (Int 8))))
  678. (leaf? (Int 8))
  679. \end{lstlisting}
  680. \end{minipage}
  681. \vrule
  682. \begin{minipage}{0.25\textwidth}
  683. \begin{lstlisting}
  684. #t
  685. #f
  686. #t
  687. \end{lstlisting}
  688. \end{minipage}
  689. \end{center}
  690. When writing a \code{match}, we refer to the grammar definition to
  691. identify which non-terminal we are expecting to match against, then we
  692. make sure that 1) we have one clause for each alternative of that
  693. non-terminal and 2) that the pattern in each clause corresponds to the
  694. corresponding right-hand side of a grammar rule. For the \code{match}
  695. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  696. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  697. alternatives, so the \code{match} has 4 clauses. The pattern in each
  698. clause corresponds to the right-hand side of a grammar rule. For
  699. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  700. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  701. patterns, replace non-terminals such as $\Exp$ with pattern variables
  702. of your choice (e.g. \code{e1} and \code{e2}).
  703. \section{Recursive Functions}
  704. \label{sec:recursion}
  705. \index{subject}{recursive function}
  706. Programs are inherently recursive. For example, an \LangInt{} expression is
  707. often made of smaller expressions. Thus, the natural way to process an
  708. entire program is with a recursive function. As a first example of
  709. such a recursive function, we define \texttt{exp?} below, which takes
  710. an arbitrary value and determines whether or not it is an \LangInt{}
  711. expression.
  712. %
  713. We say that a function is defined by \emph{structural recursion} when
  714. it is defined using a sequence of match clauses that correspond to a
  715. grammar, and the body of each clause makes a recursive call on each
  716. child node.\footnote{This principle of structuring code according to
  717. the data definition is advocated in the book \emph{How to Design
  718. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  719. Below we also define a second function, named \code{Rint?}, that
  720. determines whether an AST is an \LangInt{} program. In general we can
  721. expect to write one recursive function to handle each non-terminal in
  722. a grammar.\index{subject}{structural recursion}
  723. %
  724. \begin{center}
  725. \begin{minipage}{0.7\textwidth}
  726. \begin{lstlisting}
  727. (define (exp? ast)
  728. (match ast
  729. [(Int n) #t]
  730. [(Prim 'read '()) #t]
  731. [(Prim '- (list e)) (exp? e)]
  732. [(Prim '+ (list e1 e2))
  733. (and (exp? e1) (exp? e2))]
  734. [else #f]))
  735. (define (Rint? ast)
  736. (match ast
  737. [(Program '() e) (exp? e)]
  738. [else #f]))
  739. (Rint? (Program '() ast1.1)
  740. (Rint? (Program '()
  741. (Prim '- (list (Prim 'read '())
  742. (Prim '+ (list (Num 8)))))))
  743. \end{lstlisting}
  744. \end{minipage}
  745. \vrule
  746. \begin{minipage}{0.25\textwidth}
  747. \begin{lstlisting}
  748. #t
  749. #f
  750. \end{lstlisting}
  751. \end{minipage}
  752. \end{center}
  753. You may be tempted to merge the two functions into one, like this:
  754. \begin{center}
  755. \begin{minipage}{0.5\textwidth}
  756. \begin{lstlisting}
  757. (define (Rint? ast)
  758. (match ast
  759. [(Int n) #t]
  760. [(Prim 'read '()) #t]
  761. [(Prim '- (list e)) (Rint? e)]
  762. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  763. [(Program '() e) (Rint? e)]
  764. [else #f]))
  765. \end{lstlisting}
  766. \end{minipage}
  767. \end{center}
  768. %
  769. Sometimes such a trick will save a few lines of code, especially when
  770. it comes to the \code{Program} wrapper. Yet this style is generally
  771. \emph{not} recommended because it can get you into trouble.
  772. %
  773. For example, the above function is subtly wrong:
  774. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  775. returns true when it should return false.
  776. \section{Interpreters}
  777. \label{sec:interp-Rint}
  778. \index{subject}{interpreter}
  779. In general, the intended behavior of a program is defined by the
  780. specification of the language. For example, the Scheme language is
  781. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  782. defined in its reference manual~\citep{plt-tr}. In this book we use
  783. interpreters to specify each language that we consider. An interpreter
  784. that is designated as the definition of a language is called a
  785. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  786. \index{subject}{definitional interpreter} We warm up by creating a definitional
  787. interpreter for the \LangInt{} language, which serves as a second example
  788. of structural recursion. The \texttt{interp-Rint} function is defined in
  789. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  790. input program followed by a call to the \lstinline{interp-exp} helper
  791. function, which in turn has one match clause per grammar rule for
  792. \LangInt{} expressions.
  793. \begin{figure}[tp]
  794. \begin{lstlisting}
  795. (define (interp-exp e)
  796. (match e
  797. [(Int n) n]
  798. [(Prim 'read '())
  799. (define r (read))
  800. (cond [(fixnum? r) r]
  801. [else (error 'interp-exp "read expected an integer" r)])]
  802. [(Prim '- (list e))
  803. (define v (interp-exp e))
  804. (fx- 0 v)]
  805. [(Prim '+ (list e1 e2))
  806. (define v1 (interp-exp e1))
  807. (define v2 (interp-exp e2))
  808. (fx+ v1 v2)]))
  809. (define (interp-Rint p)
  810. (match p
  811. [(Program '() e) (interp-exp e)]))
  812. \end{lstlisting}
  813. \caption{Interpreter for the \LangInt{} language.}
  814. \label{fig:interp-Rint}
  815. \end{figure}
  816. Let us consider the result of interpreting a few \LangInt{} programs. The
  817. following program adds two integers.
  818. \begin{lstlisting}
  819. (+ 10 32)
  820. \end{lstlisting}
  821. The result is \key{42}, the answer to life, the universe, and
  822. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  823. Galaxy} by Douglas Adams.}.
  824. %
  825. We wrote the above program in concrete syntax whereas the parsed
  826. abstract syntax is:
  827. \begin{lstlisting}
  828. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  829. \end{lstlisting}
  830. The next example demonstrates that expressions may be nested within
  831. each other, in this case nesting several additions and negations.
  832. \begin{lstlisting}
  833. (+ 10 (- (+ 12 20)))
  834. \end{lstlisting}
  835. What is the result of the above program?
  836. As mentioned previously, the \LangInt{} language does not support
  837. arbitrarily-large integers, but only $63$-bit integers, so we
  838. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  839. in Racket.
  840. Suppose
  841. \[
  842. n = 999999999999999999
  843. \]
  844. which indeed fits in $63$-bits. What happens when we run the
  845. following program in our interpreter?
  846. \begin{lstlisting}
  847. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  848. \end{lstlisting}
  849. It produces an error:
  850. \begin{lstlisting}
  851. fx+: result is not a fixnum
  852. \end{lstlisting}
  853. We establish the convention that if running the definitional
  854. interpreter on a program produces an error then the meaning of that
  855. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  856. error is a \code{trapped-error}. A compiler for the language is under
  857. no obligations regarding programs with unspecified behavior; it does
  858. not have to produce an executable, and if it does, that executable can
  859. do anything. On the other hand, if the error is a
  860. \code{trapped-error}, then the compiler must produce an executable and
  861. it is required to report that an error occurred. To signal an error,
  862. exit with a return code of \code{255}. The interpreters in chapters
  863. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  864. \code{trapped-error}.
  865. %% This convention applies to the languages defined in this
  866. %% book, as a way to simplify the student's task of implementing them,
  867. %% but this convention is not applicable to all programming languages.
  868. %%
  869. Moving on to the last feature of the \LangInt{} language, the \key{read}
  870. operation prompts the user of the program for an integer. Recall that
  871. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  872. \code{8}. So if we run
  873. \begin{lstlisting}
  874. (interp-Rint (Program '() ast1.1))
  875. \end{lstlisting}
  876. and if the input is \code{50}, the result is \code{42}.
  877. We include the \key{read} operation in \LangInt{} so a clever student
  878. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  879. during compilation to obtain the output and then generates the trivial
  880. code to produce the output. (Yes, a clever student did this in the
  881. first instance of this course.)
  882. The job of a compiler is to translate a program in one language into a
  883. program in another language so that the output program behaves the
  884. same way as the input program does. This idea is depicted in the
  885. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  886. $\mathcal{L}_2$, and a definitional interpreter for each language.
  887. Given a compiler that translates from language $\mathcal{L}_1$ to
  888. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  889. compiler must translate it into some program $P_2$ such that
  890. interpreting $P_1$ and $P_2$ on their respective interpreters with
  891. same input $i$ yields the same output $o$.
  892. \begin{equation} \label{eq:compile-correct}
  893. \begin{tikzpicture}[baseline=(current bounding box.center)]
  894. \node (p1) at (0, 0) {$P_1$};
  895. \node (p2) at (3, 0) {$P_2$};
  896. \node (o) at (3, -2.5) {$o$};
  897. \path[->] (p1) edge [above] node {compile} (p2);
  898. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  899. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  900. \end{tikzpicture}
  901. \end{equation}
  902. In the next section we see our first example of a compiler.
  903. \section{Example Compiler: a Partial Evaluator}
  904. \label{sec:partial-evaluation}
  905. In this section we consider a compiler that translates \LangInt{} programs
  906. into \LangInt{} programs that may be more efficient, that is, this compiler
  907. is an optimizer. This optimizer eagerly computes the parts of the
  908. program that do not depend on any inputs, a process known as
  909. \emph{partial evaluation}~\citep{Jones:1993uq}.
  910. \index{subject}{partial evaluation}
  911. For example, given the following program
  912. \begin{lstlisting}
  913. (+ (read) (- (+ 5 3)))
  914. \end{lstlisting}
  915. our compiler will translate it into the program
  916. \begin{lstlisting}
  917. (+ (read) -8)
  918. \end{lstlisting}
  919. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  920. evaluator for the \LangInt{} language. The output of the partial evaluator
  921. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  922. recursion over $\Exp$ is captured in the \code{pe-exp} function
  923. whereas the code for partially evaluating the negation and addition
  924. operations is factored into two separate helper functions:
  925. \code{pe-neg} and \code{pe-add}. The input to these helper
  926. functions is the output of partially evaluating the children.
  927. \begin{figure}[tp]
  928. \begin{lstlisting}
  929. (define (pe-neg r)
  930. (match r
  931. [(Int n) (Int (fx- 0 n))]
  932. [else (Prim '- (list r))]))
  933. (define (pe-add r1 r2)
  934. (match* (r1 r2)
  935. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  936. [(_ _) (Prim '+ (list r1 r2))]))
  937. (define (pe-exp e)
  938. (match e
  939. [(Int n) (Int n)]
  940. [(Prim 'read '()) (Prim 'read '())]
  941. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  942. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  943. (define (pe-Rint p)
  944. (match p
  945. [(Program '() e) (Program '() (pe-exp e))]))
  946. \end{lstlisting}
  947. \caption{A partial evaluator for \LangInt{}.}
  948. \label{fig:pe-arith}
  949. \end{figure}
  950. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  951. arguments are integers and if they are, perform the appropriate
  952. arithmetic. Otherwise, they create an AST node for the arithmetic
  953. operation.
  954. To gain some confidence that the partial evaluator is correct, we can
  955. test whether it produces programs that get the same result as the
  956. input programs. That is, we can test whether it satisfies Diagram
  957. \ref{eq:compile-correct}. The following code runs the partial
  958. evaluator on several examples and tests the output program. The
  959. \texttt{parse-program} and \texttt{assert} functions are defined in
  960. Appendix~\ref{appendix:utilities}.\\
  961. \begin{minipage}{1.0\textwidth}
  962. \begin{lstlisting}
  963. (define (test-pe p)
  964. (assert "testing pe-Rint"
  965. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  966. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  967. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  968. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  969. \end{lstlisting}
  970. \end{minipage}
  971. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  972. \chapter{Integers and Variables}
  973. \label{ch:Rvar}
  974. This chapter is about compiling a subset of Racket to x86-64 assembly
  975. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  976. integer arithmetic and local variable binding. We often refer to
  977. x86-64 simply as x86. The chapter begins with a description of the
  978. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  979. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  980. is large so we discuss only the instructions needed for compiling
  981. \LangVar{}. We introduce more x86 instructions in later chapters.
  982. After introducing \LangVar{} and x86, we reflect on their differences
  983. and come up with a plan to break down the translation from \LangVar{}
  984. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  985. rest of the sections in this chapter give detailed hints regarding
  986. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  987. We hope to give enough hints that the well-prepared reader, together
  988. with a few friends, can implement a compiler from \LangVar{} to x86 in
  989. a couple weeks. To give the reader a feeling for the scale of this
  990. first compiler, the instructor solution for the \LangVar{} compiler is
  991. approximately 500 lines of code.
  992. \section{The \LangVar{} Language}
  993. \label{sec:s0}
  994. \index{subject}{variable}
  995. The \LangVar{} language extends the \LangInt{} language with variable
  996. definitions. The concrete syntax of the \LangVar{} language is defined by
  997. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  998. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  999. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1000. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1001. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1002. \key{Program} struct to mark the top of the program.
  1003. %% The $\itm{info}$
  1004. %% field of the \key{Program} structure contains an \emph{association
  1005. %% list} (a list of key-value pairs) that is used to communicate
  1006. %% auxiliary data from one compiler pass the next.
  1007. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1008. exhibit several compilation techniques.
  1009. \begin{figure}[tp]
  1010. \centering
  1011. \fbox{
  1012. \begin{minipage}{0.96\textwidth}
  1013. \[
  1014. \begin{array}{rcl}
  1015. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1016. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1017. \LangVarM{} &::=& \Exp
  1018. \end{array}
  1019. \]
  1020. \end{minipage}
  1021. }
  1022. \caption{The concrete syntax of \LangVar{}.}
  1023. \label{fig:r1-concrete-syntax}
  1024. \end{figure}
  1025. \begin{figure}[tp]
  1026. \centering
  1027. \fbox{
  1028. \begin{minipage}{0.96\textwidth}
  1029. \[
  1030. \begin{array}{rcl}
  1031. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1032. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1033. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1034. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1035. \end{array}
  1036. \]
  1037. \end{minipage}
  1038. }
  1039. \caption{The abstract syntax of \LangVar{}.}
  1040. \label{fig:r1-syntax}
  1041. \end{figure}
  1042. Let us dive further into the syntax and semantics of the \LangVar{}
  1043. language. The \key{let} feature defines a variable for use within its
  1044. body and initializes the variable with the value of an expression.
  1045. The abstract syntax for \key{let} is defined in
  1046. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1047. \begin{lstlisting}
  1048. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1049. \end{lstlisting}
  1050. For example, the following program initializes \code{x} to $32$ and then
  1051. evaluates the body \code{(+ 10 x)}, producing $42$.
  1052. \begin{lstlisting}
  1053. (let ([x (+ 12 20)]) (+ 10 x))
  1054. \end{lstlisting}
  1055. When there are multiple \key{let}'s for the same variable, the closest
  1056. enclosing \key{let} is used. That is, variable definitions overshadow
  1057. prior definitions. Consider the following program with two \key{let}'s
  1058. that define variables named \code{x}. Can you figure out the result?
  1059. \begin{lstlisting}
  1060. (let ([x 32]) (+ (let ([x 10]) x) x))
  1061. \end{lstlisting}
  1062. For the purposes of depicting which variable uses correspond to which
  1063. definitions, the following shows the \code{x}'s annotated with
  1064. subscripts to distinguish them. Double check that your answer for the
  1065. above is the same as your answer for this annotated version of the
  1066. program.
  1067. \begin{lstlisting}
  1068. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1069. \end{lstlisting}
  1070. The initializing expression is always evaluated before the body of the
  1071. \key{let}, so in the following, the \key{read} for \code{x} is
  1072. performed before the \key{read} for \code{y}. Given the input
  1073. $52$ then $10$, the following produces $42$ (not $-42$).
  1074. \begin{lstlisting}
  1075. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1076. \end{lstlisting}
  1077. \subsection{Extensible Interpreters via Method Overriding}
  1078. \label{sec:extensible-interp}
  1079. To prepare for discussing the interpreter for \LangVar{}, we need to
  1080. explain why we choose to implement the interpreter using
  1081. object-oriented programming, that is, as a collection of methods
  1082. inside of a class. Throughout this book we define many interpreters,
  1083. one for each of the languages that we study. Because each language
  1084. builds on the prior one, there is a lot of commonality between their
  1085. interpreters. We want to write down those common parts just once
  1086. instead of many times. A naive approach would be to have, for example,
  1087. the interpreter for \LangIf{} handle all of the new features in that
  1088. language and then have a default case that dispatches to the
  1089. interpreter for \LangVar{}. The following code sketches this idea.
  1090. \begin{center}
  1091. \begin{minipage}{0.45\textwidth}
  1092. \begin{lstlisting}
  1093. (define (interp-Rvar e)
  1094. (match e
  1095. [(Prim '- (list e))
  1096. (fx- 0 (interp-Rvar e))]
  1097. ...))
  1098. \end{lstlisting}
  1099. \end{minipage}
  1100. \begin{minipage}{0.45\textwidth}
  1101. \begin{lstlisting}
  1102. (define (interp-Rif e)
  1103. (match e
  1104. [(If cnd thn els)
  1105. (match (interp-Rif cnd)
  1106. [#t (interp-Rif thn)]
  1107. [#f (interp-Rif els)])]
  1108. ...
  1109. [else (interp-Rvar e)]))
  1110. \end{lstlisting}
  1111. \end{minipage}
  1112. \end{center}
  1113. The problem with this approach is that it does not handle situations
  1114. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1115. feature, like the \code{-} operator, as in the following program.
  1116. \begin{lstlisting}
  1117. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1118. \end{lstlisting}
  1119. If we invoke \code{interp-Rif} on this program, it dispatches to
  1120. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1121. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1122. which is an \code{If}. But there is no case for \code{If} in
  1123. \code{interp-Rvar}, so we get an error!
  1124. To make our interpreters extensible we need something called
  1125. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1126. recursive knot is delayed to when the functions are
  1127. composed. Object-oriented languages provide open recursion with the
  1128. late-binding of overridden methods\index{subject}{method overriding}. The
  1129. following code sketches this idea for interpreting \LangVar{} and
  1130. \LangIf{} using the
  1131. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1132. \index{subject}{class} feature of Racket. We define one class for each
  1133. language and define a method for interpreting expressions inside each
  1134. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1135. and the method \code{interp-exp} in \LangIf{} overrides the
  1136. \code{interp-exp} in \LangVar{}. Note that the default case of
  1137. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1138. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1139. that dispatches to the \code{interp-exp} in \LangVar{}.
  1140. \begin{center}
  1141. \begin{minipage}{0.45\textwidth}
  1142. \begin{lstlisting}
  1143. (define interp-Rvar-class
  1144. (class object%
  1145. (define/public (interp-exp e)
  1146. (match e
  1147. [(Prim '- (list e))
  1148. (fx- 0 (interp-exp e))]
  1149. ...))
  1150. ...))
  1151. \end{lstlisting}
  1152. \end{minipage}
  1153. \begin{minipage}{0.45\textwidth}
  1154. \begin{lstlisting}
  1155. (define interp-Rif-class
  1156. (class interp-Rvar-class
  1157. (define/override (interp-exp e)
  1158. (match e
  1159. [(If cnd thn els)
  1160. (match (interp-exp cnd)
  1161. [#t (interp-exp thn)]
  1162. [#f (interp-exp els)])]
  1163. ...
  1164. [else (super interp-exp e)]))
  1165. ...
  1166. ))
  1167. \end{lstlisting}
  1168. \end{minipage}
  1169. \end{center}
  1170. Getting back to the troublesome example, repeated here:
  1171. \begin{lstlisting}
  1172. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1173. \end{lstlisting}
  1174. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1175. expression by creating an object of the \LangIf{} class and sending it the
  1176. \code{interp-exp} method with the argument \code{e0}.
  1177. \begin{lstlisting}
  1178. (send (new interp-Rif-class) interp-exp e0)
  1179. \end{lstlisting}
  1180. The default case of \code{interp-exp} in \LangIf{} handles it by
  1181. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1182. handles the \code{-} operator. But then for the recursive method call,
  1183. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1184. \code{If} is handled correctly. Thus, method overriding gives us the
  1185. open recursion that we need to implement our interpreters in an
  1186. extensible way.
  1187. \newpage
  1188. \subsection{Definitional Interpreter for \LangVar{}}
  1189. \begin{wrapfigure}[26]{r}[0.9in]{0.55\textwidth}
  1190. \small
  1191. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1192. An \emph{association list} (alist) is a list of key-value pairs.
  1193. For example, we can map people to their ages with an alist.
  1194. \index{subject}{alist}\index{subject}{association list}
  1195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1196. (define ages
  1197. '((jane . 25) (sam . 24) (kate . 45)))
  1198. \end{lstlisting}
  1199. The \emph{dictionary} interface is for mapping keys to values.
  1200. Every alist implements this interface. \index{subject}{dictionary} The package
  1201. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1202. provides many functions for working with dictionaries. Here
  1203. are a few of them:
  1204. \begin{description}
  1205. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1206. returns the value associated with the given $\itm{key}$.
  1207. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1208. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1209. but otherwise is the same as $\itm{dict}$.
  1210. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1211. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1212. of keys and values in $\itm{dict}$. For example, the following
  1213. creates a new alist in which the ages are incremented.
  1214. \end{description}
  1215. \vspace{-10pt}
  1216. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1217. (for/list ([(k v) (in-dict ages)])
  1218. (cons k (add1 v)))
  1219. \end{lstlisting}
  1220. \end{tcolorbox}
  1221. \end{wrapfigure}
  1222. Having justified the use of classes and methods to implement
  1223. interpreters, we turn to the definitional interpreter for \LangVar{}
  1224. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1225. \LangInt{} but adds two new \key{match} cases for variables and
  1226. \key{let}. For \key{let} we need a way to communicate the value bound
  1227. to a variable to all the uses of the variable. To accomplish this, we
  1228. maintain a mapping from variables to values. Throughout the compiler
  1229. we often need to map variables to information about them. We refer to
  1230. these mappings as
  1231. \emph{environments}\index{subject}{environment}.\footnote{Another common term
  1232. for environment in the compiler literature is \emph{symbol
  1233. table}\index{subject}{symbol table}.}
  1234. %
  1235. For simplicity, we use an association list (alist) to represent the
  1236. environment. The sidebar to the right gives a brief introduction to
  1237. alists and the \code{racket/dict} package. The \code{interp-exp}
  1238. function takes the current environment, \code{env}, as an extra
  1239. parameter. When the interpreter encounters a variable, it finds the
  1240. corresponding value using the \code{dict-ref} function. When the
  1241. interpreter encounters a \key{Let}, it evaluates the initializing
  1242. expression, extends the environment with the result value bound to the
  1243. variable, using \code{dict-set}, then evaluates the body of the
  1244. \key{Let}.
  1245. \begin{figure}[tp]
  1246. \begin{lstlisting}
  1247. (define interp-Rvar-class
  1248. (class object%
  1249. (super-new)
  1250. (define/public ((interp-exp env) e)
  1251. (match e
  1252. [(Int n) n]
  1253. [(Prim 'read '())
  1254. (define r (read))
  1255. (cond [(fixnum? r) r]
  1256. [else (error 'interp-exp "expected an integer" r)])]
  1257. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1258. [(Prim '+ (list e1 e2))
  1259. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1260. [(Var x) (dict-ref env x)]
  1261. [(Let x e body)
  1262. (define new-env (dict-set env x ((interp-exp env) e)))
  1263. ((interp-exp new-env) body)]))
  1264. (define/public (interp-program p)
  1265. (match p
  1266. [(Program '() e) ((interp-exp '()) e)]))
  1267. ))
  1268. (define (interp-Rvar p)
  1269. (send (new interp-Rvar-class) interp-program p))
  1270. \end{lstlisting}
  1271. \caption{Interpreter for the \LangVar{} language.}
  1272. \label{fig:interp-Rvar}
  1273. \end{figure}
  1274. The goal for this chapter is to implement a compiler that translates
  1275. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1276. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1277. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1278. is, they output the same integer $n$. We depict this correctness
  1279. criteria in the following diagram.
  1280. \[
  1281. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1282. \node (p1) at (0, 0) {$P_1$};
  1283. \node (p2) at (4, 0) {$P_2$};
  1284. \node (o) at (4, -2) {$n$};
  1285. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1286. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1287. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1288. \end{tikzpicture}
  1289. \]
  1290. In the next section we introduce the \LangXInt{} subset of x86 that
  1291. suffices for compiling \LangVar{}.
  1292. \section{The \LangXInt{} Assembly Language}
  1293. \label{sec:x86}
  1294. \index{subject}{x86}
  1295. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1296. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1297. assembler.
  1298. %
  1299. A program begins with a \code{main} label followed by a sequence of
  1300. instructions. The \key{globl} directive says that the \key{main}
  1301. procedure is externally visible, which is necessary so that the
  1302. operating system can call it. In the grammar, ellipses such as
  1303. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1304. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1305. %
  1306. An x86 program is stored in the computer's memory. For our purposes,
  1307. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1308. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1309. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1310. the address of the next instruction to be executed. For most
  1311. instructions, the program counter is incremented after the instruction
  1312. is executed, so it points to the next instruction in memory. Most x86
  1313. instructions take two operands, where each operand is either an
  1314. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1315. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1316. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1317. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1318. && \key{r8} \mid \key{r9} \mid \key{r10}
  1319. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1320. \mid \key{r14} \mid \key{r15}}
  1321. \begin{figure}[tp]
  1322. \fbox{
  1323. \begin{minipage}{0.96\textwidth}
  1324. \[
  1325. \begin{array}{lcl}
  1326. \Reg &::=& \allregisters{} \\
  1327. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1328. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1329. \key{subq} \; \Arg\key{,} \Arg \mid
  1330. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1331. && \key{callq} \; \mathit{label} \mid
  1332. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1333. && \itm{label}\key{:}\; \Instr \\
  1334. \LangXIntM{} &::= & \key{.globl main}\\
  1335. & & \key{main:} \; \Instr\ldots
  1336. \end{array}
  1337. \]
  1338. \end{minipage}
  1339. }
  1340. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1341. \label{fig:x86-int-concrete}
  1342. \end{figure}
  1343. A register is a special kind of variable. Each one holds a 64-bit
  1344. value; there are 16 general-purpose registers in the computer and
  1345. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1346. is written with a \key{\%} followed by the register name, such as
  1347. \key{\%rax}.
  1348. An immediate value is written using the notation \key{\$}$n$ where $n$
  1349. is an integer.
  1350. %
  1351. %
  1352. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1353. which obtains the address stored in register $r$ and then adds $n$
  1354. bytes to the address. The resulting address is used to load or store
  1355. to memory depending on whether it occurs as a source or destination
  1356. argument of an instruction.
  1357. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1358. source $s$ and destination $d$, applies the arithmetic operation, then
  1359. writes the result back to the destination $d$.
  1360. %
  1361. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1362. stores the result in $d$.
  1363. %
  1364. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1365. specified by the label and $\key{retq}$ returns from a procedure to
  1366. its caller.
  1367. %
  1368. We discuss procedure calls in more detail later in this chapter and in
  1369. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1370. updates the program counter to the address of the instruction after
  1371. the specified label.
  1372. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1373. all of the x86 instructions used in this book.
  1374. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1375. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1376. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1377. adds $32$ to the $10$ in \key{rax} and
  1378. puts the result, $42$, back into \key{rax}.
  1379. %
  1380. The last instruction, \key{retq}, finishes the \key{main} function by
  1381. returning the integer in \key{rax} to the operating system. The
  1382. operating system interprets this integer as the program's exit
  1383. code. By convention, an exit code of 0 indicates that a program
  1384. completed successfully, and all other exit codes indicate various
  1385. errors. Nevertheless, in this book we return the result of the program
  1386. as the exit code.
  1387. \begin{figure}[tbp]
  1388. \begin{lstlisting}
  1389. .globl main
  1390. main:
  1391. movq $10, %rax
  1392. addq $32, %rax
  1393. retq
  1394. \end{lstlisting}
  1395. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1396. \label{fig:p0-x86}
  1397. \end{figure}
  1398. The x86 assembly language varies in a couple of ways depending on what
  1399. operating system it is assembled in. The code examples shown here are
  1400. correct on Linux and most Unix-like platforms, but when assembled on
  1401. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1402. as in \key{\_main}.
  1403. We exhibit the use of memory for storing intermediate results in the
  1404. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1405. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1406. memory called the \emph{procedure call stack} (or \emph{stack} for
  1407. short). \index{subject}{stack}\index{subject}{procedure call stack} The stack consists
  1408. of a separate \emph{frame}\index{subject}{frame} for each procedure call. The
  1409. memory layout for an individual frame is shown in
  1410. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1411. \emph{stack pointer}\index{subject}{stack pointer} and points to the item at
  1412. the top of the stack. The stack grows downward in memory, so we
  1413. increase the size of the stack by subtracting from the stack pointer.
  1414. In the context of a procedure call, the \emph{return
  1415. address}\index{subject}{return address} is the instruction after the call
  1416. instruction on the caller side. The function call instruction,
  1417. \code{callq}, pushes the return address onto the stack prior to
  1418. jumping to the procedure. The register \key{rbp} is the \emph{base
  1419. pointer}\index{subject}{base pointer} and is used to access variables that
  1420. are stored in the frame of the current procedure call. The base
  1421. pointer of the caller is pushed onto the stack after the return
  1422. address and then the base pointer is set to the location of the old
  1423. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1424. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1425. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1426. \begin{figure}[tbp]
  1427. \begin{lstlisting}
  1428. start:
  1429. movq $10, -8(%rbp)
  1430. negq -8(%rbp)
  1431. movq -8(%rbp), %rax
  1432. addq $52, %rax
  1433. jmp conclusion
  1434. .globl main
  1435. main:
  1436. pushq %rbp
  1437. movq %rsp, %rbp
  1438. subq $16, %rsp
  1439. jmp start
  1440. conclusion:
  1441. addq $16, %rsp
  1442. popq %rbp
  1443. retq
  1444. \end{lstlisting}
  1445. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1446. \label{fig:p1-x86}
  1447. \end{figure}
  1448. \begin{figure}[tbp]
  1449. \centering
  1450. \begin{tabular}{|r|l|} \hline
  1451. Position & Contents \\ \hline
  1452. 8(\key{\%rbp}) & return address \\
  1453. 0(\key{\%rbp}) & old \key{rbp} \\
  1454. -8(\key{\%rbp}) & variable $1$ \\
  1455. -16(\key{\%rbp}) & variable $2$ \\
  1456. \ldots & \ldots \\
  1457. 0(\key{\%rsp}) & variable $n$\\ \hline
  1458. \end{tabular}
  1459. \caption{Memory layout of a frame.}
  1460. \label{fig:frame}
  1461. \end{figure}
  1462. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1463. control is transferred from the operating system to the \code{main}
  1464. function. The operating system issues a \code{callq main} instruction
  1465. which pushes its return address on the stack and then jumps to
  1466. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1467. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1468. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1469. alignment (because the \code{callq} pushed the return address). The
  1470. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  1471. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1472. pointer for the caller onto the stack and subtracts $8$ from the stack
  1473. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1474. base pointer so that it points the location of the old base
  1475. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1476. pointer down to make enough room for storing variables. This program
  1477. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1478. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1479. functions. The last instruction of the prelude is \code{jmp start},
  1480. which transfers control to the instructions that were generated from
  1481. the Racket expression \code{(+ 52 (- 10))}.
  1482. The first instruction under the \code{start} label is
  1483. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1484. %
  1485. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1486. %
  1487. The next instruction moves the $-10$ from variable $1$ into the
  1488. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1489. the value in \code{rax}, updating its contents to $42$.
  1490. The three instructions under the label \code{conclusion} are the
  1491. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  1492. two instructions restore the \code{rsp} and \code{rbp} registers to
  1493. the state they were in at the beginning of the procedure. The
  1494. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1495. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1496. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1497. instruction, \key{retq}, jumps back to the procedure that called this
  1498. one and adds $8$ to the stack pointer.
  1499. The compiler needs a convenient representation for manipulating x86
  1500. programs, so we define an abstract syntax for x86 in
  1501. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1502. \LangXInt{}. The main difference compared to the concrete syntax of
  1503. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1504. allowed in front of every instruction. Instead instructions are
  1505. grouped into \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  1506. label associated with every block, which is why the \key{X86Program}
  1507. struct includes an alist mapping labels to blocks. The reason for this
  1508. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1509. introduce conditional branching. The \code{Block} structure includes
  1510. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1511. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1512. $\itm{info}$ field should contain an empty list. Also, regarding the
  1513. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1514. integer for representing the arity of the function, i.e., the number
  1515. of arguments, which is helpful to know during register allocation
  1516. (Chapter~\ref{ch:register-allocation-Rvar}).
  1517. \begin{figure}[tp]
  1518. \fbox{
  1519. \begin{minipage}{0.98\textwidth}
  1520. \small
  1521. \[
  1522. \begin{array}{lcl}
  1523. \Reg &::=& \allregisters{} \\
  1524. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1525. \mid \DEREF{\Reg}{\Int} \\
  1526. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1527. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1528. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1529. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1530. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1531. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1532. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1533. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1534. \end{array}
  1535. \]
  1536. \end{minipage}
  1537. }
  1538. \caption{The abstract syntax of \LangXInt{} assembly.}
  1539. \label{fig:x86-int-ast}
  1540. \end{figure}
  1541. \section{Planning the trip to x86 via the \LangCVar{} language}
  1542. \label{sec:plan-s0-x86}
  1543. To compile one language to another it helps to focus on the
  1544. differences between the two languages because the compiler will need
  1545. to bridge those differences. What are the differences between \LangVar{}
  1546. and x86 assembly? Here are some of the most important ones:
  1547. \begin{enumerate}
  1548. \item[(a)] x86 arithmetic instructions typically have two arguments
  1549. and update the second argument in place. In contrast, \LangVar{}
  1550. arithmetic operations take two arguments and produce a new value.
  1551. An x86 instruction may have at most one memory-accessing argument.
  1552. Furthermore, some instructions place special restrictions on their
  1553. arguments.
  1554. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1555. expression, whereas x86 instructions restrict their arguments to be
  1556. integer constants, registers, and memory locations.
  1557. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1558. sequence of instructions and jumps to labeled positions, whereas in
  1559. \LangVar{} the order of evaluation is a left-to-right depth-first
  1560. traversal of the abstract syntax tree.
  1561. \item[(d)] A program in \LangVar{} can have any number of variables
  1562. whereas x86 has 16 registers and the procedure calls stack.
  1563. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  1564. same name. In x86, registers have unique names and memory locations
  1565. have unique addresses.
  1566. \end{enumerate}
  1567. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1568. the problem into several steps, dealing with the above differences one
  1569. at a time. Each of these steps is called a \emph{pass} of the
  1570. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  1571. %
  1572. This terminology comes from the way each step passes over the AST of
  1573. the program.
  1574. %
  1575. We begin by sketching how we might implement each pass, and give them
  1576. names. We then figure out an ordering of the passes and the
  1577. input/output language for each pass. The very first pass has
  1578. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1579. its output language. In between we can choose whichever language is
  1580. most convenient for expressing the output of each pass, whether that
  1581. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1582. our own design. Finally, to implement each pass we write one
  1583. recursive function per non-terminal in the grammar of the input
  1584. language of the pass. \index{subject}{intermediate language}
  1585. \begin{description}
  1586. \item[\key{select-instructions}] handles the difference between
  1587. \LangVar{} operations and x86 instructions. This pass converts each
  1588. \LangVar{} operation to a short sequence of instructions that
  1589. accomplishes the same task.
  1590. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1591. a primitive operation is a variable or integer, that is, an
  1592. \emph{atomic} expression. We refer to non-atomic expressions as
  1593. \emph{complex}. This pass introduces temporary variables to hold
  1594. the results of complex subexpressions.\index{subject}{atomic
  1595. expression}\index{subject}{complex expression}%
  1596. \footnote{The subexpressions of an operation are often called
  1597. operators and operands which explains the presence of
  1598. \code{opera*} in the name of this pass.}
  1599. \item[\key{explicate-control}] makes the execution order of the
  1600. program explicit. It convert the abstract syntax tree representation
  1601. into a control-flow graph in which each node contains a sequence of
  1602. statements and the edges between nodes say which nodes contain jumps
  1603. to other nodes.
  1604. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1605. registers or stack locations in x86.
  1606. \item[\key{uniquify}] deals with the shadowing of variables by
  1607. renaming every variable to a unique name.
  1608. \end{description}
  1609. The next question is: in what order should we apply these passes? This
  1610. question can be challenging because it is difficult to know ahead of
  1611. time which orderings will be better (easier to implement, produce more
  1612. efficient code, etc.) so oftentimes trial-and-error is
  1613. involved. Nevertheless, we can try to plan ahead and make educated
  1614. choices regarding the ordering.
  1615. What should be the ordering of \key{explicate-control} with respect to
  1616. \key{uniquify}? The \key{uniquify} pass should come first because
  1617. \key{explicate-control} changes all the \key{let}-bound variables to
  1618. become local variables whose scope is the entire program, which would
  1619. confuse variables with the same name.
  1620. %
  1621. We place \key{remove-complex-opera*} before \key{explicate-control}
  1622. because the later removes the \key{let} form, but it is convenient to
  1623. use \key{let} in the output of \key{remove-complex-opera*}.
  1624. %
  1625. The ordering of \key{uniquify} with respect to
  1626. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1627. \key{uniquify} to come first.
  1628. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1629. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1630. learn that, in x86, registers are used for passing arguments to
  1631. functions and it is preferable to assign parameters to their
  1632. corresponding registers. On the other hand, by selecting instructions
  1633. first we may run into a dead end in \key{assign-homes}. Recall that
  1634. only one argument of an x86 instruction may be a memory access but
  1635. \key{assign-homes} might fail to assign even one of them to a
  1636. register.
  1637. %
  1638. A sophisticated approach is to iteratively repeat the two passes until
  1639. a solution is found. However, to reduce implementation complexity we
  1640. recommend a simpler approach in which \key{select-instructions} comes
  1641. first, followed by the \key{assign-homes}, then a third pass named
  1642. \key{patch-instructions} that uses a reserved register to fix
  1643. outstanding problems.
  1644. \begin{figure}[tbp]
  1645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1646. \node (Rvar) at (0,2) {\large \LangVar{}};
  1647. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1648. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1649. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1650. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1651. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1652. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1653. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1654. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1655. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1656. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1657. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1658. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1659. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1660. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1661. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1662. \end{tikzpicture}
  1663. \caption{Diagram of the passes for compiling \LangVar{}. }
  1664. \label{fig:Rvar-passes}
  1665. \end{figure}
  1666. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1667. passes and identifies the input and output language of each pass. The
  1668. last pass, \key{print-x86}, converts from the abstract syntax of
  1669. \LangXInt{} to the concrete syntax. In the following two sections
  1670. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1671. dialect of x86. The remainder of this chapter gives hints regarding
  1672. the implementation of each of the compiler passes in
  1673. Figure~\ref{fig:Rvar-passes}.
  1674. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1675. %% are programs that are still in the \LangVar{} language, though the
  1676. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1677. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1678. %% %
  1679. %% The output of \key{explicate-control} is in an intermediate language
  1680. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1681. %% syntax, which we introduce in the next section. The
  1682. %% \key{select-instruction} pass translates from \LangCVar{} to
  1683. %% \LangXVar{}. The \key{assign-homes} and
  1684. %% \key{patch-instructions}
  1685. %% passes input and output variants of x86 assembly.
  1686. \subsection{The \LangCVar{} Intermediate Language}
  1687. The output of \key{explicate-control} is similar to the $C$
  1688. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1689. categories for expressions and statements, so we name it \LangCVar{}. The
  1690. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1691. (The concrete syntax for \LangCVar{} is in the Appendix,
  1692. Figure~\ref{fig:c0-concrete-syntax}.)
  1693. %
  1694. The \LangCVar{} language supports the same operators as \LangVar{} but
  1695. the arguments of operators are restricted to atomic
  1696. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1697. assignment statements which can be executed in sequence using the
  1698. \key{Seq} form. A sequence of statements always ends with
  1699. \key{Return}, a guarantee that is baked into the grammar rules for
  1700. \itm{tail}. The naming of this non-terminal comes from the term
  1701. \emph{tail position}\index{subject}{tail position}, which refers to an
  1702. expression that is the last one to execute within a function.
  1703. A \LangCVar{} program consists of a control-flow graph represented as
  1704. an alist mapping labels to tails. This is more general than necessary
  1705. for the present chapter, as we do not yet introduce \key{goto} for
  1706. jumping to labels, but it saves us from having to change the syntax in
  1707. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1708. \key{start}, and the whole program is its tail.
  1709. %
  1710. The $\itm{info}$ field of the \key{CProgram} form, after the
  1711. \key{explicate-control} pass, contains a mapping from the symbol
  1712. \key{locals} to a list of variables, that is, a list of all the
  1713. variables used in the program. At the start of the program, these
  1714. variables are uninitialized; they become initialized on their first
  1715. assignment.
  1716. \begin{figure}[tbp]
  1717. \fbox{
  1718. \begin{minipage}{0.96\textwidth}
  1719. \[
  1720. \begin{array}{lcl}
  1721. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1722. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1723. &\mid& \ADD{\Atm}{\Atm}\\
  1724. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1725. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1726. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1727. \end{array}
  1728. \]
  1729. \end{minipage}
  1730. }
  1731. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1732. \label{fig:c0-syntax}
  1733. \end{figure}
  1734. The definitional interpreter for \LangCVar{} is in the support code,
  1735. in the file \code{interp-Cvar.rkt}.
  1736. \subsection{The \LangXVar{} dialect}
  1737. The \LangXVar{} language is the output of the pass
  1738. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1739. number of program-scope variables and removes the restrictions
  1740. regarding instruction arguments.
  1741. \section{Uniquify Variables}
  1742. \label{sec:uniquify-Rvar}
  1743. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1744. programs in which every \key{let} binds a unique variable name. For
  1745. example, the \code{uniquify} pass should translate the program on the
  1746. left into the program on the right. \\
  1747. \begin{tabular}{lll}
  1748. \begin{minipage}{0.4\textwidth}
  1749. \begin{lstlisting}
  1750. (let ([x 32])
  1751. (+ (let ([x 10]) x) x))
  1752. \end{lstlisting}
  1753. \end{minipage}
  1754. &
  1755. $\Rightarrow$
  1756. &
  1757. \begin{minipage}{0.4\textwidth}
  1758. \begin{lstlisting}
  1759. (let ([x.1 32])
  1760. (+ (let ([x.2 10]) x.2) x.1))
  1761. \end{lstlisting}
  1762. \end{minipage}
  1763. \end{tabular} \\
  1764. %
  1765. The following is another example translation, this time of a program
  1766. with a \key{let} nested inside the initializing expression of another
  1767. \key{let}.\\
  1768. \begin{tabular}{lll}
  1769. \begin{minipage}{0.4\textwidth}
  1770. \begin{lstlisting}
  1771. (let ([x (let ([x 4])
  1772. (+ x 1))])
  1773. (+ x 2))
  1774. \end{lstlisting}
  1775. \end{minipage}
  1776. &
  1777. $\Rightarrow$
  1778. &
  1779. \begin{minipage}{0.4\textwidth}
  1780. \begin{lstlisting}
  1781. (let ([x.2 (let ([x.1 4])
  1782. (+ x.1 1))])
  1783. (+ x.2 2))
  1784. \end{lstlisting}
  1785. \end{minipage}
  1786. \end{tabular}
  1787. We recommend implementing \code{uniquify} by creating a structurally
  1788. recursive function named \code{uniquify-exp} that mostly just copies
  1789. an expression. However, when encountering a \key{let}, it should
  1790. generate a unique name for the variable and associate the old name
  1791. with the new name in an alist.\footnote{The Racket function
  1792. \code{gensym} is handy for generating unique variable names.} The
  1793. \code{uniquify-exp} function needs to access this alist when it gets
  1794. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1795. for the alist.
  1796. The skeleton of the \code{uniquify-exp} function is shown in
  1797. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1798. convenient to partially apply it to an alist and then apply it to
  1799. different expressions, as in the last case for primitive operations in
  1800. Figure~\ref{fig:uniquify-Rvar}. The
  1801. %
  1802. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1803. %
  1804. form of Racket is useful for transforming each element of a list to
  1805. produce a new list.\index{subject}{for/list}
  1806. \begin{figure}[tbp]
  1807. \begin{lstlisting}
  1808. (define (uniquify-exp env)
  1809. (lambda (e)
  1810. (match e
  1811. [(Var x) ___]
  1812. [(Int n) (Int n)]
  1813. [(Let x e body) ___]
  1814. [(Prim op es)
  1815. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1816. (define (uniquify p)
  1817. (match p
  1818. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1819. \end{lstlisting}
  1820. \caption{Skeleton for the \key{uniquify} pass.}
  1821. \label{fig:uniquify-Rvar}
  1822. \end{figure}
  1823. \begin{exercise}
  1824. \normalfont % I don't like the italics for exercises. -Jeremy
  1825. Complete the \code{uniquify} pass by filling in the blanks in
  1826. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1827. variables and for the \key{let} form in the file \code{compiler.rkt}
  1828. in the support code.
  1829. \end{exercise}
  1830. \begin{exercise}
  1831. \normalfont % I don't like the italics for exercises. -Jeremy
  1832. \label{ex:Rvar}
  1833. Create five \LangVar{} programs that exercise the most interesting
  1834. parts of the \key{uniquify} pass, that is, the programs should include
  1835. \key{let} forms, variables, and variables that shadow each other.
  1836. The five programs should be placed in the subdirectory named
  1837. \key{tests} and the file names should start with \code{var\_test\_}
  1838. followed by a unique integer and end with the file extension
  1839. \key{.rkt}.
  1840. %
  1841. The \key{run-tests.rkt} script in the support code checks whether the
  1842. output programs produce the same result as the input programs. The
  1843. script uses the \key{interp-tests} function
  1844. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1845. your \key{uniquify} pass on the example programs. The \code{passes}
  1846. parameter of \key{interp-tests} is a list that should have one entry
  1847. for each pass in your compiler. For now, define \code{passes} to
  1848. contain just one entry for \code{uniquify} as shown below.
  1849. \begin{lstlisting}
  1850. (define passes
  1851. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1852. \end{lstlisting}
  1853. Run the \key{run-tests.rkt} script in the support code to check
  1854. whether the output programs produce the same result as the input
  1855. programs.
  1856. \end{exercise}
  1857. \section{Remove Complex Operands}
  1858. \label{sec:remove-complex-opera-Rvar}
  1859. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  1860. into a restricted form in which the arguments of operations are atomic
  1861. expressions. Put another way, this pass removes complex
  1862. operands\index{subject}{complex operand}, such as the expression \code{(- 10)}
  1863. in the program below. This is accomplished by introducing a new
  1864. \key{let}-bound variable, binding the complex operand to the new
  1865. variable, and then using the new variable in place of the complex
  1866. operand, as shown in the output of \code{remove-complex-opera*} on the
  1867. right.\\
  1868. \begin{tabular}{lll}
  1869. \begin{minipage}{0.4\textwidth}
  1870. % var_test_19.rkt
  1871. \begin{lstlisting}
  1872. (+ 52 (- 10))
  1873. \end{lstlisting}
  1874. \end{minipage}
  1875. &
  1876. $\Rightarrow$
  1877. &
  1878. \begin{minipage}{0.4\textwidth}
  1879. \begin{lstlisting}
  1880. (let ([tmp.1 (- 10)])
  1881. (+ 52 tmp.1))
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \end{tabular}
  1885. \begin{figure}[tp]
  1886. \centering
  1887. \fbox{
  1888. \begin{minipage}{0.96\textwidth}
  1889. \[
  1890. \begin{array}{rcl}
  1891. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1892. \Exp &::=& \Atm \mid \READ{} \\
  1893. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1894. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1895. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1896. \end{array}
  1897. \]
  1898. \end{minipage}
  1899. }
  1900. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1901. \label{fig:r1-anf-syntax}
  1902. \end{figure}
  1903. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1904. this pass, the language \LangVarANF{}. The only difference is that
  1905. operator arguments are restricted to be atomic expressions that are
  1906. defined by the \Atm{} non-terminal. In particular, integer constants
  1907. and variables are atomic. In the literature, restricting arguments to
  1908. be atomic expressions is called \emph{administrative normal form}, or
  1909. ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1910. \index{subject}{administrative normal form} \index{subject}{ANF}
  1911. We recommend implementing this pass with two mutually recursive
  1912. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1913. \code{rco-atom} to subexpressions that need to become atomic and to
  1914. apply \code{rco-exp} to subexpressions that do not. Both functions
  1915. take an \LangVar{} expression as input. The \code{rco-exp} function
  1916. returns an expression. The \code{rco-atom} function returns two
  1917. things: an atomic expression and an alist mapping temporary variables to
  1918. complex subexpressions. You can return multiple things from a function
  1919. using Racket's \key{values} form and you can receive multiple things
  1920. from a function call using the \key{define-values} form. If you are
  1921. not familiar with these features, review the Racket documentation.
  1922. Also, the
  1923. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1924. form is useful for applying a function to each element of a list, in
  1925. the case where the function returns multiple values.
  1926. \index{subject}{for/lists}
  1927. Returning to the example program \code{(+ 52 (- 10))}, the
  1928. subexpression \code{(- 10)} should be processed using the
  1929. \code{rco-atom} function because it is an argument of the \code{+} and
  1930. therefore needs to become atomic. The output of \code{rco-atom}
  1931. applied to \code{(- 10)} is as follows.
  1932. \begin{tabular}{lll}
  1933. \begin{minipage}{0.4\textwidth}
  1934. \begin{lstlisting}
  1935. (- 10)
  1936. \end{lstlisting}
  1937. \end{minipage}
  1938. &
  1939. $\Rightarrow$
  1940. &
  1941. \begin{minipage}{0.4\textwidth}
  1942. \begin{lstlisting}
  1943. tmp.1
  1944. ((tmp.1 . (- 10)))
  1945. \end{lstlisting}
  1946. \end{minipage}
  1947. \end{tabular}
  1948. Take special care of programs such as the following one that binds a
  1949. variable to an atomic expression. You should leave such variable
  1950. bindings unchanged, as shown in to the program on the right \\
  1951. \begin{tabular}{lll}
  1952. \begin{minipage}{0.4\textwidth}
  1953. % var_test_20.rkt
  1954. \begin{lstlisting}
  1955. (let ([a 42])
  1956. (let ([b a])
  1957. b))
  1958. \end{lstlisting}
  1959. \end{minipage}
  1960. &
  1961. $\Rightarrow$
  1962. &
  1963. \begin{minipage}{0.4\textwidth}
  1964. \begin{lstlisting}
  1965. (let ([a 42])
  1966. (let ([b a])
  1967. b))
  1968. \end{lstlisting}
  1969. \end{minipage}
  1970. \end{tabular} \\
  1971. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1972. produce the following output with unnecessary temporary variables.\\
  1973. \begin{minipage}{0.4\textwidth}
  1974. \begin{lstlisting}
  1975. (let ([tmp.1 42])
  1976. (let ([a tmp.1])
  1977. (let ([tmp.2 a])
  1978. (let ([b tmp.2])
  1979. b))))
  1980. \end{lstlisting}
  1981. \end{minipage}
  1982. \begin{exercise}
  1983. \normalfont
  1984. Implement the \code{remove-complex-opera*} function in
  1985. \code{compiler.rkt}.
  1986. %
  1987. Create three new \LangVar{} programs that exercise the interesting
  1988. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  1989. regarding file names described in Exercise~\ref{ex:Rvar}.
  1990. %
  1991. In the \code{run-tests.rkt} script, add the following entry to the
  1992. list of \code{passes} and then run the script to test your compiler.
  1993. \begin{lstlisting}
  1994. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  1995. \end{lstlisting}
  1996. While debugging your compiler, it is often useful to see the
  1997. intermediate programs that are output from each pass. To print the
  1998. intermediate programs, place the \lstinline{(debug-level 1)} before the call to
  1999. \code{interp-tests} in \code{run-tests.rkt}.
  2000. \end{exercise}
  2001. \section{Explicate Control}
  2002. \label{sec:explicate-control-Rvar}
  2003. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2004. programs that make the order of execution explicit in their
  2005. syntax. For now this amounts to flattening \key{let} constructs into a
  2006. sequence of assignment statements. For example, consider the following
  2007. \LangVar{} program.\\
  2008. % var_test_11.rkt
  2009. \begin{minipage}{0.96\textwidth}
  2010. \begin{lstlisting}
  2011. (let ([y (let ([x 20])
  2012. (+ x (let ([x 22]) x)))])
  2013. y)
  2014. \end{lstlisting}
  2015. \end{minipage}\\
  2016. %
  2017. The output of the previous pass and of \code{explicate-control} is
  2018. shown below. Recall that the right-hand-side of a \key{let} executes
  2019. before its body, so the order of evaluation for this program is to
  2020. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2021. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2022. output of \code{explicate-control} makes this ordering explicit.\\
  2023. \begin{tabular}{lll}
  2024. \begin{minipage}{0.4\textwidth}
  2025. \begin{lstlisting}
  2026. (let ([y (let ([x.1 20])
  2027. (let ([x.2 22])
  2028. (+ x.1 x.2)))])
  2029. y)
  2030. \end{lstlisting}
  2031. \end{minipage}
  2032. &
  2033. $\Rightarrow$
  2034. &
  2035. \begin{minipage}{0.4\textwidth}
  2036. \begin{lstlisting}[language=C]
  2037. start:
  2038. x.1 = 20;
  2039. x.2 = 22;
  2040. y = (+ x.1 x.2);
  2041. return y;
  2042. \end{lstlisting}
  2043. \end{minipage}
  2044. \end{tabular}
  2045. \begin{figure}[tbp]
  2046. \begin{lstlisting}
  2047. (define (explicate-tail e)
  2048. (match e
  2049. [(Var x) ___]
  2050. [(Int n) (Return (Int n))]
  2051. [(Let x rhs body) ___]
  2052. [(Prim op es) ___]
  2053. [else (error "explicate-tail unhandled case" e)]))
  2054. (define (explicate-assign e x cont)
  2055. (match e
  2056. [(Var x) ___]
  2057. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2058. [(Let y rhs body) ___]
  2059. [(Prim op es) ___]
  2060. [else (error "explicate-assign unhandled case" e)]))
  2061. (define (explicate-control p)
  2062. (match p
  2063. [(Program info body) ___]))
  2064. \end{lstlisting}
  2065. \caption{Skeleton for the \key{explicate-control} pass.}
  2066. \label{fig:explicate-control-Rvar}
  2067. \end{figure}
  2068. The organization of this pass depends on the notion of tail position
  2069. that we have alluded to earlier. Formally, \emph{tail
  2070. position}\index{subject}{tail position} in the context of \LangVar{} is
  2071. defined recursively by the following two rules.
  2072. \begin{enumerate}
  2073. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2074. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2075. \end{enumerate}
  2076. We recommend implementing \code{explicate-control} using two mutually
  2077. recursive functions, \code{explicate-tail} and
  2078. \code{explicate-assign}, as suggested in the skeleton code in
  2079. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2080. function should be applied to expressions in tail position whereas the
  2081. \code{explicate-assign} should be applied to expressions that occur on
  2082. the right-hand-side of a \key{let}.
  2083. %
  2084. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2085. input and produces a \Tail{} in \LangCVar{} (see
  2086. Figure~\ref{fig:c0-syntax}).
  2087. %
  2088. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2089. the variable that it is to be assigned to, and a \Tail{} in
  2090. \LangCVar{} for the code that will come after the assignment. The
  2091. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2092. The \code{explicate-assign} function is in accumulator-passing style
  2093. in that the \code{cont} parameter is used for accumulating the
  2094. output. The reader might be tempted to instead organize
  2095. \code{explicate-assign} in a more direct fashion, without the
  2096. \code{cont} parameter and perhaps using \code{append} to combine
  2097. statements. We warn against that alternative because the
  2098. accumulator-passing style is key to how we generate high-quality code
  2099. for conditional expressions in Chapter~\ref{ch:Rif}.
  2100. \begin{exercise}\normalfont
  2101. %
  2102. Implement the \code{explicate-control} function in
  2103. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2104. exercise the code in \code{explicate-control}.
  2105. %
  2106. In the \code{run-tests.rkt} script, add the following entry to the
  2107. list of \code{passes} and then run the script to test your compiler.
  2108. \begin{lstlisting}
  2109. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2110. \end{lstlisting}
  2111. \end{exercise}
  2112. \section{Select Instructions}
  2113. \label{sec:select-Rvar}
  2114. \index{subject}{instruction selection}
  2115. In the \code{select-instructions} pass we begin the work of
  2116. translating from \LangCVar{} to \LangXVar{}. The target language of
  2117. this pass is a variant of x86 that still uses variables, so we add an
  2118. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2119. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2120. recommend implementing the \code{select-instructions} with
  2121. three auxiliary functions, one for each of the non-terminals of
  2122. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2123. The cases for $\Atm$ are straightforward; variables stay
  2124. the same and integer constants are changed to immediates:
  2125. $\INT{n}$ changes to $\IMM{n}$.
  2126. Next we consider the cases for $\Stmt$, starting with arithmetic
  2127. operations. For example, consider the addition operation. We can use
  2128. the \key{addq} instruction, but it performs an in-place update. So we
  2129. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2130. add $\itm{arg}_2$ to \itm{var}. \\
  2131. \begin{tabular}{lll}
  2132. \begin{minipage}{0.4\textwidth}
  2133. \begin{lstlisting}
  2134. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2135. \end{lstlisting}
  2136. \end{minipage}
  2137. &
  2138. $\Rightarrow$
  2139. &
  2140. \begin{minipage}{0.4\textwidth}
  2141. \begin{lstlisting}
  2142. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2143. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2144. \end{lstlisting}
  2145. \end{minipage}
  2146. \end{tabular} \\
  2147. %
  2148. There are also cases that require special care to avoid generating
  2149. needlessly complicated code. For example, if one of the arguments of
  2150. the addition is the same variable as the left-hand side of the
  2151. assignment, then there is no need for the extra move instruction. The
  2152. assignment statement can be translated into a single \key{addq}
  2153. instruction as follows.\\
  2154. \begin{tabular}{lll}
  2155. \begin{minipage}{0.4\textwidth}
  2156. \begin{lstlisting}
  2157. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2158. \end{lstlisting}
  2159. \end{minipage}
  2160. &
  2161. $\Rightarrow$
  2162. &
  2163. \begin{minipage}{0.4\textwidth}
  2164. \begin{lstlisting}
  2165. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2166. \end{lstlisting}
  2167. \end{minipage}
  2168. \end{tabular}
  2169. The \key{read} operation does not have a direct counterpart in x86
  2170. assembly, so we provide this functionality with the function
  2171. \code{read\_int} in the file \code{runtime.c}, written in
  2172. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2173. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2174. system}, or simply the \emph{runtime} for short. When compiling your
  2175. generated x86 assembly code, you need to compile \code{runtime.c} to
  2176. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2177. \code{-c}) and link it into the executable. For our purposes of code
  2178. generation, all you need to do is translate an assignment of
  2179. \key{read} into a call to the \code{read\_int} function followed by a
  2180. move from \code{rax} to the left-hand-side variable. (Recall that the
  2181. return value of a function goes into \code{rax}.) \\
  2182. \begin{tabular}{lll}
  2183. \begin{minipage}{0.3\textwidth}
  2184. \begin{lstlisting}
  2185. |$\itm{var}$| = (read);
  2186. \end{lstlisting}
  2187. \end{minipage}
  2188. &
  2189. $\Rightarrow$
  2190. &
  2191. \begin{minipage}{0.3\textwidth}
  2192. \begin{lstlisting}
  2193. callq read_int
  2194. movq %rax, |$\itm{var}$|
  2195. \end{lstlisting}
  2196. \end{minipage}
  2197. \end{tabular}
  2198. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2199. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2200. assignment to the \key{rax} register followed by a jump to the
  2201. conclusion of the program (so the conclusion needs to be labeled).
  2202. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2203. recursively and then append the resulting instructions.
  2204. \begin{exercise}
  2205. \normalfont Implement the \key{select-instructions} pass in
  2206. \code{compiler.rkt}. Create three new example programs that are
  2207. designed to exercise all of the interesting cases in this pass.
  2208. %
  2209. In the \code{run-tests.rkt} script, add the following entry to the
  2210. list of \code{passes} and then run the script to test your compiler.
  2211. \begin{lstlisting}
  2212. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2213. \end{lstlisting}
  2214. \end{exercise}
  2215. \section{Assign Homes}
  2216. \label{sec:assign-Rvar}
  2217. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2218. \LangXVar{} programs that no longer use program variables.
  2219. Thus, the \key{assign-homes} pass is responsible for placing all of
  2220. the program variables in registers or on the stack. For runtime
  2221. efficiency, it is better to place variables in registers, but as there
  2222. are only 16 registers, some programs must necessarily resort to
  2223. placing some variables on the stack. In this chapter we focus on the
  2224. mechanics of placing variables on the stack. We study an algorithm for
  2225. placing variables in registers in
  2226. Chapter~\ref{ch:register-allocation-Rvar}.
  2227. Consider again the following \LangVar{} program from
  2228. Section~\ref{sec:remove-complex-opera-Rvar}.
  2229. % var_test_20.rkt
  2230. \begin{lstlisting}
  2231. (let ([a 42])
  2232. (let ([b a])
  2233. b))
  2234. \end{lstlisting}
  2235. The output of \code{select-instructions} is shown on the left and the
  2236. output of \code{assign-homes} on the right. In this example, we
  2237. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2238. variable \code{b} to location \code{-16(\%rbp)}.\\
  2239. \begin{tabular}{l}
  2240. \begin{minipage}{0.4\textwidth}
  2241. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2242. locals-types:
  2243. a : Integer, b : Integer
  2244. start:
  2245. movq $42, a
  2246. movq a, b
  2247. movq b, %rax
  2248. jmp conclusion
  2249. \end{lstlisting}
  2250. \end{minipage}
  2251. {$\Rightarrow$}
  2252. \begin{minipage}{0.4\textwidth}
  2253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2254. stack-space: 16
  2255. start:
  2256. movq $42, -8(%rbp)
  2257. movq -8(%rbp), -16(%rbp)
  2258. movq -16(%rbp), %rax
  2259. jmp conclusion
  2260. \end{lstlisting}
  2261. \end{minipage}
  2262. \end{tabular}
  2263. The \code{locals-types} entry in the $\itm{info}$ of the
  2264. \code{X86Program} node is an alist mapping all the variables in the
  2265. program to their types (for now just \code{Integer}). The
  2266. \code{assign-homes} pass should replace all uses of those variables
  2267. with stack locations. As an aside, the \code{locals-types} entry is
  2268. computed by \code{type-check-Cvar} in the support code, which installs
  2269. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2270. be propagated to the \code{X86Program} node.
  2271. In the process of assigning variables to stack locations, it is
  2272. convenient for you to compute and store the size of the frame (in
  2273. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2274. the key \code{stack-space}, which is needed later to generate the
  2275. conclusion of the \code{main} procedure. The x86-64 standard requires
  2276. the frame size to be a multiple of 16 bytes.\index{subject}{frame}
  2277. \begin{exercise}\normalfont
  2278. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2279. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2280. \Block{}. We recommend that the auxiliary functions take an extra
  2281. parameter that is an alist mapping variable names to homes (stack
  2282. locations for now).
  2283. %
  2284. In the \code{run-tests.rkt} script, add the following entry to the
  2285. list of \code{passes} and then run the script to test your compiler.
  2286. \begin{lstlisting}
  2287. (list "assign homes" assign-homes interp-x86-0)
  2288. \end{lstlisting}
  2289. \end{exercise}
  2290. \section{Patch Instructions}
  2291. \label{sec:patch-s0}
  2292. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2293. \LangXInt{} by making sure that each instruction adheres to the
  2294. restriction that at most one argument of an instruction may be a
  2295. memory reference.
  2296. We return to the following example.
  2297. % var_test_20.rkt
  2298. \begin{lstlisting}
  2299. (let ([a 42])
  2300. (let ([b a])
  2301. b))
  2302. \end{lstlisting}
  2303. The \key{assign-homes} pass produces the following output
  2304. for this program. \\
  2305. \begin{minipage}{0.5\textwidth}
  2306. \begin{lstlisting}
  2307. stack-space: 16
  2308. start:
  2309. movq $42, -8(%rbp)
  2310. movq -8(%rbp), -16(%rbp)
  2311. movq -16(%rbp), %rax
  2312. jmp conclusion
  2313. \end{lstlisting}
  2314. \end{minipage}\\
  2315. The second \key{movq} instruction is problematic because both
  2316. arguments are stack locations. We suggest fixing this problem by
  2317. moving from the source location to the register \key{rax} and then
  2318. from \key{rax} to the destination location, as follows.
  2319. \begin{lstlisting}
  2320. movq -8(%rbp), %rax
  2321. movq %rax, -16(%rbp)
  2322. \end{lstlisting}
  2323. \begin{exercise}
  2324. \normalfont Implement the \key{patch-instructions} pass in
  2325. \code{compiler.rkt}. Create three new example programs that are
  2326. designed to exercise all of the interesting cases in this pass.
  2327. %
  2328. In the \code{run-tests.rkt} script, add the following entry to the
  2329. list of \code{passes} and then run the script to test your compiler.
  2330. \begin{lstlisting}
  2331. (list "patch instructions" patch-instructions interp-x86-0)
  2332. \end{lstlisting}
  2333. \end{exercise}
  2334. \section{Print x86}
  2335. \label{sec:print-x86}
  2336. The last step of the compiler from \LangVar{} to x86 is to convert the
  2337. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2338. string representation (defined in
  2339. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2340. \key{string-append} functions are useful in this regard. The main work
  2341. that this step needs to perform is to create the \key{main} function
  2342. and the standard instructions for its prelude and conclusion, as shown
  2343. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2344. know the amount of space needed for the stack frame, which you can
  2345. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2346. the \key{X86Program} node.
  2347. When running on Mac OS X, you compiler should prefix an underscore to
  2348. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2349. useful for determining which operating system the compiler is running
  2350. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2351. \begin{exercise}\normalfont
  2352. %
  2353. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2354. %
  2355. In the \code{run-tests.rkt} script, add the following entry to the
  2356. list of \code{passes} and then run the script to test your compiler.
  2357. \begin{lstlisting}
  2358. (list "print x86" print-x86 #f)
  2359. \end{lstlisting}
  2360. %
  2361. Uncomment the call to the \key{compiler-tests} function
  2362. (Appendix~\ref{appendix:utilities}), which tests your complete
  2363. compiler by executing the generated x86 code. Compile the provided
  2364. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2365. script to test your compiler.
  2366. \end{exercise}
  2367. \section{Challenge: Partial Evaluator for \LangVar{}}
  2368. \label{sec:pe-Rvar}
  2369. \index{subject}{partial evaluation}
  2370. This section describes optional challenge exercises that involve
  2371. adapting and improving the partial evaluator for \LangInt{} that was
  2372. introduced in Section~\ref{sec:partial-evaluation}.
  2373. \begin{exercise}\label{ex:pe-Rvar}
  2374. \normalfont
  2375. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2376. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2377. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2378. and variables to the \LangInt{} language, so you will need to add cases for
  2379. them in the \code{pe-exp} function. Once complete, add the partial
  2380. evaluation pass to the front of your compiler and make sure that your
  2381. compiler still passes all of the tests.
  2382. \end{exercise}
  2383. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2384. \begin{exercise}
  2385. \normalfont
  2386. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2387. \code{pe-add} auxiliary functions with functions that know more about
  2388. arithmetic. For example, your partial evaluator should translate
  2389. \[
  2390. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2391. \code{(+ 2 (read))}
  2392. \]
  2393. To accomplish this, the \code{pe-exp} function should produce output
  2394. in the form of the $\itm{residual}$ non-terminal of the following
  2395. grammar. The idea is that when processing an addition expression, we
  2396. can always produce either 1) an integer constant, 2) an addition
  2397. expression with an integer constant on the left-hand side but not the
  2398. right-hand side, or 3) or an addition expression in which neither
  2399. subexpression is a constant.
  2400. \[
  2401. \begin{array}{lcl}
  2402. \itm{inert} &::=& \Var
  2403. \mid \LP\key{read}\RP
  2404. \mid \LP\key{-} \;\Var\RP
  2405. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2406. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2407. &\mid& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  2408. \itm{residual} &::=& \Int
  2409. \mid \LP\key{+}\; \Int\; \itm{inert}\RP
  2410. \mid \itm{inert}
  2411. \end{array}
  2412. \]
  2413. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2414. inputs are $\itm{residual}$ expressions and they should return
  2415. $\itm{residual}$ expressions. Once the improvements are complete,
  2416. make sure that your compiler still passes all of the tests. After
  2417. all, fast code is useless if it produces incorrect results!
  2418. \end{exercise}
  2419. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2420. \chapter{Register Allocation}
  2421. \label{ch:register-allocation-Rvar}
  2422. \index{subject}{register allocation}
  2423. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2424. stack. In this Chapter we learn how to improve the performance of the
  2425. generated code by placing some variables into registers. The CPU can
  2426. access a register in a single cycle, whereas accessing the stack can
  2427. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2428. serves as a running example. The source program is on the left and the
  2429. output of instruction selection is on the right. The program is almost
  2430. in the x86 assembly language but it still uses variables.
  2431. \begin{figure}
  2432. \begin{minipage}{0.45\textwidth}
  2433. Example \LangVar{} program:
  2434. % var_test_28.rkt
  2435. \begin{lstlisting}
  2436. (let ([v 1])
  2437. (let ([w 42])
  2438. (let ([x (+ v 7)])
  2439. (let ([y x])
  2440. (let ([z (+ x w)])
  2441. (+ z (- y)))))))
  2442. \end{lstlisting}
  2443. \end{minipage}
  2444. \begin{minipage}{0.45\textwidth}
  2445. After instruction selection:
  2446. \begin{lstlisting}
  2447. locals-types:
  2448. x : Integer, y : Integer,
  2449. z : Integer, t : Integer,
  2450. v : Integer, w : Integer
  2451. start:
  2452. movq $1, v
  2453. movq $42, w
  2454. movq v, x
  2455. addq $7, x
  2456. movq x, y
  2457. movq x, z
  2458. addq w, z
  2459. movq y, t
  2460. negq t
  2461. movq z, %rax
  2462. addq t, %rax
  2463. jmp conclusion
  2464. \end{lstlisting}
  2465. \end{minipage}
  2466. \caption{A running example for register allocation.}
  2467. \label{fig:reg-eg}
  2468. \end{figure}
  2469. The goal of register allocation is to fit as many variables into
  2470. registers as possible. Some programs have more variables than
  2471. registers so we cannot always map each variable to a different
  2472. register. Fortunately, it is common for different variables to be
  2473. needed during different periods of time during program execution, and
  2474. in such cases several variables can be mapped to the same register.
  2475. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2476. After the variable \code{x} is moved to \code{z} it is no longer
  2477. needed. Variable \code{z}, on the other hand, is used only after this
  2478. point, so \code{x} and \code{z} could share the same register. The
  2479. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2480. where a variable is needed. Once we have that information, we compute
  2481. which variables are needed at the same time, i.e., which ones
  2482. \emph{interfere} with each other, and represent this relation as an
  2483. undirected graph whose vertices are variables and edges indicate when
  2484. two variables interfere (Section~\ref{sec:build-interference}). We
  2485. then model register allocation as a graph coloring problem
  2486. (Section~\ref{sec:graph-coloring}).
  2487. If we run out of registers despite these efforts, we place the
  2488. remaining variables on the stack, similar to what we did in
  2489. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2490. for assigning a variable to a stack location. The decision to spill a
  2491. variable is handled as part of the graph coloring process
  2492. (Section~\ref{sec:graph-coloring}).
  2493. We make the simplifying assumption that each variable is assigned to
  2494. one location (a register or stack address). A more sophisticated
  2495. approach is to assign a variable to one or more locations in different
  2496. regions of the program. For example, if a variable is used many times
  2497. in short sequence and then only used again after many other
  2498. instructions, it could be more efficient to assign the variable to a
  2499. register during the initial sequence and then move it to the stack for
  2500. the rest of its lifetime. We refer the interested reader to
  2501. \citet{Cooper:2011aa} for more information about that approach.
  2502. % discuss prioritizing variables based on how much they are used.
  2503. \section{Registers and Calling Conventions}
  2504. \label{sec:calling-conventions}
  2505. \index{subject}{calling conventions}
  2506. As we perform register allocation, we need to be aware of the
  2507. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  2508. functions calls are performed in x86.
  2509. %
  2510. Even though \LangVar{} does not include programmer-defined functions,
  2511. our generated code includes a \code{main} function that is called by
  2512. the operating system and our generated code contains calls to the
  2513. \code{read\_int} function.
  2514. Function calls require coordination between two pieces of code that
  2515. may be written by different programmers or generated by different
  2516. compilers. Here we follow the System V calling conventions that are
  2517. used by the GNU C compiler on Linux and
  2518. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2519. %
  2520. The calling conventions include rules about how functions share the
  2521. use of registers. In particular, the caller is responsible for freeing
  2522. up some registers prior to the function call for use by the callee.
  2523. These are called the \emph{caller-saved registers}
  2524. \index{subject}{caller-saved registers}
  2525. and they are
  2526. \begin{lstlisting}
  2527. rax rcx rdx rsi rdi r8 r9 r10 r11
  2528. \end{lstlisting}
  2529. On the other hand, the callee is responsible for preserving the values
  2530. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  2531. which are
  2532. \begin{lstlisting}
  2533. rsp rbp rbx r12 r13 r14 r15
  2534. \end{lstlisting}
  2535. We can think about this caller/callee convention from two points of
  2536. view, the caller view and the callee view:
  2537. \begin{itemize}
  2538. \item The caller should assume that all the caller-saved registers get
  2539. overwritten with arbitrary values by the callee. On the other hand,
  2540. the caller can safely assume that all the callee-saved registers
  2541. contain the same values after the call that they did before the
  2542. call.
  2543. \item The callee can freely use any of the caller-saved registers.
  2544. However, if the callee wants to use a callee-saved register, the
  2545. callee must arrange to put the original value back in the register
  2546. prior to returning to the caller. This can be accomplished by saving
  2547. the value to the stack in the prelude of the function and restoring
  2548. the value in the conclusion of the function.
  2549. \end{itemize}
  2550. In x86, registers are also used for passing arguments to a function
  2551. and for the return value. In particular, the first six arguments to a
  2552. function are passed in the following six registers, in this order.
  2553. \begin{lstlisting}
  2554. rdi rsi rdx rcx r8 r9
  2555. \end{lstlisting}
  2556. If there are more than six arguments, then the convention is to use
  2557. space on the frame of the caller for the rest of the
  2558. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2559. need more than six arguments. For now, the only function we care about
  2560. is \code{read\_int} and it takes zero arguments.
  2561. %
  2562. The register \code{rax} is used for the return value of a function.
  2563. The next question is how these calling conventions impact register
  2564. allocation. Consider the \LangVar{} program in
  2565. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2566. example from the caller point of view and then from the callee point
  2567. of view.
  2568. The program makes two calls to the \code{read} function. Also, the
  2569. variable \code{x} is in use during the second call to \code{read}, so
  2570. we need to make sure that the value in \code{x} does not get
  2571. accidentally wiped out by the call to \code{read}. One obvious
  2572. approach is to save all the values in caller-saved registers to the
  2573. stack prior to each function call, and restore them after each
  2574. call. That way, if the register allocator chooses to assign \code{x}
  2575. to a caller-saved register, its value will be preserved across the
  2576. call to \code{read}. However, saving and restoring to the stack is
  2577. relatively slow. If \code{x} is not used many times, it may be better
  2578. to assign \code{x} to a stack location in the first place. Or better
  2579. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2580. register, then it won't need to be saved and restored during function
  2581. calls.
  2582. The approach that we recommend for variables that are in use during a
  2583. function call is to either assign them to callee-saved registers or to
  2584. spill them to the stack. On the other hand, for variables that are not
  2585. in use during a function call, we try the following alternatives in
  2586. order 1) look for an available caller-saved register (to leave room
  2587. for other variables in the callee-saved register), 2) look for a
  2588. callee-saved register, and 3) spill the variable to the stack.
  2589. It is straightforward to implement this approach in a graph coloring
  2590. register allocator. First, we know which variables are in use during
  2591. every function call because we compute that information for every
  2592. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2593. build the interference graph (Section~\ref{sec:build-interference}),
  2594. we can place an edge between each of these variables and the
  2595. caller-saved registers in the interference graph. This will prevent
  2596. the graph coloring algorithm from assigning those variables to
  2597. caller-saved registers.
  2598. Returning to the example in
  2599. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2600. generated x86 code on the right-hand side, focusing on the
  2601. \code{start} block. Notice that variable \code{x} is assigned to
  2602. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2603. place during the second call to \code{read\_int}. Next, notice that
  2604. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2605. because there are no function calls in the remainder of the block.
  2606. Next we analyze the example from the callee point of view, focusing on
  2607. the prelude and conclusion of the \code{main} function. As usual the
  2608. prelude begins with saving the \code{rbp} register to the stack and
  2609. setting the \code{rbp} to the current stack pointer. We now know why
  2610. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2611. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2612. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2613. (\code{x}). The other callee-saved registers are not saved in the
  2614. prelude because they are not used. The prelude subtracts 8 bytes from
  2615. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2616. \code{start} block. Shifting attention to the \code{conclusion}, we
  2617. see that \code{rbx} is restored from the stack with a \code{popq}
  2618. instruction. \index{subject}{prelude}\index{subject}{conclusion}
  2619. \begin{figure}[tp]
  2620. \begin{minipage}{0.45\textwidth}
  2621. Example \LangVar{} program:
  2622. %var_test_14.rkt
  2623. \begin{lstlisting}
  2624. (let ([x (read)])
  2625. (let ([y (read)])
  2626. (+ (+ x y) 42)))
  2627. \end{lstlisting}
  2628. \end{minipage}
  2629. \begin{minipage}{0.45\textwidth}
  2630. Generated x86 assembly:
  2631. \begin{lstlisting}
  2632. start:
  2633. callq read_int
  2634. movq %rax, %rbx
  2635. callq read_int
  2636. movq %rax, %rcx
  2637. addq %rcx, %rbx
  2638. movq %rbx, %rax
  2639. addq $42, %rax
  2640. jmp _conclusion
  2641. .globl main
  2642. main:
  2643. pushq %rbp
  2644. movq %rsp, %rbp
  2645. pushq %rbx
  2646. subq $8, %rsp
  2647. jmp start
  2648. conclusion:
  2649. addq $8, %rsp
  2650. popq %rbx
  2651. popq %rbp
  2652. retq
  2653. \end{lstlisting}
  2654. \end{minipage}
  2655. \caption{An example with function calls.}
  2656. \label{fig:example-calling-conventions}
  2657. \end{figure}
  2658. \clearpage
  2659. \section{Liveness Analysis}
  2660. \label{sec:liveness-analysis-Rvar}
  2661. \index{subject}{liveness analysis}
  2662. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2663. is, it discovers which variables are in-use in different regions of a
  2664. program.
  2665. %
  2666. A variable or register is \emph{live} at a program point if its
  2667. current value is used at some later point in the program. We
  2668. refer to variables and registers collectively as \emph{locations}.
  2669. %
  2670. Consider the following code fragment in which there are two writes to
  2671. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2672. \begin{center}
  2673. \begin{minipage}{0.96\textwidth}
  2674. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2675. movq $5, a
  2676. movq $30, b
  2677. movq a, c
  2678. movq $10, b
  2679. addq b, c
  2680. \end{lstlisting}
  2681. \end{minipage}
  2682. \end{center}
  2683. The answer is no because \code{a} is live from line 1 to 3 and
  2684. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2685. line 2 is never used because it is overwritten (line 4) before the
  2686. next read (line 5).
  2687. \begin{wrapfigure}[19]{l}[0.9in]{0.55\textwidth}
  2688. \small
  2689. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2690. A \emph{set} is an unordered collection of elements without duplicates.
  2691. \index{subject}{set}
  2692. \begin{description}
  2693. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2694. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2695. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2696. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2697. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2698. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2699. \end{description}
  2700. \end{tcolorbox}
  2701. \end{wrapfigure}
  2702. The live locations can be computed by traversing the instruction
  2703. sequence back to front (i.e., backwards in execution order). Let
  2704. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2705. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2706. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2707. locations before instruction $I_k$. The live locations after an
  2708. instruction are always the same as the live locations before the next
  2709. instruction. \index{subject}{live-after} \index{subject}{live-before}
  2710. \begin{equation} \label{eq:live-after-before-next}
  2711. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2712. \end{equation}
  2713. To start things off, there are no live locations after the last
  2714. instruction, so
  2715. \begin{equation}\label{eq:live-last-empty}
  2716. L_{\mathsf{after}}(n) = \emptyset
  2717. \end{equation}
  2718. We then apply the following rule repeatedly, traversing the
  2719. instruction sequence back to front.
  2720. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2721. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2722. \end{equation}
  2723. where $W(k)$ are the locations written to by instruction $I_k$ and
  2724. $R(k)$ are the locations read by instruction $I_k$.
  2725. There is a special case for \code{jmp} instructions. The locations
  2726. that are live before a \code{jmp} should be the locations in
  2727. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2728. maintaining an alist named \code{label->live} that maps each label to
  2729. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2730. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2731. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2732. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2733. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2734. Let us walk through the above example, applying these formulas
  2735. starting with the instruction on line 5. We collect the answers in
  2736. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2737. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2738. instruction (formula~\ref{eq:live-last-empty}). The
  2739. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2740. because it reads from variables \code{b} and \code{c}
  2741. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2742. \[
  2743. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2744. \]
  2745. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2746. the live-before set from line 5 to be the live-after set for this
  2747. instruction (formula~\ref{eq:live-after-before-next}).
  2748. \[
  2749. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2750. \]
  2751. This move instruction writes to \code{b} and does not read from any
  2752. variables, so we have the following live-before set
  2753. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2754. \[
  2755. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2756. \]
  2757. The live-before for instruction \code{movq a, c}
  2758. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2759. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2760. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2761. variable that is not live and does not read from a variable.
  2762. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2763. because it writes to variable \code{a}.
  2764. \begin{figure}[tbp]
  2765. \begin{minipage}{0.45\textwidth}
  2766. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2767. movq $5, a
  2768. movq $30, b
  2769. movq a, c
  2770. movq $10, b
  2771. addq b, c
  2772. \end{lstlisting}
  2773. \end{minipage}
  2774. \vrule\hspace{10pt}
  2775. \begin{minipage}{0.45\textwidth}
  2776. \begin{align*}
  2777. L_{\mathsf{before}}(1)= \emptyset,
  2778. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2779. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2780. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2781. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2782. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2783. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2784. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2785. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2786. L_{\mathsf{after}}(5)= \emptyset
  2787. \end{align*}
  2788. \end{minipage}
  2789. \caption{Example output of liveness analysis on a short example.}
  2790. \label{fig:liveness-example-0}
  2791. \end{figure}
  2792. \begin{exercise}\normalfont
  2793. Perform liveness analysis on the running example in
  2794. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2795. sets for each instruction. Compare your answers to the solution
  2796. shown in Figure~\ref{fig:live-eg}.
  2797. \end{exercise}
  2798. \begin{figure}[tp]
  2799. \hspace{20pt}
  2800. \begin{minipage}{0.45\textwidth}
  2801. \begin{lstlisting}
  2802. |$\{\ttm{rsp}\}$|
  2803. movq $1, v
  2804. |$\{\ttm{v},\ttm{rsp}\}$|
  2805. movq $42, w
  2806. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2807. movq v, x
  2808. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2809. addq $7, x
  2810. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2811. movq x, y
  2812. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2813. movq x, z
  2814. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2815. addq w, z
  2816. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2817. movq y, t
  2818. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2819. negq t
  2820. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2821. movq z, %rax
  2822. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2823. addq t, %rax
  2824. |$\{\ttm{rax},\ttm{rsp}\}$|
  2825. jmp conclusion
  2826. \end{lstlisting}
  2827. \end{minipage}
  2828. \caption{The running example annotated with live-after sets.}
  2829. \label{fig:live-eg}
  2830. \end{figure}
  2831. \begin{exercise}\normalfont
  2832. Implement the \code{uncover-live} pass. Store the sequence of
  2833. live-after sets in the $\itm{info}$ field of the \code{Block}
  2834. structure.
  2835. %
  2836. We recommend creating an auxiliary function that takes a list of
  2837. instructions and an initial live-after set (typically empty) and
  2838. returns the list of live-after sets.
  2839. %
  2840. We also recommend creating auxiliary functions to 1) compute the set
  2841. of locations that appear in an \Arg{}, 2) compute the locations read
  2842. by an instruction (the $R$ function), and 3) the locations written by
  2843. an instruction (the $W$ function). The \code{callq} instruction should
  2844. include all of the caller-saved registers in its write-set $W$ because
  2845. the calling convention says that those registers may be written to
  2846. during the function call. Likewise, the \code{callq} instruction
  2847. should include the appropriate argument-passing registers in its
  2848. read-set $R$, depending on the arity of the function being
  2849. called. (This is why the abstract syntax for \code{callq} includes the
  2850. arity.)
  2851. \end{exercise}
  2852. \clearpage
  2853. \section{Build the Interference Graph}
  2854. \label{sec:build-interference}
  2855. \begin{wrapfigure}[25]{r}[0.9in]{0.55\textwidth}
  2856. \small
  2857. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2858. A \emph{graph} is a collection of vertices and edges where each
  2859. edge connects two vertices. A graph is \emph{directed} if each
  2860. edge points from a source to a target. Otherwise the graph is
  2861. \emph{undirected}.
  2862. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  2863. \begin{description}
  2864. %% We currently don't use directed graphs. We instead use
  2865. %% directed multi-graphs. -Jeremy
  2866. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2867. %% directed graph from a list of edges. Each edge is a list
  2868. %% containing the source and target vertex.
  2869. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2870. undirected graph from a list of edges. Each edge is represented by
  2871. a list containing two vertices.
  2872. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2873. inserts a vertex into the graph.
  2874. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2875. inserts an edge between the two vertices into the graph.
  2876. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2877. returns a sequence of all the neighbors of the given vertex.
  2878. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2879. returns a sequence of all the vertices in the graph.
  2880. \end{description}
  2881. \end{tcolorbox}
  2882. \end{wrapfigure}
  2883. Based on the liveness analysis, we know where each location is live.
  2884. However, during register allocation, we need to answer questions of
  2885. the specific form: are locations $u$ and $v$ live at the same time?
  2886. (And therefore cannot be assigned to the same register.) To make this
  2887. question more efficient to answer, we create an explicit data
  2888. structure, an \emph{interference graph}\index{subject}{interference graph}. An
  2889. interference graph is an undirected graph that has an edge between two
  2890. locations if they are live at the same time, that is, if they
  2891. interfere with each other.
  2892. An obvious way to compute the interference graph is to look at the set
  2893. of live locations between each instruction and the next and add an edge to the graph
  2894. for every pair of variables in the same set. This approach is less
  2895. than ideal for two reasons. First, it can be expensive because it
  2896. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2897. locations. Second, in the special case where two locations hold the
  2898. same value (because one was assigned to the other), they can be live
  2899. at the same time without interfering with each other.
  2900. A better way to compute the interference graph is to focus on
  2901. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2902. must not overwrite something in a live location. So for each
  2903. instruction, we create an edge between the locations being written to
  2904. and the live locations. (Except that one should not create self
  2905. edges.) Note that for the \key{callq} instruction, we consider all of
  2906. the caller-saved registers as being written to, so an edge is added
  2907. between every live variable and every caller-saved register. For
  2908. \key{movq}, we deal with the above-mentioned special case by not
  2909. adding an edge between a live variable $v$ and the destination if $v$
  2910. matches the source. So we have the following two rules.
  2911. \begin{enumerate}
  2912. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2913. $d$, then add the edge $(d,v)$ for every $v \in
  2914. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2915. \item For any other instruction $I_k$, for every $d \in W(k)$
  2916. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2917. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2918. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2919. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2920. %% \item If instruction $I_k$ is of the form \key{callq}
  2921. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2922. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2923. \end{enumerate}
  2924. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2925. the above rules to each instruction. We highlight a few of the
  2926. instructions. The first instruction is \lstinline{movq $1, v} and the
  2927. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2928. interferes with \code{rsp}.
  2929. %
  2930. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2931. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2932. interferes with \ttm{w} and \ttm{rsp}.
  2933. %
  2934. The next instruction is \lstinline{movq x, y} and the live-after set
  2935. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2936. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2937. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2938. same value. Figure~\ref{fig:interference-results} lists the
  2939. interference results for all of the instructions and the resulting
  2940. interference graph is shown in Figure~\ref{fig:interfere}.
  2941. \begin{figure}[tbp]
  2942. \begin{quote}
  2943. \begin{tabular}{ll}
  2944. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2945. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2946. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2947. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2948. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2949. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2950. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2951. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2952. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2953. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2954. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2955. \lstinline!jmp conclusion!& no interference.
  2956. \end{tabular}
  2957. \end{quote}
  2958. \caption{Interference results for the running example.}
  2959. \label{fig:interference-results}
  2960. \end{figure}
  2961. \begin{figure}[tbp]
  2962. \large
  2963. \[
  2964. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2965. \node (rax) at (0,0) {$\ttm{rax}$};
  2966. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2967. \node (t1) at (0,2) {$\ttm{t}$};
  2968. \node (z) at (3,2) {$\ttm{z}$};
  2969. \node (x) at (6,2) {$\ttm{x}$};
  2970. \node (y) at (3,0) {$\ttm{y}$};
  2971. \node (w) at (6,0) {$\ttm{w}$};
  2972. \node (v) at (9,0) {$\ttm{v}$};
  2973. \draw (t1) to (rax);
  2974. \draw (t1) to (z);
  2975. \draw (z) to (y);
  2976. \draw (z) to (w);
  2977. \draw (x) to (w);
  2978. \draw (y) to (w);
  2979. \draw (v) to (w);
  2980. \draw (v) to (rsp);
  2981. \draw (w) to (rsp);
  2982. \draw (x) to (rsp);
  2983. \draw (y) to (rsp);
  2984. \path[-.,bend left=15] (z) edge node {} (rsp);
  2985. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2986. \draw (rax) to (rsp);
  2987. \end{tikzpicture}
  2988. \]
  2989. \caption{The interference graph of the example program.}
  2990. \label{fig:interfere}
  2991. \end{figure}
  2992. %% Our next concern is to choose a data structure for representing the
  2993. %% interference graph. There are many choices for how to represent a
  2994. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2995. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2996. %% data structure is to study the algorithm that uses the data structure,
  2997. %% determine what operations need to be performed, and then choose the
  2998. %% data structure that provide the most efficient implementations of
  2999. %% those operations. Often times the choice of data structure can have an
  3000. %% effect on the time complexity of the algorithm, as it does here. If
  3001. %% you skim the next section, you will see that the register allocation
  3002. %% algorithm needs to ask the graph for all of its vertices and, given a
  3003. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3004. %% correct choice of graph representation is that of an adjacency
  3005. %% list. There are helper functions in \code{utilities.rkt} for
  3006. %% representing graphs using the adjacency list representation:
  3007. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3008. %% (Appendix~\ref{appendix:utilities}).
  3009. %% %
  3010. %% \margincomment{\footnotesize To do: change to use the
  3011. %% Racket graph library. \\ --Jeremy}
  3012. %% %
  3013. %% In particular, those functions use a hash table to map each vertex to
  3014. %% the set of adjacent vertices, and the sets are represented using
  3015. %% Racket's \key{set}, which is also a hash table.
  3016. \begin{exercise}\normalfont
  3017. Implement the compiler pass named \code{build-interference} according
  3018. to the algorithm suggested above. We recommend using the \code{graph}
  3019. package to create and inspect the interference graph. The output
  3020. graph of this pass should be stored in the $\itm{info}$ field of the
  3021. program, under the key \code{conflicts}.
  3022. \end{exercise}
  3023. \section{Graph Coloring via Sudoku}
  3024. \label{sec:graph-coloring}
  3025. \index{subject}{graph coloring}
  3026. \index{subject}{Sudoku}
  3027. \index{subject}{color}
  3028. We come to the main event, mapping variables to registers and stack
  3029. locations. Variables that interfere with each other must be mapped to
  3030. different locations. In terms of the interference graph, this means
  3031. that adjacent vertices must be mapped to different locations. If we
  3032. think of locations as colors, the register allocation problem becomes
  3033. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3034. The reader may be more familiar with the graph coloring problem than he
  3035. or she realizes; the popular game of Sudoku is an instance of the
  3036. graph coloring problem. The following describes how to build a graph
  3037. out of an initial Sudoku board.
  3038. \begin{itemize}
  3039. \item There is one vertex in the graph for each Sudoku square.
  3040. \item There is an edge between two vertices if the corresponding squares
  3041. are in the same row, in the same column, or if the squares are in
  3042. the same $3\times 3$ region.
  3043. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3044. \item Based on the initial assignment of numbers to squares in the
  3045. Sudoku board, assign the corresponding colors to the corresponding
  3046. vertices in the graph.
  3047. \end{itemize}
  3048. If you can color the remaining vertices in the graph with the nine
  3049. colors, then you have also solved the corresponding game of Sudoku.
  3050. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3051. the corresponding graph with colored vertices. We map the Sudoku
  3052. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3053. sampling of the vertices (the colored ones) because showing edges for
  3054. all of the vertices would make the graph unreadable.
  3055. \begin{figure}[tbp]
  3056. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3057. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3058. \caption{A Sudoku game board and the corresponding colored graph.}
  3059. \label{fig:sudoku-graph}
  3060. \end{figure}
  3061. It turns out that some techniques for playing Sudoku correspond to
  3062. heuristics used in graph coloring algorithms. For example, one of the
  3063. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3064. a process of elimination to determine what numbers are no longer
  3065. available for a square and write down those numbers in the square
  3066. (writing very small). For example, if the number $1$ is assigned to a
  3067. square, then write the pencil mark $1$ in all the squares in the same
  3068. row, column, and region.
  3069. %
  3070. The Pencil Marks technique corresponds to the notion of
  3071. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  3072. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3073. are no longer available. In graph terminology, we have the following
  3074. definition:
  3075. \begin{equation*}
  3076. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3077. \text{ and } \mathrm{color}(v) = c \}
  3078. \end{equation*}
  3079. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3080. edge with $u$.
  3081. Using the Pencil Marks technique leads to a simple strategy for
  3082. filling in numbers: if there is a square with only one possible number
  3083. left, then choose that number! But what if there are no squares with
  3084. only one possibility left? One brute-force approach is to try them
  3085. all: choose the first one and if it ultimately leads to a solution,
  3086. great. If not, backtrack and choose the next possibility. One good
  3087. thing about Pencil Marks is that it reduces the degree of branching in
  3088. the search tree. Nevertheless, backtracking can be horribly time
  3089. consuming. One way to reduce the amount of backtracking is to use the
  3090. most-constrained-first heuristic. That is, when choosing a square,
  3091. always choose one with the fewest possibilities left (the vertex with
  3092. the highest saturation). The idea is that choosing highly constrained
  3093. squares earlier rather than later is better because later on there may
  3094. not be any possibilities left in the highly saturated squares.
  3095. However, register allocation is easier than Sudoku because the
  3096. register allocator can map variables to stack locations when the
  3097. registers run out. Thus, it makes sense to replace backtracking with
  3098. greedy search: make the best choice at the time and keep going. We
  3099. still wish to minimize the number of colors needed, so we use the
  3100. most-constrained-first heuristic in the greedy search.
  3101. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3102. algorithm for register allocation based on saturation and the
  3103. most-constrained-first heuristic. It is roughly equivalent to the
  3104. DSATUR
  3105. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3106. as in Sudoku, the algorithm represents colors with integers. The
  3107. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3108. for register allocation. The integers $k$ and larger correspond to
  3109. stack locations. The registers that are not used for register
  3110. allocation, such as \code{rax}, are assigned to negative integers. In
  3111. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3112. %% One might wonder why we include registers at all in the liveness
  3113. %% analysis and interference graph. For example, we never allocate a
  3114. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3115. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3116. %% to use register for passing arguments to functions, it will be
  3117. %% necessary for those registers to appear in the interference graph
  3118. %% because those registers will also be assigned to variables, and we
  3119. %% don't want those two uses to encroach on each other. Regarding
  3120. %% registers such as \code{rax} and \code{rsp} that are not used for
  3121. %% variables, we could omit them from the interference graph but that
  3122. %% would require adding special cases to our algorithm, which would
  3123. %% complicate the logic for little gain.
  3124. \begin{figure}[btp]
  3125. \centering
  3126. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3127. Algorithm: DSATUR
  3128. Input: a graph |$G$|
  3129. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3130. |$W \gets \mathrm{vertices}(G)$|
  3131. while |$W \neq \emptyset$| do
  3132. pick a vertex |$u$| from |$W$| with the highest saturation,
  3133. breaking ties randomly
  3134. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3135. |$\mathrm{color}[u] \gets c$|
  3136. |$W \gets W - \{u\}$|
  3137. \end{lstlisting}
  3138. \caption{The saturation-based greedy graph coloring algorithm.}
  3139. \label{fig:satur-algo}
  3140. \end{figure}
  3141. With the DSATUR algorithm in hand, let us return to the running
  3142. example and consider how to color the interference graph in
  3143. Figure~\ref{fig:interfere}.
  3144. %
  3145. We start by assigning the register nodes to their own color. For
  3146. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3147. assigned $-2$. The variables are not yet colored, so they are
  3148. annotated with a dash. We then update the saturation for vertices that
  3149. are adjacent to a register, obtaining the following annotated
  3150. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3151. it interferes with both \code{rax} and \code{rsp}.
  3152. \[
  3153. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3154. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3155. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3156. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3157. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3158. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3159. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3160. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3161. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3162. \draw (t1) to (rax);
  3163. \draw (t1) to (z);
  3164. \draw (z) to (y);
  3165. \draw (z) to (w);
  3166. \draw (x) to (w);
  3167. \draw (y) to (w);
  3168. \draw (v) to (w);
  3169. \draw (v) to (rsp);
  3170. \draw (w) to (rsp);
  3171. \draw (x) to (rsp);
  3172. \draw (y) to (rsp);
  3173. \path[-.,bend left=15] (z) edge node {} (rsp);
  3174. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3175. \draw (rax) to (rsp);
  3176. \end{tikzpicture}
  3177. \]
  3178. The algorithm says to select a maximally saturated vertex. So we pick
  3179. $\ttm{t}$ and color it with the first available integer, which is
  3180. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3181. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3182. \[
  3183. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3184. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3185. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3186. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3187. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3188. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3189. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3190. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3191. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3192. \draw (t1) to (rax);
  3193. \draw (t1) to (z);
  3194. \draw (z) to (y);
  3195. \draw (z) to (w);
  3196. \draw (x) to (w);
  3197. \draw (y) to (w);
  3198. \draw (v) to (w);
  3199. \draw (v) to (rsp);
  3200. \draw (w) to (rsp);
  3201. \draw (x) to (rsp);
  3202. \draw (y) to (rsp);
  3203. \path[-.,bend left=15] (z) edge node {} (rsp);
  3204. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3205. \draw (rax) to (rsp);
  3206. \end{tikzpicture}
  3207. \]
  3208. We repeat the process, selecting the next maximally saturated vertex,
  3209. which is \code{z}, and color it with the first available number, which
  3210. is $1$. We add $1$ to the saturation for the neighboring vertices
  3211. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3212. \[
  3213. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3214. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3215. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3216. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3217. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3218. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3219. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3220. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3221. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3222. \draw (t1) to (rax);
  3223. \draw (t1) to (z);
  3224. \draw (z) to (y);
  3225. \draw (z) to (w);
  3226. \draw (x) to (w);
  3227. \draw (y) to (w);
  3228. \draw (v) to (w);
  3229. \draw (v) to (rsp);
  3230. \draw (w) to (rsp);
  3231. \draw (x) to (rsp);
  3232. \draw (y) to (rsp);
  3233. \path[-.,bend left=15] (z) edge node {} (rsp);
  3234. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3235. \draw (rax) to (rsp);
  3236. \end{tikzpicture}
  3237. \]
  3238. The most saturated vertices are now \code{w} and \code{y}. We color
  3239. \code{w} with the first available color, which is $0$.
  3240. \[
  3241. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3242. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3243. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3244. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3245. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3246. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3247. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3248. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3249. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3250. \draw (t1) to (rax);
  3251. \draw (t1) to (z);
  3252. \draw (z) to (y);
  3253. \draw (z) to (w);
  3254. \draw (x) to (w);
  3255. \draw (y) to (w);
  3256. \draw (v) to (w);
  3257. \draw (v) to (rsp);
  3258. \draw (w) to (rsp);
  3259. \draw (x) to (rsp);
  3260. \draw (y) to (rsp);
  3261. \path[-.,bend left=15] (z) edge node {} (rsp);
  3262. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3263. \draw (rax) to (rsp);
  3264. \end{tikzpicture}
  3265. \]
  3266. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3267. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3268. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3269. and \code{z}, whose colors are $0$ and $1$ respectively.
  3270. \[
  3271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3272. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3273. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3274. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3275. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3276. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3277. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3278. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3279. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3280. \draw (t1) to (rax);
  3281. \draw (t1) to (z);
  3282. \draw (z) to (y);
  3283. \draw (z) to (w);
  3284. \draw (x) to (w);
  3285. \draw (y) to (w);
  3286. \draw (v) to (w);
  3287. \draw (v) to (rsp);
  3288. \draw (w) to (rsp);
  3289. \draw (x) to (rsp);
  3290. \draw (y) to (rsp);
  3291. \path[-.,bend left=15] (z) edge node {} (rsp);
  3292. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3293. \draw (rax) to (rsp);
  3294. \end{tikzpicture}
  3295. \]
  3296. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3297. \[
  3298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3299. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3300. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3301. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3302. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3303. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3304. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3305. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3306. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3307. \draw (t1) to (rax);
  3308. \draw (t1) to (z);
  3309. \draw (z) to (y);
  3310. \draw (z) to (w);
  3311. \draw (x) to (w);
  3312. \draw (y) to (w);
  3313. \draw (v) to (w);
  3314. \draw (v) to (rsp);
  3315. \draw (w) to (rsp);
  3316. \draw (x) to (rsp);
  3317. \draw (y) to (rsp);
  3318. \path[-.,bend left=15] (z) edge node {} (rsp);
  3319. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3320. \draw (rax) to (rsp);
  3321. \end{tikzpicture}
  3322. \]
  3323. In the last step of the algorithm, we color \code{x} with $1$.
  3324. \[
  3325. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3326. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3327. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3328. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3329. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3330. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3331. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3332. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3333. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3334. \draw (t1) to (rax);
  3335. \draw (t1) to (z);
  3336. \draw (z) to (y);
  3337. \draw (z) to (w);
  3338. \draw (x) to (w);
  3339. \draw (y) to (w);
  3340. \draw (v) to (w);
  3341. \draw (v) to (rsp);
  3342. \draw (w) to (rsp);
  3343. \draw (x) to (rsp);
  3344. \draw (y) to (rsp);
  3345. \path[-.,bend left=15] (z) edge node {} (rsp);
  3346. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3347. \draw (rax) to (rsp);
  3348. \end{tikzpicture}
  3349. \]
  3350. \begin{wrapfigure}[25]{r}[0.9in]{0.55\textwidth}
  3351. \small
  3352. \begin{tcolorbox}[title=Priority Queue]
  3353. A \emph{priority queue} is a collection of items in which the
  3354. removal of items is governed by priority. In a ``min'' queue,
  3355. lower priority items are removed first. An implementation is in
  3356. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  3357. queue} \index{subject}{minimum priority queue}
  3358. \begin{description}
  3359. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3360. priority queue that uses the $\itm{cmp}$ predicate to determine
  3361. whether its first argument has lower or equal priority to its
  3362. second argument.
  3363. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3364. items in the queue.
  3365. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3366. the item into the queue and returns a handle for the item in the
  3367. queue.
  3368. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3369. the lowest priority.
  3370. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3371. notifies the queue that the priority has decreased for the item
  3372. associated with the given handle.
  3373. \end{description}
  3374. \end{tcolorbox}
  3375. \end{wrapfigure}
  3376. We recommend creating an auxiliary function named \code{color-graph}
  3377. that takes an interference graph and a list of all the variables in
  3378. the program. This function should return a mapping of variables to
  3379. their colors (represented as natural numbers). By creating this helper
  3380. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3381. when we add support for functions.
  3382. To prioritize the processing of highly saturated nodes inside the
  3383. \code{color-graph} function, we recommend using the priority queue
  3384. data structure (see the side bar on the right). In addition, you will
  3385. need to maintain a mapping from variables to their ``handles'' in the
  3386. priority queue so that you can notify the priority queue when their
  3387. saturation changes.
  3388. With the coloring complete, we finalize the assignment of variables to
  3389. registers and stack locations. We map the first $k$ colors to the $k$
  3390. registers and the rest of the colors to stack locations. Suppose for
  3391. the moment that we have just one register to use for register
  3392. allocation, \key{rcx}. Then we have the following map from colors to
  3393. locations.
  3394. \[
  3395. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3396. \]
  3397. Composing this mapping with the coloring, we arrive at the following
  3398. assignment of variables to locations.
  3399. \begin{gather*}
  3400. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3401. \ttm{w} \mapsto \key{\%rcx}, \,
  3402. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3403. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3404. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3405. \ttm{t} \mapsto \key{\%rcx} \}
  3406. \end{gather*}
  3407. Adapt the code from the \code{assign-homes} pass
  3408. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3409. assigned location. Applying the above assignment to our running
  3410. example, on the left, yields the program on the right.
  3411. % why frame size of 32? -JGS
  3412. \begin{center}
  3413. \begin{minipage}{0.3\textwidth}
  3414. \begin{lstlisting}
  3415. movq $1, v
  3416. movq $42, w
  3417. movq v, x
  3418. addq $7, x
  3419. movq x, y
  3420. movq x, z
  3421. addq w, z
  3422. movq y, t
  3423. negq t
  3424. movq z, %rax
  3425. addq t, %rax
  3426. jmp conclusion
  3427. \end{lstlisting}
  3428. \end{minipage}
  3429. $\Rightarrow\qquad$
  3430. \begin{minipage}{0.45\textwidth}
  3431. \begin{lstlisting}
  3432. movq $1, -8(%rbp)
  3433. movq $42, %rcx
  3434. movq -8(%rbp), -8(%rbp)
  3435. addq $7, -8(%rbp)
  3436. movq -8(%rbp), -16(%rbp)
  3437. movq -8(%rbp), -8(%rbp)
  3438. addq %rcx, -8(%rbp)
  3439. movq -16(%rbp), %rcx
  3440. negq %rcx
  3441. movq -8(%rbp), %rax
  3442. addq %rcx, %rax
  3443. jmp conclusion
  3444. \end{lstlisting}
  3445. \end{minipage}
  3446. \end{center}
  3447. \begin{exercise}\normalfont
  3448. %
  3449. Implement the compiler pass \code{allocate-registers}.
  3450. %
  3451. Create five programs that exercise all of the register allocation
  3452. algorithm, including spilling variables to the stack.
  3453. %
  3454. Replace \code{assign-homes} in the list of \code{passes} in the
  3455. \code{run-tests.rkt} script with the three new passes:
  3456. \code{uncover-live}, \code{build-interference}, and
  3457. \code{allocate-registers}.
  3458. %
  3459. Temporarily remove the \code{print-x86} pass from the list of passes
  3460. and the call to \code{compiler-tests}.
  3461. %
  3462. Run the script to test the register allocator.
  3463. \end{exercise}
  3464. \section{Patch Instructions}
  3465. \label{sec:patch-instructions}
  3466. The remaining step in the compilation to x86 is to ensure that the
  3467. instructions have at most one argument that is a memory access.
  3468. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3469. is problematic. The fix is to first move \code{-8(\%rbp)}
  3470. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3471. %
  3472. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3473. problematic, but they can be fixed by simply deleting them. In
  3474. general, we recommend deleting all the trivial moves whose source and
  3475. destination are the same location.
  3476. %
  3477. The following is the output of \code{patch-instructions} on the
  3478. running example.
  3479. \begin{center}
  3480. \begin{minipage}{0.4\textwidth}
  3481. \begin{lstlisting}
  3482. movq $1, -8(%rbp)
  3483. movq $42, %rcx
  3484. movq -8(%rbp), -8(%rbp)
  3485. addq $7, -8(%rbp)
  3486. movq -8(%rbp), -16(%rbp)
  3487. movq -8(%rbp), -8(%rbp)
  3488. addq %rcx, -8(%rbp)
  3489. movq -16(%rbp), %rcx
  3490. negq %rcx
  3491. movq -8(%rbp), %rax
  3492. addq %rcx, %rax
  3493. jmp conclusion
  3494. \end{lstlisting}
  3495. \end{minipage}
  3496. $\Rightarrow\qquad$
  3497. \begin{minipage}{0.45\textwidth}
  3498. \begin{lstlisting}
  3499. movq $1, -8(%rbp)
  3500. movq $42, %rcx
  3501. addq $7, -8(%rbp)
  3502. movq -8(%rbp), %rax
  3503. movq %rax, -16(%rbp)
  3504. addq %rcx, -8(%rbp)
  3505. movq -16(%rbp), %rcx
  3506. negq %rcx
  3507. movq -8(%rbp), %rax
  3508. addq %rcx, %rax
  3509. jmp conclusion
  3510. \end{lstlisting}
  3511. \end{minipage}
  3512. \end{center}
  3513. \begin{exercise}\normalfont
  3514. %
  3515. Implement the \code{patch-instructions} compiler pass.
  3516. %
  3517. Insert it after \code{allocate-registers} in the list of \code{passes}
  3518. in the \code{run-tests.rkt} script.
  3519. %
  3520. Run the script to test the \code{patch-instructions} pass.
  3521. \end{exercise}
  3522. \section{Print x86}
  3523. \label{sec:print-x86-reg-alloc}
  3524. \index{subject}{calling conventions}
  3525. \index{subject}{prelude}\index{subject}{conclusion}
  3526. Recall that the \code{print-x86} pass generates the prelude and
  3527. conclusion instructions to satisfy the x86 calling conventions
  3528. (Section~\ref{sec:calling-conventions}). With the addition of the
  3529. register allocator, the callee-saved registers used by the register
  3530. allocator must be saved in the prelude and restored in the conclusion.
  3531. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3532. of \code{X86Program} named \code{used-callee} that stores the set of
  3533. callee-saved registers that were assigned to variables. The
  3534. \code{print-x86} pass can then access this information to decide which
  3535. callee-saved registers need to be saved and restored.
  3536. %
  3537. When calculating the size of the frame to adjust the \code{rsp} in the
  3538. prelude, make sure to take into account the space used for saving the
  3539. callee-saved registers. Also, don't forget that the frame needs to be
  3540. a multiple of 16 bytes!
  3541. An overview of all of the passes involved in register allocation is
  3542. shown in Figure~\ref{fig:reg-alloc-passes}.
  3543. \begin{figure}[tbp]
  3544. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3545. \node (Rvar) at (0,2) {\large \LangVar{}};
  3546. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3547. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3548. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3549. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3550. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3551. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3552. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3553. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3554. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3555. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3556. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3557. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3558. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3559. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3560. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3561. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3562. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3563. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3564. \end{tikzpicture}
  3565. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3566. \label{fig:reg-alloc-passes}
  3567. \end{figure}
  3568. \begin{exercise}\normalfont
  3569. Update the \code{print-x86} pass as described in this section.
  3570. %
  3571. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3572. list of passes and the call to \code{compiler-tests}.
  3573. %
  3574. Run the script to test the complete compiler for \LangVar{} that
  3575. performs register allocation.
  3576. \end{exercise}
  3577. \section{Challenge: Move Biasing}
  3578. \label{sec:move-biasing}
  3579. \index{subject}{move biasing}
  3580. This section describes an enhancement to the register allocator for
  3581. students looking for an extra challenge or who have a deeper interest
  3582. in register allocation.
  3583. To motivate the need for move biasing we return to the running example
  3584. but this time use all of the general purpose registers. So we have
  3585. the following mapping of color numbers to registers.
  3586. \[
  3587. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3588. \]
  3589. Using the same assignment of variables to color numbers that was
  3590. produced by the register allocator described in the last section, we
  3591. get the following program.
  3592. \begin{center}
  3593. \begin{minipage}{0.3\textwidth}
  3594. \begin{lstlisting}
  3595. movq $1, v
  3596. movq $42, w
  3597. movq v, x
  3598. addq $7, x
  3599. movq x, y
  3600. movq x, z
  3601. addq w, z
  3602. movq y, t
  3603. negq t
  3604. movq z, %rax
  3605. addq t, %rax
  3606. jmp conclusion
  3607. \end{lstlisting}
  3608. \end{minipage}
  3609. $\Rightarrow\qquad$
  3610. \begin{minipage}{0.45\textwidth}
  3611. \begin{lstlisting}
  3612. movq $1, %rdx
  3613. movq $42, %rcx
  3614. movq %rdx, %rdx
  3615. addq $7, %rdx
  3616. movq %rdx, %rsi
  3617. movq %rdx, %rdx
  3618. addq %rcx, %rdx
  3619. movq %rsi, %rcx
  3620. negq %rcx
  3621. movq %rdx, %rax
  3622. addq %rcx, %rax
  3623. jmp conclusion
  3624. \end{lstlisting}
  3625. \end{minipage}
  3626. \end{center}
  3627. In the above output code there are two \key{movq} instructions that
  3628. can be removed because their source and target are the same. However,
  3629. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3630. register, we could instead remove three \key{movq} instructions. We
  3631. can accomplish this by taking into account which variables appear in
  3632. \key{movq} instructions with which other variables.
  3633. We say that two variables $p$ and $q$ are \emph{move
  3634. related}\index{subject}{move related} if they participate together in a
  3635. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3636. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3637. for a variable, it should prefer a color that has already been used
  3638. for a move-related variable (assuming that they do not interfere). Of
  3639. course, this preference should not override the preference for
  3640. registers over stack locations. This preference should be used as a
  3641. tie breaker when choosing between registers or when choosing between
  3642. stack locations.
  3643. We recommend representing the move relationships in a graph, similar
  3644. to how we represented interference. The following is the \emph{move
  3645. graph} for our running example.
  3646. \[
  3647. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3648. \node (rax) at (0,0) {$\ttm{rax}$};
  3649. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3650. \node (t) at (0,2) {$\ttm{t}$};
  3651. \node (z) at (3,2) {$\ttm{z}$};
  3652. \node (x) at (6,2) {$\ttm{x}$};
  3653. \node (y) at (3,0) {$\ttm{y}$};
  3654. \node (w) at (6,0) {$\ttm{w}$};
  3655. \node (v) at (9,0) {$\ttm{v}$};
  3656. \draw (v) to (x);
  3657. \draw (x) to (y);
  3658. \draw (x) to (z);
  3659. \draw (y) to (t);
  3660. \end{tikzpicture}
  3661. \]
  3662. Now we replay the graph coloring, pausing to see the coloring of
  3663. \code{y}. Recall the following configuration. The most saturated vertices
  3664. were \code{w} and \code{y}.
  3665. \[
  3666. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3667. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3668. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3669. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3670. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3671. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3672. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3673. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3674. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3675. \draw (t1) to (rax);
  3676. \draw (t1) to (z);
  3677. \draw (z) to (y);
  3678. \draw (z) to (w);
  3679. \draw (x) to (w);
  3680. \draw (y) to (w);
  3681. \draw (v) to (w);
  3682. \draw (v) to (rsp);
  3683. \draw (w) to (rsp);
  3684. \draw (x) to (rsp);
  3685. \draw (y) to (rsp);
  3686. \path[-.,bend left=15] (z) edge node {} (rsp);
  3687. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3688. \draw (rax) to (rsp);
  3689. \end{tikzpicture}
  3690. \]
  3691. %
  3692. Last time we chose to color \code{w} with $0$. But this time we see
  3693. that \code{w} is not move related to any vertex, but \code{y} is move
  3694. related to \code{t}. So we choose to color \code{y} the same color as
  3695. \code{t}, $0$.
  3696. \[
  3697. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3698. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3699. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3700. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3701. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3702. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3703. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3704. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3705. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3706. \draw (t1) to (rax);
  3707. \draw (t1) to (z);
  3708. \draw (z) to (y);
  3709. \draw (z) to (w);
  3710. \draw (x) to (w);
  3711. \draw (y) to (w);
  3712. \draw (v) to (w);
  3713. \draw (v) to (rsp);
  3714. \draw (w) to (rsp);
  3715. \draw (x) to (rsp);
  3716. \draw (y) to (rsp);
  3717. \path[-.,bend left=15] (z) edge node {} (rsp);
  3718. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3719. \draw (rax) to (rsp);
  3720. \end{tikzpicture}
  3721. \]
  3722. Now \code{w} is the most saturated, so we color it $2$.
  3723. \[
  3724. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3725. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3726. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3727. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3728. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3729. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3730. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3731. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3732. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3733. \draw (t1) to (rax);
  3734. \draw (t1) to (z);
  3735. \draw (z) to (y);
  3736. \draw (z) to (w);
  3737. \draw (x) to (w);
  3738. \draw (y) to (w);
  3739. \draw (v) to (w);
  3740. \draw (v) to (rsp);
  3741. \draw (w) to (rsp);
  3742. \draw (x) to (rsp);
  3743. \draw (y) to (rsp);
  3744. \path[-.,bend left=15] (z) edge node {} (rsp);
  3745. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3746. \draw (rax) to (rsp);
  3747. \end{tikzpicture}
  3748. \]
  3749. At this point, vertices \code{x} and \code{v} are most saturated, but
  3750. \code{x} is move related to \code{y} and \code{z}, so we color
  3751. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3752. \[
  3753. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3754. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3755. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3756. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3757. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3758. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3759. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3760. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3761. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3762. \draw (t1) to (rax);
  3763. \draw (t) to (z);
  3764. \draw (z) to (y);
  3765. \draw (z) to (w);
  3766. \draw (x) to (w);
  3767. \draw (y) to (w);
  3768. \draw (v) to (w);
  3769. \draw (v) to (rsp);
  3770. \draw (w) to (rsp);
  3771. \draw (x) to (rsp);
  3772. \draw (y) to (rsp);
  3773. \path[-.,bend left=15] (z) edge node {} (rsp);
  3774. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3775. \draw (rax) to (rsp);
  3776. \end{tikzpicture}
  3777. \]
  3778. So we have the following assignment of variables to registers.
  3779. \begin{gather*}
  3780. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3781. \ttm{w} \mapsto \key{\%rsi}, \,
  3782. \ttm{x} \mapsto \key{\%rcx}, \,
  3783. \ttm{y} \mapsto \key{\%rcx}, \,
  3784. \ttm{z} \mapsto \key{\%rdx}, \,
  3785. \ttm{t} \mapsto \key{\%rcx} \}
  3786. \end{gather*}
  3787. We apply this register assignment to the running example, on the left,
  3788. to obtain the code in the middle. The \code{patch-instructions} then
  3789. removes the three trivial moves to obtain the code on the right.
  3790. \begin{minipage}{0.25\textwidth}
  3791. \begin{lstlisting}
  3792. movq $1, v
  3793. movq $42, w
  3794. movq v, x
  3795. addq $7, x
  3796. movq x, y
  3797. movq x, z
  3798. addq w, z
  3799. movq y, t
  3800. negq t
  3801. movq z, %rax
  3802. addq t, %rax
  3803. jmp conclusion
  3804. \end{lstlisting}
  3805. \end{minipage}
  3806. $\Rightarrow\qquad$
  3807. \begin{minipage}{0.25\textwidth}
  3808. \begin{lstlisting}
  3809. movq $1, %rcx
  3810. movq $42, %rsi
  3811. movq %rcx, %rcx
  3812. addq $7, %rcx
  3813. movq %rcx, %rcx
  3814. movq %rcx, %rdx
  3815. addq %rsi, %rdx
  3816. movq %rcx, %rcx
  3817. negq %rcx
  3818. movq %rdx, %rax
  3819. addq %rcx, %rax
  3820. jmp conclusion
  3821. \end{lstlisting}
  3822. \end{minipage}
  3823. $\Rightarrow\qquad$
  3824. \begin{minipage}{0.25\textwidth}
  3825. \begin{lstlisting}
  3826. movq $1, %rcx
  3827. movq $42, %rsi
  3828. addq $7, %rcx
  3829. movq %rcx, %rdx
  3830. addq %rsi, %rdx
  3831. negq %rcx
  3832. movq %rdx, %rax
  3833. addq %rcx, %rax
  3834. jmp conclusion
  3835. \end{lstlisting}
  3836. \end{minipage}
  3837. \begin{exercise}\normalfont
  3838. Change your implementation of \code{allocate-registers} to take move
  3839. biasing into account. Create two new tests that include at least one
  3840. opportunity for move biasing and visually inspect the output x86
  3841. programs to make sure that your move biasing is working properly. Make
  3842. sure that your compiler still passes all of the tests.
  3843. \end{exercise}
  3844. %To do: another neat challenge would be to do
  3845. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  3846. %% \subsection{Output of the Running Example}
  3847. %% \label{sec:reg-alloc-output}
  3848. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3849. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3850. and move biasing. To demonstrate both the use of registers and the
  3851. stack, we have limited the register allocator to use just two
  3852. registers: \code{rbx} and \code{rcx}. In the prelude\index{subject}{prelude}
  3853. of the \code{main} function, we push \code{rbx} onto the stack because
  3854. it is a callee-saved register and it was assigned to variable by the
  3855. register allocator. We subtract \code{8} from the \code{rsp} at the
  3856. end of the prelude to reserve space for the one spilled variable.
  3857. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3858. Moving on the the \code{start} block, we see how the registers were
  3859. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3860. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3861. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3862. that the prelude saved the callee-save register \code{rbx} onto the
  3863. stack. The spilled variables must be placed lower on the stack than
  3864. the saved callee-save registers, so in this case \code{w} is placed at
  3865. \code{-16(\%rbp)}.
  3866. In the \code{conclusion}\index{subject}{conclusion}, we undo the work that was
  3867. done in the prelude. We move the stack pointer up by \code{8} bytes
  3868. (the room for spilled variables), then we pop the old values of
  3869. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3870. \code{retq} to return control to the operating system.
  3871. \begin{figure}[tbp]
  3872. % var_test_28.rkt
  3873. % (use-minimal-set-of-registers! #t)
  3874. % and only rbx rcx
  3875. % tmp 0 rbx
  3876. % z 1 rcx
  3877. % y 0 rbx
  3878. % w 2 16(%rbp)
  3879. % v 0 rbx
  3880. % x 0 rbx
  3881. \begin{lstlisting}
  3882. start:
  3883. movq $1, %rbx
  3884. movq $42, -16(%rbp)
  3885. addq $7, %rbx
  3886. movq %rbx, %rcx
  3887. addq -16(%rbp), %rcx
  3888. negq %rbx
  3889. movq %rcx, %rax
  3890. addq %rbx, %rax
  3891. jmp conclusion
  3892. .globl main
  3893. main:
  3894. pushq %rbp
  3895. movq %rsp, %rbp
  3896. pushq %rbx
  3897. subq $8, %rsp
  3898. jmp start
  3899. conclusion:
  3900. addq $8, %rsp
  3901. popq %rbx
  3902. popq %rbp
  3903. retq
  3904. \end{lstlisting}
  3905. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3906. \label{fig:running-example-x86}
  3907. \end{figure}
  3908. % challenge: prioritize variables based on execution frequencies
  3909. % and the number of uses of a variable
  3910. % challenge: enhance the coloring algorithm using Chaitin's
  3911. % approach of prioritizing high-degree variables
  3912. % by removing low-degree variables (coloring them later)
  3913. % from the interference graph
  3914. \section{Further Reading}
  3915. \label{sec:register-allocation-further-reading}
  3916. Early register allocation algorithms were developed for Fortran
  3917. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3918. of graph coloring began in the late 1970s and early 1980s with the
  3919. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3920. algorithm is based on the following observation of
  3921. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3922. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3923. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3924. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3925. different colors, but since there are less than $k$ of them, there
  3926. will be one or more colors left over to use for coloring $v$ in $G$.
  3927. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3928. less than $k$ from the graph and recursively colors the rest of the
  3929. graph. Upon returning from the recursion, it colors $v$ with one of
  3930. the available colors and returns. \citet{Chaitin:1982vn} augments
  3931. this algorithm to handle spilling as follows. If there are no vertices
  3932. of degree lower than $k$ then pick a vertex at random, spill it,
  3933. remove it from the graph, and proceed recursively to color the rest of
  3934. the graph.
  3935. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3936. move-related and that don't interfere with each other, a process
  3937. called \emph{coalescing}. While coalescing decreases the number of
  3938. moves, it can make the graph more difficult to
  3939. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3940. which two variables are merged only if they have fewer than $k$
  3941. neighbors of high degree. \citet{George:1996aa} observe that
  3942. conservative coalescing is sometimes too conservative and make it more
  3943. aggressive by iterating the coalescing with the removal of low-degree
  3944. vertices.
  3945. %
  3946. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3947. also propose \emph{biased coloring} in which a variable is assigned to
  3948. the same color as another move-related variable if possible, as
  3949. discussed in Section~\ref{sec:move-biasing}.
  3950. %
  3951. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3952. performs coalescing, graph coloring, and spill code insertion until
  3953. all variables have been assigned a location.
  3954. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  3955. spills variables that don't have to be: a high-degree variable can be
  3956. colorable if many of its neighbors are assigned the same color.
  3957. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  3958. high-degree vertex is not immediately spilled. Instead the decision is
  3959. deferred until after the recursive call, at which point it is apparent
  3960. whether there is actually an available color or not. We observe that
  3961. this algorithm is equivalent to the smallest-last ordering
  3962. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  3963. be registers and the rest to be stack locations.
  3964. %% biased coloring
  3965. Earlier editions of the compiler course at Indiana University
  3966. \citep{Dybvig:2010aa} were based on the algorithm of
  3967. \citet{Briggs:1994kx}.
  3968. The smallest-last ordering algorithm is one of many \emph{greedy}
  3969. coloring algorithms. A greedy coloring algorithm visits all the
  3970. vertices in a particular order and assigns each one the first
  3971. available color. An \emph{offline} greedy algorithm chooses the
  3972. ordering up-front, prior to assigning colors. The algorithm of
  3973. \citet{Chaitin:1981vl} should be considered offline because the vertex
  3974. ordering does not depend on the colors assigned, so the algorithm
  3975. could be split into two phases. Other orderings are possible. For
  3976. example, \citet{Chow:1984ys} order variables according an estimate of
  3977. runtime cost.
  3978. An \emph{online} greedy coloring algorithm uses information about the
  3979. current assignment of colors to influence the order in which the
  3980. remaining vertices are colored. The saturation-based algorithm
  3981. described in this chapter is one such algorithm. We choose to use
  3982. saturation-based coloring is because it is fun to introduce graph
  3983. coloring via Sudoku.
  3984. A register allocator may choose to map each variable to just one
  3985. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  3986. variable to one or more locations. The later can be achieved by
  3987. \emph{live range splitting}, where a variable is replaced by several
  3988. variables that each handle part of its live
  3989. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  3990. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  3991. %% replacement algorithm, bottom-up local
  3992. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  3993. %% Cooper: top-down (priority bassed), bottom-up
  3994. %% top-down
  3995. %% order variables by priority (estimated cost)
  3996. %% caveat: split variables into two groups:
  3997. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  3998. %% color the constrained ones first
  3999. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4000. %% cite J. Cocke for an algorithm that colors variables
  4001. %% in a high-degree first ordering
  4002. %Register Allocation via Usage Counts, Freiburghouse CACM
  4003. \citet{Palsberg:2007si} observe that many of the interference graphs
  4004. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4005. that is, every cycle with four or more edges has an edge which is not
  4006. part of the cycle but which connects two vertices on the cycle. Such
  4007. graphs can be optimally colored by the greedy algorithm with a vertex
  4008. ordering determined by maximum cardinality search.
  4009. In situations where compile time is of utmost importance, such as in
  4010. just-in-time compilers, graph coloring algorithms can be too expensive
  4011. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4012. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4013. \chapter{Booleans and Control Flow}
  4014. \label{ch:Rif}
  4015. \index{subject}{Boolean}
  4016. \index{subject}{control flow}
  4017. \index{subject}{conditional expression}
  4018. The \LangInt{} and \LangVar{} languages only have a single kind of
  4019. value, integers. In this chapter we add a second kind of value, the
  4020. Booleans, to create the \LangIf{} language. The Boolean values
  4021. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4022. respectively in Racket. The \LangIf{} language includes several
  4023. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4024. \key{<}, etc.) and the conditional \key{if} expression. With the
  4025. addition of \key{if}, programs can have non-trivial control flow which
  4026. impacts \code{explicate-control} and liveness analysis. Also, because
  4027. we now have two kinds of values, we need to handle programs that apply
  4028. an operation to the wrong kind of value, such as \code{(not 1)}.
  4029. There are two language design options for such situations. One option
  4030. is to signal an error and the other is to provide a wider
  4031. interpretation of the operation. The Racket language uses a mixture of
  4032. these two options, depending on the operation and the kind of
  4033. value. For example, the result of \code{(not 1)} in Racket is
  4034. \code{\#f} because Racket treats non-zero integers as if they were
  4035. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4036. error in Racket because \code{car} expects a pair.
  4037. Typed Racket makes similar design choices as Racket, except much of
  4038. the error detection happens at compile time instead of run time. Typed
  4039. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4040. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4041. because Typed Racket expects the type of the argument to be of the
  4042. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4043. The \LangIf{} language performs type checking during compilation like
  4044. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4045. alternative choice, that is, a dynamically typed language like Racket.
  4046. The \LangIf{} language is a subset of Typed Racket; for some
  4047. operations we are more restrictive, for example, rejecting
  4048. \code{(not 1)}.
  4049. This chapter is organized as follows. We begin by defining the syntax
  4050. and interpreter for the \LangIf{} language
  4051. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4052. checking and build a type checker for \LangIf{}
  4053. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4054. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4055. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4056. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4057. discuss how our compiler passes change to accommodate Booleans and
  4058. conditional control flow. There is one new pass, named \code{shrink},
  4059. that translates some operators into others, thereby reducing the
  4060. number of operators that need to be handled in later passes. The
  4061. largest changes occur in \code{explicate-control}, to translate
  4062. \code{if} expressions into control-flow graphs
  4063. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4064. allocation, the liveness analysis now has multiple basic blocks to
  4065. process and there is the interesting question of how to handle
  4066. conditional jumps.
  4067. \section{The \LangIf{} Language}
  4068. \label{sec:lang-if}
  4069. The concrete syntax of the \LangIf{} language is defined in
  4070. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4071. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4072. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4073. \code{\#f}, and the conditional \code{if} expression. We expand the
  4074. operators to include
  4075. \begin{enumerate}
  4076. \item subtraction on integers,
  4077. \item the logical operators \key{and}, \key{or} and \key{not},
  4078. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4079. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4080. comparing integers.
  4081. \end{enumerate}
  4082. We reorganize the abstract syntax for the primitive operations in
  4083. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4084. them. This means that the grammar no longer checks whether the arity
  4085. of an operators matches the number of arguments. That responsibility
  4086. is moved to the type checker for \LangIf{}, which we introduce in
  4087. Section~\ref{sec:type-check-Rif}.
  4088. \begin{figure}[tp]
  4089. \centering
  4090. \fbox{
  4091. \begin{minipage}{0.96\textwidth}
  4092. \[
  4093. \begin{array}{lcl}
  4094. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4095. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4096. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4097. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4098. &\mid& \itm{bool}
  4099. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4100. \mid (\key{not}\;\Exp) \\
  4101. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4102. \LangIfM{} &::=& \Exp
  4103. \end{array}
  4104. \]
  4105. \end{minipage}
  4106. }
  4107. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4108. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4109. \label{fig:Rif-concrete-syntax}
  4110. \end{figure}
  4111. \begin{figure}[tp]
  4112. \centering
  4113. \fbox{
  4114. \begin{minipage}{0.96\textwidth}
  4115. \[
  4116. \begin{array}{lcl}
  4117. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4118. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4119. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4120. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4121. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4122. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4123. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4124. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4125. \end{array}
  4126. \]
  4127. \end{minipage}
  4128. }
  4129. \caption{The abstract syntax of \LangIf{}.}
  4130. \label{fig:Rif-syntax}
  4131. \end{figure}
  4132. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4133. which inherits from the interpreter for \LangVar{}
  4134. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4135. evaluate to the corresponding Boolean values. The conditional
  4136. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4137. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4138. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4139. operations \code{not} and \code{and} behave as you might expect, but
  4140. note that the \code{and} operation is short-circuiting. That is, given
  4141. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4142. evaluated if $e_1$ evaluates to \code{\#f}.
  4143. With the increase in the number of primitive operations, the
  4144. interpreter would become repetitive without some care. We refactor
  4145. the case for \code{Prim}, moving the code that differs with each
  4146. operation into the \code{interp-op} method shown in in
  4147. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4148. separately because of its short-circuiting behavior.
  4149. \begin{figure}[tbp]
  4150. \begin{lstlisting}
  4151. (define interp-Rif-class
  4152. (class interp-Rvar-class
  4153. (super-new)
  4154. (define/public (interp-op op) ...)
  4155. (define/override ((interp-exp env) e)
  4156. (define recur (interp-exp env))
  4157. (match e
  4158. [(Bool b) b]
  4159. [(If cnd thn els)
  4160. (match (recur cnd)
  4161. [#t (recur thn)]
  4162. [#f (recur els)])]
  4163. [(Prim 'and (list e1 e2))
  4164. (match (recur e1)
  4165. [#t (match (recur e2) [#t #t] [#f #f])]
  4166. [#f #f])]
  4167. [(Prim op args)
  4168. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4169. [else ((super interp-exp env) e)]))
  4170. ))
  4171. (define (interp-Rif p)
  4172. (send (new interp-Rif-class) interp-program p))
  4173. \end{lstlisting}
  4174. \caption{Interpreter for the \LangIf{} language. (See
  4175. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4176. \label{fig:interp-Rif}
  4177. \end{figure}
  4178. \begin{figure}[tbp]
  4179. \begin{lstlisting}
  4180. (define/public (interp-op op)
  4181. (match op
  4182. ['+ fx+]
  4183. ['- fx-]
  4184. ['read read-fixnum]
  4185. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4186. ['or (lambda (v1 v2)
  4187. (cond [(and (boolean? v1) (boolean? v2))
  4188. (or v1 v2)]))]
  4189. ['eq? (lambda (v1 v2)
  4190. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4191. (and (boolean? v1) (boolean? v2))
  4192. (and (vector? v1) (vector? v2)))
  4193. (eq? v1 v2)]))]
  4194. ['< (lambda (v1 v2)
  4195. (cond [(and (fixnum? v1) (fixnum? v2))
  4196. (< v1 v2)]))]
  4197. ['<= (lambda (v1 v2)
  4198. (cond [(and (fixnum? v1) (fixnum? v2))
  4199. (<= v1 v2)]))]
  4200. ['> (lambda (v1 v2)
  4201. (cond [(and (fixnum? v1) (fixnum? v2))
  4202. (> v1 v2)]))]
  4203. ['>= (lambda (v1 v2)
  4204. (cond [(and (fixnum? v1) (fixnum? v2))
  4205. (>= v1 v2)]))]
  4206. [else (error 'interp-op "unknown operator")]))
  4207. \end{lstlisting}
  4208. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4209. \label{fig:interp-op-Rif}
  4210. \end{figure}
  4211. \section{Type Checking \LangIf{} Programs}
  4212. \label{sec:type-check-Rif}
  4213. \index{subject}{type checking}
  4214. \index{subject}{semantic analysis}
  4215. It is helpful to think about type checking in two complementary
  4216. ways. A type checker predicts the type of value that will be produced
  4217. by each expression in the program. For \LangIf{}, we have just two types,
  4218. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4219. \begin{lstlisting}
  4220. (+ 10 (- (+ 12 20)))
  4221. \end{lstlisting}
  4222. produces an \key{Integer} while
  4223. \begin{lstlisting}
  4224. (and (not #f) #t)
  4225. \end{lstlisting}
  4226. produces a \key{Boolean}.
  4227. Another way to think about type checking is that it enforces a set of
  4228. rules about which operators can be applied to which kinds of
  4229. values. For example, our type checker for \LangIf{} signals an error
  4230. for the below expression
  4231. \begin{lstlisting}
  4232. (not (+ 10 (- (+ 12 20))))
  4233. \end{lstlisting}
  4234. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4235. but the type checker enforces the rule that the argument of \code{not}
  4236. must be a \key{Boolean}.
  4237. We implement type checking using classes and methods because they
  4238. provide the open recursion needed to reuse code as we extend the type
  4239. checker in later chapters, analogous to the use of classes and methods
  4240. for the interpreters (Section~\ref{sec:extensible-interp}).
  4241. We separate the type checker for the \LangVar{} fragment into its own
  4242. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4243. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4244. from the type checker for \LangVar{}. These type checkers are in the
  4245. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4246. support code.
  4247. %
  4248. Each type checker is a structurally recursive function over the AST.
  4249. Given an input expression \code{e}, the type checker either signals an
  4250. error or returns an expression and its type (\key{Integer} or
  4251. \key{Boolean}). It returns an expression because there are situations
  4252. in which we want to change or update the expression.
  4253. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4254. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4255. \code{Integer}. To handle variables, the type checker uses the
  4256. environment \code{env} to map variables to types. Consider the case
  4257. for \key{let}. We type check the initializing expression to obtain
  4258. its type \key{T} and then associate type \code{T} with the variable
  4259. \code{x} in the environment used to type check the body of the
  4260. \key{let}. Thus, when the type checker encounters a use of variable
  4261. \code{x}, it can find its type in the environment. Regarding
  4262. primitive operators, we recursively analyze the arguments and then
  4263. invoke \code{type-check-op} to check whether the argument types are
  4264. allowed.
  4265. Several auxiliary methods are used in the type checker. The method
  4266. \code{operator-types} defines a dictionary that maps the operator
  4267. names to their parameter and return types. The \code{type-equal?}
  4268. method determines whether two types are equal, which for now simply
  4269. dispatches to \code{equal?} (deep equality). The
  4270. \code{check-type-equal?} method triggers an error if the two types are
  4271. not equal. The \code{type-check-op} method looks up the operator in
  4272. the \code{operator-types} dictionary and then checks whether the
  4273. argument types are equal to the parameter types. The result is the
  4274. return type of the operator.
  4275. \begin{figure}[tbp]
  4276. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4277. (define type-check-Rvar-class
  4278. (class object%
  4279. (super-new)
  4280. (define/public (operator-types)
  4281. '((+ . ((Integer Integer) . Integer))
  4282. (- . ((Integer) . Integer))
  4283. (read . (() . Integer))))
  4284. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4285. (define/public (check-type-equal? t1 t2 e)
  4286. (unless (type-equal? t1 t2)
  4287. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4288. (define/public (type-check-op op arg-types e)
  4289. (match (dict-ref (operator-types) op)
  4290. [`(,param-types . ,return-type)
  4291. (for ([at arg-types] [pt param-types])
  4292. (check-type-equal? at pt e))
  4293. return-type]
  4294. [else (error 'type-check-op "unrecognized ~a" op)]))
  4295. (define/public (type-check-exp env)
  4296. (lambda (e)
  4297. (match e
  4298. [(Int n) (values (Int n) 'Integer)]
  4299. [(Var x) (values (Var x) (dict-ref env x))]
  4300. [(Let x e body)
  4301. (define-values (e^ Te) ((type-check-exp env) e))
  4302. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4303. (values (Let x e^ b) Tb)]
  4304. [(Prim op es)
  4305. (define-values (new-es ts)
  4306. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4307. (values (Prim op new-es) (type-check-op op ts e))]
  4308. [else (error 'type-check-exp "couldn't match" e)])))
  4309. (define/public (type-check-program e)
  4310. (match e
  4311. [(Program info body)
  4312. (define-values (body^ Tb) ((type-check-exp '()) body))
  4313. (check-type-equal? Tb 'Integer body)
  4314. (Program info body^)]
  4315. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4316. ))
  4317. (define (type-check-Rvar p)
  4318. (send (new type-check-Rvar-class) type-check-program p))
  4319. \end{lstlisting}
  4320. \caption{Type checker for the \LangVar{} language.}
  4321. \label{fig:type-check-Rvar}
  4322. \end{figure}
  4323. \begin{figure}[tbp]
  4324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4325. (define type-check-Rif-class
  4326. (class type-check-Rvar-class
  4327. (super-new)
  4328. (inherit check-type-equal?)
  4329. (define/override (operator-types)
  4330. (append '((- . ((Integer Integer) . Integer))
  4331. (and . ((Boolean Boolean) . Boolean))
  4332. (or . ((Boolean Boolean) . Boolean))
  4333. (< . ((Integer Integer) . Boolean))
  4334. (<= . ((Integer Integer) . Boolean))
  4335. (> . ((Integer Integer) . Boolean))
  4336. (>= . ((Integer Integer) . Boolean))
  4337. (not . ((Boolean) . Boolean))
  4338. )
  4339. (super operator-types)))
  4340. (define/override (type-check-exp env)
  4341. (lambda (e)
  4342. (match e
  4343. [(Prim 'eq? (list e1 e2))
  4344. (define-values (e1^ T1) ((type-check-exp env) e1))
  4345. (define-values (e2^ T2) ((type-check-exp env) e2))
  4346. (check-type-equal? T1 T2 e)
  4347. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4348. [(Bool b) (values (Bool b) 'Boolean)]
  4349. [(If cnd thn els)
  4350. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4351. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4352. (define-values (els^ Te) ((type-check-exp env) els))
  4353. (check-type-equal? Tc 'Boolean e)
  4354. (check-type-equal? Tt Te e)
  4355. (values (If cnd^ thn^ els^) Te)]
  4356. [else ((super type-check-exp env) e)])))
  4357. ))
  4358. (define (type-check-Rif p)
  4359. (send (new type-check-Rif-class) type-check-program p))
  4360. \end{lstlisting}
  4361. \caption{Type checker for the \LangIf{} language.}
  4362. \label{fig:type-check-Rif}
  4363. \end{figure}
  4364. Next we discuss the type checker for \LangIf{} in
  4365. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4366. two arguments to have the same type. The type of a Boolean constant is
  4367. \code{Boolean}. The condition of an \code{if} must be of
  4368. \code{Boolean} type and the two branches must have the same type. The
  4369. \code{operator-types} function adds dictionary entries for the other
  4370. new operators.
  4371. \begin{exercise}\normalfont
  4372. Create 10 new test programs in \LangIf{}. Half of the programs should
  4373. have a type error. For those programs, create an empty file with the
  4374. same base name but with file extension \code{.tyerr}. For example, if
  4375. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4376. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4377. \code{interp-tests} and \code{compiler-tests} that a type error is
  4378. expected. The other half of the test programs should not have type
  4379. errors.
  4380. In the \code{run-tests.rkt} script, change the second argument of
  4381. \code{interp-tests} and \code{compiler-tests} to
  4382. \code{type-check-Rif}, which causes the type checker to run prior to
  4383. the compiler passes. Temporarily change the \code{passes} to an empty
  4384. list and run the script, thereby checking that the new test programs
  4385. either type check or not as intended.
  4386. \end{exercise}
  4387. \section{The \LangCIf{} Intermediate Language}
  4388. \label{sec:Cif}
  4389. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4390. \LangCIf{} intermediate language. (The concrete syntax is in the
  4391. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4392. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4393. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4394. \key{\#f} to the \Arg{} non-terminal.
  4395. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4396. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4397. statement is a comparison operation and the branches are \code{goto}
  4398. statements, making it straightforward to compile \code{if} statements
  4399. to x86.
  4400. \begin{figure}[tp]
  4401. \fbox{
  4402. \begin{minipage}{0.96\textwidth}
  4403. \small
  4404. \[
  4405. \begin{array}{lcl}
  4406. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4407. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4408. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4409. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4410. &\mid& \UNIOP{\key{'not}}{\Atm}
  4411. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4412. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4413. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4414. \mid \GOTO{\itm{label}} \\
  4415. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4416. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4417. \end{array}
  4418. \]
  4419. \end{minipage}
  4420. }
  4421. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4422. (Figure~\ref{fig:c0-syntax}).}
  4423. \label{fig:c1-syntax}
  4424. \end{figure}
  4425. \section{The \LangXIf{} Language}
  4426. \label{sec:x86-if}
  4427. \index{subject}{x86} To implement the new logical operations, the comparison
  4428. operations, and the \key{if} expression, we need to delve further into
  4429. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4430. define the concrete and abstract syntax for the \LangXIf{} subset
  4431. of x86, which includes instructions for logical operations,
  4432. comparisons, and conditional jumps.
  4433. One challenge is that x86 does not provide an instruction that
  4434. directly implements logical negation (\code{not} in \LangIf{} and
  4435. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4436. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4437. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4438. bit of its arguments, and writes the results into its second argument.
  4439. Recall the truth table for exclusive-or:
  4440. \begin{center}
  4441. \begin{tabular}{l|cc}
  4442. & 0 & 1 \\ \hline
  4443. 0 & 0 & 1 \\
  4444. 1 & 1 & 0
  4445. \end{tabular}
  4446. \end{center}
  4447. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4448. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4449. for the bit $1$, the result is the opposite of the second bit. Thus,
  4450. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4451. the first argument:
  4452. \[
  4453. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4454. \qquad\Rightarrow\qquad
  4455. \begin{array}{l}
  4456. \key{movq}~ \Arg\key{,} \Var\\
  4457. \key{xorq}~ \key{\$1,} \Var
  4458. \end{array}
  4459. \]
  4460. \begin{figure}[tp]
  4461. \fbox{
  4462. \begin{minipage}{0.96\textwidth}
  4463. \[
  4464. \begin{array}{lcl}
  4465. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4466. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4467. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4468. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4469. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4470. \key{subq} \; \Arg\key{,} \Arg \mid
  4471. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4472. && \gray{ \key{callq} \; \itm{label} \mid
  4473. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4474. && \gray{ \itm{label}\key{:}\; \Instr }
  4475. \mid \key{xorq}~\Arg\key{,}~\Arg
  4476. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4477. && \key{set}cc~\Arg
  4478. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4479. \mid \key{j}cc~\itm{label}
  4480. \\
  4481. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  4482. & & \gray{ \key{main:} \; \Instr\ldots }
  4483. \end{array}
  4484. \]
  4485. \end{minipage}
  4486. }
  4487. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4488. \label{fig:x86-1-concrete}
  4489. \end{figure}
  4490. \begin{figure}[tp]
  4491. \fbox{
  4492. \begin{minipage}{0.98\textwidth}
  4493. \small
  4494. \[
  4495. \begin{array}{lcl}
  4496. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4497. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4498. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4499. \mid \BYTEREG{\itm{bytereg}} \\
  4500. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4501. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4502. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4503. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4504. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4505. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4506. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4507. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4508. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4509. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4510. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4511. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4512. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4513. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4514. \end{array}
  4515. \]
  4516. \end{minipage}
  4517. }
  4518. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4519. \label{fig:x86-1}
  4520. \end{figure}
  4521. Next we consider the x86 instructions that are relevant for compiling
  4522. the comparison operations. The \key{cmpq} instruction compares its two
  4523. arguments to determine whether one argument is less than, equal, or
  4524. greater than the other argument. The \key{cmpq} instruction is unusual
  4525. regarding the order of its arguments and where the result is
  4526. placed. The argument order is backwards: if you want to test whether
  4527. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4528. \key{cmpq} is placed in the special EFLAGS register. This register
  4529. cannot be accessed directly but it can be queried by a number of
  4530. instructions, including the \key{set} instruction. The instruction
  4531. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4532. depending on whether the comparison comes out according to the
  4533. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4534. for less-or-equal, \key{g} for greater, \key{ge} for
  4535. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4536. that its destination argument must be single byte register, such as
  4537. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4538. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4539. instruction can be used to move from a single byte register to a
  4540. normal 64-bit register. The abstract syntax for the \code{set}
  4541. instruction differs from the concrete syntax in that it separates the
  4542. instruction name from the condition code.
  4543. The x86 instruction for conditional jump is relevant to the
  4544. compilation of \key{if} expressions. The instruction
  4545. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4546. the instruction after \itm{label} depending on whether the result in
  4547. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4548. jump instruction falls through to the next instruction. Like the
  4549. abstract syntax for \code{set}, the abstract syntax for conditional
  4550. jump separates the instruction name from the condition code. For
  4551. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4552. the conditional jump instruction relies on the EFLAGS register, it is
  4553. common for it to be immediately preceded by a \key{cmpq} instruction
  4554. to set the EFLAGS register.
  4555. \section{Shrink the \LangIf{} Language}
  4556. \label{sec:shrink-Rif}
  4557. The \LangIf{} language includes several operators that are easily
  4558. expressible with other operators. For example, subtraction is
  4559. expressible using addition and negation.
  4560. \[
  4561. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4562. \]
  4563. Several of the comparison operations are expressible using less-than
  4564. and logical negation.
  4565. \[
  4566. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4567. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4568. \]
  4569. The \key{let} is needed in the above translation to ensure that
  4570. expression $e_1$ is evaluated before $e_2$.
  4571. By performing these translations in the front-end of the compiler, the
  4572. later passes of the compiler do not need to deal with these operators,
  4573. making the passes shorter.
  4574. %% On the other hand, sometimes
  4575. %% these translations make it more difficult to generate the most
  4576. %% efficient code with respect to the number of instructions. However,
  4577. %% these differences typically do not affect the number of accesses to
  4578. %% memory, which is the primary factor that determines execution time on
  4579. %% modern computer architectures.
  4580. \begin{exercise}\normalfont
  4581. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4582. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4583. translating them to other constructs in \LangIf{}.
  4584. %
  4585. Create six test programs that involve these operators.
  4586. %
  4587. In the \code{run-tests.rkt} script, add the following entry for
  4588. \code{shrink} to the list of passes (it should be the only pass at
  4589. this point).
  4590. \begin{lstlisting}
  4591. (list "shrink" shrink interp-Rif type-check-Rif)
  4592. \end{lstlisting}
  4593. This instructs \code{interp-tests} to run the intepreter
  4594. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4595. output of \code{shrink}.
  4596. %
  4597. Run the script to test your compiler on all the test programs.
  4598. \end{exercise}
  4599. \section{Uniquify Variables}
  4600. \label{sec:uniquify-Rif}
  4601. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4602. \code{if} expressions.
  4603. \begin{exercise}\normalfont
  4604. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4605. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4606. \begin{lstlisting}
  4607. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4608. \end{lstlisting}
  4609. Run the script to test your compiler.
  4610. \end{exercise}
  4611. \section{Remove Complex Operands}
  4612. \label{sec:remove-complex-opera-Rif}
  4613. The output language for this pass is \LangIfANF{}
  4614. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4615. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4616. \code{If} is not. All three sub-expressions of an \code{If} are
  4617. allowed to be complex expressions but the operands of \code{not} and
  4618. the comparisons must be atoms.
  4619. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4620. \code{rco-atom} functions according to whether the output needs to be
  4621. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4622. Regarding \code{If}, it is particularly important to \textbf{not}
  4623. replace its condition with a temporary variable because that would
  4624. interfere with the generation of high-quality output in the
  4625. \code{explicate-control} pass.
  4626. \begin{figure}[tp]
  4627. \centering
  4628. \fbox{
  4629. \begin{minipage}{0.96\textwidth}
  4630. \[
  4631. \begin{array}{rcl}
  4632. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4633. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4634. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4635. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4636. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4637. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4638. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4639. \end{array}
  4640. \]
  4641. \end{minipage}
  4642. }
  4643. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4644. \label{fig:Rif-anf-syntax}
  4645. \end{figure}
  4646. \begin{exercise}\normalfont
  4647. %
  4648. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4649. and \code{rco-exp} functions in \code{compiler.rkt}.
  4650. %
  4651. Create three new \LangInt{} programs that exercise the interesting
  4652. code in this pass.
  4653. %
  4654. In the \code{run-tests.rkt} script, add the following entry to the
  4655. list of \code{passes} and then run the script to test your compiler.
  4656. \begin{lstlisting}
  4657. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4658. \end{lstlisting}
  4659. \end{exercise}
  4660. \section{Explicate Control}
  4661. \label{sec:explicate-control-Rif}
  4662. Recall that the purpose of \code{explicate-control} is to make the
  4663. order of evaluation explicit in the syntax of the program. With the
  4664. addition of \key{if} this get more interesting.
  4665. As a motivating example, consider the following program that has an
  4666. \key{if} expression nested in the predicate of another \key{if}.
  4667. % cond_test_41.rkt
  4668. \begin{center}
  4669. \begin{minipage}{0.96\textwidth}
  4670. \begin{lstlisting}
  4671. (let ([x (read)])
  4672. (let ([y (read)])
  4673. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4674. (+ y 2)
  4675. (+ y 10))))
  4676. \end{lstlisting}
  4677. \end{minipage}
  4678. \end{center}
  4679. %
  4680. The naive way to compile \key{if} and the comparison would be to
  4681. handle each of them in isolation, regardless of their context. Each
  4682. comparison would be translated into a \key{cmpq} instruction followed
  4683. by a couple instructions to move the result from the EFLAGS register
  4684. into a general purpose register or stack location. Each \key{if} would
  4685. be translated into a \key{cmpq} instruction followed by a conditional
  4686. jump. The generated code for the inner \key{if} in the above example
  4687. would be as follows.
  4688. \begin{center}
  4689. \begin{minipage}{0.96\textwidth}
  4690. \begin{lstlisting}
  4691. ...
  4692. cmpq $1, x ;; (< x 1)
  4693. setl %al
  4694. movzbq %al, tmp
  4695. cmpq $1, tmp ;; (if ...)
  4696. je then_branch_1
  4697. jmp else_branch_1
  4698. ...
  4699. \end{lstlisting}
  4700. \end{minipage}
  4701. \end{center}
  4702. However, if we take context into account we can do better and reduce
  4703. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4704. Our goal will be compile \key{if} expressions so that the relevant
  4705. comparison instruction appears directly before the conditional jump.
  4706. For example, we want to generate the following code for the inner
  4707. \code{if}.
  4708. \begin{center}
  4709. \begin{minipage}{0.96\textwidth}
  4710. \begin{lstlisting}
  4711. ...
  4712. cmpq $1, x
  4713. je then_branch_1
  4714. jmp else_branch_1
  4715. ...
  4716. \end{lstlisting}
  4717. \end{minipage}
  4718. \end{center}
  4719. One way to achieve this is to reorganize the code at the level of
  4720. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4721. the following code.
  4722. \begin{center}
  4723. \begin{minipage}{0.96\textwidth}
  4724. \begin{lstlisting}
  4725. (let ([x (read)])
  4726. (let ([y (read)])
  4727. (if (< x 1)
  4728. (if (eq? x 0)
  4729. (+ y 2)
  4730. (+ y 10))
  4731. (if (eq? x 2)
  4732. (+ y 2)
  4733. (+ y 10)))))
  4734. \end{lstlisting}
  4735. \end{minipage}
  4736. \end{center}
  4737. Unfortunately, this approach duplicates the two branches from the
  4738. outer \code{if} and a compiler must never duplicate code!
  4739. We need a way to perform the above transformation but without
  4740. duplicating code. That is, we need a way for different parts of a
  4741. program to refer to the same piece of code. At the level of x86
  4742. assembly this is straightforward because we can label the code for
  4743. each branch and insert jumps in all the places that need to execute
  4744. the branch. In our intermediate language, we need to move away from
  4745. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4746. particular, we use a standard program representation called a
  4747. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4748. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  4749. labeled sequence of code, called a \emph{basic block}, and each edge
  4750. represents a jump to another block. The \key{CProgram} construct of
  4751. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4752. as an alist mapping labels to basic blocks. Each basic block is
  4753. represented by the $\Tail$ non-terminal.
  4754. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4755. \code{remove-complex-opera*} pass and then the
  4756. \code{explicate-control} pass on the example program. We walk through
  4757. the output program and then discuss the algorithm.
  4758. %
  4759. Following the order of evaluation in the output of
  4760. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4761. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4762. inner \key{if}. In the output of \code{explicate-control}, in the
  4763. block labeled \code{start}, is two assignment statements followed by a
  4764. \code{if} statement that branches to \code{block40} or
  4765. \code{block41}. The blocks associated with those labels contain the
  4766. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4767. respectively. In particular, we start \code{block40} with the
  4768. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4769. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4770. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4771. \code{block41} is similar.
  4772. \begin{figure}[tbp]
  4773. \begin{tabular}{lll}
  4774. \begin{minipage}{0.4\textwidth}
  4775. % cond_test_41.rkt
  4776. \begin{lstlisting}
  4777. (let ([x (read)])
  4778. (let ([y (read)])
  4779. (if (if (< x 1)
  4780. (eq? x 0)
  4781. (eq? x 2))
  4782. (+ y 2)
  4783. (+ y 10))))
  4784. \end{lstlisting}
  4785. \hspace{40pt}$\Downarrow$
  4786. \begin{lstlisting}
  4787. (let ([x (read)])
  4788. (let ([y (read)])
  4789. (if (if (< x 1)
  4790. (eq? x 0)
  4791. (eq? x 2))
  4792. (+ y 2)
  4793. (+ y 10))))
  4794. \end{lstlisting}
  4795. \end{minipage}
  4796. &
  4797. $\Rightarrow$
  4798. &
  4799. \begin{minipage}{0.55\textwidth}
  4800. \begin{lstlisting}
  4801. start:
  4802. x = (read);
  4803. y = (read);
  4804. if (< x 1) goto block40;
  4805. else goto block41;
  4806. block40:
  4807. if (eq? x 0) goto block38;
  4808. else goto block39;
  4809. block41:
  4810. if (eq? x 2) goto block38;
  4811. else goto block39;
  4812. block38:
  4813. return (+ y 2);
  4814. block39:
  4815. return (+ y 10);
  4816. \end{lstlisting}
  4817. \end{minipage}
  4818. \end{tabular}
  4819. \caption{Translation from \LangIf{} to \LangCIf{}
  4820. via the \code{explicate-control}.}
  4821. \label{fig:explicate-control-s1-38}
  4822. \end{figure}
  4823. %% The nice thing about the output of \code{explicate-control} is that
  4824. %% there are no unnecessary comparisons and every comparison is part of a
  4825. %% conditional jump.
  4826. %% The down-side of this output is that it includes
  4827. %% trivial blocks, such as the blocks labeled \code{block92} through
  4828. %% \code{block95}, that only jump to another block. We discuss a solution
  4829. %% to this problem in Section~\ref{sec:opt-jumps}.
  4830. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4831. \code{explicate-control} for \LangVar{} using two mutually recursive
  4832. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4833. former function translates expressions in tail position whereas the
  4834. later function translates expressions on the right-hand-side of a
  4835. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4836. have a new kind of position to deal with: the predicate position of
  4837. the \key{if}. We need another function, \code{explicate-pred}, that
  4838. takes an \LangIf{} expression and two blocks for the then-branch and
  4839. else-branch. The output of \code{explicate-pred} is a block.
  4840. %
  4841. In the following paragraphs we discuss specific cases in the
  4842. \code{explicate-pred} function as well as additions to the
  4843. \code{explicate-tail} and \code{explicate-assign} functions.
  4844. \begin{figure}[tbp]
  4845. \begin{lstlisting}
  4846. (define (explicate-pred cnd thn els)
  4847. (match cnd
  4848. [(Var x) ___]
  4849. [(Let x rhs body) ___]
  4850. [(Prim 'not (list e)) ___]
  4851. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4852. (IfStmt (Prim op arg*) (force (block->goto thn))
  4853. (force (block->goto els)))]
  4854. [(Bool b) (if b thn els)]
  4855. [(If cnd^ thn^ els^) ___]
  4856. [else (error "explicate-pred unhandled case" cnd)]))
  4857. \end{lstlisting}
  4858. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4859. \label{fig:explicate-pred}
  4860. \end{figure}
  4861. The skeleton for the \code{explicate-pred} function is given in
  4862. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4863. that can have type \code{Boolean}. We detail a few cases here and
  4864. leave the rest for the reader. The input to this function is an
  4865. expression and two blocks, \code{thn} and \code{els}, for the two
  4866. branches of the enclosing \key{if}.
  4867. %
  4868. Consider the case for Boolean constants in
  4869. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4870. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  4871. or \code{els} branch depending on whether the constant is true or
  4872. false. This case demonstrates that we sometimes discard the \code{thn}
  4873. or \code{els} blocks that are input to \code{explicate-pred}.
  4874. The case for \key{if} in \code{explicate-pred} is particularly
  4875. illuminating because it deals with the challenges we discussed above
  4876. regarding nested \key{if} expressions
  4877. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4878. \lstinline{els^} branches of the \key{if} inherit their context from
  4879. the current one, that is, predicate context. So you should recursively
  4880. apply \code{explicate-pred} to the \lstinline{thn^} and
  4881. \lstinline{els^} branches. For both of those recursive calls, pass
  4882. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4883. and \code{els} may get used twice, once inside each recursive call. As
  4884. discussed above, to avoid duplicating code, we need to add them to the
  4885. control-flow graph so that we can instead refer to them by name and
  4886. execute them with a \key{goto}. However, as we saw in the cases above
  4887. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4888. get used at all and we don't want to prematurely add them to the
  4889. control-flow graph if they end up being discarded.
  4890. The solution to this conundrum is to use \emph{lazy
  4891. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  4892. adding the blocks to the control-flow graph until the points where we
  4893. know they will be used. Racket provides support for lazy evaluation
  4894. with the
  4895. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4896. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4897. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  4898. evaluation of the expressions is postponed. When \key{(force}
  4899. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  4900. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4901. $e_n$ is cached in the promise and returned. If \code{force} is
  4902. applied again to the same promise, then the cached result is returned.
  4903. If \code{force} is applied to an argument that is not a promise,
  4904. \code{force} simply returns the argument.
  4905. We use lazy evaluation for the input and output blocks of the
  4906. functions \code{explicate-pred} and \code{explicate-assign} and for
  4907. the output block of \code{explicate-tail}. So instead of taking and
  4908. returning blocks, they take and return promises. Furthermore, when we
  4909. come to a situation in which we a block might be used more than once,
  4910. as in the case for \code{if} in \code{explicate-pred}, we transform
  4911. the promise into a new promise that will add the block to the
  4912. control-flow graph and return a \code{goto}. The following auxiliary
  4913. function named \code{block->goto} accomplishes this task. It begins
  4914. with \code{delay} to create a promise. When forced, this promise will
  4915. force the original promise. If that returns a \code{goto} (because the
  4916. block was already added to the control-flow graph), then we return the
  4917. \code{goto}. Otherwise we add the block to the control-flow graph with
  4918. another auxiliary function named \code{add-node}. That function
  4919. returns the label for the new block, which we use to create a
  4920. \code{goto}.
  4921. \begin{lstlisting}
  4922. (define (block->goto block)
  4923. (delay
  4924. (define b (force block))
  4925. (match b
  4926. [(Goto label) (Goto label)]
  4927. [else (Goto (add-node b))])))
  4928. \end{lstlisting}
  4929. Returning to the discussion of \code{explicate-pred}
  4930. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4931. operators. This is one of the base cases of the recursive function so
  4932. we translate the comparison to an \code{if} statement. We apply
  4933. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4934. that will add then to the control-flow graph, which we can immediately
  4935. \code{force} to obtain the two goto's that form the branches of the
  4936. \code{if} statement.
  4937. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4938. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4939. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4940. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4941. %% results from the two recursive calls. We complete the case for
  4942. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4943. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4944. %% the result $B_5$.
  4945. %% \[
  4946. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4947. %% \quad\Rightarrow\quad
  4948. %% B_5
  4949. %% \]
  4950. The \code{explicate-tail} and \code{explicate-assign} functions need
  4951. additional cases for Boolean constants and \key{if}.
  4952. %
  4953. In the cases for \code{if}, the two branches inherit the current
  4954. context, so in \code{explicate-tail} they are in tail position and in
  4955. \code{explicate-assign} they are in assignment position. The
  4956. \code{cont} parameter of \code{explicate-assign} is used in both
  4957. recursive calls, so make sure to use \code{block->goto} on it.
  4958. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4959. %% inherit the current context, so they are in tail position. Thus, the
  4960. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4961. %% \code{explicate-tail}.
  4962. %% %
  4963. %% We need to pass $B_0$ as the accumulator argument for both of these
  4964. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4965. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4966. %% to the control-flow graph and obtain a promised goto $G_0$.
  4967. %% %
  4968. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4969. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4970. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4971. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4972. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4973. %% \[
  4974. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4975. %% \]
  4976. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4977. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4978. %% should not be confused with the labels for the blocks that appear in
  4979. %% the generated code. We initially construct unlabeled blocks; we only
  4980. %% attach labels to blocks when we add them to the control-flow graph, as
  4981. %% we see in the next case.
  4982. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4983. %% function. The context of the \key{if} is an assignment to some
  4984. %% variable $x$ and then the control continues to some promised block
  4985. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  4986. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4987. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4988. %% branches of the \key{if} inherit the current context, so they are in
  4989. %% assignment positions. Let $B_2$ be the result of applying
  4990. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4991. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4992. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4993. %% the result of applying \code{explicate-pred} to the predicate
  4994. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4995. %% translates to the promise $B_4$.
  4996. %% \[
  4997. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4998. %% \]
  4999. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5000. The way in which the \code{shrink} pass transforms logical operations
  5001. such as \code{and} and \code{or} can impact the quality of code
  5002. generated by \code{explicate-control}. For example, consider the
  5003. following program.
  5004. % cond_test_21.rkt
  5005. \begin{lstlisting}
  5006. (if (and (eq? (read) 0) (eq? (read) 1))
  5007. 0
  5008. 42)
  5009. \end{lstlisting}
  5010. The \code{and} operation should transform into something that the
  5011. \code{explicate-pred} function can still analyze and descend through to
  5012. reach the underlying \code{eq?} conditions. Ideally, your
  5013. \code{explicate-control} pass should generate code similar to the
  5014. following for the above program.
  5015. \begin{center}
  5016. \begin{lstlisting}
  5017. start:
  5018. tmp1 = (read);
  5019. if (eq? tmp1 0) goto block40;
  5020. else goto block39;
  5021. block40:
  5022. tmp2 = (read);
  5023. if (eq? tmp2 1) goto block38;
  5024. else goto block39;
  5025. block38:
  5026. return 0;
  5027. block39:
  5028. return 42;
  5029. \end{lstlisting}
  5030. \end{center}
  5031. \begin{exercise}\normalfont
  5032. Implement the pass \code{explicate-control} by adding the cases for
  5033. Boolean constants and \key{if} to the \code{explicate-tail} and
  5034. \code{explicate-assign}. Implement the auxiliary function
  5035. \code{explicate-pred} for predicate contexts.
  5036. %
  5037. Create test cases that exercise all of the new cases in the code for
  5038. this pass.
  5039. %
  5040. Add the following entry to the list of \code{passes} in
  5041. \code{run-tests.rkt} and then run this script to test your compiler.
  5042. \begin{lstlisting}
  5043. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5044. \end{lstlisting}
  5045. \end{exercise}
  5046. \section{Select Instructions}
  5047. \label{sec:select-Rif}
  5048. \index{subject}{instruction selection}
  5049. The \code{select-instructions} pass translate \LangCIf{} to
  5050. \LangXIfVar{}. Recall that we implement this pass using three
  5051. auxiliary functions, one for each of the non-terminals $\Atm$,
  5052. $\Stmt$, and $\Tail$.
  5053. For $\Atm$, we have new cases for the Booleans. We take the usual
  5054. approach of encoding them as integers, with true as 1 and false as 0.
  5055. \[
  5056. \key{\#t} \Rightarrow \key{1}
  5057. \qquad
  5058. \key{\#f} \Rightarrow \key{0}
  5059. \]
  5060. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5061. be implemented in terms of \code{xorq} as we discussed at the
  5062. beginning of this section. Given an assignment
  5063. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5064. if the left-hand side $\itm{var}$ is
  5065. the same as $\Atm$, then just the \code{xorq} suffices.
  5066. \[
  5067. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5068. \quad\Rightarrow\quad
  5069. \key{xorq}~\key{\$}1\key{,}~\Var
  5070. \]
  5071. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5072. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5073. x86. Then we have
  5074. \[
  5075. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5076. \quad\Rightarrow\quad
  5077. \begin{array}{l}
  5078. \key{movq}~\Arg\key{,}~\Var\\
  5079. \key{xorq}~\key{\$}1\key{,}~\Var
  5080. \end{array}
  5081. \]
  5082. Next consider the cases for \code{eq?} and less-than comparison.
  5083. Translating these operations to x86 is slightly involved due to the
  5084. unusual nature of the \key{cmpq} instruction discussed above. We
  5085. recommend translating an assignment from \code{eq?} into the following
  5086. sequence of three instructions. \\
  5087. \begin{tabular}{lll}
  5088. \begin{minipage}{0.4\textwidth}
  5089. \begin{lstlisting}
  5090. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5091. \end{lstlisting}
  5092. \end{minipage}
  5093. &
  5094. $\Rightarrow$
  5095. &
  5096. \begin{minipage}{0.4\textwidth}
  5097. \begin{lstlisting}
  5098. cmpq |$\Arg_2$|, |$\Arg_1$|
  5099. sete %al
  5100. movzbq %al, |$\Var$|
  5101. \end{lstlisting}
  5102. \end{minipage}
  5103. \end{tabular} \\
  5104. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5105. and \key{if} statements. Both are straightforward to translate to
  5106. x86. A \key{goto} becomes a jump instruction.
  5107. \[
  5108. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5109. \]
  5110. An \key{if} statement becomes a compare instruction followed by a
  5111. conditional jump (for the ``then'' branch) and the fall-through is to
  5112. a regular jump (for the ``else'' branch).\\
  5113. \begin{tabular}{lll}
  5114. \begin{minipage}{0.4\textwidth}
  5115. \begin{lstlisting}
  5116. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5117. else goto |$\ell_2$|;
  5118. \end{lstlisting}
  5119. \end{minipage}
  5120. &
  5121. $\Rightarrow$
  5122. &
  5123. \begin{minipage}{0.4\textwidth}
  5124. \begin{lstlisting}
  5125. cmpq |$\Arg_2$|, |$\Arg_1$|
  5126. je |$\ell_1$|
  5127. jmp |$\ell_2$|
  5128. \end{lstlisting}
  5129. \end{minipage}
  5130. \end{tabular} \\
  5131. \begin{exercise}\normalfont
  5132. Expand your \code{select-instructions} pass to handle the new features
  5133. of the \LangIf{} language.
  5134. %
  5135. Add the following entry to the list of \code{passes} in
  5136. \code{run-tests.rkt}
  5137. \begin{lstlisting}
  5138. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5139. \end{lstlisting}
  5140. %
  5141. Run the script to test your compiler on all the test programs.
  5142. \end{exercise}
  5143. \section{Register Allocation}
  5144. \label{sec:register-allocation-Rif}
  5145. \index{subject}{register allocation}
  5146. The changes required for \LangIf{} affect liveness analysis, building the
  5147. interference graph, and assigning homes, but the graph coloring
  5148. algorithm itself does not change.
  5149. \subsection{Liveness Analysis}
  5150. \label{sec:liveness-analysis-Rif}
  5151. \index{subject}{liveness analysis}
  5152. Recall that for \LangVar{} we implemented liveness analysis for a single
  5153. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5154. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5155. produces many basic blocks arranged in a control-flow graph. We
  5156. recommend that you create a new auxiliary function named
  5157. \code{uncover-live-CFG} that applies liveness analysis to a
  5158. control-flow graph.
  5159. The first question we is: what order should we process the basic
  5160. blocks in the control-flow graph? Recall that to perform liveness
  5161. analysis on a basic block we need to know its live-after set. If a
  5162. basic block has no successors (i.e. no out-edges in the control flow
  5163. graph), then it has an empty live-after set and we can immediately
  5164. apply liveness analysis to it. If a basic block has some successors,
  5165. then we need to complete liveness analysis on those blocks first. In
  5166. graph theory, a sequence of nodes is in \emph{topological
  5167. order}\index{subject}{topological order} if each vertex comes before its
  5168. successors. We need the opposite, so we can transpose the graph
  5169. before computing a topological order.
  5170. %
  5171. Use the \code{tsort} and \code{transpose} functions of the Racket
  5172. \code{graph} package to accomplish this.
  5173. %
  5174. As an aside, a topological ordering is only guaranteed to exist if the
  5175. graph does not contain any cycles. That is indeed the case for the
  5176. control-flow graphs that we generate from \LangIf{} programs.
  5177. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5178. learn how to handle cycles in the control-flow graph.
  5179. You'll need to construct a directed graph to represent the
  5180. control-flow graph. Do not use the \code{directed-graph} of the
  5181. \code{graph} package because that only allows at most one edge between
  5182. each pair of vertices, but a control-flow graph may have multiple
  5183. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5184. the support code implements a graph representation that allows
  5185. multiple edges between a pair of vertices.
  5186. The next question is how to analyze jump instructions. Recall that in
  5187. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5188. \code{label->live} that maps each label to the set of live locations
  5189. at the beginning of its block. We use \code{label->live} to determine
  5190. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5191. that we have many basic blocks, \code{label->live} needs to be updated
  5192. as we process the blocks. In particular, after performing liveness
  5193. analysis on a block, we take the live-before set of its first
  5194. instruction and associate that with the block's label in the
  5195. \code{label->live}.
  5196. In \LangXIfVar{} we also have the conditional jump
  5197. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5198. this instruction is particularly interesting because during
  5199. compilation we do not know which way a conditional jump will go. So
  5200. we do not know whether to use the live-before set for the following
  5201. instruction or the live-before set for the $\itm{label}$. However,
  5202. there is no harm to the correctness of the compiler if we classify
  5203. more locations as live than the ones that are truly live during a
  5204. particular execution of the instruction. Thus, we can take the union
  5205. of the live-before sets from the following instruction and from the
  5206. mapping for $\itm{label}$ in \code{label->live}.
  5207. The auxiliary functions for computing the variables in an
  5208. instruction's argument and for computing the variables read-from ($R$)
  5209. or written-to ($W$) by an instruction need to be updated to handle the
  5210. new kinds of arguments and instructions in \LangXIfVar{}.
  5211. \begin{exercise}\normalfont
  5212. Update the \code{uncover-live} pass and implement the
  5213. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5214. to the control-flow graph. Add the following entry to the list of
  5215. \code{passes} in the \code{run-tests.rkt} script.
  5216. \begin{lstlisting}
  5217. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5218. \end{lstlisting}
  5219. \end{exercise}
  5220. \subsection{Build the Interference Graph}
  5221. \label{sec:build-interference-Rif}
  5222. Many of the new instructions in \LangXIfVar{} can be handled in the
  5223. same way as the instructions in \LangXVar{}. Thus, if your code was
  5224. already quite general, it will not need to be changed to handle the
  5225. new instructions. If you code is not general enough, we recommend that
  5226. you change your code to be more general. For example, you can factor
  5227. out the computing of the the read and write sets for each kind of
  5228. instruction into two auxiliary functions.
  5229. Note that the \key{movzbq} instruction requires some special care,
  5230. similar to the \key{movq} instruction. See rule number 1 in
  5231. Section~\ref{sec:build-interference}.
  5232. \begin{exercise}\normalfont
  5233. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5234. following entries to the list of \code{passes} in the
  5235. \code{run-tests.rkt} script.
  5236. \begin{lstlisting}
  5237. (list "build-interference" build-interference interp-pseudo-x86-1)
  5238. (list "allocate-registers" allocate-registers interp-x86-1)
  5239. \end{lstlisting}
  5240. Run the script to test your compiler on all the \LangIf{} test
  5241. programs.
  5242. \end{exercise}
  5243. \section{Patch Instructions}
  5244. The second argument of the \key{cmpq} instruction must not be an
  5245. immediate value (such as an integer). So if you are comparing two
  5246. immediates, we recommend inserting a \key{movq} instruction to put the
  5247. second argument in \key{rax}. Also, recall that instructions may have
  5248. at most one memory reference.
  5249. %
  5250. The second argument of the \key{movzbq} must be a register.
  5251. %
  5252. There are no special restrictions on the jump instructions.
  5253. \begin{exercise}\normalfont
  5254. %
  5255. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5256. %
  5257. Add the following entry to the list of \code{passes} in
  5258. \code{run-tests.rkt} and then run this script to test your compiler.
  5259. \begin{lstlisting}
  5260. (list "patch-instructions" patch-instructions interp-x86-1)
  5261. \end{lstlisting}
  5262. \end{exercise}
  5263. \begin{figure}[tbp]
  5264. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5265. \node (Rif) at (0,2) {\large \LangIf{}};
  5266. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5267. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5268. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5269. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5270. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5271. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5272. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5273. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5274. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5275. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5276. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5277. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5278. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5279. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5280. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5281. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5282. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5283. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5284. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5285. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5286. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5287. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5288. \end{tikzpicture}
  5289. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5290. \label{fig:Rif-passes}
  5291. \end{figure}
  5292. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5293. compilation of \LangIf{}.
  5294. \section{An Example Translation}
  5295. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5296. \LangIf{} translated to x86, showing the results of
  5297. \code{explicate-control}, \code{select-instructions}, and the final
  5298. x86 assembly code.
  5299. \begin{figure}[tbp]
  5300. \begin{tabular}{lll}
  5301. \begin{minipage}{0.4\textwidth}
  5302. % cond_test_20.rkt
  5303. \begin{lstlisting}
  5304. (if (eq? (read) 1) 42 0)
  5305. \end{lstlisting}
  5306. $\Downarrow$
  5307. \begin{lstlisting}
  5308. start:
  5309. tmp7951 = (read);
  5310. if (eq? tmp7951 1)
  5311. goto block7952;
  5312. else
  5313. goto block7953;
  5314. block7952:
  5315. return 42;
  5316. block7953:
  5317. return 0;
  5318. \end{lstlisting}
  5319. $\Downarrow$
  5320. \begin{lstlisting}
  5321. start:
  5322. callq read_int
  5323. movq %rax, tmp7951
  5324. cmpq $1, tmp7951
  5325. je block7952
  5326. jmp block7953
  5327. block7953:
  5328. movq $0, %rax
  5329. jmp conclusion
  5330. block7952:
  5331. movq $42, %rax
  5332. jmp conclusion
  5333. \end{lstlisting}
  5334. \end{minipage}
  5335. &
  5336. $\Rightarrow\qquad$
  5337. \begin{minipage}{0.4\textwidth}
  5338. \begin{lstlisting}
  5339. start:
  5340. callq read_int
  5341. movq %rax, %rcx
  5342. cmpq $1, %rcx
  5343. je block7952
  5344. jmp block7953
  5345. block7953:
  5346. movq $0, %rax
  5347. jmp conclusion
  5348. block7952:
  5349. movq $42, %rax
  5350. jmp conclusion
  5351. .globl main
  5352. main:
  5353. pushq %rbp
  5354. movq %rsp, %rbp
  5355. pushq %r13
  5356. pushq %r12
  5357. pushq %rbx
  5358. pushq %r14
  5359. subq $0, %rsp
  5360. jmp start
  5361. conclusion:
  5362. addq $0, %rsp
  5363. popq %r14
  5364. popq %rbx
  5365. popq %r12
  5366. popq %r13
  5367. popq %rbp
  5368. retq
  5369. \end{lstlisting}
  5370. \end{minipage}
  5371. \end{tabular}
  5372. \caption{Example compilation of an \key{if} expression to x86.}
  5373. \label{fig:if-example-x86}
  5374. \end{figure}
  5375. \section{Challenge: Remove Jumps}
  5376. \label{sec:opt-jumps}
  5377. %% Recall that in the example output of \code{explicate-control} in
  5378. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5379. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5380. %% block. The first goal of this challenge assignment is to remove those
  5381. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5382. %% \code{explicate-control} on the left and shows the result of bypassing
  5383. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5384. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5385. %% \code{block55}. The optimized code on the right of
  5386. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5387. %% \code{then} branch jumping directly to \code{block55}. The story is
  5388. %% similar for the \code{else} branch, as well as for the two branches in
  5389. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5390. %% have been optimized in this way, there are no longer any jumps to
  5391. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5392. %% \begin{figure}[tbp]
  5393. %% \begin{tabular}{lll}
  5394. %% \begin{minipage}{0.4\textwidth}
  5395. %% \begin{lstlisting}
  5396. %% block62:
  5397. %% tmp54 = (read);
  5398. %% if (eq? tmp54 2) then
  5399. %% goto block59;
  5400. %% else
  5401. %% goto block60;
  5402. %% block61:
  5403. %% tmp53 = (read);
  5404. %% if (eq? tmp53 0) then
  5405. %% goto block57;
  5406. %% else
  5407. %% goto block58;
  5408. %% block60:
  5409. %% goto block56;
  5410. %% block59:
  5411. %% goto block55;
  5412. %% block58:
  5413. %% goto block56;
  5414. %% block57:
  5415. %% goto block55;
  5416. %% block56:
  5417. %% return (+ 700 77);
  5418. %% block55:
  5419. %% return (+ 10 32);
  5420. %% start:
  5421. %% tmp52 = (read);
  5422. %% if (eq? tmp52 1) then
  5423. %% goto block61;
  5424. %% else
  5425. %% goto block62;
  5426. %% \end{lstlisting}
  5427. %% \end{minipage}
  5428. %% &
  5429. %% $\Rightarrow$
  5430. %% &
  5431. %% \begin{minipage}{0.55\textwidth}
  5432. %% \begin{lstlisting}
  5433. %% block62:
  5434. %% tmp54 = (read);
  5435. %% if (eq? tmp54 2) then
  5436. %% goto block55;
  5437. %% else
  5438. %% goto block56;
  5439. %% block61:
  5440. %% tmp53 = (read);
  5441. %% if (eq? tmp53 0) then
  5442. %% goto block55;
  5443. %% else
  5444. %% goto block56;
  5445. %% block56:
  5446. %% return (+ 700 77);
  5447. %% block55:
  5448. %% return (+ 10 32);
  5449. %% start:
  5450. %% tmp52 = (read);
  5451. %% if (eq? tmp52 1) then
  5452. %% goto block61;
  5453. %% else
  5454. %% goto block62;
  5455. %% \end{lstlisting}
  5456. %% \end{minipage}
  5457. %% \end{tabular}
  5458. %% \caption{Optimize jumps by removing trivial blocks.}
  5459. %% \label{fig:optimize-jumps}
  5460. %% \end{figure}
  5461. %% The name of this pass is \code{optimize-jumps}. We recommend
  5462. %% implementing this pass in two phases. The first phrase builds a hash
  5463. %% table that maps labels to possibly improved labels. The second phase
  5464. %% changes the target of each \code{goto} to use the improved label. If
  5465. %% the label is for a trivial block, then the hash table should map the
  5466. %% label to the first non-trivial block that can be reached from this
  5467. %% label by jumping through trivial blocks. If the label is for a
  5468. %% non-trivial block, then the hash table should map the label to itself;
  5469. %% we do not want to change jumps to non-trivial blocks.
  5470. %% The first phase can be accomplished by constructing an empty hash
  5471. %% table, call it \code{short-cut}, and then iterating over the control
  5472. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5473. %% then update the hash table, mapping the block's source to the target
  5474. %% of the \code{goto}. Also, the hash table may already have mapped some
  5475. %% labels to the block's source, to you must iterate through the hash
  5476. %% table and update all of those so that they instead map to the target
  5477. %% of the \code{goto}.
  5478. %% For the second phase, we recommend iterating through the $\Tail$ of
  5479. %% each block in the program, updating the target of every \code{goto}
  5480. %% according to the mapping in \code{short-cut}.
  5481. %% \begin{exercise}\normalfont
  5482. %% Implement the \code{optimize-jumps} pass as a transformation from
  5483. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5484. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5485. %% example programs. Then check that your compiler still passes all of
  5486. %% your tests.
  5487. %% \end{exercise}
  5488. There is an opportunity for optimizing jumps that is apparent in the
  5489. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5490. ends with a jump to \code{block7953} and there are no other jumps to
  5491. \code{block7953} in the rest of the program. In this situation we can
  5492. avoid the runtime overhead of this jump by merging \code{block7953}
  5493. into the preceding block, in this case the \code{start} block.
  5494. Figure~\ref{fig:remove-jumps} shows the output of
  5495. \code{select-instructions} on the left and the result of this
  5496. optimization on the right.
  5497. \begin{figure}[tbp]
  5498. \begin{tabular}{lll}
  5499. \begin{minipage}{0.5\textwidth}
  5500. % cond_test_20.rkt
  5501. \begin{lstlisting}
  5502. start:
  5503. callq read_int
  5504. movq %rax, tmp7951
  5505. cmpq $1, tmp7951
  5506. je block7952
  5507. jmp block7953
  5508. block7953:
  5509. movq $0, %rax
  5510. jmp conclusion
  5511. block7952:
  5512. movq $42, %rax
  5513. jmp conclusion
  5514. \end{lstlisting}
  5515. \end{minipage}
  5516. &
  5517. $\Rightarrow\qquad$
  5518. \begin{minipage}{0.4\textwidth}
  5519. \begin{lstlisting}
  5520. start:
  5521. callq read_int
  5522. movq %rax, tmp7951
  5523. cmpq $1, tmp7951
  5524. je block7952
  5525. movq $0, %rax
  5526. jmp conclusion
  5527. block7952:
  5528. movq $42, %rax
  5529. jmp conclusion
  5530. \end{lstlisting}
  5531. \end{minipage}
  5532. \end{tabular}
  5533. \caption{Merging basic blocks by removing unnecessary jumps.}
  5534. \label{fig:remove-jumps}
  5535. \end{figure}
  5536. \begin{exercise}\normalfont
  5537. %
  5538. Implement a pass named \code{remove-jumps} that merges basic blocks
  5539. into their preceding basic block, when there is only one preceding
  5540. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5541. %
  5542. In the \code{run-tests.rkt} script, add the following entry to the
  5543. list of \code{passes} between \code{allocate-registers}
  5544. and \code{patch-instructions}.
  5545. \begin{lstlisting}
  5546. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5547. \end{lstlisting}
  5548. Run this script to test your compiler.
  5549. %
  5550. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5551. blocks on several test programs.
  5552. \end{exercise}
  5553. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5554. \chapter{Tuples and Garbage Collection}
  5555. \label{ch:Rvec}
  5556. \index{subject}{tuple}
  5557. \index{subject}{vector}
  5558. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5559. %% all the IR grammars are spelled out! \\ --Jeremy}
  5560. %% \margincomment{\scriptsize Be more explicit about how to deal with
  5561. %% the root stack. \\ --Jeremy}
  5562. In this chapter we study the implementation of mutable tuples, called
  5563. vectors in Racket. This language feature is the first to use the
  5564. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  5565. tuple is indefinite, that is, a tuple lives forever from the
  5566. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5567. is important to reclaim the space associated with a tuple when it is
  5568. no longer needed, which is why we also study \emph{garbage collection}
  5569. \emph{garbage collection} techniques in this chapter.
  5570. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5571. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5572. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5573. \code{void} value. The reason for including the later is that the
  5574. \code{vector-set!} operation returns a value of type
  5575. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5576. called the \code{Unit} type in the programming languages
  5577. literature. Racket's \code{Void} type is inhabited by a single value
  5578. \code{void} which corresponds to \code{unit} or \code{()} in the
  5579. literature~\citep{Pierce:2002hj}.}.
  5580. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5581. copying live objects back and forth between two halves of the
  5582. heap. The garbage collector requires coordination with the compiler so
  5583. that it can see all of the \emph{root} pointers, that is, pointers in
  5584. registers or on the procedure call stack.
  5585. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5586. discuss all the necessary changes and additions to the compiler
  5587. passes, including a new compiler pass named \code{expose-allocation}.
  5588. \section{The \LangVec{} Language}
  5589. \label{sec:r3}
  5590. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5591. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5592. \LangVec{} language includes three new forms: \code{vector} for creating a
  5593. tuple, \code{vector-ref} for reading an element of a tuple, and
  5594. \code{vector-set!} for writing to an element of a tuple. The program
  5595. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5596. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5597. the 3-tuple, demonstrating that tuples are first-class values. The
  5598. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5599. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5600. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5601. 1-tuple. So the result of the program is \code{42}.
  5602. \begin{figure}[tbp]
  5603. \centering
  5604. \fbox{
  5605. \begin{minipage}{0.96\textwidth}
  5606. \[
  5607. \begin{array}{lcl}
  5608. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5609. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5610. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5611. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5612. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5613. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5614. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5615. \mid \LP\key{not}\;\Exp\RP } \\
  5616. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5617. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5618. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5619. \mid \LP\key{vector-length}\;\Exp\RP \\
  5620. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5621. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5622. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5623. \LangVecM{} &::=& \Exp
  5624. \end{array}
  5625. \]
  5626. \end{minipage}
  5627. }
  5628. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5629. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5630. \label{fig:Rvec-concrete-syntax}
  5631. \end{figure}
  5632. \begin{figure}[tbp]
  5633. \begin{lstlisting}
  5634. (let ([t (vector 40 #t (vector 2))])
  5635. (if (vector-ref t 1)
  5636. (+ (vector-ref t 0)
  5637. (vector-ref (vector-ref t 2) 0))
  5638. 44))
  5639. \end{lstlisting}
  5640. \caption{Example program that creates tuples and reads from them.}
  5641. \label{fig:vector-eg}
  5642. \end{figure}
  5643. \begin{figure}[tp]
  5644. \centering
  5645. \fbox{
  5646. \begin{minipage}{0.96\textwidth}
  5647. \[
  5648. \begin{array}{lcl}
  5649. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5650. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5651. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5652. \mid \BOOL{\itm{bool}}
  5653. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5654. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5655. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5656. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5657. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5658. \end{array}
  5659. \]
  5660. \end{minipage}
  5661. }
  5662. \caption{The abstract syntax of \LangVec{}.}
  5663. \label{fig:Rvec-syntax}
  5664. \end{figure}
  5665. \index{subject}{allocate}
  5666. \index{subject}{heap allocate}
  5667. Tuples are our first encounter with heap-allocated data, which raises
  5668. several interesting issues. First, variable binding performs a
  5669. shallow-copy when dealing with tuples, which means that different
  5670. variables can refer to the same tuple, that is, different variables
  5671. can be \emph{aliases} for the same entity. Consider the following
  5672. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5673. Thus, the mutation through \code{t2} is visible when referencing the
  5674. tuple from \code{t1}, so the result of this program is \code{42}.
  5675. \index{subject}{alias}\index{subject}{mutation}
  5676. \begin{center}
  5677. \begin{minipage}{0.96\textwidth}
  5678. \begin{lstlisting}
  5679. (let ([t1 (vector 3 7)])
  5680. (let ([t2 t1])
  5681. (let ([_ (vector-set! t2 0 42)])
  5682. (vector-ref t1 0))))
  5683. \end{lstlisting}
  5684. \end{minipage}
  5685. \end{center}
  5686. The next issue concerns the lifetime of tuples. Of course, they are
  5687. created by the \code{vector} form, but when does their lifetime end?
  5688. Notice that \LangVec{} does not include an operation for deleting
  5689. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5690. of static scoping. For example, the following program returns
  5691. \code{42} even though the variable \code{w} goes out of scope prior to
  5692. the \code{vector-ref} that reads from the vector it was bound to.
  5693. \begin{center}
  5694. \begin{minipage}{0.96\textwidth}
  5695. \begin{lstlisting}
  5696. (let ([v (vector (vector 44))])
  5697. (let ([x (let ([w (vector 42)])
  5698. (let ([_ (vector-set! v 0 w)])
  5699. 0))])
  5700. (+ x (vector-ref (vector-ref v 0) 0))))
  5701. \end{lstlisting}
  5702. \end{minipage}
  5703. \end{center}
  5704. From the perspective of programmer-observable behavior, tuples live
  5705. forever. Of course, if they really lived forever, then many programs
  5706. would run out of memory.\footnote{The \LangVec{} language does not have
  5707. looping or recursive functions, so it is nigh impossible to write a
  5708. program in \LangVec{} that will run out of memory. However, we add
  5709. recursive functions in the next Chapter!} A Racket implementation
  5710. must therefore perform automatic garbage collection.
  5711. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5712. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5713. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5714. terms of the corresponding operations in Racket. One subtle point is
  5715. that the \code{vector-set!} operation returns the \code{\#<void>}
  5716. value. The \code{\#<void>} value can be passed around just like other
  5717. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5718. compared for equality with another \code{\#<void>} value. However,
  5719. there are no other operations specific to the the \code{\#<void>}
  5720. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5721. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5722. otherwise.
  5723. \begin{figure}[tbp]
  5724. \begin{lstlisting}
  5725. (define interp-Rvec-class
  5726. (class interp-Rif-class
  5727. (super-new)
  5728. (define/override (interp-op op)
  5729. (match op
  5730. ['eq? (lambda (v1 v2)
  5731. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5732. (and (boolean? v1) (boolean? v2))
  5733. (and (vector? v1) (vector? v2))
  5734. (and (void? v1) (void? v2)))
  5735. (eq? v1 v2)]))]
  5736. ['vector vector]
  5737. ['vector-length vector-length]
  5738. ['vector-ref vector-ref]
  5739. ['vector-set! vector-set!]
  5740. [else (super interp-op op)]
  5741. ))
  5742. (define/override ((interp-exp env) e)
  5743. (define recur (interp-exp env))
  5744. (match e
  5745. [(HasType e t) (recur e)]
  5746. [(Void) (void)]
  5747. [else ((super interp-exp env) e)]
  5748. ))
  5749. ))
  5750. (define (interp-Rvec p)
  5751. (send (new interp-Rvec-class) interp-program p))
  5752. \end{lstlisting}
  5753. \caption{Interpreter for the \LangVec{} language.}
  5754. \label{fig:interp-Rvec}
  5755. \end{figure}
  5756. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5757. deserves some explanation. When allocating a vector, we need to know
  5758. which elements of the vector are pointers (i.e. are also vectors). We
  5759. can obtain this information during type checking. The type checker in
  5760. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5761. expression, it also wraps every \key{vector} creation with the form
  5762. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5763. %
  5764. To create the s-expression for the \code{Vector} type in
  5765. Figure~\ref{fig:type-check-Rvec}, we use the
  5766. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5767. operator} \code{,@} to insert the list \code{t*} without its usual
  5768. start and end parentheses. \index{subject}{unquote-slicing}
  5769. \begin{figure}[tp]
  5770. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5771. (define type-check-Rvec-class
  5772. (class type-check-Rif-class
  5773. (super-new)
  5774. (inherit check-type-equal?)
  5775. (define/override (type-check-exp env)
  5776. (lambda (e)
  5777. (define recur (type-check-exp env))
  5778. (match e
  5779. [(Void) (values (Void) 'Void)]
  5780. [(Prim 'vector es)
  5781. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5782. (define t `(Vector ,@t*))
  5783. (values (HasType (Prim 'vector e*) t) t)]
  5784. [(Prim 'vector-ref (list e1 (Int i)))
  5785. (define-values (e1^ t) (recur e1))
  5786. (match t
  5787. [`(Vector ,ts ...)
  5788. (unless (and (0 . <= . i) (i . < . (length ts)))
  5789. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5790. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5791. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5792. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5793. (define-values (e-vec t-vec) (recur e1))
  5794. (define-values (e-arg^ t-arg) (recur arg))
  5795. (match t-vec
  5796. [`(Vector ,ts ...)
  5797. (unless (and (0 . <= . i) (i . < . (length ts)))
  5798. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5799. (check-type-equal? (list-ref ts i) t-arg e)
  5800. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5801. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5802. [(Prim 'vector-length (list e))
  5803. (define-values (e^ t) (recur e))
  5804. (match t
  5805. [`(Vector ,ts ...)
  5806. (values (Prim 'vector-length (list e^)) 'Integer)]
  5807. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5808. [(Prim 'eq? (list arg1 arg2))
  5809. (define-values (e1 t1) (recur arg1))
  5810. (define-values (e2 t2) (recur arg2))
  5811. (match* (t1 t2)
  5812. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5813. [(other wise) (check-type-equal? t1 t2 e)])
  5814. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5815. [(HasType (Prim 'vector es) t)
  5816. ((type-check-exp env) (Prim 'vector es))]
  5817. [(HasType e1 t)
  5818. (define-values (e1^ t^) (recur e1))
  5819. (check-type-equal? t t^ e)
  5820. (values (HasType e1^ t) t)]
  5821. [else ((super type-check-exp env) e)]
  5822. )))
  5823. ))
  5824. (define (type-check-Rvec p)
  5825. (send (new type-check-Rvec-class) type-check-program p))
  5826. \end{lstlisting}
  5827. \caption{Type checker for the \LangVec{} language.}
  5828. \label{fig:type-check-Rvec}
  5829. \end{figure}
  5830. \section{Garbage Collection}
  5831. \label{sec:GC}
  5832. Here we study a relatively simple algorithm for garbage collection
  5833. that is the basis of state-of-the-art garbage
  5834. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5835. particular, we describe a two-space copying
  5836. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5837. perform the
  5838. copy~\citep{Cheney:1970aa}.
  5839. \index{subject}{copying collector}
  5840. \index{subject}{two-space copying collector}
  5841. Figure~\ref{fig:copying-collector} gives a
  5842. coarse-grained depiction of what happens in a two-space collector,
  5843. showing two time steps, prior to garbage collection (on the top) and
  5844. after garbage collection (on the bottom). In a two-space collector,
  5845. the heap is divided into two parts named the FromSpace and the
  5846. ToSpace. Initially, all allocations go to the FromSpace until there is
  5847. not enough room for the next allocation request. At that point, the
  5848. garbage collector goes to work to make more room.
  5849. \index{subject}{ToSpace}
  5850. \index{subject}{FromSpace}
  5851. The garbage collector must be careful not to reclaim tuples that will
  5852. be used by the program in the future. Of course, it is impossible in
  5853. general to predict what a program will do, but we can over approximate
  5854. the will-be-used tuples by preserving all tuples that could be
  5855. accessed by \emph{any} program given the current computer state. A
  5856. program could access any tuple whose address is in a register or on
  5857. the procedure call stack. These addresses are called the \emph{root
  5858. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  5859. transitively reachable from the root set. Thus, it is safe for the
  5860. garbage collector to reclaim the tuples that are not reachable in this
  5861. way.
  5862. So the goal of the garbage collector is twofold:
  5863. \begin{enumerate}
  5864. \item preserve all tuple that are reachable from the root set via a
  5865. path of pointers, that is, the \emph{live} tuples, and
  5866. \item reclaim the memory of everything else, that is, the
  5867. \emph{garbage}.
  5868. \end{enumerate}
  5869. A copying collector accomplishes this by copying all of the live
  5870. objects from the FromSpace into the ToSpace and then performs a sleight
  5871. of hand, treating the ToSpace as the new FromSpace and the old
  5872. FromSpace as the new ToSpace. In the example of
  5873. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5874. root set, one in a register and two on the stack. All of the live
  5875. objects have been copied to the ToSpace (the right-hand side of
  5876. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5877. pointer relationships. For example, the pointer in the register still
  5878. points to a 2-tuple whose first element is a 3-tuple and whose second
  5879. element is a 2-tuple. There are four tuples that are not reachable
  5880. from the root set and therefore do not get copied into the ToSpace.
  5881. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5882. created by a well-typed program in \LangVec{} because it contains a
  5883. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5884. We design the garbage collector to deal with cycles to begin with so
  5885. we will not need to revisit this issue.
  5886. \begin{figure}[tbp]
  5887. \centering
  5888. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5889. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5890. \caption{A copying collector in action.}
  5891. \label{fig:copying-collector}
  5892. \end{figure}
  5893. There are many alternatives to copying collectors (and their bigger
  5894. siblings, the generational collectors) when its comes to garbage
  5895. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5896. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5897. collectors are that allocation is fast (just a comparison and pointer
  5898. increment), there is no fragmentation, cyclic garbage is collected,
  5899. and the time complexity of collection only depends on the amount of
  5900. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5901. main disadvantages of a two-space copying collector is that it uses a
  5902. lot of space and takes a long time to perform the copy, though these
  5903. problems are ameliorated in generational collectors. Racket and
  5904. Scheme programs tend to allocate many small objects and generate a lot
  5905. of garbage, so copying and generational collectors are a good fit.
  5906. Garbage collection is an active research topic, especially concurrent
  5907. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5908. developing new techniques and revisiting old
  5909. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5910. meet every year at the International Symposium on Memory Management to
  5911. present these findings.
  5912. \subsection{Graph Copying via Cheney's Algorithm}
  5913. \label{sec:cheney}
  5914. \index{subject}{Cheney's algorithm}
  5915. Let us take a closer look at the copying of the live objects. The
  5916. allocated objects and pointers can be viewed as a graph and we need to
  5917. copy the part of the graph that is reachable from the root set. To
  5918. make sure we copy all of the reachable vertices in the graph, we need
  5919. an exhaustive graph traversal algorithm, such as depth-first search or
  5920. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5921. such algorithms take into account the possibility of cycles by marking
  5922. which vertices have already been visited, so as to ensure termination
  5923. of the algorithm. These search algorithms also use a data structure
  5924. such as a stack or queue as a to-do list to keep track of the vertices
  5925. that need to be visited. We use breadth-first search and a trick
  5926. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5927. and copying tuples into the ToSpace.
  5928. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5929. copy progresses. The queue is represented by a chunk of contiguous
  5930. memory at the beginning of the ToSpace, using two pointers to track
  5931. the front and the back of the queue. The algorithm starts by copying
  5932. all tuples that are immediately reachable from the root set into the
  5933. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5934. old tuple to indicate that it has been visited. We discuss how this
  5935. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5936. pointers inside the copied tuples in the queue still point back to the
  5937. FromSpace. Once the initial queue has been created, the algorithm
  5938. enters a loop in which it repeatedly processes the tuple at the front
  5939. of the queue and pops it off the queue. To process a tuple, the
  5940. algorithm copies all the tuple that are directly reachable from it to
  5941. the ToSpace, placing them at the back of the queue. The algorithm then
  5942. updates the pointers in the popped tuple so they point to the newly
  5943. copied tuples.
  5944. \begin{figure}[tbp]
  5945. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5946. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5947. \label{fig:cheney}
  5948. \end{figure}
  5949. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5950. tuple whose second element is $42$ to the back of the queue. The other
  5951. pointer goes to a tuple that has already been copied, so we do not
  5952. need to copy it again, but we do need to update the pointer to the new
  5953. location. This can be accomplished by storing a \emph{forwarding
  5954. pointer} to the new location in the old tuple, back when we initially
  5955. copied the tuple into the ToSpace. This completes one step of the
  5956. algorithm. The algorithm continues in this way until the front of the
  5957. queue is empty, that is, until the front catches up with the back.
  5958. \subsection{Data Representation}
  5959. \label{sec:data-rep-gc}
  5960. The garbage collector places some requirements on the data
  5961. representations used by our compiler. First, the garbage collector
  5962. needs to distinguish between pointers and other kinds of data. There
  5963. are several ways to accomplish this.
  5964. \begin{enumerate}
  5965. \item Attached a tag to each object that identifies what type of
  5966. object it is~\citep{McCarthy:1960dz}.
  5967. \item Store different types of objects in different
  5968. regions~\citep{Steele:1977ab}.
  5969. \item Use type information from the program to either generate
  5970. type-specific code for collecting or to generate tables that can
  5971. guide the
  5972. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5973. \end{enumerate}
  5974. Dynamically typed languages, such as Lisp, need to tag objects
  5975. anyways, so option 1 is a natural choice for those languages.
  5976. However, \LangVec{} is a statically typed language, so it would be
  5977. unfortunate to require tags on every object, especially small and
  5978. pervasive objects like integers and Booleans. Option 3 is the
  5979. best-performing choice for statically typed languages, but comes with
  5980. a relatively high implementation complexity. To keep this chapter
  5981. within a 2-week time budget, we recommend a combination of options 1
  5982. and 2, using separate strategies for the stack and the heap.
  5983. Regarding the stack, we recommend using a separate stack for pointers,
  5984. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  5985. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5986. is, when a local variable needs to be spilled and is of type
  5987. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5988. stack instead of the normal procedure call stack. Furthermore, we
  5989. always spill vector-typed variables if they are live during a call to
  5990. the collector, thereby ensuring that no pointers are in registers
  5991. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5992. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5993. the data layout using a root stack. The root stack contains the two
  5994. pointers from the regular stack and also the pointer in the second
  5995. register.
  5996. \begin{figure}[tbp]
  5997. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5998. \caption{Maintaining a root stack to facilitate garbage collection.}
  5999. \label{fig:shadow-stack}
  6000. \end{figure}
  6001. The problem of distinguishing between pointers and other kinds of data
  6002. also arises inside of each tuple on the heap. We solve this problem by
  6003. attaching a tag, an extra 64-bits, to each
  6004. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6005. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6006. that we have drawn the bits in a big-endian way, from right-to-left,
  6007. with bit location 0 (the least significant bit) on the far right,
  6008. which corresponds to the direction of the x86 shifting instructions
  6009. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6010. is dedicated to specifying which elements of the tuple are pointers,
  6011. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6012. indicates there is a pointer and a 0 bit indicates some other kind of
  6013. data. The pointer mask starts at bit location 7. We have limited
  6014. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6015. the pointer mask. The tag also contains two other pieces of
  6016. information. The length of the tuple (number of elements) is stored in
  6017. bits location 1 through 6. Finally, the bit at location 0 indicates
  6018. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6019. value 1, then this tuple has not yet been copied. If the bit has
  6020. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6021. of a pointer are always zero anyways because our tuples are 8-byte
  6022. aligned.)
  6023. \begin{figure}[tbp]
  6024. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6025. \caption{Representation of tuples in the heap.}
  6026. \label{fig:tuple-rep}
  6027. \end{figure}
  6028. \subsection{Implementation of the Garbage Collector}
  6029. \label{sec:organize-gz}
  6030. \index{subject}{prelude}
  6031. An implementation of the copying collector is provided in the
  6032. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6033. interface to the garbage collector that is used by the compiler. The
  6034. \code{initialize} function creates the FromSpace, ToSpace, and root
  6035. stack and should be called in the prelude of the \code{main}
  6036. function. The arguments of \code{initialize} are the root stack size
  6037. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6038. good choice for both. The \code{initialize} function puts the address
  6039. of the beginning of the FromSpace into the global variable
  6040. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6041. the address that is 1-past the last element of the FromSpace. (We use
  6042. half-open intervals to represent chunks of
  6043. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6044. points to the first element of the root stack.
  6045. As long as there is room left in the FromSpace, your generated code
  6046. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6047. %
  6048. The amount of room left in FromSpace is the difference between the
  6049. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6050. function should be called when there is not enough room left in the
  6051. FromSpace for the next allocation. The \code{collect} function takes
  6052. a pointer to the current top of the root stack (one past the last item
  6053. that was pushed) and the number of bytes that need to be
  6054. allocated. The \code{collect} function performs the copying collection
  6055. and leaves the heap in a state such that the next allocation will
  6056. succeed.
  6057. \begin{figure}[tbp]
  6058. \begin{lstlisting}
  6059. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6060. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6061. int64_t* free_ptr;
  6062. int64_t* fromspace_begin;
  6063. int64_t* fromspace_end;
  6064. int64_t** rootstack_begin;
  6065. \end{lstlisting}
  6066. \caption{The compiler's interface to the garbage collector.}
  6067. \label{fig:gc-header}
  6068. \end{figure}
  6069. %% \begin{exercise}
  6070. %% In the file \code{runtime.c} you will find the implementation of
  6071. %% \code{initialize} and a partial implementation of \code{collect}.
  6072. %% The \code{collect} function calls another function, \code{cheney},
  6073. %% to perform the actual copy, and that function is left to the reader
  6074. %% to implement. The following is the prototype for \code{cheney}.
  6075. %% \begin{lstlisting}
  6076. %% static void cheney(int64_t** rootstack_ptr);
  6077. %% \end{lstlisting}
  6078. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6079. %% rootstack (which is an array of pointers). The \code{cheney} function
  6080. %% also communicates with \code{collect} through the global
  6081. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6082. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6083. %% the ToSpace:
  6084. %% \begin{lstlisting}
  6085. %% static int64_t* tospace_begin;
  6086. %% static int64_t* tospace_end;
  6087. %% \end{lstlisting}
  6088. %% The job of the \code{cheney} function is to copy all the live
  6089. %% objects (reachable from the root stack) into the ToSpace, update
  6090. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6091. %% update the root stack so that it points to the objects in the
  6092. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6093. %% and ToSpace.
  6094. %% \end{exercise}
  6095. %% \section{Compiler Passes}
  6096. %% \label{sec:code-generation-gc}
  6097. The introduction of garbage collection has a non-trivial impact on our
  6098. compiler passes. We introduce a new compiler pass named
  6099. \code{expose-allocation}. We make
  6100. significant changes to \code{select-instructions},
  6101. \code{build-interference}, \code{allocate-registers}, and
  6102. \code{print-x86} and make minor changes in several more passes. The
  6103. following program will serve as our running example. It creates two
  6104. tuples, one nested inside the other. Both tuples have length one. The
  6105. program accesses the element in the inner tuple tuple via two vector
  6106. references.
  6107. % tests/s2_17.rkt
  6108. \begin{lstlisting}
  6109. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6110. \end{lstlisting}
  6111. \section{Shrink}
  6112. \label{sec:shrink-Rvec}
  6113. Recall that the \code{shrink} pass translates the primitives operators
  6114. into a smaller set of primitives. Because this pass comes after type
  6115. checking, but before the passes that require the type information in
  6116. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6117. to wrap \code{HasType} around each AST node that it generates.
  6118. \section{Expose Allocation}
  6119. \label{sec:expose-allocation}
  6120. The pass \code{expose-allocation} lowers the \code{vector} creation
  6121. form into a conditional call to the collector followed by the
  6122. allocation. We choose to place the \code{expose-allocation} pass
  6123. before \code{remove-complex-opera*} because the code generated by
  6124. \code{expose-allocation} contains complex operands. We also place
  6125. \code{expose-allocation} before \code{explicate-control} because
  6126. \code{expose-allocation} introduces new variables using \code{let},
  6127. but \code{let} is gone after \code{explicate-control}.
  6128. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6129. extends \LangVec{} with the three new forms that we use in the translation
  6130. of the \code{vector} form.
  6131. \[
  6132. \begin{array}{lcl}
  6133. \Exp &::=& \cdots
  6134. \mid (\key{collect} \,\itm{int})
  6135. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6136. \mid (\key{global-value} \,\itm{name})
  6137. \end{array}
  6138. \]
  6139. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6140. $n$ bytes. It will become a call to the \code{collect} function in
  6141. \code{runtime.c} in \code{select-instructions}. The
  6142. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6143. \index{subject}{allocate}
  6144. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6145. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6146. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6147. a global variable, such as \code{free\_ptr}.
  6148. In the following, we show the transformation for the \code{vector}
  6149. form into 1) a sequence of let-bindings for the initializing
  6150. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6151. \code{allocate}, and 4) the initialization of the vector. In the
  6152. following, \itm{len} refers to the length of the vector and
  6153. \itm{bytes} is how many total bytes need to be allocated for the
  6154. vector, which is 8 for the tag plus \itm{len} times 8.
  6155. \begin{lstlisting}
  6156. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6157. |$\Longrightarrow$|
  6158. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6159. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6160. (global-value fromspace_end))
  6161. (void)
  6162. (collect |\itm{bytes}|))])
  6163. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6164. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6165. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6166. |$v$|) ... )))) ...)
  6167. \end{lstlisting}
  6168. In the above, we suppressed all of the \code{has-type} forms in the
  6169. output for the sake of readability. The placement of the initializing
  6170. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6171. sequence of \code{vector-set!} is important, as those expressions may
  6172. trigger garbage collection and we cannot have an allocated but
  6173. uninitialized tuple on the heap during a collection.
  6174. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6175. \code{expose-allocation} pass on our running example.
  6176. \begin{figure}[tbp]
  6177. % tests/s2_17.rkt
  6178. \begin{lstlisting}
  6179. (vector-ref
  6180. (vector-ref
  6181. (let ([vecinit7976
  6182. (let ([vecinit7972 42])
  6183. (let ([collectret7974
  6184. (if (< (+ (global-value free_ptr) 16)
  6185. (global-value fromspace_end))
  6186. (void)
  6187. (collect 16)
  6188. )])
  6189. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6190. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6191. alloc7971)
  6192. )
  6193. )
  6194. )
  6195. ])
  6196. (let ([collectret7978
  6197. (if (< (+ (global-value free_ptr) 16)
  6198. (global-value fromspace_end))
  6199. (void)
  6200. (collect 16)
  6201. )])
  6202. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6203. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6204. alloc7975)
  6205. )
  6206. )
  6207. )
  6208. 0)
  6209. 0)
  6210. \end{lstlisting}
  6211. \caption{Output of the \code{expose-allocation} pass, minus
  6212. all of the \code{has-type} forms.}
  6213. \label{fig:expose-alloc-output}
  6214. \end{figure}
  6215. \section{Remove Complex Operands}
  6216. \label{sec:remove-complex-opera-Rvec}
  6217. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6218. should all be treated as complex operands.
  6219. %% A new case for
  6220. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6221. %% handled carefully to prevent the \code{Prim} node from being separated
  6222. %% from its enclosing \code{HasType}.
  6223. Figure~\ref{fig:Rvec-anf-syntax}
  6224. shows the grammar for the output language \LangVecANF{} of this
  6225. pass, which is \LangVec{} in administrative normal form.
  6226. \begin{figure}[tp]
  6227. \centering
  6228. \fbox{
  6229. \begin{minipage}{0.96\textwidth}
  6230. \small
  6231. \[
  6232. \begin{array}{rcl}
  6233. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6234. \mid \VOID{} \\
  6235. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6236. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6237. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6238. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6239. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6240. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6241. \mid \LP\key{GlobalValue}~\Var\RP\\
  6242. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6243. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6244. \end{array}
  6245. \]
  6246. \end{minipage}
  6247. }
  6248. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6249. \label{fig:Rvec-anf-syntax}
  6250. \end{figure}
  6251. \section{Explicate Control and the \LangCVec{} language}
  6252. \label{sec:explicate-control-r3}
  6253. \begin{figure}[tp]
  6254. \fbox{
  6255. \begin{minipage}{0.96\textwidth}
  6256. \small
  6257. \[
  6258. \begin{array}{lcl}
  6259. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6260. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6261. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6262. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6263. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6264. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6265. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6266. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6267. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6268. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6269. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6270. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6271. \mid \GOTO{\itm{label}} } \\
  6272. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6273. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6274. \end{array}
  6275. \]
  6276. \end{minipage}
  6277. }
  6278. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6279. (Figure~\ref{fig:c1-syntax}).}
  6280. \label{fig:c2-syntax}
  6281. \end{figure}
  6282. The output of \code{explicate-control} is a program in the
  6283. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6284. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6285. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6286. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6287. \key{vector-set!}, and \key{global-value} expressions and the
  6288. \code{collect} statement. The \code{explicate-control} pass can treat
  6289. these new forms much like the other expression forms that we've
  6290. already encoutered.
  6291. \section{Select Instructions and the \LangXGlobal{} Language}
  6292. \label{sec:select-instructions-gc}
  6293. \index{subject}{instruction selection}
  6294. %% void (rep as zero)
  6295. %% allocate
  6296. %% collect (callq collect)
  6297. %% vector-ref
  6298. %% vector-set!
  6299. %% global (postpone)
  6300. In this pass we generate x86 code for most of the new operations that
  6301. were needed to compile tuples, including \code{Allocate},
  6302. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6303. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6304. the later has a different concrete syntax (see
  6305. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6306. \index{subject}{x86}
  6307. The \code{vector-ref} and \code{vector-set!} forms translate into
  6308. \code{movq} instructions. (The plus one in the offset is to get past
  6309. the tag at the beginning of the tuple representation.)
  6310. \begin{lstlisting}
  6311. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6312. |$\Longrightarrow$|
  6313. movq |$\itm{vec}'$|, %r11
  6314. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6315. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6316. |$\Longrightarrow$|
  6317. movq |$\itm{vec}'$|, %r11
  6318. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6319. movq $0, |$\itm{lhs'}$|
  6320. \end{lstlisting}
  6321. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6322. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6323. register \code{r11} ensures that offset expression
  6324. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6325. removing \code{r11} from consideration by the register allocating.
  6326. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6327. \code{rax}. Then the generated code for \code{vector-set!} would be
  6328. \begin{lstlisting}
  6329. movq |$\itm{vec}'$|, %rax
  6330. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6331. movq $0, |$\itm{lhs}'$|
  6332. \end{lstlisting}
  6333. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6334. \code{patch-instructions} would insert a move through \code{rax}
  6335. as follows.
  6336. \begin{lstlisting}
  6337. movq |$\itm{vec}'$|, %rax
  6338. movq |$\itm{arg}'$|, %rax
  6339. movq %rax, |$8(n+1)$|(%rax)
  6340. movq $0, |$\itm{lhs}'$|
  6341. \end{lstlisting}
  6342. But the above sequence of instructions does not work because we're
  6343. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6344. $\itm{arg}'$) at the same time!
  6345. We compile the \code{allocate} form to operations on the
  6346. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6347. is the next free address in the FromSpace, so we copy it into
  6348. \code{r11} and then move it forward by enough space for the tuple
  6349. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6350. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6351. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6352. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6353. tag is organized. We recommend using the Racket operations
  6354. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6355. during compilation. The type annotation in the \code{vector} form is
  6356. used to determine the pointer mask region of the tag.
  6357. \begin{lstlisting}
  6358. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6359. |$\Longrightarrow$|
  6360. movq free_ptr(%rip), %r11
  6361. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6362. movq $|$\itm{tag}$|, 0(%r11)
  6363. movq %r11, |$\itm{lhs}'$|
  6364. \end{lstlisting}
  6365. The \code{collect} form is compiled to a call to the \code{collect}
  6366. function in the runtime. The arguments to \code{collect} are 1) the
  6367. top of the root stack and 2) the number of bytes that need to be
  6368. allocated. We use another dedicated register, \code{r15}, to
  6369. store the pointer to the top of the root stack. So \code{r15} is not
  6370. available for use by the register allocator.
  6371. \begin{lstlisting}
  6372. (collect |$\itm{bytes}$|)
  6373. |$\Longrightarrow$|
  6374. movq %r15, %rdi
  6375. movq $|\itm{bytes}|, %rsi
  6376. callq collect
  6377. \end{lstlisting}
  6378. \begin{figure}[tp]
  6379. \fbox{
  6380. \begin{minipage}{0.96\textwidth}
  6381. \[
  6382. \begin{array}{lcl}
  6383. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6384. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  6385. & & \gray{ \key{main:} \; \Instr\ldots }
  6386. \end{array}
  6387. \]
  6388. \end{minipage}
  6389. }
  6390. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6391. \label{fig:x86-2-concrete}
  6392. \end{figure}
  6393. \begin{figure}[tp]
  6394. \fbox{
  6395. \begin{minipage}{0.96\textwidth}
  6396. \small
  6397. \[
  6398. \begin{array}{lcl}
  6399. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6400. \mid \BYTEREG{\Reg}} \\
  6401. &\mid& (\key{Global}~\Var) \\
  6402. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6403. \end{array}
  6404. \]
  6405. \end{minipage}
  6406. }
  6407. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6408. \label{fig:x86-2}
  6409. \end{figure}
  6410. The concrete and abstract syntax of the \LangXGlobal{} language is
  6411. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6412. differs from \LangXIf{} just in the addition of the form for global
  6413. variables.
  6414. %
  6415. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6416. \code{select-instructions} pass on the running example.
  6417. \begin{figure}[tbp]
  6418. \centering
  6419. % tests/s2_17.rkt
  6420. \begin{minipage}[t]{0.5\textwidth}
  6421. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6422. block35:
  6423. movq free_ptr(%rip), alloc9024
  6424. addq $16, free_ptr(%rip)
  6425. movq alloc9024, %r11
  6426. movq $131, 0(%r11)
  6427. movq alloc9024, %r11
  6428. movq vecinit9025, 8(%r11)
  6429. movq $0, initret9026
  6430. movq alloc9024, %r11
  6431. movq 8(%r11), tmp9034
  6432. movq tmp9034, %r11
  6433. movq 8(%r11), %rax
  6434. jmp conclusion
  6435. block36:
  6436. movq $0, collectret9027
  6437. jmp block35
  6438. block38:
  6439. movq free_ptr(%rip), alloc9020
  6440. addq $16, free_ptr(%rip)
  6441. movq alloc9020, %r11
  6442. movq $3, 0(%r11)
  6443. movq alloc9020, %r11
  6444. movq vecinit9021, 8(%r11)
  6445. movq $0, initret9022
  6446. movq alloc9020, vecinit9025
  6447. movq free_ptr(%rip), tmp9031
  6448. movq tmp9031, tmp9032
  6449. addq $16, tmp9032
  6450. movq fromspace_end(%rip), tmp9033
  6451. cmpq tmp9033, tmp9032
  6452. jl block36
  6453. jmp block37
  6454. block37:
  6455. movq %r15, %rdi
  6456. movq $16, %rsi
  6457. callq 'collect
  6458. jmp block35
  6459. block39:
  6460. movq $0, collectret9023
  6461. jmp block38
  6462. \end{lstlisting}
  6463. \end{minipage}
  6464. \begin{minipage}[t]{0.45\textwidth}
  6465. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6466. start:
  6467. movq $42, vecinit9021
  6468. movq free_ptr(%rip), tmp9028
  6469. movq tmp9028, tmp9029
  6470. addq $16, tmp9029
  6471. movq fromspace_end(%rip), tmp9030
  6472. cmpq tmp9030, tmp9029
  6473. jl block39
  6474. jmp block40
  6475. block40:
  6476. movq %r15, %rdi
  6477. movq $16, %rsi
  6478. callq 'collect
  6479. jmp block38
  6480. \end{lstlisting}
  6481. \end{minipage}
  6482. \caption{Output of the \code{select-instructions} pass.}
  6483. \label{fig:select-instr-output-gc}
  6484. \end{figure}
  6485. \clearpage
  6486. \section{Register Allocation}
  6487. \label{sec:reg-alloc-gc}
  6488. \index{subject}{register allocation}
  6489. As discussed earlier in this chapter, the garbage collector needs to
  6490. access all the pointers in the root set, that is, all variables that
  6491. are vectors. It will be the responsibility of the register allocator
  6492. to make sure that:
  6493. \begin{enumerate}
  6494. \item the root stack is used for spilling vector-typed variables, and
  6495. \item if a vector-typed variable is live during a call to the
  6496. collector, it must be spilled to ensure it is visible to the
  6497. collector.
  6498. \end{enumerate}
  6499. The later responsibility can be handled during construction of the
  6500. interference graph, by adding interference edges between the call-live
  6501. vector-typed variables and all the callee-saved registers. (They
  6502. already interfere with the caller-saved registers.) The type
  6503. information for variables is in the \code{Program} form, so we
  6504. recommend adding another parameter to the \code{build-interference}
  6505. function to communicate this alist.
  6506. The spilling of vector-typed variables to the root stack can be
  6507. handled after graph coloring, when choosing how to assign the colors
  6508. (integers) to registers and stack locations. The \code{Program} output
  6509. of this pass changes to also record the number of spills to the root
  6510. stack.
  6511. % build-interference
  6512. %
  6513. % callq
  6514. % extra parameter for var->type assoc. list
  6515. % update 'program' and 'if'
  6516. % allocate-registers
  6517. % allocate spilled vectors to the rootstack
  6518. % don't change color-graph
  6519. \section{Print x86}
  6520. \label{sec:print-x86-gc}
  6521. \index{subject}{prelude}\index{subject}{conclusion}
  6522. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6523. \code{print-x86} pass on the running example. In the prelude and
  6524. conclusion of the \code{main} function, we treat the root stack very
  6525. much like the regular stack in that we move the root stack pointer
  6526. (\code{r15}) to make room for the spills to the root stack, except
  6527. that the root stack grows up instead of down. For the running
  6528. example, there was just one spill so we increment \code{r15} by 8
  6529. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6530. One issue that deserves special care is that there may be a call to
  6531. \code{collect} prior to the initializing assignments for all the
  6532. variables in the root stack. We do not want the garbage collector to
  6533. accidentally think that some uninitialized variable is a pointer that
  6534. needs to be followed. Thus, we zero-out all locations on the root
  6535. stack in the prelude of \code{main}. In
  6536. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6537. %
  6538. \lstinline{movq $0, (%r15)}
  6539. %
  6540. accomplishes this task. The garbage collector tests each root to see
  6541. if it is null prior to dereferencing it.
  6542. \begin{figure}[htbp]
  6543. \begin{minipage}[t]{0.5\textwidth}
  6544. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6545. block35:
  6546. movq free_ptr(%rip), %rcx
  6547. addq $16, free_ptr(%rip)
  6548. movq %rcx, %r11
  6549. movq $131, 0(%r11)
  6550. movq %rcx, %r11
  6551. movq -8(%r15), %rax
  6552. movq %rax, 8(%r11)
  6553. movq $0, %rdx
  6554. movq %rcx, %r11
  6555. movq 8(%r11), %rcx
  6556. movq %rcx, %r11
  6557. movq 8(%r11), %rax
  6558. jmp conclusion
  6559. block36:
  6560. movq $0, %rcx
  6561. jmp block35
  6562. block38:
  6563. movq free_ptr(%rip), %rcx
  6564. addq $16, free_ptr(%rip)
  6565. movq %rcx, %r11
  6566. movq $3, 0(%r11)
  6567. movq %rcx, %r11
  6568. movq %rbx, 8(%r11)
  6569. movq $0, %rdx
  6570. movq %rcx, -8(%r15)
  6571. movq free_ptr(%rip), %rcx
  6572. addq $16, %rcx
  6573. movq fromspace_end(%rip), %rdx
  6574. cmpq %rdx, %rcx
  6575. jl block36
  6576. movq %r15, %rdi
  6577. movq $16, %rsi
  6578. callq collect
  6579. jmp block35
  6580. block39:
  6581. movq $0, %rcx
  6582. jmp block38
  6583. \end{lstlisting}
  6584. \end{minipage}
  6585. \begin{minipage}[t]{0.45\textwidth}
  6586. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6587. start:
  6588. movq $42, %rbx
  6589. movq free_ptr(%rip), %rdx
  6590. addq $16, %rdx
  6591. movq fromspace_end(%rip), %rcx
  6592. cmpq %rcx, %rdx
  6593. jl block39
  6594. movq %r15, %rdi
  6595. movq $16, %rsi
  6596. callq collect
  6597. jmp block38
  6598. .globl main
  6599. main:
  6600. pushq %rbp
  6601. movq %rsp, %rbp
  6602. pushq %r13
  6603. pushq %r12
  6604. pushq %rbx
  6605. pushq %r14
  6606. subq $0, %rsp
  6607. movq $16384, %rdi
  6608. movq $16384, %rsi
  6609. callq initialize
  6610. movq rootstack_begin(%rip), %r15
  6611. movq $0, (%r15)
  6612. addq $8, %r15
  6613. jmp start
  6614. conclusion:
  6615. subq $8, %r15
  6616. addq $0, %rsp
  6617. popq %r14
  6618. popq %rbx
  6619. popq %r12
  6620. popq %r13
  6621. popq %rbp
  6622. retq
  6623. \end{lstlisting}
  6624. \end{minipage}
  6625. \caption{Output of the \code{print-x86} pass.}
  6626. \label{fig:print-x86-output-gc}
  6627. \end{figure}
  6628. \begin{figure}[p]
  6629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6630. \node (Rvec) at (0,2) {\large \LangVec{}};
  6631. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6632. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6633. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6634. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6635. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6636. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6637. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6638. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6639. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6640. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6641. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6642. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6643. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6644. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6645. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6646. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6647. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6648. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6649. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6650. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6651. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6652. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6653. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6654. \end{tikzpicture}
  6655. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6656. \label{fig:Rvec-passes}
  6657. \end{figure}
  6658. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6659. for the compilation of \LangVec{}.
  6660. \section{Challenge: Simple Structures}
  6661. \label{sec:simple-structures}
  6662. \index{subject}{struct}
  6663. \index{subject}{structure}
  6664. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6665. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6666. Recall that a \code{struct} in Typed Racket is a user-defined data
  6667. type that contains named fields and that is heap allocated, similar to
  6668. a vector. The following is an example of a structure definition, in
  6669. this case the definition of a \code{point} type.
  6670. \begin{lstlisting}
  6671. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6672. \end{lstlisting}
  6673. \begin{figure}[tbp]
  6674. \centering
  6675. \fbox{
  6676. \begin{minipage}{0.96\textwidth}
  6677. \[
  6678. \begin{array}{lcl}
  6679. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6680. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6681. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6682. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6683. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6684. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6685. \mid (\key{and}\;\Exp\;\Exp)
  6686. \mid (\key{or}\;\Exp\;\Exp)
  6687. \mid (\key{not}\;\Exp) } \\
  6688. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6689. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6690. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6691. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6692. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6693. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6694. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6695. \LangStruct{} &::=& \Def \ldots \; \Exp
  6696. \end{array}
  6697. \]
  6698. \end{minipage}
  6699. }
  6700. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6701. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6702. \label{fig:r3s-concrete-syntax}
  6703. \end{figure}
  6704. An instance of a structure is created using function call syntax, with
  6705. the name of the structure in the function position:
  6706. \begin{lstlisting}
  6707. (point 7 12)
  6708. \end{lstlisting}
  6709. Function-call syntax is also used to read the value in a field of a
  6710. structure. The function name is formed by the structure name, a dash,
  6711. and the field name. The following example uses \code{point-x} and
  6712. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6713. instances.
  6714. \begin{center}
  6715. \begin{lstlisting}
  6716. (let ([pt1 (point 7 12)])
  6717. (let ([pt2 (point 4 3)])
  6718. (+ (- (point-x pt1) (point-x pt2))
  6719. (- (point-y pt1) (point-y pt2)))))
  6720. \end{lstlisting}
  6721. \end{center}
  6722. Similarly, to write to a field of a structure, use its set function,
  6723. whose name starts with \code{set-}, followed by the structure name,
  6724. then a dash, then the field name, and concluded with an exclamation
  6725. mark. The following example uses \code{set-point-x!} to change the
  6726. \code{x} field from \code{7} to \code{42}.
  6727. \begin{center}
  6728. \begin{lstlisting}
  6729. (let ([pt (point 7 12)])
  6730. (let ([_ (set-point-x! pt 42)])
  6731. (point-x pt)))
  6732. \end{lstlisting}
  6733. \end{center}
  6734. \begin{exercise}\normalfont
  6735. Extend your compiler with support for simple structures, compiling
  6736. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6737. structures and test your compiler.
  6738. \end{exercise}
  6739. \section{Challenge: Generational Collection}
  6740. The copying collector described in Section~\ref{sec:GC} can incur
  6741. significant runtime overhead because the call to \code{collect} takes
  6742. time proportional to all of the live data. One way to reduce this
  6743. overhead is to reduce how much data is inspected in each call to
  6744. \code{collect}. In particular, researchers have observed that recently
  6745. allocated data is more likely to become garbage then data that has
  6746. survived one or more previous calls to \code{collect}. This insight
  6747. motivated the creation of \emph{generational garbage collectors}
  6748. \index{subject}{generational garbage collector} that
  6749. 1) segregates data according to its age into two or more generations,
  6750. 2) allocates less space for younger generations, so collecting them is
  6751. faster, and more space for the older generations, and 3) performs
  6752. collection on the younger generations more frequently then for older
  6753. generations~\citep{Wilson:1992fk}.
  6754. For this challenge assignment, the goal is to adapt the copying
  6755. collector implemented in \code{runtime.c} to use two generations, one
  6756. for young data and one for old data. Each generation consists of a
  6757. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6758. \code{collect} function to use the two generations.
  6759. \begin{enumerate}
  6760. \item Copy the young generation's FromSpace to its ToSpace then switch
  6761. the role of the ToSpace and FromSpace
  6762. \item If there is enough space for the requested number of bytes in
  6763. the young FromSpace, then return from \code{collect}.
  6764. \item If there is not enough space in the young FromSpace for the
  6765. requested bytes, then move the data from the young generation to the
  6766. old one with the following steps:
  6767. \begin{enumerate}
  6768. \item If there is enough room in the old FromSpace, copy the young
  6769. FromSpace to the old FromSpace and then return.
  6770. \item If there is not enough room in the old FromSpace, then collect
  6771. the old generation by copying the old FromSpace to the old ToSpace
  6772. and swap the roles of the old FromSpace and ToSpace.
  6773. \item If there is enough room now, copy the young FromSpace to the
  6774. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6775. and ToSpace for the old generation. Copy the young FromSpace and
  6776. the old FromSpace into the larger FromSpace for the old
  6777. generation and then return.
  6778. \end{enumerate}
  6779. \end{enumerate}
  6780. We recommend that you generalize the \code{cheney} function so that it
  6781. can be used for all the copies mentioned above: between the young
  6782. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6783. between the young FromSpace and old FromSpace. This can be
  6784. accomplished by adding parameters to \code{cheney} that replace its
  6785. use of the global variables \code{fromspace\_begin},
  6786. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6787. Note that the collection of the young generation does not traverse the
  6788. old generation. This introduces a potential problem: there may be
  6789. young data that is only reachable through pointers in the old
  6790. generation. If these pointers are not taken into account, the
  6791. collector could throw away young data that is live! One solution,
  6792. called \emph{pointer recording}, is to maintain a set of all the
  6793. pointers from the old generation into the new generation and consider
  6794. this set as part of the root set. To maintain this set, the compiler
  6795. must insert extra instructions around every \code{vector-set!}. If the
  6796. vector being modified is in the old generation, and if the value being
  6797. written is a pointer into the new generation, than that pointer must
  6798. be added to the set. Also, if the value being overwritten was a
  6799. pointer into the new generation, then that pointer should be removed
  6800. from the set.
  6801. \begin{exercise}\normalfont
  6802. Adapt the \code{collect} function in \code{runtime.c} to implement
  6803. generational garbage collection, as outlined in this section.
  6804. Update the code generation for \code{vector-set!} to implement
  6805. pointer recording. Make sure that your new compiler and runtime
  6806. passes your test suite.
  6807. \end{exercise}
  6808. % Further Reading
  6809. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6810. \chapter{Functions}
  6811. \label{ch:Rfun}
  6812. \index{subject}{function}
  6813. This chapter studies the compilation of functions similar to those
  6814. found in the C language. This corresponds to a subset of Typed Racket
  6815. in which only top-level function definitions are allowed. This kind of
  6816. function is an important stepping stone to implementing
  6817. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6818. is the topic of Chapter~\ref{ch:Rlam}.
  6819. \section{The \LangFun{} Language}
  6820. The concrete and abstract syntax for function definitions and function
  6821. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6822. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6823. \LangFun{} begin with zero or more function definitions. The function
  6824. names from these definitions are in-scope for the entire program,
  6825. including all other function definitions (so the ordering of function
  6826. definitions does not matter). The concrete syntax for function
  6827. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  6828. where the first expression must
  6829. evaluate to a function and the rest are the arguments.
  6830. The abstract syntax for function application is
  6831. $\APPLY{\Exp}{\Exp\ldots}$.
  6832. %% The syntax for function application does not include an explicit
  6833. %% keyword, which is error prone when using \code{match}. To alleviate
  6834. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6835. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6836. Functions are first-class in the sense that a function pointer
  6837. \index{subject}{function pointer} is data and can be stored in memory or passed
  6838. as a parameter to another function. Thus, we introduce a function
  6839. type, written
  6840. \begin{lstlisting}
  6841. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6842. \end{lstlisting}
  6843. for a function whose $n$ parameters have the types $\Type_1$ through
  6844. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6845. these functions (with respect to Racket functions) is that they are
  6846. not lexically scoped. That is, the only external entities that can be
  6847. referenced from inside a function body are other globally-defined
  6848. functions. The syntax of \LangFun{} prevents functions from being nested
  6849. inside each other.
  6850. \begin{figure}[tp]
  6851. \centering
  6852. \fbox{
  6853. \begin{minipage}{0.96\textwidth}
  6854. \small
  6855. \[
  6856. \begin{array}{lcl}
  6857. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6858. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6859. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6860. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6861. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6862. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6863. \mid (\key{and}\;\Exp\;\Exp)
  6864. \mid (\key{or}\;\Exp\;\Exp)
  6865. \mid (\key{not}\;\Exp)} \\
  6866. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6867. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6868. (\key{vector-ref}\;\Exp\;\Int)} \\
  6869. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6870. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6871. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6872. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6873. \LangFunM{} &::=& \Def \ldots \; \Exp
  6874. \end{array}
  6875. \]
  6876. \end{minipage}
  6877. }
  6878. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6879. \label{fig:Rfun-concrete-syntax}
  6880. \end{figure}
  6881. \begin{figure}[tp]
  6882. \centering
  6883. \fbox{
  6884. \begin{minipage}{0.96\textwidth}
  6885. \small
  6886. \[
  6887. \begin{array}{lcl}
  6888. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6889. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6890. &\mid& \gray{ \BOOL{\itm{bool}}
  6891. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6892. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6893. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6894. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6895. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6896. \end{array}
  6897. \]
  6898. \end{minipage}
  6899. }
  6900. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6901. \label{fig:Rfun-syntax}
  6902. \end{figure}
  6903. The program in Figure~\ref{fig:Rfun-function-example} is a
  6904. representative example of defining and using functions in \LangFun{}. We
  6905. define a function \code{map-vec} that applies some other function
  6906. \code{f} to both elements of a vector and returns a new
  6907. vector containing the results. We also define a function \code{add1}.
  6908. The program applies
  6909. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6910. \code{(vector 1 42)}, from which we return the \code{42}.
  6911. \begin{figure}[tbp]
  6912. \begin{lstlisting}
  6913. (define (map-vec [f : (Integer -> Integer)]
  6914. [v : (Vector Integer Integer)])
  6915. : (Vector Integer Integer)
  6916. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6917. (define (add1 [x : Integer]) : Integer
  6918. (+ x 1))
  6919. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6920. \end{lstlisting}
  6921. \caption{Example of using functions in \LangFun{}.}
  6922. \label{fig:Rfun-function-example}
  6923. \end{figure}
  6924. The definitional interpreter for \LangFun{} is in
  6925. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6926. responsible for setting up the mutual recursion between the top-level
  6927. function definitions. We use the classic back-patching \index{subject}{back-patching}
  6928. approach that uses mutable variables and makes two passes over the function
  6929. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6930. top-level environment using a mutable cons cell for each function
  6931. definition. Note that the \code{lambda} value for each function is
  6932. incomplete; it does not yet include the environment. Once the
  6933. top-level environment is constructed, we then iterate over it and
  6934. update the \code{lambda} values to use the top-level environment.
  6935. \begin{figure}[tp]
  6936. \begin{lstlisting}
  6937. (define interp-Rfun-class
  6938. (class interp-Rvec-class
  6939. (super-new)
  6940. (define/override ((interp-exp env) e)
  6941. (define recur (interp-exp env))
  6942. (match e
  6943. [(Var x) (unbox (dict-ref env x))]
  6944. [(Let x e body)
  6945. (define new-env (dict-set env x (box (recur e))))
  6946. ((interp-exp new-env) body)]
  6947. [(Apply fun args)
  6948. (define fun-val (recur fun))
  6949. (define arg-vals (for/list ([e args]) (recur e)))
  6950. (match fun-val
  6951. [`(function (,xs ...) ,body ,fun-env)
  6952. (define params-args (for/list ([x xs] [arg arg-vals])
  6953. (cons x (box arg))))
  6954. (define new-env (append params-args fun-env))
  6955. ((interp-exp new-env) body)]
  6956. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6957. [else ((super interp-exp env) e)]
  6958. ))
  6959. (define/public (interp-def d)
  6960. (match d
  6961. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6962. (cons f (box `(function ,xs ,body ())))]))
  6963. (define/override (interp-program p)
  6964. (match p
  6965. [(ProgramDefsExp info ds body)
  6966. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6967. (for/list ([f (in-dict-values top-level)])
  6968. (set-box! f (match (unbox f)
  6969. [`(function ,xs ,body ())
  6970. `(function ,xs ,body ,top-level)])))
  6971. ((interp-exp top-level) body))]))
  6972. ))
  6973. (define (interp-Rfun p)
  6974. (send (new interp-Rfun-class) interp-program p))
  6975. \end{lstlisting}
  6976. \caption{Interpreter for the \LangFun{} language.}
  6977. \label{fig:interp-Rfun}
  6978. \end{figure}
  6979. %\margincomment{TODO: explain type checker}
  6980. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  6981. \begin{figure}[tp]
  6982. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6983. (define type-check-Rfun-class
  6984. (class type-check-Rvec-class
  6985. (super-new)
  6986. (inherit check-type-equal?)
  6987. (define/public (type-check-apply env e es)
  6988. (define-values (e^ ty) ((type-check-exp env) e))
  6989. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6990. ((type-check-exp env) e)))
  6991. (match ty
  6992. [`(,ty^* ... -> ,rt)
  6993. (for ([arg-ty ty*] [param-ty ty^*])
  6994. (check-type-equal? arg-ty param-ty (Apply e es)))
  6995. (values e^ e* rt)]))
  6996. (define/override (type-check-exp env)
  6997. (lambda (e)
  6998. (match e
  6999. [(FunRef f)
  7000. (values (FunRef f) (dict-ref env f))]
  7001. [(Apply e es)
  7002. (define-values (e^ es^ rt) (type-check-apply env e es))
  7003. (values (Apply e^ es^) rt)]
  7004. [(Call e es)
  7005. (define-values (e^ es^ rt) (type-check-apply env e es))
  7006. (values (Call e^ es^) rt)]
  7007. [else ((super type-check-exp env) e)])))
  7008. (define/public (type-check-def env)
  7009. (lambda (e)
  7010. (match e
  7011. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7012. (define new-env (append (map cons xs ps) env))
  7013. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7014. (check-type-equal? ty^ rt body)
  7015. (Def f p:t* rt info body^)])))
  7016. (define/public (fun-def-type d)
  7017. (match d
  7018. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7019. (define/override (type-check-program e)
  7020. (match e
  7021. [(ProgramDefsExp info ds body)
  7022. (define new-env (for/list ([d ds])
  7023. (cons (Def-name d) (fun-def-type d))))
  7024. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7025. (define-values (body^ ty) ((type-check-exp new-env) body))
  7026. (check-type-equal? ty 'Integer body)
  7027. (ProgramDefsExp info ds^ body^)]))))
  7028. (define (type-check-Rfun p)
  7029. (send (new type-check-Rfun-class) type-check-program p))
  7030. \end{lstlisting}
  7031. \caption{Type checker for the \LangFun{} language.}
  7032. \label{fig:type-check-Rfun}
  7033. \end{figure}
  7034. \section{Functions in x86}
  7035. \label{sec:fun-x86}
  7036. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  7037. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7038. %% \margincomment{\tiny Talk about the return address on the
  7039. %% stack and what callq and retq does.\\ --Jeremy }
  7040. The x86 architecture provides a few features to support the
  7041. implementation of functions. We have already seen that x86 provides
  7042. labels so that one can refer to the location of an instruction, as is
  7043. needed for jump instructions. Labels can also be used to mark the
  7044. beginning of the instructions for a function. Going further, we can
  7045. obtain the address of a label by using the \key{leaq} instruction and
  7046. PC-relative addressing. For example, the following puts the
  7047. address of the \code{add1} label into the \code{rbx} register.
  7048. \begin{lstlisting}
  7049. leaq add1(%rip), %rbx
  7050. \end{lstlisting}
  7051. The instruction pointer register \key{rip} (aka. the program counter
  7052. \index{subject}{program counter}) always points to the next instruction to be
  7053. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7054. linker computes the distance $d$ between the address of \code{add1}
  7055. and where the \code{rip} would be at that moment and then changes
  7056. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7057. the address of \code{add1}.
  7058. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7059. jump to a function whose location is given by a label. To support
  7060. function calls in this chapter we instead will be jumping to a
  7061. function whose location is given by an address in a register, that is,
  7062. we need to make an \emph{indirect function call}. The x86 syntax for
  7063. this is a \code{callq} instruction but with an asterisk before the
  7064. register name.\index{subject}{indirect function call}
  7065. \begin{lstlisting}
  7066. callq *%rbx
  7067. \end{lstlisting}
  7068. \subsection{Calling Conventions}
  7069. \index{subject}{calling conventions}
  7070. The \code{callq} instruction provides partial support for implementing
  7071. functions: it pushes the return address on the stack and it jumps to
  7072. the target. However, \code{callq} does not handle
  7073. \begin{enumerate}
  7074. \item parameter passing,
  7075. \item pushing frames on the procedure call stack and popping them off,
  7076. or
  7077. \item determining how registers are shared by different functions.
  7078. \end{enumerate}
  7079. Regarding (1) parameter passing, recall that the following six
  7080. registers are used to pass arguments to a function, in this order.
  7081. \begin{lstlisting}
  7082. rdi rsi rdx rcx r8 r9
  7083. \end{lstlisting}
  7084. If there are
  7085. more than six arguments, then the convention is to use space on the
  7086. frame of the caller for the rest of the arguments. However, to ease
  7087. the implementation of efficient tail calls
  7088. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7089. arguments.
  7090. %
  7091. Also recall that the register \code{rax} is for the return value of
  7092. the function.
  7093. \index{subject}{prelude}\index{subject}{conclusion}
  7094. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  7095. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  7096. the stack grows down, with each function call using a chunk of space
  7097. called a frame. The caller sets the stack pointer, register
  7098. \code{rsp}, to the last data item in its frame. The callee must not
  7099. change anything in the caller's frame, that is, anything that is at or
  7100. above the stack pointer. The callee is free to use locations that are
  7101. below the stack pointer.
  7102. Recall that we are storing variables of vector type on the root stack.
  7103. So the prelude needs to move the root stack pointer \code{r15} up and
  7104. the conclusion needs to move the root stack pointer back down. Also,
  7105. the prelude must initialize to \code{0} this frame's slots in the root
  7106. stack to signal to the garbage collector that those slots do not yet
  7107. contain a pointer to a vector. Otherwise the garbage collector will
  7108. interpret the garbage bits in those slots as memory addresses and try
  7109. to traverse them, causing serious mayhem!
  7110. Regarding (3) the sharing of registers between different functions,
  7111. recall from Section~\ref{sec:calling-conventions} that the registers
  7112. are divided into two groups, the caller-saved registers and the
  7113. callee-saved registers. The caller should assume that all the
  7114. caller-saved registers get overwritten with arbitrary values by the
  7115. callee. That is why we recommend in
  7116. Section~\ref{sec:calling-conventions} that variables that are live
  7117. during a function call should not be assigned to caller-saved
  7118. registers.
  7119. On the flip side, if the callee wants to use a callee-saved register,
  7120. the callee must save the contents of those registers on their stack
  7121. frame and then put them back prior to returning to the caller. That
  7122. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7123. the register allocator assigns a variable to a callee-saved register,
  7124. then the prelude of the \code{main} function must save that register
  7125. to the stack and the conclusion of \code{main} must restore it. This
  7126. recommendation now generalizes to all functions.
  7127. Also recall that the base pointer, register \code{rbp}, is used as a
  7128. point-of-reference within a frame, so that each local variable can be
  7129. accessed at a fixed offset from the base pointer
  7130. (Section~\ref{sec:x86}).
  7131. %
  7132. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7133. and callee frames.
  7134. \begin{figure}[tbp]
  7135. \centering
  7136. \begin{tabular}{r|r|l|l} \hline
  7137. Caller View & Callee View & Contents & Frame \\ \hline
  7138. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7139. 0(\key{\%rbp}) & & old \key{rbp} \\
  7140. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7141. \ldots & & \ldots \\
  7142. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7143. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7144. \ldots & & \ldots \\
  7145. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7146. %% & & \\
  7147. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7148. %% & \ldots & \ldots \\
  7149. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7150. \hline
  7151. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7152. & 0(\key{\%rbp}) & old \key{rbp} \\
  7153. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7154. & \ldots & \ldots \\
  7155. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7156. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7157. & \ldots & \ldots \\
  7158. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7159. \end{tabular}
  7160. \caption{Memory layout of caller and callee frames.}
  7161. \label{fig:call-frames}
  7162. \end{figure}
  7163. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7164. %% local variables and for storing the values of callee-saved registers
  7165. %% (we shall refer to all of these collectively as ``locals''), and that
  7166. %% at the beginning of a function we move the stack pointer \code{rsp}
  7167. %% down to make room for them.
  7168. %% We recommend storing the local variables
  7169. %% first and then the callee-saved registers, so that the local variables
  7170. %% can be accessed using \code{rbp} the same as before the addition of
  7171. %% functions.
  7172. %% To make additional room for passing arguments, we shall
  7173. %% move the stack pointer even further down. We count how many stack
  7174. %% arguments are needed for each function call that occurs inside the
  7175. %% body of the function and find their maximum. Adding this number to the
  7176. %% number of locals gives us how much the \code{rsp} should be moved at
  7177. %% the beginning of the function. In preparation for a function call, we
  7178. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7179. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7180. %% so on.
  7181. %% Upon calling the function, the stack arguments are retrieved by the
  7182. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7183. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7184. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7185. %% the layout of the caller and callee frames. Notice how important it is
  7186. %% that we correctly compute the maximum number of arguments needed for
  7187. %% function calls; if that number is too small then the arguments and
  7188. %% local variables will smash into each other!
  7189. \subsection{Efficient Tail Calls}
  7190. \label{sec:tail-call}
  7191. In general, the amount of stack space used by a program is determined
  7192. by the longest chain of nested function calls. That is, if function
  7193. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7194. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7195. $n$ can grow quite large in the case of recursive or mutually
  7196. recursive functions. However, in some cases we can arrange to use only
  7197. constant space, i.e. $O(1)$, instead of $O(n)$.
  7198. If a function call is the last action in a function body, then that
  7199. call is said to be a \emph{tail call}\index{subject}{tail call}.
  7200. For example, in the following
  7201. program, the recursive call to \code{tail-sum} is a tail call.
  7202. \begin{center}
  7203. \begin{lstlisting}
  7204. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7205. (if (eq? n 0)
  7206. r
  7207. (tail-sum (- n 1) (+ n r))))
  7208. (+ (tail-sum 5 0) 27)
  7209. \end{lstlisting}
  7210. \end{center}
  7211. At a tail call, the frame of the caller is no longer needed, so we
  7212. can pop the caller's frame before making the tail call. With this
  7213. approach, a recursive function that only makes tail calls will only
  7214. use $O(1)$ stack space. Functional languages like Racket typically
  7215. rely heavily on recursive functions, so they typically guarantee that
  7216. all tail calls will be optimized in this way.
  7217. \index{subject}{frame}
  7218. However, some care is needed with regards to argument passing in tail
  7219. calls. As mentioned above, for arguments beyond the sixth, the
  7220. convention is to use space in the caller's frame for passing
  7221. arguments. But for a tail call we pop the caller's frame and can no
  7222. longer use it. Another alternative is to use space in the callee's
  7223. frame for passing arguments. However, this option is also problematic
  7224. because the caller and callee's frame overlap in memory. As we begin
  7225. to copy the arguments from their sources in the caller's frame, the
  7226. target locations in the callee's frame might overlap with the sources
  7227. for later arguments! We solve this problem by not using the stack for
  7228. passing more than six arguments but instead using the heap, as we
  7229. describe in the Section~\ref{sec:limit-functions-r4}.
  7230. As mentioned above, for a tail call we pop the caller's frame prior to
  7231. making the tail call. The instructions for popping a frame are the
  7232. instructions that we usually place in the conclusion of a
  7233. function. Thus, we also need to place such code immediately before
  7234. each tail call. These instructions include restoring the callee-saved
  7235. registers, so it is good that the argument passing registers are all
  7236. caller-saved registers.
  7237. One last note regarding which instruction to use to make the tail
  7238. call. When the callee is finished, it should not return to the current
  7239. function, but it should return to the function that called the current
  7240. one. Thus, the return address that is already on the stack is the
  7241. right one, and we should not use \key{callq} to make the tail call, as
  7242. that would unnecessarily overwrite the return address. Instead we can
  7243. simply use the \key{jmp} instruction. Like the indirect function call,
  7244. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  7245. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7246. jump target because the preceding conclusion overwrites just about
  7247. everything else.
  7248. \begin{lstlisting}
  7249. jmp *%rax
  7250. \end{lstlisting}
  7251. \section{Shrink \LangFun{}}
  7252. \label{sec:shrink-r4}
  7253. The \code{shrink} pass performs a minor modification to ease the
  7254. later passes. This pass introduces an explicit \code{main} function
  7255. and changes the top \code{ProgramDefsExp} form to
  7256. \code{ProgramDefs} as follows.
  7257. \begin{lstlisting}
  7258. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7259. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7260. \end{lstlisting}
  7261. where $\itm{mainDef}$ is
  7262. \begin{lstlisting}
  7263. (Def 'main '() 'Integer '() |$\Exp'$|)
  7264. \end{lstlisting}
  7265. \section{Reveal Functions and the \LangFunRef{} language}
  7266. \label{sec:reveal-functions-r4}
  7267. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7268. respect: it conflates the use of function names and local
  7269. variables. This is a problem because we need to compile the use of a
  7270. function name differently than the use of a local variable; we need to
  7271. use \code{leaq} to convert the function name (a label in x86) to an
  7272. address in a register. Thus, it is a good idea to create a new pass
  7273. that changes function references from just a symbol $f$ to
  7274. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7275. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7276. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7277. \begin{figure}[tp]
  7278. \centering
  7279. \fbox{
  7280. \begin{minipage}{0.96\textwidth}
  7281. \[
  7282. \begin{array}{lcl}
  7283. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7284. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7285. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7286. \end{array}
  7287. \]
  7288. \end{minipage}
  7289. }
  7290. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7291. (Figure~\ref{fig:Rfun-syntax}).}
  7292. \label{fig:f1-syntax}
  7293. \end{figure}
  7294. %% Distinguishing between calls in tail position and non-tail position
  7295. %% requires the pass to have some notion of context. We recommend using
  7296. %% two mutually recursive functions, one for processing expressions in
  7297. %% tail position and another for the rest.
  7298. Placing this pass after \code{uniquify} will make sure that there are
  7299. no local variables and functions that share the same name. On the
  7300. other hand, \code{reveal-functions} needs to come before the
  7301. \code{explicate-control} pass because that pass helps us compile
  7302. \code{FunRef} forms into assignment statements.
  7303. \section{Limit Functions}
  7304. \label{sec:limit-functions-r4}
  7305. Recall that we wish to limit the number of function parameters to six
  7306. so that we do not need to use the stack for argument passing, which
  7307. makes it easier to implement efficient tail calls. However, because
  7308. the input language \LangFun{} supports arbitrary numbers of function
  7309. arguments, we have some work to do!
  7310. This pass transforms functions and function calls that involve more
  7311. than six arguments to pass the first five arguments as usual, but it
  7312. packs the rest of the arguments into a vector and passes it as the
  7313. sixth argument.
  7314. Each function definition with too many parameters is transformed as
  7315. follows.
  7316. \begin{lstlisting}
  7317. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7318. |$\Rightarrow$|
  7319. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7320. \end{lstlisting}
  7321. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7322. the occurrences of the later parameters with vector references.
  7323. \begin{lstlisting}
  7324. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7325. \end{lstlisting}
  7326. For function calls with too many arguments, the \code{limit-functions}
  7327. pass transforms them in the following way.
  7328. \begin{tabular}{lll}
  7329. \begin{minipage}{0.2\textwidth}
  7330. \begin{lstlisting}
  7331. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7332. \end{lstlisting}
  7333. \end{minipage}
  7334. &
  7335. $\Rightarrow$
  7336. &
  7337. \begin{minipage}{0.4\textwidth}
  7338. \begin{lstlisting}
  7339. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7340. \end{lstlisting}
  7341. \end{minipage}
  7342. \end{tabular}
  7343. \section{Remove Complex Operands}
  7344. \label{sec:rco-r4}
  7345. The primary decisions to make for this pass is whether to classify
  7346. \code{FunRef} and \code{Apply} as either atomic or complex
  7347. expressions. Recall that a simple expression will eventually end up as
  7348. just an immediate argument of an x86 instruction. Function
  7349. application will be translated to a sequence of instructions, so
  7350. \code{Apply} must be classified as complex expression.
  7351. On the other hand, the arguments of \code{Apply} should be
  7352. atomic expressions.
  7353. %
  7354. Regarding \code{FunRef}, as discussed above, the function label needs
  7355. to be converted to an address using the \code{leaq} instruction. Thus,
  7356. even though \code{FunRef} seems rather simple, it needs to be
  7357. classified as a complex expression so that we generate an assignment
  7358. statement with a left-hand side that can serve as the target of the
  7359. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7360. output language \LangFunANF{} of this pass.
  7361. \begin{figure}[tp]
  7362. \centering
  7363. \fbox{
  7364. \begin{minipage}{0.96\textwidth}
  7365. \small
  7366. \[
  7367. \begin{array}{rcl}
  7368. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7369. \mid \VOID{} } \\
  7370. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7371. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7372. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7373. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7374. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7375. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7376. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7377. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7378. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7379. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7380. \end{array}
  7381. \]
  7382. \end{minipage}
  7383. }
  7384. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7385. \label{fig:Rfun-anf-syntax}
  7386. \end{figure}
  7387. \section{Explicate Control and the \LangCFun{} language}
  7388. \label{sec:explicate-control-r4}
  7389. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7390. output of \key{explicate-control}. (The concrete syntax is given in
  7391. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7392. functions for assignment and tail contexts should be updated with
  7393. cases for \code{Apply} and \code{FunRef} and the function for
  7394. predicate context should be updated for \code{Apply} but not
  7395. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7396. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7397. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7398. defining a new auxiliary function for processing function definitions.
  7399. This code is similar to the case for \code{Program} in \LangVec{}. The
  7400. top-level \code{explicate-control} function that handles the
  7401. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7402. all the function definitions.
  7403. \begin{figure}[tp]
  7404. \fbox{
  7405. \begin{minipage}{0.96\textwidth}
  7406. \small
  7407. \[
  7408. \begin{array}{lcl}
  7409. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7410. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7411. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7412. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7413. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7414. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7415. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7416. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7417. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7418. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7419. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7420. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7421. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7422. \mid \GOTO{\itm{label}} } \\
  7423. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7424. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7425. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7426. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7427. \end{array}
  7428. \]
  7429. \end{minipage}
  7430. }
  7431. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7432. \label{fig:c3-syntax}
  7433. \end{figure}
  7434. \section{Select Instructions and the \LangXIndCall{} Language}
  7435. \label{sec:select-r4}
  7436. \index{subject}{instruction selection}
  7437. The output of select instructions is a program in the \LangXIndCall{}
  7438. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7439. \index{subject}{x86}
  7440. \begin{figure}[tp]
  7441. \fbox{
  7442. \begin{minipage}{0.96\textwidth}
  7443. \small
  7444. \[
  7445. \begin{array}{lcl}
  7446. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7447. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7448. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7449. \Instr &::=& \ldots
  7450. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7451. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7452. \Block &::= & \Instr\ldots \\
  7453. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7454. \LangXIndCallM{} &::= & \Def\ldots
  7455. \end{array}
  7456. \]
  7457. \end{minipage}
  7458. }
  7459. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7460. \label{fig:x86-3-concrete}
  7461. \end{figure}
  7462. \begin{figure}[tp]
  7463. \fbox{
  7464. \begin{minipage}{0.96\textwidth}
  7465. \small
  7466. \[
  7467. \begin{array}{lcl}
  7468. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7469. \mid \BYTEREG{\Reg} } \\
  7470. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7471. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7472. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7473. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7474. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7475. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7476. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7477. \end{array}
  7478. \]
  7479. \end{minipage}
  7480. }
  7481. \caption{The abstract syntax of \LangXIndCall{} (extends
  7482. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7483. \label{fig:x86-3}
  7484. \end{figure}
  7485. An assignment of a function reference to a variable becomes a
  7486. load-effective-address instruction as follows: \\
  7487. \begin{tabular}{lcl}
  7488. \begin{minipage}{0.35\textwidth}
  7489. \begin{lstlisting}
  7490. |$\itm{lhs}$| = (fun-ref |$f$|);
  7491. \end{lstlisting}
  7492. \end{minipage}
  7493. &
  7494. $\Rightarrow$\qquad\qquad
  7495. &
  7496. \begin{minipage}{0.3\textwidth}
  7497. \begin{lstlisting}
  7498. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7499. \end{lstlisting}
  7500. \end{minipage}
  7501. \end{tabular} \\
  7502. Regarding function definitions, we need to remove the parameters and
  7503. instead perform parameter passing using the conventions discussed in
  7504. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7505. registers. We recommend turning the parameters into local variables
  7506. and generating instructions at the beginning of the function to move
  7507. from the argument passing registers to these local variables.
  7508. \begin{lstlisting}
  7509. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7510. |$\Rightarrow$|
  7511. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7512. \end{lstlisting}
  7513. The $G'$ control-flow graph is the same as $G$ except that the
  7514. \code{start} block is modified to add the instructions for moving from
  7515. the argument registers to the parameter variables. So the \code{start}
  7516. block of $G$ shown on the left is changed to the code on the right.
  7517. \begin{center}
  7518. \begin{minipage}{0.3\textwidth}
  7519. \begin{lstlisting}
  7520. start:
  7521. |$\itm{instr}_1$|
  7522. |$\vdots$|
  7523. |$\itm{instr}_n$|
  7524. \end{lstlisting}
  7525. \end{minipage}
  7526. $\Rightarrow$
  7527. \begin{minipage}{0.3\textwidth}
  7528. \begin{lstlisting}
  7529. start:
  7530. movq %rdi, |$x_1$|
  7531. movq %rsi, |$x_2$|
  7532. |$\vdots$|
  7533. |$\itm{instr}_1$|
  7534. |$\vdots$|
  7535. |$\itm{instr}_n$|
  7536. \end{lstlisting}
  7537. \end{minipage}
  7538. \end{center}
  7539. By changing the parameters to local variables, we are giving the
  7540. register allocator control over which registers or stack locations to
  7541. use for them. If you implemented the move-biasing challenge
  7542. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7543. assign the parameter variables to the corresponding argument register,
  7544. in which case the \code{patch-instructions} pass will remove the
  7545. \code{movq} instruction. This happens in the example translation in
  7546. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7547. the \code{add} function.
  7548. %
  7549. Also, note that the register allocator will perform liveness analysis
  7550. on this sequence of move instructions and build the interference
  7551. graph. So, for example, $x_1$ will be marked as interfering with
  7552. \code{rsi} and that will prevent the assignment of $x_1$ to
  7553. \code{rsi}, which is good, because that would overwrite the argument
  7554. that needs to move into $x_2$.
  7555. Next, consider the compilation of function calls. In the mirror image
  7556. of handling the parameters of function definitions, the arguments need
  7557. to be moved to the argument passing registers. The function call
  7558. itself is performed with an indirect function call. The return value
  7559. from the function is stored in \code{rax}, so it needs to be moved
  7560. into the \itm{lhs}.
  7561. \begin{lstlisting}
  7562. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7563. |$\Rightarrow$|
  7564. movq |$\itm{arg}_1$|, %rdi
  7565. movq |$\itm{arg}_2$|, %rsi
  7566. |$\vdots$|
  7567. callq *|\itm{fun}|
  7568. movq %rax, |\itm{lhs}|
  7569. \end{lstlisting}
  7570. The \code{IndirectCallq} AST node includes an integer for the arity of
  7571. the function, i.e., the number of parameters. That information is
  7572. useful in the \code{uncover-live} pass for determining which
  7573. argument-passing registers are potentially read during the call.
  7574. For tail calls, the parameter passing is the same as non-tail calls:
  7575. generate instructions to move the arguments into to the argument
  7576. passing registers. After that we need to pop the frame from the
  7577. procedure call stack. However, we do not yet know how big the frame
  7578. is; that gets determined during register allocation. So instead of
  7579. generating those instructions here, we invent a new instruction that
  7580. means ``pop the frame and then do an indirect jump'', which we name
  7581. \code{TailJmp}. The abstract syntax for this instruction includes an
  7582. argument that specifies where to jump and an integer that represents
  7583. the arity of the function being called.
  7584. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7585. using the label \code{start} for the initial block of a program, and
  7586. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7587. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7588. can be compiled to an assignment to \code{rax} followed by a jump to
  7589. \code{conclusion}. With the addition of function definitions, we will
  7590. have a starting block and conclusion for each function, but their
  7591. labels need to be unique. We recommend prepending the function's name
  7592. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7593. labels. (Alternatively, one could \code{gensym} labels for the start
  7594. and conclusion and store them in the $\itm{info}$ field of the
  7595. function definition.)
  7596. \section{Register Allocation}
  7597. \label{sec:register-allocation-r4}
  7598. \subsection{Liveness Analysis}
  7599. \label{sec:liveness-analysis-r4}
  7600. \index{subject}{liveness analysis}
  7601. %% The rest of the passes need only minor modifications to handle the new
  7602. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7603. %% \code{leaq}.
  7604. The \code{IndirectCallq} instruction should be treated like
  7605. \code{Callq} regarding its written locations $W$, in that they should
  7606. include all the caller-saved registers. Recall that the reason for
  7607. that is to force call-live variables to be assigned to callee-saved
  7608. registers or to be spilled to the stack.
  7609. Regarding the set of read locations $R$ the arity field of
  7610. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7611. argument-passing registers should be considered as read by those
  7612. instructions.
  7613. \subsection{Build Interference Graph}
  7614. \label{sec:build-interference-r4}
  7615. With the addition of function definitions, we compute an interference
  7616. graph for each function (not just one for the whole program).
  7617. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7618. spill vector-typed variables that are live during a call to the
  7619. \code{collect}. With the addition of functions to our language, we
  7620. need to revisit this issue. Many functions perform allocation and
  7621. therefore have calls to the collector inside of them. Thus, we should
  7622. not only spill a vector-typed variable when it is live during a call
  7623. to \code{collect}, but we should spill the variable if it is live
  7624. during any function call. Thus, in the \code{build-interference} pass,
  7625. we recommend adding interference edges between call-live vector-typed
  7626. variables and the callee-saved registers (in addition to the usual
  7627. addition of edges between call-live variables and the caller-saved
  7628. registers).
  7629. \subsection{Allocate Registers}
  7630. The primary change to the \code{allocate-registers} pass is adding an
  7631. auxiliary function for handling definitions (the \Def{} non-terminal
  7632. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7633. logic is the same as described in
  7634. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7635. allocation is performed many times, once for each function definition,
  7636. instead of just once for the whole program.
  7637. \section{Patch Instructions}
  7638. In \code{patch-instructions}, you should deal with the x86
  7639. idiosyncrasy that the destination argument of \code{leaq} must be a
  7640. register. Additionally, you should ensure that the argument of
  7641. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7642. code generation more convenient, because we trample many registers
  7643. before the tail call (as explained in the next section).
  7644. \section{Print x86}
  7645. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7646. \code{IndirectCallq} are straightforward: output their concrete
  7647. syntax.
  7648. \begin{lstlisting}
  7649. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7650. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7651. \end{lstlisting}
  7652. The \code{TailJmp} node requires a bit work. A straightforward
  7653. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7654. before the jump we need to pop the current frame. This sequence of
  7655. instructions is the same as the code for the conclusion of a function,
  7656. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7657. Regarding function definitions, you will need to generate a prelude
  7658. and conclusion for each one. This code is similar to the prelude and
  7659. conclusion that you generated for the \code{main} function in
  7660. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7661. should carry out the following steps.
  7662. \begin{enumerate}
  7663. \item Start with \code{.global} and \code{.align} directives followed
  7664. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7665. example.)
  7666. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7667. pointer.
  7668. \item Push to the stack all of the callee-saved registers that were
  7669. used for register allocation.
  7670. \item Move the stack pointer \code{rsp} down by the size of the stack
  7671. frame for this function, which depends on the number of regular
  7672. spills. (Aligned to 16 bytes.)
  7673. \item Move the root stack pointer \code{r15} up by the size of the
  7674. root-stack frame for this function, which depends on the number of
  7675. spilled vectors. \label{root-stack-init}
  7676. \item Initialize to zero all of the entries in the root-stack frame.
  7677. \item Jump to the start block.
  7678. \end{enumerate}
  7679. The prelude of the \code{main} function has one additional task: call
  7680. the \code{initialize} function to set up the garbage collector and
  7681. move the value of the global \code{rootstack\_begin} in
  7682. \code{r15}. This should happen before step \ref{root-stack-init}
  7683. above, which depends on \code{r15}.
  7684. The conclusion of every function should do the following.
  7685. \begin{enumerate}
  7686. \item Move the stack pointer back up by the size of the stack frame
  7687. for this function.
  7688. \item Restore the callee-saved registers by popping them from the
  7689. stack.
  7690. \item Move the root stack pointer back down by the size of the
  7691. root-stack frame for this function.
  7692. \item Restore \code{rbp} by popping it from the stack.
  7693. \item Return to the caller with the \code{retq} instruction.
  7694. \end{enumerate}
  7695. \begin{exercise}\normalfont
  7696. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7697. Create 5 new programs that use functions, including examples that pass
  7698. functions and return functions from other functions, recursive
  7699. functions, functions that create vectors, and functions that make tail
  7700. calls. Test your compiler on these new programs and all of your
  7701. previously created test programs.
  7702. \end{exercise}
  7703. \begin{figure}[tbp]
  7704. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7705. \node (Rfun) at (0,2) {\large \LangFun{}};
  7706. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7707. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7708. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7709. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7710. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7711. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7712. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7713. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7714. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7715. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7716. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7717. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7718. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7719. \path[->,bend left=15] (Rfun) edge [above] node
  7720. {\ttfamily\footnotesize shrink} (Rfun-1);
  7721. \path[->,bend left=15] (Rfun-1) edge [above] node
  7722. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7723. \path[->,bend left=15] (Rfun-2) edge [right] node
  7724. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7725. \path[->,bend left=15] (F1-1) edge [below] node
  7726. {\ttfamily\footnotesize limit-functions} (F1-2);
  7727. \path[->,bend right=15] (F1-2) edge [above] node
  7728. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7729. \path[->,bend right=15] (F1-3) edge [above] node
  7730. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7731. \path[->,bend left=15] (F1-4) edge [right] node
  7732. {\ttfamily\footnotesize explicate-control} (C3-2);
  7733. \path[->,bend right=15] (C3-2) edge [left] node
  7734. {\ttfamily\footnotesize select-instr.} (x86-2);
  7735. \path[->,bend left=15] (x86-2) edge [left] node
  7736. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7737. \path[->,bend right=15] (x86-2-1) edge [below] node
  7738. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7739. \path[->,bend right=15] (x86-2-2) edge [left] node
  7740. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7741. \path[->,bend left=15] (x86-3) edge [above] node
  7742. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7743. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7744. \end{tikzpicture}
  7745. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7746. \label{fig:Rfun-passes}
  7747. \end{figure}
  7748. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7749. compiling \LangFun{} to x86.
  7750. \section{An Example Translation}
  7751. \label{sec:functions-example}
  7752. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7753. function in \LangFun{} to x86. The figure also includes the results of the
  7754. \code{explicate-control} and \code{select-instructions} passes.
  7755. \begin{figure}[htbp]
  7756. \begin{tabular}{ll}
  7757. \begin{minipage}{0.5\textwidth}
  7758. % s3_2.rkt
  7759. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7760. (define (add [x : Integer] [y : Integer])
  7761. : Integer
  7762. (+ x y))
  7763. (add 40 2)
  7764. \end{lstlisting}
  7765. $\Downarrow$
  7766. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7767. (define (add86 [x87 : Integer]
  7768. [y88 : Integer]) : Integer
  7769. add86start:
  7770. return (+ x87 y88);
  7771. )
  7772. (define (main) : Integer ()
  7773. mainstart:
  7774. tmp89 = (fun-ref add86);
  7775. (tail-call tmp89 40 2)
  7776. )
  7777. \end{lstlisting}
  7778. \end{minipage}
  7779. &
  7780. $\Rightarrow$
  7781. \begin{minipage}{0.5\textwidth}
  7782. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7783. (define (add86) : Integer
  7784. add86start:
  7785. movq %rdi, x87
  7786. movq %rsi, y88
  7787. movq x87, %rax
  7788. addq y88, %rax
  7789. jmp add11389conclusion
  7790. )
  7791. (define (main) : Integer
  7792. mainstart:
  7793. leaq (fun-ref add86), tmp89
  7794. movq $40, %rdi
  7795. movq $2, %rsi
  7796. tail-jmp tmp89
  7797. )
  7798. \end{lstlisting}
  7799. $\Downarrow$
  7800. \end{minipage}
  7801. \end{tabular}
  7802. \begin{tabular}{ll}
  7803. \begin{minipage}{0.3\textwidth}
  7804. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7805. .globl add86
  7806. .align 16
  7807. add86:
  7808. pushq %rbp
  7809. movq %rsp, %rbp
  7810. jmp add86start
  7811. add86start:
  7812. movq %rdi, %rax
  7813. addq %rsi, %rax
  7814. jmp add86conclusion
  7815. add86conclusion:
  7816. popq %rbp
  7817. retq
  7818. \end{lstlisting}
  7819. \end{minipage}
  7820. &
  7821. \begin{minipage}{0.5\textwidth}
  7822. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7823. .globl main
  7824. .align 16
  7825. main:
  7826. pushq %rbp
  7827. movq %rsp, %rbp
  7828. movq $16384, %rdi
  7829. movq $16384, %rsi
  7830. callq initialize
  7831. movq rootstack_begin(%rip), %r15
  7832. jmp mainstart
  7833. mainstart:
  7834. leaq add86(%rip), %rcx
  7835. movq $40, %rdi
  7836. movq $2, %rsi
  7837. movq %rcx, %rax
  7838. popq %rbp
  7839. jmp *%rax
  7840. mainconclusion:
  7841. popq %rbp
  7842. retq
  7843. \end{lstlisting}
  7844. \end{minipage}
  7845. \end{tabular}
  7846. \caption{Example compilation of a simple function to x86.}
  7847. \label{fig:add-fun}
  7848. \end{figure}
  7849. % Challenge idea: inlining! (simple version)
  7850. % Further Reading
  7851. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7852. \chapter{Lexically Scoped Functions}
  7853. \label{ch:Rlam}
  7854. \index{subject}{lambda}
  7855. \index{subject}{lexical scoping}
  7856. This chapter studies lexically scoped functions as they appear in
  7857. functional languages such as Racket. By lexical scoping we mean that a
  7858. function's body may refer to variables whose binding site is outside
  7859. of the function, in an enclosing scope.
  7860. %
  7861. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7862. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7863. \key{lambda} form. The body of the \key{lambda}, refers to three
  7864. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7865. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7866. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7867. parameter of function \code{f}. The \key{lambda} is returned from the
  7868. function \code{f}. The main expression of the program includes two
  7869. calls to \code{f} with different arguments for \code{x}, first
  7870. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7871. to variables \code{g} and \code{h}. Even though these two functions
  7872. were created by the same \code{lambda}, they are really different
  7873. functions because they use different values for \code{x}. Applying
  7874. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7875. \code{15} produces \code{22}. The result of this program is \code{42}.
  7876. \begin{figure}[btp]
  7877. % s4_6.rkt
  7878. \begin{lstlisting}
  7879. (define (f [x : Integer]) : (Integer -> Integer)
  7880. (let ([y 4])
  7881. (lambda: ([z : Integer]) : Integer
  7882. (+ x (+ y z)))))
  7883. (let ([g (f 5)])
  7884. (let ([h (f 3)])
  7885. (+ (g 11) (h 15))))
  7886. \end{lstlisting}
  7887. \caption{Example of a lexically scoped function.}
  7888. \label{fig:lexical-scoping}
  7889. \end{figure}
  7890. The approach that we take for implementing lexically scoped
  7891. functions is to compile them into top-level function definitions,
  7892. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7893. provide special treatment for variable occurrences such as \code{x}
  7894. and \code{y} in the body of the \code{lambda} of
  7895. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7896. refer to variables defined outside of it. To identify such variable
  7897. occurrences, we review the standard notion of free variable.
  7898. \begin{definition}
  7899. A variable is \emph{free in expression} $e$ if the variable occurs
  7900. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  7901. variable}
  7902. \end{definition}
  7903. For example, in the expression \code{(+ x (+ y z))} the variables
  7904. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7905. only \code{x} and \code{y} are free in the following expression
  7906. because \code{z} is bound by the \code{lambda}.
  7907. \begin{lstlisting}
  7908. (lambda: ([z : Integer]) : Integer
  7909. (+ x (+ y z)))
  7910. \end{lstlisting}
  7911. So the free variables of a \code{lambda} are the ones that will need
  7912. special treatment. We need to arrange for some way to transport, at
  7913. runtime, the values of those variables from the point where the
  7914. \code{lambda} was created to the point where the \code{lambda} is
  7915. applied. An efficient solution to the problem, due to
  7916. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7917. free variables together with the function pointer for the lambda's
  7918. code, an arrangement called a \emph{flat closure} (which we shorten to
  7919. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  7920. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7921. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7922. pointers. The function pointer resides at index $0$ and the
  7923. values for the free variables will fill in the rest of the vector.
  7924. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7925. how closures work. It's a three-step dance. The program first calls
  7926. function \code{f}, which creates a closure for the \code{lambda}. The
  7927. closure is a vector whose first element is a pointer to the top-level
  7928. function that we will generate for the \code{lambda}, the second
  7929. element is the value of \code{x}, which is \code{5}, and the third
  7930. element is \code{4}, the value of \code{y}. The closure does not
  7931. contain an element for \code{z} because \code{z} is not a free
  7932. variable of the \code{lambda}. Creating the closure is step 1 of the
  7933. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7934. shown in Figure~\ref{fig:closures}.
  7935. %
  7936. The second call to \code{f} creates another closure, this time with
  7937. \code{3} in the second slot (for \code{x}). This closure is also
  7938. returned from \code{f} but bound to \code{h}, which is also shown in
  7939. Figure~\ref{fig:closures}.
  7940. \begin{figure}[tbp]
  7941. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7942. \caption{Example closure representation for the \key{lambda}'s
  7943. in Figure~\ref{fig:lexical-scoping}.}
  7944. \label{fig:closures}
  7945. \end{figure}
  7946. Continuing with the example, consider the application of \code{g} to
  7947. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7948. obtain the function pointer in the first element of the closure and
  7949. call it, passing in the closure itself and then the regular arguments,
  7950. in this case \code{11}. This technique for applying a closure is step
  7951. 2 of the dance.
  7952. %
  7953. But doesn't this \code{lambda} only take 1 argument, for parameter
  7954. \code{z}? The third and final step of the dance is generating a
  7955. top-level function for a \code{lambda}. We add an additional
  7956. parameter for the closure and we insert a \code{let} at the beginning
  7957. of the function for each free variable, to bind those variables to the
  7958. appropriate elements from the closure parameter.
  7959. %
  7960. This three-step dance is known as \emph{closure conversion}. We
  7961. discuss the details of closure conversion in
  7962. Section~\ref{sec:closure-conversion} and the code generated from the
  7963. example in Section~\ref{sec:example-lambda}. But first we define the
  7964. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7965. \section{The \LangLam{} Language}
  7966. \label{sec:r5}
  7967. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7968. functions and lexical scoping, is defined in
  7969. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7970. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7971. syntax for function application.
  7972. \begin{figure}[tp]
  7973. \centering
  7974. \fbox{
  7975. \begin{minipage}{0.96\textwidth}
  7976. \small
  7977. \[
  7978. \begin{array}{lcl}
  7979. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7980. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7981. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7982. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7983. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7984. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7985. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7986. \mid (\key{and}\;\Exp\;\Exp)
  7987. \mid (\key{or}\;\Exp\;\Exp)
  7988. \mid (\key{not}\;\Exp) } \\
  7989. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7990. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7991. (\key{vector-ref}\;\Exp\;\Int)} \\
  7992. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7993. \mid (\Exp \; \Exp\ldots) } \\
  7994. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7995. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7996. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7997. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  7998. \end{array}
  7999. \]
  8000. \end{minipage}
  8001. }
  8002. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8003. with \key{lambda}.}
  8004. \label{fig:Rlam-concrete-syntax}
  8005. \end{figure}
  8006. \begin{figure}[tp]
  8007. \centering
  8008. \fbox{
  8009. \begin{minipage}{0.96\textwidth}
  8010. \small
  8011. \[
  8012. \begin{array}{lcl}
  8013. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8014. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8015. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8016. &\mid& \gray{ \BOOL{\itm{bool}}
  8017. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8018. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8019. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8020. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8021. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8022. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8023. \end{array}
  8024. \]
  8025. \end{minipage}
  8026. }
  8027. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8028. \label{fig:Rlam-syntax}
  8029. \end{figure}
  8030. \index{subject}{interpreter}
  8031. \label{sec:interp-Rlambda}
  8032. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8033. \LangLam{}. The case for \key{lambda} saves the current environment
  8034. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8035. the environment from the \key{lambda}, the \code{lam-env}, when
  8036. interpreting the body of the \key{lambda}. The \code{lam-env}
  8037. environment is extended with the mapping of parameters to argument
  8038. values.
  8039. \begin{figure}[tbp]
  8040. \begin{lstlisting}
  8041. (define interp-Rlambda-class
  8042. (class interp-Rfun-class
  8043. (super-new)
  8044. (define/override (interp-op op)
  8045. (match op
  8046. ['procedure-arity
  8047. (lambda (v)
  8048. (match v
  8049. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8050. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8051. [else (super interp-op op)]))
  8052. (define/override ((interp-exp env) e)
  8053. (define recur (interp-exp env))
  8054. (match e
  8055. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8056. `(function ,xs ,body ,env)]
  8057. [else ((super interp-exp env) e)]))
  8058. ))
  8059. (define (interp-Rlambda p)
  8060. (send (new interp-Rlambda-class) interp-program p))
  8061. \end{lstlisting}
  8062. \caption{Interpreter for \LangLam{}.}
  8063. \label{fig:interp-Rlambda}
  8064. \end{figure}
  8065. \label{sec:type-check-r5}
  8066. \index{subject}{type checking}
  8067. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8068. \key{lambda} form. The body of the \key{lambda} is checked in an
  8069. environment that includes the current environment (because it is
  8070. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8071. require the body's type to match the declared return type.
  8072. \begin{figure}[tbp]
  8073. \begin{lstlisting}
  8074. (define (type-check-Rlambda env)
  8075. (lambda (e)
  8076. (match e
  8077. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8078. (define-values (new-body bodyT)
  8079. ((type-check-exp (append (map cons xs Ts) env)) body))
  8080. (define ty `(,@Ts -> ,rT))
  8081. (cond
  8082. [(equal? rT bodyT)
  8083. (values (HasType (Lambda params rT new-body) ty) ty)]
  8084. [else
  8085. (error "mismatch in return type" bodyT rT)])]
  8086. ...
  8087. )))
  8088. \end{lstlisting}
  8089. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8090. \label{fig:type-check-Rlambda}
  8091. \end{figure}
  8092. \section{Reveal Functions and the $F_2$ language}
  8093. \label{sec:reveal-functions-r5}
  8094. To support the \code{procedure-arity} operator we need to communicate
  8095. the arity of a function to the point of closure creation. We can
  8096. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8097. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8098. output of this pass is the language $F_2$, whose syntax is defined in
  8099. Figure~\ref{fig:f2-syntax}.
  8100. \begin{figure}[tp]
  8101. \centering
  8102. \fbox{
  8103. \begin{minipage}{0.96\textwidth}
  8104. \[
  8105. \begin{array}{lcl}
  8106. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8107. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8108. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8109. \end{array}
  8110. \]
  8111. \end{minipage}
  8112. }
  8113. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8114. (Figure~\ref{fig:Rlam-syntax}).}
  8115. \label{fig:f2-syntax}
  8116. \end{figure}
  8117. \section{Closure Conversion}
  8118. \label{sec:closure-conversion}
  8119. \index{subject}{closure conversion}
  8120. The compiling of lexically-scoped functions into top-level function
  8121. definitions is accomplished in the pass \code{convert-to-closures}
  8122. that comes after \code{reveal-functions} and before
  8123. \code{limit-functions}.
  8124. As usual, we implement the pass as a recursive function over the
  8125. AST. All of the action is in the cases for \key{Lambda} and
  8126. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8127. that creates a closure, that is, a vector whose first element is a
  8128. function pointer and the rest of the elements are the free variables
  8129. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8130. using \code{vector} so that we can distinguish closures from vectors
  8131. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8132. the generated code below, the \itm{name} is a unique symbol generated
  8133. to identify the function and the \itm{arity} is the number of
  8134. parameters (the length of \itm{ps}).
  8135. \begin{lstlisting}
  8136. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8137. |$\Rightarrow$|
  8138. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8139. \end{lstlisting}
  8140. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8141. create a top-level function definition for each \key{Lambda}, as
  8142. shown below.\\
  8143. \begin{minipage}{0.8\textwidth}
  8144. \begin{lstlisting}
  8145. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8146. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8147. ...
  8148. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8149. |\itm{body'}|)...))
  8150. \end{lstlisting}
  8151. \end{minipage}\\
  8152. The \code{clos} parameter refers to the closure. Translate the type
  8153. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8154. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8155. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8156. underscore \code{\_} is a dummy type that we use because it is rather
  8157. difficult to give a type to the function in the closure's
  8158. type.\footnote{To give an accurate type to a closure, we would need to
  8159. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8160. The dummy type is considered to be equal to any other type during type
  8161. checking. The sequence of \key{Let} forms bind the free variables to
  8162. their values obtained from the closure.
  8163. Closure conversion turns functions into vectors, so the type
  8164. annotations in the program must also be translated. We recommend
  8165. defining a auxiliary recursive function for this purpose. Function
  8166. types should be translated as follows.
  8167. \begin{lstlisting}
  8168. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8169. |$\Rightarrow$|
  8170. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8171. \end{lstlisting}
  8172. The above type says that the first thing in the vector is a function
  8173. pointer. The first parameter of the function pointer is a vector (a
  8174. closure) and the rest of the parameters are the ones from the original
  8175. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8176. the closure omits the types of the free variables because 1) those
  8177. types are not available in this context and 2) we do not need them in
  8178. the code that is generated for function application.
  8179. We transform function application into code that retrieves the
  8180. function pointer from the closure and then calls the function, passing
  8181. in the closure as the first argument. We bind $e'$ to a temporary
  8182. variable to avoid code duplication.
  8183. \begin{lstlisting}
  8184. (Apply |$e$| |\itm{es}|)
  8185. |$\Rightarrow$|
  8186. (Let |\itm{tmp}| |$e'$|
  8187. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8188. \end{lstlisting}
  8189. There is also the question of what to do with references top-level
  8190. function definitions. To maintain a uniform translation of function
  8191. application, we turn function references into closures.
  8192. \begin{tabular}{lll}
  8193. \begin{minipage}{0.3\textwidth}
  8194. \begin{lstlisting}
  8195. (FunRefArity |$f$| |$n$|)
  8196. \end{lstlisting}
  8197. \end{minipage}
  8198. &
  8199. $\Rightarrow$
  8200. &
  8201. \begin{minipage}{0.5\textwidth}
  8202. \begin{lstlisting}
  8203. (Closure |$n$| (FunRef |$f$|) '())
  8204. \end{lstlisting}
  8205. \end{minipage}
  8206. \end{tabular} \\
  8207. %
  8208. The top-level function definitions need to be updated as well to take
  8209. an extra closure parameter.
  8210. \section{An Example Translation}
  8211. \label{sec:example-lambda}
  8212. Figure~\ref{fig:lexical-functions-example} shows the result of
  8213. \code{reveal-functions} and \code{convert-to-closures} for the example
  8214. program demonstrating lexical scoping that we discussed at the
  8215. beginning of this chapter.
  8216. \begin{figure}[tbp]
  8217. \begin{minipage}{0.8\textwidth}
  8218. % tests/lambda_test_6.rkt
  8219. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8220. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8221. (let ([y8 4])
  8222. (lambda: ([z9 : Integer]) : Integer
  8223. (+ x7 (+ y8 z9)))))
  8224. (define (main) : Integer
  8225. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8226. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8227. (+ (g0 11) (h1 15)))))
  8228. \end{lstlisting}
  8229. $\Rightarrow$
  8230. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8231. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8232. (let ([y8 4])
  8233. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8234. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8235. (let ([x7 (vector-ref fvs3 1)])
  8236. (let ([y8 (vector-ref fvs3 2)])
  8237. (+ x7 (+ y8 z9)))))
  8238. (define (main) : Integer
  8239. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8240. ((vector-ref clos5 0) clos5 5))])
  8241. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8242. ((vector-ref clos6 0) clos6 3))])
  8243. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8244. \end{lstlisting}
  8245. \end{minipage}
  8246. \caption{Example of closure conversion.}
  8247. \label{fig:lexical-functions-example}
  8248. \end{figure}
  8249. \begin{exercise}\normalfont
  8250. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8251. Create 5 new programs that use \key{lambda} functions and make use of
  8252. lexical scoping. Test your compiler on these new programs and all of
  8253. your previously created test programs.
  8254. \end{exercise}
  8255. \section{Expose Allocation}
  8256. \label{sec:expose-allocation-r5}
  8257. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8258. that allocates and initializes a vector, similar to the translation of
  8259. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8260. The only difference is replacing the use of
  8261. \ALLOC{\itm{len}}{\itm{type}} with
  8262. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8263. \section{Explicate Control and \LangCLam{}}
  8264. \label{sec:explicate-r5}
  8265. The output language of \code{explicate-control} is \LangCLam{} whose
  8266. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8267. difference with respect to \LangCFun{} is the addition of the
  8268. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8269. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8270. similar to the handling of other expressions such as primitive
  8271. operators.
  8272. \begin{figure}[tp]
  8273. \fbox{
  8274. \begin{minipage}{0.96\textwidth}
  8275. \small
  8276. \[
  8277. \begin{array}{lcl}
  8278. \Exp &::= & \ldots
  8279. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8280. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8281. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8282. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8283. \mid \GOTO{\itm{label}} } \\
  8284. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8285. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8286. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8287. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8288. \end{array}
  8289. \]
  8290. \end{minipage}
  8291. }
  8292. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8293. \label{fig:c4-syntax}
  8294. \end{figure}
  8295. \section{Select Instructions}
  8296. \label{sec:select-instructions-Rlambda}
  8297. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8298. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8299. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8300. that you should place the \itm{arity} in the tag that is stored at
  8301. position $0$ of the vector. Recall that in
  8302. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8303. was not used. We store the arity in the $5$ bits starting at position
  8304. $58$.
  8305. Compile the \code{procedure-arity} operator into a sequence of
  8306. instructions that access the tag from position $0$ of the vector and
  8307. extract the $5$-bits starting at position $58$ from the tag.
  8308. \begin{figure}[p]
  8309. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8310. \node (Rfun) at (0,2) {\large \LangFun{}};
  8311. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8312. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8313. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8314. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8315. \node (F1-3) at (6,0) {\large $F_1$};
  8316. \node (F1-4) at (3,0) {\large $F_1$};
  8317. \node (F1-5) at (0,0) {\large $F_1$};
  8318. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8319. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8320. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8321. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8322. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8323. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8324. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8325. \path[->,bend left=15] (Rfun) edge [above] node
  8326. {\ttfamily\footnotesize shrink} (Rfun-2);
  8327. \path[->,bend left=15] (Rfun-2) edge [above] node
  8328. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8329. \path[->,bend left=15] (Rfun-3) edge [right] node
  8330. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8331. \path[->,bend left=15] (F1-1) edge [below] node
  8332. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8333. \path[->,bend right=15] (F1-2) edge [above] node
  8334. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8335. \path[->,bend right=15] (F1-3) edge [above] node
  8336. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8337. \path[->,bend right=15] (F1-4) edge [above] node
  8338. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8339. \path[->,bend right=15] (F1-5) edge [right] node
  8340. {\ttfamily\footnotesize explicate-control} (C3-2);
  8341. \path[->,bend left=15] (C3-2) edge [left] node
  8342. {\ttfamily\footnotesize select-instr.} (x86-2);
  8343. \path[->,bend right=15] (x86-2) edge [left] node
  8344. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8345. \path[->,bend right=15] (x86-2-1) edge [below] node
  8346. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8347. \path[->,bend right=15] (x86-2-2) edge [left] node
  8348. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8349. \path[->,bend left=15] (x86-3) edge [above] node
  8350. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8351. \path[->,bend left=15] (x86-4) edge [right] node
  8352. {\ttfamily\footnotesize print-x86} (x86-5);
  8353. \end{tikzpicture}
  8354. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8355. functions.}
  8356. \label{fig:Rlambda-passes}
  8357. \end{figure}
  8358. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8359. for the compilation of \LangLam{}.
  8360. \clearpage
  8361. \section{Challenge: Optimize Closures}
  8362. \label{sec:optimize-closures}
  8363. In this chapter we compiled lexically-scoped functions into a
  8364. relatively efficient representation: flat closures. However, even this
  8365. representation comes with some overhead. For example, consider the
  8366. following program with a function \code{tail-sum} that does not have
  8367. any free variables and where all the uses of \code{tail-sum} are in
  8368. applications where we know that only \code{tail-sum} is being applied
  8369. (and not any other functions).
  8370. \begin{center}
  8371. \begin{minipage}{0.95\textwidth}
  8372. \begin{lstlisting}
  8373. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8374. (if (eq? n 0)
  8375. r
  8376. (tail-sum (- n 1) (+ n r))))
  8377. (+ (tail-sum 5 0) 27)
  8378. \end{lstlisting}
  8379. \end{minipage}
  8380. \end{center}
  8381. As described in this chapter, we uniformly apply closure conversion to
  8382. all functions, obtaining the following output for this program.
  8383. \begin{center}
  8384. \begin{minipage}{0.95\textwidth}
  8385. \begin{lstlisting}
  8386. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8387. (if (eq? n2 0)
  8388. r3
  8389. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8390. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8391. (define (main) : Integer
  8392. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8393. ((vector-ref clos6 0) clos6 5 0)) 27))
  8394. \end{lstlisting}
  8395. \end{minipage}
  8396. \end{center}
  8397. In the previous Chapter, there would be no allocation in the program
  8398. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8399. the above program allocates memory for each \code{closure} and the
  8400. calls to \code{tail-sum} are indirect. These two differences incur
  8401. considerable overhead in a program such as this one, where the
  8402. allocations and indirect calls occur inside a tight loop.
  8403. One might think that this problem is trivial to solve: can't we just
  8404. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8405. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8406. e'_n$)} instead of treating it like a call to a closure? We would
  8407. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8408. %
  8409. However, this problem is not so trivial because a global function may
  8410. ``escape'' and become involved in applications that also involve
  8411. closures. Consider the following example in which the application
  8412. \code{(f 41)} needs to be compiled into a closure application, because
  8413. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8414. function might also get bound to \code{f}.
  8415. \begin{lstlisting}
  8416. (define (add1 [x : Integer]) : Integer
  8417. (+ x 1))
  8418. (let ([y (read)])
  8419. (let ([f (if (eq? (read) 0)
  8420. add1
  8421. (lambda: ([x : Integer]) : Integer (- x y)))])
  8422. (f 41)))
  8423. \end{lstlisting}
  8424. If a global function name is used in any way other than as the
  8425. operator in a direct call, then we say that the function
  8426. \emph{escapes}. If a global function does not escape, then we do not
  8427. need to perform closure conversion on the function.
  8428. \begin{exercise}\normalfont
  8429. Implement an auxiliary function for detecting which global
  8430. functions escape. Using that function, implement an improved version
  8431. of closure conversion that does not apply closure conversion to
  8432. global functions that do not escape but instead compiles them as
  8433. regular functions. Create several new test cases that check whether
  8434. you properly detect whether global functions escape or not.
  8435. \end{exercise}
  8436. So far we have reduced the overhead of calling global functions, but
  8437. it would also be nice to reduce the overhead of calling a
  8438. \code{lambda} when we can determine at compile time which
  8439. \code{lambda} will be called. We refer to such calls as \emph{known
  8440. calls}. Consider the following example in which a \code{lambda} is
  8441. bound to \code{f} and then applied.
  8442. \begin{lstlisting}
  8443. (let ([y (read)])
  8444. (let ([f (lambda: ([x : Integer]) : Integer
  8445. (+ x y))])
  8446. (f 21)))
  8447. \end{lstlisting}
  8448. Closure conversion compiles \code{(f 21)} into an indirect call:
  8449. \begin{lstlisting}
  8450. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8451. (let ([y2 (vector-ref fvs6 1)])
  8452. (+ x3 y2)))
  8453. (define (main) : Integer
  8454. (let ([y2 (read)])
  8455. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8456. ((vector-ref f4 0) f4 21))))
  8457. \end{lstlisting}
  8458. but we can instead compile the application \code{(f 21)} into a direct call
  8459. to \code{lambda5}:
  8460. \begin{lstlisting}
  8461. (define (main) : Integer
  8462. (let ([y2 (read)])
  8463. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8464. ((fun-ref lambda5) f4 21))))
  8465. \end{lstlisting}
  8466. The problem of determining which lambda will be called from a
  8467. particular application is quite challenging in general and the topic
  8468. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8469. following exercise we recommend that you compile an application to a
  8470. direct call when the operator is a variable and the variable is
  8471. \code{let}-bound to a closure. This can be accomplished by maintaining
  8472. an environment mapping \code{let}-bound variables to function names.
  8473. Extend the environment whenever you encounter a closure on the
  8474. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8475. to the name of the global function for the closure. This pass should
  8476. come after closure conversion.
  8477. \begin{exercise}\normalfont
  8478. Implement a compiler pass, named \code{optimize-known-calls}, that
  8479. compiles known calls into direct calls. Verify that your compiler is
  8480. successful in this regard on several example programs.
  8481. \end{exercise}
  8482. These exercises only scratches the surface of optimizing of
  8483. closures. A good next step for the interested reader is to look at the
  8484. work of \citet{Keep:2012ab}.
  8485. \section{Further Reading}
  8486. The notion of lexically scoped anonymous functions predates modern
  8487. computers by about a decade. They were invented by
  8488. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8489. foundation for logic. Anonymous functions were included in the
  8490. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8491. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8492. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8493. compile Scheme programs. However, environments were represented as
  8494. linked lists, so variable lookup was linear in the size of the
  8495. environment. In this chapter we represent environments using flat
  8496. closures, which were invented by
  8497. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8498. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8499. closures, variable lookup is constant time but the time to create a
  8500. closure is proportional to the number of its free variables. Flat
  8501. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8502. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8503. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8504. \chapter{Dynamic Typing}
  8505. \label{ch:Rdyn}
  8506. \index{subject}{dynamic typing}
  8507. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8508. typed language that is a subset of Racket. This is in contrast to the
  8509. previous chapters, which have studied the compilation of Typed
  8510. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8511. expression may produce a value of a different type each time it is
  8512. executed. Consider the following example with a conditional \code{if}
  8513. expression that may return a Boolean or an integer depending on the
  8514. input to the program.
  8515. % part of dynamic_test_25.rkt
  8516. \begin{lstlisting}
  8517. (not (if (eq? (read) 1) #f 0))
  8518. \end{lstlisting}
  8519. Languages that allow expressions to produce different kinds of values
  8520. are called \emph{polymorphic}, a word composed of the Greek roots
  8521. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8522. are several kinds of polymorphism in programming languages, such as
  8523. subtype polymorphism and parametric
  8524. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8525. study in this chapter does not have a special name but it is the kind
  8526. that arises in dynamically typed languages.
  8527. Another characteristic of dynamically typed languages is that
  8528. primitive operations, such as \code{not}, are often defined to operate
  8529. on many different types of values. In fact, in Racket, the \code{not}
  8530. operator produces a result for any kind of value: given \code{\#f} it
  8531. returns \code{\#t} and given anything else it returns \code{\#f}.
  8532. Furthermore, even when primitive operations restrict their inputs to
  8533. values of a certain type, this restriction is enforced at runtime
  8534. instead of during compilation. For example, the following vector
  8535. reference results in a run-time contract violation because the index
  8536. must be in integer, not a Boolean such as \code{\#t}.
  8537. \begin{lstlisting}
  8538. (vector-ref (vector 42) #t)
  8539. \end{lstlisting}
  8540. \begin{figure}[tp]
  8541. \centering
  8542. \fbox{
  8543. \begin{minipage}{0.97\textwidth}
  8544. \[
  8545. \begin{array}{rcl}
  8546. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8547. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8548. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8549. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8550. &\mid& \key{\#t} \mid \key{\#f}
  8551. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8552. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8553. \mid \CUNIOP{\key{not}}{\Exp} \\
  8554. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8555. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8556. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8557. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8558. &\mid& \LP\Exp \; \Exp\ldots\RP
  8559. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8560. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8561. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8562. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8563. \LangDynM{} &::=& \Def\ldots\; \Exp
  8564. \end{array}
  8565. \]
  8566. \end{minipage}
  8567. }
  8568. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8569. \label{fig:r7-concrete-syntax}
  8570. \end{figure}
  8571. \begin{figure}[tp]
  8572. \centering
  8573. \fbox{
  8574. \begin{minipage}{0.96\textwidth}
  8575. \small
  8576. \[
  8577. \begin{array}{lcl}
  8578. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8579. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8580. &\mid& \BOOL{\itm{bool}}
  8581. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8582. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8583. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8584. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8585. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8586. \end{array}
  8587. \]
  8588. \end{minipage}
  8589. }
  8590. \caption{The abstract syntax of \LangDyn{}.}
  8591. \label{fig:r7-syntax}
  8592. \end{figure}
  8593. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8594. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8595. \ref{fig:r7-syntax}.
  8596. %
  8597. There is no type checker for \LangDyn{} because it is not a statically
  8598. typed language (it's dynamically typed!).
  8599. The definitional interpreter for \LangDyn{} is presented in
  8600. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8601. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8602. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8603. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8604. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  8605. value} that combines an underlying value with a tag that identifies
  8606. what kind of value it is. We define the following struct
  8607. to represented tagged values.
  8608. \begin{lstlisting}
  8609. (struct Tagged (value tag) #:transparent)
  8610. \end{lstlisting}
  8611. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8612. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8613. but don't always capture all the information that a type does. For
  8614. example, a vector of type \code{(Vector Any Any)} is tagged with
  8615. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8616. is tagged with \code{Procedure}.
  8617. Next consider the match case for \code{vector-ref}. The
  8618. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8619. is used to ensure that the first argument is a vector and the second
  8620. is an integer. If they are not, a \code{trapped-error} is raised.
  8621. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8622. interpreter raises a \code{trapped-error} error, the compiled code
  8623. must also signal an error by exiting with return code \code{255}. A
  8624. \code{trapped-error} is also raised if the index is not less than
  8625. length of the vector.
  8626. \begin{figure}[tbp]
  8627. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8628. (define ((interp-Rdyn-exp env) ast)
  8629. (define recur (interp-Rdyn-exp env))
  8630. (match ast
  8631. [(Var x) (lookup x env)]
  8632. [(Int n) (Tagged n 'Integer)]
  8633. [(Bool b) (Tagged b 'Boolean)]
  8634. [(Lambda xs rt body)
  8635. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8636. [(Prim 'vector es)
  8637. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8638. [(Prim 'vector-ref (list e1 e2))
  8639. (define vec (recur e1)) (define i (recur e2))
  8640. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8641. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8642. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8643. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8644. [(Prim 'vector-set! (list e1 e2 e3))
  8645. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8646. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8647. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8648. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8649. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8650. (Tagged (void) 'Void)]
  8651. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8652. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8653. [(Prim 'or (list e1 e2))
  8654. (define v1 (recur e1))
  8655. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8656. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8657. [(Prim op (list e1))
  8658. #:when (set-member? type-predicates op)
  8659. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8660. [(Prim op es)
  8661. (define args (map recur es))
  8662. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8663. (unless (for/or ([expected-tags (op-tags op)])
  8664. (equal? expected-tags tags))
  8665. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8666. (tag-value
  8667. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8668. [(If q t f)
  8669. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8670. [(Apply f es)
  8671. (define new-f (recur f)) (define args (map recur es))
  8672. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8673. (match f-val
  8674. [`(function ,xs ,body ,lam-env)
  8675. (unless (eq? (length xs) (length args))
  8676. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8677. (define new-env (append (map cons xs args) lam-env))
  8678. ((interp-Rdyn-exp new-env) body)]
  8679. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8680. \end{lstlisting}
  8681. \caption{Interpreter for the \LangDyn{} language.}
  8682. \label{fig:interp-Rdyn}
  8683. \end{figure}
  8684. \begin{figure}[tbp]
  8685. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8686. (define (interp-op op)
  8687. (match op
  8688. ['+ fx+]
  8689. ['- fx-]
  8690. ['read read-fixnum]
  8691. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8692. ['< (lambda (v1 v2)
  8693. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8694. ['<= (lambda (v1 v2)
  8695. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8696. ['> (lambda (v1 v2)
  8697. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8698. ['>= (lambda (v1 v2)
  8699. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8700. ['boolean? boolean?]
  8701. ['integer? fixnum?]
  8702. ['void? void?]
  8703. ['vector? vector?]
  8704. ['vector-length vector-length]
  8705. ['procedure? (match-lambda
  8706. [`(functions ,xs ,body ,env) #t] [else #f])]
  8707. [else (error 'interp-op "unknown operator" op)]))
  8708. (define (op-tags op)
  8709. (match op
  8710. ['+ '((Integer Integer))]
  8711. ['- '((Integer Integer) (Integer))]
  8712. ['read '(())]
  8713. ['not '((Boolean))]
  8714. ['< '((Integer Integer))]
  8715. ['<= '((Integer Integer))]
  8716. ['> '((Integer Integer))]
  8717. ['>= '((Integer Integer))]
  8718. ['vector-length '((Vector))]))
  8719. (define type-predicates
  8720. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8721. (define (tag-value v)
  8722. (cond [(boolean? v) (Tagged v 'Boolean)]
  8723. [(fixnum? v) (Tagged v 'Integer)]
  8724. [(procedure? v) (Tagged v 'Procedure)]
  8725. [(vector? v) (Tagged v 'Vector)]
  8726. [(void? v) (Tagged v 'Void)]
  8727. [else (error 'tag-value "unidentified value ~a" v)]))
  8728. (define (check-tag val expected ast)
  8729. (define tag (Tagged-tag val))
  8730. (unless (eq? tag expected)
  8731. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8732. \end{lstlisting}
  8733. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8734. \label{fig:interp-Rdyn-aux}
  8735. \end{figure}
  8736. \clearpage
  8737. \section{Representation of Tagged Values}
  8738. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8739. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8740. values at the bit level. Because almost every operation in \LangDyn{}
  8741. involves manipulating tagged values, the representation must be
  8742. efficient. Recall that all of our values are 64 bits. We shall steal
  8743. the 3 right-most bits to encode the tag. We use $001$ to identify
  8744. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8745. and $101$ for the void value. We define the following auxiliary
  8746. function for mapping types to tag codes.
  8747. \begin{align*}
  8748. \itm{tagof}(\key{Integer}) &= 001 \\
  8749. \itm{tagof}(\key{Boolean}) &= 100 \\
  8750. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8751. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8752. \itm{tagof}(\key{Void}) &= 101
  8753. \end{align*}
  8754. This stealing of 3 bits comes at some price: our integers are reduced
  8755. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8756. affect vectors and procedures because those values are addresses, and
  8757. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8758. they are always $000$. Thus, we do not lose information by overwriting
  8759. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8760. to recover the original address.
  8761. To make tagged values into first-class entities, we can give them a
  8762. type, called \code{Any}, and define operations such as \code{Inject}
  8763. and \code{Project} for creating and using them, yielding the \LangAny{}
  8764. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8765. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8766. in greater detail.
  8767. \section{The \LangAny{} Language}
  8768. \label{sec:Rany-lang}
  8769. \begin{figure}[tp]
  8770. \centering
  8771. \fbox{
  8772. \begin{minipage}{0.96\textwidth}
  8773. \small
  8774. \[
  8775. \begin{array}{lcl}
  8776. \Type &::= & \ldots \mid \key{Any} \\
  8777. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8778. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8779. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8780. \mid \code{procedure?} \mid \code{void?} \\
  8781. \Exp &::=& \ldots
  8782. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8783. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8784. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8785. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8786. \end{array}
  8787. \]
  8788. \end{minipage}
  8789. }
  8790. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8791. \label{fig:Rany-syntax}
  8792. \end{figure}
  8793. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8794. (The concrete syntax of \LangAny{} is in the Appendix,
  8795. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8796. converts the value produced by expression $e$ of type $T$ into a
  8797. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8798. produced by expression $e$ into a value of type $T$ or else halts the
  8799. program if the type tag is not equivalent to $T$.
  8800. %
  8801. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8802. restricted to a flat type $\FType$, which simplifies the
  8803. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8804. The \code{any-vector} operators adapt the vector operations so that
  8805. they can be applied to a value of type \code{Any}. They also
  8806. generalize the vector operations in that the index is not restricted
  8807. to be a literal integer in the grammar but is allowed to be any
  8808. expression.
  8809. The type predicates such as \key{boolean?} expect their argument to
  8810. produce a tagged value; they return \key{\#t} if the tag corresponds
  8811. to the predicate and they return \key{\#f} otherwise.
  8812. The type checker for \LangAny{} is shown in
  8813. Figures~\ref{fig:type-check-Rany-part-1} and
  8814. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8815. Figure~\ref{fig:type-check-Rany-aux}.
  8816. %
  8817. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8818. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8819. in Figure~\ref{fig:apply-project}.
  8820. \begin{figure}[btp]
  8821. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8822. (define type-check-Rany-class
  8823. (class type-check-Rlambda-class
  8824. (super-new)
  8825. (inherit check-type-equal?)
  8826. (define/override (type-check-exp env)
  8827. (lambda (e)
  8828. (define recur (type-check-exp env))
  8829. (match e
  8830. [(Inject e1 ty)
  8831. (unless (flat-ty? ty)
  8832. (error 'type-check "may only inject from flat type, not ~a" ty))
  8833. (define-values (new-e1 e-ty) (recur e1))
  8834. (check-type-equal? e-ty ty e)
  8835. (values (Inject new-e1 ty) 'Any)]
  8836. [(Project e1 ty)
  8837. (unless (flat-ty? ty)
  8838. (error 'type-check "may only project to flat type, not ~a" ty))
  8839. (define-values (new-e1 e-ty) (recur e1))
  8840. (check-type-equal? e-ty 'Any e)
  8841. (values (Project new-e1 ty) ty)]
  8842. [(Prim 'any-vector-length (list e1))
  8843. (define-values (e1^ t1) (recur e1))
  8844. (check-type-equal? t1 'Any e)
  8845. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8846. [(Prim 'any-vector-ref (list e1 e2))
  8847. (define-values (e1^ t1) (recur e1))
  8848. (define-values (e2^ t2) (recur e2))
  8849. (check-type-equal? t1 'Any e)
  8850. (check-type-equal? t2 'Integer e)
  8851. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8852. [(Prim 'any-vector-set! (list e1 e2 e3))
  8853. (define-values (e1^ t1) (recur e1))
  8854. (define-values (e2^ t2) (recur e2))
  8855. (define-values (e3^ t3) (recur e3))
  8856. (check-type-equal? t1 'Any e)
  8857. (check-type-equal? t2 'Integer e)
  8858. (check-type-equal? t3 'Any e)
  8859. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8860. \end{lstlisting}
  8861. \caption{Type checker for the \LangAny{} language, part 1.}
  8862. \label{fig:type-check-Rany-part-1}
  8863. \end{figure}
  8864. \begin{figure}[btp]
  8865. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8866. [(ValueOf e ty)
  8867. (define-values (new-e e-ty) (recur e))
  8868. (values (ValueOf new-e ty) ty)]
  8869. [(Prim pred (list e1))
  8870. #:when (set-member? (type-predicates) pred)
  8871. (define-values (new-e1 e-ty) (recur e1))
  8872. (check-type-equal? e-ty 'Any e)
  8873. (values (Prim pred (list new-e1)) 'Boolean)]
  8874. [(If cnd thn els)
  8875. (define-values (cnd^ Tc) (recur cnd))
  8876. (define-values (thn^ Tt) (recur thn))
  8877. (define-values (els^ Te) (recur els))
  8878. (check-type-equal? Tc 'Boolean cnd)
  8879. (check-type-equal? Tt Te e)
  8880. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8881. [(Exit) (values (Exit) '_)]
  8882. [(Prim 'eq? (list arg1 arg2))
  8883. (define-values (e1 t1) (recur arg1))
  8884. (define-values (e2 t2) (recur arg2))
  8885. (match* (t1 t2)
  8886. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8887. [(other wise) (check-type-equal? t1 t2 e)])
  8888. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8889. [else ((super type-check-exp env) e)])))
  8890. ))
  8891. \end{lstlisting}
  8892. \caption{Type checker for the \LangAny{} language, part 2.}
  8893. \label{fig:type-check-Rany-part-2}
  8894. \end{figure}
  8895. \begin{figure}[tbp]
  8896. \begin{lstlisting}
  8897. (define/override (operator-types)
  8898. (append
  8899. '((integer? . ((Any) . Boolean))
  8900. (vector? . ((Any) . Boolean))
  8901. (procedure? . ((Any) . Boolean))
  8902. (void? . ((Any) . Boolean))
  8903. (tag-of-any . ((Any) . Integer))
  8904. (make-any . ((_ Integer) . Any))
  8905. )
  8906. (super operator-types)))
  8907. (define/public (type-predicates)
  8908. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8909. (define/public (combine-types t1 t2)
  8910. (match (list t1 t2)
  8911. [(list '_ t2) t2]
  8912. [(list t1 '_) t1]
  8913. [(list `(Vector ,ts1 ...)
  8914. `(Vector ,ts2 ...))
  8915. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8916. (combine-types t1 t2)))]
  8917. [(list `(,ts1 ... -> ,rt1)
  8918. `(,ts2 ... -> ,rt2))
  8919. `(,@(for/list ([t1 ts1] [t2 ts2])
  8920. (combine-types t1 t2))
  8921. -> ,(combine-types rt1 rt2))]
  8922. [else t1]))
  8923. (define/public (flat-ty? ty)
  8924. (match ty
  8925. [(or `Integer `Boolean '_ `Void) #t]
  8926. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8927. [`(,ts ... -> ,rt)
  8928. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8929. [else #f]))
  8930. \end{lstlisting}
  8931. \caption{Auxiliary methods for type checking \LangAny{}.}
  8932. \label{fig:type-check-Rany-aux}
  8933. \end{figure}
  8934. \begin{figure}[btp]
  8935. \begin{lstlisting}
  8936. (define interp-Rany-class
  8937. (class interp-Rlambda-class
  8938. (super-new)
  8939. (define/override (interp-op op)
  8940. (match op
  8941. ['boolean? (match-lambda
  8942. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8943. [else #f])]
  8944. ['integer? (match-lambda
  8945. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8946. [else #f])]
  8947. ['vector? (match-lambda
  8948. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8949. [else #f])]
  8950. ['procedure? (match-lambda
  8951. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8952. [else #f])]
  8953. ['eq? (match-lambda*
  8954. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8955. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8956. [ls (apply (super interp-op op) ls)])]
  8957. ['any-vector-ref (lambda (v i)
  8958. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8959. ['any-vector-set! (lambda (v i a)
  8960. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8961. ['any-vector-length (lambda (v)
  8962. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8963. [else (super interp-op op)]))
  8964. (define/override ((interp-exp env) e)
  8965. (define recur (interp-exp env))
  8966. (match e
  8967. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8968. [(Project e ty2) (apply-project (recur e) ty2)]
  8969. [else ((super interp-exp env) e)]))
  8970. ))
  8971. (define (interp-Rany p)
  8972. (send (new interp-Rany-class) interp-program p))
  8973. \end{lstlisting}
  8974. \caption{Interpreter for \LangAny{}.}
  8975. \label{fig:interp-Rany}
  8976. \end{figure}
  8977. \begin{figure}[tbp]
  8978. \begin{lstlisting}
  8979. (define/public (apply-inject v tg) (Tagged v tg))
  8980. (define/public (apply-project v ty2)
  8981. (define tag2 (any-tag ty2))
  8982. (match v
  8983. [(Tagged v1 tag1)
  8984. (cond
  8985. [(eq? tag1 tag2)
  8986. (match ty2
  8987. [`(Vector ,ts ...)
  8988. (define l1 ((interp-op 'vector-length) v1))
  8989. (cond
  8990. [(eq? l1 (length ts)) v1]
  8991. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8992. l1 (length ts))])]
  8993. [`(,ts ... -> ,rt)
  8994. (match v1
  8995. [`(function ,xs ,body ,env)
  8996. (cond [(eq? (length xs) (length ts)) v1]
  8997. [else
  8998. (error 'apply-project "arity mismatch ~a != ~a"
  8999. (length xs) (length ts))])]
  9000. [else (error 'apply-project "expected function not ~a" v1)])]
  9001. [else v1])]
  9002. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9003. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9004. \end{lstlisting}
  9005. \caption{Auxiliary functions for injection and projection.}
  9006. \label{fig:apply-project}
  9007. \end{figure}
  9008. \clearpage
  9009. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9010. \label{sec:compile-r7}
  9011. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9012. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9013. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9014. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9015. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9016. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9017. the Boolean \code{\#t}, which must be injected to produce an
  9018. expression of type \key{Any}.
  9019. %
  9020. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9021. addition, is representative of compilation for many primitive
  9022. operations: the arguments have type \key{Any} and must be projected to
  9023. \key{Integer} before the addition can be performed.
  9024. The compilation of \key{lambda} (third row of
  9025. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9026. produce type annotations: we simply use \key{Any}.
  9027. %
  9028. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9029. has to account for some differences in behavior between \LangDyn{} and
  9030. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9031. kind of values can be used in various places. For example, the
  9032. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9033. the arguments need not be of the same type (in that case the
  9034. result is \code{\#f}).
  9035. \begin{figure}[btp]
  9036. \centering
  9037. \begin{tabular}{|lll|} \hline
  9038. \begin{minipage}{0.27\textwidth}
  9039. \begin{lstlisting}
  9040. #t
  9041. \end{lstlisting}
  9042. \end{minipage}
  9043. &
  9044. $\Rightarrow$
  9045. &
  9046. \begin{minipage}{0.65\textwidth}
  9047. \begin{lstlisting}
  9048. (inject #t Boolean)
  9049. \end{lstlisting}
  9050. \end{minipage}
  9051. \\[2ex]\hline
  9052. \begin{minipage}{0.27\textwidth}
  9053. \begin{lstlisting}
  9054. (+ |$e_1$| |$e_2$|)
  9055. \end{lstlisting}
  9056. \end{minipage}
  9057. &
  9058. $\Rightarrow$
  9059. &
  9060. \begin{minipage}{0.65\textwidth}
  9061. \begin{lstlisting}
  9062. (inject
  9063. (+ (project |$e'_1$| Integer)
  9064. (project |$e'_2$| Integer))
  9065. Integer)
  9066. \end{lstlisting}
  9067. \end{minipage}
  9068. \\[2ex]\hline
  9069. \begin{minipage}{0.27\textwidth}
  9070. \begin{lstlisting}
  9071. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9072. \end{lstlisting}
  9073. \end{minipage}
  9074. &
  9075. $\Rightarrow$
  9076. &
  9077. \begin{minipage}{0.65\textwidth}
  9078. \begin{lstlisting}
  9079. (inject
  9080. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9081. (Any|$\ldots$|Any -> Any))
  9082. \end{lstlisting}
  9083. \end{minipage}
  9084. \\[2ex]\hline
  9085. \begin{minipage}{0.27\textwidth}
  9086. \begin{lstlisting}
  9087. (|$e_0$| |$e_1 \ldots e_n$|)
  9088. \end{lstlisting}
  9089. \end{minipage}
  9090. &
  9091. $\Rightarrow$
  9092. &
  9093. \begin{minipage}{0.65\textwidth}
  9094. \begin{lstlisting}
  9095. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9096. \end{lstlisting}
  9097. \end{minipage}
  9098. \\[2ex]\hline
  9099. \begin{minipage}{0.27\textwidth}
  9100. \begin{lstlisting}
  9101. (vector-ref |$e_1$| |$e_2$|)
  9102. \end{lstlisting}
  9103. \end{minipage}
  9104. &
  9105. $\Rightarrow$
  9106. &
  9107. \begin{minipage}{0.65\textwidth}
  9108. \begin{lstlisting}
  9109. (any-vector-ref |$e_1'$| |$e_2'$|)
  9110. \end{lstlisting}
  9111. \end{minipage}
  9112. \\[2ex]\hline
  9113. \begin{minipage}{0.27\textwidth}
  9114. \begin{lstlisting}
  9115. (if |$e_1$| |$e_2$| |$e_3$|)
  9116. \end{lstlisting}
  9117. \end{minipage}
  9118. &
  9119. $\Rightarrow$
  9120. &
  9121. \begin{minipage}{0.65\textwidth}
  9122. \begin{lstlisting}
  9123. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9124. \end{lstlisting}
  9125. \end{minipage}
  9126. \\[2ex]\hline
  9127. \begin{minipage}{0.27\textwidth}
  9128. \begin{lstlisting}
  9129. (eq? |$e_1$| |$e_2$|)
  9130. \end{lstlisting}
  9131. \end{minipage}
  9132. &
  9133. $\Rightarrow$
  9134. &
  9135. \begin{minipage}{0.65\textwidth}
  9136. \begin{lstlisting}
  9137. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9138. \end{lstlisting}
  9139. \end{minipage}
  9140. \\[2ex]\hline
  9141. \begin{minipage}{0.27\textwidth}
  9142. \begin{lstlisting}
  9143. (not |$e_1$|)
  9144. \end{lstlisting}
  9145. \end{minipage}
  9146. &
  9147. $\Rightarrow$
  9148. &
  9149. \begin{minipage}{0.65\textwidth}
  9150. \begin{lstlisting}
  9151. (if (eq? |$e'_1$| (inject #f Boolean))
  9152. (inject #t Boolean) (inject #f Boolean))
  9153. \end{lstlisting}
  9154. \end{minipage}
  9155. \\[2ex]\hline
  9156. \end{tabular}
  9157. \caption{Cast Insertion}
  9158. \label{fig:compile-r7-Rany}
  9159. \end{figure}
  9160. \section{Reveal Casts}
  9161. \label{sec:reveal-casts-Rany}
  9162. % TODO: define R'_6
  9163. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9164. into an \code{if} expression that checks whether the value's tag
  9165. matches the target type; if it does, the value is converted to a value
  9166. of the target type by removing the tag; if it does not, the program
  9167. exits. To perform these actions we need a new primitive operation,
  9168. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9169. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9170. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9171. underlying value from a tagged value. The \code{ValueOf} form
  9172. includes the type for the underlying value which is used by the type
  9173. checker. Finally, the \code{Exit} form ends the execution of the
  9174. program.
  9175. If the target type of the projection is \code{Boolean} or
  9176. \code{Integer}, then \code{Project} can be translated as follows.
  9177. \begin{center}
  9178. \begin{minipage}{1.0\textwidth}
  9179. \begin{lstlisting}
  9180. (Project |$e$| |$\FType$|)
  9181. |$\Rightarrow$|
  9182. (Let |$\itm{tmp}$| |$e'$|
  9183. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9184. (Int |$\itm{tagof}(\FType)$|)))
  9185. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9186. (Exit)))
  9187. \end{lstlisting}
  9188. \end{minipage}
  9189. \end{center}
  9190. If the target type of the projection is a vector or function type,
  9191. then there is a bit more work to do. For vectors, check that the
  9192. length of the vector type matches the length of the vector (using the
  9193. \code{vector-length} primitive). For functions, check that the number
  9194. of parameters in the function type matches the function's arity (using
  9195. \code{procedure-arity}).
  9196. Regarding \code{inject}, we recommend compiling it to a slightly
  9197. lower-level primitive operation named \code{make-any}. This operation
  9198. takes a tag instead of a type.
  9199. \begin{center}
  9200. \begin{minipage}{1.0\textwidth}
  9201. \begin{lstlisting}
  9202. (Inject |$e$| |$\FType$|)
  9203. |$\Rightarrow$|
  9204. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9205. \end{lstlisting}
  9206. \end{minipage}
  9207. \end{center}
  9208. The type predicates (\code{boolean?}, etc.) can be translated into
  9209. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9210. translation of \code{Project}.
  9211. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9212. combine the projection action with the vector operation. Also, the
  9213. read and write operations allow arbitrary expressions for the index so
  9214. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9215. cannot guarantee that the index is within bounds. Thus, we insert code
  9216. to perform bounds checking at runtime. The translation for
  9217. \code{any-vector-ref} is as follows and the other two operations are
  9218. translated in a similar way.
  9219. \begin{lstlisting}
  9220. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9221. |$\Rightarrow$|
  9222. (Let |$v$| |$e'_1$|
  9223. (Let |$i$| |$e'_2$|
  9224. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9225. (If (Prim '< (list (Var |$i$|)
  9226. (Prim 'any-vector-length (list (Var |$v$|)))))
  9227. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9228. (Exit))))
  9229. \end{lstlisting}
  9230. \section{Remove Complex Operands}
  9231. \label{sec:rco-Rany}
  9232. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9233. The subexpression of \code{ValueOf} must be atomic.
  9234. \section{Explicate Control and \LangCAny{}}
  9235. \label{sec:explicate-Rany}
  9236. The output of \code{explicate-control} is the \LangCAny{} language whose
  9237. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9238. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9239. expression becomes a $\Tail$. Also, note that the index argument of
  9240. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9241. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9242. \begin{figure}[tp]
  9243. \fbox{
  9244. \begin{minipage}{0.96\textwidth}
  9245. \small
  9246. \[
  9247. \begin{array}{lcl}
  9248. \Exp &::= & \ldots
  9249. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9250. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9251. &\mid& \VALUEOF{\Exp}{\FType} \\
  9252. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9253. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9254. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9255. \mid \GOTO{\itm{label}} } \\
  9256. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9257. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9258. \mid \LP\key{Exit}\RP \\
  9259. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9260. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9261. \end{array}
  9262. \]
  9263. \end{minipage}
  9264. }
  9265. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9266. \label{fig:c5-syntax}
  9267. \end{figure}
  9268. \section{Select Instructions}
  9269. \label{sec:select-Rany}
  9270. In the \code{select-instructions} pass we translate the primitive
  9271. operations on the \code{Any} type to x86 instructions that involve
  9272. manipulating the 3 tag bits of the tagged value.
  9273. \paragraph{Make-any}
  9274. We recommend compiling the \key{make-any} primitive as follows if the
  9275. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9276. shifts the destination to the left by the number of bits specified its
  9277. source argument (in this case $3$, the length of the tag) and it
  9278. preserves the sign of the integer. We use the \key{orq} instruction to
  9279. combine the tag and the value to form the tagged value. \\
  9280. \begin{lstlisting}
  9281. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9282. |$\Rightarrow$|
  9283. movq |$e'$|, |\itm{lhs'}|
  9284. salq $3, |\itm{lhs'}|
  9285. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9286. \end{lstlisting}
  9287. The instruction selection for vectors and procedures is different
  9288. because their is no need to shift them to the left. The rightmost 3
  9289. bits are already zeros as described at the beginning of this
  9290. chapter. So we just combine the value and the tag using \key{orq}. \\
  9291. \begin{lstlisting}
  9292. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9293. |$\Rightarrow$|
  9294. movq |$e'$|, |\itm{lhs'}|
  9295. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9296. \end{lstlisting}
  9297. \paragraph{Tag-of-any}
  9298. Recall that the \code{tag-of-any} operation extracts the type tag from
  9299. a value of type \code{Any}. The type tag is the bottom three bits, so
  9300. we obtain the tag by taking the bitwise-and of the value with $111$
  9301. ($7$ in decimal).
  9302. \begin{lstlisting}
  9303. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9304. |$\Rightarrow$|
  9305. movq |$e'$|, |\itm{lhs'}|
  9306. andq $7, |\itm{lhs'}|
  9307. \end{lstlisting}
  9308. \paragraph{ValueOf}
  9309. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9310. depending on whether the type $T$ is a pointer (vector or procedure)
  9311. or not (Integer or Boolean). The following shows the instruction
  9312. selection for Integer and Boolean. We produce an untagged value by
  9313. shifting it to the right by 3 bits.
  9314. \begin{lstlisting}
  9315. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9316. |$\Rightarrow$|
  9317. movq |$e'$|, |\itm{lhs'}|
  9318. sarq $3, |\itm{lhs'}|
  9319. \end{lstlisting}
  9320. %
  9321. In the case for vectors and procedures, there is no need to
  9322. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9323. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9324. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9325. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9326. then apply \code{andq} with the tagged value to get the desired
  9327. result. \\
  9328. \begin{lstlisting}
  9329. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9330. |$\Rightarrow$|
  9331. movq $|$-8$|, |\itm{lhs'}|
  9332. andq |$e'$|, |\itm{lhs'}|
  9333. \end{lstlisting}
  9334. %% \paragraph{Type Predicates} We leave it to the reader to
  9335. %% devise a sequence of instructions to implement the type predicates
  9336. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9337. \paragraph{Any-vector-length}
  9338. \begin{lstlisting}
  9339. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9340. |$\Longrightarrow$|
  9341. movq |$\neg 111$|, %r11
  9342. andq |$a_1'$|, %r11
  9343. movq 0(%r11), %r11
  9344. andq $126, %r11
  9345. sarq $1, %r11
  9346. movq %r11, |$\itm{lhs'}$|
  9347. \end{lstlisting}
  9348. \paragraph{Any-vector-ref}
  9349. The index may be an arbitrary atom so instead of computing the offset
  9350. at compile time, instructions need to be generated to compute the
  9351. offset at runtime as follows. Note the use of the new instruction
  9352. \code{imulq}.
  9353. \begin{center}
  9354. \begin{minipage}{0.96\textwidth}
  9355. \begin{lstlisting}
  9356. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9357. |$\Longrightarrow$|
  9358. movq |$\neg 111$|, %r11
  9359. andq |$a_1'$|, %r11
  9360. movq |$a_2'$|, %rax
  9361. addq $1, %rax
  9362. imulq $8, %rax
  9363. addq %rax, %r11
  9364. movq 0(%r11) |$\itm{lhs'}$|
  9365. \end{lstlisting}
  9366. \end{minipage}
  9367. \end{center}
  9368. \paragraph{Any-vector-set!}
  9369. The code generation for \code{any-vector-set!} is similar to the other
  9370. \code{any-vector} operations.
  9371. \section{Register Allocation for \LangAny{}}
  9372. \label{sec:register-allocation-Rany}
  9373. \index{subject}{register allocation}
  9374. There is an interesting interaction between tagged values and garbage
  9375. collection that has an impact on register allocation. A variable of
  9376. type \code{Any} might refer to a vector and therefore it might be a
  9377. root that needs to be inspected and copied during garbage
  9378. collection. Thus, we need to treat variables of type \code{Any} in a
  9379. similar way to variables of type \code{Vector} for purposes of
  9380. register allocation. In particular,
  9381. \begin{itemize}
  9382. \item If a variable of type \code{Any} is live during a function call,
  9383. then it must be spilled. This can be accomplished by changing
  9384. \code{build-interference} to mark all variables of type \code{Any}
  9385. that are live after a \code{callq} as interfering with all the
  9386. registers.
  9387. \item If a variable of type \code{Any} is spilled, it must be spilled
  9388. to the root stack instead of the normal procedure call stack.
  9389. \end{itemize}
  9390. Another concern regarding the root stack is that the garbage collector
  9391. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9392. tagged value that points to a tuple, and (3) a tagged value that is
  9393. not a tuple. We enable this differentiation by choosing not to use the
  9394. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9395. reserved for identifying plain old pointers to tuples. That way, if
  9396. one of the first three bits is set, then we have a tagged value and
  9397. inspecting the tag can differentiation between vectors ($010$) and the
  9398. other kinds of values.
  9399. \begin{exercise}\normalfont
  9400. Expand your compiler to handle \LangAny{} as discussed in the last few
  9401. sections. Create 5 new programs that use the \code{Any} type and the
  9402. new operations (\code{inject}, \code{project}, \code{boolean?},
  9403. etc.). Test your compiler on these new programs and all of your
  9404. previously created test programs.
  9405. \end{exercise}
  9406. \begin{exercise}\normalfont
  9407. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9408. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9409. by removing type annotations. Add 5 more tests programs that
  9410. specifically rely on the language being dynamically typed. That is,
  9411. they should not be legal programs in a statically typed language, but
  9412. nevertheless, they should be valid \LangDyn{} programs that run to
  9413. completion without error.
  9414. \end{exercise}
  9415. \begin{figure}[p]
  9416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9417. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9418. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9419. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9420. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9421. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9422. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9423. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9424. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9425. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9426. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9427. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9428. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9429. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9430. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9431. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9432. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9433. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9434. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9435. \path[->,bend left=15] (Rfun) edge [above] node
  9436. {\ttfamily\footnotesize shrink} (Rfun-2);
  9437. \path[->,bend left=15] (Rfun-2) edge [above] node
  9438. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9439. \path[->,bend left=15] (Rfun-3) edge [above] node
  9440. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9441. \path[->,bend right=15] (Rfun-4) edge [left] node
  9442. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9443. \path[->,bend left=15] (Rfun-5) edge [above] node
  9444. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9445. \path[->,bend left=15] (Rfun-6) edge [left] node
  9446. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9447. \path[->,bend left=15] (Rfun-7) edge [below] node
  9448. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9449. \path[->,bend right=15] (F1-2) edge [above] node
  9450. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9451. \path[->,bend right=15] (F1-3) edge [above] node
  9452. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9453. \path[->,bend right=15] (F1-4) edge [above] node
  9454. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9455. \path[->,bend right=15] (F1-5) edge [right] node
  9456. {\ttfamily\footnotesize explicate-control} (C3-2);
  9457. \path[->,bend left=15] (C3-2) edge [left] node
  9458. {\ttfamily\footnotesize select-instr.} (x86-2);
  9459. \path[->,bend right=15] (x86-2) edge [left] node
  9460. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9461. \path[->,bend right=15] (x86-2-1) edge [below] node
  9462. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9463. \path[->,bend right=15] (x86-2-2) edge [left] node
  9464. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9465. \path[->,bend left=15] (x86-3) edge [above] node
  9466. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9467. \path[->,bend left=15] (x86-4) edge [right] node
  9468. {\ttfamily\footnotesize print-x86} (x86-5);
  9469. \end{tikzpicture}
  9470. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9471. \label{fig:Rdyn-passes}
  9472. \end{figure}
  9473. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9474. for the compilation of \LangDyn{}.
  9475. % Further Reading
  9476. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9477. \chapter{Loops and Assignment}
  9478. \label{ch:Rwhile}
  9479. % TODO: define R'_8
  9480. % TODO: multi-graph
  9481. In this chapter we study two features that are the hallmarks of
  9482. imperative programming languages: loops and assignments to local
  9483. variables. The following example demonstrates these new features by
  9484. computing the sum of the first five positive integers.
  9485. % similar to loop_test_1.rkt
  9486. \begin{lstlisting}
  9487. (let ([sum 0])
  9488. (let ([i 5])
  9489. (begin
  9490. (while (> i 0)
  9491. (begin
  9492. (set! sum (+ sum i))
  9493. (set! i (- i 1))))
  9494. sum)))
  9495. \end{lstlisting}
  9496. The \code{while} loop consists of a condition and a body.
  9497. %
  9498. The \code{set!} consists of a variable and a right-hand-side expression.
  9499. %
  9500. The primary purpose of both the \code{while} loop and \code{set!} is
  9501. to cause side effects, so it is convenient to also include in a
  9502. language feature for sequencing side effects: the \code{begin}
  9503. expression. It consists of one or more subexpressions that are
  9504. evaluated left-to-right.
  9505. \section{The \LangLoop{} Language}
  9506. \begin{figure}[tp]
  9507. \centering
  9508. \fbox{
  9509. \begin{minipage}{0.96\textwidth}
  9510. \small
  9511. \[
  9512. \begin{array}{lcl}
  9513. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9514. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9515. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9516. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9517. \mid (\key{and}\;\Exp\;\Exp)
  9518. \mid (\key{or}\;\Exp\;\Exp)
  9519. \mid (\key{not}\;\Exp) } \\
  9520. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9521. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9522. (\key{vector-ref}\;\Exp\;\Int)} \\
  9523. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9524. \mid (\Exp \; \Exp\ldots) } \\
  9525. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9526. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9527. &\mid& \CSETBANG{\Var}{\Exp}
  9528. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9529. \mid \CWHILE{\Exp}{\Exp} \\
  9530. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9531. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  9532. \end{array}
  9533. \]
  9534. \end{minipage}
  9535. }
  9536. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9537. \label{fig:Rwhile-concrete-syntax}
  9538. \end{figure}
  9539. \begin{figure}[tp]
  9540. \centering
  9541. \fbox{
  9542. \begin{minipage}{0.96\textwidth}
  9543. \small
  9544. \[
  9545. \begin{array}{lcl}
  9546. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9547. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9548. &\mid& \gray{ \BOOL{\itm{bool}}
  9549. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9550. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9551. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9552. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9553. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9554. \mid \WHILE{\Exp}{\Exp} \\
  9555. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9556. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9557. \end{array}
  9558. \]
  9559. \end{minipage}
  9560. }
  9561. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9562. \label{fig:Rwhile-syntax}
  9563. \end{figure}
  9564. The concrete syntax of \LangLoop{} is defined in
  9565. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9566. in Figure~\ref{fig:Rwhile-syntax}.
  9567. %
  9568. The definitional interpreter for \LangLoop{} is shown in
  9569. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9570. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9571. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9572. support assignment to variables and to make their lifetimes indefinite
  9573. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9574. box the value that is bound to each variable (in \code{Let}) and
  9575. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9576. the value.
  9577. %
  9578. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9579. variable in the environment to obtain a boxed value and then we change
  9580. it using \code{set-box!} to the result of evaluating the right-hand
  9581. side. The result value of a \code{SetBang} is \code{void}.
  9582. %
  9583. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9584. if the result is true, 2) evaluate the body.
  9585. The result value of a \code{while} loop is also \code{void}.
  9586. %
  9587. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9588. subexpressions \itm{es} for their effects and then evaluates
  9589. and returns the result from \itm{body}.
  9590. \begin{figure}[tbp]
  9591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9592. (define interp-Rwhile-class
  9593. (class interp-Rany-class
  9594. (super-new)
  9595. (define/override ((interp-exp env) e)
  9596. (define recur (interp-exp env))
  9597. (match e
  9598. [(SetBang x rhs)
  9599. (set-box! (lookup x env) (recur rhs))]
  9600. [(WhileLoop cnd body)
  9601. (define (loop)
  9602. (cond [(recur cnd) (recur body) (loop)]
  9603. [else (void)]))
  9604. (loop)]
  9605. [(Begin es body)
  9606. (for ([e es]) (recur e))
  9607. (recur body)]
  9608. [else ((super interp-exp env) e)]))
  9609. ))
  9610. (define (interp-Rwhile p)
  9611. (send (new interp-Rwhile-class) interp-program p))
  9612. \end{lstlisting}
  9613. \caption{Interpreter for \LangLoop{}.}
  9614. \label{fig:interp-Rwhile}
  9615. \end{figure}
  9616. The type checker for \LangLoop{} is define in
  9617. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9618. variable and the right-hand-side must agree. The result type is
  9619. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9620. \code{Boolean}. The result type is also \code{Void}. For
  9621. \code{Begin}, the result type is the type of its last subexpression.
  9622. \begin{figure}[tbp]
  9623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9624. (define type-check-Rwhile-class
  9625. (class type-check-Rany-class
  9626. (super-new)
  9627. (inherit check-type-equal?)
  9628. (define/override (type-check-exp env)
  9629. (lambda (e)
  9630. (define recur (type-check-exp env))
  9631. (match e
  9632. [(SetBang x rhs)
  9633. (define-values (rhs^ rhsT) (recur rhs))
  9634. (define varT (dict-ref env x))
  9635. (check-type-equal? rhsT varT e)
  9636. (values (SetBang x rhs^) 'Void)]
  9637. [(WhileLoop cnd body)
  9638. (define-values (cnd^ Tc) (recur cnd))
  9639. (check-type-equal? Tc 'Boolean e)
  9640. (define-values (body^ Tbody) ((type-check-exp env) body))
  9641. (values (WhileLoop cnd^ body^) 'Void)]
  9642. [(Begin es body)
  9643. (define-values (es^ ts)
  9644. (for/lists (l1 l2) ([e es]) (recur e)))
  9645. (define-values (body^ Tbody) (recur body))
  9646. (values (Begin es^ body^) Tbody)]
  9647. [else ((super type-check-exp env) e)])))
  9648. ))
  9649. (define (type-check-Rwhile p)
  9650. (send (new type-check-Rwhile-class) type-check-program p))
  9651. \end{lstlisting}
  9652. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9653. and \code{Begin} in \LangLoop{}.}
  9654. \label{fig:type-check-Rwhile}
  9655. \end{figure}
  9656. At first glance, the translation of these language features to x86
  9657. seems straightforward because the \LangCFun{} intermediate language already
  9658. supports all of the ingredients that we need: assignment, \code{goto},
  9659. conditional branching, and sequencing. However, there are two
  9660. complications that arise which we discuss in the next two
  9661. sections. After that we introduce one new compiler pass and the
  9662. changes necessary to the existing passes.
  9663. \section{Assignment and Lexically Scoped Functions}
  9664. \label{sec:assignment-scoping}
  9665. The addition of assignment raises a problem with our approach to
  9666. implementing lexically-scoped functions. Consider the following
  9667. example in which function \code{f} has a free variable \code{x} that
  9668. is changed after \code{f} is created but before the call to \code{f}.
  9669. % loop_test_11.rkt
  9670. \begin{lstlisting}
  9671. (let ([x 0])
  9672. (let ([y 0])
  9673. (let ([z 20])
  9674. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9675. (begin
  9676. (set! x 10)
  9677. (set! y 12)
  9678. (f y))))))
  9679. \end{lstlisting}
  9680. The correct output for this example is \code{42} because the call to
  9681. \code{f} is required to use the current value of \code{x} (which is
  9682. \code{10}). Unfortunately, the closure conversion pass
  9683. (Section~\ref{sec:closure-conversion}) generates code for the
  9684. \code{lambda} that copies the old value of \code{x} into a
  9685. closure. Thus, if we naively add support for assignment to our current
  9686. compiler, the output of this program would be \code{32}.
  9687. A first attempt at solving this problem would be to save a pointer to
  9688. \code{x} in the closure and change the occurrences of \code{x} inside
  9689. the lambda to dereference the pointer. Of course, this would require
  9690. assigning \code{x} to the stack and not to a register. However, the
  9691. problem goes a bit deeper. Consider the following example in which we
  9692. create a counter abstraction by creating a pair of functions that
  9693. share the free variable \code{x}.
  9694. % similar to loop_test_10.rkt
  9695. \begin{lstlisting}
  9696. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9697. (vector
  9698. (lambda: () : Integer x)
  9699. (lambda: () : Void (set! x (+ 1 x)))))
  9700. (let ([counter (f 0)])
  9701. (let ([get (vector-ref counter 0)])
  9702. (let ([inc (vector-ref counter 1)])
  9703. (begin
  9704. (inc)
  9705. (get)))))
  9706. \end{lstlisting}
  9707. In this example, the lifetime of \code{x} extends beyond the lifetime
  9708. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9709. stack frame for the call to \code{f}, it would be gone by the time we
  9710. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9711. \code{x}. This example demonstrates that when a variable occurs free
  9712. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9713. value of the variable needs to live on the heap. The verb ``box'' is
  9714. often used for allocating a single value on the heap, producing a
  9715. pointer, and ``unbox'' for dereferencing the pointer.
  9716. We recommend solving these problems by ``boxing'' the local variables
  9717. that are in the intersection of 1) variables that appear on the
  9718. left-hand-side of a \code{set!} and 2) variables that occur free
  9719. inside a \code{lambda}. We shall introduce a new pass named
  9720. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9721. perform this translation. But before diving into the compiler passes,
  9722. we one more problem to discuss.
  9723. \section{Cyclic Control Flow and Dataflow Analysis}
  9724. \label{sec:dataflow-analysis}
  9725. Up until this point the control-flow graphs generated in
  9726. \code{explicate-control} were guaranteed to be acyclic. However, each
  9727. \code{while} loop introduces a cycle in the control-flow graph.
  9728. But does that matter?
  9729. %
  9730. Indeed it does. Recall that for register allocation, the compiler
  9731. performs liveness analysis to determine which variables can share the
  9732. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9733. the control-flow graph in reverse topological order, but topological
  9734. order is only well-defined for acyclic graphs.
  9735. Let us return to the example of computing the sum of the first five
  9736. positive integers. Here is the program after instruction selection but
  9737. before register allocation.
  9738. \begin{center}
  9739. \begin{minipage}{0.45\textwidth}
  9740. \begin{lstlisting}
  9741. (define (main) : Integer
  9742. mainstart:
  9743. movq $0, sum1
  9744. movq $5, i2
  9745. jmp block5
  9746. block5:
  9747. movq i2, tmp3
  9748. cmpq tmp3, $0
  9749. jl block7
  9750. jmp block8
  9751. \end{lstlisting}
  9752. \end{minipage}
  9753. \begin{minipage}{0.45\textwidth}
  9754. \begin{lstlisting}
  9755. block7:
  9756. addq i2, sum1
  9757. movq $1, tmp4
  9758. negq tmp4
  9759. addq tmp4, i2
  9760. jmp block5
  9761. block8:
  9762. movq $27, %rax
  9763. addq sum1, %rax
  9764. jmp mainconclusion
  9765. )
  9766. \end{lstlisting}
  9767. \end{minipage}
  9768. \end{center}
  9769. Recall that liveness analysis works backwards, starting at the end
  9770. of each function. For this example we could start with \code{block8}
  9771. because we know what is live at the beginning of the conclusion,
  9772. just \code{rax} and \code{rsp}. So the live-before set
  9773. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9774. %
  9775. Next we might try to analyze \code{block5} or \code{block7}, but
  9776. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9777. we are stuck.
  9778. The way out of this impasse comes from the realization that one can
  9779. perform liveness analysis starting with an empty live-after set to
  9780. compute an under-approximation of the live-before set. By
  9781. \emph{under-approximation}, we mean that the set only contains
  9782. variables that are really live, but it may be missing some. Next, the
  9783. under-approximations for each block can be improved by 1) updating the
  9784. live-after set for each block using the approximate live-before sets
  9785. from the other blocks and 2) perform liveness analysis again on each
  9786. block. In fact, by iterating this process, the under-approximations
  9787. eventually become the correct solutions!
  9788. %
  9789. This approach of iteratively analyzing a control-flow graph is
  9790. applicable to many static analysis problems and goes by the name
  9791. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9792. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9793. Washington.
  9794. Let us apply this approach to the above example. We use the empty set
  9795. for the initial live-before set for each block. Let $m_0$ be the
  9796. following mapping from label names to sets of locations (variables and
  9797. registers).
  9798. \begin{center}
  9799. \begin{lstlisting}
  9800. mainstart: {}
  9801. block5: {}
  9802. block7: {}
  9803. block8: {}
  9804. \end{lstlisting}
  9805. \end{center}
  9806. Using the above live-before approximations, we determine the
  9807. live-after for each block and then apply liveness analysis to each
  9808. block. This produces our next approximation $m_1$ of the live-before
  9809. sets.
  9810. \begin{center}
  9811. \begin{lstlisting}
  9812. mainstart: {}
  9813. block5: {i2}
  9814. block7: {i2, sum1}
  9815. block8: {rsp, sum1}
  9816. \end{lstlisting}
  9817. \end{center}
  9818. For the second round, the live-after for \code{mainstart} is the
  9819. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9820. liveness analysis for \code{mainstart} computes the empty set. The
  9821. live-after for \code{block5} is the union of the live-before sets for
  9822. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9823. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9824. sum1\}}. The live-after for \code{block7} is the live-before for
  9825. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9826. So the liveness analysis for \code{block7} remains \code{\{i2,
  9827. sum1\}}. Together these yield the following approximation $m_2$ of
  9828. the live-before sets.
  9829. \begin{center}
  9830. \begin{lstlisting}
  9831. mainstart: {}
  9832. block5: {i2, rsp, sum1}
  9833. block7: {i2, sum1}
  9834. block8: {rsp, sum1}
  9835. \end{lstlisting}
  9836. \end{center}
  9837. In the preceding iteration, only \code{block5} changed, so we can
  9838. limit our attention to \code{mainstart} and \code{block7}, the two
  9839. blocks that jump to \code{block5}. As a result, the live-before sets
  9840. for \code{mainstart} and \code{block7} are updated to include
  9841. \code{rsp}, yielding the following approximation $m_3$.
  9842. \begin{center}
  9843. \begin{lstlisting}
  9844. mainstart: {rsp}
  9845. block5: {i2, rsp, sum1}
  9846. block7: {i2, rsp, sum1}
  9847. block8: {rsp, sum1}
  9848. \end{lstlisting}
  9849. \end{center}
  9850. Because \code{block7} changed, we analyze \code{block5} once more, but
  9851. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9852. our approximations have converged, so $m_3$ is the solution.
  9853. This iteration process is guaranteed to converge to a solution by the
  9854. Kleene Fixed-Point Theorem, a general theorem about functions on
  9855. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9856. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9857. elements, a least element $\bot$ (pronounced bottom), and a join
  9858. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9859. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9860. working with join semi-lattices.} When two elements are ordered $m_i
  9861. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9862. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9863. approximation than $m_i$. The bottom element $\bot$ represents the
  9864. complete lack of information, i.e., the worst approximation. The join
  9865. operator takes two lattice elements and combines their information,
  9866. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9867. bound}
  9868. A dataflow analysis typically involves two lattices: one lattice to
  9869. represent abstract states and another lattice that aggregates the
  9870. abstract states of all the blocks in the control-flow graph. For
  9871. liveness analysis, an abstract state is a set of locations. We form
  9872. the lattice $L$ by taking its elements to be sets of locations, the
  9873. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9874. set, and the join operator to be set union.
  9875. %
  9876. We form a second lattice $M$ by taking its elements to be mappings
  9877. from the block labels to sets of locations (elements of $L$). We
  9878. order the mappings point-wise, using the ordering of $L$. So given any
  9879. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9880. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9881. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9882. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9883. We can think of one iteration of liveness analysis as being a function
  9884. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9885. mapping.
  9886. \[
  9887. f(m_i) = m_{i+1}
  9888. \]
  9889. Next let us think for a moment about what a final solution $m_s$
  9890. should look like. If we perform liveness analysis using the solution
  9891. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9892. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9893. \[
  9894. f(m_s) = m_s
  9895. \]
  9896. Furthermore, the solution should only include locations that are
  9897. forced to be there by performing liveness analysis on the program, so
  9898. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9899. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9900. monotone (better inputs produce better outputs), then the least fixed
  9901. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9902. chain} obtained by starting at $\bot$ and iterating $f$ as
  9903. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9904. \[
  9905. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9906. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9907. \]
  9908. When a lattice contains only finitely-long ascending chains, then
  9909. every Kleene chain tops out at some fixed point after a number of
  9910. iterations of $f$. So that fixed point is also a least upper
  9911. bound of the chain.
  9912. \[
  9913. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9914. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9915. \]
  9916. The liveness analysis is indeed a monotone function and the lattice
  9917. $M$ only has finitely-long ascending chains because there are only a
  9918. finite number of variables and blocks in the program. Thus we are
  9919. guaranteed that iteratively applying liveness analysis to all blocks
  9920. in the program will eventually produce the least fixed point solution.
  9921. Next let us consider dataflow analysis in general and discuss the
  9922. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9923. %
  9924. The algorithm has four parameters: the control-flow graph \code{G}, a
  9925. function \code{transfer} that applies the analysis to one block, the
  9926. \code{bottom} and \code{join} operator for the lattice of abstract
  9927. states. The algorithm begins by creating the bottom mapping,
  9928. represented by a hash table. It then pushes all of the nodes in the
  9929. control-flow graph onto the work list (a queue). The algorithm repeats
  9930. the \code{while} loop as long as there are items in the work list. In
  9931. each iteration, a node is popped from the work list and processed. The
  9932. \code{input} for the node is computed by taking the join of the
  9933. abstract states of all the predecessor nodes. The \code{transfer}
  9934. function is then applied to obtain the \code{output} abstract
  9935. state. If the output differs from the previous state for this block,
  9936. the mapping for this block is updated and its successor nodes are
  9937. pushed onto the work list.
  9938. \begin{figure}[tb]
  9939. \begin{lstlisting}
  9940. (define (analyze-dataflow G transfer bottom join)
  9941. (define mapping (make-hash))
  9942. (for ([v (in-vertices G)])
  9943. (dict-set! mapping v bottom))
  9944. (define worklist (make-queue))
  9945. (for ([v (in-vertices G)])
  9946. (enqueue! worklist v))
  9947. (define trans-G (transpose G))
  9948. (while (not (queue-empty? worklist))
  9949. (define node (dequeue! worklist))
  9950. (define input (for/fold ([state bottom])
  9951. ([pred (in-neighbors trans-G node)])
  9952. (join state (dict-ref mapping pred))))
  9953. (define output (transfer node input))
  9954. (cond [(not (equal? output (dict-ref mapping node)))
  9955. (dict-set! mapping node output)
  9956. (for ([v (in-neighbors G node)])
  9957. (enqueue! worklist v))]))
  9958. mapping)
  9959. \end{lstlisting}
  9960. \caption{Generic work list algorithm for dataflow analysis}
  9961. \label{fig:generic-dataflow}
  9962. \end{figure}
  9963. Having discussed the two complications that arise from adding support
  9964. for assignment and loops, we turn to discussing the one new compiler
  9965. pass and the significant changes to existing passes.
  9966. \section{Convert Assignments}
  9967. \label{sec:convert-assignments}
  9968. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9969. the combination of assignments and lexically-scoped functions requires
  9970. that we box those variables that are both assigned-to and that appear
  9971. free inside a \code{lambda}. The purpose of the
  9972. \code{convert-assignments} pass is to carry out that transformation.
  9973. We recommend placing this pass after \code{uniquify} but before
  9974. \code{reveal-functions}.
  9975. Consider again the first example from
  9976. Section~\ref{sec:assignment-scoping}:
  9977. \begin{lstlisting}
  9978. (let ([x 0])
  9979. (let ([y 0])
  9980. (let ([z 20])
  9981. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9982. (begin
  9983. (set! x 10)
  9984. (set! y 12)
  9985. (f y))))))
  9986. \end{lstlisting}
  9987. The variables \code{x} and \code{y} are assigned-to. The variables
  9988. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9989. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9990. The boxing of \code{x} consists of three transformations: initialize
  9991. \code{x} with a vector, replace reads from \code{x} with
  9992. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9993. \code{vector-set!}. The output of \code{convert-assignments} for this
  9994. example is as follows.
  9995. \begin{lstlisting}
  9996. (define (main) : Integer
  9997. (let ([x0 (vector 0)])
  9998. (let ([y1 0])
  9999. (let ([z2 20])
  10000. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10001. (+ a3 (+ (vector-ref x0 0) z2)))])
  10002. (begin
  10003. (vector-set! x0 0 10)
  10004. (set! y1 12)
  10005. (f4 y1)))))))
  10006. \end{lstlisting}
  10007. \paragraph{Assigned \& Free}
  10008. We recommend defining an auxiliary function named
  10009. \code{assigned\&free} that takes an expression and simultaneously
  10010. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10011. that occur free within lambda's, and 3) a new version of the
  10012. expression that records which bound variables occurred in the
  10013. intersection of $A$ and $F$. You can use the struct
  10014. \code{AssignedFree} to do this. Consider the case for
  10015. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10016. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10017. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10018. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10019. \begin{lstlisting}
  10020. (Let |$x$| |$rhs$| |$body$|)
  10021. |$\Rightarrow$|
  10022. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10023. \end{lstlisting}
  10024. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10025. The set of assigned variables for this \code{Let} is
  10026. $A_r \cup (A_b - \{x\})$
  10027. and the set of variables free in lambda's is
  10028. $F_r \cup (F_b - \{x\})$.
  10029. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10030. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10031. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10032. and $F_r$.
  10033. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10034. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10035. recursively processing \itm{body}. Wrap each of parameter that occurs
  10036. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10037. Let $P$ be the set of parameter names in \itm{params}. The result is
  10038. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10039. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10040. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10041. \paragraph{Convert Assignments}
  10042. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10043. functions for expressions and definitions. The function for
  10044. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10045. set of assigned-and-free variables (obtained from the result of
  10046. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10047. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10048. \code{vector-ref}.
  10049. \begin{lstlisting}
  10050. (Var |$x$|)
  10051. |$\Rightarrow$|
  10052. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10053. \end{lstlisting}
  10054. %
  10055. In the case for $\LET{\LP\code{AssignedFree}\,
  10056. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10057. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10058. \itm{body'} but with $x$ added to the set of assigned-and-free
  10059. variables. Translate the let-expression as follows to bind $x$ to a
  10060. boxed value.
  10061. \begin{lstlisting}
  10062. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10063. |$\Rightarrow$|
  10064. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10065. \end{lstlisting}
  10066. %
  10067. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10068. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10069. variables, translate the \code{set!} into a \code{vector-set!}
  10070. as follows.
  10071. \begin{lstlisting}
  10072. (SetBang |$x$| |$\itm{rhs}$|)
  10073. |$\Rightarrow$|
  10074. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10075. \end{lstlisting}
  10076. %
  10077. The case for \code{Lambda} is non-trivial, but it is similar to the
  10078. case for function definitions, which we discuss next.
  10079. The auxiliary function for definitions, \code{cnvt-assign-def},
  10080. applies assignment conversion to function definitions.
  10081. We translate a function definition as follows.
  10082. \begin{lstlisting}
  10083. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10084. |$\Rightarrow$|
  10085. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10086. \end{lstlisting}
  10087. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10088. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10089. \code{assigned\&free} on $\itm{body_1}$.
  10090. Let $P$ be the parameter names in \itm{params}.
  10091. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10092. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10093. as the set of assigned-and-free variables.
  10094. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10095. in a sequence of let-expressions that box the parameters
  10096. that are in $A_b \cap F_b$.
  10097. %
  10098. Regarding \itm{params'}, change the names of the parameters that are
  10099. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10100. variables can retain the original names). Recall the second example in
  10101. Section~\ref{sec:assignment-scoping} involving a counter
  10102. abstraction. The following is the output of assignment version for
  10103. function \code{f}.
  10104. \begin{lstlisting}
  10105. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10106. (vector
  10107. (lambda: () : Integer x1)
  10108. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10109. |$\Rightarrow$|
  10110. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10111. (let ([x1 (vector param_x1)])
  10112. (vector (lambda: () : Integer (vector-ref x1 0))
  10113. (lambda: () : Void
  10114. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10115. \end{lstlisting}
  10116. \section{Remove Complex Operands}
  10117. \label{sec:rco-loop}
  10118. The three new language forms, \code{while}, \code{set!}, and
  10119. \code{begin} are all complex expressions and their subexpressions are
  10120. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10121. output language \LangFunANF{} of this pass.
  10122. \begin{figure}[tp]
  10123. \centering
  10124. \fbox{
  10125. \begin{minipage}{0.96\textwidth}
  10126. \small
  10127. \[
  10128. \begin{array}{rcl}
  10129. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10130. \mid \VOID{} } \\
  10131. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10132. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10133. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10134. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10135. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10136. \end{array}
  10137. \]
  10138. \end{minipage}
  10139. }
  10140. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10141. \label{fig:Rwhile-anf-syntax}
  10142. \end{figure}
  10143. As usual, when a complex expression appears in a grammar position that
  10144. needs to be atomic, such as the argument of a primitive operator, we
  10145. must introduce a temporary variable and bind it to the complex
  10146. expression. This approach applies, unchanged, to handle the new
  10147. language forms. For example, in the following code there are two
  10148. \code{begin} expressions appearing as arguments to \code{+}. The
  10149. output of \code{rco-exp} is shown below, in which the \code{begin}
  10150. expressions have been bound to temporary variables. Recall that
  10151. \code{let} expressions in \LangLoopANF{} are allowed to have
  10152. arbitrary expressions in their right-hand-side expression, so it is
  10153. fine to place \code{begin} there.
  10154. \begin{lstlisting}
  10155. (let ([x0 10])
  10156. (let ([y1 0])
  10157. (+ (+ (begin (set! y1 (read)) x0)
  10158. (begin (set! x0 (read)) y1))
  10159. x0)))
  10160. |$\Rightarrow$|
  10161. (let ([x0 10])
  10162. (let ([y1 0])
  10163. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10164. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10165. (let ([tmp4 (+ tmp2 tmp3)])
  10166. (+ tmp4 x0))))))
  10167. \end{lstlisting}
  10168. \section{Explicate Control and \LangCLoop{}}
  10169. \label{sec:explicate-loop}
  10170. Recall that in the \code{explicate-control} pass we define one helper
  10171. function for each kind of position in the program. For the \LangVar{}
  10172. language of integers and variables we needed kinds of positions:
  10173. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10174. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10175. yet another kind of position: effect position. Except for the last
  10176. subexpression, the subexpressions inside a \code{begin} are evaluated
  10177. only for their effect. Their result values are discarded. We can
  10178. generate better code by taking this fact into account.
  10179. The output language of \code{explicate-control} is \LangCLoop{}
  10180. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10181. \LangCLam{}. The only syntactic difference is that \code{Call},
  10182. \code{vector-set!}, and \code{read} may also appear as statements.
  10183. The most significant difference between \LangCLam{} and \LangCLoop{}
  10184. is that the control-flow graphs of the later may contain cycles.
  10185. \begin{figure}[tp]
  10186. \fbox{
  10187. \begin{minipage}{0.96\textwidth}
  10188. \small
  10189. \[
  10190. \begin{array}{lcl}
  10191. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10192. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10193. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10194. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10195. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10196. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10197. \end{array}
  10198. \]
  10199. \end{minipage}
  10200. }
  10201. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10202. \label{fig:c7-syntax}
  10203. \end{figure}
  10204. The new auxiliary function \code{explicate-effect} takes an expression
  10205. (in an effect position) and a promise of a continuation block. The
  10206. function returns a promise for a $\Tail$ that includes the generated
  10207. code for the input expression followed by the continuation block. If
  10208. the expression is obviously pure, that is, never causes side effects,
  10209. then the expression can be removed, so the result is just the
  10210. continuation block.
  10211. %
  10212. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10213. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10214. the loop. Recursively process the \itm{body} (in effect position)
  10215. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10216. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10217. \itm{body'} as the then-branch and the continuation block as the
  10218. else-branch. The result should be added to the control-flow graph with
  10219. the label \itm{loop}. The result for the whole \code{while} loop is a
  10220. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10221. added to the control-flow graph if the loop is indeed used, which can
  10222. be accomplished using \code{delay}.
  10223. The auxiliary functions for tail, assignment, and predicate positions
  10224. need to be updated. The three new language forms, \code{while},
  10225. \code{set!}, and \code{begin}, can appear in assignment and tail
  10226. positions. Only \code{begin} may appear in predicate positions; the
  10227. other two have result type \code{Void}.
  10228. \section{Select Instructions}
  10229. \label{sec:select-instructions-loop}
  10230. Only three small additions are needed in the
  10231. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10232. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10233. stand-alone statements instead of only appearing on the right-hand
  10234. side of an assignment statement. The code generation is nearly
  10235. identical; just leave off the instruction for moving the result into
  10236. the left-hand side.
  10237. \section{Register Allocation}
  10238. \label{sec:register-allocation-loop}
  10239. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10240. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10241. which complicates the liveness analysis needed for register
  10242. allocation.
  10243. \subsection{Liveness Analysis}
  10244. \label{sec:liveness-analysis-r8}
  10245. We recommend using the generic \code{analyze-dataflow} function that
  10246. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10247. perform liveness analysis, replacing the code in
  10248. \code{uncover-live-CFG} that processed the basic blocks in topological
  10249. order (Section~\ref{sec:liveness-analysis-Rif}).
  10250. The \code{analyze-dataflow} function has four parameters.
  10251. \begin{enumerate}
  10252. \item The first parameter \code{G} should be a directed graph from the
  10253. \code{racket/graph} package (see the sidebar in
  10254. Section~\ref{sec:build-interference}) that represents the
  10255. control-flow graph.
  10256. \item The second parameter \code{transfer} is a function that applies
  10257. liveness analysis to a basic block. It takes two parameters: the
  10258. label for the block to analyze and the live-after set for that
  10259. block. The transfer function should return the live-before set for
  10260. the block. Also, as a side-effect, it should update the block's
  10261. $\itm{info}$ with the liveness information for each instruction. To
  10262. implement the \code{transfer} function, you should be able to reuse
  10263. the code you already have for analyzing basic blocks.
  10264. \item The third and fourth parameters of \code{analyze-dataflow} are
  10265. \code{bottom} and \code{join} for the lattice of abstract states,
  10266. i.e. sets of locations. The bottom of the lattice is the empty set
  10267. \code{(set)} and the join operator is \code{set-union}.
  10268. \end{enumerate}
  10269. \begin{figure}[p]
  10270. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10271. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10272. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10273. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10274. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10275. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10276. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10277. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10278. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10279. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10280. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10281. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10282. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10283. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10284. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10285. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10286. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10287. %% \path[->,bend left=15] (Rfun) edge [above] node
  10288. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10289. \path[->,bend left=15] (Rfun) edge [above] node
  10290. {\ttfamily\footnotesize shrink} (Rfun-2);
  10291. \path[->,bend left=15] (Rfun-2) edge [above] node
  10292. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10293. \path[->,bend left=15] (Rfun-3) edge [above] node
  10294. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10295. \path[->,bend left=15] (Rfun-4) edge [right] node
  10296. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10297. \path[->,bend left=15] (F1-1) edge [below] node
  10298. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10299. \path[->,bend right=15] (F1-2) edge [above] node
  10300. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10301. \path[->,bend right=15] (F1-3) edge [above] node
  10302. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10303. \path[->,bend right=15] (F1-4) edge [above] node
  10304. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10305. \path[->,bend right=15] (F1-5) edge [right] node
  10306. {\ttfamily\footnotesize explicate-control} (C3-2);
  10307. \path[->,bend left=15] (C3-2) edge [left] node
  10308. {\ttfamily\footnotesize select-instr.} (x86-2);
  10309. \path[->,bend right=15] (x86-2) edge [left] node
  10310. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10311. \path[->,bend right=15] (x86-2-1) edge [below] node
  10312. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10313. \path[->,bend right=15] (x86-2-2) edge [left] node
  10314. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10315. \path[->,bend left=15] (x86-3) edge [above] node
  10316. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10317. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10318. \end{tikzpicture}
  10319. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10320. \label{fig:Rwhile-passes}
  10321. \end{figure}
  10322. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10323. for the compilation of \LangLoop{}.
  10324. \section{Challenge: Arrays}
  10325. \label{sec:arrays}
  10326. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10327. elements whose length is determined at compile-time and where each
  10328. element of a tuple may have a different type (they are
  10329. heterogeous). This challenge is also about sequences, but this time
  10330. the length is determined at run-time and all the elements have the same
  10331. type (they are homogeneous). We use the term ``array'' for this later
  10332. kind of sequence.
  10333. The Racket language does not distinguish between tuples and arrays,
  10334. they are both represented by vectors. However, Typed Racket
  10335. distinguishes between tuples and arrays: the \code{Vector} type is for
  10336. tuples and the \code{Vectorof} type is for arrays.
  10337. %
  10338. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10339. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10340. and the \code{make-vector} primitive operator for creating an array,
  10341. whose arguments are the length of the array and an initial value for
  10342. all the elements in the array. The \code{vector-length},
  10343. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10344. for tuples become overloaded for use with arrays.
  10345. %
  10346. We also include integer multiplication in \LangArray{}, as it is
  10347. useful in many examples involving arrays such as computing the
  10348. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10349. \begin{figure}[tp]
  10350. \centering
  10351. \fbox{
  10352. \begin{minipage}{0.96\textwidth}
  10353. \small
  10354. \[
  10355. \begin{array}{lcl}
  10356. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10357. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10358. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10359. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10360. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10361. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10362. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10363. \mid \LP\key{not}\;\Exp\RP } \\
  10364. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10365. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10366. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10367. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10368. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10369. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10370. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10371. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10372. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10373. \mid \CWHILE{\Exp}{\Exp} } \\
  10374. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10375. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10376. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10377. \end{array}
  10378. \]
  10379. \end{minipage}
  10380. }
  10381. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10382. \label{fig:Rvecof-concrete-syntax}
  10383. \end{figure}
  10384. \begin{figure}[tp]
  10385. \begin{lstlisting}
  10386. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10387. [n : Integer]) : Integer
  10388. (let ([i 0])
  10389. (let ([prod 0])
  10390. (begin
  10391. (while (< i n)
  10392. (begin
  10393. (set! prod (+ prod (* (vector-ref A i)
  10394. (vector-ref B i))))
  10395. (set! i (+ i 1))
  10396. ))
  10397. prod))))
  10398. (let ([A (make-vector 2 2)])
  10399. (let ([B (make-vector 2 3)])
  10400. (+ (inner-product A B 2)
  10401. 30)))
  10402. \end{lstlisting}
  10403. \caption{Example program that computes the inner-product.}
  10404. \label{fig:inner-product}
  10405. \end{figure}
  10406. The type checker for \LangArray{} is define in
  10407. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10408. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10409. of the intializing expression. The length expression is required to
  10410. have type \code{Integer}. The type checking of the operators
  10411. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10412. updated to handle the situation where the vector has type
  10413. \code{Vectorof}. In these cases we translate the operators to their
  10414. \code{vectorof} form so that later passes can easily distinguish
  10415. between operations on tuples versus arrays. We override the
  10416. \code{operator-types} method to provide the type signature for
  10417. multiplication: it takes two integers and returns an integer. To
  10418. support injection and projection of arrays to the \code{Any} type
  10419. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10420. predicate.
  10421. \begin{figure}[tbp]
  10422. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10423. (define type-check-Rvecof-class
  10424. (class type-check-Rwhile-class
  10425. (super-new)
  10426. (inherit check-type-equal?)
  10427. (define/override (flat-ty? ty)
  10428. (match ty
  10429. ['(Vectorof Any) #t]
  10430. [else (super flat-ty? ty)]))
  10431. (define/override (operator-types)
  10432. (append '((* . ((Integer Integer) . Integer)))
  10433. (super operator-types)))
  10434. (define/override (type-check-exp env)
  10435. (lambda (e)
  10436. (define recur (type-check-exp env))
  10437. (match e
  10438. [(Prim 'make-vector (list e1 e2))
  10439. (define-values (e1^ t1) (recur e1))
  10440. (define-values (e2^ elt-type) (recur e2))
  10441. (define vec-type `(Vectorof ,elt-type))
  10442. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10443. vec-type)]
  10444. [(Prim 'vector-ref (list e1 e2))
  10445. (define-values (e1^ t1) (recur e1))
  10446. (define-values (e2^ t2) (recur e2))
  10447. (match* (t1 t2)
  10448. [(`(Vectorof ,elt-type) 'Integer)
  10449. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10450. [(other wise) ((super type-check-exp env) e)])]
  10451. [(Prim 'vector-set! (list e1 e2 e3) )
  10452. (define-values (e-vec t-vec) (recur e1))
  10453. (define-values (e2^ t2) (recur e2))
  10454. (define-values (e-arg^ t-arg) (recur e3))
  10455. (match t-vec
  10456. [`(Vectorof ,elt-type)
  10457. (check-type-equal? elt-type t-arg e)
  10458. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10459. [else ((super type-check-exp env) e)])]
  10460. [(Prim 'vector-length (list e1))
  10461. (define-values (e1^ t1) (recur e1))
  10462. (match t1
  10463. [`(Vectorof ,t)
  10464. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10465. [else ((super type-check-exp env) e)])]
  10466. [else ((super type-check-exp env) e)])))
  10467. ))
  10468. (define (type-check-Rvecof p)
  10469. (send (new type-check-Rvecof-class) type-check-program p))
  10470. \end{lstlisting}
  10471. \caption{Type checker for the \LangArray{} language.}
  10472. \label{fig:type-check-Rvecof}
  10473. \end{figure}
  10474. The interpreter for \LangArray{} is defined in
  10475. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10476. implemented with Racket's \code{make-vector} function and
  10477. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10478. integers.
  10479. \begin{figure}[tbp]
  10480. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10481. (define interp-Rvecof-class
  10482. (class interp-Rwhile-class
  10483. (super-new)
  10484. (define/override (interp-op op)
  10485. (verbose "Rvecof/interp-op" op)
  10486. (match op
  10487. ['make-vector make-vector]
  10488. ['* fx*]
  10489. [else (super interp-op op)]))
  10490. ))
  10491. (define (interp-Rvecof p)
  10492. (send (new interp-Rvecof-class) interp-program p))
  10493. \end{lstlisting}
  10494. \caption{Interpreter for \LangArray{}.}
  10495. \label{fig:interp-Rvecof}
  10496. \end{figure}
  10497. \subsection{Data Representation}
  10498. \label{sec:array-rep}
  10499. Just like tuples, we store arrays on the heap which means that the
  10500. garbage collector will need to inspect arrays. An immediate thought is
  10501. to use the same representation for arrays that we use for tuples.
  10502. However, we limit tuples to a length of $50$ so that their length and
  10503. pointer mask can fit into the 64-bit tag at the beginning of each
  10504. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10505. millions of elements, so we need more bits to store the length.
  10506. However, because arrays are homogeneous, we only need $1$ bit for the
  10507. pointer mask instead of one bit per array elements. Finally, the
  10508. garbage collector will need to be able to distinguish between tuples
  10509. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10510. arrive at the following layout for the 64-bit tag at the beginning of
  10511. an array:
  10512. \begin{itemize}
  10513. \item The right-most bit is the forwarding bit, just like in a tuple.
  10514. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10515. it is not.
  10516. \item The next bit to the left is the pointer mask. A $0$ indicates
  10517. that none of the elements are pointers to the heap and a $1$
  10518. indicates that all of the elements are pointers.
  10519. \item The next $61$ bits store the length of the array.
  10520. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10521. array ($1$).
  10522. \end{itemize}
  10523. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10524. differentiate the kinds of values that have been injected into the
  10525. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10526. to indicate that the value is an array.
  10527. In the following subsections we provide hints regarding how to update
  10528. the passes to handle arrays.
  10529. \subsection{Reveal Casts}
  10530. The array-access operators \code{vectorof-ref} and
  10531. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10532. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10533. that the type checker cannot tell whether the index will be in bounds,
  10534. so the bounds check must be performed at run time. Recall that the
  10535. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10536. an \code{If} arround a vector reference for update to check whether
  10537. the index is less than the length. You should do the same for
  10538. \code{vectorof-ref} and \code{vectorof-set!} .
  10539. In addition, the handling of the \code{any-vector} operators in
  10540. \code{reveal-casts} needs to be updated to account for arrays that are
  10541. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10542. generated code should test whether the tag is for tuples (\code{010})
  10543. or arrays (\code{110}) and then dispatch to either
  10544. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10545. we add a case in \code{select-instructions} to generate the
  10546. appropriate instructions for accessing the array length from the
  10547. header of an array.
  10548. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10549. the generated code needs to check that the index is less than the
  10550. vector length, so like the code for \code{any-vector-length}, check
  10551. the tag to determine whether to use \code{any-vector-length} or
  10552. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10553. is complete, the generated code can use \code{any-vector-ref} and
  10554. \code{any-vector-set!} for both tuples and arrays because the
  10555. instructions used for those operators do not look at the tag at the
  10556. front of the tuple or array.
  10557. \subsection{Expose Allocation}
  10558. This pass should translate the \code{make-vector} operator into
  10559. lower-level operations. In particular, the new AST node
  10560. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10561. length specified by the $\Exp$, but does not initialize the elements
  10562. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10563. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10564. element type for the array. Regarding the initialization of the array,
  10565. we recommend generated a \code{while} loop that uses
  10566. \code{vector-set!} to put the initializing value into every element of
  10567. the array.
  10568. \subsection{Remove Complex Operands}
  10569. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10570. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10571. complex and its subexpression must be atomic.
  10572. \subsection{Explicate Control}
  10573. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10574. \code{explicate-assign}.
  10575. \subsection{Select Instructions}
  10576. Generate instructions for \code{AllocateArray} similar to those for
  10577. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10578. that the tag at the front of the array should instead use the
  10579. representation discussed in Section~\ref{sec:array-rep}.
  10580. Regarding \code{vectorof-length}, extract the length from the tag
  10581. according to the representation discussed in
  10582. Section~\ref{sec:array-rep}.
  10583. The instructions generated for \code{vectorof-ref} differ from those
  10584. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10585. that the index is not a constant so the offset must be computed at
  10586. runtime, similar to the instructions generated for
  10587. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10588. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10589. appear in an assignment and as a stand-alone statement, so make sure
  10590. to handle both situations in this pass.
  10591. Finally, the instructions for \code{any-vectorof-length} should be
  10592. similar to those for \code{vectorof-length}, except that one must
  10593. first project the array by writing zeroes into the $3$-bit tag
  10594. \begin{exercise}\normalfont
  10595. Implement a compiler for the \LangArray{} language by extending your
  10596. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10597. programs, including the one in Figure~\ref{fig:inner-product} and also
  10598. a program that multiplies two matrices. Note that matrices are
  10599. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10600. arrays by laying out each row in the array, one after the next.
  10601. \end{exercise}
  10602. % Further Reading: dataflow analysis
  10603. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10604. \chapter{Gradual Typing}
  10605. \label{ch:Rgrad}
  10606. \index{subject}{gradual typing}
  10607. This chapter studies a language, \LangGrad{}, in which the programmer
  10608. can choose between static and dynamic type checking in different parts
  10609. of a program, thereby mixing the statically typed \LangLoop{} language
  10610. with the dynamically typed \LangDyn{}. There are several approaches to
  10611. mixing static and dynamic typing, including multi-language
  10612. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10613. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10614. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  10615. programmer controls the amount of static versus dynamic checking by
  10616. adding or removing type annotations on parameters and
  10617. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10618. %
  10619. The concrete syntax of \LangGrad{} is defined in
  10620. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10621. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10622. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10623. non-terminals that make type annotations optional. The return types
  10624. are not optional in the abstract syntax; the parser fills in
  10625. \code{Any} when the return type is not specified in the concrete
  10626. syntax.
  10627. \begin{figure}[tp]
  10628. \centering
  10629. \fbox{
  10630. \begin{minipage}{0.96\textwidth}
  10631. \small
  10632. \[
  10633. \begin{array}{lcl}
  10634. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10635. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10636. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10637. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10638. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10639. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10640. \mid (\key{and}\;\Exp\;\Exp)
  10641. \mid (\key{or}\;\Exp\;\Exp)
  10642. \mid (\key{not}\;\Exp) } \\
  10643. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10644. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10645. (\key{vector-ref}\;\Exp\;\Int)} \\
  10646. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10647. \mid (\Exp \; \Exp\ldots) } \\
  10648. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10649. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10650. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10651. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10652. \mid \CWHILE{\Exp}{\Exp} } \\
  10653. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10654. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  10655. \end{array}
  10656. \]
  10657. \end{minipage}
  10658. }
  10659. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10660. \label{fig:Rgrad-concrete-syntax}
  10661. \end{figure}
  10662. \begin{figure}[tp]
  10663. \centering
  10664. \fbox{
  10665. \begin{minipage}{0.96\textwidth}
  10666. \small
  10667. \[
  10668. \begin{array}{lcl}
  10669. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10670. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10671. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10672. &\mid& \gray{ \BOOL{\itm{bool}}
  10673. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10674. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10675. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10676. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10677. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10678. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10679. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10680. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10681. \end{array}
  10682. \]
  10683. \end{minipage}
  10684. }
  10685. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10686. \label{fig:Rgrad-syntax}
  10687. \end{figure}
  10688. Both the type checker and the interpreter for \LangGrad{} require some
  10689. interesting changes to enable gradual typing, which we discuss in the
  10690. next two sections in the context of the \code{map-vec} example from
  10691. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10692. revised the \code{map-vec} example, omitting the type annotations from
  10693. the \code{add1} function.
  10694. \begin{figure}[btp]
  10695. % gradual_test_9.rkt
  10696. \begin{lstlisting}
  10697. (define (map-vec [f : (Integer -> Integer)]
  10698. [v : (Vector Integer Integer)])
  10699. : (Vector Integer Integer)
  10700. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10701. (define (add1 x) (+ x 1))
  10702. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10703. \end{lstlisting}
  10704. \caption{A partially-typed version of the \code{map-vec} example.}
  10705. \label{fig:gradual-map-vec}
  10706. \end{figure}
  10707. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10708. \label{sec:gradual-type-check}
  10709. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10710. parameter and return types. For example, the \code{x} parameter of
  10711. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10712. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10713. consider the \code{+} operator inside \code{add1}. It expects both
  10714. arguments to have type \code{Integer}, but its first argument \code{x}
  10715. has type \code{Any}. In a gradually typed language, such differences
  10716. are allowed so long as the types are \emph{consistent}, that is, they
  10717. are equal except in places where there is an \code{Any} type. The type
  10718. \code{Any} is consistent with every other type.
  10719. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10720. \begin{figure}[tbp]
  10721. \begin{lstlisting}
  10722. (define/public (consistent? t1 t2)
  10723. (match* (t1 t2)
  10724. [('Integer 'Integer) #t]
  10725. [('Boolean 'Boolean) #t]
  10726. [('Void 'Void) #t]
  10727. [('Any t2) #t]
  10728. [(t1 'Any) #t]
  10729. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10730. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10731. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10732. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10733. (consistent? rt1 rt2))]
  10734. [(other wise) #f]))
  10735. \end{lstlisting}
  10736. \caption{The consistency predicate on types.}
  10737. \label{fig:consistent}
  10738. \end{figure}
  10739. Returning to the \code{map-vec} example of
  10740. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10741. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10742. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10743. because the two types are consistent. In particular, \code{->} is
  10744. equal to \code{->} and because \code{Any} is consistent with
  10745. \code{Integer}.
  10746. Next consider a program with an error, such as applying the
  10747. \code{map-vec} to a function that sometimes returns a Boolean, as
  10748. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10749. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10750. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10751. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10752. Integer)}. One might say that a gradual type checker is optimistic
  10753. in that it accepts programs that might execute without a runtime type
  10754. error.
  10755. %
  10756. Unfortunately, running this program with input \code{1} triggers an
  10757. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10758. performs checking at runtime to ensure the integrity of the static
  10759. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10760. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10761. new \code{Cast} form that is inserted by the type checker. Thus, the
  10762. output of the type checker is a program in the \LangCast{} language, which
  10763. adds \code{Cast} to \LangLoop{}, as shown in
  10764. Figure~\ref{fig:Rgrad-prime-syntax}.
  10765. \begin{figure}[tp]
  10766. \centering
  10767. \fbox{
  10768. \begin{minipage}{0.96\textwidth}
  10769. \small
  10770. \[
  10771. \begin{array}{lcl}
  10772. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10773. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10774. \end{array}
  10775. \]
  10776. \end{minipage}
  10777. }
  10778. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10779. \label{fig:Rgrad-prime-syntax}
  10780. \end{figure}
  10781. \begin{figure}[tbp]
  10782. \begin{lstlisting}
  10783. (define (map-vec [f : (Integer -> Integer)]
  10784. [v : (Vector Integer Integer)])
  10785. : (Vector Integer Integer)
  10786. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10787. (define (add1 x) (+ x 1))
  10788. (define (true) #t)
  10789. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10790. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10791. \end{lstlisting}
  10792. \caption{A variant of the \code{map-vec} example with an error.}
  10793. \label{fig:map-vec-maybe-add1}
  10794. \end{figure}
  10795. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10796. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10797. inserted every time the type checker sees two types that are
  10798. consistent but not equal. In the \code{add1} function, \code{x} is
  10799. cast to \code{Integer} and the result of the \code{+} is cast to
  10800. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10801. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10802. \begin{figure}[btp]
  10803. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10804. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10805. : (Vector Integer Integer)
  10806. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10807. (define (add1 [x : Any]) : Any
  10808. (cast (+ (cast x Any Integer) 1) Integer Any))
  10809. (define (true) : Any (cast #t Boolean Any))
  10810. (define (maybe-add1 [x : Any]) : Any
  10811. (if (eq? 0 (read)) (add1 x) (true)))
  10812. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10813. (vector 0 41)) 0)
  10814. \end{lstlisting}
  10815. \caption{Output of type checking \code{map-vec}
  10816. and \code{maybe-add1}.}
  10817. \label{fig:map-vec-cast}
  10818. \end{figure}
  10819. The type checker for \LangGrad{} is defined in
  10820. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10821. and \ref{fig:type-check-Rgradual-3}.
  10822. \begin{figure}[tbp]
  10823. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10824. (define type-check-gradual-class
  10825. (class type-check-Rwhile-class
  10826. (super-new)
  10827. (inherit operator-types type-predicates)
  10828. (define/override (type-check-exp env)
  10829. (lambda (e)
  10830. (define recur (type-check-exp env))
  10831. (match e
  10832. [(Prim 'vector-length (list e1))
  10833. (define-values (e1^ t) (recur e1))
  10834. (match t
  10835. [`(Vector ,ts ...)
  10836. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10837. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10838. [(Prim 'vector-ref (list e1 e2))
  10839. (define-values (e1^ t1) (recur e1))
  10840. (define-values (e2^ t2) (recur e2))
  10841. (check-consistent? t2 'Integer e)
  10842. (match t1
  10843. [`(Vector ,ts ...)
  10844. (match e2^
  10845. [(Int i)
  10846. (unless (and (0 . <= . i) (i . < . (length ts)))
  10847. (error 'type-check "invalid index ~a in ~a" i e))
  10848. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10849. [else (define e1^^ (make-cast e1^ t1 'Any))
  10850. (define e2^^ (make-cast e2^ t2 'Integer))
  10851. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10852. ['Any
  10853. (define e2^^ (make-cast e2^ t2 'Integer))
  10854. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10855. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10856. [(Prim 'vector-set! (list e1 e2 e3) )
  10857. (define-values (e1^ t1) (recur e1))
  10858. (define-values (e2^ t2) (recur e2))
  10859. (define-values (e3^ t3) (recur e3))
  10860. (check-consistent? t2 'Integer e)
  10861. (match t1
  10862. [`(Vector ,ts ...)
  10863. (match e2^
  10864. [(Int i)
  10865. (unless (and (0 . <= . i) (i . < . (length ts)))
  10866. (error 'type-check "invalid index ~a in ~a" i e))
  10867. (check-consistent? (list-ref ts i) t3 e)
  10868. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10869. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10870. [else
  10871. (define e1^^ (make-cast e1^ t1 'Any))
  10872. (define e2^^ (make-cast e2^ t2 'Integer))
  10873. (define e3^^ (make-cast e3^ t3 'Any))
  10874. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10875. ['Any
  10876. (define e2^^ (make-cast e2^ t2 'Integer))
  10877. (define e3^^ (make-cast e3^ t3 'Any))
  10878. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10879. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10880. \end{lstlisting}
  10881. \caption{Type checker for the \LangGrad{} language, part 1.}
  10882. \label{fig:type-check-Rgradual-1}
  10883. \end{figure}
  10884. \begin{figure}[tbp]
  10885. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10886. [(Prim 'eq? (list e1 e2))
  10887. (define-values (e1^ t1) (recur e1))
  10888. (define-values (e2^ t2) (recur e2))
  10889. (check-consistent? t1 t2 e)
  10890. (define T (meet t1 t2))
  10891. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10892. 'Boolean)]
  10893. [(Prim 'not (list e1))
  10894. (define-values (e1^ t1) (recur e1))
  10895. (match t1
  10896. ['Any
  10897. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10898. (Bool #t) (Bool #f)))]
  10899. [else
  10900. (define-values (t-ret new-es^)
  10901. (type-check-op 'not (list t1) (list e1^) e))
  10902. (values (Prim 'not new-es^) t-ret)])]
  10903. [(Prim 'and (list e1 e2))
  10904. (recur (If e1 e2 (Bool #f)))]
  10905. [(Prim 'or (list e1 e2))
  10906. (define tmp (gensym 'tmp))
  10907. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10908. [(Prim op es)
  10909. #:when (not (set-member? explicit-prim-ops op))
  10910. (define-values (new-es ts)
  10911. (for/lists (exprs types) ([e es])
  10912. (recur e)))
  10913. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10914. (values (Prim op new-es^) t-ret)]
  10915. [(If e1 e2 e3)
  10916. (define-values (e1^ T1) (recur e1))
  10917. (define-values (e2^ T2) (recur e2))
  10918. (define-values (e3^ T3) (recur e3))
  10919. (check-consistent? T2 T3 e)
  10920. (match T1
  10921. ['Boolean
  10922. (define Tif (join T2 T3))
  10923. (values (If e1^ (make-cast e2^ T2 Tif)
  10924. (make-cast e3^ T3 Tif)) Tif)]
  10925. ['Any
  10926. (define Tif (meet T2 T3))
  10927. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10928. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10929. Tif)]
  10930. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10931. [(HasType e1 T)
  10932. (define-values (e1^ T1) (recur e1))
  10933. (check-consistent? T1 T)
  10934. (values (make-cast e1^ T1 T) T)]
  10935. [(SetBang x e1)
  10936. (define-values (e1^ T1) (recur e1))
  10937. (define varT (dict-ref env x))
  10938. (check-consistent? T1 varT e)
  10939. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10940. [(WhileLoop e1 e2)
  10941. (define-values (e1^ T1) (recur e1))
  10942. (check-consistent? T1 'Boolean e)
  10943. (define-values (e2^ T2) ((type-check-exp env) e2))
  10944. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10945. \end{lstlisting}
  10946. \caption{Type checker for the \LangGrad{} language, part 2.}
  10947. \label{fig:type-check-Rgradual-2}
  10948. \end{figure}
  10949. \begin{figure}[tbp]
  10950. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10951. [(Apply e1 e2s)
  10952. (define-values (e1^ T1) (recur e1))
  10953. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10954. (match T1
  10955. [`(,T1ps ... -> ,T1rt)
  10956. (for ([T2 T2s] [Tp T1ps])
  10957. (check-consistent? T2 Tp e))
  10958. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10959. (make-cast e2 src tgt)))
  10960. (values (Apply e1^ e2s^^) T1rt)]
  10961. [`Any
  10962. (define e1^^ (make-cast e1^ 'Any
  10963. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10964. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10965. (make-cast e2 src 'Any)))
  10966. (values (Apply e1^^ e2s^^) 'Any)]
  10967. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10968. [(Lambda params Tr e1)
  10969. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10970. (match p
  10971. [`[,x : ,T] (values x T)]
  10972. [(? symbol? x) (values x 'Any)])))
  10973. (define-values (e1^ T1)
  10974. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10975. (check-consistent? Tr T1 e)
  10976. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10977. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10978. [else ((super type-check-exp env) e)]
  10979. )))
  10980. \end{lstlisting}
  10981. \caption{Type checker for the \LangGrad{} language, part 3.}
  10982. \label{fig:type-check-Rgradual-3}
  10983. \end{figure}
  10984. \begin{figure}[tbp]
  10985. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10986. (define/public (join t1 t2)
  10987. (match* (t1 t2)
  10988. [('Integer 'Integer) 'Integer]
  10989. [('Boolean 'Boolean) 'Boolean]
  10990. [('Void 'Void) 'Void]
  10991. [('Any t2) t2]
  10992. [(t1 'Any) t1]
  10993. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10994. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10995. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10996. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10997. -> ,(join rt1 rt2))]))
  10998. (define/public (meet t1 t2)
  10999. (match* (t1 t2)
  11000. [('Integer 'Integer) 'Integer]
  11001. [('Boolean 'Boolean) 'Boolean]
  11002. [('Void 'Void) 'Void]
  11003. [('Any t2) 'Any]
  11004. [(t1 'Any) 'Any]
  11005. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11006. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11007. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11008. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11009. -> ,(meet rt1 rt2))]))
  11010. (define/public (make-cast e src tgt)
  11011. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11012. (define/public (check-consistent? t1 t2 e)
  11013. (unless (consistent? t1 t2)
  11014. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11015. (define/override (type-check-op op arg-types args e)
  11016. (match (dict-ref (operator-types) op)
  11017. [`(,param-types . ,return-type)
  11018. (for ([at arg-types] [pt param-types])
  11019. (check-consistent? at pt e))
  11020. (values return-type
  11021. (for/list ([e args] [s arg-types] [t param-types])
  11022. (make-cast e s t)))]
  11023. [else (error 'type-check-op "unrecognized ~a" op)]))
  11024. (define explicit-prim-ops
  11025. (set-union
  11026. (type-predicates)
  11027. (set 'procedure-arity 'eq?
  11028. 'vector 'vector-length 'vector-ref 'vector-set!
  11029. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11030. (define/override (fun-def-type d)
  11031. (match d
  11032. [(Def f params rt info body)
  11033. (define ps
  11034. (for/list ([p params])
  11035. (match p
  11036. [`[,x : ,T] T]
  11037. [(? symbol?) 'Any]
  11038. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11039. `(,@ps -> ,rt)]
  11040. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11041. \end{lstlisting}
  11042. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11043. \label{fig:type-check-Rgradual-aux}
  11044. \end{figure}
  11045. \clearpage
  11046. \section{Interpreting \LangCast{}}
  11047. \label{sec:interp-casts}
  11048. The runtime behavior of first-order casts is straightforward, that is,
  11049. casts involving simple types such as \code{Integer} and
  11050. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11051. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11052. puts the integer into a tagged value
  11053. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11054. \code{Integer} is accomplished with the \code{Project} operator, that
  11055. is, by checking the value's tag and either retrieving the underlying
  11056. integer or signaling an error if it the tag is not the one for
  11057. integers (Figure~\ref{fig:apply-project}).
  11058. %
  11059. Things get more interesting for higher-order casts, that is, casts
  11060. involving function or vector types.
  11061. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11062. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11063. this cast at runtime, we can't know in general whether the function
  11064. will always return an integer.\footnote{Predicting the return value of
  11065. a function is equivalent to the halting problem, which is
  11066. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11067. of the cast until the function is applied. This is accomplished by
  11068. wrapping \code{maybe-add1} in a new function that casts its parameter
  11069. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11070. casts the return value from \code{Any} to \code{Integer}.
  11071. Turning our attention to casts involving vector types, we consider the
  11072. example in Figure~\ref{fig:map-vec-bang} that defines a
  11073. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11074. type \code{(Vector Any Any)} and that updates \code{v} in place
  11075. instead of returning a new vector. So we name this function
  11076. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11077. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11078. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11079. cast between vector types would be a build a new vector whose elements
  11080. are the result of casting each of the original elements to the
  11081. appropriate target type. However, this approach is only valid for
  11082. immutable vectors; and our vectors are mutable. In the example of
  11083. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11084. the updates inside of \code{map-vec!} would happen to the new vector
  11085. and not the original one.
  11086. \begin{figure}[tbp]
  11087. % gradual_test_11.rkt
  11088. \begin{lstlisting}
  11089. (define (map-vec! [f : (Any -> Any)]
  11090. [v : (Vector Any Any)]) : Void
  11091. (begin
  11092. (vector-set! v 0 (f (vector-ref v 0)))
  11093. (vector-set! v 1 (f (vector-ref v 1)))))
  11094. (define (add1 x) (+ x 1))
  11095. (let ([v (vector 0 41)])
  11096. (begin (map-vec! add1 v) (vector-ref v 1)))
  11097. \end{lstlisting}
  11098. \caption{An example involving casts on vectors.}
  11099. \label{fig:map-vec-bang}
  11100. \end{figure}
  11101. Instead the interpreter needs to create a new kind of value, a
  11102. \emph{vector proxy}, that intercepts every vector operation. On a
  11103. read, the proxy reads from the underlying vector and then applies a
  11104. cast to the resulting value. On a write, the proxy casts the argument
  11105. value and then performs the write to the underlying vector. For the
  11106. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11107. \code{0} from \code{Integer} to \code{Any}. For the first
  11108. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11109. to \code{Integer}.
  11110. The final category of cast that we need to consider are casts between
  11111. the \code{Any} type and either a function or a vector
  11112. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11113. in which parameter \code{v} does not have a type annotation, so it is
  11114. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11115. type \code{(Vector Integer Integer)} so the type checker inserts a
  11116. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11117. thought is to use \code{Inject}, but that doesn't work because
  11118. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11119. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11120. to \code{Any}.
  11121. \begin{figure}[tbp]
  11122. \begin{lstlisting}
  11123. (define (map-vec! [f : (Any -> Any)] v) : Void
  11124. (begin
  11125. (vector-set! v 0 (f (vector-ref v 0)))
  11126. (vector-set! v 1 (f (vector-ref v 1)))))
  11127. (define (add1 x) (+ x 1))
  11128. (let ([v (vector 0 41)])
  11129. (begin (map-vec! add1 v) (vector-ref v 1)))
  11130. \end{lstlisting}
  11131. \caption{Casting a vector to \code{Any}.}
  11132. \label{fig:map-vec-any}
  11133. \end{figure}
  11134. The \LangCast{} interpreter uses an auxiliary function named
  11135. \code{apply-cast} to cast a value from a source type to a target type,
  11136. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11137. of the kinds of casts that we've discussed in this section.
  11138. \begin{figure}[tbp]
  11139. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11140. (define/public (apply-cast v s t)
  11141. (match* (s t)
  11142. [(t1 t2) #:when (equal? t1 t2) v]
  11143. [('Any t2)
  11144. (match t2
  11145. [`(,ts ... -> ,rt)
  11146. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11147. (define v^ (apply-project v any->any))
  11148. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11149. [`(Vector ,ts ...)
  11150. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11151. (define v^ (apply-project v vec-any))
  11152. (apply-cast v^ vec-any `(Vector ,@ts))]
  11153. [else (apply-project v t2)])]
  11154. [(t1 'Any)
  11155. (match t1
  11156. [`(,ts ... -> ,rt)
  11157. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11158. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11159. (apply-inject v^ (any-tag any->any))]
  11160. [`(Vector ,ts ...)
  11161. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11162. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11163. (apply-inject v^ (any-tag vec-any))]
  11164. [else (apply-inject v (any-tag t1))])]
  11165. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11166. (define x (gensym 'x))
  11167. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11168. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11169. (define cast-writes
  11170. (for/list ([t1 ts1] [t2 ts2])
  11171. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11172. `(vector-proxy ,(vector v (apply vector cast-reads)
  11173. (apply vector cast-writes)))]
  11174. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11175. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11176. `(function ,xs ,(Cast
  11177. (Apply (Value v)
  11178. (for/list ([x xs][t1 ts1][t2 ts2])
  11179. (Cast (Var x) t2 t1)))
  11180. rt1 rt2) ())]
  11181. ))
  11182. \end{lstlisting}
  11183. \caption{The \code{apply-cast} auxiliary method.}
  11184. \label{fig:apply-cast}
  11185. \end{figure}
  11186. The interpreter for \LangCast{} is defined in
  11187. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11188. dispatching to \code{apply-cast}. To handle the addition of vector
  11189. proxies, we update the vector primitives in \code{interp-op} using the
  11190. functions in Figure~\ref{fig:guarded-vector}.
  11191. \begin{figure}[tbp]
  11192. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11193. (define interp-Rcast-class
  11194. (class interp-Rwhile-class
  11195. (super-new)
  11196. (inherit apply-fun apply-inject apply-project)
  11197. (define/override (interp-op op)
  11198. (match op
  11199. ['vector-length guarded-vector-length]
  11200. ['vector-ref guarded-vector-ref]
  11201. ['vector-set! guarded-vector-set!]
  11202. ['any-vector-ref (lambda (v i)
  11203. (match v [`(tagged ,v^ ,tg)
  11204. (guarded-vector-ref v^ i)]))]
  11205. ['any-vector-set! (lambda (v i a)
  11206. (match v [`(tagged ,v^ ,tg)
  11207. (guarded-vector-set! v^ i a)]))]
  11208. ['any-vector-length (lambda (v)
  11209. (match v [`(tagged ,v^ ,tg)
  11210. (guarded-vector-length v^)]))]
  11211. [else (super interp-op op)]
  11212. ))
  11213. (define/override ((interp-exp env) e)
  11214. (define (recur e) ((interp-exp env) e))
  11215. (match e
  11216. [(Value v) v]
  11217. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11218. [else ((super interp-exp env) e)]))
  11219. ))
  11220. (define (interp-Rcast p)
  11221. (send (new interp-Rcast-class) interp-program p))
  11222. \end{lstlisting}
  11223. \caption{The interpreter for \LangCast{}.}
  11224. \label{fig:interp-Rcast}
  11225. \end{figure}
  11226. \begin{figure}[tbp]
  11227. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11228. (define (guarded-vector-ref vec i)
  11229. (match vec
  11230. [`(vector-proxy ,proxy)
  11231. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11232. (define rd (vector-ref (vector-ref proxy 1) i))
  11233. (apply-fun rd (list val) 'guarded-vector-ref)]
  11234. [else (vector-ref vec i)]))
  11235. (define (guarded-vector-set! vec i arg)
  11236. (match vec
  11237. [`(vector-proxy ,proxy)
  11238. (define wr (vector-ref (vector-ref proxy 2) i))
  11239. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11240. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11241. [else (vector-set! vec i arg)]))
  11242. (define (guarded-vector-length vec)
  11243. (match vec
  11244. [`(vector-proxy ,proxy)
  11245. (guarded-vector-length (vector-ref proxy 0))]
  11246. [else (vector-length vec)]))
  11247. \end{lstlisting}
  11248. \caption{The guarded-vector auxiliary functions.}
  11249. \label{fig:guarded-vector}
  11250. \end{figure}
  11251. \section{Lower Casts}
  11252. \label{sec:lower-casts}
  11253. The next step in the journey towards x86 is the \code{lower-casts}
  11254. pass that translates the casts in \LangCast{} to the lower-level
  11255. \code{Inject} and \code{Project} operators and a new operator for
  11256. creating vector proxies, extending the \LangLoop{} language to create
  11257. \LangProxy{}. We recommend creating an auxiliary function named
  11258. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11259. and a target type, and translates it to expression in \LangProxy{} that has
  11260. the same behavior as casting the expression from the source to the
  11261. target type in the interpreter.
  11262. The \code{lower-cast} function can follow a code structure similar to
  11263. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11264. the interpreter for \LangCast{} because it must handle the same cases as
  11265. \code{apply-cast} and it needs to mimic the behavior of
  11266. \code{apply-cast}. The most interesting cases are those concerning the
  11267. casts between two vector types and between two function types.
  11268. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11269. type to another vector type is accomplished by creating a proxy that
  11270. intercepts the operations on the underlying vector. Here we make the
  11271. creation of the proxy explicit with the \code{vector-proxy} primitive
  11272. operation. It takes three arguments, the first is an expression for
  11273. the vector, the second is a vector of functions for casting an element
  11274. that is being read from the vector, and the third is a vector of
  11275. functions for casting an element that is being written to the vector.
  11276. You can create the functions using \code{Lambda}. Also, as we shall
  11277. see in the next section, we need to differentiate these vectors from
  11278. the user-created ones, so we recommend using a new primitive operator
  11279. named \code{raw-vector} instead of \code{vector} to create these
  11280. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11281. the output of \code{lower-casts} on the example in
  11282. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11283. integers to a vector of \code{Any}.
  11284. \begin{figure}[tbp]
  11285. \begin{lstlisting}
  11286. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11287. (begin
  11288. (vector-set! v 0 (f (vector-ref v 0)))
  11289. (vector-set! v 1 (f (vector-ref v 1)))))
  11290. (define (add1 [x : Any]) : Any
  11291. (inject (+ (project x Integer) 1) Integer))
  11292. (let ([v (vector 0 41)])
  11293. (begin
  11294. (map-vec! add1 (vector-proxy v
  11295. (raw-vector (lambda: ([x9 : Integer]) : Any
  11296. (inject x9 Integer))
  11297. (lambda: ([x9 : Integer]) : Any
  11298. (inject x9 Integer)))
  11299. (raw-vector (lambda: ([x9 : Any]) : Integer
  11300. (project x9 Integer))
  11301. (lambda: ([x9 : Any]) : Integer
  11302. (project x9 Integer)))))
  11303. (vector-ref v 1)))
  11304. \end{lstlisting}
  11305. \caption{Output of \code{lower-casts} on the example in
  11306. Figure~\ref{fig:map-vec-bang}.}
  11307. \label{fig:map-vec-bang-lower-cast}
  11308. \end{figure}
  11309. A cast from one function type to another function type is accomplished
  11310. by generating a \code{Lambda} whose parameter and return types match
  11311. the target function type. The body of the \code{Lambda} should cast
  11312. the parameters from the target type to the source type (yes,
  11313. backwards! functions are contravariant\index{subject}{contravariant} in the
  11314. parameters), then call the underlying function, and finally cast the
  11315. result from the source return type to the target return type.
  11316. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11317. \code{lower-casts} pass on the \code{map-vec} example in
  11318. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11319. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11320. \begin{figure}[tbp]
  11321. \begin{lstlisting}
  11322. (define (map-vec [f : (Integer -> Integer)]
  11323. [v : (Vector Integer Integer)])
  11324. : (Vector Integer Integer)
  11325. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11326. (define (add1 [x : Any]) : Any
  11327. (inject (+ (project x Integer) 1) Integer))
  11328. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11329. (project (add1 (inject x9 Integer)) Integer))
  11330. (vector 0 41)) 1)
  11331. \end{lstlisting}
  11332. \caption{Output of \code{lower-casts} on the example in
  11333. Figure~\ref{fig:gradual-map-vec}.}
  11334. \label{fig:map-vec-lower-cast}
  11335. \end{figure}
  11336. \section{Differentiate Proxies}
  11337. \label{sec:differentiate-proxies}
  11338. So far the job of differentiating vectors and vector proxies has been
  11339. the job of the interpreter. For example, the interpreter for \LangCast{}
  11340. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11341. function in Figure~\ref{fig:guarded-vector}. In the
  11342. \code{differentiate-proxies} pass we shift this responsibility to the
  11343. generated code.
  11344. We begin by designing the output language $R^p_8$. In
  11345. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11346. proxies. In $R^p_8$ we return the \code{Vector} type to
  11347. its original meaning, as the type of real vectors, and we introduce a
  11348. new type, \code{PVector}, whose values can be either real vectors or
  11349. vector proxies. This new type comes with a suite of new primitive
  11350. operations for creating and using values of type \code{PVector}. We
  11351. don't need to introduce a new type to represent vector proxies. A
  11352. proxy is represented by a vector containing three things: 1) the
  11353. underlying vector, 2) a vector of functions for casting elements that
  11354. are read from the vector, and 3) a vector of functions for casting
  11355. values to be written to the vector. So we define the following
  11356. abbreviation for the type of a vector proxy:
  11357. \[
  11358. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11359. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11360. \to (\key{PVector}~ T' \ldots)
  11361. \]
  11362. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11363. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11364. %
  11365. Next we describe each of the new primitive operations.
  11366. \begin{description}
  11367. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11368. (\key{PVector} $T \ldots$)]\ \\
  11369. %
  11370. This operation brands a vector as a value of the \code{PVector} type.
  11371. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11372. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11373. %
  11374. This operation brands a vector proxy as value of the \code{PVector} type.
  11375. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11376. \code{Boolean}] \ \\
  11377. %
  11378. returns true if the value is a vector proxy and false if it is a
  11379. real vector.
  11380. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11381. (\key{Vector} $T \ldots$)]\ \\
  11382. %
  11383. Assuming that the input is a vector (and not a proxy), this
  11384. operation returns the vector.
  11385. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11386. $\to$ \code{Boolean}]\ \\
  11387. %
  11388. Given a vector proxy, this operation returns the length of the
  11389. underlying vector.
  11390. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11391. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11392. %
  11393. Given a vector proxy, this operation returns the $i$th element of
  11394. the underlying vector.
  11395. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11396. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11397. proxy, this operation writes a value to the $i$th element of the
  11398. underlying vector.
  11399. \end{description}
  11400. Now to discuss the translation that differentiates vectors from
  11401. proxies. First, every type annotation in the program must be
  11402. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11403. Next, we must insert uses of \code{PVector} operations in the
  11404. appropriate places. For example, we wrap every vector creation with an
  11405. \code{inject-vector}.
  11406. \begin{lstlisting}
  11407. (vector |$e_1 \ldots e_n$|)
  11408. |$\Rightarrow$|
  11409. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11410. \end{lstlisting}
  11411. The \code{raw-vector} operator that we introduced in the previous
  11412. section does not get injected.
  11413. \begin{lstlisting}
  11414. (raw-vector |$e_1 \ldots e_n$|)
  11415. |$\Rightarrow$|
  11416. (vector |$e'_1 \ldots e'_n$|)
  11417. \end{lstlisting}
  11418. The \code{vector-proxy} primitive translates as follows.
  11419. \begin{lstlisting}
  11420. (vector-proxy |$e_1~e_2~e_3$|)
  11421. |$\Rightarrow$|
  11422. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11423. \end{lstlisting}
  11424. We translate the vector operations into conditional expressions that
  11425. check whether the value is a proxy and then dispatch to either the
  11426. appropriate proxy vector operation or the regular vector operation.
  11427. For example, the following is the translation for \code{vector-ref}.
  11428. \begin{lstlisting}
  11429. (vector-ref |$e_1$| |$i$|)
  11430. |$\Rightarrow$|
  11431. (let ([|$v~e_1$|])
  11432. (if (proxy? |$v$|)
  11433. (proxy-vector-ref |$v$| |$i$|)
  11434. (vector-ref (project-vector |$v$|) |$i$|)
  11435. \end{lstlisting}
  11436. Note in the case of a real vector, we must apply \code{project-vector}
  11437. before the \code{vector-ref}.
  11438. \section{Reveal Casts}
  11439. \label{sec:reveal-casts-gradual}
  11440. Recall that the \code{reveal-casts} pass
  11441. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11442. \code{Inject} and \code{Project} into lower-level operations. In
  11443. particular, \code{Project} turns into a conditional expression that
  11444. inspects the tag and retrieves the underlying value. Here we need to
  11445. augment the translation of \code{Project} to handle the situation when
  11446. the target type is \code{PVector}. Instead of using
  11447. \code{vector-length} we need to use \code{proxy-vector-length}.
  11448. \begin{lstlisting}
  11449. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11450. |$\Rightarrow$|
  11451. (let |$\itm{tmp}$| |$e'$|
  11452. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11453. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11454. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11455. (exit)))
  11456. \end{lstlisting}
  11457. \section{Closure Conversion}
  11458. \label{sec:closure-conversion-gradual}
  11459. The closure conversion pass only requires one minor adjustment. The
  11460. auxiliary function that translates type annotations needs to be
  11461. updated to handle the \code{PVector} type.
  11462. \section{Explicate Control}
  11463. \label{sec:explicate-control-gradual}
  11464. Update the \code{explicate-control} pass to handle the new primitive
  11465. operations on the \code{PVector} type.
  11466. \section{Select Instructions}
  11467. \label{sec:select-instructions-gradual}
  11468. Recall that the \code{select-instructions} pass is responsible for
  11469. lowering the primitive operations into x86 instructions. So we need
  11470. to translate the new \code{PVector} operations to x86. To do so, the
  11471. first question we need to answer is how will we differentiate the two
  11472. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11473. We need just one bit to accomplish this, and use the bit in position
  11474. $57$ of the 64-bit tag at the front of every vector (see
  11475. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11476. for \code{inject-vector} we leave it that way.
  11477. \begin{lstlisting}
  11478. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11479. |$\Rightarrow$|
  11480. movq |$e'_1$|, |$\itm{lhs'}$|
  11481. \end{lstlisting}
  11482. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11483. \begin{lstlisting}
  11484. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11485. |$\Rightarrow$|
  11486. movq |$e'_1$|, %r11
  11487. movq |$(1 << 57)$|, %rax
  11488. orq 0(%r11), %rax
  11489. movq %rax, 0(%r11)
  11490. movq %r11, |$\itm{lhs'}$|
  11491. \end{lstlisting}
  11492. The \code{proxy?} operation consumes the information so carefully
  11493. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11494. isolates the $57$th bit to tell whether the value is a real vector or
  11495. a proxy.
  11496. \begin{lstlisting}
  11497. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11498. |$\Rightarrow$|
  11499. movq |$e_1'$|, %r11
  11500. movq 0(%r11), %rax
  11501. sarq $57, %rax
  11502. andq $1, %rax
  11503. movq %rax, |$\itm{lhs'}$|
  11504. \end{lstlisting}
  11505. The \code{project-vector} operation is straightforward to translate,
  11506. so we leave it up to the reader.
  11507. Regarding the \code{proxy-vector} operations, the runtime provides
  11508. procedures that implement them (they are recursive functions!) so
  11509. here we simply need to translate these vector operations into the
  11510. appropriate function call. For example, here is the translation for
  11511. \code{proxy-vector-ref}.
  11512. \begin{lstlisting}
  11513. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11514. |$\Rightarrow$|
  11515. movq |$e_1'$|, %rdi
  11516. movq |$e_2'$|, %rsi
  11517. callq proxy_vector_ref
  11518. movq %rax, |$\itm{lhs'}$|
  11519. \end{lstlisting}
  11520. We have another batch of vector operations to deal with, those for the
  11521. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11522. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11523. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11524. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11525. Section~\ref{sec:select-Rany} we selected instructions for these
  11526. operations based on the idea that the underlying value was a real
  11527. vector. But in the current setting, the underlying value is of type
  11528. \code{PVector}. So \code{any-vector-ref} can be translates to
  11529. pseudo-x86 as follows. We begin by projecting the underlying value out
  11530. of the tagged value and then call the \code{proxy\_vector\_ref}
  11531. procedure in the runtime.
  11532. \begin{lstlisting}
  11533. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11534. movq |$\neg 111$|, %rdi
  11535. andq |$e_1'$|, %rdi
  11536. movq |$e_2'$|, %rsi
  11537. callq proxy_vector_ref
  11538. movq %rax, |$\itm{lhs'}$|
  11539. \end{lstlisting}
  11540. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11541. be translated in a similar way.
  11542. \begin{exercise}\normalfont
  11543. Implement a compiler for the gradually-typed \LangGrad{} language by
  11544. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11545. partially-typed test programs. In addition to testing with these
  11546. new programs, also test your compiler on all the tests for \LangLoop{}
  11547. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11548. on the \LangDyn{} programs but you can adapt them by inserting
  11549. a cast to the \code{Any} type around each subexpression
  11550. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11551. you can induce one by wrapping the subexpression \code{e}
  11552. with a call to an un-annotated identity function, like this:
  11553. \code{((lambda (x) x) e)}.
  11554. \end{exercise}
  11555. \begin{figure}[p]
  11556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11557. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11558. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11559. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11560. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11561. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11562. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11563. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11564. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11565. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11566. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11567. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11568. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11569. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11570. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11571. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11572. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11573. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11574. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11575. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11576. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11577. \path[->,bend right=15] (Rgradual) edge [above] node
  11578. {\ttfamily\footnotesize type-check} (Rgradualp);
  11579. \path[->,bend right=15] (Rgradualp) edge [above] node
  11580. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11581. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11582. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11583. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11584. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11585. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11586. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11587. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11588. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11589. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11590. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11591. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11592. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11593. \path[->,bend left=15] (F1-1) edge [below] node
  11594. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11595. \path[->,bend right=15] (F1-2) edge [above] node
  11596. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11597. \path[->,bend right=15] (F1-3) edge [above] node
  11598. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11599. \path[->,bend right=15] (F1-4) edge [above] node
  11600. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11601. \path[->,bend right=15] (F1-5) edge [right] node
  11602. {\ttfamily\footnotesize explicate-control} (C3-2);
  11603. \path[->,bend left=15] (C3-2) edge [left] node
  11604. {\ttfamily\footnotesize select-instr.} (x86-2);
  11605. \path[->,bend right=15] (x86-2) edge [left] node
  11606. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11607. \path[->,bend right=15] (x86-2-1) edge [below] node
  11608. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11609. \path[->,bend right=15] (x86-2-2) edge [left] node
  11610. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11611. \path[->,bend left=15] (x86-3) edge [above] node
  11612. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11613. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11614. \end{tikzpicture}
  11615. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11616. \label{fig:Rgradual-passes}
  11617. \end{figure}
  11618. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11619. for the compilation of \LangGrad{}.
  11620. \section{Further Reading}
  11621. This chapter just scratches the surface of gradual typing. The basic
  11622. approach described here is missing two key ingredients that one would
  11623. want in a implementation of gradual typing: blame
  11624. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11625. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11626. problem addressed by blame tracking is that when a cast on a
  11627. higher-order value fails, it often does so at a point in the program
  11628. that is far removed from the original cast. Blame tracking is a
  11629. technique for propagating extra information through casts and proxies
  11630. so that when a cast fails, the error message can point back to the
  11631. original location of the cast in the source program.
  11632. The problem addressed by space-efficient casts also relates to
  11633. higher-order casts. It turns out that in partially typed programs, a
  11634. function or vector can flow through very-many casts at runtime. With
  11635. the approach described in this chapter, each cast adds another
  11636. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11637. considerable space, but it also makes the function calls and vector
  11638. operations slow. For example, a partially-typed version of quicksort
  11639. could, in the worst case, build a chain of proxies of length $O(n)$
  11640. around the vector, changing the overall time complexity of the
  11641. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11642. solution to this problem by representing casts using the coercion
  11643. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11644. long chains of proxies by compressing them into a concise normal
  11645. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11646. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11647. the Grift compiler.
  11648. \begin{center}
  11649. \url{https://github.com/Gradual-Typing/Grift}
  11650. \end{center}
  11651. There are also interesting interactions between gradual typing and
  11652. other language features, such as parametetric polymorphism,
  11653. information-flow types, and type inference, to name a few. We
  11654. recommend the reader to the online gradual typing bibliography:
  11655. \begin{center}
  11656. \url{http://samth.github.io/gradual-typing-bib/}
  11657. \end{center}
  11658. % TODO: challenge problem:
  11659. % type analysis and type specialization?
  11660. % coercions?
  11661. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11662. \chapter{Parametric Polymorphism}
  11663. \label{ch:Rpoly}
  11664. \index{subject}{parametric polymorphism}
  11665. \index{subject}{generics}
  11666. This chapter studies the compilation of parametric
  11667. polymorphism\index{subject}{parametric polymorphism}
  11668. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  11669. Racket. Parametric polymorphism enables improved code reuse by
  11670. parameterizing functions and data structures with respect to the types
  11671. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11672. revisits the \code{map-vec} example but this time gives it a more
  11673. fitting type. This \code{map-vec} function is parameterized with
  11674. respect to the element type of the vector. The type of \code{map-vec}
  11675. is the following polymorphic type as specified by the \code{All} and
  11676. the type parameter \code{a}.
  11677. \begin{lstlisting}
  11678. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11679. \end{lstlisting}
  11680. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11681. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11682. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11683. \code{a}, but we could have just as well applied \code{map-vec} to a
  11684. vector of Booleans (and a function on Booleans).
  11685. \begin{figure}[tbp]
  11686. % poly_test_2.rkt
  11687. \begin{lstlisting}
  11688. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11689. (define (map-vec f v)
  11690. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11691. (define (add1 [x : Integer]) : Integer (+ x 1))
  11692. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11693. \end{lstlisting}
  11694. \caption{The \code{map-vec} example using parametric polymorphism.}
  11695. \label{fig:map-vec-poly}
  11696. \end{figure}
  11697. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11698. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11699. syntax. We add a second form for function definitions in which a type
  11700. declaration comes before the \code{define}. In the abstract syntax,
  11701. the return type in the \code{Def} is \code{Any}, but that should be
  11702. ignored in favor of the return type in the type declaration. (The
  11703. \code{Any} comes from using the same parser as in
  11704. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11705. enables the use of an \code{All} type for a function, thereby making
  11706. it polymorphic. The grammar for types is extended to include
  11707. polymorphic types and type variables.
  11708. \begin{figure}[tp]
  11709. \centering
  11710. \fbox{
  11711. \begin{minipage}{0.96\textwidth}
  11712. \small
  11713. \[
  11714. \begin{array}{lcl}
  11715. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11716. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11717. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11718. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11719. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11720. \end{array}
  11721. \]
  11722. \end{minipage}
  11723. }
  11724. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11725. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11726. \label{fig:Rpoly-concrete-syntax}
  11727. \end{figure}
  11728. \begin{figure}[tp]
  11729. \centering
  11730. \fbox{
  11731. \begin{minipage}{0.96\textwidth}
  11732. \small
  11733. \[
  11734. \begin{array}{lcl}
  11735. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11736. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11737. &\mid& \DECL{\Var}{\Type} \\
  11738. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11739. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11740. \end{array}
  11741. \]
  11742. \end{minipage}
  11743. }
  11744. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11745. (Figure~\ref{fig:Rwhile-syntax}).}
  11746. \label{fig:Rpoly-syntax}
  11747. \end{figure}
  11748. By including polymorphic types in the $\Type$ non-terminal we choose
  11749. to make them first-class which has interesting repercussions on the
  11750. compiler. Many languages with polymorphism, such as
  11751. C++~\citep{stroustrup88:_param_types} and Standard
  11752. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11753. it is useful to see an example of first-class polymorphism. In
  11754. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11755. whose parameter is a polymorphic function. The occurrence of a
  11756. polymorphic type underneath a function type is enabled by the normal
  11757. recursive structure of the grammar for $\Type$ and the categorization
  11758. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11759. applies the polymorphic function to a Boolean and to an integer.
  11760. \begin{figure}[tbp]
  11761. \begin{lstlisting}
  11762. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11763. (define (apply-twice f)
  11764. (if (f #t) (f 42) (f 777)))
  11765. (: id (All (a) (a -> a)))
  11766. (define (id x) x)
  11767. (apply-twice id)
  11768. \end{lstlisting}
  11769. \caption{An example illustrating first-class polymorphism.}
  11770. \label{fig:apply-twice}
  11771. \end{figure}
  11772. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11773. three new responsibilities (compared to \LangLoop{}). The type checking of
  11774. function application is extended to handle the case where the operator
  11775. expression is a polymorphic function. In that case the type arguments
  11776. are deduced by matching the type of the parameters with the types of
  11777. the arguments.
  11778. %
  11779. The \code{match-types} auxiliary function carries out this deduction
  11780. by recursively descending through a parameter type \code{pt} and the
  11781. corresponding argument type \code{at}, making sure that they are equal
  11782. except when there is a type parameter on the left (in the parameter
  11783. type). If it's the first time that the type parameter has been
  11784. encountered, then the algorithm deduces an association of the type
  11785. parameter to the corresponding type on the right (in the argument
  11786. type). If it's not the first time that the type parameter has been
  11787. encountered, the algorithm looks up its deduced type and makes sure
  11788. that it is equal to the type on the right.
  11789. %
  11790. Once the type arguments are deduced, the operator expression is
  11791. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11792. type of the operator, but more importantly, records the deduced type
  11793. arguments. The return type of the application is the return type of
  11794. the polymorphic function, but with the type parameters replaced by the
  11795. deduced type arguments, using the \code{subst-type} function.
  11796. The second responsibility of the type checker is extending the
  11797. function \code{type-equal?} to handle the \code{All} type. This is
  11798. not quite a simple as equal on other types, such as function and
  11799. vector types, because two polymorphic types can be syntactically
  11800. different even though they are equivalent types. For example,
  11801. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11802. Two polymorphic types should be considered equal if they differ only
  11803. in the choice of the names of the type parameters. The
  11804. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11805. renames the type parameters of the first type to match the type
  11806. parameters of the second type.
  11807. The third responsibility of the type checker is making sure that only
  11808. defined type variables appear in type annotations. The
  11809. \code{check-well-formed} function defined in
  11810. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11811. sure that each type variable has been defined.
  11812. The output language of the type checker is \LangInst{}, defined in
  11813. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11814. declaration and polymorphic function into a single definition, using
  11815. the \code{Poly} form, to make polymorphic functions more convenient to
  11816. process in next pass of the compiler.
  11817. \begin{figure}[tp]
  11818. \centering
  11819. \fbox{
  11820. \begin{minipage}{0.96\textwidth}
  11821. \small
  11822. \[
  11823. \begin{array}{lcl}
  11824. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11825. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11826. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11827. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11828. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11829. \end{array}
  11830. \]
  11831. \end{minipage}
  11832. }
  11833. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11834. (Figure~\ref{fig:Rwhile-syntax}).}
  11835. \label{fig:Rpoly-prime-syntax}
  11836. \end{figure}
  11837. The output of the type checker on the polymorphic \code{map-vec}
  11838. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11839. \begin{figure}[tbp]
  11840. % poly_test_2.rkt
  11841. \begin{lstlisting}
  11842. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11843. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11844. (define (add1 [x : Integer]) : Integer (+ x 1))
  11845. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11846. (Integer))
  11847. add1 (vector 0 41)) 1)
  11848. \end{lstlisting}
  11849. \caption{Output of the type checker on the \code{map-vec} example.}
  11850. \label{fig:map-vec-type-check}
  11851. \end{figure}
  11852. \begin{figure}[tbp]
  11853. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11854. (define type-check-poly-class
  11855. (class type-check-Rwhile-class
  11856. (super-new)
  11857. (inherit check-type-equal?)
  11858. (define/override (type-check-apply env e1 es)
  11859. (define-values (e^ ty) ((type-check-exp env) e1))
  11860. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11861. ((type-check-exp env) e)))
  11862. (match ty
  11863. [`(,ty^* ... -> ,rt)
  11864. (for ([arg-ty ty*] [param-ty ty^*])
  11865. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11866. (values e^ es^ rt)]
  11867. [`(All ,xs (,tys ... -> ,rt))
  11868. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11869. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11870. (match-types env^^ param-ty arg-ty)))
  11871. (define targs
  11872. (for/list ([x xs])
  11873. (match (dict-ref env^^ x (lambda () #f))
  11874. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11875. x (Apply e1 es))]
  11876. [ty ty])))
  11877. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11878. [else (error 'type-check "expected a function, not ~a" ty)]))
  11879. (define/override ((type-check-exp env) e)
  11880. (match e
  11881. [(Lambda `([,xs : ,Ts] ...) rT body)
  11882. (for ([T Ts]) ((check-well-formed env) T))
  11883. ((check-well-formed env) rT)
  11884. ((super type-check-exp env) e)]
  11885. [(HasType e1 ty)
  11886. ((check-well-formed env) ty)
  11887. ((super type-check-exp env) e)]
  11888. [else ((super type-check-exp env) e)]))
  11889. (define/override ((type-check-def env) d)
  11890. (verbose 'type-check "poly/def" d)
  11891. (match d
  11892. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11893. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11894. (for ([p ps]) ((check-well-formed ts-env) p))
  11895. ((check-well-formed ts-env) rt)
  11896. (define new-env (append ts-env (map cons xs ps) env))
  11897. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11898. (check-type-equal? ty^ rt body)
  11899. (Generic ts (Def f p:t* rt info body^))]
  11900. [else ((super type-check-def env) d)]))
  11901. (define/override (type-check-program p)
  11902. (match p
  11903. [(Program info body)
  11904. (type-check-program (ProgramDefsExp info '() body))]
  11905. [(ProgramDefsExp info ds body)
  11906. (define ds^ (combine-decls-defs ds))
  11907. (define new-env (for/list ([d ds^])
  11908. (cons (def-name d) (fun-def-type d))))
  11909. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11910. (define-values (body^ ty) ((type-check-exp new-env) body))
  11911. (check-type-equal? ty 'Integer body)
  11912. (ProgramDefsExp info ds^^ body^)]))
  11913. ))
  11914. \end{lstlisting}
  11915. \caption{Type checker for the \LangPoly{} language.}
  11916. \label{fig:type-check-Rvar0}
  11917. \end{figure}
  11918. \begin{figure}[tbp]
  11919. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11920. (define/override (type-equal? t1 t2)
  11921. (match* (t1 t2)
  11922. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11923. (define env (map cons xs ys))
  11924. (type-equal? (subst-type env T1) T2)]
  11925. [(other wise)
  11926. (super type-equal? t1 t2)]))
  11927. (define/public (match-types env pt at)
  11928. (match* (pt at)
  11929. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11930. [('Void 'Void) env] [('Any 'Any) env]
  11931. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11932. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11933. (match-types env^ pt1 at1))]
  11934. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11935. (define env^ (match-types env prt art))
  11936. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11937. (match-types env^^ pt1 at1))]
  11938. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11939. (define env^ (append (map cons pxs axs) env))
  11940. (match-types env^ pt1 at1)]
  11941. [((? symbol? x) at)
  11942. (match (dict-ref env x (lambda () #f))
  11943. [#f (error 'type-check "undefined type variable ~a" x)]
  11944. ['Type (cons (cons x at) env)]
  11945. [t^ (check-type-equal? at t^ 'matching) env])]
  11946. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11947. (define/public (subst-type env pt)
  11948. (match pt
  11949. ['Integer 'Integer] ['Boolean 'Boolean]
  11950. ['Void 'Void] ['Any 'Any]
  11951. [`(Vector ,ts ...)
  11952. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11953. [`(,ts ... -> ,rt)
  11954. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11955. [`(All ,xs ,t)
  11956. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11957. [(? symbol? x) (dict-ref env x)]
  11958. [else (error 'type-check "expected a type not ~a" pt)]))
  11959. (define/public (combine-decls-defs ds)
  11960. (match ds
  11961. ['() '()]
  11962. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11963. (unless (equal? name f)
  11964. (error 'type-check "name mismatch, ~a != ~a" name f))
  11965. (match type
  11966. [`(All ,xs (,ps ... -> ,rt))
  11967. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11968. (cons (Generic xs (Def name params^ rt info body))
  11969. (combine-decls-defs ds^))]
  11970. [`(,ps ... -> ,rt)
  11971. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11972. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11973. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11974. [`(,(Def f params rt info body) . ,ds^)
  11975. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11976. \end{lstlisting}
  11977. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11978. \label{fig:type-check-Rvar0-aux}
  11979. \end{figure}
  11980. \begin{figure}[tbp]
  11981. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11982. (define/public ((check-well-formed env) ty)
  11983. (match ty
  11984. ['Integer (void)]
  11985. ['Boolean (void)]
  11986. ['Void (void)]
  11987. [(? symbol? a)
  11988. (match (dict-ref env a (lambda () #f))
  11989. ['Type (void)]
  11990. [else (error 'type-check "undefined type variable ~a" a)])]
  11991. [`(Vector ,ts ...)
  11992. (for ([t ts]) ((check-well-formed env) t))]
  11993. [`(,ts ... -> ,t)
  11994. (for ([t ts]) ((check-well-formed env) t))
  11995. ((check-well-formed env) t)]
  11996. [`(All ,xs ,t)
  11997. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11998. ((check-well-formed env^) t)]
  11999. [else (error 'type-check "unrecognized type ~a" ty)]))
  12000. \end{lstlisting}
  12001. \caption{Well-formed types.}
  12002. \label{fig:well-formed-types}
  12003. \end{figure}
  12004. % TODO: interpreter for R'_10
  12005. \section{Compiling Polymorphism}
  12006. \label{sec:compiling-poly}
  12007. Broadly speaking, there are four approaches to compiling parametric
  12008. polymorphism, which we describe below.
  12009. \begin{description}
  12010. \item[Monomorphization] generates a different version of a polymorphic
  12011. function for each set of type arguments that it is used with,
  12012. producing type-specialized code. This approach results in the most
  12013. efficient code but requires whole-program compilation (no separate
  12014. compilation) and increases code size. For our current purposes
  12015. monomorphization is a non-starter because, with first-class
  12016. polymorphism, it is sometimes not possible to determine which
  12017. generic functions are used with which type arguments during
  12018. compilation. (It can be done at runtime, with just-in-time
  12019. compilation.) This approach is used to compile C++
  12020. templates~\citep{stroustrup88:_param_types} and polymorphic
  12021. functions in NESL~\citep{Blelloch:1993aa} and
  12022. ML~\citep{Weeks:2006aa}.
  12023. \item[Uniform representation] generates one version of each
  12024. polymorphic function but requires all values have a common ``boxed''
  12025. format, such as the tagged values of type \code{Any} in
  12026. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12027. similarly to code in a dynamically typed language (like \LangDyn{}),
  12028. in which primitive operators require their arguments to be projected
  12029. from \code{Any} and their results are injected into \code{Any}. (In
  12030. object-oriented languages, the projection is accomplished via
  12031. virtual method dispatch.) The uniform representation approach is
  12032. compatible with separate compilation and with first-class
  12033. polymorphism. However, it produces the least-efficient code because
  12034. it introduces overhead in the entire program, including
  12035. non-polymorphic code. This approach is used in implementations of
  12036. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12037. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12038. Java~\citep{Bracha:1998fk}.
  12039. \item[Mixed representation] generates one version of each polymorphic
  12040. function, using a boxed representation for type
  12041. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12042. and conversions are performed at the boundaries between monomorphic
  12043. and polymorphic (e.g. when a polymorphic function is instantiated
  12044. and called). This approach is compatible with separate compilation
  12045. and first-class polymorphism and maintains the efficiency of
  12046. monomorphic code. The tradeoff is increased overhead at the boundary
  12047. between monomorphic and polymorphic code. This approach is used in
  12048. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12049. Java 5 with the addition of autoboxing.
  12050. \item[Type passing] uses the unboxed representation in both
  12051. monomorphic and polymorphic code. Each polymorphic function is
  12052. compiled to a single function with extra parameters that describe
  12053. the type arguments. The type information is used by the generated
  12054. code to know how to access the unboxed values at runtime. This
  12055. approach is used in implementation of the Napier88
  12056. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12057. passing is compatible with separate compilation and first-class
  12058. polymorphism and maintains the efficiency for monomorphic
  12059. code. There is runtime overhead in polymorphic code from dispatching
  12060. on type information.
  12061. \end{description}
  12062. In this chapter we use the mixed representation approach, partly
  12063. because of its favorable attributes, and partly because it is
  12064. straightforward to implement using the tools that we have already
  12065. built to support gradual typing. To compile polymorphic functions, we
  12066. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12067. \LangCast{}.
  12068. \section{Erase Types}
  12069. \label{sec:erase-types}
  12070. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12071. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12072. shows the output of the \code{erase-types} pass on the polymorphic
  12073. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12074. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12075. \code{All} types are removed from the type of \code{map-vec}.
  12076. \begin{figure}[tbp]
  12077. \begin{lstlisting}
  12078. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12079. : (Vector Any Any)
  12080. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12081. (define (add1 [x : Integer]) : Integer (+ x 1))
  12082. (vector-ref ((cast map-vec
  12083. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12084. ((Integer -> Integer) (Vector Integer Integer)
  12085. -> (Vector Integer Integer)))
  12086. add1 (vector 0 41)) 1)
  12087. \end{lstlisting}
  12088. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12089. \label{fig:map-vec-erase}
  12090. \end{figure}
  12091. This process of type erasure creates a challenge at points of
  12092. instantiation. For example, consider the instantiation of
  12093. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12094. The type of \code{map-vec} is
  12095. \begin{lstlisting}
  12096. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12097. \end{lstlisting}
  12098. and it is instantiated to
  12099. \begin{lstlisting}
  12100. ((Integer -> Integer) (Vector Integer Integer)
  12101. -> (Vector Integer Integer))
  12102. \end{lstlisting}
  12103. After erasure, the type of \code{map-vec} is
  12104. \begin{lstlisting}
  12105. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12106. \end{lstlisting}
  12107. but we need to convert it to the instantiated type. This is easy to
  12108. do in the target language \LangCast{} with a single \code{cast}. In
  12109. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12110. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12111. the instantiated type. The source and target type of a cast must be
  12112. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12113. because both the source and target are obtained from the same
  12114. polymorphic type of \code{map-vec}, replacing the type parameters with
  12115. \code{Any} in the former and with the deduced type arguments in the
  12116. later. (Recall that the \code{Any} type is consistent with any type.)
  12117. To implement the \code{erase-types} pass, we recommend defining a
  12118. recursive auxiliary function named \code{erase-type} that applies the
  12119. following two transformations. It replaces type variables with
  12120. \code{Any}
  12121. \begin{lstlisting}
  12122. |$x$|
  12123. |$\Rightarrow$|
  12124. Any
  12125. \end{lstlisting}
  12126. and it removes the polymorphic \code{All} types.
  12127. \begin{lstlisting}
  12128. (All |$xs$| |$T_1$|)
  12129. |$\Rightarrow$|
  12130. |$T'_1$|
  12131. \end{lstlisting}
  12132. Apply the \code{erase-type} function to all of the type annotations in
  12133. the program.
  12134. Regarding the translation of expressions, the case for \code{Inst} is
  12135. the interesting one. We translate it into a \code{Cast}, as shown
  12136. below. The type of the subexpression $e$ is the polymorphic type
  12137. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12138. $T$, the type $T'$. The target type $T''$ is the result of
  12139. substituting the arguments types $ts$ for the type parameters $xs$ in
  12140. $T$ followed by doing type erasure.
  12141. \begin{lstlisting}
  12142. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12143. |$\Rightarrow$|
  12144. (Cast |$e'$| |$T'$| |$T''$|)
  12145. \end{lstlisting}
  12146. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12147. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12148. Finally, each polymorphic function is translated to a regular
  12149. functions in which type erasure has been applied to all the type
  12150. annotations and the body.
  12151. \begin{lstlisting}
  12152. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12153. |$\Rightarrow$|
  12154. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12155. \end{lstlisting}
  12156. \begin{exercise}\normalfont
  12157. Implement a compiler for the polymorphic language \LangPoly{} by
  12158. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12159. programs that use polymorphic functions. Some of them should make
  12160. use of first-class polymorphism.
  12161. \end{exercise}
  12162. \begin{figure}[p]
  12163. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12164. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12165. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12166. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12167. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12168. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12169. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12170. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12171. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12172. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12173. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12174. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12175. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12176. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12177. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12178. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12179. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12180. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12181. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12182. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12183. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12184. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12185. \path[->,bend right=15] (Rpoly) edge [above] node
  12186. {\ttfamily\footnotesize type-check} (Rpolyp);
  12187. \path[->,bend right=15] (Rpolyp) edge [above] node
  12188. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12189. \path[->,bend right=15] (Rgradualp) edge [above] node
  12190. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12191. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12192. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12193. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12194. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12195. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12196. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12197. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12198. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12199. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12200. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12201. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12202. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12203. \path[->,bend left=15] (F1-1) edge [below] node
  12204. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12205. \path[->,bend right=15] (F1-2) edge [above] node
  12206. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12207. \path[->,bend right=15] (F1-3) edge [above] node
  12208. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12209. \path[->,bend right=15] (F1-4) edge [above] node
  12210. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12211. \path[->,bend right=15] (F1-5) edge [right] node
  12212. {\ttfamily\footnotesize explicate-control} (C3-2);
  12213. \path[->,bend left=15] (C3-2) edge [left] node
  12214. {\ttfamily\footnotesize select-instr.} (x86-2);
  12215. \path[->,bend right=15] (x86-2) edge [left] node
  12216. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12217. \path[->,bend right=15] (x86-2-1) edge [below] node
  12218. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12219. \path[->,bend right=15] (x86-2-2) edge [left] node
  12220. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12221. \path[->,bend left=15] (x86-3) edge [above] node
  12222. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12223. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12224. \end{tikzpicture}
  12225. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12226. \label{fig:Rpoly-passes}
  12227. \end{figure}
  12228. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12229. for the compilation of \LangPoly{}.
  12230. % TODO: challenge problem: specialization of instantiations
  12231. % Further Reading
  12232. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12233. \begin{chapappendix}[Appendix]
  12234. \section{Interpreters}
  12235. \label{appendix:interp}
  12236. \index{subject}{interpreter}
  12237. We provide interpreters for each of the source languages \LangInt{},
  12238. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12239. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12240. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12241. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12242. and x86 are in the \key{interp.rkt} file.
  12243. \section{Utility Functions}
  12244. \label{appendix:utilities}
  12245. The utility functions described in this section are in the
  12246. \key{utilities.rkt} file of the support code.
  12247. \paragraph{\code{interp-tests}}
  12248. The \key{interp-tests} function runs the compiler passes and the
  12249. interpreters on each of the specified tests to check whether each pass
  12250. is correct. The \key{interp-tests} function has the following
  12251. parameters:
  12252. \begin{description}
  12253. \item[name (a string)] a name to identify the compiler,
  12254. \item[typechecker] a function of exactly one argument that either
  12255. raises an error using the \code{error} function when it encounters a
  12256. type error, or returns \code{\#f} when it encounters a type
  12257. error. If there is no type error, the type checker returns the
  12258. program.
  12259. \item[passes] a list with one entry per pass. An entry is a list with
  12260. four things:
  12261. \begin{enumerate}
  12262. \item a string giving the name of the pass,
  12263. \item the function that implements the pass (a translator from AST
  12264. to AST),
  12265. \item a function that implements the interpreter (a function from
  12266. AST to result value) for the output language,
  12267. \item and a type checker for the output language. Type checkers for
  12268. the $R$ and $C$ languages are provided in the support code. For
  12269. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12270. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12271. type checker entry is optional. The support code does not provide
  12272. type checkers for the x86 languages.
  12273. \end{enumerate}
  12274. \item[source-interp] an interpreter for the source language. The
  12275. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12276. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12277. \item[tests] a list of test numbers that specifies which tests to
  12278. run. (see below)
  12279. \end{description}
  12280. %
  12281. The \key{interp-tests} function assumes that the subdirectory
  12282. \key{tests} has a collection of Racket programs whose names all start
  12283. with the family name, followed by an underscore and then the test
  12284. number, ending with the file extension \key{.rkt}. Also, for each test
  12285. program that calls \code{read} one or more times, there is a file with
  12286. the same name except that the file extension is \key{.in} that
  12287. provides the input for the Racket program. If the test program is
  12288. expected to fail type checking, then there should be an empty file of
  12289. the same name but with extension \key{.tyerr}.
  12290. \paragraph{\code{compiler-tests}}
  12291. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12292. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12293. machine code and checks that the output is $42$. The parameters to the
  12294. \code{compiler-tests} function are similar to those of the
  12295. \code{interp-tests} function, and consist of
  12296. \begin{itemize}
  12297. \item a compiler name (a string),
  12298. \item a type checker,
  12299. \item description of the passes,
  12300. \item name of a test-family, and
  12301. \item a list of test numbers.
  12302. \end{itemize}
  12303. \paragraph{\code{compile-file}}
  12304. takes a description of the compiler passes (see the comment for
  12305. \key{interp-tests}) and returns a function that, given a program file
  12306. name (a string ending in \key{.rkt}), applies all of the passes and
  12307. writes the output to a file whose name is the same as the program file
  12308. name but with \key{.rkt} replaced with \key{.s}.
  12309. \paragraph{\code{read-program}}
  12310. takes a file path and parses that file (it must be a Racket program)
  12311. into an abstract syntax tree.
  12312. \paragraph{\code{parse-program}}
  12313. takes an S-expression representation of an abstract syntax tree and converts it into
  12314. the struct-based representation.
  12315. \paragraph{\code{assert}}
  12316. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12317. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12318. \paragraph{\code{lookup}}
  12319. % remove discussion of lookup? -Jeremy
  12320. takes a key and an alist, and returns the first value that is
  12321. associated with the given key, if there is one. If not, an error is
  12322. triggered. The alist may contain both immutable pairs (built with
  12323. \key{cons}) and mutable pairs (built with \key{mcons}).
  12324. %The \key{map2} function ...
  12325. \section{x86 Instruction Set Quick-Reference}
  12326. \label{sec:x86-quick-reference}
  12327. \index{subject}{x86}
  12328. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12329. do. We write $A \to B$ to mean that the value of $A$ is written into
  12330. location $B$. Address offsets are given in bytes. The instruction
  12331. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12332. registers (such as \code{\%rax}), or memory references (such as
  12333. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12334. reference per instruction. Other operands must be immediates or
  12335. registers.
  12336. \begin{table}[tbp]
  12337. \centering
  12338. \begin{tabular}{l|l}
  12339. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12340. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12341. \texttt{negq} $A$ & $- A \to A$ \\
  12342. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12343. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12344. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12345. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12346. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12347. \texttt{retq} & Pops the return address and jumps to it \\
  12348. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12349. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12350. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12351. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12352. be an immediate) \\
  12353. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12354. matches the condition code of the instruction, otherwise go to the
  12355. next instructions. The condition codes are \key{e} for ``equal'',
  12356. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12357. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12358. \texttt{jl} $L$ & \\
  12359. \texttt{jle} $L$ & \\
  12360. \texttt{jg} $L$ & \\
  12361. \texttt{jge} $L$ & \\
  12362. \texttt{jmp} $L$ & Jump to label $L$ \\
  12363. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12364. \texttt{movzbq} $A$, $B$ &
  12365. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12366. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12367. and the extra bytes of $B$ are set to zero.} \\
  12368. & \\
  12369. & \\
  12370. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12371. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12372. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12373. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12374. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12375. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12376. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12377. description of the condition codes. $A$ must be a single byte register
  12378. (e.g., \texttt{al} or \texttt{cl}).} \\
  12379. \texttt{setl} $A$ & \\
  12380. \texttt{setle} $A$ & \\
  12381. \texttt{setg} $A$ & \\
  12382. \texttt{setge} $A$ &
  12383. \end{tabular}
  12384. \vspace{5pt}
  12385. \caption{Quick-reference for the x86 instructions used in this book.}
  12386. \label{tab:x86-instr}
  12387. \end{table}
  12388. \cleardoublepage
  12389. \section{Concrete Syntax for Intermediate Languages}
  12390. The concrete syntax of \LangAny{} is defined in
  12391. Figure~\ref{fig:Rany-concrete-syntax}.
  12392. \begin{figure}[tp]
  12393. \centering
  12394. \fbox{
  12395. \begin{minipage}{0.97\textwidth}\small
  12396. \[
  12397. \begin{array}{lcl}
  12398. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12399. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12400. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12401. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12402. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12403. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12404. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12405. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12406. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12407. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12408. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12409. \mid \LP\key{void?}\;\Exp\RP \\
  12410. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12411. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12412. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  12413. \end{array}
  12414. \]
  12415. \end{minipage}
  12416. }
  12417. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12418. (Figure~\ref{fig:Rlam-syntax}).}
  12419. \label{fig:Rany-concrete-syntax}
  12420. \end{figure}
  12421. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12422. defined in Figures~\ref{fig:c0-concrete-syntax},
  12423. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12424. and \ref{fig:c3-concrete-syntax}, respectively.
  12425. \begin{figure}[tbp]
  12426. \fbox{
  12427. \begin{minipage}{0.96\textwidth}
  12428. \[
  12429. \begin{array}{lcl}
  12430. \Atm &::=& \Int \mid \Var \\
  12431. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12432. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12433. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12434. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12435. \end{array}
  12436. \]
  12437. \end{minipage}
  12438. }
  12439. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12440. \label{fig:c0-concrete-syntax}
  12441. \end{figure}
  12442. \begin{figure}[tbp]
  12443. \fbox{
  12444. \begin{minipage}{0.96\textwidth}
  12445. \small
  12446. \[
  12447. \begin{array}{lcl}
  12448. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12449. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12450. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12451. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12452. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12453. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12454. \mid \key{goto}~\itm{label}\key{;}\\
  12455. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12456. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12457. \end{array}
  12458. \]
  12459. \end{minipage}
  12460. }
  12461. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12462. \label{fig:c1-concrete-syntax}
  12463. \end{figure}
  12464. \begin{figure}[tbp]
  12465. \fbox{
  12466. \begin{minipage}{0.96\textwidth}
  12467. \small
  12468. \[
  12469. \begin{array}{lcl}
  12470. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12471. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12472. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12473. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12474. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12475. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12476. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12477. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12478. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12479. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12480. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12481. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12482. \end{array}
  12483. \]
  12484. \end{minipage}
  12485. }
  12486. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12487. \label{fig:c2-concrete-syntax}
  12488. \end{figure}
  12489. \begin{figure}[tp]
  12490. \fbox{
  12491. \begin{minipage}{0.96\textwidth}
  12492. \small
  12493. \[
  12494. \begin{array}{lcl}
  12495. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12496. \\
  12497. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12498. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12499. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12500. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12501. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12502. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12503. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12504. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12505. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12506. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12507. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12508. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12509. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12510. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12511. \LangCFunM{} & ::= & \Def\ldots
  12512. \end{array}
  12513. \]
  12514. \end{minipage}
  12515. }
  12516. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12517. \label{fig:c3-concrete-syntax}
  12518. \end{figure}
  12519. \end{chapappendix}
  12520. %\setcounter{chapter}{2}
  12521. \clearpage
  12522. \appendix
  12523. \backmatter
  12524. %% \addtocontents{toc}{\vspace{11pt}}
  12525. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  12526. \nocite{*}\let\bibname\refname
  12527. \addcontentsline{toc}{fmbm}{\refname}
  12528. \printbibliography
  12529. \printindex{authors}{Author Index}
  12530. \printindex{subject}{Subject Index}
  12531. \end{document}